@needle-tools/engine 4.7.2 → 4.7.3-next.1603bb0
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-CnzaSk8v.min.js → needle-engine.bundle-6bPQlS1q.min.js} +23 -23
- package/dist/{needle-engine.bundle-DALjvqho.js → needle-engine.bundle-CL5SiInU.js} +89 -76
- package/dist/{needle-engine.bundle-RNpCdQTu.umd.cjs → needle-engine.bundle-Dm9L7JpU.umd.cjs} +26 -26
- package/dist/needle-engine.d.ts +15 -15
- 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-TkXiVrjY.min.js → postprocessing-BzY0H7ry.min.js} +8 -8
- package/dist/{postprocessing-CNCT892s.umd.cjs → postprocessing-Dw2OCMp4.umd.cjs} +8 -8
- package/dist/{postprocessing-qvgDnYKK.js → postprocessing-vKBVFpSz.js} +9 -9
- package/lib/engine-components/OrbitControls.d.ts +12 -0
- package/lib/engine-components/OrbitControls.js +14 -0
- package/lib/engine-components/OrbitControls.js.map +1 -1
- package/lib/engine-components/Skybox.d.ts +1 -0
- package/lib/engine-components/Skybox.js +13 -17
- package/lib/engine-components/Skybox.js.map +1 -1
- package/lib/engine-components/postprocessing/PostProcessingHandler.js +1 -1
- package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
- package/lib/engine-components/postprocessing/Volume.d.ts +3 -1
- package/lib/engine-components/postprocessing/Volume.js +2 -0
- package/lib/engine-components/postprocessing/Volume.js.map +1 -1
- package/package.json +2 -2
- package/plugins/vite/logger.client.js +68 -30
- package/plugins/vite/logger.js +5 -5
- package/src/engine-components/OrbitControls.ts +16 -0
- package/src/engine-components/Skybox.ts +14 -20
- package/src/engine-components/postprocessing/PostProcessingHandler.ts +1 -1
- package/src/engine-components/postprocessing/Volume.ts +2 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var RC=Object.defineProperty,Mv=n=>{throw TypeError(n)},TC=(n,e,t)=>e in n?RC(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,a=(n,e,t)=>TC(n,typeof e!="symbol"?e+"":e,t),Mm=(n,e,t)=>e.has(n)||Mv("Cannot "+t),ge=(n,e,t)=>(Mm(n,e,"read from private field"),t?t.call(n):e.get(n)),Fs=(n,e,t)=>e.has(n)?Mv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),Us=(n,e,t,s)=>(Mm(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),ud=(n,e,t)=>(Mm(n,e,"access private method"),t);import{Vector2 as ie,Vector3 as S,Vector4 as fe,Quaternion as V,PlaneGeometry as zs,WebGLRenderer as gr,PerspectiveCamera as we,OrthographicCamera as pd,Scene as Si,Mesh as q,Texture as je,Uniform$1 as Qi,Color as re,ShaderMaterial as Ns,Box3 as Ci,ShadowMaterial as Rv,Euler as Bt,MeshStandardMaterial as bt,Box3Helper as EC,GridHelper as Rm,Object3D as A,Material as Pe,Matrix3 as Tv,Matrix4 as ne,Layers as po,Ray as mo,MathUtils as Cn,AxesHelper as Pi,MeshBasicMaterial as Me,DoubleSide as Oi,BufferGeometry as Ws,Group as go,CylinderGeometry as Ev,SphereGeometry as md,BoxGeometry as xa,SpriteMaterial as AC,Sprite as IC,Shape as LC,ExtrudeGeometry as jC,Fog as Av,DirectionalLight as Tm,PointLight as Em,EdgesGeometry as DC,LineSegments as Iv,LineBasicMaterial as Lv,Line as Hl,BufferAttribute as _t,Raycaster as gd,Sphere as fd,ArrayCamera as BC,Plane as fr,SkinnedMesh as Pn,InterleavedBufferAttribute as jv,Skeleton as FC,Bone as UC,Source as zC,WebGLCubeRenderTarget as NC,CubeCamera as WC,AnimationClip as fo,FileLoader as Am,TextureLoader as Sa,PropertyBinding as Ca,LinearSRGBColorSpace as On,ShaderChunk as qt,UniformsLib as VC,DataTexture as Im,RGBAFormat as yd,EquirectangularReflectionMapping as kn,SRGBColorSpace as Mn,Clock as $C,NeutralToneMapping as Pa,AgXToneMapping as vd,ACESFilmicToneMapping as bd,NoToneMapping as _d,PCFSoftShadowMap$1 as HC,BasicNodeLibrary as GC,WebGLRenderTarget as Vs,DepthTexture as Dv,NearestFilter as wd,LoopRepeat as qC,LoopOnce as Lm,AnimationMixer as jm,CompressedTexture as XC,FrontSide as yo,Camera as QC,Frustum as Bv,AudioListener as YC,PositionalAudio as KC,AudioLoader as Dm,EventDispatcher as Bm,BackSide as xd,MeshDepthMaterial as ZC,CustomBlending as JC,MaxEquation as eP,AmbientLight as tP,HemisphereLight as iP,AlwaysStencilFunc as sP,GreaterEqualStencilFunc as nP,NotEqualStencilFunc as oP,GreaterStencilFunc as rP,LessEqualStencilFunc as aP,EqualStencilFunc as lP,LessStencilFunc as cP,NeverStencilFunc as Fv,InvertStencilOp as hP,DecrementWrapStencilOp as dP,IncrementWrapStencilOp as uP,DecrementStencilOp as pP,IncrementStencilOp as mP,ReplaceStencilOp as gP,ZeroStencilOp as fP,KeepStencilOp as yP,RawShaderMaterial as Uv,GLSL3 as vP,AlwaysDepth as bP,GreaterEqualDepth as _P,GreaterDepth as wP,LessEqualDepth as xP,LessDepth as SP,NotEqualDepth as CP,EqualDepth as PP,BatchedMesh as zv,MeshPhysicalMaterial as Fm,LinearFilter as Sd,UnsignedByteType as OP,RingGeometry as kP,Line3 as MP,AdditiveBlending as Nv,BoxHelper as RP,SpotLight as TP,DirectionalLightHelper as EP,CameraHelper as AP,LOD as IP,Triangle as LP,NormalBlending as jP,ReinhardToneMapping as Um,LinearToneMapping as zm,HalfFloatType as Nm,VideoTexture as DP,CubeTexture as BP,CompressedCubeTexture as FP,EquirectangularRefractionMapping as UP,VectorKeyframeTrack as zP,QuaternionKeyframeTrack as NP,Audio as WP,ShaderLib as Cd,UniformsUtils as Wv,MirroredRepeatWrapping as Vv,MeshNormalMaterial as VP,AudioContext as $P,PMREMGenerator$1 as HP}from"./three-DuDKwKB8.min.js";import{createLoaders as Wm,getRaycastMesh as $v,LODsManager as Oa,NEEDLE_progressive as Xe,addDracoAndKTX2Loaders as GP,configureLoader as qP,setKTX2TranscoderLocation as XP,setDracoDecoderLocation as QP}from"./gltf-progressive-BCZdu3Gc.min.js";import{GroundedSkybox as ka,Font as YP,TextGeometry as KP,FontLoader as ZP,GLTFLoader as Rn,TransformControlsGizmo as Hv,EXRLoader as Pd,RGBELoader as Vm,Stats as JP,nodeFrame as eO,OrbitControls as Gv,PositionalAudioHelper as tO,HorizontalBlurShader as iO,VerticalBlurShader as sO,GLTFExporter as qv,strToU8 as Xv,zipSync as nO,XRControllerModelFactory as oO,XRHandMeshModel as rO,Line2 as aO,LineGeometry as lO,LineMaterial as cO,KTX2Loader as hO,TransformControls as dO,InteractiveGroup as uO,HTMLMesh as pO,VertexNormalsHelper as mO,OBJLoader as $m,FBXLoader as Qv,mergeVertices as gO}from"./three-examples-BMOhDaYR.min.js";import{fetchProfile as fO,MotionController as yO,$70d766613f57b014$export$2e2bcd8739ae039 as Yv,ByteBuffer as vO,v5 as Kv,md5 as Zv,SIZE_PREFIX_LENGTH as Jv,Builder as Hm,createNoise4D as bO,Matrix4 as Gm,BatchedParticleRenderer as _O,ParticleSystem as wO,RenderMode as Tn,ConstantColor as xO,Vector4 as SO,ConstantValue as CO,TrailParticle as eb,WorkerBase as PO,MeshBVH as OO}from"./vendor-BlSxe9JJ.min.js";import{__webpack_exports__default as Re,__webpack_exports__Text as tb,__webpack_exports__Block as ib,__webpack_exports__update as kO,SimpleStateBehavior as MO,__webpack_exports__Inline as qm,__webpack_exports__FontLibrary as sb,ThreeMeshUI as nb}from"./three-mesh-ui-B3p3gyUz.min.js";import{EffectAttribute as RO}from"./postprocessing-TkXiVrjY.min.js";const Xm=new Map;function Xt(n=(e=>(e=globalThis.location)==null?void 0:e.hostname)()){if(Xm.has(n))return Xm.get(n);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(n);return Xm.set(n,e),e===!0}function ob(){return window.location.hostname.includes("glitch.me")}const TO='<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>',EO=btoa(TO),AO="data:image/svg+xml;base64,"+EO,rb=AO,IO=`<?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(IO);const LO='<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>',jO=btoa(LO),DO="data:image/svg+xml;charset=utf-8;base64,"+jO,BO=DO,ab=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var me=(n=>(n.ContextRegistered="ContextRegistered",n.ContextCreationStart="ContextCreationStart",n.ContextCreated="ContextCreated",n.ContextFirstFrameRendered="ContextFirstFrameRendered",n.ContextDestroying="ContextDestroying",n.ContextDestroyed="ContextDestroyed",n.MissingCamera="MissingCamera",n.ContextClearing="ContextClearing",n.ContextCleared="ContextCleared",n))(me||{});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 register(e){this.Registered.indexOf(e)===-1&&(ab&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(ab&&console.warn("Unregistering context"),this.Registered.splice(t,1))}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 s=this._callbacks[e].indexOf(t);s!==-1&&this._callbacks[e].splice(s,1)}static dispatchCallback(e,t,s){if(!this._callbacks[e])return!0;const o={event:e,context:t};if(s)for(const l in s)o[l]=s[l];const r=new Array;return this._callbacks[e].forEach(l=>{const c=l(o);c instanceof Promise&&r.push(c)}),Promise.all(r)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}a(pe,"Registered",[]),a(pe,"_callbacks",{});const lb=()=>n=>n;function FO(n){return lb()(n)}function UO(){return!!C("debug")}class ki{constructor(e,t){a(this,"_factory"),a(this,"_cache",[]),a(this,"_maxSize"),a(this,"_index",0),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 yr=!1;const Qm=new Array;typeof window<"u"&&setTimeout(()=>{if(yr){const n={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const s=t.toString().replace(/=$|=(?=&)/g,"");for(const r of Qm){const l=new URL(e);l.searchParams.append(r,""),n[r]=l.toString().replace(/=$|=(?=&)/g,"")}console.log(`\u{1F335} ?help: Debug Options for Needle Engine.
|
|
1
|
+
var RC=Object.defineProperty,Mv=n=>{throw TypeError(n)},TC=(n,e,t)=>e in n?RC(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,a=(n,e,t)=>TC(n,typeof e!="symbol"?e+"":e,t),Mm=(n,e,t)=>e.has(n)||Mv("Cannot "+t),ge=(n,e,t)=>(Mm(n,e,"read from private field"),t?t.call(n):e.get(n)),Fs=(n,e,t)=>e.has(n)?Mv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),Us=(n,e,t,s)=>(Mm(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),ud=(n,e,t)=>(Mm(n,e,"access private method"),t);import{Vector2 as ie,Vector3 as S,Vector4 as fe,Quaternion as V,PlaneGeometry as zs,WebGLRenderer as gr,PerspectiveCamera as we,OrthographicCamera as pd,Scene as Si,Mesh as q,Texture as je,Uniform$1 as Qi,Color as re,ShaderMaterial as Ns,Box3 as Ci,ShadowMaterial as Rv,Euler as Dt,MeshStandardMaterial as bt,Box3Helper as EC,GridHelper as Rm,Object3D as A,Material as Pe,Matrix3 as Tv,Matrix4 as ne,Layers as po,Ray as mo,MathUtils as Cn,AxesHelper as Pi,MeshBasicMaterial as Me,DoubleSide as Oi,BufferGeometry as Ws,Group as go,CylinderGeometry as Ev,SphereGeometry as md,BoxGeometry as xa,SpriteMaterial as AC,Sprite as IC,Shape as LC,ExtrudeGeometry as jC,Fog as Av,DirectionalLight as Tm,PointLight as Em,EdgesGeometry as DC,LineSegments as Iv,LineBasicMaterial as Lv,Line as Hl,BufferAttribute as _t,Raycaster as gd,Sphere as fd,ArrayCamera as BC,Plane as fr,SkinnedMesh as Pn,InterleavedBufferAttribute as jv,Skeleton as FC,Bone as UC,Source as zC,WebGLCubeRenderTarget as NC,CubeCamera as WC,AnimationClip as fo,FileLoader as Am,TextureLoader as Sa,PropertyBinding as Ca,LinearSRGBColorSpace as On,ShaderChunk as qt,UniformsLib as VC,DataTexture as Im,RGBAFormat as yd,EquirectangularReflectionMapping as kn,SRGBColorSpace as Mn,Clock as $C,NeutralToneMapping as Pa,AgXToneMapping as vd,ACESFilmicToneMapping as bd,NoToneMapping as _d,PCFSoftShadowMap$1 as HC,BasicNodeLibrary as GC,WebGLRenderTarget as Vs,DepthTexture as Dv,NearestFilter as wd,LoopRepeat as qC,LoopOnce as Lm,AnimationMixer as jm,CompressedTexture as XC,FrontSide as yo,Camera as QC,Frustum as Bv,AudioListener as YC,PositionalAudio as KC,AudioLoader as Dm,EventDispatcher as Bm,BackSide as xd,MeshDepthMaterial as ZC,CustomBlending as JC,MaxEquation as eP,AmbientLight as tP,HemisphereLight as iP,AlwaysStencilFunc as sP,GreaterEqualStencilFunc as nP,NotEqualStencilFunc as oP,GreaterStencilFunc as rP,LessEqualStencilFunc as aP,EqualStencilFunc as lP,LessStencilFunc as cP,NeverStencilFunc as Fv,InvertStencilOp as hP,DecrementWrapStencilOp as dP,IncrementWrapStencilOp as uP,DecrementStencilOp as pP,IncrementStencilOp as mP,ReplaceStencilOp as gP,ZeroStencilOp as fP,KeepStencilOp as yP,RawShaderMaterial as Uv,GLSL3 as vP,AlwaysDepth as bP,GreaterEqualDepth as _P,GreaterDepth as wP,LessEqualDepth as xP,LessDepth as SP,NotEqualDepth as CP,EqualDepth as PP,BatchedMesh as zv,MeshPhysicalMaterial as Fm,LinearFilter as Sd,UnsignedByteType as OP,RingGeometry as kP,Line3 as MP,AdditiveBlending as Nv,BoxHelper as RP,SpotLight as TP,DirectionalLightHelper as EP,CameraHelper as AP,LOD as IP,Triangle as LP,NormalBlending as jP,ReinhardToneMapping as Um,LinearToneMapping as zm,HalfFloatType as Nm,VideoTexture as DP,CubeTexture as BP,CompressedCubeTexture as FP,EquirectangularRefractionMapping as UP,VectorKeyframeTrack as zP,QuaternionKeyframeTrack as NP,Audio as WP,ShaderLib as Cd,UniformsUtils as Wv,MirroredRepeatWrapping as Vv,MeshNormalMaterial as VP,AudioContext as $P,PMREMGenerator$1 as HP}from"./three-DuDKwKB8.min.js";import{createLoaders as Wm,getRaycastMesh as $v,LODsManager as Oa,NEEDLE_progressive as Xe,addDracoAndKTX2Loaders as GP,configureLoader as qP,setKTX2TranscoderLocation as XP,setDracoDecoderLocation as QP}from"./gltf-progressive-BCZdu3Gc.min.js";import{GroundedSkybox as ka,Font as YP,TextGeometry as KP,FontLoader as ZP,GLTFLoader as Rn,TransformControlsGizmo as Hv,EXRLoader as Pd,RGBELoader as Vm,Stats as JP,nodeFrame as eO,OrbitControls as Gv,PositionalAudioHelper as tO,HorizontalBlurShader as iO,VerticalBlurShader as sO,GLTFExporter as qv,strToU8 as Xv,zipSync as nO,XRControllerModelFactory as oO,XRHandMeshModel as rO,Line2 as aO,LineGeometry as lO,LineMaterial as cO,KTX2Loader as hO,TransformControls as dO,InteractiveGroup as uO,HTMLMesh as pO,VertexNormalsHelper as mO,OBJLoader as $m,FBXLoader as Qv,mergeVertices as gO}from"./three-examples-BMOhDaYR.min.js";import{fetchProfile as fO,MotionController as yO,$70d766613f57b014$export$2e2bcd8739ae039 as Yv,ByteBuffer as vO,v5 as Kv,md5 as Zv,SIZE_PREFIX_LENGTH as Jv,Builder as Hm,createNoise4D as bO,Matrix4 as Gm,BatchedParticleRenderer as _O,ParticleSystem as wO,RenderMode as Tn,ConstantColor as xO,Vector4 as SO,ConstantValue as CO,TrailParticle as eb,WorkerBase as PO,MeshBVH as OO}from"./vendor-BlSxe9JJ.min.js";import{__webpack_exports__default as Re,__webpack_exports__Text as tb,__webpack_exports__Block as ib,__webpack_exports__update as kO,SimpleStateBehavior as MO,__webpack_exports__Inline as qm,__webpack_exports__FontLibrary as sb,ThreeMeshUI as nb}from"./three-mesh-ui-B3p3gyUz.min.js";import{EffectAttribute as RO}from"./postprocessing-BzY0H7ry.min.js";const Xm=new Map;function Xt(n=(e=>(e=globalThis.location)==null?void 0:e.hostname)()){if(Xm.has(n))return Xm.get(n);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(n);return Xm.set(n,e),e===!0}function ob(){return window.location.hostname.includes("glitch.me")}const TO='<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>',EO=btoa(TO),AO="data:image/svg+xml;base64,"+EO,rb=AO,IO=`<?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(IO);const LO='<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>',jO=btoa(LO),DO="data:image/svg+xml;charset=utf-8;base64,"+jO,BO=DO,ab=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var me=(n=>(n.ContextRegistered="ContextRegistered",n.ContextCreationStart="ContextCreationStart",n.ContextCreated="ContextCreated",n.ContextFirstFrameRendered="ContextFirstFrameRendered",n.ContextDestroying="ContextDestroying",n.ContextDestroyed="ContextDestroyed",n.MissingCamera="MissingCamera",n.ContextClearing="ContextClearing",n.ContextCleared="ContextCleared",n))(me||{});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 register(e){this.Registered.indexOf(e)===-1&&(ab&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(ab&&console.warn("Unregistering context"),this.Registered.splice(t,1))}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 s=this._callbacks[e].indexOf(t);s!==-1&&this._callbacks[e].splice(s,1)}static dispatchCallback(e,t,s){if(!this._callbacks[e])return!0;const o={event:e,context:t};if(s)for(const l in s)o[l]=s[l];const r=new Array;return this._callbacks[e].forEach(l=>{const c=l(o);c instanceof Promise&&r.push(c)}),Promise.all(r)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}a(pe,"Registered",[]),a(pe,"_callbacks",{});const lb=()=>n=>n;function FO(n){return lb()(n)}function UO(){return!!C("debug")}class ki{constructor(e,t){a(this,"_factory"),a(this,"_cache",[]),a(this,"_maxSize"),a(this,"_index",0),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 yr=!1;const Qm=new Array;typeof window<"u"&&setTimeout(()=>{if(yr){const n={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const s=t.toString().replace(/=$|=(?=&)/g,"");for(const r of Qm){const l=new URL(e);l.searchParams.append(r,""),n[r]=l.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: ${s} will show an onscreen console window.`);const o=yr===!0?"":` (containing "${yr}")`;console.group("Available URL parameters:"+o);for(const r of Object.keys(n).sort())typeof yr=="string"&&!r.toLowerCase().includes(yr.toLowerCase())||(console.groupCollapsed(r),console.log("Reload with this flag enabled:"),console.log(n[r]),console.groupEnd());console.groupEnd()}},100);function Gl(){var n;return new URLSearchParams((n=globalThis.location)==null?void 0:n.search)}function C(n){yr&&!Qm.includes(n)&&Qm.push(n);const e=Gl();if(e.has(n)){const t=e.get(n);if(t){const s=Number(t);return isNaN(s)?t:s}else return!0}return!1}yr=C("help");function zO(n,e){const t=Gl();t.has(n)?t.set(n,e):t.append(n,e),document.location.search=t.toString()}function ql(n,e,t=!0){const s=Gl();s.has(n)?e===null?s.delete(n):s.set(n,e):e!==null&&s.append(n,e),t?cb(n,s):Km(n,s)}function Ym(n,e,t){n.has(e)?n.set(e,t.toString()):n.append(e,t.toString())}function cb(n,e,t){window.history.pushState(t,n,"?"+e.toString())}function Km(n,e,t){window.history.replaceState(t,n,"?"+e.toString())}function NO(n){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s=t.length,o=0;o<n;o++)e+=t.charAt(Math.floor(Math.random()*s));return e}function WO(n,e){return Math.floor(Math.random()*(e-n+1))+n}const hb=["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"],db=["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 ub(){const n=hb[Math.floor(Math.random()*hb.length)],e=db[Math.floor(Math.random()*db.length)];return n+"_"+e}function pb(n){return n=n.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),n.trim()}function Ma(n,e,t=!0,s=!1){var o;if(e==null)return null;if(e.userData&&e.userData.guid===n||e.guid==n)return e;if(s&&(o=e.userData)!=null&&o.components){for(const r of e.userData.components)if(r.guid===n)return r}if(t){if(e.scenes)for(const r in e.scenes){const l=e.scenes[r],c=Ma(n,l,t,s);if(c)return c}if(e.children)for(const r in e.children){const l=e.children[r],c=Ma(n,l,t,s);if(c)return c}}}function Xl(n,e){if(n!=null&&typeof n=="object"){let t;Array.isArray(n)?t=[]:(t=Object.create(n),Object.assign(t,n));for(const s of Object.keys(n)){const o=n[s];e&&!e(n,s,o)?t[s]=o:o?.clone!==void 0&&typeof o.clone=="function"?t[s]=o.clone():t[s]=Xl(o,e)}return t}return n}function $s(n){return new Promise((e,t)=>{setTimeout(e,n)})}function Ql(n,e){if(n<=0)return Promise.resolve();if(e||(e=pe.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+n;return new Promise((s,o)=>{if(!e)return o("No context");const r=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(r),1),s())};e.pre_update_callbacks.push(r)})}const Od=C("debugresolveurl"),mb="rel:";function VO(n,e){return vo(n,e)}function vo(n,e){if(e===void 0)return Od&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Od&&console.warn("getPath: uri is absolute, returning uri",e),e;if(n===void 0)return Od&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(mb)&&(e=e.substring(4));const t=n.lastIndexOf("/");if(t>=0){const s=n.substring(0,t+1);for(;s.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const o=s+e;return Od&&console.log("source:",n,`changed uri
|
|
4
4
|
from`,e,`
|
|
@@ -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
|
-
`,n.shadowRoot?n.shadowRoot.appendChild(t):n.appendChild(t);const s=document.createElement("style");return s.innerHTML=dk,t.appendChild(s),t}}const Sb=Symbol("logtype"),Md=new Map;function Cb(n){n.remove();const e=n[Sb],t=Md.get(e)??[];t.push(n),Md.set(e,t)}function pk(n,e){if(Md.has(n)){const s=Md.get(n);if(s.length>0){const o=s.pop();return o.innerHTML=e,o}}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[Sb]=n,n){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 mk{constructor(){a(this,"Rad2Deg",180/Math.PI),a(this,"Deg2Rad",Math.PI/180),a(this,"Epsilon",1e-5)}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,s=1){e.x=this.random(t,s),e.y=this.random(t,s),e.z=this.random(t,s)}clamp(e,t,s){return e<t?t:e>s?s:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,s){return s=s<0?0:s,s=s>1?1:s,e+(t-e)*s}inverseLerp(e,t,s){return(s-e)/(t-e)}remap(e,t,s,o,r){return o+(r-o)*(e-t)/(s-t)}moveTowards(e,t,s){return e+=s,(s<0&&e<t||s>0&&e>t)&&(e=t),e}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,s=Number.EPSILON){for(const o of gk){const r=e[o],l=t[o];if(r===void 0||l===void 0)break;if(Math.abs(r-l)>s)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const gk=["x","y","z","w"],W=new mk;class Pb{constructor(e){a(this,"y"),a(this,"s"),a(this,"alpha",0),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 s;return this.y?s=this.alpha*e+(1-this.alpha)*this.s:s=e,this.y=e,this.s=s,s}lastValue(){return this.y}reset(e){this.y=e,this.s=e}}class Rd{constructor(e,t=1,s=0,o=1){if(a(this,"freq"),a(this,"minCutOff"),a(this,"beta"),a(this,"dCutOff"),a(this,"x"),a(this,"dx"),a(this,"lasttime"),e<=0||t<=0||o<=0)throw new Error;this.freq=e,this.minCutOff=t,this.beta=s,this.dCutOff=o,this.x=new Pb(this.alpha(this.minCutOff)),this.dx=new Pb(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 s=this.x.lastValue(),o=s?(e-s)*this.freq:0,r=this.dx.filter(o,this.alpha(this.dCutOff)),l=this.minCutOff+this.beta*Math.abs(r);return this.x.filter(e,this.alpha(l))}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 rg{constructor(e,t=1,s=0,o=1){a(this,"x"),a(this,"y"),a(this,"z"),this.x=new Rd(e,t,s,o),this.y=new Rd(e,t,s,o),this.z=new Rd(e,t,s,o)}filter(e,t,s=null){t.x=this.x.filter(e.x,s),t.y=this.y.filter(e.y,s),t.z=this.z.filter(e.z,s)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}}const Td="needle:cameraController";function Ob(n){return n[Td]}function ag(n,e,t){t?n[Td]=e:n[Td]===e&&(n[Td]=null)}const lg="needle:autofit";function kb(n){return n[lg]===void 0?!0:n[lg]!==!1}function Ed(n,e){n[lg]=e}function fk(n,e,t){const s=n.length(),o=e.length(),r=W.lerp(s,o,t);return n.lerp(e,t).normalize().multiplyScalar(r)}const cg=new V,Mb=new V().setFromAxisAngle(new S(0,1,0),Math.PI);function yk(n,e){n.lookAt(e),n.quaternion.multiply(Mb)}function Zl(n,e,t=!0,s=!1){if(n===e)return;cg.copy(n.quaternion);const o=ee(e),r=ee(n);if(s){if(Yi(n,Se(e)),t){const l=r.y,c=r.sub(Ib(n));c.y=l,n.lookAt(c),n.quaternion.multiply(Mb)}Number.isNaN(n.quaternion.x)&&n.quaternion.copy(cg);return}t&&(o.y=r.y),n.lookAt(o),Number.isNaN(n.quaternion.x)&&n.quaternion.copy(cg)}function vk(n,e,t,s=1){if(t){const o=X(0,0,0),r=e.x/window.innerWidth*2-1,l=-(e.y/window.innerHeight)*2+1;o.set(r,l,0),o.unproject(t);const c=t.worldPosition,h=n.worldPosition.distanceTo(c),d=o.sub(c);d.multiplyScalar(s*3.6*h);const u=t.worldPosition.add(d);return n.lookAt(u),u}return null}const bk=new ki(()=>new S,100);function X(n,e,t){const s=bk.get();return s.set(0,0,0),n instanceof S?s.copy(n):Array.isArray(n)?s.set(n[0],n[1],n[2]):n instanceof DOMPointReadOnly?s.set(n.x,n.y,n.z):typeof n=="number"?(s.x=n,s.y=e!==void 0?e:s.x,s.z=t!==void 0?t:s.x):typeof n=="object"&&(s.x=n.x,s.y=n.y,s.z=n.z),s}const _k=new ki(()=>new re,30);function Rb(n){const e=_k.get();return n?e.copy(n):e.set(0,0,0),e}const wk=new ki(()=>new V,100);function vs(n){const e=wk.get();return e.identity(),n instanceof V?e.copy(n):n instanceof DOMPointReadOnly&&e.set(n.x,n.y,n.z,n.w),e}const hg=new ki(()=>new S,100),Tb=Symbol("lastMatrixWorldUpdateKey");function ee(n,e=null,t=!0){const s=e??hg.get();return n?n.parent?(t&&n.updateWorldMatrix(!0,!1),n.matrixWorldNeedsUpdate&&n[Tb]!==Date.now()&&(n[Tb]=Date.now(),n.updateMatrixWorld()),s.setFromMatrixPosition(n.matrixWorld),s):s.copy(n.position):s.set(0,0,0)}function lt(n,e){if(!n)return n;const t=hg.get();return e!==t&&t.copy(e),(n?.parent??n).worldToLocal(t),n.position.set(t.x,t.y,t.z),n}function vr(n,e,t,s){const o=hg.get();return o.set(e,t,s),lt(n,o),n}const Ad=new ki(()=>new V,100),br=new V,dg=new V;function Se(n,e=null){if(!n)return Ad.get().identity();const t=e??Ad.get();return n.parent?(n.getWorldQuaternion(t),t):t.copy(n.quaternion)}function Yi(n,e){if(!n)return;e!==br&&br.copy(e);const t=br,s=n?.parent;s?.getWorldQuaternion(dg),dg.invert();const o=dg.multiply(t);n.quaternion.set(o.x,o.y,o.z,o.w)}function ug(n,e,t,s,o){br.set(e,t,s,o),Yi(n,br)}const xk=new ki(()=>new S,100),Sk=new S;function Ge(n,e=null){return e||(e=xk.get()),n?n.parent?(n.getWorldScale(e),e):e.copy(n.scale):e.set(0,0,0)}function Ta(n,e){if(!n)return;if(!n.parent){n.scale.copy(e);return}const t=Sk;n.parent.getWorldScale(t),n.scale.copy(e),n.scale.divide(t)}const Ck=new S,Eb=new V;function Pk(n){return Se(n,Eb),Ck.set(0,0,1).applyQuaternion(Eb)}const Ok=new ki(()=>new S,100),Ab=new V;function Ib(n,e){return e||(e=Ok.get().set(0,0,1)),Se(n,Ab),e.applyQuaternion(Ab)}const Lb=new
|
|
57
|
+
`,n.shadowRoot?n.shadowRoot.appendChild(t):n.appendChild(t);const s=document.createElement("style");return s.innerHTML=dk,t.appendChild(s),t}}const Sb=Symbol("logtype"),Md=new Map;function Cb(n){n.remove();const e=n[Sb],t=Md.get(e)??[];t.push(n),Md.set(e,t)}function pk(n,e){if(Md.has(n)){const s=Md.get(n);if(s.length>0){const o=s.pop();return o.innerHTML=e,o}}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[Sb]=n,n){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 mk{constructor(){a(this,"Rad2Deg",180/Math.PI),a(this,"Deg2Rad",Math.PI/180),a(this,"Epsilon",1e-5)}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,s=1){e.x=this.random(t,s),e.y=this.random(t,s),e.z=this.random(t,s)}clamp(e,t,s){return e<t?t:e>s?s:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,s){return s=s<0?0:s,s=s>1?1:s,e+(t-e)*s}inverseLerp(e,t,s){return(s-e)/(t-e)}remap(e,t,s,o,r){return o+(r-o)*(e-t)/(s-t)}moveTowards(e,t,s){return e+=s,(s<0&&e<t||s>0&&e>t)&&(e=t),e}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,s=Number.EPSILON){for(const o of gk){const r=e[o],l=t[o];if(r===void 0||l===void 0)break;if(Math.abs(r-l)>s)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const gk=["x","y","z","w"],W=new mk;class Pb{constructor(e){a(this,"y"),a(this,"s"),a(this,"alpha",0),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 s;return this.y?s=this.alpha*e+(1-this.alpha)*this.s:s=e,this.y=e,this.s=s,s}lastValue(){return this.y}reset(e){this.y=e,this.s=e}}class Rd{constructor(e,t=1,s=0,o=1){if(a(this,"freq"),a(this,"minCutOff"),a(this,"beta"),a(this,"dCutOff"),a(this,"x"),a(this,"dx"),a(this,"lasttime"),e<=0||t<=0||o<=0)throw new Error;this.freq=e,this.minCutOff=t,this.beta=s,this.dCutOff=o,this.x=new Pb(this.alpha(this.minCutOff)),this.dx=new Pb(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 s=this.x.lastValue(),o=s?(e-s)*this.freq:0,r=this.dx.filter(o,this.alpha(this.dCutOff)),l=this.minCutOff+this.beta*Math.abs(r);return this.x.filter(e,this.alpha(l))}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 rg{constructor(e,t=1,s=0,o=1){a(this,"x"),a(this,"y"),a(this,"z"),this.x=new Rd(e,t,s,o),this.y=new Rd(e,t,s,o),this.z=new Rd(e,t,s,o)}filter(e,t,s=null){t.x=this.x.filter(e.x,s),t.y=this.y.filter(e.y,s),t.z=this.z.filter(e.z,s)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}}const Td="needle:cameraController";function Ob(n){return n[Td]}function ag(n,e,t){t?n[Td]=e:n[Td]===e&&(n[Td]=null)}const lg="needle:autofit";function kb(n){return n[lg]===void 0?!0:n[lg]!==!1}function Ed(n,e){n[lg]=e}function fk(n,e,t){const s=n.length(),o=e.length(),r=W.lerp(s,o,t);return n.lerp(e,t).normalize().multiplyScalar(r)}const cg=new V,Mb=new V().setFromAxisAngle(new S(0,1,0),Math.PI);function yk(n,e){n.lookAt(e),n.quaternion.multiply(Mb)}function Zl(n,e,t=!0,s=!1){if(n===e)return;cg.copy(n.quaternion);const o=ee(e),r=ee(n);if(s){if(Yi(n,Se(e)),t){const l=r.y,c=r.sub(Ib(n));c.y=l,n.lookAt(c),n.quaternion.multiply(Mb)}Number.isNaN(n.quaternion.x)&&n.quaternion.copy(cg);return}t&&(o.y=r.y),n.lookAt(o),Number.isNaN(n.quaternion.x)&&n.quaternion.copy(cg)}function vk(n,e,t,s=1){if(t){const o=X(0,0,0),r=e.x/window.innerWidth*2-1,l=-(e.y/window.innerHeight)*2+1;o.set(r,l,0),o.unproject(t);const c=t.worldPosition,h=n.worldPosition.distanceTo(c),d=o.sub(c);d.multiplyScalar(s*3.6*h);const u=t.worldPosition.add(d);return n.lookAt(u),u}return null}const bk=new ki(()=>new S,100);function X(n,e,t){const s=bk.get();return s.set(0,0,0),n instanceof S?s.copy(n):Array.isArray(n)?s.set(n[0],n[1],n[2]):n instanceof DOMPointReadOnly?s.set(n.x,n.y,n.z):typeof n=="number"?(s.x=n,s.y=e!==void 0?e:s.x,s.z=t!==void 0?t:s.x):typeof n=="object"&&(s.x=n.x,s.y=n.y,s.z=n.z),s}const _k=new ki(()=>new re,30);function Rb(n){const e=_k.get();return n?e.copy(n):e.set(0,0,0),e}const wk=new ki(()=>new V,100);function vs(n){const e=wk.get();return e.identity(),n instanceof V?e.copy(n):n instanceof DOMPointReadOnly&&e.set(n.x,n.y,n.z,n.w),e}const hg=new ki(()=>new S,100),Tb=Symbol("lastMatrixWorldUpdateKey");function ee(n,e=null,t=!0){const s=e??hg.get();return n?n.parent?(t&&n.updateWorldMatrix(!0,!1),n.matrixWorldNeedsUpdate&&n[Tb]!==Date.now()&&(n[Tb]=Date.now(),n.updateMatrixWorld()),s.setFromMatrixPosition(n.matrixWorld),s):s.copy(n.position):s.set(0,0,0)}function lt(n,e){if(!n)return n;const t=hg.get();return e!==t&&t.copy(e),(n?.parent??n).worldToLocal(t),n.position.set(t.x,t.y,t.z),n}function vr(n,e,t,s){const o=hg.get();return o.set(e,t,s),lt(n,o),n}const Ad=new ki(()=>new V,100),br=new V,dg=new V;function Se(n,e=null){if(!n)return Ad.get().identity();const t=e??Ad.get();return n.parent?(n.getWorldQuaternion(t),t):t.copy(n.quaternion)}function Yi(n,e){if(!n)return;e!==br&&br.copy(e);const t=br,s=n?.parent;s?.getWorldQuaternion(dg),dg.invert();const o=dg.multiply(t);n.quaternion.set(o.x,o.y,o.z,o.w)}function ug(n,e,t,s,o){br.set(e,t,s,o),Yi(n,br)}const xk=new ki(()=>new S,100),Sk=new S;function Ge(n,e=null){return e||(e=xk.get()),n?n.parent?(n.getWorldScale(e),e):e.copy(n.scale):e.set(0,0,0)}function Ta(n,e){if(!n)return;if(!n.parent){n.scale.copy(e);return}const t=Sk;n.parent.getWorldScale(t),n.scale.copy(e),n.scale.divide(t)}const Ck=new S,Eb=new V;function Pk(n){return Se(n,Eb),Ck.set(0,0,1).applyQuaternion(Eb)}const Ok=new ki(()=>new S,100),Ab=new V;function Ib(n,e){return e||(e=Ok.get().set(0,0,1)),Se(n,Ab),e.applyQuaternion(Ab)}const Lb=new Dt,jb=new Dt,kk=new S;function pg(n){const e=Ad.get();return n.getWorldQuaternion(e),jb.setFromQuaternion(e),jb}function mg(n,e){const t=Ad.get();Yi(n,t.setFromEuler(e))}function Id(n){const e=pg(n),t=kk;return t.set(e.x,e.y,e.z),t.x=W.toDegrees(t.x),t.y=W.toDegrees(t.y),t.z=W.toDegrees(t.z),t}function Db(n,e){Jl(n,e.x,e.y,e.z,!0)}function Jl(n,e,t,s,o=!0){o&&(e=W.toRadians(e),t=W.toRadians(t),s=W.toRadians(s)),Lb.set(e,t,s),br.setFromEuler(Lb),Yi(n,br)}function Ld(n,e=!0){n&&(e?function t(s){console.groupCollapsed((s.name?s.name:"(no name : "+s.type+")")+" %o",s),s.children.forEach(t),console.groupEnd()}(n):n.traverse(function(t){for(var s="|___",o=t;o.parent!==null;)s=" "+s,o=o.parent;console.log(s+t.name+" <"+t.type+">")}))}function Mk(n){let e=n?.name||"";if(!n)return e;let t=n.parent;for(;t;)e=t.name+"/"+e,t=t.parent;return e}function Bb(n){if(n){const e=n;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}const Fb=class mC extends Ns{constructor(){super({vertexShader:mC.vertex,uniforms:{map:new Qi(null),flipY:new Qi(!0),writeDepth:new Qi(!1),depthTexture:new Qi(null)},fragmentShader:`
|
|
58
58
|
uniform sampler2D map;
|
|
59
59
|
uniform bool flipY;
|
|
60
60
|
uniform bool writeDepth;
|
|
@@ -142,8 +142,8 @@ Open this page to get the console: `+e.toString())}const n=Q.isMobileDevice()||Q
|
|
|
142
142
|
#__vconsole .vc-mask {
|
|
143
143
|
overflow: hidden;
|
|
144
144
|
}
|
|
145
|
-
`,Ki?.prepend(s),n===!0&&ig()<=0&&qb(),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.":"")),nc=!1,oi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Wk(){if(!globalThis.VConsole)return;const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);n.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(o){window.open(n.fullUrl,"_blank"),oi?.hide()}}),s.push({name:"Reload",onClick:function(o){const r=e();r&&(r.src=n.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(o){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),n}function Vk(){return document.querySelector("#__vconsole .vc-switch")||null}function $k(){return document.querySelector("#__vconsole")||null}const Kb=C("debugdefines");_o('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),_o('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),_o('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),_o('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),_o('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.
|
|
146
|
-
Project built at ${wg}`);const Ea=NEEDLE_PUBLIC_KEY,En="needle_isActiveInHierarchy",wr="builtin_components",rc="needle_editor_guid";function _o(n){try{(0,eval)(n)}catch(e){Kb&&console.error(e)}}let Zb,Jb=null;function ws(){return Zb}function xg(n){if(n==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}Jb!==n&&(Jb=n,Zb=new n)}const Ri=Symbol("shadowDomOwner"),Hk=C("debugpatch");function Bd(n,e,t,s){const o=Hk===e;if(!t&&!s)return;const r=e+"___needle";qk(n,e,t,s);const l=Object.getOwnPropertyDescriptor(n,e),c=n[e];o&&console.log("Patch",n.constructor.name,e,l,c),l?(o&&console.log("Apply patch with existing descriptor",n.constructor.name,e,l),typeof l.value=="function"&&(n[e]=t_(l.value,n,e))):(o&&console.log("Create patch with new property",n.constructor.name,e,l),Object.defineProperty(n,e,{set:function(h){if(typeof h=="function")this[r]=t_(h,n,e);else{const d=this[r];i_(n,e,this,d,h),this[r]=h,s_(n,e,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function Gk(n,e,t){const s=Cg(n,e);if(s)for(let o=s.length-1;o>=0;o--){const r=s[o];r.prefix===t&&(r.prefix=null),r.postfix===t&&(r.postfix=null),!r.prefix&&!r.postfix&&s.splice(o,1)}}const e_=Symbol("Needle:Patches:WrappedFunction");function t_(n,e,t){if(n[e_])return n;const s=function(...o){i_(e,t,this,...o);const r=n.apply(this,o);return s_(e,t,this,r,...o),r};return s[e_]=!0,s}const Fd="Needle:Patches";function Sg(){return globalThis[Fd]||(globalThis[Fd]=new WeakMap),globalThis[Fd]}function Cg(n,e){const t=Sg().get(n);return t?t.get(e):null}function qk(n,e,t,s){let o=Sg().get(n);o||(o=new Map,Sg().set(n,o));let r=o.get(e);r||(r=[],o.set(e,r)),r.push({prefix:t,postfix:s})}function i_(n,e,t,...s){var o;if(!t)return;const r=Cg(n,e);if(r)for(const l of r)(o=l.prefix)==null||o.call(t,...s)}function s_(n,e,t,s,...o){var r;if(!t)return;const l=Cg(n,e);if(l)for(const c of l)(r=c.postfix)==null||r.call(t,s,...o)}const Aa=[];function Ud(n){Aa.indexOf(n)===-1&&Aa.push(n)}function Xk(n){const e=Aa.indexOf(n);e!==-1&&Aa.splice(e,1)}const Ia=[];function Pg(n){Ia.indexOf(n)===-1&&Ia.push(n)}function Qk(n){const e=Ia.indexOf(n);e!==-1&&Ia.splice(e,1)}function n_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<Aa.length;e++)Aa[e](n)}function o_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Ia.length;e++)Ia[e](n)}const ct=C("debuginput");var zd=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(zd||{}),Be=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(Be||{});class An extends PointerEvent{constructor(e,t,s){super(e,s),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=s.clientZ,this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this._ray=s.ray,this.space=s.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new mo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),ct&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ac extends KeyboardEvent{constructor(e,t,s){super(e,s),a(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class Yk{constructor(e){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ri=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ri||{});class r_{constructor(e){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_setCursorTypes",[]),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new ie]),a(this,"_pointerPositionsLastFrame",[new ie]),a(this,"_pointerPositionsDelta",[new ie]),a(this,"_pointerPositionsRC",[new ie]),a(this,"_pointerPositionDown",[new S]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),a(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",t=>{if(ct&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const o=new ac("keydown",t,t);this.onDispatchEvent(o)}),a(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const o=new ac("keypress",t,t);this.onDispatchEvent(o)}),a(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const o=new ac("keyup",t,t);this.onDispatchEvent(o)}),a(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),a(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),a(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const s=this.getPointerId(t);ct&&De(`pointer down #${s}, identifier:${t.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),r=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onDown(r)}),a(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let s=t.button;t.pointerType==="mouse"&&(s=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(t,s);s===-1&&(s=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,t.clientX,t.clientY),l=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:r,pressure:t.pressure});this.onMove(l)}),a(this,"onPointerCancel",t=>{this.context.isInAR||(ct&&console.log("Pointer cancel",t),this.onPointerUp(t))}),a(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const s=this.getPointerId(t),o=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),pressure:t.pressure});this.onUp(o),this._pointerIds[s]=-1,ct&&console.log("ID="+s,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new S),a(this,"tempFarPlaneVector",new S),a(this,"tempLookMatrix",new ne),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}s?s={...s}:s={};let o=0;s?.queue!=null&&(o=s.queue);const r=this._eventListeners[e],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:t,options:s}):(r.push({priority:o,listeners:[{callback:t,options:s}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e]||!t)return;const o=this._eventListeners[e];if(s?.queue!=null){const r=o.find(c=>c.priority===s.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(e){var t,s,o,r;let l=!1;if(e instanceof ac){const c=this._eventListeners[e.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((s=(t=u.options)==null?void 0:t.signal)!=null&&s.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}if(e instanceof An){const c=this._eventListeners[e.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(e.immediatePropagationStopped){l=!0,ct&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(l=!0,ct&&console.log("propagationStopped",e.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){var e;((e=this._setCursorTypes)==null?void 0:e.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let o=!1;for(const r of e)if(s===r){o=!0;break}if(!o)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const o=s.indexOf(t);o>=0&&s.splice(o,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.startFrame===this.context.time.frameCount)return s.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.pressed)return s.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const s=this.keysPressed[t];return s.pressed===!1&&s.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyDown(o))return!0;return!1}const s=this.keysPressed[e];return s?s.startFrame===this.context.time.frameCount&&s.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyUp(o))return!0;return!1}const s=this.keysPressed[e];return s?s.frame===this.context.time.frameCount&&s.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyPressed(o))return!0;return!1}const s=this.keysPressed[e];return s&&s.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":ct&&De("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ct&&De("Create Pointer move"),this.onMove(e);break;case"pointerup":ct&&De("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;for(const s in this._eventListeners)this._eventListeners[s].length=0;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&Q.isMozillaXR()?!0:(ct&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let o=this._pointerSpace[e];o||(o=new A,this._pointerSpace[e]=o),this._pointerSpace[e]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||X(0,1,0).applyQuaternion(Se(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,o=e.clientY,r=s>=t.x&&s<=t.right&&o>=t.y&&o<=t.bottom;return ct&&!r&&console.log("Not in rect",t,s,o),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,ct?e:""),ct&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new S);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new ie);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){ct&&console.log(e.pointerType,"UP",t,"was not down");return}ct&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===t){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[t]){ct&&be("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,l=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,l<1){let c=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-s;ct&&console.log("CLICK",t,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ie);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ie);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ie);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const o=this._pointerPositionsDelta[t];let r=e.clientX-s.x,l=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const c=e.clientX,h=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ie);const d=this._pointerPositionsRC[t];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(e){let t=-1;for(let s=0;s<this._pointerIds.length;s++){if(this._pointerIds[s]===e)return s;t===-1&&this._pointerIds[s]===-1&&(t=s)}return t!==-1?(this._pointerIds[t]=e,t):(ct&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=J.Current;try{J.Current=this.context,this.dispatchEvent(e)}finally{J.Current=t}}}const La=new ne().makeRotationY(Math.PI),Zi=new V().setFromAxisAngle(new S(0,1,0),Math.PI),Kk=C("debugwebxr");class Zk{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new A,this.gameObject.name="Implicit XR Rig",Kk){const e=$g(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const In=C("debugwebxr"),Nd=C("debugcustomgesture"),Jk="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",eM="generic-trigger",tM=new V().setFromEuler(new Bt(Cn.degToRad(0),Cn.degToRad(-90),Cn.degToRad(-90))),iM=new S(.04,-.04,0);class Og{constructor(e,t,s){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new ne),a(this,"_gripPosition",new S),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new S),a(this,"_rayPositionRaw",new S),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new ne),a(this,"_rayPosition",new S),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new S),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new S),a(this,"_rayWorldQuaternion",new V),a(this,"_pinchPosition",new S),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new Pi(.15)),a(this,"_debugGripAxesHelper",new Pi(.07)),a(this,"_debugRayAxesHelper",new Pi(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!Nd&&(In&&G.DrawDirection(this.rayWorldPosition,X(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Be.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(Nd||this.inputSource===o.inputSource&&this.emitPointerEvent(Be.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(In&&G.DrawDirection(this.rayWorldPosition,X(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Be.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Be.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new S),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=e,this.inputSource=t,this.index=s,this._object=new A,this._object.name=`NeedleXRController_${s}`,In&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new A,this._raySpaceObject=new A,this._gripSpaceObject.name=`NeedleXRController_${s}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${s}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new mo,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e,t){var s;if(t=t||this.xr.frame,!this.hand||!(t!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let o=(s=this._handJointPoses)==null?void 0:s.get(e);return o||(o=t.getJointPose(e,this.xr.referenceSpace),o&&this._handJointPoses.set(e,o),o)}get gripPosition(){return X(this._gripPosition)}get gripQuaternion(){return vs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return X(this._linearVelocity).applyQuaternion(Zi)}get rayPosition(){return X(this._rayPosition)}get rayQuaternion(){return vs(this._rayQuaternion)}get gripWorldPosition(){return X(this._gripWorldPosition)}get gripWorldQuaternion(){return vs(this._gripWorldQuaternion)}get rayWorldPosition(){return X(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return vs(this._rayWorldQuaternion)}get pinchPosition(){return X(this._pinchPosition)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Se(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Zi),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(X(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const s=X(0,1,0).applyQuaternion(t.quaternion),o=X(0,1,0).dot(s);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var e;return this.isHandUpsideDown&&((e=this.getGesture("pinch"))==null?void 0:e.isDown)}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}_requestHitTestSource(){var e;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((e=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:e.then(t=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=t:(t.cancel(),null))))??null:null}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;G.DrawSphere(this.rayWorldPosition,.003),G.DrawDirection(this.rayWorldPosition,X(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
|
|
145
|
+
`,Ki?.prepend(s),n===!0&&ig()<=0&&qb(),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.":"")),nc=!1,oi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Wk(){if(!globalThis.VConsole)return;const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);n.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(o){window.open(n.fullUrl,"_blank"),oi?.hide()}}),s.push({name:"Reload",onClick:function(o){const r=e();r&&(r.src=n.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(o){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),n}function Vk(){return document.querySelector("#__vconsole .vc-switch")||null}function $k(){return document.querySelector("#__vconsole")||null}const Kb=C("debugdefines");_o('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),_o('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),_o('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),_o('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),_o('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.3-alpha";'),_o('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),_o('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Aug 06 2025 09:23:38 GMT+0000 (Coordinated Universal Time)";'),_o('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _s="4.7.3-alpha",Dd="undefined",wg="Wed Aug 06 2025 09:23:38 GMT+0000 (Coordinated Universal Time)";Kb&&console.log(`Engine version: ${_s} (generator: ${Dd})
|
|
146
|
+
Project built at ${wg}`);const Ea=NEEDLE_PUBLIC_KEY,En="needle_isActiveInHierarchy",wr="builtin_components",rc="needle_editor_guid";function _o(n){try{(0,eval)(n)}catch(e){Kb&&console.error(e)}}let Zb,Jb=null;function ws(){return Zb}function xg(n){if(n==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}Jb!==n&&(Jb=n,Zb=new n)}const Ri=Symbol("shadowDomOwner"),Hk=C("debugpatch");function Bd(n,e,t,s){const o=Hk===e;if(!t&&!s)return;const r=e+"___needle";qk(n,e,t,s);const l=Object.getOwnPropertyDescriptor(n,e),c=n[e];o&&console.log("Patch",n.constructor.name,e,l,c),l?(o&&console.log("Apply patch with existing descriptor",n.constructor.name,e,l),typeof l.value=="function"&&(n[e]=t_(l.value,n,e))):(o&&console.log("Create patch with new property",n.constructor.name,e,l),Object.defineProperty(n,e,{set:function(h){if(typeof h=="function")this[r]=t_(h,n,e);else{const d=this[r];i_(n,e,this,d,h),this[r]=h,s_(n,e,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function Gk(n,e,t){const s=Cg(n,e);if(s)for(let o=s.length-1;o>=0;o--){const r=s[o];r.prefix===t&&(r.prefix=null),r.postfix===t&&(r.postfix=null),!r.prefix&&!r.postfix&&s.splice(o,1)}}const e_=Symbol("Needle:Patches:WrappedFunction");function t_(n,e,t){if(n[e_])return n;const s=function(...o){i_(e,t,this,...o);const r=n.apply(this,o);return s_(e,t,this,r,...o),r};return s[e_]=!0,s}const Fd="Needle:Patches";function Sg(){return globalThis[Fd]||(globalThis[Fd]=new WeakMap),globalThis[Fd]}function Cg(n,e){const t=Sg().get(n);return t?t.get(e):null}function qk(n,e,t,s){let o=Sg().get(n);o||(o=new Map,Sg().set(n,o));let r=o.get(e);r||(r=[],o.set(e,r)),r.push({prefix:t,postfix:s})}function i_(n,e,t,...s){var o;if(!t)return;const r=Cg(n,e);if(r)for(const l of r)(o=l.prefix)==null||o.call(t,...s)}function s_(n,e,t,s,...o){var r;if(!t)return;const l=Cg(n,e);if(l)for(const c of l)(r=c.postfix)==null||r.call(t,s,...o)}const Aa=[];function Ud(n){Aa.indexOf(n)===-1&&Aa.push(n)}function Xk(n){const e=Aa.indexOf(n);e!==-1&&Aa.splice(e,1)}const Ia=[];function Pg(n){Ia.indexOf(n)===-1&&Ia.push(n)}function Qk(n){const e=Ia.indexOf(n);e!==-1&&Ia.splice(e,1)}function n_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<Aa.length;e++)Aa[e](n)}function o_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Ia.length;e++)Ia[e](n)}const ct=C("debuginput");var zd=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(zd||{}),Be=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(Be||{});class An extends PointerEvent{constructor(e,t,s){super(e,s),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=s.clientZ,this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this._ray=s.ray,this.space=s.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new mo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),ct&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ac extends KeyboardEvent{constructor(e,t,s){super(e,s),a(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class Yk{constructor(e){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ri=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ri||{});class r_{constructor(e){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_setCursorTypes",[]),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new ie]),a(this,"_pointerPositionsLastFrame",[new ie]),a(this,"_pointerPositionsDelta",[new ie]),a(this,"_pointerPositionsRC",[new ie]),a(this,"_pointerPositionDown",[new S]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),a(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",t=>{if(ct&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const o=new ac("keydown",t,t);this.onDispatchEvent(o)}),a(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const o=new ac("keypress",t,t);this.onDispatchEvent(o)}),a(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const o=new ac("keyup",t,t);this.onDispatchEvent(o)}),a(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),a(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),a(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const s=this.getPointerId(t);ct&&De(`pointer down #${s}, identifier:${t.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),r=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onDown(r)}),a(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let s=t.button;t.pointerType==="mouse"&&(s=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(t,s);s===-1&&(s=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,t.clientX,t.clientY),l=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:r,pressure:t.pressure});this.onMove(l)}),a(this,"onPointerCancel",t=>{this.context.isInAR||(ct&&console.log("Pointer cancel",t),this.onPointerUp(t))}),a(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const s=this.getPointerId(t),o=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),pressure:t.pressure});this.onUp(o),this._pointerIds[s]=-1,ct&&console.log("ID="+s,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new S),a(this,"tempFarPlaneVector",new S),a(this,"tempLookMatrix",new ne),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}s?s={...s}:s={};let o=0;s?.queue!=null&&(o=s.queue);const r=this._eventListeners[e],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:t,options:s}):(r.push({priority:o,listeners:[{callback:t,options:s}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e]||!t)return;const o=this._eventListeners[e];if(s?.queue!=null){const r=o.find(c=>c.priority===s.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(e){var t,s,o,r;let l=!1;if(e instanceof ac){const c=this._eventListeners[e.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((s=(t=u.options)==null?void 0:t.signal)!=null&&s.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}if(e instanceof An){const c=this._eventListeners[e.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(e.immediatePropagationStopped){l=!0,ct&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(l=!0,ct&&console.log("propagationStopped",e.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){var e;((e=this._setCursorTypes)==null?void 0:e.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let o=!1;for(const r of e)if(s===r){o=!0;break}if(!o)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const o=s.indexOf(t);o>=0&&s.splice(o,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.startFrame===this.context.time.frameCount)return s.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.pressed)return s.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const s=this.keysPressed[t];return s.pressed===!1&&s.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyDown(o))return!0;return!1}const s=this.keysPressed[e];return s?s.startFrame===this.context.time.frameCount&&s.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyUp(o))return!0;return!1}const s=this.keysPressed[e];return s?s.frame===this.context.time.frameCount&&s.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyPressed(o))return!0;return!1}const s=this.keysPressed[e];return s&&s.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":ct&&De("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ct&&De("Create Pointer move"),this.onMove(e);break;case"pointerup":ct&&De("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;for(const s in this._eventListeners)this._eventListeners[s].length=0;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&Q.isMozillaXR()?!0:(ct&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let o=this._pointerSpace[e];o||(o=new A,this._pointerSpace[e]=o),this._pointerSpace[e]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||X(0,1,0).applyQuaternion(Se(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,o=e.clientY,r=s>=t.x&&s<=t.right&&o>=t.y&&o<=t.bottom;return ct&&!r&&console.log("Not in rect",t,s,o),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,ct?e:""),ct&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new S);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new ie);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){ct&&console.log(e.pointerType,"UP",t,"was not down");return}ct&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===t){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[t]){ct&&be("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,l=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,l<1){let c=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-s;ct&&console.log("CLICK",t,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ie);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ie);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ie);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const o=this._pointerPositionsDelta[t];let r=e.clientX-s.x,l=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const c=e.clientX,h=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ie);const d=this._pointerPositionsRC[t];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(e){let t=-1;for(let s=0;s<this._pointerIds.length;s++){if(this._pointerIds[s]===e)return s;t===-1&&this._pointerIds[s]===-1&&(t=s)}return t!==-1?(this._pointerIds[t]=e,t):(ct&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=J.Current;try{J.Current=this.context,this.dispatchEvent(e)}finally{J.Current=t}}}const La=new ne().makeRotationY(Math.PI),Zi=new V().setFromAxisAngle(new S(0,1,0),Math.PI),Kk=C("debugwebxr");class Zk{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new A,this.gameObject.name="Implicit XR Rig",Kk){const e=$g(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const In=C("debugwebxr"),Nd=C("debugcustomgesture"),Jk="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",eM="generic-trigger",tM=new V().setFromEuler(new Dt(Cn.degToRad(0),Cn.degToRad(-90),Cn.degToRad(-90))),iM=new S(.04,-.04,0);class Og{constructor(e,t,s){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new ne),a(this,"_gripPosition",new S),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new S),a(this,"_rayPositionRaw",new S),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new ne),a(this,"_rayPosition",new S),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new S),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new S),a(this,"_rayWorldQuaternion",new V),a(this,"_pinchPosition",new S),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new Pi(.15)),a(this,"_debugGripAxesHelper",new Pi(.07)),a(this,"_debugRayAxesHelper",new Pi(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!Nd&&(In&&G.DrawDirection(this.rayWorldPosition,X(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Be.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(Nd||this.inputSource===o.inputSource&&this.emitPointerEvent(Be.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(In&&G.DrawDirection(this.rayWorldPosition,X(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Be.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Be.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new S),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=e,this.inputSource=t,this.index=s,this._object=new A,this._object.name=`NeedleXRController_${s}`,In&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new A,this._raySpaceObject=new A,this._gripSpaceObject.name=`NeedleXRController_${s}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${s}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new mo,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e,t){var s;if(t=t||this.xr.frame,!this.hand||!(t!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let o=(s=this._handJointPoses)==null?void 0:s.get(e);return o||(o=t.getJointPose(e,this.xr.referenceSpace),o&&this._handJointPoses.set(e,o),o)}get gripPosition(){return X(this._gripPosition)}get gripQuaternion(){return vs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return X(this._linearVelocity).applyQuaternion(Zi)}get rayPosition(){return X(this._rayPosition)}get rayQuaternion(){return vs(this._rayQuaternion)}get gripWorldPosition(){return X(this._gripWorldPosition)}get gripWorldQuaternion(){return vs(this._gripWorldQuaternion)}get rayWorldPosition(){return X(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return vs(this._rayWorldQuaternion)}get pinchPosition(){return X(this._pinchPosition)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Se(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Zi),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(X(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const s=X(0,1,0).applyQuaternion(t.quaternion),o=X(0,1,0).dot(s);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var e;return this.isHandUpsideDown&&((e=this.getGesture("pinch"))==null?void 0:e.isDown)}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}_requestHitTestSource(){var e;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((e=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:e.then(t=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=t:(t.cancel(),null))))??null:null}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;G.DrawSphere(this.rayWorldPosition,.003),G.DrawDirection(this.rayWorldPosition,X(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
|
|
147
147
|
`);let o=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
148
148
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(o+=`
|
|
149
149
|
Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),o+=`
|
|
@@ -163,12 +163,12 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
|
|
|
163
163
|
`+Ti);const c=await import("./vendor-BlSxe9JJ.min.js").then(p=>p.index),h=((s=c.default)==null?void 0:s.WebsocketBuilder)??c.WebsocketBuilder,d=((o=c.default)==null?void 0:o.ExponentialBackoff)??c.ExponentialBackoff,u=new h(Ti).withMaxRetries(10).withBackoff(new d(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,B()||ai?console.log(`\u229E Connected to networking backend
|
|
164
164
|
`+Ti):console.debug("\u229E Connected to networking backend",Ti),l(!0),this.onSendQueued(xs.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,l(!1);let g="Websocket connection closed...";Ti!=null&&Ti.includes("/socket")||(g+=' Do you perhaps mean to connect to "/socket"?'),console.error(g)}).onError(p=>{console.error("\u22A0 Websocket connection failed..."),l(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();u.addEventListener(c.WebsocketEvent.message,(p,g)=>{this.onMessage(p,g)})})}onMessage(e,t){const s=t.data;try{if(typeof s!="string"){s.size&&this.handleIncomingBinaryMessage(s);return}const o=JSON.parse(s);if(Array.isArray(o))for(const r of o)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(o);return}catch(o){ai&&s==="pong"?console.log("<<",s):B()&&console.error("Failed to parse message",o)}}async handleIncomingBinaryMessage(e){$d&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var s=new Uint8Array(t);const o=new vO(s),r=o.getBufferIdentifier(),l=this._listenersBinary[r],c=p_(o),h=m_(c);if(h&&typeof h=="string"&&(this._state[h]=c),!l)return;const d=c??o;for(const u of l)u(d)}handleIncomingStringMessage(e){var t,s;if(ai&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const h=e.data;h&&(console.assert(h.id!==void 0&&h.id!==null&&h.id.length>0,"server did not send connection id",h.id),console.debug("Your id is: "+h.id,this.context.alias??""),this._connectionId=h.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ai&&console.log(e),e){this._isInRoom=!0;const h=e;this._currentRoomName=h.room,this._currentRoomViewId=h.viewId,this._currentRoomAllowEditing=h.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...h.inRoom),($d||B())&&console.debug("Joined Needle Engine Room: "+h.room);const d=new URL(window.location.href);d.searchParams.has("room")&&d.searchParams.delete("room"),d.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
|
|
165
165
|
${d.href}`)}this.onSendQueued(xs.OnRoomJoin);break;case"left-room":const l=e;l.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,($d||B())&&console.debug("Left Needle Engine Room: "+l.room));break;case"user-joined-room":if(e.data){const h=e.data;this._currentInRoom.push(h.userId),ai&&console.log(h.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const h=e.data,d=this._currentInRoom.indexOf(h.userId);d>=0&&(ai&&console.log(h.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(d,1)),h.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ai&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const c=(t=e.data)==null?void 0:t.time;c&&(this._currentDelay=this.context.time.time-c),ai&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+((s=this._currentInRoom)==null?void 0:s.length));break}const o=e.data;o&&(this._state[o.guid]=o);let r=this._listeners[e.key];if(r){r=[...r];for(const l of r)try{l(e.data)}catch(c){console.error('Error invoking callback for "'+e.key+'"',c)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,s=xs.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[s]||[];r.push(()=>this.sendWithWebsocket(e,t,s)),this._waitingForSocket[s]=r;return}const o=JSON.stringify(this.toMessage(e,t));ai&&console.log(">>",e),this._ws.send(o)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const s of t)s();t.length=0}}}const cc=C("debugwebxr");class Lg{constructor(e,t){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",s=>{cc&&console.log(`XRSync: Received change for ${this.userId}: ${s.type} ${s.handedness}; tracked=${s.isTracking}`);let o=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===s.index){this.controllerStates[r]=s,o=!0;break}o||this.controllerStates.push(s)}),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)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const s=this.controllerStates[t];let o=!1;for(let r=0;r<e.controllers.length;r++)e.controllers[r].index===s.index&&(o=!0);o||(cc&&console.log(`XRSync: ${s.type} ${s.handedness} removed`,s.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(s))}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(s=>s.index===e.index);if(t){let s=!1;s||(s=t.isTracking!=e.isTracking),s&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const s={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(s),this.context.connection.send(this.userStateEvtName,s),cc&&console.log(`XRSync: ${s.type} ${s.handedness} added`,s.index)}}}class x_{constructor(e){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(cc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Lg(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new Lg(t,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",t=>{const s=t.userId;this._states.has(s)||(cc&&console.log("XRSync: Remote user joined room",s),this._states.set(s,new Lg(s,this.context)))}),a(this,"onOtherUserLeftRoom",t=>{const s=t.userId;if(!this._states.has(s)){const o=this._states.get(s);o?.dispose(),this._states.delete(s)}}),a(this,"_states",new Map),this.context=e,this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(se.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(se.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const s=this._states.get(e);if(!s)return;const o=s.controllerStates.find(r=>r.handedness===t);return o?.isTracking||!1}getDeviceType(e,t){if(!e)return;const s=this._states.get(e);if(!s)return;const o=s.controllerStates.find(r=>r.handedness===t);return o?.type||"unknown"}destroy(){this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(se.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(se.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class S_{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Me({color:0,transparent:!0,depthTest:!1,fog:!1,side:Oi}),this._fadeToColorQuad=new q(new zs(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const s=this._fadeToColorQuad,o=this._fadeToColorMaterial;s.parent!==e&&o.opacity>0?e.add(s):o.opacity===0&&s.removeFromParent(),s.layers.set(2),s.material=this._fadeToColorMaterial,s.position.z=-1,s.renderOrder=1/0;const r=this._requestedFadeValue;o.opacity=W.lerp(o.opacity,r,t/.03),Math.abs(o.opacity-r)<=.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}}var Sr=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n[n.Cylinder=3]="Cylinder",n[n.RoundedCube=10]="RoundedCube",n))(Sr||{}),Hd,jg;class xo{static createText(e,t){let s=null;const o=t?.font||dM(t?.familyFamily||null);o instanceof YP?s=ud(this,Hd,jg).call(this,e,o,t):s==null&&(s=new Ws);const r=t?.color||16777215,l=new q(s,t?.material??new bt({color:r}));return this.applyDefaultObjectOptions(l,t),o instanceof Promise?o.then(c=>{l.geometry=ud(this,Hd,jg).call(this,e,c,t),t!=null&&t.onGeometry&&t.onGeometry(l)}):t!=null&&t.onGeometry&&t.onGeometry(l),l}static createOccluder(e){const t=new Me({colorWrite:!1,depthWrite:!0,side:Oi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let s;const o=t?.color||16777215;switch(e){case"Quad":case 0:{const r=new zs(1,1,1,1),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Quad"}break;case"Cube":case 1:{const r=new xa(1,1,1),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Cube"}break;case 10:case"RoundedCube":{const r=hM(1,1,1,.1,2),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="RoundedCube"}break;case"Sphere":case 2:{const r=new md(.5,16,16),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Sphere"}break;case"Cylinder":case 3:{const r=new Ev(.5,.5,1,32),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Cylinder"}break;case"ShaderBall":s=new go,s.name="ShaderBall",uM(s,t);break}return this.applyDefaultObjectOptions(s,t),s}static createSprite(e){const t=new AC({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const s=new IC(t);return this.applyDefaultObjectOptions(s,e),s}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x,t.position.y,t.position.z)),t!=null&&t.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z)),t!=null&&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,t.scale.y,t.scale.z)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t!=null&&t.parent&&t.parent.add(e)}}Hd=new WeakSet,jg=function(n,e,t){const s=t?.depth||.1;return new KP(n,{font:e,size:1,depth:s,height:s,bevelEnabled:t?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},Fs(xo,Hd);function hM(n,e,t,s,o){const r=new LC,l=1e-5,c=s-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,e-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(n-c*2,e-c*2,l,Math.PI/2,0,!0),r.absarc(n-c*2,l,l,0,-Math.PI/2,!0);const h=new jC(r,{bevelEnabled:!0,bevelSegments:o*2,steps:1,bevelSize:c,bevelThickness:s,curveSegments:o,UVGenerator:{generateTopUV:(d,u)=>{const p=[];for(let g=0;g<u.length;g+=3)p.push(new ie(u[g]/n,u[g+1]/e));return p},generateSideWallUV:(d,u,p,g,f,y)=>{const v=[];return v.push(new ie(u[p]/n,u[p+1]/e)),v.push(new ie(u[g]/n,u[g+1]/e)),v.push(new ie(u[f]/n,u[f+1]/e)),v.push(new ie(u[y]/n,u[y+1]/e)),v}}});return h.scale(1,1,1-s),h.center(),h.index||h.setIndex(Array.from({length:h.attributes.position.count},(d,u)=>u)),h.computeVertexNormals(),h}const Gd=new Map;function dM(n){let e="";switch(n){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Gd.has(e)){const o=Gd.get(e);if(o)return o}const t=new ZP,s=new Promise((o,r)=>{t.load(e,l=>{Gd.set(e,l),o(l)},void 0,r)});return Gd.set(e,s),s}let Dg=!1,Bg=null;function uM(n,e){if(Bg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",s=new Rn,o=Wm(null);s.setDRACOLoader(o.dracoLoader),s.setKTX2Loader(o.ktx2Loader),Dg=!0,Bg=s.loadAsync(t).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),P_())).finally(()=>{Dg=!1})}if(Dg){const t=P_();t.name="ShaderBall-Placeholder";const s=t.children[0];s?.type==="Mesh"&&C_(s,e),n.add(t)}Bg.then(t=>{n.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&n.remove(r)});const s=t.clone(),o=s.children[0];o?.type==="Mesh"&&(o.geometry.attributes.tangent||o.geometry.computeTangents(),C_(o,e)),n.add(s)})}function C_(n,e){var t;if(e?.color||e?.material||e?.texture){const s=e?.material??((t=n.material)==null?void 0:t.clone())??new bt;e.color&&"color"in s&&s.color instanceof re&&s.color.set(e.color),e!=null&&e.texture&&"map"in s&&(s.map=e.texture),n.material=s}}function P_(){return new go().add(xo.createPrimitive("Sphere",{material:new Me({transparent:!0,opacity:.1})}))}const Fg=class gC{constructor(e,t,s){a(this,"_session"),a(this,"_mode"),a(this,"_init"),a(this,"_renderer"),a(this,"_camera"),a(this,"_scene"),a(this,"onEnd",()=>{var o;(o=this._session)==null||o.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),a(this,"_lastTime",0),a(this,"onFrame",(o,r)=>{const l=o-this._lastTime;this.update(o,l),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=e,this._init=t,this._session=s,this._session.addEventListener("end",this.onEnd),this._renderer=new gr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(s),this._renderer.xr.enabled=!0,this._camera=new we,this._scene=new Si,this._scene.fog=new Av(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}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 s=await navigator.xr.requestSession(e,t);return s.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new gC(e,t,s),this._active):(s.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await $s(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}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}async onBeforeHandoff(){await $s(1e3),this._scene.clear()}setupScene(){this._scene.background=new re(0),this._scene.add(new Rm(5,10,1118481,1118481));const e=new Tm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new Tm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const s=new Em(16777215,1,100,1);s.position.set(0,2,0),s.castShadow=!1,s.distance=200,this._scene.add(s);const o=50;for(let r=0;r<100;r++){const l=new bt({color:2236962,metalness:1,roughness:.8});this.isAR&&(l.emissive=new re(Math.random(),Math.random(),Math.random()),l.emissiveIntensity=Math.random());const c=W.random(0,1)>.5?Sr.Sphere:Sr.Cube,h=xo.createPrimitive(c,{material:l});h.position.x=W.random(-o,o),h.position.y=W.random(-2,o),h.position.z=W.random(-o,o),h.rotation.x=W.random(0,Math.PI*2),h.rotation.y=W.random(0,Math.PI*2),h.rotation.z=W.random(0,Math.PI*2),h.scale.multiplyScalar(.5+Math.random()*10);const d=h.position.distanceTo(this._camera.position)-h.scale.x;d<1&&h.position.multiplyScalar(1+1/d),this._objects.push(h),this._scene.add(h)}}update(e,t){const s=e*4e-4;for(let o=0;o<this._objects.length;o++){const r=this._objects[o];r.position.y+=Math.sin(s+o*.5)*.005,r.rotateY(.002)}}};a(Fg,"_active",null),a(Fg,"_requestInFlight",!1);let qd=Fg;var hc;(n=>{const e=[];function t(){if(!(e!=null&&e.length))return!1;for(const r of e)r.exportAndOpen();return!0}n.exportAndOpen=t;function s(r){e.push(r)}n.registerExporter=s;function o(r){if(!e)return;const l=e.indexOf(r);l>=0&&e.splice(l,1)}n.unregisterExporter=o})(hc||(hc={}));const Je=C("debugwebxr"),O_=C("stats");let Ug=0;function pM(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}mM();async function mM(){var n;if(C("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;_r(!0);const s=await e;if(s){const o=oe.getDefaultSessionInit("immersive-vr");oe.setSession("immersive-vr",s,o,t.context)}else console.error("NeedleXRSession: 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}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{_r(!0),console.log("Received Session Granted..."),await $s(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,s=t?JSON.parse(t):null;let o=null;if(k_()&&(await qd.start(e||"immersive-vr",s||oe.getDefaultSessionInit("immersive-vr")),await yM(),o=await qd.handoff()),o)oe.setSession(o.mode,o.session,o.init,J.Current);else if(e&&t){console.log("Session Granted: Restore last session");const r=JSON.parse(t);oe.start(e,r).catch(l=>console.warn(l))}else oe.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function gM(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function fM(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const zg=new Set;pe.registerCallback(me.ContextCreationStart,async n=>{zg.add(n.context)}),pe.registerCallback(me.ContextCreated,async n=>{var e;zg.delete(n.context);const t=((e=n.context)==null?void 0:e.domElement.getAttribute("autostart"))||null;vM(t)});function k_(){return zg.size>0}function yM(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!k_()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}Q.isDesktop()&&B()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&oe.active&&oe.stop()});function vM(n){if(n)switch(n?.toLowerCase()){case"ar":Ln.registerWaitForInteraction(()=>{oe.start("ar")});break}}const li=class ba{constructor(e,t,s,o){a(this,"context"),a(this,"session"),a(this,"mode"),a(this,"controllers",[]),a(this,"_rigScale",1),a(this,"_lastRigScaleUpdate",-1),a(this,"_rigs",[]),a(this,"_viewerHitTestSource",null),a(this,"_defaultRig"),a(this,"_xr_scripts"),a(this,"_xr_update_scripts",[]),a(this,"_inactive_scripts",[]),a(this,"_controllerAdded"),a(this,"_controllerRemoved"),a(this,"_originalCameraWorldPosition"),a(this,"_originalCameraWorldRotation"),a(this,"_originalCameraWorldScale"),a(this,"_originalCameraParent"),a(this,"_mainCamera",null),a(this,"onRendererSessionSet",()=>{var c;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(c=this.context.mainCameraComponent)==null||c.applyClearFlags())}),a(this,"onInputSourceAdded",c=>{if(c.targetRayMode==="screen")return;let h=0;for(let u=0;u<this.session.inputSources.length;u++)if(this.session.inputSources[u]===c){h=u;break}if(this.controllers.find(u=>u.inputSource===c)){console.debug("Controller already exists for input source",h);return}else if(this._newControllers.find(u=>u.inputSource===c)){console.debug("Controller already registered for input source",h);return}const d=new Og(this,c,h);this._newControllers.push(d)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",c=>{var h,d,u;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),fM(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,wo(this.onBefore,Oe.LateUpdate);const p=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);p>=0&&this.context.pre_render_callbacks.splice(p,1);const g=this.context.post_render_callbacks.indexOf(this.onAfterRender);g>=0&&this.context.post_render_callbacks.splice(g,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var y,v;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(v=this.context.mainCameraComponent)==null||v.applyClippingPlane()}),o_({session:this});for(const y of ba._xrEndListeners)y({xr:this});const f=[...this.controllers];for(let y=0;y<f.length;y++)this.disconnectInputSource(f[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(h=y?.onLeaveXR)==null||h.call(y,{xr:this});(d=this.sync)==null||d.onExitXR(this),this.context.mainCamera&&((u=this._originalCameraParent)==null||u.add(this.context.mainCamera),this._originalCameraWorldPosition&<(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Yi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ta(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),_r(!1)}),a(this,"_didStart",!1),a(this,"onBefore",c=>{var h,d,u,p,g,f,y,v;const b=c.xrFrame;if(!b)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((h=this.rig)==null?void 0:h.isActive)==!1&&(Je&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(d=this._mainCamera)!=null&&d.gameObject&&((p=(u=this._mainCamera)==null?void 0:u.gameObject)==null?void 0:p.parent)!==this.rig.gameObject&&this.rig.gameObject.add((g=this._mainCamera)==null?void 0:g.gameObject),this.internalUpdateState(),this.applyCustomForward();const _={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let x=0;x<w.length;x++){const k=this.context.new_scripts_xr[x];if(!k||k.destroyed||((f=k.supportsXR)==null?void 0:f.call(k,this.mode))==!1){this.context.new_scripts_xr.splice(x,1);continue}if(!k.activeAndEnabled){this.context.new_scripts_xr.splice(x,1),this.markInactive(k);continue}if(this.addScript(k)){this.invokeCallback_EnterXR(k);for(const M of this.controllers)this.invokeCallback_ControllerAdded(k,M)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const x=ni(this.context.scene.children);if(x){const k=x.getSize(X());if(k.length()>0){const M=this._defaultRig.gameObject;M.position.set(x.min.x+k.x*.5,x.min.y,x.max.z+k.z*.5+1.5);const T=x.getCenter(X());T.y=M.position.y,M.lookAt(T)}}}n_({session:this}),xr();for(const x of ba._xrStartListeners)x(_);const w=[...this._xr_scripts];Je&&console.log("NeedleXRSession start, handle scripts:",w);for(const x of w){if(x.destroyed){this._script_to_remove.push(x);continue}if(!x.activeAndEnabled){this.markInactive(x);continue}this.invokeCallback_EnterXR(x);for(const k of this.controllers)this.invokeCallback_ControllerAdded(x,k)}}this.syncCameraCullingMask();for(const w of this.controllers)w.onUpdate(b);if(this._newControllers.length>0){const w=[...this._newControllers];this._newControllers.length=0;for(const x of w){if(!x.connected){console.warn("New controller is not connected",x);continue}this.controllers.push(x);for(const k of this._xr_scripts){if(k.destroyed){this._script_to_remove.push(k);continue}k.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(k,x)}}this.controllers.sort((x,k)=>x.index-k.index)}Je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(_r(!0),console.error("XRControllers are not added but inputSources are present"));for(const w of this._xr_update_scripts){if(w.destroyed===!0){this._script_to_remove.push(w);continue}if(w.activeAndEnabled===!1){this.markInactive(w);continue}w.onUpdateXR&&w.onUpdateXR(_)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const x of w)!x.destroyed&&this.running&&((y=x.onLeaveXR)==null||y.call(x,_)),this.removeScript(x)}(v=this.sync)==null||v.onUpdate(this),this.onRenderDebug()}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),Q.isDesktop()||!this._renderOnceOnDevice){const c=this.context.renderer;if(c.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const h=c.xr.enabled,d=c.getRenderTarget(),u=this.context.scene.background;c.xr.enabled=!1,c.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):c.render(this.context.scene,this.context.mainCamera),c.xr.enabled=h,c.setRenderTarget(d),this.context.scene.background=u}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new A().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new V),a(this,"_transformPosition",new S),a(this,"_transition");var r,l;gM(e,o.init),this.session=t,this.mode=e,this.context=s,(Je||C("console"))&&_r(!0),this._xr_scripts=[...o.scripts],this._xr_update_scripts=this._xr_scripts.filter(c=>typeof c.onUpdateXR=="function"),this._controllerAdded=o.controller_added,this._controllerRemoved=o.controller_removed,jn(this.onBefore,Oe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=o.init.optionalFeatures)!=null&&r.includes("hit-test")||(l=o.init.requiredFeatures)!=null&&l.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(c=>{var h,d;return(d=(h=t.requestHitTestSource)==null?void 0:h.call(t,{space:c}))==null?void 0:d.then(u=>this._viewerHitTestSource=u).catch(u=>console.error(u))}).catch(c=>console.error(c)),this.context.mainCamera&&(this._originalCameraWorldPosition=ee(this.context.mainCamera,new S),this._originalCameraWorldRotation=Se(this.context.mainCamera,new V),this._originalCameraWorldScale=Ge(this.context.mainCamera,new S),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Zk,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let c=0;c<t.inputSources.length;c++){const h=t.inputSources[c];if(!h.handedness){console.warn("Input source in xr session has no handedness - ignoring",c);continue}this.onInputSourceAdded(h)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",c=>{for(const h of c.removed)this.disconnectInputSource(h);for(const h of c.added)this.onInputSourceAdded(h)}),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):Je&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(e){return this._sync||(this._sync=new x_(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var e;return((e=this._activeSession)==null?void 0:e.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){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(e).catch(s=>(Je&&console.error(s),!1)))??Promise.resolve(!1)}static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(e,t,s){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(o=>ba.setSession(e,o,t,s)).catch(o=>{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 Q.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const s=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return Q.isVisionOS()||s.push("hand-tracking"),{optionalFeatures:s};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,s){var o,r,l,c;if(Q.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return hc.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(B()&&C("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await qd.start(e,t||ba.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Je||B())&&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(s||(s=J.Current),s||(s=pe.All[0]),!s)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(e+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(e),p=pM(s.domElement);p&&!Q.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((r=this.xrSystem)==null?void 0:r.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.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await qd.stop();const h=e=="immersive-ar"?s.scripts_immersive_ar:s.scripts_immersive_vr;Je?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,h):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const u of h)u.onBeforeXR&&u.onBeforeXR(e,t);for(const u of this._sessionRequestStartListeners)u({mode:e,init:t});Je&&De("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=(l=navigator.xr)==null?void 0:l.requestSession(e,t),this._currentSessionRequestMode=e;const d=await((c=this._currentSessionRequest)==null?void 0:c.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&be("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&be("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:e,init:t,newSession:d||null});return d?this.setSession(e,d,t,s):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,s,o){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=e=="immersive-ar"?o.scripts_immersive_ar:o.scripts_immersive_vr;return this._activeSession=new ba(e,t,o,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:s}),t.addEventListener("end",this.onEnd),Je?console.log(`%cStarted ${e} session`,"font-weight:bold;",r):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}get sync(){return ba._sync}get running(){return!this._ended&&this.session!=null}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}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")||B()&&Q.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!=null&&e.gameObject&&Tr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}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),s=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=s?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var e;const t=(e=this.context.mainCamera)==null?void 0:e.position;if(!t||!this.rig)return X(0,0,0);const s=X(t);return s.x*=-1,s.z*=-1,s.applyQuaternion(vs(this.rig.gameObject.quaternion)),s}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 s=1;s<this._rigs.length;s++){const o=this._rigs[s];if(o.isActive){if(Tr(o.gameObject)){this._rigs.splice(s,1),s--;continue}(!t||t.isActive===!1||o.priority!==void 0&&o.priority>t.priority)&&(t=o)}}if(e!==t){const s=this._rigs.indexOf(t);s>=0&&this._rigs.splice(s,1),this._rigs.unshift(t)}Je&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,s=this.frame.getHitTestResults(t);if(s.length>0){const o=s[0];return this.convertHitTestResult(o)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const s=this.frame.getHitTestResultsForTransientInput(t);for(const o of s)if(o.inputSource===e.inputSource)for(const r of o.results)return this.convertHitTestResult(r);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),s=t&&e.getPose(t);if(s){const o=X(s.transform.position),r=vs(s.transform.orientation),l=this.context.mainCamera;if(l?.parent!==this._cameraRenderParent&&o.applyMatrix4(La),l!=null&&l.parent){o.applyMatrix4(l.parent.matrixWorld),r.multiply(Zi);const c=Se(l.parent);c.premultiply(Zi),r.premultiply(c)}return{hit:e,position:o,quaternion:r}}return null}convertSpace(e){const t=X(e.position);t.applyMatrix4(La);const s=vs(e.orientation);return s.premultiply(Zi),{position:t,quaternion:s}}disconnectInputSource(e){const t=(s,o,r)=>{if(s.inputSource===e){Je&&console.log("Disconnecting controller",s.index),this.controllers.splice(r,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()}};for(let s=this.controllers.length-1;s>=0;s--){const o=this.controllers[s];t(o,this.controllers,s)}for(let s=this._newControllers.length-1;s>=0;s--){const o=this._newControllers[s];t(o,this._newControllers,s)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}onRenderDebug(){if(Je)for(const e of this.controllers)e.onRenderDebug();if((Je||O_)&&this.rig&&(Ug++,Ug>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const s=this.rig.gameObject.worldUp;e.add(s.multiplyScalar(2.5));let o="";if(o+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,o+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Je||O_)for(const r of this.controllers)o+=`
|
|
166
|
-
${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking} hts:${r.hasHitTestSource?"yes":"no"}`;Ug=0,G.DrawLabel(e,o,void 0,1/60*20)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Je&&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 s of this.controllers)this.invokeCallback_ControllerAdded(t,s)}}}removeScript(e,t=!0){Je&&console.log("Remove XRScript",e);const s=this._xr_scripts.indexOf(e);s>=0&&this._xr_scripts.splice(s,1);const o=this._xr_update_scripts.indexOf(e);if(o>=0&&this._xr_update_scripts.splice(o,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,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(){var e;const t=this.context.xrCamera,s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(t&&s!==void 0){for(const o of t.cameras)o.layers.mask=s;t.layers.mask=s}else if(t){for(const o of t.cameras)o.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(e,t,s){for(let o=t.length-1;o>=0;o--){const r=t[o];if(r)try{r({xr:this,controller:e,change:s})}catch(l){console.error(l)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const s=Ge(this.rig.gameObject);t*=s.x}this._camera instanceof we&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof we&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}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)}}get transition(){return this._transition||(this._transition=new S_),this._transition}fadeTransition(){return this._transition||(this._transition=new S_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof we&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};a(li,"_sync",null),a(li,"_currentSessionRequestMode",null),a(li,"_currentSessionRequest"),a(li,"_activeSession"),a(li,"_sessionRequestStartListeners",[]),a(li,"_sessionRequestEndListeners",[]),a(li,"_xrStartListeners",[]),a(li,"_xrEndListeners",[]),a(li,"_controllerAddedListeners",[]),a(li,"_controllerRemovedListeners",[]),a(li,"$_stop_request",Symbol()),a(li,"onEnd",()=>{Je&&console.log("XR Session ended"),li._activeSession=null});let oe=li;const Ng=C("debugwebxr");class M_{static tryFindAvatarObjects(e,t,s){if(s.head&&s.leftHand&&s.rightHand)return;const o=e.name.toLocaleLowerCase();!s.head&&o.includes("head")&&(Ng&&console.log("FOUND AVATAR HEAD",e.name),s.head=new ce("",t,e)),o.includes("hand")&&(!s.leftHand&&o.includes("left")&&(Ng&&console.log("FOUND AVATAR LEFT HAND",e.name),s.leftHand=new ce("",t,e)),!s.rightHand&&o.includes("right")&&(Ng&&console.log("FOUND AVATAR RIGHT HAND",e.name),s.rightHand=new ce("",t,e)));for(let r=0;r<e.children.length;r++){if(s.head&&s.leftHand&&s.rightHand)return;const l=e.children[r];this.tryFindAvatarObjects(l,t,s)}}}const Ft=new S,R_=new S,T_=new V,bM=C("debuggizmos"),Ss=8947848,Wg=32,Vg=class Ds{constructor(){}static isGizmo(e){return e[Hg]!==void 0}static setVisible(e){for(const t of Ee.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,s=.05,o=0,r,l,c){var h;if(!Ds.enabled)return null;r||(r=Ss);const d=((h=oe.active)==null?void 0:h.rigScale)??1,u=Ee.getTextLabel(o,t,s*d,r,l);return c instanceof A&&c.add(u),u.position.x=e.x,u.position.y=e.y,u.position.z=e.z,u}static DrawRay(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),Ft.set(t.x,t.y,t.z).multiplyScalar(999999999),c.setXYZ(1,e.x+Ft.x,e.y+Ft.y,e.z+Ft.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawDirection(e,t,s=Ss,o=0,r=!0,l=1){if(!Ds.enabled)return;const c=Ee.getLine(o),h=c.geometry.getAttribute("position");h.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Ft.set(0,0,-l),T_.set(t.x,t.y,t.z,t.w),Ft.applyQuaternion(T_)):(Ft.set(t.x,t.y,t.z),Ft.multiplyScalar(l)),h.setXYZ(1,e.x+Ft.x,e.y+Ft.y,e.z+Ft.z),h.needsUpdate=!0,c.material.color.set(s),c.material.depthTest=r,c.material.depthWrite=!1}static DrawLine(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),c.setXYZ(1,t.x,t.y,t.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawCircle(e,t,s,o=Ss,r=0,l=!0){if(!Ds.enabled)return;const c=Ee.getCircle(r);c.position.set(e.x,e.y,e.z),c.scale.set(s,s,s),c.quaternion.setFromUnitVectors(this._up,Ft.set(t.x,t.y,t.z).normalize()),c.material.color.set(o),c.material.depthTest=l,c.material.depthWrite=!1,c.material.fog=!1}static DrawWireSphere(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getSphere(t,o,!0);vr(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawSphere(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getSphere(t,o,!1);vr(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawWireBox(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getBox(o);l.position.set(e.x,e.y,e.z),l.scale.set(t.x,t.y,t.z),l.material.color.set(s),l.material.depthTest=r,l.material.wireframe=!0,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireBox3(e,t=Ss,s=0,o=!0){if(!Ds.enabled)return;const r=Ee.getBox(s);r.position.copy(e.getCenter(Ft)),r.scale.copy(e.getSize(Ft)),r.material.color.set(t),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,s=Ss,o=0,r=!0,l=!1){if(!Ds.enabled)return;const c=Ee.getArrowHead(o);c.position.set(t.x,t.y,t.z),c.quaternion.setFromUnitVectors(this._up.set(0,1,0),Ft.set(t.x,t.y,t.z).sub(R_.set(e.x,e.y,e.z)).normalize());const h=Ft.set(t.x,t.y,t.z).sub(R_.set(e.x,e.y,e.z)).length()*.1;c.scale.set(h,h,h),c.material.color.set(s),c.material.depthTest=r,c.material.wireframe=l,this.DrawLine(e,t,s,o,r)}static DrawWireMesh(e){const t=Ee.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Ss),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};a(Vg,"enabled",!0),a(Vg,"_up",new S(0,1,0));let G=Vg;const _M=new xa(1,1,1);function $g(n=null){const e=new re(n??14540253),t=new DC(_M);return new Iv(t,new Lv({color:e}))}const Hg=Symbol("GizmoCache");class Ee{static ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(e,t,s,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),bM&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre",offset:.05*s};if(l)l.set(h);else{l=new tb(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(J.Current,l,e,this.textLabelCache),l}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new xa(1,1,1);t=new q(s)}return this.registerTimedObject(J.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Hl;let s=t.geometry.getAttribute("position");s||(s=new _t(new Float32Array(6),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Hl;let s=t.geometry.getAttribute("position");if(!s){s=new _t(new Float32Array(Wg*3),3),t.geometry.setAttribute("position",s);const o=X(0,1,0),r=X(0,0,1),l=X(r);l.cross(o).normalize();const c=X(l),h=Math.PI*2/(Wg-1);for(let d=0;d<Wg+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);s.setXYZ(d,p.x,p.y,p.z)}}}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.circlesCache),t}static getSphere(e,t,s){let o=this.spheresCache.pop();return o||(o=new q(new md(1,8,8))),o.scale.set(e,e,e),o.material.wireframe=s,this.registerTimedObject(J.Current,o,t,this.spheresCache),o}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new q(new Ev(0,.5,1,8))),this.registerTimedObject(J.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new q,t.material=new Me),this.registerTimedObject(J.Current,t,e,this.mesh),t}static registerTimedObject(e,t,s,o){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(e),l=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const c=e.pre_render_callbacks.indexOf(r);c>=0&&e.pre_render_callbacks.splice(c,1),e.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,c),e.pre_render_callbacks.push(c)}if(l){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==l){const c=e.post_render_callbacks.indexOf(l);c>=0&&e.post_render_callbacks.splice(c,1),e.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,c),e.post_render_callbacks.push(c)}t.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),t.renderOrder=999999,t[Hg]=o,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(J.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let s=0;s<t.length;s++){const o=t[s];if(e.mainCamera&&o instanceof Re.MeshUIBaseElement){if(Tr(o))continue;const r=e.isInVR,l=!1,c=!r;Zl(o,e.mainCamera,l,c)}}}static onPostRender(e,t,s){const o=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const l=t[r];o>=s[r]-1e-6&&(t.splice(r,1),s.splice(r,1),l.removeFromParent(),Tr(l)!=!0&&l[Hg].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Qt=C("debugphysics"),E_=new po;class Dn{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast"),a(this,"allowSlowRaycastFallback",!0)}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ie),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){E_.set(e),this.layerMask=E_}setMask(e){this.layerMask||(this.layerMask=new po);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}a(Dn,"AllLayers",4294967295);class Gg{constructor(e,t,s){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=e,this.distance=t,this.point=s}}const A_=class bv{constructor(e){a(this,"context"),a(this,"engine"),a(this,"raycaster",new gd),a(this,"defaultRaycastOptions",new Dn),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new po),a(this,"sphere",new fd),a(this,"tempBoundingBox",new Ci),this.context=e}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:s,solid:o}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:s,solid:o}))??null}sphereOverlapPhysics(e,t){var s;return((s=this.context.physics.engine)==null?void 0:s.sphereOverlap(e,t))??null}sphereOverlap(e,t,s=!0,o=!1,r=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const l=this.sphereMask;l.enableAll(),l.disable(2);for(const c of this.context.scene.children)this.intersectSphere(c,e,t,l,this.sphereResults,s,o,r);return this.sphereResults.sort((c,h)=>c.distance-h.distance)}raycastFromRay(e,t=null){const s=t??this.defaultRaycastOptions;s.ray=e;const o=this.raycast(s);return s===this.defaultRaycastOptions&&(s.ray=void 0),o}raycast(e=null){Qt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,s=e.raycaster??this.raycaster;if(s.near=e.minDistance??0,s.far=e.maxDistance??1/0,s.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),s.params.Line={threshold:e.lineThreshold},e.ray)s.ray.copy(e.ray);else{const c=e.cam??this.context.mainCamera;if(!c)return Qt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const h=this.context.xrCamera;this.context.isInXR&&h instanceof BC&&h.cameras.length>0?s.setFromCamera(t,h.cameras[0]):s.setFromCamera(t,c)}let o=e.targets;o||(o=this.targetBuffer,o.length=1,o[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof po?s.layers.mask=e.layerMask.mask:s.layers.mask=e.layerMask:(s.layers.enableAll(),s.layers.disable(2)),Qt&&console.time("raycast"),r.length=0,bv._raycasting++,this.intersect(this.raycaster,o,r,e),r.sort((c,h)=>c.distance-h.distance);const l=e.ignore;return l!==void 0&&l.length>0&&(r=r.filter(c=>!l.includes(c.object))),bv._raycasting--,Qt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),r}intersect(e,t,s,o){var r,l,c;for(const h of t){if(!h||h.visible===!1||G.isGizmo(h)||o.lineThreshold!==void 0&&o.lineThreshold<0&&h instanceof Hl)continue;let d=!0;const u=h,p=u.geometry;if(o.testObject){const g=(r=o.testObject)==null?void 0:r.call(o,h);if(g===!1)continue;g==="continue in children"&&(d=!1)}if(d&&(p&&I_(p)||(d=!1)),d){const g=$v(h);g&&(u.geometry=g);const f=s.length;let y=!0;if(o.precise===!1&&(y=!1),y||(y=((c=(l=p.getAttribute("position"))==null?void 0:l.array)==null?void 0:c.length)<64),u instanceof ka&&(y=!1),!y&&xM(u,e,s)||(o.useAcceleratedRaycast!==!1?Qd.runMeshBVHRaycast(e,u,s,this.context,o):e.intersectObject(u,!1,s)),Qt&&s.length!=f){const v=s[s.length-1],b=g?8969557:7798784;G.DrawWireSphere(v.point,.1,b,1,!1),G.DrawWireMesh({mesh:h,depthTest:!1,duration:.2,color:b})}u.geometry=p}o.recursive!==!1&&this.intersect(e,h.children,s,o)}return s}intersectSphere(e,t,s,o,r,l,c,h){let d=e&&e.isMesh&&e.layers.test(o)&&!G.isGizmo(e);d&&(d=e.visible),d&&(d=!(e instanceof Hl)),d&&(d=!(e instanceof ka));const u=e,p=u.geometry;if(d&&h){const g=h(e);if(g===!1)return;g==="continue in children"&&(d=!1)}if(p&&I_(p)||(d=!1),d){if(c){const g=this.sphere;g.center.copy(t),g.radius=s;const f=r.length;if(Qd.runMeshBVHRaycast(this.sphere,u,r,this.context,{}),f!=r.length&&!l)return}else if(p.boundingBox||p.computeBoundingBox(),p.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const g=this.tempBoundingBox.copy(p.boundingBox).applyMatrix4(u.matrixWorld),f=this.sphere;if(f.center.copy(t),f.radius=s,f.intersectsBox(g)){const y=ee(e),v=y.distanceTo(f.center),b=new Gg(e,v,y);if(r.push(b),!l)return}}}if(e.children)for(const g of e.children){const f=r.length;if(this.intersectSphere(g,t,s,o,r,l,c,h),f!=r.length&&!l)return}}};a(A_,"_raycasting",0);let qg=A_;function I_(n){return!(n.index&&n.index.array.length<3)}const Cr=new fd,Xd=new fr,wM=new Tv;function xM(n,e,t){const s=n._computeIntersections;if(!s)return!1;let o=n["_computeIntersections:Needle"];return o||(o=n["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof ka){Xd.setFromNormalAndCoplanarPoint(X(0,1,0),X(0,-h.position.y,0)),Xd.applyMatrix4(h.matrixWorld,wM);const p=r.ray.intersectPlane(Xd,X());if(p){Cr.copy(d),Cr.applyMatrix4(h.matrixWorld);const g=X(p).sub(r.ray.origin).length(),f=Cr.radius*.5;g<f&&l.push({distance:g,point:p,object:h,normal:Xd.normal.clone()})}return}Cr.copy(d),Cr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(Cr,X());if(u){const p=X(u).sub(r.ray.origin),g=p.length();if(g>Cr.radius){const f=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:f})}}}}),n._computeIntersections=o,e.intersectObject(n,!1,t),n._computeIntersections=s,!0}var Qd;(n=>{function e(_,w,x,k,M){var T,D,z;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const U=w.geometry;if(w!=null&&w.isSkinnedMesh){const E=w,$=E.bvhNeedsUpdate;if(!E.staticGenerator)c(),r&&(E.staticGenerator=new r(w),E.staticGenerator.applyWorldTransforms=!1,E.staticGeometry=E.staticGenerator.generate(),U.boundsTree=l?.call(E.staticGeometry),E.staticGeometryLastUpdate=performance.now()+Math.random()*200,E.bvhNeedsUpdate=!0);else if(U.boundsTree&&(E.autoUpdateMeshBvhInterval!==void 0&&E.autoUpdateMeshBvhInterval>=0||$===!0)){const H=performance.now(),F=H-E.staticGeometryLastUpdate,I=E.autoUpdateMeshBvhInterval??100;($||F>I)&&(Qt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${F.toFixed(2)}ms`),E.bvhNeedsUpdate=!1,E.staticGeometryLastUpdate=H,(T=E.staticGenerator)==null||T.generate(E.staticGeometry),U.boundsTree.refit())}}else if(!U.boundsTree){d||b();let E=!0;if((k.xr||U[f]===!1||(D=U.getAttribute("position"))!=null&&D.isInterleavedBufferAttribute||U.index&&(z=U.index)!=null&&z.isInterleavedBufferAttribute)&&(E=!1),E&&p){if(U[g]===void 0){let $=null;if(v.length>0){const H=v.shift();H&&!H.running&&($=H)}if(!$&&y.length<3&&($=new p,y.push($)),$!=null&&!$.running){const H=w.name;Qt&&console.log("<<<< worker start",H,$),U[g]="queued",performance.mark("bvh.create.start");const F=U.clone();try{$.generate(F).then(I=>{U[g]="done",U.boundsTree=I}).catch(I=>{U[g]="failed - "+I?.message,U[f]=!1,Qt&&console.error("Failed to generate mesh bvh on worker",I)}).finally(()=>{Qt&&console.log(">>>>> worker done",H,{hasBoundsTre:U.boundsTree!=null}),v.push($),F.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(I){console.error("Failed to generate mesh bvh on worker",I)}}else Qt&&console.warn("No worker available")}}else(!u||!E)&&(c(),o&&(performance.mark("bvh.create.start"),U.boundsTree=new o(U),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof gd){const E=_,$=w.raycast;if(U.boundsTree)c(),s&&(w.acceleratedRaycast||(w.acceleratedRaycast=s.bind(w),Qt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Qt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:U[g],hasAcceleratedRaycast:s!=null}),M.allowSlowRaycastFallback===!1)return Qt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const H=E.firstHitOnly;return E.firstHitOnly=!1,E.intersectObject(w,!1,x),E.firstHitOnly=H,w.raycast=$,!0}else if(_ instanceof fd){const E=U.boundsTree;if(E){const $=_;if(h.copy(w.matrixWorld).invert(),$.applyMatrix4(h),E.intersectsSphere($)){const H=ee(w),F=H.distanceTo($.center),I=new Gg(w,F,H);x.push(I)}}return!0}return!1}n.runMeshBVHRaycast=e;let t=!1,s=null,o=null,r=null,l=null;function c(){t||(t=!0,import("./vendor-BlSxe9JJ.min.js").then(_=>_.index$1).then(_=>{s=_.acceleratedRaycast,o=_.MeshBVH,r=_.StaticGeometryGenerator,l=_.computeBoundsTree}).catch(_=>{(Qt||B())&&console.error("Failed to load BVH library...",_.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>YL).then(_=>{p=_.GenerateMeshBVHWorker}).catch(_=>{(Qt||B())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Qd||(Qd={}));const L_=Symbol("gltf-loader-internal-usage-tracker"),SM=C("debugusers"),j_=class ym{constructor(e){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ym._loadingProcesses>0}beforeRoot(){ym._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(s,o){const r=t.call(this,s,o);return r.then(l=>(l&&(e._loadedObjects.add(l),l[L_]=e._loadingId),l)),r},null}afterRoot(e){ym._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[L_],t instanceof A&&(t.parent||t instanceof q&&setTimeout(()=>{SM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};a(j_,"_loadingProcesses",0);let D_=j_;class B_{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const s=(t=e?.reason)==null?void 0:t.path;if(s){const o=s[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
166
|
+
${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking} hts:${r.hasHitTestSource?"yes":"no"}`;Ug=0,G.DrawLabel(e,o,void 0,1/60*20)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Je&&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 s of this.controllers)this.invokeCallback_ControllerAdded(t,s)}}}removeScript(e,t=!0){Je&&console.log("Remove XRScript",e);const s=this._xr_scripts.indexOf(e);s>=0&&this._xr_scripts.splice(s,1);const o=this._xr_update_scripts.indexOf(e);if(o>=0&&this._xr_update_scripts.splice(o,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,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(){var e;const t=this.context.xrCamera,s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(t&&s!==void 0){for(const o of t.cameras)o.layers.mask=s;t.layers.mask=s}else if(t){for(const o of t.cameras)o.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(e,t,s){for(let o=t.length-1;o>=0;o--){const r=t[o];if(r)try{r({xr:this,controller:e,change:s})}catch(l){console.error(l)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const s=Ge(this.rig.gameObject);t*=s.x}this._camera instanceof we&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof we&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}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)}}get transition(){return this._transition||(this._transition=new S_),this._transition}fadeTransition(){return this._transition||(this._transition=new S_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof we&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};a(li,"_sync",null),a(li,"_currentSessionRequestMode",null),a(li,"_currentSessionRequest"),a(li,"_activeSession"),a(li,"_sessionRequestStartListeners",[]),a(li,"_sessionRequestEndListeners",[]),a(li,"_xrStartListeners",[]),a(li,"_xrEndListeners",[]),a(li,"_controllerAddedListeners",[]),a(li,"_controllerRemovedListeners",[]),a(li,"$_stop_request",Symbol()),a(li,"onEnd",()=>{Je&&console.log("XR Session ended"),li._activeSession=null});let oe=li;const Ng=C("debugwebxr");class M_{static tryFindAvatarObjects(e,t,s){if(s.head&&s.leftHand&&s.rightHand)return;const o=e.name.toLocaleLowerCase();!s.head&&o.includes("head")&&(Ng&&console.log("FOUND AVATAR HEAD",e.name),s.head=new ce("",t,e)),o.includes("hand")&&(!s.leftHand&&o.includes("left")&&(Ng&&console.log("FOUND AVATAR LEFT HAND",e.name),s.leftHand=new ce("",t,e)),!s.rightHand&&o.includes("right")&&(Ng&&console.log("FOUND AVATAR RIGHT HAND",e.name),s.rightHand=new ce("",t,e)));for(let r=0;r<e.children.length;r++){if(s.head&&s.leftHand&&s.rightHand)return;const l=e.children[r];this.tryFindAvatarObjects(l,t,s)}}}const Bt=new S,R_=new S,T_=new V,bM=C("debuggizmos"),Ss=8947848,Wg=32,Vg=class Ds{constructor(){}static isGizmo(e){return e[Hg]!==void 0}static setVisible(e){for(const t of Ee.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,s=.05,o=0,r,l,c){var h;if(!Ds.enabled)return null;r||(r=Ss);const d=((h=oe.active)==null?void 0:h.rigScale)??1,u=Ee.getTextLabel(o,t,s*d,r,l);return c instanceof A&&c.add(u),u.position.x=e.x,u.position.y=e.y,u.position.z=e.z,u}static DrawRay(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),c.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawDirection(e,t,s=Ss,o=0,r=!0,l=1){if(!Ds.enabled)return;const c=Ee.getLine(o),h=c.geometry.getAttribute("position");h.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-l),T_.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(T_)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(l)),h.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),h.needsUpdate=!0,c.material.color.set(s),c.material.depthTest=r,c.material.depthWrite=!1}static DrawLine(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),c.setXYZ(1,t.x,t.y,t.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawCircle(e,t,s,o=Ss,r=0,l=!0){if(!Ds.enabled)return;const c=Ee.getCircle(r);c.position.set(e.x,e.y,e.z),c.scale.set(s,s,s),c.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),c.material.color.set(o),c.material.depthTest=l,c.material.depthWrite=!1,c.material.fog=!1}static DrawWireSphere(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getSphere(t,o,!0);vr(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawSphere(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getSphere(t,o,!1);vr(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawWireBox(e,t,s=Ss,o=0,r=!0){if(!Ds.enabled)return;const l=Ee.getBox(o);l.position.set(e.x,e.y,e.z),l.scale.set(t.x,t.y,t.z),l.material.color.set(s),l.material.depthTest=r,l.material.wireframe=!0,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireBox3(e,t=Ss,s=0,o=!0){if(!Ds.enabled)return;const r=Ee.getBox(s);r.position.copy(e.getCenter(Bt)),r.scale.copy(e.getSize(Bt)),r.material.color.set(t),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,s=Ss,o=0,r=!0,l=!1){if(!Ds.enabled)return;const c=Ee.getArrowHead(o);c.position.set(t.x,t.y,t.z),c.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(R_.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(R_.set(e.x,e.y,e.z)).length()*.1;c.scale.set(h,h,h),c.material.color.set(s),c.material.depthTest=r,c.material.wireframe=l,this.DrawLine(e,t,s,o,r)}static DrawWireMesh(e){const t=Ee.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Ss),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};a(Vg,"enabled",!0),a(Vg,"_up",new S(0,1,0));let G=Vg;const _M=new xa(1,1,1);function $g(n=null){const e=new re(n??14540253),t=new DC(_M);return new Iv(t,new Lv({color:e}))}const Hg=Symbol("GizmoCache");class Ee{static ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(e,t,s,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),bM&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre",offset:.05*s};if(l)l.set(h);else{l=new tb(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(J.Current,l,e,this.textLabelCache),l}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new xa(1,1,1);t=new q(s)}return this.registerTimedObject(J.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Hl;let s=t.geometry.getAttribute("position");s||(s=new _t(new Float32Array(6),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Hl;let s=t.geometry.getAttribute("position");if(!s){s=new _t(new Float32Array(Wg*3),3),t.geometry.setAttribute("position",s);const o=X(0,1,0),r=X(0,0,1),l=X(r);l.cross(o).normalize();const c=X(l),h=Math.PI*2/(Wg-1);for(let d=0;d<Wg+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);s.setXYZ(d,p.x,p.y,p.z)}}}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.circlesCache),t}static getSphere(e,t,s){let o=this.spheresCache.pop();return o||(o=new q(new md(1,8,8))),o.scale.set(e,e,e),o.material.wireframe=s,this.registerTimedObject(J.Current,o,t,this.spheresCache),o}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new q(new Ev(0,.5,1,8))),this.registerTimedObject(J.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new q,t.material=new Me),this.registerTimedObject(J.Current,t,e,this.mesh),t}static registerTimedObject(e,t,s,o){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(e),l=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const c=e.pre_render_callbacks.indexOf(r);c>=0&&e.pre_render_callbacks.splice(c,1),e.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,c),e.pre_render_callbacks.push(c)}if(l){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==l){const c=e.post_render_callbacks.indexOf(l);c>=0&&e.post_render_callbacks.splice(c,1),e.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,c),e.post_render_callbacks.push(c)}t.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),t.renderOrder=999999,t[Hg]=o,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(J.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let s=0;s<t.length;s++){const o=t[s];if(e.mainCamera&&o instanceof Re.MeshUIBaseElement){if(Tr(o))continue;const r=e.isInVR,l=!1,c=!r;Zl(o,e.mainCamera,l,c)}}}static onPostRender(e,t,s){const o=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const l=t[r];o>=s[r]-1e-6&&(t.splice(r,1),s.splice(r,1),l.removeFromParent(),Tr(l)!=!0&&l[Hg].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Qt=C("debugphysics"),E_=new po;class Dn{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast"),a(this,"allowSlowRaycastFallback",!0)}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ie),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){E_.set(e),this.layerMask=E_}setMask(e){this.layerMask||(this.layerMask=new po);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}a(Dn,"AllLayers",4294967295);class Gg{constructor(e,t,s){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=e,this.distance=t,this.point=s}}const A_=class bv{constructor(e){a(this,"context"),a(this,"engine"),a(this,"raycaster",new gd),a(this,"defaultRaycastOptions",new Dn),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new po),a(this,"sphere",new fd),a(this,"tempBoundingBox",new Ci),this.context=e}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:s,solid:o}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:s,solid:o}))??null}sphereOverlapPhysics(e,t){var s;return((s=this.context.physics.engine)==null?void 0:s.sphereOverlap(e,t))??null}sphereOverlap(e,t,s=!0,o=!1,r=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const l=this.sphereMask;l.enableAll(),l.disable(2);for(const c of this.context.scene.children)this.intersectSphere(c,e,t,l,this.sphereResults,s,o,r);return this.sphereResults.sort((c,h)=>c.distance-h.distance)}raycastFromRay(e,t=null){const s=t??this.defaultRaycastOptions;s.ray=e;const o=this.raycast(s);return s===this.defaultRaycastOptions&&(s.ray=void 0),o}raycast(e=null){Qt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,s=e.raycaster??this.raycaster;if(s.near=e.minDistance??0,s.far=e.maxDistance??1/0,s.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),s.params.Line={threshold:e.lineThreshold},e.ray)s.ray.copy(e.ray);else{const c=e.cam??this.context.mainCamera;if(!c)return Qt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const h=this.context.xrCamera;this.context.isInXR&&h instanceof BC&&h.cameras.length>0?s.setFromCamera(t,h.cameras[0]):s.setFromCamera(t,c)}let o=e.targets;o||(o=this.targetBuffer,o.length=1,o[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof po?s.layers.mask=e.layerMask.mask:s.layers.mask=e.layerMask:(s.layers.enableAll(),s.layers.disable(2)),Qt&&console.time("raycast"),r.length=0,bv._raycasting++,this.intersect(this.raycaster,o,r,e),r.sort((c,h)=>c.distance-h.distance);const l=e.ignore;return l!==void 0&&l.length>0&&(r=r.filter(c=>!l.includes(c.object))),bv._raycasting--,Qt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),r}intersect(e,t,s,o){var r,l,c;for(const h of t){if(!h||h.visible===!1||G.isGizmo(h)||o.lineThreshold!==void 0&&o.lineThreshold<0&&h instanceof Hl)continue;let d=!0;const u=h,p=u.geometry;if(o.testObject){const g=(r=o.testObject)==null?void 0:r.call(o,h);if(g===!1)continue;g==="continue in children"&&(d=!1)}if(d&&(p&&I_(p)||(d=!1)),d){const g=$v(h);g&&(u.geometry=g);const f=s.length;let y=!0;if(o.precise===!1&&(y=!1),y||(y=((c=(l=p.getAttribute("position"))==null?void 0:l.array)==null?void 0:c.length)<64),u instanceof ka&&(y=!1),!y&&xM(u,e,s)||(o.useAcceleratedRaycast!==!1?Qd.runMeshBVHRaycast(e,u,s,this.context,o):e.intersectObject(u,!1,s)),Qt&&s.length!=f){const v=s[s.length-1],b=g?8969557:7798784;G.DrawWireSphere(v.point,.1,b,1,!1),G.DrawWireMesh({mesh:h,depthTest:!1,duration:.2,color:b})}u.geometry=p}o.recursive!==!1&&this.intersect(e,h.children,s,o)}return s}intersectSphere(e,t,s,o,r,l,c,h){let d=e&&e.isMesh&&e.layers.test(o)&&!G.isGizmo(e);d&&(d=e.visible),d&&(d=!(e instanceof Hl)),d&&(d=!(e instanceof ka));const u=e,p=u.geometry;if(d&&h){const g=h(e);if(g===!1)return;g==="continue in children"&&(d=!1)}if(p&&I_(p)||(d=!1),d){if(c){const g=this.sphere;g.center.copy(t),g.radius=s;const f=r.length;if(Qd.runMeshBVHRaycast(this.sphere,u,r,this.context,{}),f!=r.length&&!l)return}else if(p.boundingBox||p.computeBoundingBox(),p.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const g=this.tempBoundingBox.copy(p.boundingBox).applyMatrix4(u.matrixWorld),f=this.sphere;if(f.center.copy(t),f.radius=s,f.intersectsBox(g)){const y=ee(e),v=y.distanceTo(f.center),b=new Gg(e,v,y);if(r.push(b),!l)return}}}if(e.children)for(const g of e.children){const f=r.length;if(this.intersectSphere(g,t,s,o,r,l,c,h),f!=r.length&&!l)return}}};a(A_,"_raycasting",0);let qg=A_;function I_(n){return!(n.index&&n.index.array.length<3)}const Cr=new fd,Xd=new fr,wM=new Tv;function xM(n,e,t){const s=n._computeIntersections;if(!s)return!1;let o=n["_computeIntersections:Needle"];return o||(o=n["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof ka){Xd.setFromNormalAndCoplanarPoint(X(0,1,0),X(0,-h.position.y,0)),Xd.applyMatrix4(h.matrixWorld,wM);const p=r.ray.intersectPlane(Xd,X());if(p){Cr.copy(d),Cr.applyMatrix4(h.matrixWorld);const g=X(p).sub(r.ray.origin).length(),f=Cr.radius*.5;g<f&&l.push({distance:g,point:p,object:h,normal:Xd.normal.clone()})}return}Cr.copy(d),Cr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(Cr,X());if(u){const p=X(u).sub(r.ray.origin),g=p.length();if(g>Cr.radius){const f=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:f})}}}}),n._computeIntersections=o,e.intersectObject(n,!1,t),n._computeIntersections=s,!0}var Qd;(n=>{function e(_,w,x,k,M){var T,D,z;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const U=w.geometry;if(w!=null&&w.isSkinnedMesh){const E=w,$=E.bvhNeedsUpdate;if(!E.staticGenerator)c(),r&&(E.staticGenerator=new r(w),E.staticGenerator.applyWorldTransforms=!1,E.staticGeometry=E.staticGenerator.generate(),U.boundsTree=l?.call(E.staticGeometry),E.staticGeometryLastUpdate=performance.now()+Math.random()*200,E.bvhNeedsUpdate=!0);else if(U.boundsTree&&(E.autoUpdateMeshBvhInterval!==void 0&&E.autoUpdateMeshBvhInterval>=0||$===!0)){const H=performance.now(),F=H-E.staticGeometryLastUpdate,I=E.autoUpdateMeshBvhInterval??100;($||F>I)&&(Qt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${F.toFixed(2)}ms`),E.bvhNeedsUpdate=!1,E.staticGeometryLastUpdate=H,(T=E.staticGenerator)==null||T.generate(E.staticGeometry),U.boundsTree.refit())}}else if(!U.boundsTree){d||b();let E=!0;if((k.xr||U[f]===!1||(D=U.getAttribute("position"))!=null&&D.isInterleavedBufferAttribute||U.index&&(z=U.index)!=null&&z.isInterleavedBufferAttribute)&&(E=!1),E&&p){if(U[g]===void 0){let $=null;if(v.length>0){const H=v.shift();H&&!H.running&&($=H)}if(!$&&y.length<3&&($=new p,y.push($)),$!=null&&!$.running){const H=w.name;Qt&&console.log("<<<< worker start",H,$),U[g]="queued",performance.mark("bvh.create.start");const F=U.clone();try{$.generate(F).then(I=>{U[g]="done",U.boundsTree=I}).catch(I=>{U[g]="failed - "+I?.message,U[f]=!1,Qt&&console.error("Failed to generate mesh bvh on worker",I)}).finally(()=>{Qt&&console.log(">>>>> worker done",H,{hasBoundsTre:U.boundsTree!=null}),v.push($),F.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(I){console.error("Failed to generate mesh bvh on worker",I)}}else Qt&&console.warn("No worker available")}}else(!u||!E)&&(c(),o&&(performance.mark("bvh.create.start"),U.boundsTree=new o(U),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof gd){const E=_,$=w.raycast;if(U.boundsTree)c(),s&&(w.acceleratedRaycast||(w.acceleratedRaycast=s.bind(w),Qt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Qt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:U[g],hasAcceleratedRaycast:s!=null}),M.allowSlowRaycastFallback===!1)return Qt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const H=E.firstHitOnly;return E.firstHitOnly=!1,E.intersectObject(w,!1,x),E.firstHitOnly=H,w.raycast=$,!0}else if(_ instanceof fd){const E=U.boundsTree;if(E){const $=_;if(h.copy(w.matrixWorld).invert(),$.applyMatrix4(h),E.intersectsSphere($)){const H=ee(w),F=H.distanceTo($.center),I=new Gg(w,F,H);x.push(I)}}return!0}return!1}n.runMeshBVHRaycast=e;let t=!1,s=null,o=null,r=null,l=null;function c(){t||(t=!0,import("./vendor-BlSxe9JJ.min.js").then(_=>_.index$1).then(_=>{s=_.acceleratedRaycast,o=_.MeshBVH,r=_.StaticGeometryGenerator,l=_.computeBoundsTree}).catch(_=>{(Qt||B())&&console.error("Failed to load BVH library...",_.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>YL).then(_=>{p=_.GenerateMeshBVHWorker}).catch(_=>{(Qt||B())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Qd||(Qd={}));const L_=Symbol("gltf-loader-internal-usage-tracker"),SM=C("debugusers"),j_=class ym{constructor(e){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ym._loadingProcesses>0}beforeRoot(){ym._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(s,o){const r=t.call(this,s,o);return r.then(l=>(l&&(e._loadedObjects.add(l),l[L_]=e._loadingId),l)),r},null}afterRoot(e){ym._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[L_],t instanceof A&&(t.parent||t instanceof q&&setTimeout(()=>{SM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};a(j_,"_loadingProcesses",0);let D_=j_;class B_{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const s=(t=e?.reason)==null?void 0:t.path;if(s){const o=s[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
167
167
|
`+o.src),e.preventDefault())}})}}const Yd=C("trackresources");function F_(){return Yd==="dispose"}let Pr=!0;Yd===0&&(Pr=!1);function CM(n){Pr=n}function U_(){return Pr}const z_=Symbol("disposable");function Xg(n,e){n&&(n[z_]=e,Or&&console.warn("Set disposable",e,n))}const N_=Symbol("disposed");function PM(n){return n[N_]===!0}function Te(n){var e;if(n){if(n[z_]===!1){Or&&console.warn("Object is marked as not disposable",n);return}if(typeof n=="object"&&(n[N_]=!0),n instanceof Si)Te(n.environment),Te(n.background),Te(n.customDepthMaterial),Te(n.customDistanceMaterial);else if(n instanceof Pn)Te(n.geometry),Te(n.material),Te(n.skeleton),Te(n.bindMatrix),Te(n.bindMatrixInverse),Te(n.customDepthMaterial),Te(n.customDistanceMaterial),n.geometry=null,n.material=null,n.visible=!1;else if(n instanceof q)Te(n.geometry),Te(n.material),Te(n.customDepthMaterial),Te(n.customDistanceMaterial),n.geometry=null,n.material=null,n.visible=!1;else if(n instanceof Ws){Fa(n);for(const t of Object.keys(n.attributes)){const s=n.attributes[t];Te(s)}}else if(n instanceof _t||n instanceof jv)Or&&console.warn("BufferAttribute dispose not supported",n.count);else if(n instanceof Array)for(const t of n)t instanceof Pe&&Te(t);else if(n instanceof Pe){Fa(n);for(const s of Object.keys(n)){const o=n[s];o instanceof je&&(Te(o),n[s]=null)}const t=n.uniforms;if(t)for(const s of Object.keys(t)){const o=t[s];o instanceof je?(Te(o),t[s]=null):o instanceof Qi&&(Te(o.value),o.value=null)}}else n instanceof je?(Fa(n),Fa(n.source),((e=n.source)==null?void 0:e.data)instanceof ImageBitmap&&Fa(n.source.data)):n instanceof FC?(Fa(n.boneTexture),n.boneTexture=null):n instanceof UC||!(n instanceof A)&&Or&&console.warn("Unknown object type",n)}}function Fa(n){n&&((Or||F_()||Yd)&&console.warn("\u{1F9E8} FREE",n),n instanceof ImageBitmap?n.close():n instanceof zC?n.data=null:n.dispose())}function W_(n){(n instanceof q||n instanceof Pn)&&(n.material=null,n.geometry=null)}const OM=new Set;function Qg(n,e,t=null,s){if(s||(s=OM,s.clear()),!n)return s;const o=n[dc];if(o)for(const r of o)s.has(r)||t?.call(null,r)!==!1&&(s.add(r),e&&Qg(r,!0,t,s));return s}function kM(n){return n[uc]}const Or=C("debugresourceusers")||C("debugmemory"),dc=Symbol("needle-resource-users"),uc=Symbol("needle-resource-users-count");function Yt(n,e){Bd(n,e,function(t,s){Pr&&!qg.raycasting&&(Kd(dc,this,t,!1),Kd(dc,this,s,!0))})}Pr&&(Yt(q.prototype,"material"),Yt(q.prototype,"geometry"),Yt(Pe.prototype,"map"),Yt(Pe.prototype,"bumpMap"),Yt(Pe.prototype,"alphaMap"),Yt(Pe.prototype,"normalMap"),Yt(Pe.prototype,"displacementMap"),Yt(Pe.prototype,"roughnessMap"),Yt(Pe.prototype,"metalnessMap"),Yt(Pe.prototype,"emissiveMap"),Yt(Pe.prototype,"specularMap"),Yt(Pe.prototype,"envMap"),Yt(Pe.prototype,"lightMap"),Yt(Pe.prototype,"aoMap"),Yt(Pe.prototype,"gradientMap"));function MM(n){if(Pr===!1)return;const e=n[dc];if(e)for(const t of e)Kd(dc,t,n,!1)}Pr&&Bd(Pe.prototype,"dispose",function(){MM(this)});let Yg=0;function Kd(n,e,t,s){if(Yg>0)return;if(Array.isArray(t)){for(const r of t)Kd(n,e,r,s);return}if(!t)return;let o=t[n];if(o||(o=new Set),s){if(e&&!o.has(e)){o.add(e);let r=t[uc]||0;r+=1,t[uc]=r,Or&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,r,"users:",o)}}else if(e&&o.has(e)){o.delete(e);let r=t[uc]||0;r>0&&(r-=1,t[uc]=r),Or&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,r,"users:",o),r<=0&&(D_.isLoading(t)||(Yd&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),F_()&&Te(t)))}t[n]=o}try{Bd(gr.prototype,"render",function(){Yg++},function(){Yg--})}catch(n){console.warn("Could not wrap WebGLRenderer.render",n)}const V_=C("debugcomponentevents");class pc{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),V_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const o=s.indexOf(t);o<0||s.splice(o,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(V_&&console.log("Dispatching event "+e,s),!!s)for(const o of s)o(t)}}a(pc,"eventListeners",new Map);const mc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),$_=Symbol("isUsingInstancing"),H_=Symbol("instancingRenderer"),gc=Symbol("instancingAutoUpdateBounds");class ms{static isUsingInstancing(e){return e[$_]===!0}static getRenderer(e){return e[H_]||null}setAutoUpdateBounds(e,t){const s=ms.getRenderer(e);s&&(s[gc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[mc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const s of e.children)ms.markDirty(s,!0)}}function Ua(n,e){try{e||n()}catch(t){return console.error(t),!1}return!0}const Kg=C("debugnewscripts"),RM=C("debughierarchy"),Fe=[];function TM(){return Fe.length>0}function Zd(n){if(Kg&&console.log("Register new components",n.new_scripts.length,[...n.new_scripts],n.alias?"element: "+n.alias:n.hash,n),n.new_scripts_pre_setup_callbacks.length>0){for(const e of n.new_scripts_pre_setup_callbacks)e&&e();n.new_scripts_pre_setup_callbacks.length=0}if(!(n.new_scripts.length<=0)){Fe.length=0,n.new_scripts.length>0&&Fe.push(...n.new_scripts),n.new_scripts.length=0;for(let e=0;e<Fe.length;e++)try{const t=Fe[e];if(t.isComponent!==!0){(B()||Kg)&&console.error(`Registered script is not a Needle Engine component.
|
|
168
168
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
169
169
|
`,t),Fe.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
170
170
|
Did you add and remove a component in the same frame?`),Fe.splice(e,1),e--;continue}t.context=n,fc(t.gameObject),Zg(t,n)}catch(t){console.error(t),Bn(Fe[e],n),Fe.splice(e,1),e--}for(let e=0;e<Fe.length;e++)try{const t=Fe[e];if(t.destroyed){Bn(Fe[e],n),Fe.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(s){console.error(s)}t.__internalAwake!==void 0&&(t.gameObject||console.error("Calling awake for a component without a GameObject",t,t.gameObject),fc(t.gameObject),t.activeAndEnabled&&Ua(t.__internalAwake.bind(t)))}catch(t){console.error(t),Bn(Fe[e],n),Fe.splice(e,1),e--}for(let e=0;e<Fe.length;e++)try{const t=Fe[e];if(t.destroyed||t.enabled===!1||(fc(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Ua(t.__internalEnable.bind(t)))}catch(t){console.error(t),Bn(Fe[e],n),Fe.splice(e,1),e--}for(let e=0;e<Fe.length;e++)try{const t=Fe[e];if(t.destroyed||!t.gameObject)continue;n.new_script_start.push(t)}catch(t){console.error(t),Bn(Fe[e],n),Fe.splice(e,1),e--}Fe.length=0;for(const e of n.new_scripts_post_setup_callbacks)e&&e();n.new_scripts_post_setup_callbacks.length=0}}function EM(n){n&&(n.__internalDisable(!0),Bn(n,n.context))}function G_(n,e){for(let t=0;t<n.new_script_start.length;t++)try{const s=n.new_script_start[t];if(e!==void 0&&s.gameObject!==e||s.destroyed||s.activeAndEnabled===!1)continue;Ua(s.__internalAwake.bind(s)),s.enabled&&(Ua(s.__internalEnable.bind(s)),Ua(s.__internalStart.bind(s)),n.new_script_start.splice(t,1),t--)}catch(s){console.error(s),Bn(n.new_script_start[t],n),n.new_script_start.splice(t,1),t--}}function Zg(n,e){e.scripts.indexOf(n)===-1&&(e.scripts.push(n),n.earlyUpdate&&e.scripts_earlyUpdate.push(n),n.update&&e.scripts_update.push(n),n.lateUpdate&&e.scripts_lateUpdate.push(n),n.onBeforeRender&&e.scripts_onBeforeRender.push(n),n.onAfterRender&&e.scripts_onAfterRender.push(n),n.onPausedChanged&&e.scripts_pausedChanged.push(n),Jg(n,null)&&e.new_scripts_xr.push(n),Jg(n,"immersive-vr")&&e.scripts_immersive_vr.push(n),Jg(n,"immersive-ar")&&e.scripts_immersive_ar.push(n))}function Bn(n,e){Ji(n,e.new_scripts),Ji(n,e.new_script_start),Ji(n,e.scripts),Ji(n,e.scripts_earlyUpdate),Ji(n,e.scripts_update),Ji(n,e.scripts_lateUpdate),Ji(n,e.scripts_onBeforeRender),Ji(n,e.scripts_onAfterRender),Ji(n,e.scripts_pausedChanged),Ji(n,e.new_scripts_xr),Ji(n,e.scripts_immersive_vr),Ji(n,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(n)}function Ji(n,e){const t=e.indexOf(n);t>=0&&e.splice(t,1)}function Jg(n,e){var t;if(n){const s=n;if(s.onBeforeXR||s.onEnterXR||s.onUpdateXR||s.onLeaveXR||s.onXRControllerAdded||s.onXRControllerRemoved)return!(e!=null&&((t=s.supportsXR)==null?void 0:t.call(s,e))===!1)}return!1}function Jd(n){if(n||(n=pe.Current.scene),!n){console.trace("Invalid call - no current context.");return}const e=Va(n);q_(n,e,!0)||(Kg||B()?console.error(`Error updating hierarchy
|
|
171
|
-
Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,n):console.error('Failed to update active state in hierarchy of "'+n.name+'"',n),console.warn(" \u2191 this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function q_(n,e,t,s=0){if(s>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const o=Va(n);if(e&&(e=o,e&&n.parent)){const c=n.parent;e=c[En],e===void 0&&(c instanceof Si||(e=!0))}const r=n[En]!==e;n[En]=e,r&&(RM&&console.warn("ACTIVE CHANGE",n.name,o,n.visible,e,"changed?"+r,n),AM(n,c=>{e?c.enabled&&(Ua(c.__internalAwake.bind(c)),c.enabled&&c.__internalEnable()):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(n.children)for(const c of n.children)q_(c,e,t,s+1)===!1&&(l=!1);return l}function fc(n){let e=!0,t=n,s=!1;for(;t&&t;){if(t.type==="Scene"&&(s=!0),!Va(t)){e=!1;break}t=t.parent}if(!n){console.error("GO is null");return}n[En]=e&&s}function AM(n,e){var t;if((t=n.userData)!=null&&t.components)for(const s of n.userData.components)e(s)}const eu=new Map,X_=Symbol("prewarmFlag"),ef=Symbol("waitingForPrewarm"),tf=C("debugprewarm");function IM(n,e){!n||n[X_]===!0||n[ef]===!0||(eu.has(e)||eu.set(e,[]),n[ef]=!0,eu.get(e).push(n),tf&&console.debug("register prewarm",n.name))}let sf=null,nf=null;function LM(n){if(!n)return;const e=eu.get(n);if(!(e!=null&&e.length))return;const t=n.mainCamera;if(t){tf&&console.log("prewarm",e.length,"objects",[...e]);const s=n.renderer;if(s.compile){const o=n.scene;s.compile(o,t),sf??(sf=new NC(64)),nf??(nf=new WC(.001,9999999,sf)),nf.update(s,o);for(const r of e)r[X_]=!0,r[ef]=!1;e.length=0,tf&&console.log("prewarm done")}}}pe.registerCallback(me.ContextCreated,n=>{const e=n.context;ew(e),K_(e)});const tu=C("debugcomponents"),Q_="eff8ba80-635d-11ec-90d6-0242ac120003";class Dt{constructor(e){a(this,"_originalSeed"),a(this,"_seed"),typeof e=="string"&&(e=Dt.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Kv(e,Q_);const t=this._seed;return this._seed-=1,Kv(t.toString(),Q_)}initialize(e){typeof e=="string"?this._seed=Dt.hash(e):this._seed=e}static createFromString(e){return new Dt(this.hash(e))}static hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}var Y_=(n=>(n.NewInstanceCreated="new-instance-created",n.InstanceDestroyed="instance-destroyed",n))(Y_||{});class jM{constructor(e){a(this,"guid"),a(this,"dontSave"),this.guid=e}}function yc(n,e,t=!0,s){if(!n)return;const o=n;if(Ai(n,t),!e){console.warn("Can not send destroy: No networking connection provided",n.guid);return}if(!e.isConnected){B()&&console.debug("Can not send destroy: not connected",n.guid);return}let r=n.guid;if(!r&&o.uuid&&(r=o.uuid),!r){console.warn("Can not send destroy: failed to find guid",n);return}of(r,e,s)}function of(n,e,t){const s=new jM(n);t?.saveInRoom===!1&&(s.dontSave=!0),e.send("instance-destroyed",s,xs.Queued)}function K_(n){n.connection.beginListen("instance-destroyed",e=>{tu&&console.log("[Remote] Destroyed",n.scene,e);const t=ff(e.guid,n.scene);t&&Ai(t)})}class DM{constructor(e,t,s){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=e,this.hash=t,this.size=s}}class Z_{constructor(e,t){a(this,"guid"),a(this,"originalGuid"),a(this,"seed"),a(this,"visible"),a(this,"hostData"),a(this,"dontSave"),a(this,"parent"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"preventCreation"),a(this,"deleteStateOnDisconnect"),this.originalGuid=e,this.guid=t}}function rf(n,e,t,s){var o,r;const l=n;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(e.context||(e.context=J.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=e?{...e}:null,{instance:h,seed:d}=BM(l,e);if(h){const u=h;if(u.guid){tu&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new Z_(l.guid,u.guid);p.seed=d,e.deleteOnDisconnect===!0&&(p.deleteStateOnDisconnect=!0),c&&(c.position&&(p.position={x:c.position.x,y:c.position.y,z:c.position.z}),c.rotation&&(p.rotation={x:c.rotation.x,y:c.rotation.y,z:c.rotation.z,w:c.rotation.w}),c.scale&&(p.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z})),p.position||(p.position={x:u.position.x,y:u.position.y,z:u.position.z}),p.rotation||(p.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),p.scale||(p.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),p.visible=l.visible,c!=null&&c.parent&&(typeof c.parent=="string"?p.parent=c.parent:p.parent=c.parent.guid),p.hostData=t,s===!1&&(p.dontSave=!0),!((o=e?.context)!=null&&o.connection)&&B()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),e.context.connection.isInRoom&&za.push(new WeakRef(u)),(r=e?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function J_(){return Math.random()*9999999}const za=new Array;function ew(n){n.connection.beginListen("new-instance-created",async e=>{const t=await FM(e.originalGuid,n.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const s=new Bs;e.position&&(s.position=new S(e.position.x,e.position.y,e.position.z)),e.rotation&&(s.rotation=new V(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(s.scale=new S(e.scale.x,e.scale.y,e.scale.z)),s.parent=e.parent,e.seed&&(s.idProvider=new Dt(e.seed)),s.visible=e.visible,s.context=n,tu&&n.alias&&console.log("[Remote] instantiate in: "+n.alias);const o=Ha(t,s);za.push(new WeakRef(o)),o&&(e.parent==="scene"&&n.scene.add(o),tu&&console.log("[Remote] new instance","gameobject:",o?.guid,t))}),n.connection.beginListen("left-room",()=>{za.length>0&&console.debug(`Left networking room, cleaning up ${za.length} instantiated objects`);for(const e of za){const t=e.deref();t&&t.destroy()}za.length=0})}function BM(n,e){const t=J_(),s=e??new Bs;s.idProvider=new Dt(t);const o=Ha(n,s);return{seed:t,instance:o}}const tw={};function iw(n,e){tw[n]=e}async function FM(n,e){const t=tw[n];if(t!=null){const s=await t(n);if(s)return s}return sw(n,e)}function sw(n,e){if(e===null||!n)return null;if(e.guid===n)return e;if(e.children)for(const t of e.children){const s=sw(n,t);if(s)return s}return null}const vc=C("gizmos"),wt=C("debugextension"),af=C("debugtypes");class UM{constructor(){a(this,"_types",new Map),af&&console.warn("TypeStore: Created",this)}add(e,t){af&&console.warn("ADD TYPE",e);const s=this._types.get(e);s?af&&s!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):this._types.set(e,t)}get(e){return this._types.get(e)||null}getKey(e){for(const[t,s]of this._types)if(s===e)return t;return null}}const zM=Symbol("BuiltInType"),R=new UM,NM=function(n){R.get(n.name)||R.add(n.name,n)},lf=C("debugresolvedependencies"),WM=["/extensions/","extensions/"],VM=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function cf(n,e){lf&&console.log(n,e);const t=[];hf(VM,n,e,t);const s=await Promise.all(t);return typeof e=="string"&&s.length===1?s[0]:s}function nw(n,e){return!n||!e?!1:n["needle:identifier"]!=null&&e["needle:identifier"]!=null?n["needle:identifier"]===e["needle:identifier"]:!1}function $M(n,e){n["needle:identifier"]=e}function hf(n,e,t,s){if(typeof t=="object"&&t!==void 0&&t!==null)for(const o of Object.keys(t)){const r=t[o];if(typeof r=="string"){const l=ow(e,r);if(l!=null)typeof l.then=="function"?s.push(l.then(c=>t[o]=c)):t[o]=l;else{const c=rw(n,e,r);if(c){s.push(c.then(h=>(t[o]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=ow(e,c);if(h!==null){typeof h.then=="function"?s.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of n){const u=aw(d.prefix,c);if(u>=0){lf&&console.log(d,u,d.dependencyName),s.push(e.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&hf(n,e,c,s)}else typeof r=="object"&&hf(n,e,r,s)}else if(typeof t=="string"){const o=rw(n,e,t);o&&s.push(o)}}function ow(n,e){if(n&&n.plugins&&typeof e=="string"){for(const t of WM)if(e.startsWith(t)){let s=e.substring(t.length);const o=s.indexOf("/");o>=0&&(s=s.substring(0,o));const r=n.plugins[s];if(wt&&console.log(s,r),typeof r?.resolve=="function"){const l=e.substring(t.length+s.length+1);return r.resolve(n,l)}break}}return null}function rw(n,e,t){for(const s of n){const o=aw(s.prefix,t);if(o>=0)return lf&&console.warn("GET DEPENDENCY",s,o,s.dependencyName),e.getDependency(s.dependencyName,o)}return null}function aw(n,e){if(typeof e=="string"&&e.startsWith(n)){const t=e.substring(n.length),s=Number.parseInt(t);if(s>=0)return s}return-1}const df="NEEDLE_persistent_assets";function HM(n){return n?.___persistentAsset===!0}class GM{constructor(e){a(this,"parser"),this.parser=e}get name(){return df}async afterRoot(e){var t,s;if(!((s=(t=this.parser)==null?void 0:t.json)!=null&&s.extensions))return;const o=this.parser.json.extensions[df];if(!o)return;wt&&console.log(o);const r=new Array;for(const l of o?.assets){const c=cf(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(e,t){const s=Number.parseInt(t);if(s>=0){wt&&console.log(t);const o=e.json.extensions[df];if(o){const r=o?.assets[s];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&R.get(l)}return r}}return null}}const Qs=C("debugserializer");class qM{constructor(){a(this,"typeMap",new Map)}register(e,t){if(this.typeMap.has(e)){const s=this.typeMap.get(e);if(s===t)return;Qs&&console.warn("Type: "+e+" is already registered",t,s)}Qs&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){Qs&&console.log("invalid type");return}const s=e.name,o=this.getSerializer(e);if(o!==void 0)return Qs&&console.log("FOUND SERIALIZER",o?.name,e.name,e.constructor.name,"for type: "+s,o,e,this.typeMap),o;const r=Object.getPrototypeOf(e);if(r&&r!==e){const l=this.getSerializerForConstructor(r,++t);if(l){const c=r.constructor||r.prototype;Qs&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Qs&&console.warn("No serializer found for "+s,e,e.name,e.constructor.name)}}const iu=new qM;class es{constructor(e,t){if(a(this,"name"),this.name=t,Array.isArray(e))for(const s of e)iu.register(s,this);else iu.register(e,this)}}class XM{constructor(){a(this,"isDevMode",Xt()),a(this,"cache",{})}registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const s=t;s.$serializedTypes&&Object.keys(s.$serializedTypes)&&this.cache[e].push(...Object.keys(s.$serializedTypes)),Qs&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class uf{constructor(e){a(this,"root"),a(this,"gltf"),a(this,"gltfId"),a(this,"object"),a(this,"target"),a(this,"nodeId"),a(this,"nodeToObject"),a(this,"objectToNode"),a(this,"context"),a(this,"path"),a(this,"type"),a(this,"serializable"),a(this,"implementationInformation"),this.root=e}}function lw(n,e){const t=n.$serializedTypes;if(t===void 0)return null;const s={};for(const r in t){const l=n[r];if(l!=null&&typeof l=="object"){const c=iu.getSerializerForConstructor(l);if(c){s[r]=c.onSerialize(l,e);continue}}s[r]=l}function o(r){const l=R._types;for(const[c,h]of l)if(h===n.constructor)return c;return r.__name||r.constructor.name}return s.name=o(n),typeof n.guid=="string"&&(s.guid=n.guid),s}const su=[];function cw(n,e){if(!n)return e;typeof n.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,n.$serializedTypes));const t=Object.getPrototypeOf(n);return cw(t,e)}function nu(n,e,t){if(!n)return!1;if(t.target=n,n.onBeforeDeserialize!==void 0){const o=n.onBeforeDeserialize(e,t);if(typeof o=="boolean")return o}const s=cw(n);if(e){if(typeof e.guid=="string"&&(n.guid=e.guid),s)for(const o in s){let r=function(h){const d=h.type;return d?pf(c,d,t,void 0,n[o]):pf(c,h,t,void 0,n[o])};const l=s[o],c=e[o];if(Qs&&console.log(o,c,n,l),!(n[o]!==void 0&&c===void 0)&&(t.type=void 0,t.path=o,t.serializable=l,!(n.onBeforeDeserializeMember!==void 0&&n.onBeforeDeserializeMember(o,c,t)===!0))){if(l===null)n[o]=c;else{if(Array.isArray(l))for(let h=0;h<l.length;h++){const d=l[h],u=r(d);if(u!==void 0||h===l.length-1){n[o]=u;break}}else n[o]=r(l);su.length=0}n.onAfterDeserializeMember!==void 0&&n.onAfterDeserializeMember(o,c,t)}}KM(n,e)}return YM(n,e,t.implementationInformation),n.onAfterDeserialize!==void 0&&n.onAfterDeserialize(e,t),!0}const QM=C("noerrors");function YM(n,e,t){var s,o;if(QM||!e||!Xt()||!n||n.constructor&&n.constructor[zM]===!0)return;const r=(s=n.constructor)==null?void 0:s.name,l=Object.getOwnPropertyNames(e);for(const c of l){if(c==="sourceId")continue;const h=n[c];if(h==null)continue;const d=e[c];if(t?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);t.getDefinedKey(r,u)&&(Hs(Mi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,n));continue}if(d!=null){if(typeof d=="object"&&(h===void 0||!h.isObject3D)){if(typeof d.node=="number"||typeof d.guid=="string"){if(d.could_not_resolve)continue;if(!(h!==void 0&&Object.keys(h).length>1)){Hs(Mi.Warn,`<strong>Missing serialization for object reference!</strong>
|
|
171
|
+
Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,n):console.error('Failed to update active state in hierarchy of "'+n.name+'"',n),console.warn(" \u2191 this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function q_(n,e,t,s=0){if(s>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const o=Va(n);if(e&&(e=o,e&&n.parent)){const c=n.parent;e=c[En],e===void 0&&(c instanceof Si||(e=!0))}const r=n[En]!==e;n[En]=e,r&&(RM&&console.warn("ACTIVE CHANGE",n.name,o,n.visible,e,"changed?"+r,n),AM(n,c=>{e?c.enabled&&(Ua(c.__internalAwake.bind(c)),c.enabled&&c.__internalEnable()):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(n.children)for(const c of n.children)q_(c,e,t,s+1)===!1&&(l=!1);return l}function fc(n){let e=!0,t=n,s=!1;for(;t&&t;){if(t.type==="Scene"&&(s=!0),!Va(t)){e=!1;break}t=t.parent}if(!n){console.error("GO is null");return}n[En]=e&&s}function AM(n,e){var t;if((t=n.userData)!=null&&t.components)for(const s of n.userData.components)e(s)}const eu=new Map,X_=Symbol("prewarmFlag"),ef=Symbol("waitingForPrewarm"),tf=C("debugprewarm");function IM(n,e){!n||n[X_]===!0||n[ef]===!0||(eu.has(e)||eu.set(e,[]),n[ef]=!0,eu.get(e).push(n),tf&&console.debug("register prewarm",n.name))}let sf=null,nf=null;function LM(n){if(!n)return;const e=eu.get(n);if(!(e!=null&&e.length))return;const t=n.mainCamera;if(t){tf&&console.log("prewarm",e.length,"objects",[...e]);const s=n.renderer;if(s.compile){const o=n.scene;s.compile(o,t),sf??(sf=new NC(64)),nf??(nf=new WC(.001,9999999,sf)),nf.update(s,o);for(const r of e)r[X_]=!0,r[ef]=!1;e.length=0,tf&&console.log("prewarm done")}}}pe.registerCallback(me.ContextCreated,n=>{const e=n.context;ew(e),K_(e)});const tu=C("debugcomponents"),Q_="eff8ba80-635d-11ec-90d6-0242ac120003";class jt{constructor(e){a(this,"_originalSeed"),a(this,"_seed"),typeof e=="string"&&(e=jt.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Kv(e,Q_);const t=this._seed;return this._seed-=1,Kv(t.toString(),Q_)}initialize(e){typeof e=="string"?this._seed=jt.hash(e):this._seed=e}static createFromString(e){return new jt(this.hash(e))}static hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}var Y_=(n=>(n.NewInstanceCreated="new-instance-created",n.InstanceDestroyed="instance-destroyed",n))(Y_||{});class jM{constructor(e){a(this,"guid"),a(this,"dontSave"),this.guid=e}}function yc(n,e,t=!0,s){if(!n)return;const o=n;if(Ai(n,t),!e){console.warn("Can not send destroy: No networking connection provided",n.guid);return}if(!e.isConnected){B()&&console.debug("Can not send destroy: not connected",n.guid);return}let r=n.guid;if(!r&&o.uuid&&(r=o.uuid),!r){console.warn("Can not send destroy: failed to find guid",n);return}of(r,e,s)}function of(n,e,t){const s=new jM(n);t?.saveInRoom===!1&&(s.dontSave=!0),e.send("instance-destroyed",s,xs.Queued)}function K_(n){n.connection.beginListen("instance-destroyed",e=>{tu&&console.log("[Remote] Destroyed",n.scene,e);const t=ff(e.guid,n.scene);t&&Ai(t)})}class DM{constructor(e,t,s){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=e,this.hash=t,this.size=s}}class Z_{constructor(e,t){a(this,"guid"),a(this,"originalGuid"),a(this,"seed"),a(this,"visible"),a(this,"hostData"),a(this,"dontSave"),a(this,"parent"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"preventCreation"),a(this,"deleteStateOnDisconnect"),this.originalGuid=e,this.guid=t}}function rf(n,e,t,s){var o,r;const l=n;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(e.context||(e.context=J.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=e?{...e}:null,{instance:h,seed:d}=BM(l,e);if(h){const u=h;if(u.guid){tu&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new Z_(l.guid,u.guid);p.seed=d,e.deleteOnDisconnect===!0&&(p.deleteStateOnDisconnect=!0),c&&(c.position&&(p.position={x:c.position.x,y:c.position.y,z:c.position.z}),c.rotation&&(p.rotation={x:c.rotation.x,y:c.rotation.y,z:c.rotation.z,w:c.rotation.w}),c.scale&&(p.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z})),p.position||(p.position={x:u.position.x,y:u.position.y,z:u.position.z}),p.rotation||(p.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),p.scale||(p.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),p.visible=l.visible,c!=null&&c.parent&&(typeof c.parent=="string"?p.parent=c.parent:p.parent=c.parent.guid),p.hostData=t,s===!1&&(p.dontSave=!0),!((o=e?.context)!=null&&o.connection)&&B()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),e.context.connection.isInRoom&&za.push(new WeakRef(u)),(r=e?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function J_(){return Math.random()*9999999}const za=new Array;function ew(n){n.connection.beginListen("new-instance-created",async e=>{const t=await FM(e.originalGuid,n.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const s=new Bs;e.position&&(s.position=new S(e.position.x,e.position.y,e.position.z)),e.rotation&&(s.rotation=new V(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(s.scale=new S(e.scale.x,e.scale.y,e.scale.z)),s.parent=e.parent,e.seed&&(s.idProvider=new jt(e.seed)),s.visible=e.visible,s.context=n,tu&&n.alias&&console.log("[Remote] instantiate in: "+n.alias);const o=Ha(t,s);za.push(new WeakRef(o)),o&&(e.parent==="scene"&&n.scene.add(o),tu&&console.log("[Remote] new instance","gameobject:",o?.guid,t))}),n.connection.beginListen("left-room",()=>{za.length>0&&console.debug(`Left networking room, cleaning up ${za.length} instantiated objects`);for(const e of za){const t=e.deref();t&&t.destroy()}za.length=0})}function BM(n,e){const t=J_(),s=e??new Bs;s.idProvider=new jt(t);const o=Ha(n,s);return{seed:t,instance:o}}const tw={};function iw(n,e){tw[n]=e}async function FM(n,e){const t=tw[n];if(t!=null){const s=await t(n);if(s)return s}return sw(n,e)}function sw(n,e){if(e===null||!n)return null;if(e.guid===n)return e;if(e.children)for(const t of e.children){const s=sw(n,t);if(s)return s}return null}const vc=C("gizmos"),wt=C("debugextension"),af=C("debugtypes");class UM{constructor(){a(this,"_types",new Map),af&&console.warn("TypeStore: Created",this)}add(e,t){af&&console.warn("ADD TYPE",e);const s=this._types.get(e);s?af&&s!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):this._types.set(e,t)}get(e){return this._types.get(e)||null}getKey(e){for(const[t,s]of this._types)if(s===e)return t;return null}}const zM=Symbol("BuiltInType"),R=new UM,NM=function(n){R.get(n.name)||R.add(n.name,n)},lf=C("debugresolvedependencies"),WM=["/extensions/","extensions/"],VM=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function cf(n,e){lf&&console.log(n,e);const t=[];hf(VM,n,e,t);const s=await Promise.all(t);return typeof e=="string"&&s.length===1?s[0]:s}function nw(n,e){return!n||!e?!1:n["needle:identifier"]!=null&&e["needle:identifier"]!=null?n["needle:identifier"]===e["needle:identifier"]:!1}function $M(n,e){n["needle:identifier"]=e}function hf(n,e,t,s){if(typeof t=="object"&&t!==void 0&&t!==null)for(const o of Object.keys(t)){const r=t[o];if(typeof r=="string"){const l=ow(e,r);if(l!=null)typeof l.then=="function"?s.push(l.then(c=>t[o]=c)):t[o]=l;else{const c=rw(n,e,r);if(c){s.push(c.then(h=>(t[o]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=ow(e,c);if(h!==null){typeof h.then=="function"?s.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of n){const u=aw(d.prefix,c);if(u>=0){lf&&console.log(d,u,d.dependencyName),s.push(e.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&hf(n,e,c,s)}else typeof r=="object"&&hf(n,e,r,s)}else if(typeof t=="string"){const o=rw(n,e,t);o&&s.push(o)}}function ow(n,e){if(n&&n.plugins&&typeof e=="string"){for(const t of WM)if(e.startsWith(t)){let s=e.substring(t.length);const o=s.indexOf("/");o>=0&&(s=s.substring(0,o));const r=n.plugins[s];if(wt&&console.log(s,r),typeof r?.resolve=="function"){const l=e.substring(t.length+s.length+1);return r.resolve(n,l)}break}}return null}function rw(n,e,t){for(const s of n){const o=aw(s.prefix,t);if(o>=0)return lf&&console.warn("GET DEPENDENCY",s,o,s.dependencyName),e.getDependency(s.dependencyName,o)}return null}function aw(n,e){if(typeof e=="string"&&e.startsWith(n)){const t=e.substring(n.length),s=Number.parseInt(t);if(s>=0)return s}return-1}const df="NEEDLE_persistent_assets";function HM(n){return n?.___persistentAsset===!0}class GM{constructor(e){a(this,"parser"),this.parser=e}get name(){return df}async afterRoot(e){var t,s;if(!((s=(t=this.parser)==null?void 0:t.json)!=null&&s.extensions))return;const o=this.parser.json.extensions[df];if(!o)return;wt&&console.log(o);const r=new Array;for(const l of o?.assets){const c=cf(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(e,t){const s=Number.parseInt(t);if(s>=0){wt&&console.log(t);const o=e.json.extensions[df];if(o){const r=o?.assets[s];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&R.get(l)}return r}}return null}}const Qs=C("debugserializer");class qM{constructor(){a(this,"typeMap",new Map)}register(e,t){if(this.typeMap.has(e)){const s=this.typeMap.get(e);if(s===t)return;Qs&&console.warn("Type: "+e+" is already registered",t,s)}Qs&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){Qs&&console.log("invalid type");return}const s=e.name,o=this.getSerializer(e);if(o!==void 0)return Qs&&console.log("FOUND SERIALIZER",o?.name,e.name,e.constructor.name,"for type: "+s,o,e,this.typeMap),o;const r=Object.getPrototypeOf(e);if(r&&r!==e){const l=this.getSerializerForConstructor(r,++t);if(l){const c=r.constructor||r.prototype;Qs&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Qs&&console.warn("No serializer found for "+s,e,e.name,e.constructor.name)}}const iu=new qM;class es{constructor(e,t){if(a(this,"name"),this.name=t,Array.isArray(e))for(const s of e)iu.register(s,this);else iu.register(e,this)}}class XM{constructor(){a(this,"isDevMode",Xt()),a(this,"cache",{})}registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const s=t;s.$serializedTypes&&Object.keys(s.$serializedTypes)&&this.cache[e].push(...Object.keys(s.$serializedTypes)),Qs&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class uf{constructor(e){a(this,"root"),a(this,"gltf"),a(this,"gltfId"),a(this,"object"),a(this,"target"),a(this,"nodeId"),a(this,"nodeToObject"),a(this,"objectToNode"),a(this,"context"),a(this,"path"),a(this,"type"),a(this,"serializable"),a(this,"implementationInformation"),this.root=e}}function lw(n,e){const t=n.$serializedTypes;if(t===void 0)return null;const s={};for(const r in t){const l=n[r];if(l!=null&&typeof l=="object"){const c=iu.getSerializerForConstructor(l);if(c){s[r]=c.onSerialize(l,e);continue}}s[r]=l}function o(r){const l=R._types;for(const[c,h]of l)if(h===n.constructor)return c;return r.__name||r.constructor.name}return s.name=o(n),typeof n.guid=="string"&&(s.guid=n.guid),s}const su=[];function cw(n,e){if(!n)return e;typeof n.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,n.$serializedTypes));const t=Object.getPrototypeOf(n);return cw(t,e)}function nu(n,e,t){if(!n)return!1;if(t.target=n,n.onBeforeDeserialize!==void 0){const o=n.onBeforeDeserialize(e,t);if(typeof o=="boolean")return o}const s=cw(n);if(e){if(typeof e.guid=="string"&&(n.guid=e.guid),s)for(const o in s){let r=function(h){const d=h.type;return d?pf(c,d,t,void 0,n[o]):pf(c,h,t,void 0,n[o])};const l=s[o],c=e[o];if(Qs&&console.log(o,c,n,l),!(n[o]!==void 0&&c===void 0)&&(t.type=void 0,t.path=o,t.serializable=l,!(n.onBeforeDeserializeMember!==void 0&&n.onBeforeDeserializeMember(o,c,t)===!0))){if(l===null)n[o]=c;else{if(Array.isArray(l))for(let h=0;h<l.length;h++){const d=l[h],u=r(d);if(u!==void 0||h===l.length-1){n[o]=u;break}}else n[o]=r(l);su.length=0}n.onAfterDeserializeMember!==void 0&&n.onAfterDeserializeMember(o,c,t)}}KM(n,e)}return YM(n,e,t.implementationInformation),n.onAfterDeserialize!==void 0&&n.onAfterDeserialize(e,t),!0}const QM=C("noerrors");function YM(n,e,t){var s,o;if(QM||!e||!Xt()||!n||n.constructor&&n.constructor[zM]===!0)return;const r=(s=n.constructor)==null?void 0:s.name,l=Object.getOwnPropertyNames(e);for(const c of l){if(c==="sourceId")continue;const h=n[c];if(h==null)continue;const d=e[c];if(t?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);t.getDefinedKey(r,u)&&(Hs(Mi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,n));continue}if(d!=null){if(typeof d=="object"&&(h===void 0||!h.isObject3D)){if(typeof d.node=="number"||typeof d.guid=="string"){if(d.could_not_resolve)continue;if(!(h!==void 0&&Object.keys(h).length>1)){Hs(Mi.Warn,`<strong>Missing serialization for object reference!</strong>
|
|
172
172
|
|
|
173
173
|
Please change to:
|
|
174
174
|
@serializable(Object3D)
|
|
@@ -183,12 +183,12 @@ Please change to:
|
|
|
183
183
|
${c}? : AssetReference;
|
|
184
184
|
|
|
185
185
|
in script ${r}.ts
|
|
186
|
-
<a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,n[c],n);continue}}}}function KM(n,e){for(const t of Object.keys(e)){const s=e[t];if(typeof s=="object"&&s!==null&&s!==void 0){const o=n[t];if(!o){Qs&&console.log(t,"is undefined on",n);continue}for(const r of Object.keys(s))if(o[r]===void 0&&hw(s[r])&&!hw(o)){const l=ZM(o,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Qs&&console.warn('Property is not writable "'+r+'"',o,l,s[r],o[r]);continue}o[r]=s[r]}}}}function ZM(n,e){for(;n;){const t=Object.getOwnPropertyDescriptor(n,e);if(t)return t;n=Object.getPrototypeOf(n)}}function hw(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}function pf(n,e,t,s,o){let r=typeof e=="function"&&e.prototype===void 0,l=e;if(r)try{if(l=e?.call(e,o),r=!1,l==null)return}catch(u){console.error("Error in callback",u,n)}if(t.type=l,!r&&o&&(o instanceof Pe||o instanceof q||o instanceof Ws||o instanceof fo))return o;if(s||(s={serializer:iu.getSerializerForConstructor(l)}),o&&typeof o=="object"&&HM(o)){if(o.__concreteInstance)return o.__concreteInstance;const u=o;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&nu(u,n,t),o&&l!==void 0)try{let p=null;s.serializer&&(p=s.serializer.onDeserialize(n,t)),p||(p=new l,wt&&console.log("Create concrete instance for persistent asset",o,"instance:",p),Na(p,o)),o.__concreteInstance=p,o=p}catch(p){console.error("Error creating instance or creating values on instance",p,o,l)}return o}if(Array.isArray(n)){const u=[];for(let p=0;p<n.length;p++){const g=n[p],f=pf(g,e,t,s,g);u.push(f)}return u}const c=s?.serializer;if(c)return c.onDeserialize(n,t);if(o instanceof je)return o;let h;if(n&&(n.isMaterial||n.isTexture||n.isObject3D||n instanceof fo))h=n;else{if(n===void 0)return;if(n===null&&(l===Pe||l===je||l===q||l===fo))return null;try{h=new l(...JM(n))}catch(u){console.error("Error creating "+t.path,t.target,u);return}}const d=h;return d.$serializedTypes&&nu(d,n,t),h}function JM(n){if(su.length=0,typeof n=="object"&&n!==null&&n!==void 0)for(const e of Object.keys(n))su.push(n[e]);return su}const mf=Symbol("assigned component properties");function Na(n,e,t,s){var o;if(e==null||n==null)return;n[mf]=!0;const r=((o=n.constructor)==null?void 0:o.name)??"unknown";t?.registerDefinedKeys(r,n);for(const l of Object.keys(e)){const c=eR(n,l);if(typeof c?.value!="function"){if(!c||c.writable===!0){const h=s!=null&&s.onAssign?s.onAssign(e,l,e[l]):e[l];n[l]=h}else if(c?.set!==void 0){const h=s!=null&&s.onAssign?s.onAssign(e,l,e[l]):e[l];n[l]=h}}}delete n[mf]}function eR(n,e){let t;do t=Object.getOwnPropertyDescriptor(n,e);while(!t&&(n=Object.getPrototypeOf(n)));return t}const dw=Symbol("customVisibilityFlag");function Fn(n,e){n.layers[dw]=e}const uw=Symbol("DidPatchLayers");function tR(){const n=po.prototype;if(n[uw])return;n[uw]=!0;const e=n.test;n.test=function(t){return this[dw]===!1?!1:e.call(this,t)}}tR(),Object.defineProperty(we.prototype,"fov",{get:function(){return this._fov},set:function(n){const e=n!==this._fov;this._fov=n,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"near",{get:function(){return this._near},set:function(n){const e=n!==this._near;this._near=n,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"far",{get:function(){return this._far},set:function(n){const e=n!==this._far;this._far=n,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const pw=new Map;function mw(n,e){if(!n)return;if(!e){console.warn("No prototype found",n,n.prototype,n.constructor);return}const t=pw.get(e);t&&t.apply(n)}function gw(n){const e=iR(n.prototype);pw.set(n,e)}function iR(n){return new sR(n)}class sR{constructor(e){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],o=Object.getOwnPropertyDescriptor(e,s);o&&this.descriptors.push(o)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],o=this.descriptors[t];o&&Object.defineProperty(e,s,o)}}}}const nR=C("debuggetcomponent"),fw=()=>nR||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function oR(n){return n==null||n.isObject3D?n:n.object&&n.object.isObject3D?n.object:n}function gf(n,e){if(!n||!n.userData.components)return e;const t=n.userData.components.indexOf(e);return t<0||(pc.dispatchComponentLifecycleEvent("removing-component",e),e.gameObject=null,n.userData.components.splice(t,1)),e}function bc(n,e,t){return Mr(n,e)||Ei(n,e,t)}const yw=new
|
|
186
|
+
<a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,n[c],n);continue}}}}function KM(n,e){for(const t of Object.keys(e)){const s=e[t];if(typeof s=="object"&&s!==null&&s!==void 0){const o=n[t];if(!o){Qs&&console.log(t,"is undefined on",n);continue}for(const r of Object.keys(s))if(o[r]===void 0&&hw(s[r])&&!hw(o)){const l=ZM(o,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Qs&&console.warn('Property is not writable "'+r+'"',o,l,s[r],o[r]);continue}o[r]=s[r]}}}}function ZM(n,e){for(;n;){const t=Object.getOwnPropertyDescriptor(n,e);if(t)return t;n=Object.getPrototypeOf(n)}}function hw(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}function pf(n,e,t,s,o){let r=typeof e=="function"&&e.prototype===void 0,l=e;if(r)try{if(l=e?.call(e,o),r=!1,l==null)return}catch(u){console.error("Error in callback",u,n)}if(t.type=l,!r&&o&&(o instanceof Pe||o instanceof q||o instanceof Ws||o instanceof fo))return o;if(s||(s={serializer:iu.getSerializerForConstructor(l)}),o&&typeof o=="object"&&HM(o)){if(o.__concreteInstance)return o.__concreteInstance;const u=o;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&nu(u,n,t),o&&l!==void 0)try{let p=null;s.serializer&&(p=s.serializer.onDeserialize(n,t)),p||(p=new l,wt&&console.log("Create concrete instance for persistent asset",o,"instance:",p),Na(p,o)),o.__concreteInstance=p,o=p}catch(p){console.error("Error creating instance or creating values on instance",p,o,l)}return o}if(Array.isArray(n)){const u=[];for(let p=0;p<n.length;p++){const g=n[p],f=pf(g,e,t,s,g);u.push(f)}return u}const c=s?.serializer;if(c)return c.onDeserialize(n,t);if(o instanceof je)return o;let h;if(n&&(n.isMaterial||n.isTexture||n.isObject3D||n instanceof fo))h=n;else{if(n===void 0)return;if(n===null&&(l===Pe||l===je||l===q||l===fo))return null;try{h=new l(...JM(n))}catch(u){console.error("Error creating "+t.path,t.target,u);return}}const d=h;return d.$serializedTypes&&nu(d,n,t),h}function JM(n){if(su.length=0,typeof n=="object"&&n!==null&&n!==void 0)for(const e of Object.keys(n))su.push(n[e]);return su}const mf=Symbol("assigned component properties");function Na(n,e,t,s){var o;if(e==null||n==null)return;n[mf]=!0;const r=((o=n.constructor)==null?void 0:o.name)??"unknown";t?.registerDefinedKeys(r,n);for(const l of Object.keys(e)){const c=eR(n,l);if(typeof c?.value!="function"){if(!c||c.writable===!0){const h=s!=null&&s.onAssign?s.onAssign(e,l,e[l]):e[l];n[l]=h}else if(c?.set!==void 0){const h=s!=null&&s.onAssign?s.onAssign(e,l,e[l]):e[l];n[l]=h}}}delete n[mf]}function eR(n,e){let t;do t=Object.getOwnPropertyDescriptor(n,e);while(!t&&(n=Object.getPrototypeOf(n)));return t}const dw=Symbol("customVisibilityFlag");function Fn(n,e){n.layers[dw]=e}const uw=Symbol("DidPatchLayers");function tR(){const n=po.prototype;if(n[uw])return;n[uw]=!0;const e=n.test;n.test=function(t){return this[dw]===!1?!1:e.call(this,t)}}tR(),Object.defineProperty(we.prototype,"fov",{get:function(){return this._fov},set:function(n){const e=n!==this._fov;this._fov=n,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"near",{get:function(){return this._near},set:function(n){const e=n!==this._near;this._near=n,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"far",{get:function(){return this._far},set:function(n){const e=n!==this._far;this._far=n,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const pw=new Map;function mw(n,e){if(!n)return;if(!e){console.warn("No prototype found",n,n.prototype,n.constructor);return}const t=pw.get(e);t&&t.apply(n)}function gw(n){const e=iR(n.prototype);pw.set(n,e)}function iR(n){return new sR(n)}class sR{constructor(e){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],o=Object.getOwnPropertyDescriptor(e,s);o&&this.descriptors.push(o)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],o=this.descriptors[t];o&&Object.defineProperty(e,s,o)}}}}const nR=C("debuggetcomponent"),fw=()=>nR||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function oR(n){return n==null||n.isObject3D?n:n.object&&n.object.isObject3D?n.object:n}function gf(n,e){if(!n||!n.userData.components)return e;const t=n.userData.components.indexOf(e);return t<0||(pc.dispatchComponentLifecycleEvent("removing-component",e),e.gameObject=null,n.userData.components.splice(t,1)),e}function bc(n,e,t){return Mr(n,e)||Ei(n,e,t)}const yw=new jt("addComponentIdProvider");function kr(n,e,t=!0){n.userData||(n.userData={}),n.userData.components||(n.userData.components=[]),n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=yw.generateUUID()),ru(n),_u(e,e.context);try{t&&e.__internalAwake&&(fc(n),e.activeAndEnabled&&e.__internalAwake()),pc.dispatchComponentLifecycleEvent("component-added",e)}catch(s){console.error(s)}return e}function Ei(n,e,t,s){var o;if(typeof e=="function"){const r=new e;t&&r.__internalNewInstanceCreated(t);let l=!0;return s?.callAwake!=null&&(l=s.callAwake),kr(n,r,l)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===n)return e;if(e.gameObject&&(o=e.gameObject.userData)!=null&&o.components){const r=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(r,1)}if(n.userData||(n.userData={}),!n.userData.components)n.userData.components=[];else if(n.userData.components.includes(e))return e;return n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=yw.generateUUID()),t&&e._internalInit(t),_u(e,e.context),e}function vw(n){if(n.gameObject&&n.gameObject.userData.components){const e=n.gameObject.userData.components.indexOf(n);n.gameObject.userData.components.splice(e,1)}n.__internalDisable&&n.__internalDisable(),Bn(n,n.context??J.Current),n.destroy(),n.gameObject=null}let bw=!1;function _w(n,e,t){var s;if(n==null)return null;if(!n.isObject3D)return console.error("Object is not object3D"),null;if(!((s=n?.userData)!=null&&s.components)||(typeof e=="string"&&(bw||(bw=!0,console.warn(`Accessing components by name is not supported.
|
|
187
187
|
Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
|
|
188
188
|
|
|
189
189
|
You can import other modules your main module to get access to types
|
|
190
190
|
or if you use npmdefs you can make types available globally using globalThis:
|
|
191
|
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),fw()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===e.prototype)if(fw()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),t)t.push(r);else return r;l=Object.getPrototypeOf(l)}}return t||null}function Mr(n,e){const t=_w(n,e);return t?Array.isArray(t)?t[0]:t:null}function _c(n,e,t,s=!0){return t||(t=[]),s&&(t.length=0),_w(n,e,t),t}function wc(n,e,t){var s;if(t===!1&&n[En]===!1)return null;const o=Mr(n,e);if(t===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((s=n?.children)==null?void 0:s.length);r++){const l=wc(n.children[r],e);if(l)return l}return null}function Wa(n,e,t,s=!0){var o;t||(t=[]),s&&(t.length=0),_c(n,e,t,!1);for(let r=0;r<((o=n?.children)==null?void 0:o.length);r++)Wa(n.children[r],e,t,!1);return t}function xc(n,e){if(!n)return null;if(Array.isArray(n)){for(let s=0;s<n.length;s++){const o=oR(n[s]),r=xc(o,e);if(r)return r}return null}return Mr(n,e)||(n.parent?xc(n.parent,e):null)}function ou(n,e,t,s=!0){return t||(t=[]),s&&(t.length=0),n?(_c(n,e,t,!1),n.parent?ou(n.parent,e,t,!1):t):t}function Sc(n,e=void 0,t=!0){if(!n)return null;if(!e&&(e=J.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let s=e;return s.isScene||(s=e?.scene),s&&wc(s,n,t)||null}function ww(n,e,t=void 0){if(!n)return e??[];if(e||(e=[]),e.length=0,!t&&(t=J.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const s=t;return s&&Wa(s,n,e,!1),e}function ru(n){n&&n.isObject3D===!0&&mw(n,A)}A.prototype.SetActive=function(n){this.visible=n},A.prototype.setActive=function(n){this.visible=n},A.prototype.destroy=function(){Ai(this)},A.prototype.addComponent=function(n,e){return Ei(this,n,e)},A.prototype.addNewComponent=function(n,e){return Ei(this,n,e)},A.prototype.removeComponent=function(n){return gf(this,n)},A.prototype.getOrAddComponent=function(n,e){return bc(this,n,e)},A.prototype.getComponent=function(n){return Mr(this,n)},A.prototype.getComponents=function(n,e){return _c(this,n,e)},A.prototype.getComponentInChildren=function(n){return wc(this,n)},A.prototype.getComponentsInChildren=function(n,e){return Wa(this,n,e)},A.prototype.getComponentInParent=function(n){return xc(this,n)},A.prototype.getComponentsInParent=function(n,e){return ou(this,n,e)},Object.getOwnPropertyDescriptor(A.prototype,"activeSelf")||Object.defineProperty(A.prototype,"activeSelf",{get:function(){return Va(this)},set:function(n){Cc(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldPosition")||Object.defineProperty(A.prototype,"worldPosition",{get:function(){return this instanceof Hv?ee(this.object):ee(this)},set:function(n){lt(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldQuaternion")||Object.defineProperty(A.prototype,"worldQuaternion",{get:function(){return this instanceof Hv?Se(this.object):Se(this)},set:function(n){Yi(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldRotation")||Object.defineProperty(A.prototype,"worldRotation",{get:function(){return Id(this)},set:function(n){Db(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldScale")||Object.defineProperty(A.prototype,"worldScale",{get:function(){return Ge(this)},set:function(n){Ta(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldForward")||Object.defineProperty(A.prototype,"worldForward",{get:function(){return X().set(0,0,1).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(A.prototype,"worldRight")||Object.defineProperty(A.prototype,"worldRight",{get:function(){return X().set(1,0,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(A.prototype,"worldUp")||Object.defineProperty(A.prototype,"worldUp",{get:function(){return X().set(0,1,0).applyQuaternion(Se(this))}}),gw(A);class he extends re{constructor(e,t,s,o){super(),a(this,"alpha",1),typeof e=="number"&&typeof t=="number"&&typeof s=="number"?(this.set(e,t,s),this.alpha=typeof o=="number"?o:1):e!==void 0&&(this.set(e),this.alpha=1)}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}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 s=e;return s.alpha!=null&&(this.alpha=W.lerp(this.alpha,s.alpha,t)),super.lerp(e,t)}lerpColors(e,t,s){const o=e,r=t;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,s)),super.lerpColors(e,t,s)}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 he(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),s=t>>24&255,o=t>>16&255,r=t>>8&255,l=t>>0&255;return new he(s/255,o/255,r/255,l/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),s=t>>16&255,o=t>>8&255,r=t>>0&255;return new he(s/255,o/255,r/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new he(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 he(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new he(e[0],e[1],e[2],e[3]);if(e.length===3)return new he(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new he(e)}}const au=C("debuggetcomponent"),Rr=C("debuginstantiate");class Bs{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var e,t,s;const o=new Bs;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(e=this.position)==null?void 0:e.clone(),o.rotation=(t=this.rotation)==null?void 0:t.clone(),o.scale=(s=this.scale)==null?void 0:s.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(e){var t,s,o;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(s=e.rotation)==null?void 0:s.clone(),this.scale=(o=e.scale)==null?void 0:o.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function Va(n){return n.visible}function Cc(n,e){return typeof e=="number"&&(e=e>.5),n.visible=e,n.visible}function xw(n){return n[En]||lu(n)}function Sw(n,e){n[$_]=e}function lu(n){return ms.isUsingInstancing(n)}function ff(n,e){return Ma(n,e,!0,!0)}const Cw=Symbol("isDestroyed");function Tr(n){return n[Cw]}function Pw(n,e){n[Cw]=e}const yf=Symbol("isDontDestroy");function $a(n,e=!0){n[yf]=e}const cu=[],hu=[];function Ai(n,e=!0,t=!1){cu.length=0,hu.length=0,vf(n,e,!0);for(const s of cu)s.gameObject=null,s.context=null;for(const s of hu)Pw(s,!0),t&&Te(s),W_(s);hu.length=0,cu.length=0}function vf(n,e=!0,t=!0){var s;if(n==null)return;const o=n;if(o.isComponent){if(o[yf])return;cu.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(n[yf])return;const r=n;au&&console.log(r),hu.push(r);const l=(s=r.userData)==null?void 0:s.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];vf(d,e,!1),l.length<c&&(c=l.length,h--)}}if(e&&r.children)for(const c of r.children)vf(c,e,!1);t&&r.removeFromParent()}function Er(n,e,t=!0){return Ow(n,e,t)}function*du(n,e,t=!1,s=999,o=0){if(n!=null&&n.userData.components&&!(o>s)){for(const r of n.userData.components)e&&r?.isComponent===!0&&r instanceof e?yield r:yield r;if(t===!0)for(const r of n.children)yield*du(r,e,!0,s,o+1)}}function Ow(n,e,t,s=0){var o;if(n){if(n.isObject3D,s>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=n.userData)!=null&&o.components)for(let r=0;r<n.userData.components.length;r++){const l=n.userData.components[r];if(l?.isComponent===!0){const c=e(l);if(c!==void 0)return c}}if(t&&n.children){const r=s+1;for(let l=0;l<n.children.length;l++){const c=n.children[l];if(!c)continue;const h=Ow(c,e,t,r);if(h!==void 0)return h}}}}function Ha(n,e){if("isAssetReference"in n)return n.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new Bs,t.position=e):t=e);let s=J.Current;t!=null&&t.context&&(s=t.context),au&&s.alias&&console.log("context",s.alias),t&&!t.idProvider&&(t.idProvider=new Dt(Date.now()));const o=[],r={},l={},c=kw(s,n,t,o,r,l);c&&(aR(r),rR(l,r)),au&&(Ld(n,!0),Ld(c,!0));const h={};if(t?.components!==!1){for(const d in o){const u=o[d],p=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),h[p]=u.guid,au&&console.log(u.name,u.guid)),_u(u,s),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Zd(s)}return c}function kw(n,e,t,s,o,r){var l;if(!e||e[Ri])return null;const c=e.userData;e.userData={};const h=e.children;e.children=[];const d=e.clone(!1);if(ru(d),e.userData=c,e.children=h,o[e.uuid]={original:e,clone:d},Rr&&console.log("ADD",e,d),e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:d}),t?.visible!==void 0&&(d.visible=t.visible),t!=null&&t.idProvider){d.uuid=t.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}e.animations&&e.animations.length>0&&(d.animations=[...e.animations]);const u=e.parent;if(u&&u.add(d),t!=null&&t.position?lt(d,t.position):d.position.copy(e.position),t!=null&&t.rotation?Yi(d,t.rotation):d.quaternion.copy(e.quaternion),t!=null&&t.scale?d.scale.copy(t.scale):d.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let p=null;if(typeof t.parent=="string"?p=Ma(t.parent,n.scene,!0):p=t.parent,p){const g=t.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[p,g]of Object.entries(e.userData))p!=="components"&&(d.userData[p]=g);if((l=e.userData)!=null&&l.components){const p=e.userData.components,g=[];d.userData.components=g;for(let f=0;f<p.length;f++){const y=p[f],v=new y.constructor;Na(v,y,void 0,{}),y[rc]!==void 0&&(v[rc]=y[rc]),g.push(v),v.gameObject=d,s.push(v),o[y.guid]={original:y,clone:v},pc.dispatchComponentLifecycleEvent("component-added",v)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const p in e.children){const g=e.children[p],f=kw(n,g,t,s,o,r);f&&(o[f.uuid]={original:g,clone:f},d.add(f))}return d}function rR(n,e){for(const t in n){const s=n[t],o=s.original,r=o.skeleton,l=s.clone;if(!r){console.warn("Skinned mesh has no skeleton?",s);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=e[p.uuid].clone;d.push(g)}}for(const t in n){const s=n[t].clone;s.skeleton.update(),s.bind(s.skeleton,s.bindMatrix),s.updateMatrixWorld(!0)}}function aR(n){var e;for(const t in n){const s=n[t].clone;if(s!=null&&s.isObject3D&&(e=s?.userData)!=null&&e.components)for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=Mw(r,c,p,n);g!==void 0?(Rr&&console.log("Found new instance for",c,p,"->",g),d.push(g)):(Rr&&console.warn("Could not find new instance for",c,p),d.push(p))}}else if(typeof h=="object"){const d=Mw(r,c,h,n);d!==void 0?r[c]=d:Rr&&console.warn("Could not find new instance for",c,h)}}}}function Mw(n,e,t,s){var o,r;if(t!=null)if(t.isComponent===!0){const l=t.gameObject;if(l){const c=l.uuid,h=(o=s[c])==null?void 0:o.clone;if(!h){Rr&&console.log("reference did not change",e,n,t);return}const d=l.userData.components.indexOf(t);if(d>=0&&h.isObject3D)return Rr&&console.log(e,c),h.userData.components[d];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const l=t;if(l){const c=l.uuid,h=(r=s[c])==null?void 0:r.clone;if(h)return Rr&&console.log(e,"old",t,"new",h),h}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(s)}}var Ar;(n=>{n.baseUrl="https://networking.needle.tools";function e(h){return Zv(new Uint8Array(h))}n.hashMD5=e;function t(h){const d=Zv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}n.hashMD5_Base64=t;function s(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}n.hashSha256=s;function o(h){const d=h.filesize/1024/1024;return Js()?d<50:d<5}n.canUpload=o;async function r(h,d){var u;const p=n.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const f=g.byteLength,y=f/1024/1024;if(y>50)return d?.silent!==!0&&be(`File (${y.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${y.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Js()&&y>5)return d?.silent!==!0&&be('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${y.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(f<1)return console.warn(`Your file is too small for uploading (${y.toFixed(1)}MB). Min size is 1 byte`),null;const v=t(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:f.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},_=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(w=>w.json()).catch(w=>(console.error(w),null));if(_==null)return console.warn("Upload failed..."),null;if("error"in _)return console.error(_.error),null;if("upload"in _&&_.upload){let w=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(D=>{var z;return(z=d?.onProgress)==null||z.call(null,{progress01:1,state:"finished"}),D}).catch(D=>D)};console.debug("Uploading file",_.upload);let x=!1,k=null;for(let M=0;M<3;M++)try{if(x)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await w(_.upload);T instanceof Error?(k=T,await $s(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),x=!0)}catch(T){console.error(T)}if(!x)return console.error(k?.message||"Failed to upload file"),null}if("download"in _){const w=p+_.download;return console.debug("File found in blob storage",w),{key:_.key,success:!0,download_url:w}}return null}n.upload=r;function l(h){return`${n.baseUrl}/api/needle/blob/${h}`}n.getBlobUrlForKey=l;async function c(h,d){const u=new Am;u.setResponseType("arraybuffer");const p=await u.loadAsync(h,g=>{d&&d.call(null,g)});return p instanceof ArrayBuffer?new Uint8Array(p):(console.error("Download failed, no arraybuffer returned"),null)}n.download=c})(Ar||(Ar={}));const So=C("debugaddressables");class Rw{constructor(e){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const s=this._assetReferences[t];s?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const bf=Symbol("assetReference"),Tw=class Fl{constructor(e,t,s=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_urlName"),a(this,"_progressListeners",[]),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=e;const o=e.lastIndexOf("/");if(o>=0){this._urlName=e.substring(o+1);const r=this._urlName.lastIndexOf(".");r>=0&&(this._urlName=this._urlName.substring(0,r))}else this._urlName=e;s!==null&&(this.asset=s),iw(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(e,t){if(!t&&(t=J.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const s=t.addressables,o=s.findAssetReference(e);if(o)return o;const r=new Fl(e,t.hash);return s.registerAssetReference(r),r}static getOrCreate(e,t,s){if(typeof e=="string"){if(!s&&(s=J.Current,!s))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else s=e.context,e=e.sourceId;const o=vo(e,t);So&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",o);const r=s.addressables,l=r.findAssetReference(o);if(l)return l;const c=new Fl(o,s.hash);return r.registerAssetReference(c),c}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Tr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(So&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ai(this.asset.scene,!0,!0),Ai(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,J.Current&&J.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,So&&console.log("Preload",this.url);const e=await Ar.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(So&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading.then(o=>this.asset);const t=J.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Failed loading: Invalid raw binary data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loading=ws().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else So&&console.log("Load async",this.url),this._loading=ws().loadSync(t,this.url,this.url,null,o=>{this.raiseProgressEvent(o)});const s=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(s),this._loading=void 0,s?(s[bf]=this,this._glbRoot&&(this._glbRoot[bf]=this),this.asset&&(this.asset[bf]=this),Zd(t),s.scene!==void 0&&(this.asset=s),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,s){const o=J.Current,r=new Bs;if(e instanceof A?r.parent=e:e&&(Object.assign(r,e),r.cloneAssign(e)),r.parent===void 0&&(r.parent=o.scene),this.mustLoad&&await this.loadAssetAsync(),So&&console.log("Instantiate",this.url,"parent:",e),this.asset){So&&console.log("Add to scene",this.asset);let l=Fl.currentlyInstantiating.get(this.url);if(l!==void 0&&l>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+l+")"),null;try{if(l===void 0&&(l=0),l+=1,Fl.currentlyInstantiating.set(this.url,l),t){r.context=o;const c=this.asset;c.guid=this.url;const h=rf(c,r,void 0,s);if(h)return h}else{const c=Ha(this.asset,r);if(c)return c}}finally{o.post_render_callbacks.push(()=>{l===void 0||l<0?l=0:l-=1,Fl.currentlyInstantiating.set(this.url,l)})}}else So&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};a(Tw,"currentlyInstantiating",new Map);let ce=Tw;class lR extends es{constructor(){super([ce],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ce.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof A){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const s=e,o=t.context,r=s.guid??s.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new ce(r,void 0,s);return o.addressables.registerAssetReference(c),c}return null}}new lR;const cR=Promise.resolve(null),Ew=class vm{constructor(e){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=e}static getOrCreate(e){let t=vm.imageReferences.get(e);return t||(t=new vm(e),vm.imageReferences.set(e,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}createTexture(){return this.url?(this.loader||(this.loader=new Sa),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>{var t;return e&&!((t=e.name)!=null&&t.length)&&(e.name=this.url.split("/").pop()??this.url),e})):(console.error("Can not load texture without url"),cR)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const s=document.createElement("img");s.addEventListener("load",()=>{this._bitmap=createImageBitmap(s).then(o=>(this._bitmapObject=o,e(o),o))}),s.addEventListener("error",o=>{console.error("Failed to load image:"+this.url,o),e(null)}),s.src=this.url}),this._bitmap)}};a(Ew,"imageReferences",new Map);let _f=Ew;class Aw extends es{constructor(){super([_f],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=vo(t.gltfId,e);return _f.getOrCreate(s)}}}new Aw;const Iw=class bm{constructor(e){a(this,"url"),a(this,"res"),this.url=e}static getOrCreate(e){let t=bm.cache.get(e);return t||(t=new bm(e),bm.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}};a(Iw,"cache",new Map);let wf=Iw;class Lw extends es{constructor(){super([wf],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=vo(t.gltfId,e);return wf.getOrCreate(s)}}}new Lw;class hR{constructor(e){a(this,"context"),a(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Ga{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const s of e.children)this.tryGetAnimationClipsFromObjectHierarchy(s,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations){console.debug("No animations found in file");return}for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=Ca.parseTrackName(c.name);let d=Ca.findNode(e.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=e.scene.getObjectByProperty("uuid",p),!d)continue}let u=s(d);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,r)}u.addClip&&u.addClip(r)}}function s(o){var r;if(!o)return null;const l=(r=o.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return o}return s(o.parent)}}}function*xf(n,e=null){const t=e?e.time:J.Current.time,s=t.time;for(;t.time-s<n;)yield}function*dR(n){for(let e=0;e<n;e++)yield}function*jw(n){let e=!0;for(n.then(()=>e=!1),n.catch(()=>e=!1);e;)yield}const Dw="NEEDLE_lightmaps",Pc=C("debuglightmapsextension")||C("debuglightmaps");var Ys=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(Ys||{});class uR{constructor(e,t,s){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=e,this.registry=t,this.source=s}get name(){return Dw}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[Dw];if(s){const o=s.textures;return o!=null&&o.length?(Pc&&console.log(s),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Pc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Pc&&console.log("Load texture from gltf",d.pointer),u=cf(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Pc&&console.log("Load texture from path",d.pointer);const p=vo(this.source,d.pointer);let g;p.endsWith(".exr")?g=new Pd(this.parser.options.manager):p.endsWith(".hdr")?g=new Vm(this.parser.options.manager):g=new Sa(this.parser.options.manager),u=g.loadAsync(p,void 0).then(f=>this.resolveTexture(d,f))}else d.pointer;u&&c.push(u)}const h=await eg(c);h!=null&&h.anyFailed&&B()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(e,t){const s=t;Pc&&console.log("Lightmap loaded:",s),s!=null&&s.isTexture&&(this.registry?(s.colorSpace=On,this.registry.registerTexture(this.source,e.type,s,e.index)):console.log(Ys[e.type],e.pointer,s))}}const qa=!!C("debuglightmaps");class pR{constructor(e){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,s,o){qa&&console.log("Registering ",Ys[t]+' "'+e+'"',s),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const r=this._lightmaps.get(e),l=r?.get(t)??[];l.length<o&&(l.length=o+1),l[o]=s,r?.set(t,l)}tryGetLightmap(e,t=0){return this.tryGet(e,Ys.Lightmap,t)}tryGetSkybox(e){return qa&&console.log("[Get Skybox]",e,this._lightmaps),this.tryGet(e,Ys.Skybox,0)}tryGetReflection(e){return qa&&console.log("[Get Reflection]",e,this._lightmaps),this.tryGet(e,Ys.Reflection,0)}tryGet(e,t,s){if(!e)return qa&&console.warn("Missing source id"),null;const o=this._lightmaps.get(e);if(!o)return qa&&console.warn(`[Lighting] No ${Ys[t]} texture entry for`,e),null;const r=o.get(t);return r===void 0?(qa&&console.warn(`[Lighting] No ${Ys[t]} texture for`,e,"index",s),null):!(r!=null&&r.length)||r.length<=s?null:r[s]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
|
|
191
|
+
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),fw()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===e.prototype)if(fw()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),t)t.push(r);else return r;l=Object.getPrototypeOf(l)}}return t||null}function Mr(n,e){const t=_w(n,e);return t?Array.isArray(t)?t[0]:t:null}function _c(n,e,t,s=!0){return t||(t=[]),s&&(t.length=0),_w(n,e,t),t}function wc(n,e,t){var s;if(t===!1&&n[En]===!1)return null;const o=Mr(n,e);if(t===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((s=n?.children)==null?void 0:s.length);r++){const l=wc(n.children[r],e);if(l)return l}return null}function Wa(n,e,t,s=!0){var o;t||(t=[]),s&&(t.length=0),_c(n,e,t,!1);for(let r=0;r<((o=n?.children)==null?void 0:o.length);r++)Wa(n.children[r],e,t,!1);return t}function xc(n,e){if(!n)return null;if(Array.isArray(n)){for(let s=0;s<n.length;s++){const o=oR(n[s]),r=xc(o,e);if(r)return r}return null}return Mr(n,e)||(n.parent?xc(n.parent,e):null)}function ou(n,e,t,s=!0){return t||(t=[]),s&&(t.length=0),n?(_c(n,e,t,!1),n.parent?ou(n.parent,e,t,!1):t):t}function Sc(n,e=void 0,t=!0){if(!n)return null;if(!e&&(e=J.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let s=e;return s.isScene||(s=e?.scene),s&&wc(s,n,t)||null}function ww(n,e,t=void 0){if(!n)return e??[];if(e||(e=[]),e.length=0,!t&&(t=J.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const s=t;return s&&Wa(s,n,e,!1),e}function ru(n){n&&n.isObject3D===!0&&mw(n,A)}A.prototype.SetActive=function(n){this.visible=n},A.prototype.setActive=function(n){this.visible=n},A.prototype.destroy=function(){Ai(this)},A.prototype.addComponent=function(n,e){return Ei(this,n,e)},A.prototype.addNewComponent=function(n,e){return Ei(this,n,e)},A.prototype.removeComponent=function(n){return gf(this,n)},A.prototype.getOrAddComponent=function(n,e){return bc(this,n,e)},A.prototype.getComponent=function(n){return Mr(this,n)},A.prototype.getComponents=function(n,e){return _c(this,n,e)},A.prototype.getComponentInChildren=function(n){return wc(this,n)},A.prototype.getComponentsInChildren=function(n,e){return Wa(this,n,e)},A.prototype.getComponentInParent=function(n){return xc(this,n)},A.prototype.getComponentsInParent=function(n,e){return ou(this,n,e)},Object.getOwnPropertyDescriptor(A.prototype,"activeSelf")||Object.defineProperty(A.prototype,"activeSelf",{get:function(){return Va(this)},set:function(n){Cc(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldPosition")||Object.defineProperty(A.prototype,"worldPosition",{get:function(){return this instanceof Hv?ee(this.object):ee(this)},set:function(n){lt(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldQuaternion")||Object.defineProperty(A.prototype,"worldQuaternion",{get:function(){return this instanceof Hv?Se(this.object):Se(this)},set:function(n){Yi(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldRotation")||Object.defineProperty(A.prototype,"worldRotation",{get:function(){return Id(this)},set:function(n){Db(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldScale")||Object.defineProperty(A.prototype,"worldScale",{get:function(){return Ge(this)},set:function(n){Ta(this,n)}}),Object.getOwnPropertyDescriptor(A.prototype,"worldForward")||Object.defineProperty(A.prototype,"worldForward",{get:function(){return X().set(0,0,1).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(A.prototype,"worldRight")||Object.defineProperty(A.prototype,"worldRight",{get:function(){return X().set(1,0,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(A.prototype,"worldUp")||Object.defineProperty(A.prototype,"worldUp",{get:function(){return X().set(0,1,0).applyQuaternion(Se(this))}}),gw(A);class he extends re{constructor(e,t,s,o){super(),a(this,"alpha",1),typeof e=="number"&&typeof t=="number"&&typeof s=="number"?(this.set(e,t,s),this.alpha=typeof o=="number"?o:1):e!==void 0&&(this.set(e),this.alpha=1)}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}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 s=e;return s.alpha!=null&&(this.alpha=W.lerp(this.alpha,s.alpha,t)),super.lerp(e,t)}lerpColors(e,t,s){const o=e,r=t;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,s)),super.lerpColors(e,t,s)}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 he(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),s=t>>24&255,o=t>>16&255,r=t>>8&255,l=t>>0&255;return new he(s/255,o/255,r/255,l/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),s=t>>16&255,o=t>>8&255,r=t>>0&255;return new he(s/255,o/255,r/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new he(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 he(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new he(e[0],e[1],e[2],e[3]);if(e.length===3)return new he(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new he(e)}}const au=C("debuggetcomponent"),Rr=C("debuginstantiate");class Bs{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var e,t,s;const o=new Bs;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(e=this.position)==null?void 0:e.clone(),o.rotation=(t=this.rotation)==null?void 0:t.clone(),o.scale=(s=this.scale)==null?void 0:s.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(e){var t,s,o;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(s=e.rotation)==null?void 0:s.clone(),this.scale=(o=e.scale)==null?void 0:o.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function Va(n){return n.visible}function Cc(n,e){return typeof e=="number"&&(e=e>.5),n.visible=e,n.visible}function xw(n){return n[En]||lu(n)}function Sw(n,e){n[$_]=e}function lu(n){return ms.isUsingInstancing(n)}function ff(n,e){return Ma(n,e,!0,!0)}const Cw=Symbol("isDestroyed");function Tr(n){return n[Cw]}function Pw(n,e){n[Cw]=e}const yf=Symbol("isDontDestroy");function $a(n,e=!0){n[yf]=e}const cu=[],hu=[];function Ai(n,e=!0,t=!1){cu.length=0,hu.length=0,vf(n,e,!0);for(const s of cu)s.gameObject=null,s.context=null;for(const s of hu)Pw(s,!0),t&&Te(s),W_(s);hu.length=0,cu.length=0}function vf(n,e=!0,t=!0){var s;if(n==null)return;const o=n;if(o.isComponent){if(o[yf])return;cu.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(n[yf])return;const r=n;au&&console.log(r),hu.push(r);const l=(s=r.userData)==null?void 0:s.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];vf(d,e,!1),l.length<c&&(c=l.length,h--)}}if(e&&r.children)for(const c of r.children)vf(c,e,!1);t&&r.removeFromParent()}function Er(n,e,t=!0){return Ow(n,e,t)}function*du(n,e,t=!1,s=999,o=0){if(n!=null&&n.userData.components&&!(o>s)){for(const r of n.userData.components)e&&r?.isComponent===!0&&r instanceof e?yield r:yield r;if(t===!0)for(const r of n.children)yield*du(r,e,!0,s,o+1)}}function Ow(n,e,t,s=0){var o;if(n){if(n.isObject3D,s>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=n.userData)!=null&&o.components)for(let r=0;r<n.userData.components.length;r++){const l=n.userData.components[r];if(l?.isComponent===!0){const c=e(l);if(c!==void 0)return c}}if(t&&n.children){const r=s+1;for(let l=0;l<n.children.length;l++){const c=n.children[l];if(!c)continue;const h=Ow(c,e,t,r);if(h!==void 0)return h}}}}function Ha(n,e){if("isAssetReference"in n)return n.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new Bs,t.position=e):t=e);let s=J.Current;t!=null&&t.context&&(s=t.context),au&&s.alias&&console.log("context",s.alias),t&&!t.idProvider&&(t.idProvider=new jt(Date.now()));const o=[],r={},l={},c=kw(s,n,t,o,r,l);c&&(aR(r),rR(l,r)),au&&(Ld(n,!0),Ld(c,!0));const h={};if(t?.components!==!1){for(const d in o){const u=o[d],p=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),h[p]=u.guid,au&&console.log(u.name,u.guid)),_u(u,s),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Zd(s)}return c}function kw(n,e,t,s,o,r){var l;if(!e||e[Ri])return null;const c=e.userData;e.userData={};const h=e.children;e.children=[];const d=e.clone(!1);if(ru(d),e.userData=c,e.children=h,o[e.uuid]={original:e,clone:d},Rr&&console.log("ADD",e,d),e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:d}),t?.visible!==void 0&&(d.visible=t.visible),t!=null&&t.idProvider){d.uuid=t.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}e.animations&&e.animations.length>0&&(d.animations=[...e.animations]);const u=e.parent;if(u&&u.add(d),t!=null&&t.position?lt(d,t.position):d.position.copy(e.position),t!=null&&t.rotation?Yi(d,t.rotation):d.quaternion.copy(e.quaternion),t!=null&&t.scale?d.scale.copy(t.scale):d.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let p=null;if(typeof t.parent=="string"?p=Ma(t.parent,n.scene,!0):p=t.parent,p){const g=t.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[p,g]of Object.entries(e.userData))p!=="components"&&(d.userData[p]=g);if((l=e.userData)!=null&&l.components){const p=e.userData.components,g=[];d.userData.components=g;for(let f=0;f<p.length;f++){const y=p[f],v=new y.constructor;Na(v,y,void 0,{}),y[rc]!==void 0&&(v[rc]=y[rc]),g.push(v),v.gameObject=d,s.push(v),o[y.guid]={original:y,clone:v},pc.dispatchComponentLifecycleEvent("component-added",v)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const p in e.children){const g=e.children[p],f=kw(n,g,t,s,o,r);f&&(o[f.uuid]={original:g,clone:f},d.add(f))}return d}function rR(n,e){for(const t in n){const s=n[t],o=s.original,r=o.skeleton,l=s.clone;if(!r){console.warn("Skinned mesh has no skeleton?",s);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=e[p.uuid].clone;d.push(g)}}for(const t in n){const s=n[t].clone;s.skeleton.update(),s.bind(s.skeleton,s.bindMatrix),s.updateMatrixWorld(!0)}}function aR(n){var e;for(const t in n){const s=n[t].clone;if(s!=null&&s.isObject3D&&(e=s?.userData)!=null&&e.components)for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=Mw(r,c,p,n);g!==void 0?(Rr&&console.log("Found new instance for",c,p,"->",g),d.push(g)):(Rr&&console.warn("Could not find new instance for",c,p),d.push(p))}}else if(typeof h=="object"){const d=Mw(r,c,h,n);d!==void 0?r[c]=d:Rr&&console.warn("Could not find new instance for",c,h)}}}}function Mw(n,e,t,s){var o,r;if(t!=null)if(t.isComponent===!0){const l=t.gameObject;if(l){const c=l.uuid,h=(o=s[c])==null?void 0:o.clone;if(!h){Rr&&console.log("reference did not change",e,n,t);return}const d=l.userData.components.indexOf(t);if(d>=0&&h.isObject3D)return Rr&&console.log(e,c),h.userData.components[d];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const l=t;if(l){const c=l.uuid,h=(r=s[c])==null?void 0:r.clone;if(h)return Rr&&console.log(e,"old",t,"new",h),h}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(s)}}var Ar;(n=>{n.baseUrl="https://networking.needle.tools";function e(h){return Zv(new Uint8Array(h))}n.hashMD5=e;function t(h){const d=Zv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}n.hashMD5_Base64=t;function s(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}n.hashSha256=s;function o(h){const d=h.filesize/1024/1024;return Js()?d<50:d<5}n.canUpload=o;async function r(h,d){var u;const p=n.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const f=g.byteLength,y=f/1024/1024;if(y>50)return d?.silent!==!0&&be(`File (${y.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${y.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Js()&&y>5)return d?.silent!==!0&&be('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${y.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(f<1)return console.warn(`Your file is too small for uploading (${y.toFixed(1)}MB). Min size is 1 byte`),null;const v=t(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:f.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},_=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(w=>w.json()).catch(w=>(console.error(w),null));if(_==null)return console.warn("Upload failed..."),null;if("error"in _)return console.error(_.error),null;if("upload"in _&&_.upload){let w=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(D=>{var z;return(z=d?.onProgress)==null||z.call(null,{progress01:1,state:"finished"}),D}).catch(D=>D)};console.debug("Uploading file",_.upload);let x=!1,k=null;for(let M=0;M<3;M++)try{if(x)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await w(_.upload);T instanceof Error?(k=T,await $s(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),x=!0)}catch(T){console.error(T)}if(!x)return console.error(k?.message||"Failed to upload file"),null}if("download"in _){const w=p+_.download;return console.debug("File found in blob storage",w),{key:_.key,success:!0,download_url:w}}return null}n.upload=r;function l(h){return`${n.baseUrl}/api/needle/blob/${h}`}n.getBlobUrlForKey=l;async function c(h,d){const u=new Am;u.setResponseType("arraybuffer");const p=await u.loadAsync(h,g=>{d&&d.call(null,g)});return p instanceof ArrayBuffer?new Uint8Array(p):(console.error("Download failed, no arraybuffer returned"),null)}n.download=c})(Ar||(Ar={}));const So=C("debugaddressables");class Rw{constructor(e){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const s=this._assetReferences[t];s?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const bf=Symbol("assetReference"),Tw=class Fl{constructor(e,t,s=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_urlName"),a(this,"_progressListeners",[]),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=e;const o=e.lastIndexOf("/");if(o>=0){this._urlName=e.substring(o+1);const r=this._urlName.lastIndexOf(".");r>=0&&(this._urlName=this._urlName.substring(0,r))}else this._urlName=e;s!==null&&(this.asset=s),iw(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(e,t){if(!t&&(t=J.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const s=t.addressables,o=s.findAssetReference(e);if(o)return o;const r=new Fl(e,t.hash);return s.registerAssetReference(r),r}static getOrCreate(e,t,s){if(typeof e=="string"){if(!s&&(s=J.Current,!s))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else s=e.context,e=e.sourceId;const o=vo(e,t);So&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",o);const r=s.addressables,l=r.findAssetReference(o);if(l)return l;const c=new Fl(o,s.hash);return r.registerAssetReference(c),c}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Tr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(So&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ai(this.asset.scene,!0,!0),Ai(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,J.Current&&J.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,So&&console.log("Preload",this.url);const e=await Ar.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(So&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading.then(o=>this.asset);const t=J.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Failed loading: Invalid raw binary data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loading=ws().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else So&&console.log("Load async",this.url),this._loading=ws().loadSync(t,this.url,this.url,null,o=>{this.raiseProgressEvent(o)});const s=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(s),this._loading=void 0,s?(s[bf]=this,this._glbRoot&&(this._glbRoot[bf]=this),this.asset&&(this.asset[bf]=this),Zd(t),s.scene!==void 0&&(this.asset=s),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,s){const o=J.Current,r=new Bs;if(e instanceof A?r.parent=e:e&&(Object.assign(r,e),r.cloneAssign(e)),r.parent===void 0&&(r.parent=o.scene),this.mustLoad&&await this.loadAssetAsync(),So&&console.log("Instantiate",this.url,"parent:",e),this.asset){So&&console.log("Add to scene",this.asset);let l=Fl.currentlyInstantiating.get(this.url);if(l!==void 0&&l>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+l+")"),null;try{if(l===void 0&&(l=0),l+=1,Fl.currentlyInstantiating.set(this.url,l),t){r.context=o;const c=this.asset;c.guid=this.url;const h=rf(c,r,void 0,s);if(h)return h}else{const c=Ha(this.asset,r);if(c)return c}}finally{o.post_render_callbacks.push(()=>{l===void 0||l<0?l=0:l-=1,Fl.currentlyInstantiating.set(this.url,l)})}}else So&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};a(Tw,"currentlyInstantiating",new Map);let ce=Tw;class lR extends es{constructor(){super([ce],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ce.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof A){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const s=e,o=t.context,r=s.guid??s.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new ce(r,void 0,s);return o.addressables.registerAssetReference(c),c}return null}}new lR;const cR=Promise.resolve(null),Ew=class vm{constructor(e){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=e}static getOrCreate(e){let t=vm.imageReferences.get(e);return t||(t=new vm(e),vm.imageReferences.set(e,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}createTexture(){return this.url?(this.loader||(this.loader=new Sa),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>{var t;return e&&!((t=e.name)!=null&&t.length)&&(e.name=this.url.split("/").pop()??this.url),e})):(console.error("Can not load texture without url"),cR)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const s=document.createElement("img");s.addEventListener("load",()=>{this._bitmap=createImageBitmap(s).then(o=>(this._bitmapObject=o,e(o),o))}),s.addEventListener("error",o=>{console.error("Failed to load image:"+this.url,o),e(null)}),s.src=this.url}),this._bitmap)}};a(Ew,"imageReferences",new Map);let _f=Ew;class Aw extends es{constructor(){super([_f],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=vo(t.gltfId,e);return _f.getOrCreate(s)}}}new Aw;const Iw=class bm{constructor(e){a(this,"url"),a(this,"res"),this.url=e}static getOrCreate(e){let t=bm.cache.get(e);return t||(t=new bm(e),bm.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}};a(Iw,"cache",new Map);let wf=Iw;class Lw extends es{constructor(){super([wf],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=vo(t.gltfId,e);return wf.getOrCreate(s)}}}new Lw;class hR{constructor(e){a(this,"context"),a(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Ga{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const s of e.children)this.tryGetAnimationClipsFromObjectHierarchy(s,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations){console.debug("No animations found in file");return}for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=Ca.parseTrackName(c.name);let d=Ca.findNode(e.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=e.scene.getObjectByProperty("uuid",p),!d)continue}let u=s(d);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,r)}u.addClip&&u.addClip(r)}}function s(o){var r;if(!o)return null;const l=(r=o.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return o}return s(o.parent)}}}function*xf(n,e=null){const t=e?e.time:J.Current.time,s=t.time;for(;t.time-s<n;)yield}function*dR(n){for(let e=0;e<n;e++)yield}function*jw(n){let e=!0;for(n.then(()=>e=!1),n.catch(()=>e=!1);e;)yield}const Dw="NEEDLE_lightmaps",Pc=C("debuglightmapsextension")||C("debuglightmaps");var Ys=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(Ys||{});class uR{constructor(e,t,s){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=e,this.registry=t,this.source=s}get name(){return Dw}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[Dw];if(s){const o=s.textures;return o!=null&&o.length?(Pc&&console.log(s),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Pc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Pc&&console.log("Load texture from gltf",d.pointer),u=cf(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Pc&&console.log("Load texture from path",d.pointer);const p=vo(this.source,d.pointer);let g;p.endsWith(".exr")?g=new Pd(this.parser.options.manager):p.endsWith(".hdr")?g=new Vm(this.parser.options.manager):g=new Sa(this.parser.options.manager),u=g.loadAsync(p,void 0).then(f=>this.resolveTexture(d,f))}else d.pointer;u&&c.push(u)}const h=await eg(c);h!=null&&h.anyFailed&&B()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(e,t){const s=t;Pc&&console.log("Lightmap loaded:",s),s!=null&&s.isTexture&&(this.registry?(s.colorSpace=On,this.registry.registerTexture(this.source,e.type,s,e.index)):console.log(Ys[e.type],e.pointer,s))}}const qa=!!C("debuglightmaps");class pR{constructor(e){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,s,o){qa&&console.log("Registering ",Ys[t]+' "'+e+'"',s),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const r=this._lightmaps.get(e),l=r?.get(t)??[];l.length<o&&(l.length=o+1),l[o]=s,r?.set(t,l)}tryGetLightmap(e,t=0){return this.tryGet(e,Ys.Lightmap,t)}tryGetSkybox(e){return qa&&console.log("[Get Skybox]",e,this._lightmaps),this.tryGet(e,Ys.Skybox,0)}tryGetReflection(e){return qa&&console.log("[Get Reflection]",e,this._lightmaps),this.tryGet(e,Ys.Reflection,0)}tryGet(e,t,s){if(!e)return qa&&console.warn("Missing source id"),null;const o=this._lightmaps.get(e);if(!o)return qa&&console.warn(`[Lighting] No ${Ys[t]} texture entry for`,e),null;const r=o.get(t);return r===void 0?(qa&&console.warn(`[Lighting] No ${Ys[t]} texture for`,e,"index",s),null):!(r!=null&&r.length)||r.length<=s?null:r[s]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
|
|
192
192
|
vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
|
|
193
193
|
vec4 lightMapTexel = texture2D( lightMap, lUv);
|
|
194
194
|
// The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
|
|
@@ -853,10 +853,10 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
|
|
|
853
853
|
padding-left: 25px;
|
|
854
854
|
border-radius: .5em;
|
|
855
855
|
border: 2px solid rgba(160,160,160,.3);
|
|
856
|
-
`,o=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_s}`;(e=J.Current)!=null&&e.xr?console.log(o):console.log("%c "+o,s)}async function UR(n){var e,t;if(!window.crossOriginIsolated){if(Ks==="pro"){const s=(e=n?.domElement)==null?void 0:e.getAttribute("no-telemetry");if(s===""||s==="true"||s==="1"){Ii&&console.debug("Telemetry is disabled");return}Ii&&console.debug("Telemetry attribute: "+s)}try{const s="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(s){const o=window.location.href.split("?")[0];let r="api/v2/new/request";s.endsWith("/")||(r="/"+r);const l=Ks,c=`${s}${r}`;Ii&&console.debug("Sending beacon");const h={license:l,url:o,hostname:window.location.hostname,pathname:window.location.pathname,version:_s,generator:Dd,build_time:wg,public_key:Ea},d=(t=navigator.sendBeacon)==null?void 0:t.call(navigator,c,JSON.stringify(h));Ii&&console.debug("Sent beacon: "+d)}}catch(s){Ii&&console.log("Failed to send non-commercial usage message to analytics backend",s)}}}function nx(n,e){return jn(n,me.ContextCreated,e),()=>wo(n,me.ContextCreated)}function zR(n,e){return jn(n,me.ContextClearing,e),()=>wo(n,me.ContextClearing)}function NR(n,e){return jn(n,me.ContextDestroying,e),()=>wo(n,me.ContextDestroying)}function jf(n,e){return jn(n,Oe.Start,e),()=>wo(n,Oe.Start)}function ox(n,e){return jn(n,Oe.Update,e),()=>wo(n,Oe.Update)}function WR(n,e){return jn(n,Oe.OnBeforeRender,e),()=>wo(n,Oe.OnBeforeRender)}function VR(n,e){return jn(n,Oe.OnAfterRender,e),()=>wo(n,Oe.OnAfterRender)}const $R=C("debugdecoders");let Df=null;function rx(){if(!Df){const n=Wm(null);Df={dracoLoader:n.dracoLoader,ktx2Loader:n.ktx2Loader,meshoptDecoder:n.meshoptDecoder}}return Df}function ax(n){n!==void 0&&typeof n=="string"&&QP(n)}function lx(n){if(n!==void 0&&typeof n=="string"&&n!=="js"){const e=rx();$R&&console.log("Setting draco decoder type to",n),e.dracoLoader.setDecoderConfig({type:n})}}function cx(n){n!==void 0&&typeof n=="string"&&XP(n)}function Bf(n,e){const t=rx();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),GP(n),n.dracoLoader||n.setDRACOLoader(t.dracoLoader),n.ktx2Loader||n.setKTX2Loader(t.ktx2Loader),n.meshoptDecoder||n.setMeshoptDecoder(t.meshoptDecoder),qP(n,{progressive:!0}),n}const jr=function(n){return m(n)},m=function(n){if(n===void 0&&(n=null),!Array.isArray(n))n=hx(n);else for(let e=0;e<n.length;e++){const t=n[e];n[e]=hx(t)}return function(e,t){if(!e){console.error("Found @serializable decorator without a target");return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const s=e.$serializedTypes=e.$serializedTypes||{};s[t]=n}};function hx(n){var e,t;switch((t=(e=n?.prototype)==null?void 0:e.constructor)==null?void 0:t.name){case"Number":case"String":case"Boolean":return null}return n}const Oo=C("debughotreload");let Rc=!1;const Tc=new Map;function HR(){return Rc}function Ff(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function dx(n){var e;if(Rc){Oo&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",n);return}Oo&&console.log("[Needle Engine] Registering hot reload instance",n);const t=n.constructor.name;Tc.has(t)?(e=Tc.get(t))==null||e.push(n):Tc.set(t,[n])}function ux(n){if(Rc){Oo&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",n);return}Oo&&console.log("[Needle Engine] Unregistering hot reload instance",n);const e=n.constructor.name,t=Tc.get(e);if(!t)return;const s=t.indexOf(n);s!==-1&&t.splice(s,1)}let px=!1;function GR(){if(Oo||px)return;px=!0;const n=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}}n.apply(console,e)}}function qR(n){Oo&&console.log("[HMR] Apply changes",n,Object.keys(n)),GR();for(const e of Object.keys(n))try{Rc=!0;const t=R.get(e);if(!t){Oo&&console.log("[HMR] Type not found: "+e);continue}const s=n[e],o=Tc.get(s.name);let r="[Needle Engine] Updating type: "+e;const l=o?.length??-1;l>0?r+=" x"+l:r+=" (No instances registered)",console.log(r);const c=Object.getOwnPropertyNames(t.prototype),h=Object.getOwnPropertyDescriptors(s.prototype);for(const d in h)h[d].writable&&(t.prototype[d]=n[e].prototype[d]);for(const d of c)h[d]||delete t.prototype[d];if(o){const d=new s,u=Object.getOwnPropertyDescriptors(d);for(const p of o){const g=p,f=g.isComponent===!0,y=f?g.activeAndEnabled:!0,v=f?g.context:void 0;try{if(f&&v&&Bn(g,v),f&&y&&(g.enabled=!1),p.onBeforeHotReloadFields&&p.onBeforeHotReloadFields()===!1)continue;for(const b in u)if(u[b].writable){if(p[b]===void 0)p[b]=d[b];else if(typeof p[b]=="function"&&!p[b].prototype){const _=p[b],w=_.name,x="bound ";if(w===x)continue;const k=_.name.substring(x.length),M=s.prototype[k];M&&(p[b]=M.bind(p))}}p.onAfterHotReloadFields&&p.onAfterHotReloadFields()}finally{f&&v&&Zg(g,v),f&&y&&(g.enabled=!0)}}}}catch(t){if(Oo)console.error(t);else return!1}finally{Rc=!1,Hs(Mi.Log,"Script changes applied (HMR)")}return!0}class P extends A{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(e){return Tr(e)}static setActive(e,t,s=!0){e&&(Cc(e,t),Jd(e),t&&s&&G_(J.Current,e))}static isActiveSelf(e){return Va(e)}static isActiveInHierarchy(e){return xw(e)}static markAsInstancedRendered(e,t){Sw(e,t)}static isUsingInstancing(e){return lu(e)}static foreachComponent(e,t,s=!0){return Er(e,t,s)}static instantiateSynced(e,t){return e?rf(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Ha(e,t)}static destroySynced(e,t,s=!0){if(!e)return;const o=e;t=t??J.Current,yc(o,t.connection,s)}static destroy(e,t=!0){return Ai(e,t)}static add(e,t,s){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}s||(s=J.Current),t.add(e),Cc(e,!0),Jd(e),s?P.foreachComponent(e,o=>{Zg(o,s),!o.__internalDidAwakeAndStart&&s.new_script_start.includes(o)===!1&&s.new_script_start.push(o)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),Cc(e,!1),Jd(e),P.foreachComponent(e,s=>{EM(s)},!0))}static invokeOnChildren(e,t,...s){this.invoke(e,t,!0,s)}static invoke(e,t,s=!1,...o){e&&this.foreachComponent(e,r=>{const l=r[t];l&&typeof l=="function"&&l?.call(r,...o)},s)}static addNewComponent(e,t,s,o=!0){return Ei(e,t,s,{callAwake:o})}static addComponent(e,t,s,o){return Ei(e,t,s,o)}static moveComponent(e,t){return Ei(e,t)}static removeComponent(e){return gf(e.gameObject,e),e}static getOrAddComponent(e,t){return bc(e,t)}static getComponent(e,t){return e===null?null:Mr(e,t)}static getComponents(e,t,s=null){return e===null?s??[]:_c(e,t,s)}static findByGuid(e,t){return ff(e,t)}static findObjectOfType(e,t,s=!0){return Sc(e,t??J.Current,s)}static findObjectsOfType(e,t){const s=[];return ww(e,s,t),s}static getComponentInChildren(e,t){return wc(e,t)}static getComponentsInChildren(e,t,s=null){return Wa(e,t,s??void 0)}static getComponentInParent(e,t){return xc(e,t)}static getComponentsInParent(e,t,s=null){return ou(e,t,s)}static getAllComponents(e){var t;const s=(t=e.userData)==null?void 0:t.components;return s?[...s]:[]}static*iterateComponents(e){var t;const s=(t=e?.userData)==null?void 0:t.components;if(s&&Array.isArray(s))for(let o=0;o<s.length;o++)yield s[o]}}const Su=class _m{constructor(e){a(this,"__context"),a(this,"__name"),a(this,"gameObject"),a(this,"guid","invalid"),a(this,"sourceId"),a(this,"__didAwake",!1),a(this,"__didStart",!1),a(this,"__didEnable",!1),a(this,"__isEnabled"),a(this,"__destroyed",!1),a(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Ff()&&dx(this)}get isComponent(){return!0}get context(){return this.__context??J.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){var e,t;return(t=(e=this.gameObject)==null?void 0:e.userData)==null?void 0:t.layer}get name(){var e,t;return(e=this.gameObject)!=null&&e.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.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(){var e;return(e=this.gameObject)==null?void 0:e.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){var e;return(e=this.gameObject)==null?void 0:e.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[En];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[En]=e)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=Oe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=Oe.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__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 s=e[t];typeof s!="function"&&(this[t]=s)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(B()&&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(){var e;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((e=this.onDestroy)==null||e.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),vw(this),Ff()&&ux(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){B()&&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){lt(this.gameObject,e)}setWorldPosition(e,t,s){vr(this.gameObject,e,t,s)}get worldQuaternion(){return Se(this.gameObject)}set worldQuaternion(e){Yi(this.gameObject,e)}setWorldQuaternion(e,t,s,o){ug(this.gameObject,e,t,s,o)}get worldEuler(){return pg(this.gameObject)}set worldEuler(e){mg(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,s,o=!0){Jl(this.gameObject,e,t,s,o)}get forward(){return _m._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return _m._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return _m._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const s=this._eventListeners[e].indexOf(t);s>=0&&this._eventListeners[e].splice(s,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let s=0;s<t.length;s++)t[s](e);return!1}};a(Su,"_forward",new S),a(Su,"_right",new S),a(Su,"_up",new S);let j=Su;const XR=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:j,Component:j,GameObject:P},Symbol.toStringTag,{value:"Module"}));var QR=Object.defineProperty,mx=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&QR(e,t,o),o};class Ec extends j{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"width",0),a(this,"centered",!0),a(this,"_centerPos")}awake(){this._centerPos=new S}update(){if(!this.from||!this.to)return;const e=ee(this.from).clone(),t=ee(this.to).clone(),s=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),lt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}mx([m(P)],Ec.prototype,"from"),mx([m(P)],Ec.prototype,"to");var YR=Object.defineProperty,KR=Object.getOwnPropertyDescriptor,Dr=(n,e,t,s)=>{for(var o=s>1?void 0:s?KR(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&YR(e,t,o),o};const ko=C("debuganimation");let gx=class{constructor(){a(this,"x"),a(this,"y")}};class Ut extends j{constructor(){super(...arguments),a(this,"playAutomatically",!0),a(this,"randomStartTime",!0),a(this,"minMaxSpeed"),a(this,"minMaxOffsetNormalized"),a(this,"loop",!0),a(this,"clampWhenFinished",!1),a(this,"_tempAnimationClipBeforeGameObjectExisted",null),a(this,"_tempAnimationsArray"),a(this,"mixer"),a(this,"_actions"),a(this,"_handles")}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}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 clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){ko&&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}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||[]}get actions(){return this._actions}set actions(e){this._actions=e}awake(){this.mixer=void 0,ko&&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(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const t=Math.floor(Math.random()*this.animations.length),s=this.animations[t];this.play(t,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*s.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){var t;return((t=this.actions)==null?void 0:t.find(s=>s.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!=null&&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){ko&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(o=>o.name===e));if(!e){console.error("Could not find clip",e);return}const s=this.actions.find(o=>o.getClip()===e);if(!s){console.error("Could not find action",e);return}t!=null&&t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop()}pause(e,t=!1){if(e===void 0){for(const o of this.actions)o.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){ko&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(o=>o.name===e));if(!e){console.error("Could not find clip",e);return}const s=this.actions.find(o=>o.getClip()===e);if(!s){console.error("Could not find action",e);return}s.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(ko&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){ko&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let s=e;if(typeof e=="number"){if(e>=this.animations.length){ko&&console.log("No animation at index",e);return}s=this.animations[e]}else typeof e=="string"&&(s=this.animations.find(r=>r.name===e));if(!s){console.error("Could not find clip",e);return}t||(t={});for(const r of this.actions)if(r.getClip()===s)return this.internalOnPlay(r,t);if(!s.tracks){console.warn("Clip is no AnimationClip",s);return}const o=this.mixer.clipAction(s);return this.actions.push(o),this.internalOnPlay(o,t)}internalOnPlay(e,t){var s=this.actions.find(r=>r===e);if(s===e&&s.isRunning()&&s.time<s.getClip().duration){const r=this.tryFindHandle(e);if(s.paused&&(s.paused=!1),r)return r.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const r of this.actions)r!=s&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop());if(t!=null&&t.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t!=null&&t.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const r=e.getClip();e.time=W.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration}else e.time>=e.getClip().duration&&(e.time=0);t!=null&&t.minMaxSpeed?e.timeScale=W.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?qC:Lm:e.loop=Lm,t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),ko&&console.log("PLAY",e.getClip().name,e);const o=new ZR(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new jm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Dr([m()],Ut.prototype,"playAutomatically",2),Dr([m()],Ut.prototype,"randomStartTime",2),Dr([m(gx)],Ut.prototype,"minMaxSpeed",2),Dr([m(gx)],Ut.prototype,"minMaxOffsetNormalized",2),Dr([m()],Ut.prototype,"loop",2),Dr([m()],Ut.prototype,"clampWhenFinished",2),Dr([m(fo)],Ut.prototype,"clips",1);class ZR{constructor(e,t,s,o){a(this,"mixer"),a(this,"action"),a(this,"promise",null),a(this,"_options"),a(this,"_resolveCallback",null),a(this,"_resolvedOrRejectedCallback"),a(this,"onFinished",r=>{r.action===this.action&&this.onResolve()}),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=o,this._options=s}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(){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const Cu=Symbol("objectIsAnimatedData");function fx(n,e,t){if(!n)return;if(n[Cu]===void 0){if(!t)return;n[Cu]=new Set}const s=n[Cu];t?s.add(e):s.has(e)&&s.delete(e)}function JR(n){if(!n)return!1;const e=n[Cu];return e!==void 0&&e.size>0}class eT{constructor(){a(this,"_context")}get context(){return this._context??J.Current}get isStateMachineBehaviour(){return!0}}class Ac{constructor(e,t,s,o){a(this,"name"),a(this,"nameHash"),a(this,"normalizedTime"),a(this,"length"),a(this,"speed"),a(this,"action"),a(this,"hasTransitions");var r;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=s,this.speed=o,this.action=e.motion.action||null,this.hasTransitions=((r=e.transitions)==null?void 0:r.length)>0||!1}}function yx(n,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??Cn.generateUUID(),index:-1,clip:new fo(n,0,[])}}var Mo=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(Mo||{}),Uf=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(Uf||{});const ht=C("debuganimatorcontroller"),Pu=C("debugrootmotion");class gs{constructor(e){a(this,"_speed",1),a(this,"normalizedStartOffset",0),a(this,"animator"),a(this,"model"),a(this,"_mixer"),a(this,"_activeState"),a(this,"_activeStates",[]),a(this,"_heldActions",[]),a(this,"rootMotionHandler"),this.model=e,ht&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const s=[];for(let r=0;r<e.length;r++){const l=e[r],c=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/l.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),c.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:r,motion:{name:l.name,clip:l,isLooping:t?.looping??!1},transitions:c,behaviours:[]};s.push(h)}const o={name:"AnimatorController",guid:new Dt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:s}}]};return new gs(o)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,o=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[t].stateMachine;for(const l of r.states)if(l.name===e||l.hash===e){ht&&console.log("transition to ",l),this.transitionTo(l,o,s);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,o;const r=typeof e=="string"?"name":"hash";return(o=(s=this.model)==null?void 0:s.parameters)==null?void 0:o.filter(l=>l[r]===e).forEach(l=>l.value=t)}getBool(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??!1}setFloat(e,t){var s,o;const r=typeof e=="string"?"name":"hash",l=(o=(s=this.model)==null?void 0:s.parameters)==null?void 0:o.filter(c=>c[r]===e);return l.forEach(c=>c.value=t),l?.length>0}getFloat(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??0}setInteger(e,t){var s,o;const r=typeof e=="string"?"name":"hash";return(o=(s=this.model)==null?void 0:s.parameters)==null?void 0:o.filter(l=>l[r]===e).forEach(l=>l.value=t)}getInteger(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??0}setTrigger(e){var t,s;ht&&console.log("SET TRIGGER",e);const o=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(r=>r[o]===e).forEach(r=>r.value=!0)}resetTrigger(e){var t,s;const o=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(r=>r[o]===e).forEach(r=>r.value=!1)}getTrigger(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}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 s of t.stateMachine.states)if(s.name===e||s.hash==e)return s}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,s=t<=0?0:Math.abs(e.time/t);return new Ac(this._activeState,s,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}dispose(){var e;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const t of this._activeStates)t.motion.clip&&this.mixer.uncacheAction(t.motion.clip,this.animator.gameObject)}(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)}bind(e){var t,s;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new jm(this.animator.gameObject),(s=this.context)==null||s.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;ht&&console.warn("AnimatorController clone()",this.model);const e=Xl(this.model,(t,s,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Bb(o)||o.tracks!==void 0||o instanceof gs));return console.assert(e!==this.model),new gs(e)}update(e){var t,s;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const o=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(o),this.animator.applyRootMotion&&((s=this.rootMotionHandler)==null||s.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const s=this._activeStates[t],o=s.motion;if(!o.action)this._activeStates.splice(t,1),t--;else{const r=o.action;r.weight=e,r.getEffectiveWeight()<=0&&!r.isRunning()&&(ht&&console.debug("REMOVE",s.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(ht||B())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const s=t.stateMachine;s.defaultState===void 0&&(ht&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),s.defaultState=0);const o=s.states[s.defaultState];this.transitionTo(o,0,this.normalizedStartOffset);break}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const s=this._activeState,o=s.motion.action;for(const l of s.transitions){if(!l.hasExitTime&&l.conditions.length<=0)continue;let c=!0;for(const h of l.conditions)if(!this.evaluateCondition(h)){c=!1;break}if(c)if(o){const h=s.motion.clip.duration,d=h<=0?1:Math.abs(o.time/h);let u=l.exitTime;o.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?o.timeScale>0?p=d>=l.exitTime:o.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const f=this.model.parameters.find(y=>y.name===g.parameter);f?.type===Uf.Trigger&&f.value&&(f.value=!1)}if(o.clampWhenFinished=!0,ht){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
|
|
856
|
+
`,o=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_s}`;(e=J.Current)!=null&&e.xr?console.log(o):console.log("%c "+o,s)}async function UR(n){var e,t;if(!window.crossOriginIsolated){if(Ks==="pro"){const s=(e=n?.domElement)==null?void 0:e.getAttribute("no-telemetry");if(s===""||s==="true"||s==="1"){Ii&&console.debug("Telemetry is disabled");return}Ii&&console.debug("Telemetry attribute: "+s)}try{const s="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(s){const o=window.location.href.split("?")[0];let r="api/v2/new/request";s.endsWith("/")||(r="/"+r);const l=Ks,c=`${s}${r}`;Ii&&console.debug("Sending beacon");const h={license:l,url:o,hostname:window.location.hostname,pathname:window.location.pathname,version:_s,generator:Dd,build_time:wg,public_key:Ea},d=(t=navigator.sendBeacon)==null?void 0:t.call(navigator,c,JSON.stringify(h));Ii&&console.debug("Sent beacon: "+d)}}catch(s){Ii&&console.log("Failed to send non-commercial usage message to analytics backend",s)}}}function nx(n,e){return jn(n,me.ContextCreated,e),()=>wo(n,me.ContextCreated)}function zR(n,e){return jn(n,me.ContextClearing,e),()=>wo(n,me.ContextClearing)}function NR(n,e){return jn(n,me.ContextDestroying,e),()=>wo(n,me.ContextDestroying)}function jf(n,e){return jn(n,Oe.Start,e),()=>wo(n,Oe.Start)}function ox(n,e){return jn(n,Oe.Update,e),()=>wo(n,Oe.Update)}function WR(n,e){return jn(n,Oe.OnBeforeRender,e),()=>wo(n,Oe.OnBeforeRender)}function VR(n,e){return jn(n,Oe.OnAfterRender,e),()=>wo(n,Oe.OnAfterRender)}const $R=C("debugdecoders");let Df=null;function rx(){if(!Df){const n=Wm(null);Df={dracoLoader:n.dracoLoader,ktx2Loader:n.ktx2Loader,meshoptDecoder:n.meshoptDecoder}}return Df}function ax(n){n!==void 0&&typeof n=="string"&&QP(n)}function lx(n){if(n!==void 0&&typeof n=="string"&&n!=="js"){const e=rx();$R&&console.log("Setting draco decoder type to",n),e.dracoLoader.setDecoderConfig({type:n})}}function cx(n){n!==void 0&&typeof n=="string"&&XP(n)}function Bf(n,e){const t=rx();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),GP(n),n.dracoLoader||n.setDRACOLoader(t.dracoLoader),n.ktx2Loader||n.setKTX2Loader(t.ktx2Loader),n.meshoptDecoder||n.setMeshoptDecoder(t.meshoptDecoder),qP(n,{progressive:!0}),n}const jr=function(n){return m(n)},m=function(n){if(n===void 0&&(n=null),!Array.isArray(n))n=hx(n);else for(let e=0;e<n.length;e++){const t=n[e];n[e]=hx(t)}return function(e,t){if(!e){console.error("Found @serializable decorator without a target");return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const s=e.$serializedTypes=e.$serializedTypes||{};s[t]=n}};function hx(n){var e,t;switch((t=(e=n?.prototype)==null?void 0:e.constructor)==null?void 0:t.name){case"Number":case"String":case"Boolean":return null}return n}const Oo=C("debughotreload");let Rc=!1;const Tc=new Map;function HR(){return Rc}function Ff(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function dx(n){var e;if(Rc){Oo&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",n);return}Oo&&console.log("[Needle Engine] Registering hot reload instance",n);const t=n.constructor.name;Tc.has(t)?(e=Tc.get(t))==null||e.push(n):Tc.set(t,[n])}function ux(n){if(Rc){Oo&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",n);return}Oo&&console.log("[Needle Engine] Unregistering hot reload instance",n);const e=n.constructor.name,t=Tc.get(e);if(!t)return;const s=t.indexOf(n);s!==-1&&t.splice(s,1)}let px=!1;function GR(){if(Oo||px)return;px=!0;const n=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}}n.apply(console,e)}}function qR(n){Oo&&console.log("[HMR] Apply changes",n,Object.keys(n)),GR();for(const e of Object.keys(n))try{Rc=!0;const t=R.get(e);if(!t){Oo&&console.log("[HMR] Type not found: "+e);continue}const s=n[e],o=Tc.get(s.name);let r="[Needle Engine] Updating type: "+e;const l=o?.length??-1;l>0?r+=" x"+l:r+=" (No instances registered)",console.log(r);const c=Object.getOwnPropertyNames(t.prototype),h=Object.getOwnPropertyDescriptors(s.prototype);for(const d in h)h[d].writable&&(t.prototype[d]=n[e].prototype[d]);for(const d of c)h[d]||delete t.prototype[d];if(o){const d=new s,u=Object.getOwnPropertyDescriptors(d);for(const p of o){const g=p,f=g.isComponent===!0,y=f?g.activeAndEnabled:!0,v=f?g.context:void 0;try{if(f&&v&&Bn(g,v),f&&y&&(g.enabled=!1),p.onBeforeHotReloadFields&&p.onBeforeHotReloadFields()===!1)continue;for(const b in u)if(u[b].writable){if(p[b]===void 0)p[b]=d[b];else if(typeof p[b]=="function"&&!p[b].prototype){const _=p[b],w=_.name,x="bound ";if(w===x)continue;const k=_.name.substring(x.length),M=s.prototype[k];M&&(p[b]=M.bind(p))}}p.onAfterHotReloadFields&&p.onAfterHotReloadFields()}finally{f&&v&&Zg(g,v),f&&y&&(g.enabled=!0)}}}}catch(t){if(Oo)console.error(t);else return!1}finally{Rc=!1,Hs(Mi.Log,"Script changes applied (HMR)")}return!0}class P extends A{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(e){return Tr(e)}static setActive(e,t,s=!0){e&&(Cc(e,t),Jd(e),t&&s&&G_(J.Current,e))}static isActiveSelf(e){return Va(e)}static isActiveInHierarchy(e){return xw(e)}static markAsInstancedRendered(e,t){Sw(e,t)}static isUsingInstancing(e){return lu(e)}static foreachComponent(e,t,s=!0){return Er(e,t,s)}static instantiateSynced(e,t){return e?rf(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Ha(e,t)}static destroySynced(e,t,s=!0){if(!e)return;const o=e;t=t??J.Current,yc(o,t.connection,s)}static destroy(e,t=!0){return Ai(e,t)}static add(e,t,s){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}s||(s=J.Current),t.add(e),Cc(e,!0),Jd(e),s?P.foreachComponent(e,o=>{Zg(o,s),!o.__internalDidAwakeAndStart&&s.new_script_start.includes(o)===!1&&s.new_script_start.push(o)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),Cc(e,!1),Jd(e),P.foreachComponent(e,s=>{EM(s)},!0))}static invokeOnChildren(e,t,...s){this.invoke(e,t,!0,s)}static invoke(e,t,s=!1,...o){e&&this.foreachComponent(e,r=>{const l=r[t];l&&typeof l=="function"&&l?.call(r,...o)},s)}static addNewComponent(e,t,s,o=!0){return Ei(e,t,s,{callAwake:o})}static addComponent(e,t,s,o){return Ei(e,t,s,o)}static moveComponent(e,t){return Ei(e,t)}static removeComponent(e){return gf(e.gameObject,e),e}static getOrAddComponent(e,t){return bc(e,t)}static getComponent(e,t){return e===null?null:Mr(e,t)}static getComponents(e,t,s=null){return e===null?s??[]:_c(e,t,s)}static findByGuid(e,t){return ff(e,t)}static findObjectOfType(e,t,s=!0){return Sc(e,t??J.Current,s)}static findObjectsOfType(e,t){const s=[];return ww(e,s,t),s}static getComponentInChildren(e,t){return wc(e,t)}static getComponentsInChildren(e,t,s=null){return Wa(e,t,s??void 0)}static getComponentInParent(e,t){return xc(e,t)}static getComponentsInParent(e,t,s=null){return ou(e,t,s)}static getAllComponents(e){var t;const s=(t=e.userData)==null?void 0:t.components;return s?[...s]:[]}static*iterateComponents(e){var t;const s=(t=e?.userData)==null?void 0:t.components;if(s&&Array.isArray(s))for(let o=0;o<s.length;o++)yield s[o]}}const Su=class _m{constructor(e){a(this,"__context"),a(this,"__name"),a(this,"gameObject"),a(this,"guid","invalid"),a(this,"sourceId"),a(this,"__didAwake",!1),a(this,"__didStart",!1),a(this,"__didEnable",!1),a(this,"__isEnabled"),a(this,"__destroyed",!1),a(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Ff()&&dx(this)}get isComponent(){return!0}get context(){return this.__context??J.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){var e,t;return(t=(e=this.gameObject)==null?void 0:e.userData)==null?void 0:t.layer}get name(){var e,t;return(e=this.gameObject)!=null&&e.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.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(){var e;return(e=this.gameObject)==null?void 0:e.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){var e;return(e=this.gameObject)==null?void 0:e.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[En];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[En]=e)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=Oe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=Oe.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__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 s=e[t];typeof s!="function"&&(this[t]=s)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(B()&&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(){var e;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((e=this.onDestroy)==null||e.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),vw(this),Ff()&&ux(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){B()&&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){lt(this.gameObject,e)}setWorldPosition(e,t,s){vr(this.gameObject,e,t,s)}get worldQuaternion(){return Se(this.gameObject)}set worldQuaternion(e){Yi(this.gameObject,e)}setWorldQuaternion(e,t,s,o){ug(this.gameObject,e,t,s,o)}get worldEuler(){return pg(this.gameObject)}set worldEuler(e){mg(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,s,o=!0){Jl(this.gameObject,e,t,s,o)}get forward(){return _m._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return _m._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return _m._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const s=this._eventListeners[e].indexOf(t);s>=0&&this._eventListeners[e].splice(s,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let s=0;s<t.length;s++)t[s](e);return!1}};a(Su,"_forward",new S),a(Su,"_right",new S),a(Su,"_up",new S);let j=Su;const XR=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:j,Component:j,GameObject:P},Symbol.toStringTag,{value:"Module"}));var QR=Object.defineProperty,mx=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&QR(e,t,o),o};class Ec extends j{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"width",0),a(this,"centered",!0),a(this,"_centerPos")}awake(){this._centerPos=new S}update(){if(!this.from||!this.to)return;const e=ee(this.from).clone(),t=ee(this.to).clone(),s=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),lt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}mx([m(P)],Ec.prototype,"from"),mx([m(P)],Ec.prototype,"to");var YR=Object.defineProperty,KR=Object.getOwnPropertyDescriptor,Dr=(n,e,t,s)=>{for(var o=s>1?void 0:s?KR(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&YR(e,t,o),o};const ko=C("debuganimation");let gx=class{constructor(){a(this,"x"),a(this,"y")}};class Ft extends j{constructor(){super(...arguments),a(this,"playAutomatically",!0),a(this,"randomStartTime",!0),a(this,"minMaxSpeed"),a(this,"minMaxOffsetNormalized"),a(this,"loop",!0),a(this,"clampWhenFinished",!1),a(this,"_tempAnimationClipBeforeGameObjectExisted",null),a(this,"_tempAnimationsArray"),a(this,"mixer"),a(this,"_actions"),a(this,"_handles")}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}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 clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){ko&&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}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||[]}get actions(){return this._actions}set actions(e){this._actions=e}awake(){this.mixer=void 0,ko&&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(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const t=Math.floor(Math.random()*this.animations.length),s=this.animations[t];this.play(t,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*s.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){var t;return((t=this.actions)==null?void 0:t.find(s=>s.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!=null&&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){ko&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(o=>o.name===e));if(!e){console.error("Could not find clip",e);return}const s=this.actions.find(o=>o.getClip()===e);if(!s){console.error("Could not find action",e);return}t!=null&&t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop()}pause(e,t=!1){if(e===void 0){for(const o of this.actions)o.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){ko&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(o=>o.name===e));if(!e){console.error("Could not find clip",e);return}const s=this.actions.find(o=>o.getClip()===e);if(!s){console.error("Could not find action",e);return}s.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(ko&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){ko&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let s=e;if(typeof e=="number"){if(e>=this.animations.length){ko&&console.log("No animation at index",e);return}s=this.animations[e]}else typeof e=="string"&&(s=this.animations.find(r=>r.name===e));if(!s){console.error("Could not find clip",e);return}t||(t={});for(const r of this.actions)if(r.getClip()===s)return this.internalOnPlay(r,t);if(!s.tracks){console.warn("Clip is no AnimationClip",s);return}const o=this.mixer.clipAction(s);return this.actions.push(o),this.internalOnPlay(o,t)}internalOnPlay(e,t){var s=this.actions.find(r=>r===e);if(s===e&&s.isRunning()&&s.time<s.getClip().duration){const r=this.tryFindHandle(e);if(s.paused&&(s.paused=!1),r)return r.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const r of this.actions)r!=s&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop());if(t!=null&&t.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t!=null&&t.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const r=e.getClip();e.time=W.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration}else e.time>=e.getClip().duration&&(e.time=0);t!=null&&t.minMaxSpeed?e.timeScale=W.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?qC:Lm:e.loop=Lm,t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),ko&&console.log("PLAY",e.getClip().name,e);const o=new ZR(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new jm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Dr([m()],Ft.prototype,"playAutomatically",2),Dr([m()],Ft.prototype,"randomStartTime",2),Dr([m(gx)],Ft.prototype,"minMaxSpeed",2),Dr([m(gx)],Ft.prototype,"minMaxOffsetNormalized",2),Dr([m()],Ft.prototype,"loop",2),Dr([m()],Ft.prototype,"clampWhenFinished",2),Dr([m(fo)],Ft.prototype,"clips",1);class ZR{constructor(e,t,s,o){a(this,"mixer"),a(this,"action"),a(this,"promise",null),a(this,"_options"),a(this,"_resolveCallback",null),a(this,"_resolvedOrRejectedCallback"),a(this,"onFinished",r=>{r.action===this.action&&this.onResolve()}),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=o,this._options=s}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(){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const Cu=Symbol("objectIsAnimatedData");function fx(n,e,t){if(!n)return;if(n[Cu]===void 0){if(!t)return;n[Cu]=new Set}const s=n[Cu];t?s.add(e):s.has(e)&&s.delete(e)}function JR(n){if(!n)return!1;const e=n[Cu];return e!==void 0&&e.size>0}class eT{constructor(){a(this,"_context")}get context(){return this._context??J.Current}get isStateMachineBehaviour(){return!0}}class Ac{constructor(e,t,s,o){a(this,"name"),a(this,"nameHash"),a(this,"normalizedTime"),a(this,"length"),a(this,"speed"),a(this,"action"),a(this,"hasTransitions");var r;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=s,this.speed=o,this.action=e.motion.action||null,this.hasTransitions=((r=e.transitions)==null?void 0:r.length)>0||!1}}function yx(n,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??Cn.generateUUID(),index:-1,clip:new fo(n,0,[])}}var Mo=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(Mo||{}),Uf=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(Uf||{});const ht=C("debuganimatorcontroller"),Pu=C("debugrootmotion");class gs{constructor(e){a(this,"_speed",1),a(this,"normalizedStartOffset",0),a(this,"animator"),a(this,"model"),a(this,"_mixer"),a(this,"_activeState"),a(this,"_activeStates",[]),a(this,"_heldActions",[]),a(this,"rootMotionHandler"),this.model=e,ht&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const s=[];for(let r=0;r<e.length;r++){const l=e[r],c=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/l.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),c.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:r,motion:{name:l.name,clip:l,isLooping:t?.looping??!1},transitions:c,behaviours:[]};s.push(h)}const o={name:"AnimatorController",guid:new jt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:s}}]};return new gs(o)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,o=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[t].stateMachine;for(const l of r.states)if(l.name===e||l.hash===e){ht&&console.log("transition to ",l),this.transitionTo(l,o,s);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,o;const r=typeof e=="string"?"name":"hash";return(o=(s=this.model)==null?void 0:s.parameters)==null?void 0:o.filter(l=>l[r]===e).forEach(l=>l.value=t)}getBool(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??!1}setFloat(e,t){var s,o;const r=typeof e=="string"?"name":"hash",l=(o=(s=this.model)==null?void 0:s.parameters)==null?void 0:o.filter(c=>c[r]===e);return l.forEach(c=>c.value=t),l?.length>0}getFloat(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??0}setInteger(e,t){var s,o;const r=typeof e=="string"?"name":"hash";return(o=(s=this.model)==null?void 0:s.parameters)==null?void 0:o.filter(l=>l[r]===e).forEach(l=>l.value=t)}getInteger(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??0}setTrigger(e){var t,s;ht&&console.log("SET TRIGGER",e);const o=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(r=>r[o]===e).forEach(r=>r.value=!0)}resetTrigger(e){var t,s;const o=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(r=>r[o]===e).forEach(r=>r.value=!1)}getTrigger(e){var t,s,o;const r=typeof e=="string"?"name":"hash";return((o=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:o.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}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 s of t.stateMachine.states)if(s.name===e||s.hash==e)return s}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,s=t<=0?0:Math.abs(e.time/t);return new Ac(this._activeState,s,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}dispose(){var e;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const t of this._activeStates)t.motion.clip&&this.mixer.uncacheAction(t.motion.clip,this.animator.gameObject)}(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)}bind(e){var t,s;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new jm(this.animator.gameObject),(s=this.context)==null||s.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;ht&&console.warn("AnimatorController clone()",this.model);const e=Xl(this.model,(t,s,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Bb(o)||o.tracks!==void 0||o instanceof gs));return console.assert(e!==this.model),new gs(e)}update(e){var t,s;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const o=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(o),this.animator.applyRootMotion&&((s=this.rootMotionHandler)==null||s.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const s=this._activeStates[t],o=s.motion;if(!o.action)this._activeStates.splice(t,1),t--;else{const r=o.action;r.weight=e,r.getEffectiveWeight()<=0&&!r.isRunning()&&(ht&&console.debug("REMOVE",s.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(ht||B())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const s=t.stateMachine;s.defaultState===void 0&&(ht&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),s.defaultState=0);const o=s.states[s.defaultState];this.transitionTo(o,0,this.normalizedStartOffset);break}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const s=this._activeState,o=s.motion.action;for(const l of s.transitions){if(!l.hasExitTime&&l.conditions.length<=0)continue;let c=!0;for(const h of l.conditions)if(!this.evaluateCondition(h)){c=!1;break}if(c)if(o){const h=s.motion.clip.duration,d=h<=0?1:Math.abs(o.time/h);let u=l.exitTime;o.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?o.timeScale>0?p=d>=l.exitTime:o.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const f=this.model.parameters.find(y=>y.name===g.parameter);f?.type===Uf.Trigger&&f.value&&(f.value=!1)}if(o.clampWhenFinished=!0,ht){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
|
|
857
857
|
Timescale: `+o.timeScale,`
|
|
858
858
|
Normalized time: `+d.toFixed(3),`
|
|
859
|
-
Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}o&&this.setTimescale(o,s);let r=!1;if(s.motion.isLooping&&o&&(o.time>=o.getClip().duration?(r=!0,o.reset(),o.time=0,o.play()):o.time<=0&&o.timeScale<0&&(r=!0,o.reset(),o.time=o.getClip().duration,o.play())),!r&&s&&!t&&o&&this.animator&&s.behaviours){const l=o?.getClip().duration,c=o.time/l,h=new Ac(this._activeState,c,l,this._speed);for(const d of s.behaviours)d.instance&&((e=d.instance.onStateUpdate)==null||e.call(d.instance,this.animator,h,0))}}setTimescale(e,t){let s=t.speed??1;t.speedParameter&&(s*=this.getFloat(t.speedParameter)),s!==void 0&&(e.timeScale=s*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(ht&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,s){var o,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(e=this.getState(e,g),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof fo))return;const f=this._activeState===e;if(f){const w=e.motion;if(!w.action_loopback&&w.clip){const x=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(w.clip,this.animator.gameObject),x&&x.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),w.action_loopback=this.createAction(w.clip)}}if((o=this._activeState)!=null&&o.behaviours&&this._activeState.motion.action){const w=(r=this._activeState)==null?void 0:r.motion.clip.duration,x=this._activeState.motion.action.time/w,k=new Ac(this._activeState,x,w,this._speed);for(const M of this._activeState.behaviours)(c=(l=M.instance)==null?void 0:l.onStateExit)==null||c.call(M.instance,this.animator,k,g)}const y=(h=this._activeState)==null?void 0:h.motion.action;f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=y);const v=this._activeState;this._activeState=e;const b=(d=e.motion)==null?void 0:d.action,_=e.motion.clip;if(_?.duration<=0&&_.tracks.length<=0?y&&this._heldActions.push(y):y&&(y.fadeOut(t),this.releaseHeldActions(t)),b){if(s=Math.max(0,Math.min(1,s)),e.cycleOffsetParameter){let x=this.getFloat(e.cycleOffsetParameter);typeof x=="number"?(x<0&&(x+=1),s+=x,s%=1):ht&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(s+=e.cycleOffset,s%=1);b.isRunning()&&b.stop(),b.reset(),b.enabled=!0,this.setTimescale(b,e);const w=e.motion.clip.duration;if(b.time=f?0:s*w,b.timeScale<0&&(b.time=w-b.time),b.clampWhenFinished=!0,b.setLoop(Lm,0),t>0?b.fadeIn(t):b.weight=1,b.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(b),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const x=new Ac(e,s,w,this._speed);for(const k of this._activeState.behaviours)(p=(u=k.instance)==null?void 0:u.onStateEnter)==null||p.call(k.instance,this.animator,x,g)}}else ht&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));ht&&console.log("TRANSITION FROM "+v?.name+" TO "+e.name,t,y,b,b?.getEffectiveTimeScale(),b?.getEffectiveWeight(),b?.isRunning(),b?.isScheduled(),b?.paused)}createAction(e){var t,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new iT(this));const o=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,o,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(s=>s.name===e.parameter);if(!t)return!1;switch(e.mode){case Mo.If:return t.value===!0;case Mo.IfNot:return t.value===!1;case Mo.Greater:return t.value>e.threshold;case Mo.Less:return t.value<e.threshold;case Mo.Equals:return t.value===e.threshold;case Mo.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,s,o,r;ht&&console.log("AnimatorController createActions",this.model);for(const l of this.model.layers){const c=l.stateMachine;for(let h=0;h<c.states.length;h++){const d=c.states[h];d.transitions||(d.transitions=[]);for(const u of d.transitions)u.conditions||(u.conditions=[]);if(d.motion||(ht&&console.warn("No motion",d),d.motion=yx(d.name)),this.animator&&d.motion.clips){const u=(t=d.motion.clips)==null?void 0:t.find(p=>{var g,f;return p.node.name===((f=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:f.name)});u?d.motion.clip=u.clip:(ht||B())&&console.warn('Could not find clip for animator "'+((o=(s=this.animator)==null?void 0:s.gameObject)==null?void 0:o.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){ht&&console.warn("No clip assigned to state",d);const u=new fo(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof fo){const p=this.createAction(u);d.motion.action=p}else(ht||B())&&console.warn("No valid animationclip assigned",d)}if(d.behaviours&&Array.isArray(d.behaviours))for(const u of d.behaviours){if(!(u!=null&&u.typeName))continue;const p=R.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,Na(g,u.properties),u.instance=g),ht&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(ht||B())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let s=0;s<t.states.length;s++){const o=t.states[s];o!=null&&o.motion&&(o.motion.action&&(yield o.motion.action),o.motion.action_loopback&&(yield o.motion.action_loopback))}}}}class vx{constructor(e,t){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=e;const s=e,o=s.createInterpolant.bind(e);s.createInterpolant=()=>(s.createInterpolant=o,this.createdInterpolant=o(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return t(r,l)},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}}const Ro=class kt{constructor(e,t,s,o,r){if(a(this,"_action"),a(this,"root"),a(this,"clip"),a(this,"positionWrapper",null),a(this,"rotationWrapper",null),a(this,"context"),a(this,"positionChange",new S),a(this,"rotationChange",new V),a(this,"_prevTime",0),this.context=e,this.root=t,this.clip=s,kt.firstKeyframeRotation[this.cacheId]||(kt.firstKeyframeRotation[this.cacheId]=new V),r){const l=r.values;kt.firstKeyframeRotation[this.cacheId].set(l[0],l[1],l[2],l[3])}kt.spaceRotation[this.cacheId]||(kt.spaceRotation[this.cacheId]=new V),kt.effectiveSpaceRotation[this.cacheId]||(kt.effectiveSpaceRotation[this.cacheId]=new V),kt.clipOffsetRotation[this.cacheId]=new V,r&&kt.clipOffsetRotation[this.cacheId].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(s,o),this.handleRotation(s,r)}set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(e){if(e.getClip()!==this.clip)return;kt.lastObjRotation[this.cacheId]||(kt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=kt.lastObjRotation[this.cacheId];if(kt.spaceRotation[this.cacheId].copy(t),Pu){const s=new Bt().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(s.y),this.root.position.z)}}getClipRotationOffset(){return kt.clipOffsetRotation[this.cacheId]}handlePosition(e,t){if(t){const s=this.root;Pu&&s.add(new Pi),kt.lastObjPosition[this.cacheId]||(kt.lastObjPosition[this.cacheId]=this.root.position.clone());const o=new S,r=new S;this.positionWrapper=new vx(t,(l,c)=>{const h=this.action.getEffectiveWeight();return Pu&&s.position.length()>8&&s.position.set(0,s.position.y,0),l>this._prevTime&&(o.set(c[0],c[1],c[2]),o.sub(r),o.multiplyScalar(h),o.applyQuaternion(this.getClipRotationOffset()),o.applyQuaternion(s.quaternion),this.positionChange.copy(o)),r.fromArray(c),this._prevTime=l,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Pu){const l=t.values,c=new Bt().setFromQuaternion(new V(l[0],l[1],l[2],l[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(c.y));const h=t.values.length-4,d=new V().set(l[h],l[h+1],l[h+2],l[h+3]),u=new Bt().setFromQuaternion(d);console.log(e.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(u.y))}let s=0;const o=new V,r=new V;this.rotationWrapper=new vx(t,(l,c)=>(l>s&&(r.set(c[0],c[1],c[2],c[3]),o.invert(),r.multiply(o),this.rotationChange.copy(r)),o.fromArray(c),s=l,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}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(kt.identityQuaternion,1-e),!0)}};a(Ro,"lastObjPosition",{}),a(Ro,"lastObjRotation",{}),a(Ro,"firstKeyframeRotation",{}),a(Ro,"spaceRotation",{}),a(Ro,"effectiveSpaceRotation",{}),a(Ro,"clipOffsetRotation",{}),a(Ro,"identityQuaternion",new V);let tT=Ro;class iT{constructor(e){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new S),a(this,"baseQuaternion",new V),a(this,"baseRotation",new Bt),a(this,"summedPosition",new S),a(this,"summedRotation",new V),this.controller=e}createClip(e,t,s){this.root=t,t&&"name"in t&&t.name;const o=this.findRootTrack(s,".position"),r=this.findRootTrack(s,".quaternion"),l=new tT(this.controller.context,t,s,o,r);this.handler.push(l);const c=e.clipAction(s);return l.action=c,c}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)}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 s=e.tracks;if(!s)return null;for(const o of s)if(o.name.endsWith(t))return o;return null}}class sT extends es{onSerialize(e,t){}onDeserialize(e,t){if(t.type===gs&&e?.__type==="AnimatorController")return new gs(e)}}new sT(gs);var nT=Object.defineProperty,oT=Object.getOwnPropertyDescriptor,Ou=(n,e,t,s)=>{for(var o=s>1?void 0:s?oT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&nT(e,t,o),o};const ts=C("debuganimator");class Rt extends j{constructor(){super(...arguments),a(this,"applyRootMotion",!1),a(this,"hasRootMotion",!1),a(this,"keepAnimatorControllerStateOnDisable",!1),a(this,"_parametersAreDirty",!1),a(this,"_isDirty",!1),a(this,"_speed",1),a(this,"_normalizedStartOffset",0),a(this,"_animatorController",null),a(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof gs?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new gs(e.model)),this._animatorController=e,this._animatorController.bind(this)):(ts&&console.log("Assign animator controller",e,this),this._animatorController=new gs(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,s=Number.NEGATIVE_INFINITY,o=0){this.play(e,t,s,o)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,o=0){var r;(r=this.runtimeAnimatorController)==null||r.play(e,t,s,o),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var s,o;ts&&console.log("setBool",e,t),((s=this.runtimeAnimatorController)==null?void 0:s.getBool(e))!==t&&(this._parametersAreDirty=!0),(o=this.runtimeAnimatorController)==null||o.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1;return ts&&console.log("getBool",e,s),s}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var s,o;((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(e))!==t&&(this._parametersAreDirty=!0),ts&&console.log("setFloat",e,t),(o=this.runtimeAnimatorController)==null||o.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1;return ts&&console.log("getFloat",e,s),s}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var s,o;((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(e))!==t&&(this._parametersAreDirty=!0),ts&&console.log("setInteger",e,t),(o=this.runtimeAnimatorController)==null||o.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1;return ts&&console.log("getInteger",e,s),s}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,ts&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,ts&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var t;const s=(t=this.runtimeAnimatorController)==null?void 0:t.getTrigger(e);return ts&&console.log("getTrigger",e,s),s}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this._speed&&(ts&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=W.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=W.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){ts&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const s=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=s,s?(console.assert(this.runtimeAnimatorController!==s),this.runtimeAnimatorController=s,console.assert(this.runtimeAnimatorController===s),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!JR(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Ou([m()],Rt.prototype,"applyRootMotion",2),Ou([m()],Rt.prototype,"hasRootMotion",2),Ou([m()],Rt.prototype,"keepAnimatorControllerStateOnDisable",2),Ou([m()],Rt.prototype,"runtimeAnimatorController",1);const bx=Symbol("previous-visibility"),_x=class nd extends Vs{render(e,t,s){if("addPass"in s)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(s instanceof gr){this.onBeforeRender();const o=s.getRenderTarget(),r=s.xr.enabled;s.xr.enabled=!1,s.setRenderTarget(this),s.clear(!0,!0,!0),s.render(e,t),s.setRenderTarget(o),s.xr.enabled=r,this.onAfterRender()}}onBeforeRender(){nd._userSet.clear();const e=Qg(this.texture,!0,null,nd._userSet);for(const t of e)t instanceof q&&(t[bx]=t.visible,t.visible=!1)}onAfterRender(){for(const e of nd._userSet)e instanceof q&&(e.visible=e[bx]);nd._userSet.clear()}};a(_x,"_userSet",new Set);let Ic=_x;var rT=Object.defineProperty,aT=Object.getOwnPropertyDescriptor,Lc=(n,e,t,s)=>{for(var o=s>1?void 0:s?aT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&rT(e,t,o),o};const ku=C("debuggroundprojection");class en extends j{constructor(){super(...arguments),a(this,"applyOnAwake",!1),a(this,"autoFit",!0),a(this,"_radius",50),a(this,"_height",3),a(this,"_arblending",0),a(this,"_lastBackground"),a(this,"_lastRadius"),a(this,"_lastHeight"),a(this,"_projection"),a(this,"_watcher"),a(this,"_needsTextureUpdate",!1),a(this,"_blurrynessShader",null),a(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new co(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{ku&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var e,t;(e=this._watcher)==null||e.revoke(),(t=this._projection)==null||t.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Ql(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 je&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var e,t,s,o,r,l;if(!this.context.scene.background){(e=this._projection)==null||e.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof je)){(t=this._projection)==null||t.removeFromParent();return}if(((s=this.context.xr)!=null&&s.isPassThrough||(o=this.context.xr)!=null&&o.isAR)&&this.arBlending===0){(r=this._projection)==null||r.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let h=!0;const d=0,u=c!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||u){ku&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new ka(c,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-d,this._projection.name="GroundProjection",gg(this._projection,!1)}else h=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&h){this._projection.updateWorldMatrix(!0,!0);const p=ni(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const f=X();f.x=p.min.x+(p.max.x-p.min.x)*.5;const y=Ge(this.gameObject).x;f.y=g+this._height*y-d,f.z=p.min.z+(p.max.z-p.min.z)*.5,lt(this._projection,f)}ku&&G.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(c,this.context.scene.backgroundBlurriness),this._lastBackground=c,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(e,t){var s;if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,ku&&console.log("Update Blurriness",t),this._blurrynessShader??(this._blurrynessShader=new Ns({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:lT,fragmentShader:cT})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const o=this._projection.material.transparent;this._projection.material.transparent=(((s=this.context.xr)==null?void 0:s.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,o!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=ec.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Lc([m()],en.prototype,"applyOnAwake",2),Lc([m()],en.prototype,"autoFit",2),Lc([m()],en.prototype,"radius",1),Lc([m()],en.prototype,"height",1),Lc([m()],en.prototype,"arBlending",1);const lT=`
|
|
859
|
+
Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}o&&this.setTimescale(o,s);let r=!1;if(s.motion.isLooping&&o&&(o.time>=o.getClip().duration?(r=!0,o.reset(),o.time=0,o.play()):o.time<=0&&o.timeScale<0&&(r=!0,o.reset(),o.time=o.getClip().duration,o.play())),!r&&s&&!t&&o&&this.animator&&s.behaviours){const l=o?.getClip().duration,c=o.time/l,h=new Ac(this._activeState,c,l,this._speed);for(const d of s.behaviours)d.instance&&((e=d.instance.onStateUpdate)==null||e.call(d.instance,this.animator,h,0))}}setTimescale(e,t){let s=t.speed??1;t.speedParameter&&(s*=this.getFloat(t.speedParameter)),s!==void 0&&(e.timeScale=s*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(ht&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,s){var o,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(e=this.getState(e,g),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof fo))return;const f=this._activeState===e;if(f){const w=e.motion;if(!w.action_loopback&&w.clip){const x=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(w.clip,this.animator.gameObject),x&&x.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),w.action_loopback=this.createAction(w.clip)}}if((o=this._activeState)!=null&&o.behaviours&&this._activeState.motion.action){const w=(r=this._activeState)==null?void 0:r.motion.clip.duration,x=this._activeState.motion.action.time/w,k=new Ac(this._activeState,x,w,this._speed);for(const M of this._activeState.behaviours)(c=(l=M.instance)==null?void 0:l.onStateExit)==null||c.call(M.instance,this.animator,k,g)}const y=(h=this._activeState)==null?void 0:h.motion.action;f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=y);const v=this._activeState;this._activeState=e;const b=(d=e.motion)==null?void 0:d.action,_=e.motion.clip;if(_?.duration<=0&&_.tracks.length<=0?y&&this._heldActions.push(y):y&&(y.fadeOut(t),this.releaseHeldActions(t)),b){if(s=Math.max(0,Math.min(1,s)),e.cycleOffsetParameter){let x=this.getFloat(e.cycleOffsetParameter);typeof x=="number"?(x<0&&(x+=1),s+=x,s%=1):ht&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(s+=e.cycleOffset,s%=1);b.isRunning()&&b.stop(),b.reset(),b.enabled=!0,this.setTimescale(b,e);const w=e.motion.clip.duration;if(b.time=f?0:s*w,b.timeScale<0&&(b.time=w-b.time),b.clampWhenFinished=!0,b.setLoop(Lm,0),t>0?b.fadeIn(t):b.weight=1,b.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(b),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const x=new Ac(e,s,w,this._speed);for(const k of this._activeState.behaviours)(p=(u=k.instance)==null?void 0:u.onStateEnter)==null||p.call(k.instance,this.animator,x,g)}}else ht&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));ht&&console.log("TRANSITION FROM "+v?.name+" TO "+e.name,t,y,b,b?.getEffectiveTimeScale(),b?.getEffectiveWeight(),b?.isRunning(),b?.isScheduled(),b?.paused)}createAction(e){var t,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new iT(this));const o=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,o,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(s=>s.name===e.parameter);if(!t)return!1;switch(e.mode){case Mo.If:return t.value===!0;case Mo.IfNot:return t.value===!1;case Mo.Greater:return t.value>e.threshold;case Mo.Less:return t.value<e.threshold;case Mo.Equals:return t.value===e.threshold;case Mo.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,s,o,r;ht&&console.log("AnimatorController createActions",this.model);for(const l of this.model.layers){const c=l.stateMachine;for(let h=0;h<c.states.length;h++){const d=c.states[h];d.transitions||(d.transitions=[]);for(const u of d.transitions)u.conditions||(u.conditions=[]);if(d.motion||(ht&&console.warn("No motion",d),d.motion=yx(d.name)),this.animator&&d.motion.clips){const u=(t=d.motion.clips)==null?void 0:t.find(p=>{var g,f;return p.node.name===((f=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:f.name)});u?d.motion.clip=u.clip:(ht||B())&&console.warn('Could not find clip for animator "'+((o=(s=this.animator)==null?void 0:s.gameObject)==null?void 0:o.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){ht&&console.warn("No clip assigned to state",d);const u=new fo(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof fo){const p=this.createAction(u);d.motion.action=p}else(ht||B())&&console.warn("No valid animationclip assigned",d)}if(d.behaviours&&Array.isArray(d.behaviours))for(const u of d.behaviours){if(!(u!=null&&u.typeName))continue;const p=R.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,Na(g,u.properties),u.instance=g),ht&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(ht||B())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let s=0;s<t.states.length;s++){const o=t.states[s];o!=null&&o.motion&&(o.motion.action&&(yield o.motion.action),o.motion.action_loopback&&(yield o.motion.action_loopback))}}}}class vx{constructor(e,t){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=e;const s=e,o=s.createInterpolant.bind(e);s.createInterpolant=()=>(s.createInterpolant=o,this.createdInterpolant=o(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return t(r,l)},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}}const Ro=class kt{constructor(e,t,s,o,r){if(a(this,"_action"),a(this,"root"),a(this,"clip"),a(this,"positionWrapper",null),a(this,"rotationWrapper",null),a(this,"context"),a(this,"positionChange",new S),a(this,"rotationChange",new V),a(this,"_prevTime",0),this.context=e,this.root=t,this.clip=s,kt.firstKeyframeRotation[this.cacheId]||(kt.firstKeyframeRotation[this.cacheId]=new V),r){const l=r.values;kt.firstKeyframeRotation[this.cacheId].set(l[0],l[1],l[2],l[3])}kt.spaceRotation[this.cacheId]||(kt.spaceRotation[this.cacheId]=new V),kt.effectiveSpaceRotation[this.cacheId]||(kt.effectiveSpaceRotation[this.cacheId]=new V),kt.clipOffsetRotation[this.cacheId]=new V,r&&kt.clipOffsetRotation[this.cacheId].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(s,o),this.handleRotation(s,r)}set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(e){if(e.getClip()!==this.clip)return;kt.lastObjRotation[this.cacheId]||(kt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=kt.lastObjRotation[this.cacheId];if(kt.spaceRotation[this.cacheId].copy(t),Pu){const s=new Dt().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(s.y),this.root.position.z)}}getClipRotationOffset(){return kt.clipOffsetRotation[this.cacheId]}handlePosition(e,t){if(t){const s=this.root;Pu&&s.add(new Pi),kt.lastObjPosition[this.cacheId]||(kt.lastObjPosition[this.cacheId]=this.root.position.clone());const o=new S,r=new S;this.positionWrapper=new vx(t,(l,c)=>{const h=this.action.getEffectiveWeight();return Pu&&s.position.length()>8&&s.position.set(0,s.position.y,0),l>this._prevTime&&(o.set(c[0],c[1],c[2]),o.sub(r),o.multiplyScalar(h),o.applyQuaternion(this.getClipRotationOffset()),o.applyQuaternion(s.quaternion),this.positionChange.copy(o)),r.fromArray(c),this._prevTime=l,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Pu){const l=t.values,c=new Dt().setFromQuaternion(new V(l[0],l[1],l[2],l[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(c.y));const h=t.values.length-4,d=new V().set(l[h],l[h+1],l[h+2],l[h+3]),u=new Dt().setFromQuaternion(d);console.log(e.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(u.y))}let s=0;const o=new V,r=new V;this.rotationWrapper=new vx(t,(l,c)=>(l>s&&(r.set(c[0],c[1],c[2],c[3]),o.invert(),r.multiply(o),this.rotationChange.copy(r)),o.fromArray(c),s=l,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}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(kt.identityQuaternion,1-e),!0)}};a(Ro,"lastObjPosition",{}),a(Ro,"lastObjRotation",{}),a(Ro,"firstKeyframeRotation",{}),a(Ro,"spaceRotation",{}),a(Ro,"effectiveSpaceRotation",{}),a(Ro,"clipOffsetRotation",{}),a(Ro,"identityQuaternion",new V);let tT=Ro;class iT{constructor(e){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new S),a(this,"baseQuaternion",new V),a(this,"baseRotation",new Dt),a(this,"summedPosition",new S),a(this,"summedRotation",new V),this.controller=e}createClip(e,t,s){this.root=t,t&&"name"in t&&t.name;const o=this.findRootTrack(s,".position"),r=this.findRootTrack(s,".quaternion"),l=new tT(this.controller.context,t,s,o,r);this.handler.push(l);const c=e.clipAction(s);return l.action=c,c}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)}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 s=e.tracks;if(!s)return null;for(const o of s)if(o.name.endsWith(t))return o;return null}}class sT extends es{onSerialize(e,t){}onDeserialize(e,t){if(t.type===gs&&e?.__type==="AnimatorController")return new gs(e)}}new sT(gs);var nT=Object.defineProperty,oT=Object.getOwnPropertyDescriptor,Ou=(n,e,t,s)=>{for(var o=s>1?void 0:s?oT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&nT(e,t,o),o};const ts=C("debuganimator");class Rt extends j{constructor(){super(...arguments),a(this,"applyRootMotion",!1),a(this,"hasRootMotion",!1),a(this,"keepAnimatorControllerStateOnDisable",!1),a(this,"_parametersAreDirty",!1),a(this,"_isDirty",!1),a(this,"_speed",1),a(this,"_normalizedStartOffset",0),a(this,"_animatorController",null),a(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof gs?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new gs(e.model)),this._animatorController=e,this._animatorController.bind(this)):(ts&&console.log("Assign animator controller",e,this),this._animatorController=new gs(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,s=Number.NEGATIVE_INFINITY,o=0){this.play(e,t,s,o)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,o=0){var r;(r=this.runtimeAnimatorController)==null||r.play(e,t,s,o),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var s,o;ts&&console.log("setBool",e,t),((s=this.runtimeAnimatorController)==null?void 0:s.getBool(e))!==t&&(this._parametersAreDirty=!0),(o=this.runtimeAnimatorController)==null||o.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1;return ts&&console.log("getBool",e,s),s}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var s,o;((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(e))!==t&&(this._parametersAreDirty=!0),ts&&console.log("setFloat",e,t),(o=this.runtimeAnimatorController)==null||o.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1;return ts&&console.log("getFloat",e,s),s}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var s,o;((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(e))!==t&&(this._parametersAreDirty=!0),ts&&console.log("setInteger",e,t),(o=this.runtimeAnimatorController)==null||o.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1;return ts&&console.log("getInteger",e,s),s}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,ts&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,ts&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var t;const s=(t=this.runtimeAnimatorController)==null?void 0:t.getTrigger(e);return ts&&console.log("getTrigger",e,s),s}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this._speed&&(ts&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=W.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=W.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){ts&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const s=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=s,s?(console.assert(this.runtimeAnimatorController!==s),this.runtimeAnimatorController=s,console.assert(this.runtimeAnimatorController===s),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!JR(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Ou([m()],Rt.prototype,"applyRootMotion",2),Ou([m()],Rt.prototype,"hasRootMotion",2),Ou([m()],Rt.prototype,"keepAnimatorControllerStateOnDisable",2),Ou([m()],Rt.prototype,"runtimeAnimatorController",1);const bx=Symbol("previous-visibility"),_x=class nd extends Vs{render(e,t,s){if("addPass"in s)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(s instanceof gr){this.onBeforeRender();const o=s.getRenderTarget(),r=s.xr.enabled;s.xr.enabled=!1,s.setRenderTarget(this),s.clear(!0,!0,!0),s.render(e,t),s.setRenderTarget(o),s.xr.enabled=r,this.onAfterRender()}}onBeforeRender(){nd._userSet.clear();const e=Qg(this.texture,!0,null,nd._userSet);for(const t of e)t instanceof q&&(t[bx]=t.visible,t.visible=!1)}onAfterRender(){for(const e of nd._userSet)e instanceof q&&(e.visible=e[bx]);nd._userSet.clear()}};a(_x,"_userSet",new Set);let Ic=_x;var rT=Object.defineProperty,aT=Object.getOwnPropertyDescriptor,Lc=(n,e,t,s)=>{for(var o=s>1?void 0:s?aT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&rT(e,t,o),o};const ku=C("debuggroundprojection");class en extends j{constructor(){super(...arguments),a(this,"applyOnAwake",!1),a(this,"autoFit",!0),a(this,"_radius",50),a(this,"_height",3),a(this,"_arblending",0),a(this,"_lastBackground"),a(this,"_lastRadius"),a(this,"_lastHeight"),a(this,"_projection"),a(this,"_watcher"),a(this,"_needsTextureUpdate",!1),a(this,"_blurrynessShader",null),a(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new co(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{ku&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var e,t;(e=this._watcher)==null||e.revoke(),(t=this._projection)==null||t.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Ql(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 je&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var e,t,s,o,r,l;if(!this.context.scene.background){(e=this._projection)==null||e.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof je)){(t=this._projection)==null||t.removeFromParent();return}if(((s=this.context.xr)!=null&&s.isPassThrough||(o=this.context.xr)!=null&&o.isAR)&&this.arBlending===0){(r=this._projection)==null||r.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let h=!0;const d=0,u=c!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||u){ku&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new ka(c,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-d,this._projection.name="GroundProjection",gg(this._projection,!1)}else h=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&h){this._projection.updateWorldMatrix(!0,!0);const p=ni(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const f=X();f.x=p.min.x+(p.max.x-p.min.x)*.5;const y=Ge(this.gameObject).x;f.y=g+this._height*y-d,f.z=p.min.z+(p.max.z-p.min.z)*.5,lt(this._projection,f)}ku&&G.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(c,this.context.scene.backgroundBlurriness),this._lastBackground=c,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(e,t){var s;if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,ku&&console.log("Update Blurriness",t),this._blurrynessShader??(this._blurrynessShader=new Ns({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:lT,fragmentShader:cT})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const o=this._projection.material.transparent;this._projection.material.transparent=(((s=this.context.xr)==null?void 0:s.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,o!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=ec.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Lc([m()],en.prototype,"applyOnAwake",2),Lc([m()],en.prototype,"autoFit",2),Lc([m()],en.prototype,"radius",1),Lc([m()],en.prototype,"height",1),Lc([m()],en.prototype,"arBlending",1);const lT=`
|
|
860
860
|
varying vec2 vUv;
|
|
861
861
|
|
|
862
862
|
void main() {
|
|
@@ -925,7 +925,7 @@ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.
|
|
|
925
925
|
// Uncomment to visualize blur amount
|
|
926
926
|
// gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
|
|
927
927
|
}
|
|
928
|
-
`;var hT=Object.defineProperty,zf=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&hT(e,t,o),o};class Br extends j{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}zf([m()],Br.prototype,"constraintActive"),zf([m()],Br.prototype,"locked"),zf([m(A)],Br.prototype,"sources");let Fr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(n,e){return this.bb_pos=n,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(n,e,t,s){return n.prep(4,12),n.writeFloat32(s),n.writeFloat32(t),n.writeFloat32(e),n.offset()}};class wx{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Fr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Fr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Fr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,s,o,r,l,c,h,d,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(d),e.writeFloat32(h),e.prep(4,12),e.writeFloat32(c),e.writeFloat32(l),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(o),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class ho{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new ho).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Jv),(t||new ho).__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 wx).__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 L;(n=>{(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function o(){if(e.MODULE)return e.MODULE;const r=await import("./rapier-CyWhltHY.min.js");return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=o})(n.RAPIER_PHYSICS||(n.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function o(){if(e.MODULE)return e.MODULE;const r=await import("./postprocessing-TkXiVrjY.min.js").then(l=>l.index);return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=o})(n.POSTPROCESSING||(n.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function o(){if(e.MODULE)return e.MODULE;const r=await import("./postprocessing-TkXiVrjY.min.js").then(l=>l.N8AO);return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=o})(n.POSTPROCESSING_AO||(n.POSTPROCESSING_AO={}))})(L||(L={}));var xt=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(xt||{}),Mu=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(Mu||{}),Qe=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(Qe||{}),Qa=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Qa||{});const Tt=function(n,e){return function(t,s,o){dT(t,s,o,n,e)}};function dT(n,e,t,s,o){if(!o&&!s&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),De("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Mi.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,n.__internalAwake){const l=Symbol(r),c=n.__internalAwake;n.__internalAwake=function(){var h;if(!this.onValidate){B()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=n.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof ie||d instanceof S||d instanceof fe||d instanceof V){const u=this[r];kd(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[mf]===!0)this[l]=u;else{s?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const uT=function(n){return function(e,t,s){let o="";typeof t=="string"?o=t:o=t.name;const r=n.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const c=l.value,h=e[o];Object.defineProperty(r,o,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var pT=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,Li=(n,e,t,s)=>{for(var o=s>1?void 0:s?mT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&pT(e,t,o),o};class gT{constructor(e,t){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}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]}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)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new co(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new co(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const s=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),s(r,l)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var Ya;const ci=(Ya=class extends j{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new S(0,0,0)),a(this,"constraints",Qe.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Mu.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new S),a(this,"_smoothedVelocity",new S),a(this,"_smoothedVelocityGetter",new S),a(this,"_lastPosition",new S),a(this,"_watch")}get isRigidbody(){return!0}set mass(n){n!==this._mass&&(this._mass=n,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var n,e;return this.autoMass?((e=(n=this.context.physics.engine)==null?void 0:n.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Qe.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Qe.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Qe.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Qe.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Qe.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Qe.FreezeRotationZ)!==0}set lockPositionX(n){n?this.constraints|=Qe.FreezePositionX:this.constraints&=~Qe.FreezePositionX}set lockPositionY(n){n?this.constraints|=Qe.FreezePositionY:this.constraints&=~Qe.FreezePositionY}set lockPositionZ(n){n?this.constraints|=Qe.FreezePositionZ:this.constraints&=~Qe.FreezePositionZ}set lockRotationX(n){n?this.constraints|=Qe.FreezeRotationX:this.constraints&=~Qe.FreezeRotationX}set lockRotationY(n){n?this.constraints|=Qe.FreezeRotationY:this.constraints&=~Qe.FreezeRotationY}set lockRotationZ(n){n?this.constraints|=Qe.FreezeRotationZ:this.constraints&=~Qe.FreezeRotationZ}set gravityScale(n){this._gravityScale=n}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new gT(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Oe.LateUpdate),B()&&(globalThis.NEEDLE_USE_RAPIER?L.RAPIER_PHYSICS.ready().then(async()=>{var n;await Ql(3),(n=this.context.physics.engine)!=null&&n.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(){var n,e;(n=this._watch)==null||n.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var n;(n=this.context.physics.engine)==null||n.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var n,e,t,s;;)this._propertiesChanged&&(this._propertiesChanged=!1,(n=this.context.physics.engine)==null||n.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(n,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(n.x,n.y,n.z):this.setWorldPosition(n.x,n.y,n.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(n=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,n)}resetTorques(n=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,n)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var n;(n=this.context.physics.engine)==null||n.wakeup(this)}get isSleeping(){var n;return(n=this.context.physics.engine)==null?void 0:n.isSleeping(this)}updateProperties(){var n;return this._propertiesChanged=!1,(n=this.context.physics.engine)==null?void 0:n.updateProperties(this)}applyForce(n,e,t=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,n,t)}applyImpulse(n,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,n,e)}setForce(n,e,t,s=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,s),typeof n=="number"?(e??(e=0),t??(t=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:n,y:e,z:t},s)):(l=this.context.physics.engine)==null||l.addForce(this,n,s)}getVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,s=!0){var o,r;if(n instanceof S){const l=n;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,s);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:n,y:e,z:t},s)}getAngularVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,s=!0){var o,r;if(typeof n=="object"){const l=n;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,s);return}if(e===void 0||t===void 0||typeof e=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:n,y:e,z:t},s)}setTorque(n,e,t){typeof n=="number"?this.setAngularVelocity(n,e,t):this.setAngularVelocity(n)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(n=null){}captureVelocity(){const n=this.gameObject.matrixWorld;Ya.tempPosition.setFromMatrixPosition(n);const e=Ya.tempPosition.sub(this._lastPosition);this._lastPosition.copy(Ya.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},a(Ya,"tempPosition",new S),Ya);Li([Tt()],ci.prototype,"autoMass",2),Li([m()],ci.prototype,"mass",1),Li([Tt(),m()],ci.prototype,"useGravity",2),Li([m(S)],ci.prototype,"centerOfMass",2),Li([Tt(),m()],ci.prototype,"constraints",2),Li([Tt(),m()],ci.prototype,"isKinematic",2),Li([Tt(),m()],ci.prototype,"drag",2),Li([Tt(),m()],ci.prototype,"angularDrag",2),Li([Tt(),m()],ci.prototype,"detectCollisions",2),Li([Tt(),m()],ci.prototype,"sleepThreshold",2),Li([Tt(),m()],ci.prototype,"collisionDetectionMode",2),Li([Tt()],ci.prototype,"_gravityScale",2),Li([Tt()],ci.prototype,"dominanceGroup",2);let dt=ci;new S,new S;const To=C("debugsync"),jc="STRS";Eg(jc,ho.getRootAsSyncedTransformModel);const tn=new Hm;function xx(n,e,t=!0){tn.clear();const s=tn.createString(n);ho.startSyncedTransformModel(tn),ho.addGuid(tn,s),ho.addFast(tn,t);const o=e.worldPosition,r=e.worldEuler,l=e.gameObject.scale;ho.addTransform(tn,wx.createTransform(tn,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=ho.endSyncedTransformModel(tn);return tn.finish(c,jc),tn.asUint8Array()}let Nf=0,Dc=0;ox(n=>{var e;const t=(e=n.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;Dc=Math.floor(Nf/t),Nf=0,To&&Dc>0&&console.log("Sync Transform Fast Interval",Dc)});class sn extends j{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new Bt),a(this,"receivedUpdate",!1),a(this,"lastPosition"),a(this,"lastRotation"),a(this,"lastScale")}requestOwnership(){To&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){var e;(e=this._model)==null||e.freeOwnership()}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){To&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new V,this.lastPosition=new S,this.lastRotation=new V,this.lastScale=new S,this.rb=P.getComponentInChildren(this.gameObject,dt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ig(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(se.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(jc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&of(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(se.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(jc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){To&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const s=e.transform();if(s){ms.markDirty(this.gameObject,!0);const o=s.position();o&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=s.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&mg(this.gameObject,this.tempEuler));const l=s.scale();l&&this.gameObject.scale.set(l.x(),l.y(),l.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()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){To&&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,s=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const l=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>l||t.angleTo(this.lastRotation)>l||s.distanceTo(this.lastScale)>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(To&&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),ms.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const l=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const h=this.worldPosition;h.lerp(this._targetPosition,l),this.worldPosition=h,c=!0}if(this.interpolateRotation&&this._targetRotation){const h=this.worldQuaternion;h.slerp(this._targetRotation,l),this.worldQuaternion=h,c=!0}c&&ms.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(s),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(To&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const o=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%o===0||r)){if(Nf++,r&&Dc>0&&this.context.time.frameCount%Dc!==0)return;To&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const l=xx(this.guid,this,!!r);this.context.connection.sendBinary(l)}}}class hd{constructor(e,t){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=t,this.input=e,this.button=t.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const e=new hd(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Ru(n,e){return P.foreachComponent(n,t=>{if(!t.enabled)return;const s=t;if(e)switch(e){case"pointerdown":if(s.onPointerDown)return!0;break;case"pointerup":if(s.onPointerUp||s.onPointerClick)return!0;break;case"pointermove":if(s.onPointerEnter||s.onPointerExit||s.onPointerMove)return!0;break}else if(s.onPointerDown||s.onPointerUp||s.onPointerEnter||s.onPointerExit||s.onPointerClick)return!0},!1)===!0}const Un=new Array;class zn{constructor(e,t,s,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=e,this.methodName=t||null,this.arguments=s,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Un.length=0,e!==void 0&&e.length>0&&Un.push(...e),Un.push(...this.arguments),this.target(...this.arguments),Un.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Un.length=0,e!==void 0&&e.length>0&&Un.push(...e),Un.push(...this.arguments),t.call(this.target,...Un),Un.length=0):t.call(this.target,...e):this.arguments?this.target[this.methodName]=this.arguments[0]||e[0]:this.target[this.methodName]=e[0]}}}}const fT=n=>/^[A-Z]*$/.test(n);class Tu extends Event{constructor(){super(...arguments),a(this,"args")}}class xe{constructor(e){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(e))for(const t of e)t instanceof zn?this.methods.push(t):typeof t=="function"&&this.methods.push(new zn(t));else typeof e=="function"&&this.methods.push(new zn(e))}__internalOnInstantiate(e){var t;const s=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=e[c];if(h){const d=(t=r.arguments)==null?void 0:t.map(u=>u instanceof Object&&u.uuid?e[u.uuid]:u!=null&&u.isComponent?e[u.guid]:u);s.push(new zn(h.clone,r.methodName,d,r.enabled))}else B()&&console.warn("Could not find target for event listener")}}}return new xe(s)}setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let s="",o=!1;for(const r of this.key)o&&fT(r)&&(s+="-"),o=!0,s+=r.toLowerCase();this.key=s}}get listenerCount(){var e;return((e=this.methods)==null?void 0:e.length)??0}get isInvoking(){return this._isInvoking}static from(...e){return new xe(e)}invoke(...e){var t;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((t=this.methods)==null?void 0:t.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const s of this._methodsCopy)s.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const s=this.target.dispatchEvent;if(typeof s=="function"){const o=new Tu(this.key);o.args=e,s.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new zn(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 yT extends es{constructor(){super([re,he],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new he(e.r,e.g,e.b,e.a):e.alpha!==void 0?new he(e.r,e.g,e.b,e.alpha):new re(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 vT=new yT;class bT extends es{constructor(){super([Bt],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new Bt(e.x,e.y,e.z,e.order);if(e.x!=null)return new Bt(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const _T=new bT;class wT extends es{constructor(){super(A,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const s=t.objectToNode[e.uuid];return wt&&console.log(s,e.name,e.uuid),{node:s}}}onDeserialize(e,t){var s,o,r;if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ce))return;B()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(s=t.target)==null?void 0:s.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
|
|
928
|
+
`;var hT=Object.defineProperty,zf=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&hT(e,t,o),o};class Br extends j{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}zf([m()],Br.prototype,"constraintActive"),zf([m()],Br.prototype,"locked"),zf([m(A)],Br.prototype,"sources");let Fr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(n,e){return this.bb_pos=n,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(n,e,t,s){return n.prep(4,12),n.writeFloat32(s),n.writeFloat32(t),n.writeFloat32(e),n.offset()}};class wx{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Fr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Fr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Fr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,s,o,r,l,c,h,d,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(d),e.writeFloat32(h),e.prep(4,12),e.writeFloat32(c),e.writeFloat32(l),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(o),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class ho{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new ho).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Jv),(t||new ho).__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 wx).__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 L;(n=>{(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function o(){if(e.MODULE)return e.MODULE;const r=await import("./rapier-CyWhltHY.min.js");return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=o})(n.RAPIER_PHYSICS||(n.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function o(){if(e.MODULE)return e.MODULE;const r=await import("./postprocessing-BzY0H7ry.min.js").then(l=>l.index);return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=o})(n.POSTPROCESSING||(n.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function o(){if(e.MODULE)return e.MODULE;const r=await import("./postprocessing-BzY0H7ry.min.js").then(l=>l.N8AO);return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=o})(n.POSTPROCESSING_AO||(n.POSTPROCESSING_AO={}))})(L||(L={}));var xt=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(xt||{}),Mu=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(Mu||{}),Qe=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(Qe||{}),Qa=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Qa||{});const Tt=function(n,e){return function(t,s,o){dT(t,s,o,n,e)}};function dT(n,e,t,s,o){if(!o&&!s&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),De("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Mi.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,n.__internalAwake){const l=Symbol(r),c=n.__internalAwake;n.__internalAwake=function(){var h;if(!this.onValidate){B()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=n.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof ie||d instanceof S||d instanceof fe||d instanceof V){const u=this[r];kd(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[mf]===!0)this[l]=u;else{s?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const uT=function(n){return function(e,t,s){let o="";typeof t=="string"?o=t:o=t.name;const r=n.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const c=l.value,h=e[o];Object.defineProperty(r,o,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var pT=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,Li=(n,e,t,s)=>{for(var o=s>1?void 0:s?mT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&pT(e,t,o),o};class gT{constructor(e,t){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}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]}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)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new co(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new co(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const s=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),s(r,l)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var Ya;const ci=(Ya=class extends j{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new S(0,0,0)),a(this,"constraints",Qe.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Mu.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new S),a(this,"_smoothedVelocity",new S),a(this,"_smoothedVelocityGetter",new S),a(this,"_lastPosition",new S),a(this,"_watch")}get isRigidbody(){return!0}set mass(n){n!==this._mass&&(this._mass=n,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var n,e;return this.autoMass?((e=(n=this.context.physics.engine)==null?void 0:n.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Qe.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Qe.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Qe.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Qe.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Qe.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Qe.FreezeRotationZ)!==0}set lockPositionX(n){n?this.constraints|=Qe.FreezePositionX:this.constraints&=~Qe.FreezePositionX}set lockPositionY(n){n?this.constraints|=Qe.FreezePositionY:this.constraints&=~Qe.FreezePositionY}set lockPositionZ(n){n?this.constraints|=Qe.FreezePositionZ:this.constraints&=~Qe.FreezePositionZ}set lockRotationX(n){n?this.constraints|=Qe.FreezeRotationX:this.constraints&=~Qe.FreezeRotationX}set lockRotationY(n){n?this.constraints|=Qe.FreezeRotationY:this.constraints&=~Qe.FreezeRotationY}set lockRotationZ(n){n?this.constraints|=Qe.FreezeRotationZ:this.constraints&=~Qe.FreezeRotationZ}set gravityScale(n){this._gravityScale=n}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new gT(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Oe.LateUpdate),B()&&(globalThis.NEEDLE_USE_RAPIER?L.RAPIER_PHYSICS.ready().then(async()=>{var n;await Ql(3),(n=this.context.physics.engine)!=null&&n.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(){var n,e;(n=this._watch)==null||n.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var n;(n=this.context.physics.engine)==null||n.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var n,e,t,s;;)this._propertiesChanged&&(this._propertiesChanged=!1,(n=this.context.physics.engine)==null||n.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(n,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(n.x,n.y,n.z):this.setWorldPosition(n.x,n.y,n.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(n=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,n)}resetTorques(n=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,n)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var n;(n=this.context.physics.engine)==null||n.wakeup(this)}get isSleeping(){var n;return(n=this.context.physics.engine)==null?void 0:n.isSleeping(this)}updateProperties(){var n;return this._propertiesChanged=!1,(n=this.context.physics.engine)==null?void 0:n.updateProperties(this)}applyForce(n,e,t=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,n,t)}applyImpulse(n,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,n,e)}setForce(n,e,t,s=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,s),typeof n=="number"?(e??(e=0),t??(t=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:n,y:e,z:t},s)):(l=this.context.physics.engine)==null||l.addForce(this,n,s)}getVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,s=!0){var o,r;if(n instanceof S){const l=n;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,s);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:n,y:e,z:t},s)}getAngularVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,s=!0){var o,r;if(typeof n=="object"){const l=n;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,s);return}if(e===void 0||t===void 0||typeof e=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:n,y:e,z:t},s)}setTorque(n,e,t){typeof n=="number"?this.setAngularVelocity(n,e,t):this.setAngularVelocity(n)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(n=null){}captureVelocity(){const n=this.gameObject.matrixWorld;Ya.tempPosition.setFromMatrixPosition(n);const e=Ya.tempPosition.sub(this._lastPosition);this._lastPosition.copy(Ya.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},a(Ya,"tempPosition",new S),Ya);Li([Tt()],ci.prototype,"autoMass",2),Li([m()],ci.prototype,"mass",1),Li([Tt(),m()],ci.prototype,"useGravity",2),Li([m(S)],ci.prototype,"centerOfMass",2),Li([Tt(),m()],ci.prototype,"constraints",2),Li([Tt(),m()],ci.prototype,"isKinematic",2),Li([Tt(),m()],ci.prototype,"drag",2),Li([Tt(),m()],ci.prototype,"angularDrag",2),Li([Tt(),m()],ci.prototype,"detectCollisions",2),Li([Tt(),m()],ci.prototype,"sleepThreshold",2),Li([Tt(),m()],ci.prototype,"collisionDetectionMode",2),Li([Tt()],ci.prototype,"_gravityScale",2),Li([Tt()],ci.prototype,"dominanceGroup",2);let dt=ci;new S,new S;const To=C("debugsync"),jc="STRS";Eg(jc,ho.getRootAsSyncedTransformModel);const tn=new Hm;function xx(n,e,t=!0){tn.clear();const s=tn.createString(n);ho.startSyncedTransformModel(tn),ho.addGuid(tn,s),ho.addFast(tn,t);const o=e.worldPosition,r=e.worldEuler,l=e.gameObject.scale;ho.addTransform(tn,wx.createTransform(tn,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=ho.endSyncedTransformModel(tn);return tn.finish(c,jc),tn.asUint8Array()}let Nf=0,Dc=0;ox(n=>{var e;const t=(e=n.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;Dc=Math.floor(Nf/t),Nf=0,To&&Dc>0&&console.log("Sync Transform Fast Interval",Dc)});class sn extends j{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new Dt),a(this,"receivedUpdate",!1),a(this,"lastPosition"),a(this,"lastRotation"),a(this,"lastScale")}requestOwnership(){To&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){var e;(e=this._model)==null||e.freeOwnership()}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){To&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new V,this.lastPosition=new S,this.lastRotation=new V,this.lastScale=new S,this.rb=P.getComponentInChildren(this.gameObject,dt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ig(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(se.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(jc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&of(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(se.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(jc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){To&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const s=e.transform();if(s){ms.markDirty(this.gameObject,!0);const o=s.position();o&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=s.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&mg(this.gameObject,this.tempEuler));const l=s.scale();l&&this.gameObject.scale.set(l.x(),l.y(),l.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()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){To&&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,s=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const l=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>l||t.angleTo(this.lastRotation)>l||s.distanceTo(this.lastScale)>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(To&&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),ms.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const l=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const h=this.worldPosition;h.lerp(this._targetPosition,l),this.worldPosition=h,c=!0}if(this.interpolateRotation&&this._targetRotation){const h=this.worldQuaternion;h.slerp(this._targetRotation,l),this.worldQuaternion=h,c=!0}c&&ms.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(s),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(To&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const o=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%o===0||r)){if(Nf++,r&&Dc>0&&this.context.time.frameCount%Dc!==0)return;To&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const l=xx(this.guid,this,!!r);this.context.connection.sendBinary(l)}}}class hd{constructor(e,t){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=t,this.input=e,this.button=t.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const e=new hd(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Ru(n,e){return P.foreachComponent(n,t=>{if(!t.enabled)return;const s=t;if(e)switch(e){case"pointerdown":if(s.onPointerDown)return!0;break;case"pointerup":if(s.onPointerUp||s.onPointerClick)return!0;break;case"pointermove":if(s.onPointerEnter||s.onPointerExit||s.onPointerMove)return!0;break}else if(s.onPointerDown||s.onPointerUp||s.onPointerEnter||s.onPointerExit||s.onPointerClick)return!0},!1)===!0}const Un=new Array;class zn{constructor(e,t,s,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=e,this.methodName=t||null,this.arguments=s,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Un.length=0,e!==void 0&&e.length>0&&Un.push(...e),Un.push(...this.arguments),this.target(...this.arguments),Un.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Un.length=0,e!==void 0&&e.length>0&&Un.push(...e),Un.push(...this.arguments),t.call(this.target,...Un),Un.length=0):t.call(this.target,...e):this.arguments?this.target[this.methodName]=this.arguments[0]||e[0]:this.target[this.methodName]=e[0]}}}}const fT=n=>/^[A-Z]*$/.test(n);class Tu extends Event{constructor(){super(...arguments),a(this,"args")}}class xe{constructor(e){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(e))for(const t of e)t instanceof zn?this.methods.push(t):typeof t=="function"&&this.methods.push(new zn(t));else typeof e=="function"&&this.methods.push(new zn(e))}__internalOnInstantiate(e){var t;const s=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=e[c];if(h){const d=(t=r.arguments)==null?void 0:t.map(u=>u instanceof Object&&u.uuid?e[u.uuid]:u!=null&&u.isComponent?e[u.guid]:u);s.push(new zn(h.clone,r.methodName,d,r.enabled))}else B()&&console.warn("Could not find target for event listener")}}}return new xe(s)}setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let s="",o=!1;for(const r of this.key)o&&fT(r)&&(s+="-"),o=!0,s+=r.toLowerCase();this.key=s}}get listenerCount(){var e;return((e=this.methods)==null?void 0:e.length)??0}get isInvoking(){return this._isInvoking}static from(...e){return new xe(e)}invoke(...e){var t;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((t=this.methods)==null?void 0:t.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const s of this._methodsCopy)s.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const s=this.target.dispatchEvent;if(typeof s=="function"){const o=new Tu(this.key);o.args=e,s.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new zn(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 yT extends es{constructor(){super([re,he],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new he(e.r,e.g,e.b,e.a):e.alpha!==void 0?new he(e.r,e.g,e.b,e.alpha):new re(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 vT=new yT;class bT extends es{constructor(){super([Dt],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new Dt(e.x,e.y,e.z,e.order);if(e.x!=null)return new Dt(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const _T=new bT;class wT extends es{constructor(){super(A,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const s=t.objectToNode[e.uuid];return wt&&console.log(s,e.name,e.uuid),{node:s}}}onDeserialize(e,t){var s,o,r;if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ce))return;B()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(s=t.target)==null?void 0:s.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
|
|
929
929
|
|
|
930
930
|
It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
|
|
931
931
|
|
|
@@ -937,7 +937,7 @@ ${t.path}! : AssetReference;
|
|
|
937
937
|
Could not find method ${d.method} on object ${p.name}. Please rename ${d.method} to ${y}?
|
|
938
938
|
`,p[y],`
|
|
939
939
|
in script: `,p),be("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
|
|
940
|
-
Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){y=!0;break}v=Object.getPrototypeOf(v)}!y&&(B()||wt)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new zn(p,d.method,f,d.enabled);l.push(y)}}else B()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);wt&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const CT=new ST,Au=new WeakMap,PT=je.prototype.clone;je.prototype.clone=function(){const n=PT.call(this);return Au.has(n)||Au.set(n,this),n};class Cx extends es{constructor(){super([Ic,Vs])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof je&&t.type===Ic){let s=e;Au.has(s)&&(s=Au.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof XC&&(s.isCompressedTexture=!1,s.format=yd);const o=new Ic(s.image.width,s.image.height,{colorSpace:On});return o.texture=s,o}}}new Cx;class Px extends es{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return vo(t.gltfId,e)}}new Px;var OT=Object.defineProperty,kT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OT(e,t,o),o};class Ka extends j{awake(){si.createIfNoneExists(this.context)}onEnable(){var e;(e=si.get(this.context))==null||e.register(this)}onDisable(){var e;(e=si.get(this.context))==null||e.unregister(this)}}class ji extends Ka{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Dn),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=o=>o instanceof Pn?"continue in children":t?t(o):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}kT([m()],ji.prototype,"ignoreSkinnedMeshes");class Iu extends ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ox=class yC extends Ka{performRaycast(e){if(!oe.active||!yC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(Ox,"allow",!0);let Bc=Ox;class Wf{static getObject(e){const t=e[Ri];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const o=Er(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&o?.isGraphic===!0&&(t.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Er(e,s=>{const o=s;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Vf(n){return n[Ri]||(n.parent?Vf(n.parent):null)}function MT(n){return n.isUI===!0||typeof n[Ri]=="object"}function Lu(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const s=n.parent;s&&s.isText,t.side=e.doubleSided??!0?Oi:yo,t.shadowSide=e.doubleSided?Oi:yo,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of n.children)Lu(s,e)}function Za(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const s=Proxy.revocable(n[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),o=s.revoke,r=n[e];return s.revoke=()=>{n[e]=r,o()},n[e]=s.proxy,s}const kx=Symbol("Scheduled action");function RT(n,e,t=Oe.OnBeforeRender){let s=n[kx];s||(s=n[kx]={});const o=e.name;s[t]||(s[t]={});const r=s[t];if(r[o])return;function*l(){e?.call(n),r[o]=null}const c=n.startCoroutine(l(),t);r[o]=c}const Eo=C("debugeventsystem");var $f=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))($f||{});nx(n=>{si.createIfNoneExists(n)});class si extends j{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new hd(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==Be.PointerDown,t.isUp=e.type==Be.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const s=new Dn;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),s.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const o=this.performRaycast(s);if(Eo&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:o.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:o.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:o.length})),o){for(const l of o)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:o})}Eo&&t.isClick&&De("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(Ka):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let o=null;if(MT(e)&&(o=(t=e[Ri])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Ru(e,this._currentPointerEventName);if(!r&&o&&(r=Ru(o,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Ao.update(e,t,s)}static markUIDirty(e){Ao.markDirty()}static createIfNoneExists(e){e.scene.getComponent(si)||e.scene.addComponent(si)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(si)}static get instance(){return this.get(J.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const o=(t=this.raycaster)==null?void 0:t.indexOf(e);o!==void 0&&o!==-1&&((s=this.raycaster)==null||s.splice(o,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(Ka)||this.context.scene.addComponent(ji)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}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 s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.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){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const o=this.hoveredByID.get(t.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],o=s.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Eo&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Eo&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,o=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[Ri]){const u=s[Ri].gameObject;if(u){if(!Wf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}o&&Eo&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const o=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),o?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),o?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===zd.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,o.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.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,s,o){let r=e[s];if(o)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const o=this._capturedPointer[s]||[];o.push(t),this._capturedPointer[s]=o}else B()&&!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 s=e.pointerId;if(this._capturedPointer[s]){const o=this._capturedPointer[s].indexOf(t);o!==-1&&(this._capturedPointer[s].splice(o,1),Eo&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Be.PointerMove){const s=e.pointerId,o=this._capturedPointer[s];if(o){Eo&&console.log("Captured",s,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}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)}handleMeshUIIntersection(e,t){const s=Ao.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ao.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ao.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ao{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const o=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(Eo&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:o,nextUpdate:o+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}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}}a(Ao,"lastSelected",null),a(Ao,"lastUpdateFrame",[]),a(Ao,"needsUpdate",!1);var TT=Object.defineProperty,Ue=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TT(e,t,o),o};const is=C("debugorbit"),Hf=C("freecam"),Fc=C("debugcamerafit"),ju=C("smoothcam"),ET={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Gf;class Uc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends j{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new S),a(this,"_lookTargetEndPosition",new S),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new S),a(this,"_cameraEndPosition",new S),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}is&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"_zoomStartDistance",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(is&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):is&&console.debug("OrbitControls: No target update",{deltaAngle:e})}}),a(this,"_shouldDisable",!1),a(this,"__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}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}rotateLeft(e){var t;(t=this._controls)==null||t._rotateLeft(e)}pan(e,t){var s;(s=this._controls)==null||s._pan(e,t)}zoomIn(e){var t,s;e>0?(t=this._controls)==null||t._dollyIn(1-e):e<0&&((s=this._controls)==null||s._dollyOut(1+e))}awake(){is&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=si.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener($f.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener($f.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,hi);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&ag(t,this,!0),!this._controls&&t instanceof A){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,o=t?.quaternion.clone();this._controls=new Gv(t,s),t?.quaternion.copy(o),Gf===void 0&&(Gf={...this._controls.keys});const r=ee(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Hf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Q.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=P.getComponent(this.gameObject,sn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ri.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ri.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ri.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&ag(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)}updateTargetNow(e){var t,s,o;const r=new mo((t=this._cameraObject)==null?void 0:t.worldPosition,(s=this._cameraObject)==null?void 0:s.worldForward.multiplyScalar(-1)),l=this.context.physics.raycastFromRay(r,e),c=l.length>0?l[0]:void 0;c&&c.distance>this.minZoom&&c.distance<this.maxZoom&&(is&&G.DrawWireSphere(c.point,.1,16711680,2),(o=this._controls)==null||o.target.copy(l[0].point))}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))}onBeforeRender(){var e,t,s,o;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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.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 r=P.getComponent(this.gameObject,hi);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=ee(r.threeCamera),c=Math.max(.01,l.length()),h=new S(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);is&&G.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Dn;l.screenPoint=new ie(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Fc&&console.log("OrbitControls hits",...c)}}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 Uc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Uc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?Gf:ET,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Hf||(((s=(t=this._camera)==null?void 0:t.threeCamera)==null?void 0:s.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 ju=="number"||ju===!0){this._controls.enableDamping=!0;const r=typeof ju=="number"?ju:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!Hf&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),is&&G.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(B()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof A)&&!(e instanceof hi))return(B()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof hi&&(e=e.gameObject);const s=e.worldPosition,o=e.worldForward;e instanceof QC&&(is&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),o.multiplyScalar(-1));const r=new mo(s,o);return is&&G.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,X()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof A&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),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((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const o=(s=this._camera)==null?void 0:s.threeCamera;o&&(t===!0?o.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof A&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,is&&(console.warn("OrbitControls: setLookTargetPosition",e,t),G.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(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){var s,o;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of s)if(o.distance>0&&P.isActiveInHierarchy(o.object)){const r=Vf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,t),!0}return!1}fitCamera(e,t){var s,o;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof A)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new S,y=new S,v=ni(r,void 0,(o=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(y);const _=new S;if(v.getSize(_),v.applyMatrix4(l.matrixWorldInverse),v.getSize(f),v.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(f.length()<=1e-10){Fc&&console.warn("Camera fit size is zero",v,[...r]);return}const w=t.fov||l.fov,x=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*x/360)),T=p*Math.max(k,M)+f.z/2;Fc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:x}),this.maxZoom=T*10,this.minZoom=T*.01;const D=.05,z=y.clone();if(z.y-=f.y*D,this.setLookTargetPosition(z,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const F=P.findObjectOfType(en),I=F?F.radius:0,Y=Math.max(_.x,_.y,_.z,I);l.near=T/100,l.far=Y+T*10,F&&(this.maxZoom=Math.max(Math.min(this.maxZoom,I*.5),T))}const U=c.getDistance();U<this.minZoom&&(this.minZoom=U*.9),U>this.maxZoom&&(this.maxZoom=U*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const E=ee(l),$=y.clone();$.sub(E),d==="y"&&($.y=0),$.normalize(),$.multiplyScalar(T),d==="y"&&($.y+=-D*4*T);let H=y.clone().sub($);l.parent&&(H=l.parent.worldToLocal(H)),this.setCameraTargetPosition(H,h),(Fc||t.debug)&&(G.DrawWireBox3(v,16777011,10),G.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Fc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",F=>{if(F.code==="KeyF"){let I;this._cameraObject instanceof we&&(I=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:I})}F.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Ue([m()],_e.prototype,"autoTarget"),Ue([m()],_e.prototype,"autoFit"),Ue([m()],_e.prototype,"enableRotate"),Ue([m()],_e.prototype,"autoRotate"),Ue([m()],_e.prototype,"autoRotateSpeed"),Ue([m()],_e.prototype,"minAzimuthAngle"),Ue([m()],_e.prototype,"maxAzimuthAngle"),Ue([m()],_e.prototype,"minPolarAngle"),Ue([m()],_e.prototype,"maxPolarAngle"),Ue([m()],_e.prototype,"enableKeys"),Ue([m()],_e.prototype,"enableDamping"),Ue([m()],_e.prototype,"dampingFactor"),Ue([m()],_e.prototype,"enableZoom"),Ue([m()],_e.prototype,"minZoom"),Ue([m()],_e.prototype,"maxZoom"),Ue([m()],_e.prototype,"zoomSpeed"),Ue([m()],_e.prototype,"enablePan"),Ue([m(Br)],_e.prototype,"lookAtConstraint"),Ue([m()],_e.prototype,"lookAtConstraint01"),Ue([m()],_e.prototype,"allowInterrupt"),Ue([m()],_e.prototype,"middleClickToFocus"),Ue([m()],_e.prototype,"doubleClickToFocus"),Ue([m()],_e.prototype,"clickBackgroundToFitScene"),Ue([m()],_e.prototype,"targetLerpDuration");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Kt=(n,e,t,s)=>{for(var o=s>1?void 0:s?IT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&AT(e,t,o),o},Ur=(n=>(n[n.None=0]="None",n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(Ur||{});const Io=C("debugcam"),Mx=C("debugscreenpointtoray");var Lo;const zt=(Lo=class extends j{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new ne)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof we&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof we){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&(e||this._cam.near!=n)&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&(e||this._cam.far!=n)&&(this._cam.far=n,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){if(typeof n=="string")switch(n){case"skybox":n=1;break;case"solidcolor":n=2;break;default:n=0;break}n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){n&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(n),(!("alpha"in n)||n.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const s=this.threeCamera,o=Lo._origin;o.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Mx&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(s);const r=Lo._direction.set(o.x,o.y,o.z),l=ee(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new mo(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new Bv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Bv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){Mx&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),o="#"+Math.floor(Math.random()*16777215).toString(16);G.DrawRay(s.origin,s.direction,o,10)})}onEnable(){Io&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Ur[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jT(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new pd(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){var e;if(!this._cam){Io&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Io){const s=`[Camera] Apply ClearFlags: ${Ur[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(Lo.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Io&&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:Io&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;Lo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(Rb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Io&&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 LT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,s,o;const r=(e=n.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Io&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return n.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(Lo,"_origin",new S),a(Lo,"_direction",new S),Lo);Kt([m()],zt.prototype,"aspect",1),Kt([m()],zt.prototype,"fieldOfView",1),Kt([m()],zt.prototype,"nearClipPlane",1),Kt([m()],zt.prototype,"farClipPlane",1),Kt([m()],zt.prototype,"clearFlags",1),Kt([m()],zt.prototype,"orthographic",2),Kt([m()],zt.prototype,"orthographicSize",2),Kt([m()],zt.prototype,"ARBackgroundAlpha",2),Kt([m()],zt.prototype,"cullingMask",1),Kt([m()],zt.prototype,"backgroundBlurriness",1),Kt([m()],zt.prototype,"backgroundIntensity",1),Kt([m(Bt)],zt.prototype,"backgroundRotation",1),Kt([m()],zt.prototype,"environmentIntensity",1),Kt([m(he)],zt.prototype,"backgroundColor",1),Kt([m(Ic)],zt.prototype,"targetTexture",1);let hi=zt;class LT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;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 t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Io&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function jT(n){C("freecam")&&n.context.mainCameraComponent===n&&P.getOrAddComponent(n.gameObject,_e)}class Nn extends j{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new YC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,hi);t!=null&&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 DT=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,Ps=(n,e,t,s)=>{for(var o=s>1?void 0:s?BT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&DT(e,t,o),o};const Et=C("debugaudio"),ss=class dr extends j{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||Q.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Et&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,dr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&dr.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Et&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Et&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Et&&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&&dr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),dr.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.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)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Et&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&dr.userInteractionRegistered){let t=this.gameObject.getComponent(Nn)??this.context.mainCamera.getComponent(Nn)??Sc(Nn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(Nn)),t!=null&&t.listener?(this.sound=new KC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Et&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){Et&&console.log("[AudioSource]",this),this.audioLoader=new Dm,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),dr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():dr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(kg.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(kg.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Et&&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?Et&&!this.helper&&(this.helper=new tO(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(Et&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Dm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Et&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Et&&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){var t,s,o;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(B()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
940
|
+
Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){y=!0;break}v=Object.getPrototypeOf(v)}!y&&(B()||wt)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new zn(p,d.method,f,d.enabled);l.push(y)}}else B()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);wt&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const CT=new ST,Au=new WeakMap,PT=je.prototype.clone;je.prototype.clone=function(){const n=PT.call(this);return Au.has(n)||Au.set(n,this),n};class Cx extends es{constructor(){super([Ic,Vs])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof je&&t.type===Ic){let s=e;Au.has(s)&&(s=Au.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof XC&&(s.isCompressedTexture=!1,s.format=yd);const o=new Ic(s.image.width,s.image.height,{colorSpace:On});return o.texture=s,o}}}new Cx;class Px extends es{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return vo(t.gltfId,e)}}new Px;var OT=Object.defineProperty,kT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OT(e,t,o),o};class Ka extends j{awake(){si.createIfNoneExists(this.context)}onEnable(){var e;(e=si.get(this.context))==null||e.register(this)}onDisable(){var e;(e=si.get(this.context))==null||e.unregister(this)}}class ji extends Ka{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Dn),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=o=>o instanceof Pn?"continue in children":t?t(o):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}kT([m()],ji.prototype,"ignoreSkinnedMeshes");class Iu extends ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ox=class yC extends Ka{performRaycast(e){if(!oe.active||!yC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(Ox,"allow",!0);let Bc=Ox;class Wf{static getObject(e){const t=e[Ri];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const o=Er(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&o?.isGraphic===!0&&(t.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Er(e,s=>{const o=s;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Vf(n){return n[Ri]||(n.parent?Vf(n.parent):null)}function MT(n){return n.isUI===!0||typeof n[Ri]=="object"}function Lu(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const s=n.parent;s&&s.isText,t.side=e.doubleSided??!0?Oi:yo,t.shadowSide=e.doubleSided?Oi:yo,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of n.children)Lu(s,e)}function Za(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const s=Proxy.revocable(n[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),o=s.revoke,r=n[e];return s.revoke=()=>{n[e]=r,o()},n[e]=s.proxy,s}const kx=Symbol("Scheduled action");function RT(n,e,t=Oe.OnBeforeRender){let s=n[kx];s||(s=n[kx]={});const o=e.name;s[t]||(s[t]={});const r=s[t];if(r[o])return;function*l(){e?.call(n),r[o]=null}const c=n.startCoroutine(l(),t);r[o]=c}const Eo=C("debugeventsystem");var $f=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))($f||{});nx(n=>{si.createIfNoneExists(n)});class si extends j{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new hd(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==Be.PointerDown,t.isUp=e.type==Be.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const s=new Dn;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),s.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const o=this.performRaycast(s);if(Eo&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:o.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:o.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:o.length})),o){for(const l of o)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:o})}Eo&&t.isClick&&De("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(Ka):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let o=null;if(MT(e)&&(o=(t=e[Ri])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Ru(e,this._currentPointerEventName);if(!r&&o&&(r=Ru(o,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Ao.update(e,t,s)}static markUIDirty(e){Ao.markDirty()}static createIfNoneExists(e){e.scene.getComponent(si)||e.scene.addComponent(si)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(si)}static get instance(){return this.get(J.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const o=(t=this.raycaster)==null?void 0:t.indexOf(e);o!==void 0&&o!==-1&&((s=this.raycaster)==null||s.splice(o,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(Ka)||this.context.scene.addComponent(ji)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}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 s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.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){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const o=this.hoveredByID.get(t.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],o=s.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Eo&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Eo&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,o=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[Ri]){const u=s[Ri].gameObject;if(u){if(!Wf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}o&&Eo&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const o=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),o?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),o?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===zd.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,o.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.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,s,o){let r=e[s];if(o)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const o=this._capturedPointer[s]||[];o.push(t),this._capturedPointer[s]=o}else B()&&!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 s=e.pointerId;if(this._capturedPointer[s]){const o=this._capturedPointer[s].indexOf(t);o!==-1&&(this._capturedPointer[s].splice(o,1),Eo&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Be.PointerMove){const s=e.pointerId,o=this._capturedPointer[s];if(o){Eo&&console.log("Captured",s,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}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)}handleMeshUIIntersection(e,t){const s=Ao.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ao.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ao.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ao{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const o=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(Eo&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:o,nextUpdate:o+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}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}}a(Ao,"lastSelected",null),a(Ao,"lastUpdateFrame",[]),a(Ao,"needsUpdate",!1);var TT=Object.defineProperty,Ue=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TT(e,t,o),o};const is=C("debugorbit"),Hf=C("freecam"),Fc=C("debugcamerafit"),ju=C("smoothcam"),ET={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Gf;class Uc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends j{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new S),a(this,"_lookTargetEndPosition",new S),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new S),a(this,"_cameraEndPosition",new S),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}is&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"_zoomStartDistance",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(is&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):is&&console.debug("OrbitControls: No target update",{deltaAngle:e})}}),a(this,"_shouldDisable",!1),a(this,"__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}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}rotateLeft(e){var t;(t=this._controls)==null||t._rotateLeft(e)}rotateUp(e){var t;(t=this._controls)==null||t._rotateUp(e)}pan(e,t){var s;(s=this._controls)==null||s._pan(e,t)}zoomIn(e){var t,s;e>0?(t=this._controls)==null||t._dollyIn(1-e):e<0&&((s=this._controls)==null||s._dollyOut(1+e))}awake(){is&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=si.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener($f.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener($f.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,hi);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&ag(t,this,!0),!this._controls&&t instanceof A){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,o=t?.quaternion.clone();this._controls=new Gv(t,s),t?.quaternion.copy(o),Gf===void 0&&(Gf={...this._controls.keys});const r=ee(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Hf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Q.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=P.getComponent(this.gameObject,sn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ri.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ri.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ri.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&ag(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)}updateTargetNow(e){var t,s,o;const r=new mo((t=this._cameraObject)==null?void 0:t.worldPosition,(s=this._cameraObject)==null?void 0:s.worldForward.multiplyScalar(-1)),l=this.context.physics.raycastFromRay(r,e),c=l.length>0?l[0]:void 0;c&&c.distance>this.minZoom&&c.distance<this.maxZoom&&(is&&G.DrawWireSphere(c.point,.1,16711680,2),(o=this._controls)==null||o.target.copy(l[0].point))}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))}onBeforeRender(){var e,t,s,o;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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.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 r=P.getComponent(this.gameObject,hi);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=ee(r.threeCamera),c=Math.max(.01,l.length()),h=new S(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);is&&G.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Dn;l.screenPoint=new ie(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Fc&&console.log("OrbitControls hits",...c)}}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 Uc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Uc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?Gf:ET,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Hf||(((s=(t=this._camera)==null?void 0:t.threeCamera)==null?void 0:s.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 ju=="number"||ju===!0){this._controls.enableDamping=!0;const r=typeof ju=="number"?ju:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!Hf&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),is&&G.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(B()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof A)&&!(e instanceof hi))return(B()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof hi&&(e=e.gameObject);const s=e.worldPosition,o=e.worldForward;e instanceof QC&&(is&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),o.multiplyScalar(-1));const r=new mo(s,o);return is&&G.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,X()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof A&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),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((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const o=(s=this._camera)==null?void 0:s.threeCamera;o&&(t===!0?o.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof A&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,is&&(console.warn("OrbitControls: setLookTargetPosition",e,t),G.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(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){var s,o;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of s)if(o.distance>0&&P.isActiveInHierarchy(o.object)){const r=Vf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,t),!0}return!1}fitCamera(e,t){var s,o;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof A)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new S,y=new S,v=ni(r,void 0,(o=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(y);const _=new S;if(v.getSize(_),v.applyMatrix4(l.matrixWorldInverse),v.getSize(f),v.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(f.length()<=1e-10){Fc&&console.warn("Camera fit size is zero",v,[...r]);return}const w=t.fov||l.fov,x=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*x/360)),T=p*Math.max(k,M)+f.z/2;Fc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:x}),this.maxZoom=T*10,this.minZoom=T*.01;const D=.05,z=y.clone();if(z.y-=f.y*D,this.setLookTargetPosition(z,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const F=P.findObjectOfType(en),I=F?F.radius:0,Y=Math.max(_.x,_.y,_.z,I);l.near=T/100,l.far=Y+T*10,F&&(this.maxZoom=Math.max(Math.min(this.maxZoom,I*.5),T))}const U=c.getDistance();U<this.minZoom&&(this.minZoom=U*.9),U>this.maxZoom&&(this.maxZoom=U*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const E=ee(l),$=y.clone();$.sub(E),d==="y"&&($.y=0),$.normalize(),$.multiplyScalar(T),d==="y"&&($.y+=-D*4*T);let H=y.clone().sub($);l.parent&&(H=l.parent.worldToLocal(H)),this.setCameraTargetPosition(H,h),(Fc||t.debug)&&(G.DrawWireBox3(v,16777011,10),G.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Fc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",F=>{if(F.code==="KeyF"){let I;this._cameraObject instanceof we&&(I=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:I})}F.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Ue([m()],_e.prototype,"autoTarget"),Ue([m()],_e.prototype,"autoFit"),Ue([m()],_e.prototype,"enableRotate"),Ue([m()],_e.prototype,"autoRotate"),Ue([m()],_e.prototype,"autoRotateSpeed"),Ue([m()],_e.prototype,"minAzimuthAngle"),Ue([m()],_e.prototype,"maxAzimuthAngle"),Ue([m()],_e.prototype,"minPolarAngle"),Ue([m()],_e.prototype,"maxPolarAngle"),Ue([m()],_e.prototype,"enableKeys"),Ue([m()],_e.prototype,"enableDamping"),Ue([m()],_e.prototype,"dampingFactor"),Ue([m()],_e.prototype,"enableZoom"),Ue([m()],_e.prototype,"minZoom"),Ue([m()],_e.prototype,"maxZoom"),Ue([m()],_e.prototype,"zoomSpeed"),Ue([m()],_e.prototype,"enablePan"),Ue([m(Br)],_e.prototype,"lookAtConstraint"),Ue([m()],_e.prototype,"lookAtConstraint01"),Ue([m()],_e.prototype,"allowInterrupt"),Ue([m()],_e.prototype,"middleClickToFocus"),Ue([m()],_e.prototype,"doubleClickToFocus"),Ue([m()],_e.prototype,"clickBackgroundToFitScene"),Ue([m()],_e.prototype,"targetLerpDuration");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Kt=(n,e,t,s)=>{for(var o=s>1?void 0:s?IT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&AT(e,t,o),o},Ur=(n=>(n[n.None=0]="None",n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(Ur||{});const Io=C("debugcam"),Mx=C("debugscreenpointtoray");var Lo;const Ut=(Lo=class extends j{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new ne)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof we&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof we){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&(e||this._cam.near!=n)&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&(e||this._cam.far!=n)&&(this._cam.far=n,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){if(typeof n=="string")switch(n){case"skybox":n=1;break;case"solidcolor":n=2;break;default:n=0;break}n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){n&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(n),(!("alpha"in n)||n.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const s=this.threeCamera,o=Lo._origin;o.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Mx&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(s);const r=Lo._direction.set(o.x,o.y,o.z),l=ee(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new mo(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new Bv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Bv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){Mx&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),o="#"+Math.floor(Math.random()*16777215).toString(16);G.DrawRay(s.origin,s.direction,o,10)})}onEnable(){Io&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Ur[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jT(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new pd(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){var e;if(!this._cam){Io&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Io){const s=`[Camera] Apply ClearFlags: ${Ur[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(Lo.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Io&&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:Io&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;Lo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(Rb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Io&&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 LT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,s,o;const r=(e=n.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Io&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return n.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(Lo,"_origin",new S),a(Lo,"_direction",new S),Lo);Kt([m()],Ut.prototype,"aspect",1),Kt([m()],Ut.prototype,"fieldOfView",1),Kt([m()],Ut.prototype,"nearClipPlane",1),Kt([m()],Ut.prototype,"farClipPlane",1),Kt([m()],Ut.prototype,"clearFlags",1),Kt([m()],Ut.prototype,"orthographic",2),Kt([m()],Ut.prototype,"orthographicSize",2),Kt([m()],Ut.prototype,"ARBackgroundAlpha",2),Kt([m()],Ut.prototype,"cullingMask",1),Kt([m()],Ut.prototype,"backgroundBlurriness",1),Kt([m()],Ut.prototype,"backgroundIntensity",1),Kt([m(Dt)],Ut.prototype,"backgroundRotation",1),Kt([m()],Ut.prototype,"environmentIntensity",1),Kt([m(he)],Ut.prototype,"backgroundColor",1),Kt([m(Ic)],Ut.prototype,"targetTexture",1);let hi=Ut;class LT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;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 t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Io&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function jT(n){C("freecam")&&n.context.mainCameraComponent===n&&P.getOrAddComponent(n.gameObject,_e)}class Nn extends j{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new YC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,hi);t!=null&&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 DT=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,Ps=(n,e,t,s)=>{for(var o=s>1?void 0:s?BT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&DT(e,t,o),o};const Et=C("debugaudio"),ss=class dr extends j{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||Q.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Et&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,dr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&dr.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Et&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Et&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Et&&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&&dr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),dr.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.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)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Et&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&dr.userInteractionRegistered){let t=this.gameObject.getComponent(Nn)??this.context.mainCamera.getComponent(Nn)??Sc(Nn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(Nn)),t!=null&&t.listener?(this.sound=new KC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Et&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){Et&&console.log("[AudioSource]",this),this.audioLoader=new Dm,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),dr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():dr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(kg.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(kg.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Et&&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?Et&&!this.helper&&(this.helper=new tO(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(Et&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Dm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Et&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Et&&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){var t,s,o;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(B()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
941
941
|
Using the assigned clip instead:`,this.clip),e=this.clip);let r=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(r=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),r){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Et&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const l=this.context.application.muted;l&&this.sound.setVolume(0),(s=this.gameObject)==null||s.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||(o=this.context.domElement.shadowRoot)==null||o.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(l?.1:0))}}pause(){var e,t;Et&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;Et&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,Et&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}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,Et&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Ps([m(URL)],ss.prototype,"clip",2),Ps([m()],ss.prototype,"playOnAwake",2),Ps([m()],ss.prototype,"preload",2),Ps([m()],ss.prototype,"playInBackground",2),Ps([m()],ss.prototype,"loop",1),Ps([m()],ss.prototype,"spatialBlend",1),Ps([m()],ss.prototype,"minDistance",1),Ps([m()],ss.prototype,"maxDistance",1),Ps([m()],ss.prototype,"volume",1),Ps([m()],ss.prototype,"pitch",1),Ps([m()],ss.prototype,"rollOffMode",2);let ns=ss;const FT=C("debugavatar"),Du=class wn extends j{constructor(){super(...arguments),a(this,"connectionId"),a(this,"avatar")}static getAvatar(e){return e>=0&&e<wn.instances.length?wn.instances[e]:null}static onAvatarMarkerCreated(e){return wn._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return wn._onAvatarMarkerDestroyed.push(e),e}awake(){wn.instances.push(this),FT&&console.log(this);for(const e of wn._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wn.instances.splice(wn.instances.indexOf(this),1);for(const e of wn._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};a(Du,"instances",[]),a(Du,"_onNewAvatarMarkerAdded",[]),a(Du,"_onAvatarMarkerDestroyed",[]);let di=Du;class Wn{static Add(e,t,s=null){if(t){for(const o of this.Pois)if(o.obj===t)return;this.Pois.push({obj:t,avatar:s}),this.LastChangeTime=e.time.time}}static Remove(e,t){var s;if(t){for(const o of this.Pois)if(o.obj===t){this.Pois.splice(this.Pois.indexOf(o),1),this.LastChangeTime=e?.time.time??((s=J.Current)==null?void 0:s.time.time);return}}}}a(Wn,"Pois",[]),a(Wn,"LastChangeTime",0);class UT{constructor(){a(this,"guid"),a(this,"position",new S)}}class zc extends j{constructor(){super(...arguments),a(this,"target",null),a(this,"avatar",null),a(this,"_model",null),a(this,"_targetModel",new UT),a(this,"_currentTargetObject",null),a(this,"_lastUpdateTime",0),a(this,"_lookDuration",0),a(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=R.get("MoveRandom");if(t&&this.target){const s=P.getComponent(this.target,t);s&&s.destroy()}}awake(){if(this.avatar=P.getComponentInParent(this.gameObject,di),this.avatar){const e=P.getComponentInParent(this.gameObject,di);this._model=new Ig(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&<(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Wn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Wn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=ee(this._currentTargetObject);lt(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Wn.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}function Rx(n){const e=n;return!!(e.parser&&e.parser.json)}var Bu=(n=>(n[n.None=0]="None",n[n.DontExport=1]="DontExport",n))(Bu||{});function Tx(n){return n&&n.isComponent}const zT=Symbol("object"),qf=new ki(()=>new S,20);class Ex{constructor(e,t,s,o,r,l){a(this,"_point"),a(this,"_normal"),a(this,"_tangentVelocity"),a(this,"distance"),a(this,"impulse"),a(this,"friction"),this._point=e,this.distance=t,this._normal=s,this.impulse=o,this.friction=r,this._tangentVelocity=l}get point(){return qf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return qf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return qf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class Ax{constructor(e,t,s){a(this,"contacts"),a(this,"me"),a(this,"_collider"),a(this,"_gameObject"),this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=s}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var e;return(e=this.collider)==null?void 0:e.attachedRigidbody}}class Ix{constructor(e,t){a(this,"object"),a(this,"collider"),this.object=e,this.collider=t}}const Ye=C("debugnetworkingstreams");var nn=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(nn||{});class Xf{constructor(e,t){a(this,"type","call-ended"),a(this,"userId"),a(this,"direction"),this.userId=e,this.direction=t}}class Lx{constructor(e,t,s){a(this,"type","receive-stream"),a(this,"userId"),a(this,"stream"),a(this,"target"),this.userId=e,this.stream=t,this.target=s}}class NT{constructor(e,t){a(this,"guid"),a(this,"peerId"),a(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var jx=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(jx||{});class WT extends Bm{constructor(e,t,s,o=null){super(),a(this,"peerId"),a(this,"userId"),a(this,"direction"),a(this,"call"),a(this,"_stream",null),a(this,"_isDisposed",!1),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=s,this._stream=o,t.on("stream",r=>{if(Ye&&console.log("Receive stream",`
|
|
942
942
|
Audio:`,r.getAudioTracks(),`
|
|
943
943
|
Video:`,r.getVideoTracks()),this._stream=r,s==="incoming"){const l=new Lx(e,r,this);this.dispatchEvent(l)}}),t.on("close",()=>{this.dispatchEvent(new Xf(e,s))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),on(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function Dx(n){return n=n.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),n}const Bx=class od extends Bm{constructor(e,t){super(),a(this,"updateCalls",()=>{var s;for(let o=this._incomingCalls.length-1;o>=0;o--){const r=this._incomingCalls[o];r.isClosed&&!r.isOpening&&this._incomingCalls.splice(o,1)}for(let o=this._outgoingCalls.length-1;o>=0;o--){const r=this._outgoingCalls[o];let l=!1;r.isClosed&&!r.isOpening&&((s=r.stream)!=null&&s.active?Ye&&console.warn("!!! Stream is still active, don't remove call",r.userId,"Your id: "+this.context.connection.connectionId):(Ye&&console.warn("!!! Remove closed call",r.userId),l=!0)),this.context.connection.userIsInRoom(r.userId)===!1&&(Ye&&console.warn("!!! User is not in room anymore, remove call",r.userId),l=!0),l&&(r.close(),this._outgoingCalls.splice(o,1))}}),a(this,"id"),a(this,"context"),a(this,"_incomingCalls",[]),a(this,"_outgoingCalls",[]),a(this,"_peer"),a(this,"_enabled",!1),a(this,"_enabledPeer",!1),a(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),a(this,"onPeerConnect",s=>{if(Ye&&console.log("PEER opened as",s),s===null){console.error("Peer connection failed",s);return}this.context.connection.send("peer-user-connected",new NT(this,s))}),a(this,"onPeerClose",()=>{Ye&&console.log("PEER closed"),this.updateCalls()}),a(this,"onPeerDisconnected",()=>{Ye&&console.log("PEER disconnected"),this.updateCalls()}),a(this,"onPeerError",s=>{Ye&&console.error("PEER error",s)}),a(this,"onPeerReceivingCall",s=>{s.answer(void 0,{sdpTransform:o=>Dx(o)}),this.registerCall(s,"incoming",null)}),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,t){if(od.instances.has(t))return od.instances.get(t);const s=new od(e,t);return od.instances.set(t,s),s}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){var s;if(!(t!=null&&t.id)){Ye?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 o={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:l=>Dx(l)},r=(s=this._peer)==null?void 0:s.call(e,t,o);if(r){const l=this.registerCall(r,"outgoing",t);return Ye&&console.warn(`\u{1F4DE} CALL ${e}`,`
|
|
@@ -945,7 +945,7 @@ Outgoing:`,this._outgoingCalls,`
|
|
|
945
945
|
Incoming:`,this._incomingCalls),l}else Ye&&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()}get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(se.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(se.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=g_(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))}registerCall(e,t,s){const o=e.metadata;(!o||!o.userId)&&console.error("Missing call metadata",e);const r=o.userId;t==="incoming"&&Ye?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):Ye&&console.warn("\u2192 Make call to",e.metadata);const l=t==="incoming"?this._incomingCalls:this._outgoingCalls,c=new WT(r,e,t,s);return l.push(c),e.on("error",h=>{console.error("Call error",h)}),e.on("close",()=>{Ye&&console.log("Call ended",e.metadata);const h=l.indexOf(c);h!==-1&&l.splice(h,1),c.close(),this.dispatchEvent(new Xf(r,t))}),c.addEventListener("call-ended",h=>{this.dispatchEvent(h)}),t==="incoming"&&(c.addEventListener("receive-stream",h=>{this.dispatchEvent(h)}),e.on("stream",()=>{Ye&&console.log("Received stream for call",e.metadata);let h=0;const d=setInterval(()=>{const u=h===0;!c.isOpen&&u&&(Ye&&console.warn("Close call because stream is not active",e.metadata),h+=1,clearInterval(d),c.close())},2e3)})),c}};a(Bx,"instances",new Map);let Fu=Bx;class dd extends Bm{constructor(e,t){if(super(),a(this,"context"),a(this,"peer"),a(this,"_sendingStreams",new Map),a(this,"debug",!1),a(this,"_enabled",!1),a(this,"_tickIntervalId"),a(this,"tick",()=>{this.updateSendingCalls()}),a(this,"onJoinedRoom",s=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${s!=null&&s.userId?`User ${s.userId}`:"You"} joined room`,s,this._sendingStreams.size),this.updateSendingCalls())}),a(this,"onLeftRoom",s=>{this.debug&&console.warn(`${s?.userId||"You"} left room`,s),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()}),a(this,"onCallStreamReceived",s=>{this.debug&&console.log("Call with "+s.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:s.stream,userId:s.userId}),this.debug&&this.debugLogCurrentState()}),a(this,"onCallEnded",s=>{this.debug&&console.log("Call with "+s.userId+" ended"),this.dispatchEvent(s),this.debug&&this.debugLogCurrentState()}),a(this,"onUserConnected",s=>{if(this.peer.id===s.guid){this.debug&&console.log("PEER USER CONNECTED",s.guid,s,this._sendingStreams.size);const o=this._sendingStreams.keys().next().value;this.peer.makeCall(s.peerId,o)}else Ye&&console.log("Unknown user connected",s.guid,s.peerId)}),a(this,"onUserLeft",s=>{this.debug&&console.log("User left room: "+s.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),Tx(e)){const s=e;e=s.context,t=Fu.getOrCreate(s.context,s.guid)}else typeof t=="string"&&(t=Fu.getOrCreate(e,t));if(e){if(!(e instanceof J))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,Ye&&(this.debug=!0)}static create(e,t){const s=Fu.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new dd(e.context,s)}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 s of t)s.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}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(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(se.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(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const s=this._sendingStreams.get(t)||[];for(const o of this.context.connection.usersInRoom()){if(o===e)continue;const r=this.peer.getPeerIdFromUserId(o);if(s.find(l=>{var c;return l.peerId===r&&l.direction==="outgoing"&&!l.isClosed&&((c=l.stream)==null?void 0:c.active)}))Ye&&console.debug("Already have a call with user "+o+" / peer "+r);else{const l=this.peer.makeCall(r,t);l&&s.push(l)}}this._sendingStreams.set(t,s)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let s=t.length-1;s>=0;s--){const o=t[s];this.context.connection.userIsInRoom(o.userId)?Ye&&(this.context.connection.connectionId===o.userId?console.warn(`You are still in the room [${s}] ${o.userId}`):console.log(`User is still in room [${s}] ${o.userId}`)):(Ye&&console.log(`Remove call ${[s]} to user that is not in room anymore ${o.userId}`),o.close(),t.splice(s,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 on(n){if(n&&n instanceof MediaStream)for(const e of n.getTracks())e.stop()}var VT=Object.defineProperty,Qf=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&VT(e,t,o),o};const $T="noVoip",HT=C("debugvoip");class jo extends j{constructor(){super(...arguments),a(this,"autoConnect",!0),a(this,"runInBackground",!0),a(this,"createMenuButton",!0),a(this,"debug",!1),a(this,"_net"),a(this,"_menubutton"),a(this,"_allowSending",!0),a(this,"_outputStream",null),a(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await $s(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()}),a(this,"onLeftRoom",()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())on(e.srcObject);this._incomingStreams.clear()}),a(this,"_incomingStreams",new Map),a(this,"onReceiveStream",e=>{const t=e.target.userId,s=e.stream;let o=this._incomingStreams.get(t);o||(o=new Audio,this._incomingStreams.set(t,o)),o.srcObject=s,o.setAttribute("autoplay","true"),Ln.registerWaitForInteraction(()=>{o?.play().catch(r=>{console.error("VOIP: Failed to play audio",r)})})}),a(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);on(t?.srcObject),this._incomingStreams.delete(e.userId)}),a(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}}),a(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const s=t[1];s.muted=e}})}awake(){HT&&(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=dd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(nn.StreamReceived,this.onReceiveStream),this._net.addEventListener(nn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(nn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(nn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable()),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){var e;(e=this._menubutton)==null||e.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){var t,s;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 Q.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,(t=this._net)==null||t.stopSendingStream(this._outputStream),on(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(s=this._net)==null||s.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await Q.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):sc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||B())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){var t;e!=null&&e.remember&&(this._allowSending=!1),(t=this._net)==null||t.stopSendingStream(this._outputStream),on(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){var t;const s=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(s)for(const o of s)o.enabled=!e}get isMuted(){var e;if(this._outputStream===null)return!1;const t=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(t){for(const s of t)if(!s.enabled)return!0}return!1}async updateButton(){var e;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),Q.microphonePermissionsGranted().then(t=>{t||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 t=(this.isSending,""),s=this.isSending?"mic":"mic_off";await Q.microphonePermissionsGranted()||(t="No Permission",s="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=t,this._menubutton.prepend(Mt(s)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(e=this._menubutton)==null||e.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,B()&&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 o=>await navigator.mediaDevices.getUserMedia({audio:o??!0,video:!1}).catch(r=>(console.warn("VOIP failed getting audio stream",r),null)),s=await t(e);if(!s)return null;if(Q.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);return r.deviceId=o.deviceId,await t(r)}}return s}}Qf([m()],jo.prototype,"autoConnect"),Qf([m()],jo.prototype,"runInBackground"),Qf([m()],jo.prototype,"createMenuButton");var GT=Object.defineProperty,Fx=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&>(e,t,o),o};const qT=C("debugmouth");class Nc extends j{constructor(){super(...arguments),a(this,"idle",[]),a(this,"talking",[]),a(this,"marker",null),a(this,"voip",null),a(this,"lastMouthChangeTime",0),a(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=P.findObjectOfType(jo,this.context),this.marker||(this.marker=P.getComponentInParent(this.gameObject,di))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){qT&&(t=null);return}const s=this.voip.getFrequency(t)??0;this.updateLips(s)}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(s=>s.visible=!1):this.talking.map(s=>s.visible=!1);for(let s=0;s<e.length;s++){const o=e[s];o&&(o.visible=s===t)}}}}Fx([m(A)],Nc.prototype,"idle"),Fx([m(A)],Nc.prototype,"talking");class Yf extends j{constructor(){super(...arguments),a(this,"voip",null),a(this,"marker",null),a(this,"_startPosition",null)}awake(){this.voip=P.findObjectOfType(jo,this.context),this.marker=P.getComponentInParent(this.gameObject,di)}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 s=t/100;this.gameObject.position.y=this._startPosition.y+s*.07}}var XT=Object.defineProperty,QT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&XT(e,t,o),o};const Ja=C("debugxrflags"),Ux=C("disablexrflags");Ux&&console.warn("XRFlags are disabled");var rn=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(rn||{});const Kf=class{constructor(){a(this,"Mask",17)}Has(e){return(this.Mask&e)!==0}Set(e){Ja&&console.warn("Set XR flag state to",e),this.Mask=e,os.Apply()}Enable(e){this.Mask|=e,os.Apply()}Disable(e){this.Mask&=~e,os.Apply()}Toggle(e){this.Mask^=e,os.Apply()}EnableAll(){this.Mask=-1,os.Apply()}DisableAll(){this.Mask=0,os.Apply()}};a(Kf,"Global",new Kf);let Di=Kf;var Bi;const zx=(Bi=class extends j{constructor(){super(...arguments),a(this,"visibleIn")}static Apply(){for(const n of this.registry)n.UpdateVisible(Di.Global)}awake(){Bi.registry.push(this)}onEnable(){Bi.firstApply?this.UpdateVisible(Di.Global):(Bi.firstApply=!0,Bi.Apply())}onDestroy(){const n=Bi.registry.indexOf(this);n>=0&&Bi.registry.splice(n,1)}get isOn(){return this.gameObject.visible}UpdateVisible(n=null){if(Ux)return;let e;const t=n;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),Ja&&console.log(t),Bi.buffer.Mask=t,n=Bi.buffer),n instanceof Di?(Ja&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),e=n.Has(this.visibleIn)):(Ja&&console.log(this.name,"use global mask"),Di.Global.Has(this.visibleIn)),e!==void 0)if(e)Ja&&console.log(this.name,"is visible",this.gameObject.uuid),P.setActive(this.gameObject,!0);else{if(Ja&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},a(Bi,"registry",[]),a(Bi,"firstApply"),a(Bi,"buffer",new Di),Bi);QT([m()],zx.prototype,"visibleIn");let os=zx;var YT=Object.defineProperty,Uu=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YT(e,t,o),o};class zr extends j{constructor(){super(...arguments),a(this,"eyes",[]),a(this,"lastBlinkTime",0),a(this,"blinkLength",0),a(this,"eyesOpen",!0),a(this,"state",null)}awake(){this.state=P.getComponentInParent(this.gameObject,os)}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)}}}Uu([m(A)],zr.prototype,"eyes"),Uu([m()],zr.prototype,"lastBlinkTime"),Uu([m()],zr.prototype,"blinkLength"),Uu([m()],zr.prototype,"eyesOpen");var KT=Object.defineProperty,Zf=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&KT(e,t,o),o},zu;const Nu=(zu=class extends j{constructor(){super(...arguments),a(this,"head",null),a(this,"eyes",null),a(this,"target",null),a(this,"brain",null),a(this,"vec",new S),a(this,"currentTargetPoint",new S)}awake(){this.brain||(this.brain=P.getComponentInParent(this.gameObject,zc)),this.brain||(this.brain=P.addComponent(this.gameObject,zc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const n=this.target;if(n&&this.head){const e=this.eyes;if(e){const t=ee(n);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const s=ee(this.head),o=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(o.length()<.1)return;const r=zu.forward;if(r.set(0,0,1),r.applyQuaternion(Se(this.head)),r.dot(o)>.45)for(let l=0;l<e.length;l++)e[l].lookAt(this.currentTargetPoint)}}}},a(zu,"forward",new S(0,0,1)),zu);Zf([m(A)],Nu.prototype,"head"),Zf([m(A)],Nu.prototype,"eyes"),Zf([m(A)],Nu.prototype,"target");let Jf=Nu;var ZT=Object.defineProperty,e0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&ZT(e,t,o),o};class el extends j{constructor(){super(...arguments),a(this,"length",1),a(this,"depthTest",!0),a(this,"isGizmo",!1),a(this,"_axes",null)}onEnable(){if(this.isGizmo&&!vc)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)}}e0([m()],el.prototype,"length"),e0([m()],el.prototype,"depthTest"),e0([m()],el.prototype,"isGizmo");class t0 extends j{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"hint"),a(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ee(this.to).clone(),t=ee(this.from).clone(),s=e.distanceTo(t),o=e.clone();o.sub(t);const r=t.clone();r.add(e),r.multiplyScalar(.5);const l=ee(this.hint).clone();l.sub(r);const c=new S;c.crossVectors(l,o),c.crossVectors(o,c),c.normalize();const h=s*.5,d=Math.max(this.desiredDistance,h),u=Math.sqrt(d*d-h*h),p=c.clone();p.multiplyScalar(u),p.add(r),lt(this.gameObject,p);const g=r.clone();g.sub(c),this.gameObject.lookAt(g)}}const JT=C("gizmos"),eE=C("debugboxhelper"),Wc=class xn extends j{constructor(){super(...arguments),a(this,"box",null),a(this,"_lastMatrixUpdateFrame",-1),a(this,"_helper",null),a(this,"_color",null)}isInBox(e){var t;if(!e)return;if(this.box||(this.box=new Ci),ni([e],void 0,void 0,xn.testBox),xn.testBox.isEmpty()){const o=ee(e,xn._position);xn.testBox.setFromCenterAndSize(o,xn._emptyObjectSize)}this.updateBox();const s=(t=this.box)==null?void 0:t.intersectsBox(xn.testBox);return s&&eE&&G.DrawWireBox3(xn.testBox,16711680,5),s}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Ci),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const s=t,o=ee(this.gameObject,xn._position,s),r=Ge(this.gameObject,xn._size);this.box.setFromCenterAndSize(o,r)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){var s;if(!(!JT&&!t)){if(this._helper){e&&((s=this._color)==null||s.set(e)),this.gameObject.add(this._helper);return}this._helper=$g(e),this.gameObject.add(this._helper)}}};a(Wc,"testBox",new Ci),a(Wc,"_position",new S),a(Wc,"_size",new S(.01,.01,.01)),a(Wc,"_emptyObjectSize",new S(.01,.01,.01));let Do=Wc;var tE=Object.defineProperty,ui=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&tE(e,t,o),o};class pi extends j{constructor(){super(...arguments),a(this,"attachedRigidbody",null),a(this,"isTrigger",!1),a(this,"sharedMaterial"),a(this,"membership",[0]),a(this,"filter"),a(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(dt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(dt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(dt))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}ui([m(dt)],pi.prototype,"attachedRigidbody"),ui([m()],pi.prototype,"isTrigger"),ui([m()],pi.prototype,"sharedMaterial"),ui([m()],pi.prototype,"membership"),ui([m()],pi.prototype,"filter");class tl extends pi{constructor(){super(...arguments),a(this,"radius",.5),a(this,"center",new S(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),kd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Zm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}ui([Tt(),m()],tl.prototype,"radius"),ui([m(S)],tl.prototype,"center");const i0=class vC extends pi{constructor(){super(...arguments),a(this,"size",new S(1,1,1)),a(this,"center",new S(0,0,0))}static add(e,t){const s=Ei(e,vC);return s.autoFit(),t?.rigidbody===!0&&Ei(e,dt,{isKinematic:!1}),s}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),kd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Zm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,s=t.position.clone(),o=t.quaternion.clone(),r=t.scale.clone(),l=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 c=ni([t]);t.position.copy(s),t.quaternion.copy(o),t.scale.copy(r),t.parent=l,e?.debug===!0&&G.DrawWireBox3(c,16768256,20),this.size=c.getSize(new S)||new S(1,1,1),this.center=c.getCenter(new S)||new S(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};ui([Tt(),m(S)],i0.prototype,"size"),ui([m(S)],i0.prototype,"center");let Wu=i0;class Bo extends pi{constructor(){super(...arguments),a(this,"sharedMesh"),a(this,"convex",!1)}onEnable(){var e,t,s;if(super.onEnable(),!this.context.physics.engine)return;(e=this.sharedMesh)!=null&&e.isMesh||(this.gameObject instanceof q||this.gameObject instanceof go)&&(this.sharedMesh=this.gameObject);const o=0;if((t=this.sharedMesh)!=null&&t.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Xe.assignMeshLOD(this.sharedMesh,o).then(r=>{r&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=r,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const r=this.sharedMesh;if(r!=null&&r.isGroup){console.warn(`MeshCollider mesh is a group "${((s=this.sharedMesh)==null?void 0:s.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 l=new Array;for(const c in r.children){const h=r.children[c];h.isMesh&&(this.context.physics.engine.addMeshCollider(this,h,this.convex),l.push(Xe.assignMeshLOD(h,o)))}Promise.all(l).then(c=>{var h,d;if(c.some(p=>p)==!1)return;(h=this.context.physics.engine)==null||h.removeBody(this);const u=new q;for(const p of c)p&&this.activeAndEnabled&&(u.geometry=p,(d=this.context.physics.engine)==null||d.addMeshCollider(this,u,this.convex))})}else(B()||C("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)}}}ui([m(q)],Bo.prototype,"sharedMesh"),ui([m()],Bo.prototype,"convex");class Vn extends pi{constructor(){super(...arguments),a(this,"center",new S(0,0,0)),a(this,"radius",.5),a(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}ui([m(S)],Vn.prototype,"center"),ui([m()],Vn.prototype,"radius"),ui([m()],Vn.prototype,"height");var iE=Object.defineProperty,$n=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&iE(e,t,o),o};const Nx=C("debugcharactercontroller");class Nr extends j{constructor(){super(...arguments),a(this,"center",new S(0,0,0)),a(this,"radius",.5),a(this,"height",2),a(this,"_rigidbody",null),a(this,"_activeGroundCollisions"),a(this,"_contactVelocity",new S)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(dt),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(dt)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Vn);t||(t=this.gameObject.addComponent(Vn)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const s=new S(0,0,1),o=new S(1,0,0),r=new S(0,1,0),l=this.gameObject.getWorldDirection(new S);l.y=0;const c=o.dot(l)<0?-1:1,h=s.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(r,h),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),Nx&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Nx&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const t of this._activeGroundCollisions){const s=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);s&&(this._contactVelocity.x+=s.x,this._contactVelocity.y+=s.y,this._contactVelocity.z+=s.z)}return this._contactVelocity}}$n([m(S)],Nr.prototype,"center"),$n([m()],Nr.prototype,"radius"),$n([m()],Nr.prototype,"height");class Hn extends j{constructor(){super(...arguments),a(this,"controller"),a(this,"movementSpeed",2),a(this,"rotationSpeed",2),a(this,"jumpForce",1),a(this,"doubleJumpForce",2),a(this,"animator"),a(this,"lookForward",!0),a(this,"lookInput",new ie(0,0)),a(this,"moveInput",new ie(0,0)),a(this,"jumpInput",!1),a(this,"_currentSpeed",new S(0,0,0)),a(this,"_currentAngularSpeed",new S(0,0,0)),a(this,"_temp",new S(0,0,0)),a(this,"_jumpCount",0),a(this,"_currentRotation"),a(this,"_raycastOptions",new Dn)}awake(){this._currentRotation=new V}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||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,t,s){var o,r,l,c,h,d,u,p,g,f,y;if((o=this.controller)!=null&&o.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((r=this.animator)==null||r.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",e.length()>.01),(h=this.animator)==null||h.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&s),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+=W.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const v=this.context.mainCameraComponent.forward;v.y=0,v.normalize(),this._currentRotation.setFromUnitVectors(new S(0,0,1),v),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&&s&&this.jumpForce>0){let v=(d=this.controller)==null?void 0:d.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(v=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),v){this._jumpCount+=1;const b=this.controller.rigidbody,_=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;b.applyImpulse(new S(0,1,0).multiplyScalar(_))}}if(this.controller){const v=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(v<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new mo),this._raycastOptions.ray.origin.copy(ee(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const b=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const _=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(b),(_.length&&_[0].distance>2||v<-10)&&((f=this.animator)==null||f.setBool("falling",!0))}else(y=this.animator)==null||y.setBool("falling",!1)}}}$n([m(Nr)],Hn.prototype,"controller"),$n([m()],Hn.prototype,"movementSpeed"),$n([m()],Hn.prototype,"rotationSpeed"),$n([m()],Hn.prototype,"jumpForce"),$n([m()],Hn.prototype,"doubleJumpForce"),$n([m(Rt)],Hn.prototype,"animator");var sE=Object.defineProperty,il=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sE(e,t,o),o};const Vc=C("debugcontactshadows");jf(n=>{const e=n.domElement.getAttribute("contactshadows")||n.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=$c.auto(n),s=parseFloat(e);isNaN(s)||(t.opacity=s,t.darkness=s)}});var Wr;const Vr=(Wr=class extends j{constructor(){super(...arguments),a(this,"autoFit",!1),a(this,"darkness",.5),a(this,"opacity",.5),a(this,"blur",4),a(this,"occludeBelowGround",!1),a(this,"backfaceShadows",!0),a(this,"minSize"),a(this,"manualUpdate",!1),a(this,"_needsUpdate",!1),a(this,"shadowsRoot",new A),a(this,"shadowCamera"),a(this,"shadowGroup",new go),a(this,"renderTarget"),a(this,"renderTargetBlur"),a(this,"plane"),a(this,"occluderMesh"),a(this,"blurPlane"),a(this,"depthMaterial"),a(this,"horizontalBlurMaterial"),a(this,"verticalBlurMaterial"),a(this,"textureSize",512)}static auto(n){if(n||(n=J.Current),!n)throw new Error("No context provided and no current context set.");let e=this._instances.get(n);if(!e||e.destroyed){const t=new A;e=Ei(t,Wr,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(n,e)}return n.scene.add(e.gameObject),e.fitShadows(),e}set needsUpdate(n){this._needsUpdate=n}get needsUpdate(){return this._needsUpdate}fitShadows(){Vc&&console.warn("Fitting shadows to scene"),Ed(this.shadowsRoot,!1);const n=ni(this.context.scene.children,[this.shadowsRoot]),e=Math.max(1,this.blur/32),t=n.max.x-n.min.x,s=n.max.z-n.min.z;n.expandByVector(new S(e*t,0,e*s)),Vc&&G.DrawWireBox3(n,16776960,60),this.gameObject.parent&&n.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=n.min,r=Math.max(1e-5,(n.max.y-o.y)*.002);n.max.y+=r,this.shadowsRoot.position.set((o.x+n.max.x)/2,o.y-r,(o.z+n.max.z)/2),this.shadowsRoot.scale.set(n.max.x-o.x,n.max.y-o.y,n.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Vc&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Wr._instances.set(this.context,this),this.shadowsRoot.hideFlags=Bu.DontExport,Ed(this.shadowsRoot,!1)}start(){Vc&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new Vs(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new Vs(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const n=new zs(1,1).rotateX(Math.PI/2);this.gameObject instanceof q&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Fn(this.gameObject,!1));const e=new Me({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:yo});this.plane=new q(n,e),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new q(this.plane.geometry,new Me({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:xd})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new q(n),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const t=0,s=1;this.shadowCamera=new pd(-1/2,1/2,1/2,-1/2,t,s),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new ZC,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=JC,this.depthMaterial.blendEquation=eP,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
|
|
946
946
|
uniform float darkness;
|
|
947
947
|
${o.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
|
|
948
|
-
`)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Ns(iO),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Ns(sO),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){var n,e,t,s,o,r,l,c;Wr._instances.get(this.context)===this&&Wr._instances.delete(this.context),(n=this.renderTarget)==null||n.dispose(),(e=this.renderTargetBlur)==null||e.dispose(),(t=this.depthMaterial)==null||t.dispose(),(s=this.horizontalBlurMaterial)==null||s.dispose(),(o=this.verticalBlurMaterial)==null||o.dispose(),(r=this.blurPlane)==null||r.geometry.dispose(),(l=this.plane)==null||l.geometry.dispose(),(c=this.occluderMesh)==null||c.geometry.dispose()}onBeforeRender(n){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){Vc&&console.error("ContactShadows: not initialized yet");return}const e=this.context.scene,t=this.context.renderer,s=t.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof q&&Fn(this.gameObject,!1);const r=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Oi:this.depthMaterial.side=yo;const l=t.getClearAlpha();t.setClearAlpha(0);const c=t.xr.enabled;t.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=t.renderLists.get(e,0),u=d.transparent;Wx.length=0,d.transparent=Wx,s0.length=0;for(const g of d.opaque){if(!g.object.visible)continue;const f=g.material;let y=g.material.colorWrite==!1||f.wireframe===!0||Nb(g.object)===!1;!y&&g.material.isLineMaterial&&(y=!0),!y&&g.material.isPointsMaterial&&(y=!0),y&&(s0.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}t.setRenderTarget(this.renderTarget),t.clear(),t.render(e,this.shadowCamera),d.transparent=u;for(const g of s0)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);e.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=o,t.setRenderTarget(s),t.setClearAlpha(l),e.background=r,t.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(n){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const e=this.shadowsRoot.worldScale,t=(e.x+e.z)/2,s=e.z/t,o=e.x/t;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=n*1/this.textureSize*s;const r=this.context.renderer,l=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=n*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(l)}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))}},a(Wr,"_instances",new Map),Wr);il([m()],Vr.prototype,"autoFit"),il([m()],Vr.prototype,"darkness"),il([m()],Vr.prototype,"opacity"),il([m()],Vr.prototype,"blur"),il([m()],Vr.prototype,"occludeBelowGround"),il([m()],Vr.prototype,"backfaceShadows");let $c=Vr;const Wx=[],s0=new Array,nE=C("logstats");class n0 extends j{onEnable(){console.log(this),nE&&this.startCoroutine(this.run(),Oe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Hc extends j{constructor(){super(...arguments),a(this,"isUsed",!0),a(this,"usedBy",null)}}class o0 extends j{}const Vx=C("debugdeletable"),$x=class wm extends Do{onEnable(){wm._instances.push(this)}onDisable(){const e=wm._instances.indexOf(this);e>=0&&wm._instances.splice(e,1)}};a($x,"_instances",[]);let Vu=$x;class r0 extends j{update(){for(const e of Vu._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const s=P.getComponentInParent(this.gameObject,Hc);if(s)Vx&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,s);else{if(Vx)try{if(e.box){const o=e.box,r=Do.testBox;G.DrawWireBox3(o,16711680,5),G.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}yc(this.gameObject,this.context.connection)}}}}}var oE=Object.defineProperty,rE=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&oE(e,t,o),o};class $u extends j{constructor(){super(...arguments),a(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||P.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Q.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}rE([m()],$u.prototype,"visibleOn");var aE=Object.defineProperty,$r=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&aE(e,t,o),o};const an=C("debugdrag"),a0=[];var l0=(n=>(n[n.XZPlane=0]="XZPlane",n[n.Attached=1]="Attached",n[n.HitNormal=2]="HitNormal",n[n.DynamicViewAngle=3]="DynamicViewAngle",n[n.SnapToSurfaces=4]="SnapToSurfaces",n[n.None=5]="None",n))(l0||{}),Nt;const Fo=(Nt=class extends j{constructor(){super(...arguments),a(this,"dragMode",3),a(this,"snapGridResolution",0),a(this,"keepRotation",!0),a(this,"xrDragMode",1),a(this,"xrKeepRotation",!1),a(this,"xrDistanceDragFactor",1),a(this,"showGizmo",!1),a(this,"_rigidbody",null),a(this,"_targetObject",null),a(this,"_dragHelper",null),a(this,"_draggingRigidbodies",[]),a(this,"_potentialDragStartEvt",null),a(this,"_dragHandlers",new Map),a(this,"_totalMovement",new S),a(this,"_marker",null),a(this,"_isDragging",!1),a(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){a0.length=0;for(const n of this._instances)n._isDragging&&a0.push(n);return a0}get draggedObject(){return this._targetObject}setTargetObject(n){var e,t;this._targetObject=n;for(const o of this._dragHandlers.values())o.setTargetObject(n);const s="_rigidbody-was-kinematic";((e=this._rigidbody)==null?void 0:e[s])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[s]=void 0),this._rigidbody=null,n&&(this._rigidbody=P.getComponentInChildren(n,dt),((t=this._rigidbody)==null?void 0:t.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[s]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new S,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(ji)||this.gameObject.addComponent(ji)}onEnable(){Nt._instances.push(this)}onDisable(){Nt._instances=Nt._instances.filter(n=>n!==this)}allowEdit(n=null){return this.context.connection.allowEditing}onPointerEnter(n){if(!this.allowEdit(this.gameObject)||n.mode!=="screen"||(n.event.mode==="tracked-pointer"||n.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=P.getComponentInParent(n.object,Nt);!e||e!==this||(Nt.lastHovered=n.object,this.context.domElement.style.cursor="pointer")}onPointerMove(n){(this._isDragging||this._potentialDragStartEvt!==null)&&n.use()}onPointerExit(n){this.allowEdit(this.gameObject)&&n.mode==="screen"&&Nt.lastHovered===n.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(n){if(!(!this.allowEdit(this.gameObject)||n.used||(n.mode==="tracked-pointer"||n.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Nt.lastHovered=n.object,n.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=n),this._targetObject||this.setTargetObject(this.gameObject),Nt._active+=1;const e=new c0(this,this._targetObject);if(this._dragHandlers.set(n.event.space,e),e.onDragStart(n),this._dragHandlers.size===2){const t=this._dragHandlers.values(),s=t.next().value,o=t.next().value;if(s instanceof c0&&o instanceof c0){const r=new lE(this,this._targetObject,s,o);this._dragHandlers.set(this.gameObject,r),r.onDragStart(n)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:s,b:o})}n.use()}}onPointerUp(n){if(an&&G.DrawLabel(n.point??this.gameObject.worldPosition,"POINTERUP:"+n.pointerId+", "+n.button,.03,3),!this.allowEdit(this.gameObject)||n.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(n.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(n)),e&&(Nt._active>0&&(Nt._active-=1),this.setTargetObject(null),e.onDragEnd&&e.onDragEnd(n),this._dragHandlers.delete(n.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(n),n.use())}update(){for(const n of this._dragHandlers.values())n.collectMovementInfo&&n.collectMovementInfo(),n.getTotalMovement&&this._totalMovement.add(n.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const n=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(n)}for(const n of this._dragHandlers.values())n.onDragUpdate&&n.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(n){if(!n||!n.object)return;const e=P.getComponentInParent(n.object,Nt);if(!e||e!==this&&e._isDragging)return;const t=this._targetObject||this.gameObject;if(!t)return;this._isDragging=!0;const s=P.getComponentInChildren(t,sn);an&&console.log("DRAG START",s,t),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=P.addComponent(t,Hc),this._draggingRigidbodies.length=0;const o=P.getComponentsInChildren(t,dt);o&&this._draggingRigidbodies.push(...o)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const n=this._targetObject||this.gameObject;ms.markDirty(n)}onLastDragEnd(n){if(!this||!this._isDragging)return;this._isDragging=!1;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,n!=null&&n.object){const t=P.getComponentInChildren(n.object,sn);t&&(t.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const e=this._dragHelper.selected;an&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context)}},a(Nt,"_active",0),a(Nt,"_instances",[]),a(Nt,"lastHovered"),Nt);$r([m()],Fo.prototype,"dragMode"),$r([m()],Fo.prototype,"snapGridResolution"),$r([m()],Fo.prototype,"keepRotation"),$r([m()],Fo.prototype,"xrDragMode"),$r([m()],Fo.prototype,"xrKeepRotation"),$r([m()],Fo.prototype,"xrDistanceDragFactor"),$r([m()],Fo.prototype,"showGizmo");let Hr=Fo;class lE{constructor(e,t,s,o){a(this,"handlerA"),a(this,"handlerB"),a(this,"context"),a(this,"settings"),a(this,"gameObject"),a(this,"_handlerAAttachmentPoint",new S),a(this,"_handlerBAttachmentPoint",new S),a(this,"_followObject"),a(this,"_manipulatorObject"),a(this,"_deviceMode"),a(this,"_followObjectStartWorldQuaternion",new V),a(this,"_manipulatorPosOffset",new S),a(this,"_manipulatorRotOffset",new V),a(this,"_manipulatorScaleOffset",new S),a(this,"_tempVec1",new S),a(this,"_tempVec2",new S),a(this,"_tempVec3",new S),a(this,"tempLookMatrix",new ne),a(this,"_initialScale",new S),a(this,"_initialDistance",0);var r,l;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=s,this.handlerB=o,this._followObject=new A,this._manipulatorObject=new A,this.context.scene.add(this._manipulatorObject);const c=(l=(r=oe.active)==null?void 0:r.rig)==null?void 0:l.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),c&&(c.worldToLocal(this._tempVec1),c.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(an&&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),an){this._followObject.add(new Pi(2)),this._manipulatorObject.add(new Pi(5));const h=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;G.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),G.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
|
|
948
|
+
`)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Ns(iO),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Ns(sO),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){var n,e,t,s,o,r,l,c;Wr._instances.get(this.context)===this&&Wr._instances.delete(this.context),(n=this.renderTarget)==null||n.dispose(),(e=this.renderTargetBlur)==null||e.dispose(),(t=this.depthMaterial)==null||t.dispose(),(s=this.horizontalBlurMaterial)==null||s.dispose(),(o=this.verticalBlurMaterial)==null||o.dispose(),(r=this.blurPlane)==null||r.geometry.dispose(),(l=this.plane)==null||l.geometry.dispose(),(c=this.occluderMesh)==null||c.geometry.dispose()}onBeforeRender(n){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){Vc&&console.error("ContactShadows: not initialized yet");return}const e=this.context.scene,t=this.context.renderer,s=t.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof q&&Fn(this.gameObject,!1);const r=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Oi:this.depthMaterial.side=yo;const l=t.getClearAlpha();t.setClearAlpha(0);const c=t.xr.enabled;t.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=t.renderLists.get(e,0),u=d.transparent;Wx.length=0,d.transparent=Wx,s0.length=0;for(const g of d.opaque){if(!g.object.visible)continue;const f=g.material;let y=g.material.colorWrite==!1||f.wireframe===!0||Nb(g.object)===!1;!y&&g.material.isLineMaterial&&(y=!0),!y&&g.material.isPointsMaterial&&(y=!0),y&&(s0.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}t.setRenderTarget(this.renderTarget),t.clear(),t.render(e,this.shadowCamera),d.transparent=u;for(const g of s0)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);e.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=o,t.setRenderTarget(s),t.setClearAlpha(l),e.background=r,t.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(n){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const e=this.shadowsRoot.worldScale,t=(e.x+e.z)/2,s=e.z/t,o=e.x/t;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=n*1/this.textureSize*s;const r=this.context.renderer,l=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=n*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(l)}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))}},a(Wr,"_instances",new Map),Wr);il([m()],Vr.prototype,"autoFit"),il([m()],Vr.prototype,"darkness"),il([m()],Vr.prototype,"opacity"),il([m()],Vr.prototype,"blur"),il([m()],Vr.prototype,"occludeBelowGround"),il([m()],Vr.prototype,"backfaceShadows");let $c=Vr;const Wx=[],s0=new Array,nE=C("logstats");class n0 extends j{onEnable(){console.log(this),nE&&this.startCoroutine(this.run(),Oe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Hc extends j{constructor(){super(...arguments),a(this,"isUsed",!0),a(this,"usedBy",null)}}class o0 extends j{}const Vx=C("debugdeletable"),$x=class wm extends Do{onEnable(){wm._instances.push(this)}onDisable(){const e=wm._instances.indexOf(this);e>=0&&wm._instances.splice(e,1)}};a($x,"_instances",[]);let Vu=$x;class r0 extends j{update(){for(const e of Vu._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const s=P.getComponentInParent(this.gameObject,Hc);if(s)Vx&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,s);else{if(Vx)try{if(e.box){const o=e.box,r=Do.testBox;G.DrawWireBox3(o,16711680,5),G.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}yc(this.gameObject,this.context.connection)}}}}}var oE=Object.defineProperty,rE=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&oE(e,t,o),o};class $u extends j{constructor(){super(...arguments),a(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||P.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Q.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}rE([m()],$u.prototype,"visibleOn");var aE=Object.defineProperty,$r=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&aE(e,t,o),o};const an=C("debugdrag"),a0=[];var l0=(n=>(n[n.XZPlane=0]="XZPlane",n[n.Attached=1]="Attached",n[n.HitNormal=2]="HitNormal",n[n.DynamicViewAngle=3]="DynamicViewAngle",n[n.SnapToSurfaces=4]="SnapToSurfaces",n[n.None=5]="None",n))(l0||{}),zt;const Fo=(zt=class extends j{constructor(){super(...arguments),a(this,"dragMode",3),a(this,"snapGridResolution",0),a(this,"keepRotation",!0),a(this,"xrDragMode",1),a(this,"xrKeepRotation",!1),a(this,"xrDistanceDragFactor",1),a(this,"showGizmo",!1),a(this,"_rigidbody",null),a(this,"_targetObject",null),a(this,"_dragHelper",null),a(this,"_draggingRigidbodies",[]),a(this,"_potentialDragStartEvt",null),a(this,"_dragHandlers",new Map),a(this,"_totalMovement",new S),a(this,"_marker",null),a(this,"_isDragging",!1),a(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){a0.length=0;for(const n of this._instances)n._isDragging&&a0.push(n);return a0}get draggedObject(){return this._targetObject}setTargetObject(n){var e,t;this._targetObject=n;for(const o of this._dragHandlers.values())o.setTargetObject(n);const s="_rigidbody-was-kinematic";((e=this._rigidbody)==null?void 0:e[s])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[s]=void 0),this._rigidbody=null,n&&(this._rigidbody=P.getComponentInChildren(n,dt),((t=this._rigidbody)==null?void 0:t.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[s]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new S,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(ji)||this.gameObject.addComponent(ji)}onEnable(){zt._instances.push(this)}onDisable(){zt._instances=zt._instances.filter(n=>n!==this)}allowEdit(n=null){return this.context.connection.allowEditing}onPointerEnter(n){if(!this.allowEdit(this.gameObject)||n.mode!=="screen"||(n.event.mode==="tracked-pointer"||n.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=P.getComponentInParent(n.object,zt);!e||e!==this||(zt.lastHovered=n.object,this.context.domElement.style.cursor="pointer")}onPointerMove(n){(this._isDragging||this._potentialDragStartEvt!==null)&&n.use()}onPointerExit(n){this.allowEdit(this.gameObject)&&n.mode==="screen"&&zt.lastHovered===n.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(n){if(!(!this.allowEdit(this.gameObject)||n.used||(n.mode==="tracked-pointer"||n.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(zt.lastHovered=n.object,n.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=n),this._targetObject||this.setTargetObject(this.gameObject),zt._active+=1;const e=new c0(this,this._targetObject);if(this._dragHandlers.set(n.event.space,e),e.onDragStart(n),this._dragHandlers.size===2){const t=this._dragHandlers.values(),s=t.next().value,o=t.next().value;if(s instanceof c0&&o instanceof c0){const r=new lE(this,this._targetObject,s,o);this._dragHandlers.set(this.gameObject,r),r.onDragStart(n)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:s,b:o})}n.use()}}onPointerUp(n){if(an&&G.DrawLabel(n.point??this.gameObject.worldPosition,"POINTERUP:"+n.pointerId+", "+n.button,.03,3),!this.allowEdit(this.gameObject)||n.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(n.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(n)),e&&(zt._active>0&&(zt._active-=1),this.setTargetObject(null),e.onDragEnd&&e.onDragEnd(n),this._dragHandlers.delete(n.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(n),n.use())}update(){for(const n of this._dragHandlers.values())n.collectMovementInfo&&n.collectMovementInfo(),n.getTotalMovement&&this._totalMovement.add(n.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const n=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(n)}for(const n of this._dragHandlers.values())n.onDragUpdate&&n.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(n){if(!n||!n.object)return;const e=P.getComponentInParent(n.object,zt);if(!e||e!==this&&e._isDragging)return;const t=this._targetObject||this.gameObject;if(!t)return;this._isDragging=!0;const s=P.getComponentInChildren(t,sn);an&&console.log("DRAG START",s,t),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=P.addComponent(t,Hc),this._draggingRigidbodies.length=0;const o=P.getComponentsInChildren(t,dt);o&&this._draggingRigidbodies.push(...o)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const n=this._targetObject||this.gameObject;ms.markDirty(n)}onLastDragEnd(n){if(!this||!this._isDragging)return;this._isDragging=!1;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,n!=null&&n.object){const t=P.getComponentInChildren(n.object,sn);t&&(t.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const e=this._dragHelper.selected;an&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context)}},a(zt,"_active",0),a(zt,"_instances",[]),a(zt,"lastHovered"),zt);$r([m()],Fo.prototype,"dragMode"),$r([m()],Fo.prototype,"snapGridResolution"),$r([m()],Fo.prototype,"keepRotation"),$r([m()],Fo.prototype,"xrDragMode"),$r([m()],Fo.prototype,"xrKeepRotation"),$r([m()],Fo.prototype,"xrDistanceDragFactor"),$r([m()],Fo.prototype,"showGizmo");let Hr=Fo;class lE{constructor(e,t,s,o){a(this,"handlerA"),a(this,"handlerB"),a(this,"context"),a(this,"settings"),a(this,"gameObject"),a(this,"_handlerAAttachmentPoint",new S),a(this,"_handlerBAttachmentPoint",new S),a(this,"_followObject"),a(this,"_manipulatorObject"),a(this,"_deviceMode"),a(this,"_followObjectStartWorldQuaternion",new V),a(this,"_manipulatorPosOffset",new S),a(this,"_manipulatorRotOffset",new V),a(this,"_manipulatorScaleOffset",new S),a(this,"_tempVec1",new S),a(this,"_tempVec2",new S),a(this,"_tempVec3",new S),a(this,"tempLookMatrix",new ne),a(this,"_initialScale",new S),a(this,"_initialDistance",0);var r,l;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=s,this.handlerB=o,this._followObject=new A,this._manipulatorObject=new A,this.context.scene.add(this._manipulatorObject);const c=(l=(r=oe.active)==null?void 0:r.rig)==null?void 0:l.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),c&&(c.worldToLocal(this._tempVec1),c.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(an&&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),an){this._followObject.add(new Pi(2)),this._manipulatorObject.add(new Pi(5));const h=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;G.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),G.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
|
|
949
949
|
`+h(this._tempVec1)+`
|
|
950
950
|
`+h(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()}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),an&&(G.DrawLabel(this._tempVec3.clone().add(new S(0,.2,0)),"A:B "+t.toFixed(2),.03),G.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 s=this.gameObject,o=this._followObject;if(!s){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}o.updateMatrix(),o.updateMatrixWorld(!0);const r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,this._followObject.worldPosition=u,this._followObject.updateMatrix()}r&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const l=W.clamp01(this.context.time.deltaTime*e*t),c=s.worldPosition;c.lerp(o.worldPosition,l),s.worldPosition=c;const h=s.worldQuaternion;h.slerp(o.worldQuaternion,l),s.worldQuaternion=h;const d=s.worldScale;d.lerp(o.worldScale,l),s.worldScale=d}setTargetObject(e){this.gameObject=e}}class c0{constructor(e,t){a(this,"context"),a(this,"gameObject"),a(this,"settings"),a(this,"_lastRig"),a(this,"_followObject"),a(this,"_totalMovement",new S),a(this,"_totalMovementAlongRayDirection",0),a(this,"_grabStartDistance",0),a(this,"_deviceMode"),a(this,"_followObjectStartPosition",new S),a(this,"_followObjectStartQuaternion",new V),a(this,"_followObjectStartWorldQuaternion",new V),a(this,"_lastDragPosRigSpace"),a(this,"_tempVec",new S),a(this,"_tempMat",new ne),a(this,"_hitPointInLocalSpace",new S),a(this,"_hitNormalInLocalSpace",new S),a(this,"_bottomCenter",new S),a(this,"_backCenter",new S),a(this,"_backBottomCenter",new S),a(this,"_bounds",new Ci),a(this,"_dragPlane",new fr(new S(0,1,0))),a(this,"_draggedOverObject",null),a(this,"_draggedOverObjectLastSetUp",null),a(this,"_draggedOverObjectLastNormal",new S),a(this,"_draggedOverObjectDuration",0),a(this,"_hasLastSurfaceHitPoint",!1),a(this,"_lastSurfaceHitPoint",new S),this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new A}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var e,t;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 s=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),s.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 o=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(o),this._grabStartDistance=o.distanceTo(s.worldPosition);const r=(t=(e=oe.active)==null?void 0:e.rig)==null?void 0:t.gameObject,l=r?.worldScale.x||1;this._grabStartDistance/=l,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,an&&(G.DrawLine(o,s.worldPosition,65280,.5,!1),G.DrawLabel(s.worldPosition.add(new S(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 f=e.event.space,y=f.worldPosition;this.gameObject.worldToLocal(y),this._hitPointInLocalSpace.copy(y);const v=f.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),s){case 0:const f=new S(0,1,0);this.gameObject.parent&&f.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(f,o);break;case 2:const y=this._hitNormalInLocalSpace.clone();y.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(y,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,o);break;case 3:this.setPlaneViewAligned(o,!0);break;case 4:this.setPlaneViewAligned(o,!1);break}const r=this.gameObject.parent,l=this.gameObject.position.clone(),c=this.gameObject.quaternion.clone(),h=this.gameObject.scale.clone(),d=this.gameObject.matrixWorld.clone();r&&r.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 u=ni([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new S;u.getCenter(p);const g=new S;u.getSize(g),this._bottomCenter.copy(p.clone().add(new S(0,-g.y/2,0))),this._backCenter.copy(p.clone().add(new S(0,0,g.z/2))),this._backBottomCenter.copy(p.clone().add(new S(0,-g.y/2,g.z/2))),this._bounds.copy(u),r&&r.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(c),this.gameObject.scale.copy(h),this.gameObject.matrixWorld.copy(d),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var e,t;if(!this._followObject.parent)return;const s=this._followObject.parent;this._followObject.updateMatrix();const o=s.worldPosition,r=(t=(e=oe.active)==null?void 0:e.rig)==null?void 0:t.gameObject;r&&r.worldToLocal(o),(this._lastDragPosRigSpace===void 0||r!=this._lastRig)&&(this._lastDragPosRigSpace=o.clone(),this._lastRig=r),this._tempVec.copy(o).sub(this._lastDragPosRigSpace);const l=s.worldForward;if(r&&(this._tempMat.copy(r.matrixWorld).invert(),l.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=l.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(o),an){let c=o;r&&(c=c.clone(),c.transformDirection(r.matrixWorld)),G.DrawRay(c,l,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 s=this._followObject.parent;if(!s){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const o=s.worldPosition,r=s.worldForward,l=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",c=l?this.settings.xrKeepRotation:this.settings.keepRotation,h=l?this.settings.xrDragMode:this.settings.dragMode;if(h===5)return;const d=10;c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(l&&this._grabStartDistance>.5){const w=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,w),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),c||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const g=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const f=new mo(o,r);if(h==4){const w=this.context.physics.raycastFromRay(f,{testObject:x=>x!==this.followObject&&x!==s&&x!==t});if(w.length>0){const x=w[0];if(this._draggedOverObject===x.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=x.object,this._draggedOverObjectDuration=0),x.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(x.point);const k=this._draggedOverObjectDuration>=.15,M=this._totalMovement.length()>=.001,T=X(x.normal||x.face.normal).applyQuaternion(x.object.worldQuaternion);if((k||M)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(T)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(x.face.normal);const D=X(),z=X();this._bounds.getCenter(D),this._bounds.getSize(z),D.sub(z.multiplyScalar(.5).multiply(T)),this._hitPointInLocalSpace.copy(D),this._hitNormalInLocalSpace.copy(x.face.normal),this._bounds.getCenter(D),this._bounds.getSize(z),D.add(z.multiplyScalar(.5).multiply(x.face.normal));const U=X(this._hitPointInLocalSpace).add(D);this._followObject.localToWorld(U);const E=x.point;this._dragPlane.setFromNormalAndCoplanarPoint(T,E)}else if(!(k||M))return}}else g&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(h!==1&&f.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const w=X(this._hitPointInLocalSpace);this._followObject.localToWorld(w),an&&G.DrawLine(w,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(w),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const w=this._followObject.worldPosition,x=this.settings.snapGridResolution;w.x=Math.round(w.x/x)*x,w.y=Math.round(w.y/x)*x,w.z=Math.round(w.z/x)*x,this._followObject.worldPosition=w,this._followObject.updateMatrix()}c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const y=W.clamp01(this.context.time.deltaTime*d*p),v=W.clamp01(this.context.time.deltaTime*d*.5*p),b=t.worldPosition;b.lerp(this._followObject.worldPosition,y),t.worldPosition=b;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,v),t.worldQuaternion=_,an){const w=this._hitPointInLocalSpace.clone();t.localToWorld(w),G.DrawSphere(w,.02,16711680);const x=this._hitNormalInLocalSpace.clone();x.applyQuaternion(_),G.DrawRay(w,x,16711680),G.DrawLabel(b.add(new S(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
951
951
|
|
|
@@ -963,7 +963,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
963
963
|
|
|
964
964
|
Content-Type: "${t.headers.get("content-type")}
|
|
965
965
|
"Text: "${o}"
|
|
966
|
-
Binary:`,s)}else console.debug("Could not determine file type from binary data");return"unknown"}var hE=Object.defineProperty,nl=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&hE(e,t,o),o};const Fi=C("debugdroplistener");class dE extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const uE="blob";class Gn extends j{constructor(){super(...arguments),a(this,"useNetworking",!0),a(this,"dropArea"),a(this,"fitIntoVolume",!1),a(this,"fitVolumeSize",new S(1,1,1)),a(this,"placeAtHitPosition",!0),a(this,"onDropped",new xe),a(this,"onNetworkEvent",e=>{var t;if(!this.useNetworking){Fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if((t=e.guid)!=null&&t.startsWith(this.guid)){const s=e.url;if(console.debug("[DropListener] Received networked event",e),s)if(Array.isArray(s))for(const o of s)this.addFromUrl(o,{screenposition:new ie,point:e.point,size:e.size},!0);else this.addFromUrl(s,{screenposition:new ie,point:e.point,size:e.size},!0)}}),a(this,"handlePaste",e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const s={screenposition:new ie(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(s)&&this.addFromUrl(t,s,!1)}}).catch(console.warn)}),a(this,"onDrag",e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()}),a(this,"onDrop",async e=>{if(this.context.connection.allowEditing===!1||(Fi&&console.log(e),!(e!=null&&e.dataTransfer))||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new ie(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const s=e.dataTransfer.items;if(!s)return;const o=[];for(const r in s){const l=s[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,t,!1)})}o.length>0&&await this.addDroppedFiles(o,t)}),a(this,"_abort",null),a(this,"_addedObjects",new Array),a(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(e,t){this.addFromUrl(e,{screenposition:new ie,point:t?.point,size:t?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(e,t,s){Fi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const l=e.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");e=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else e.startsWith("https://polyhaven.com/a")&&(e=pE(e));if(!e)return null;const o=e.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await Gu.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(r&&this._addedObjects.length<=0)return t.url=e,this.addObject(r,t,s)}catch{console.warn("String is not a valid URL",e)}return null}async addDroppedFiles(e,t){var s,o;if(Fi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),ql(uE,null),(s=this._abort)==null||s.abort("New files dropped"),this._abort=new AbortController;for(const r of e){if(!r)continue;if(r.type.startsWith("image/")){Fi&&console.warn("Ignoring dropped image file",r.name,r.type);continue}else if(r.name.endsWith(".bin")){Fi&&console.warn("Ignoring dropped binary file",r.name,r.type);continue}console.debug("Load file "+r.name+" + "+r.type);const l=await Gu.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),t.file=r;const c=this.addObject(l,t,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Ar.upload(r,{abort:(o=this._abort)==null?void 0:o.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&Ai(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(e,t,s){var o,r;const{model:l,contentMD5:c}=e;if(Fi&&console.log(`Dropped ${this.gameObject.name}`,l),!(l!=null&&l.scene))return console.warn("No object specified to add to scene",l),null;this.removePreviouslyAddedObjects();const h=l.scene;this.gameObject.attach(h),h.position.set(0,0,0),h.quaternion.identity(),this._addedObjects.push(h),this._addedModels.push(l);const d=new Ci().setFromCenterAndSize(new S(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Fi&&G.DrawWireBox3(d,255,5),this.fitIntoVolume&&Wb(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const f=g.point.clone();Fi&&console.log("Place object at hit",g),Vb(h,f);break}}Ga.assignAnimationsFromFile(l,{createAnimationComponent:p=>Ei(p,Ut)});const u=new dE({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!s&&(r=t.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(t.url,h,c),h}async sendDropEvent(e,t,s){if(!this.useNetworking){Fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const o=ni([t]),r={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:o.getSize(new S),contentMD5:s};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:t,recursive:!0,testObject:s=>!this._addedObjects.includes(s)}).length)return B()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}nl([m()],Gn.prototype,"useNetworking"),nl([m(A)],Gn.prototype,"dropArea"),nl([m()],Gn.prototype,"fitIntoVolume"),nl([m(S)],Gn.prototype,"fitVolumeSize"),nl([m()],Gn.prototype,"placeAtHitPosition"),nl([m(xe)],Gn.prototype,"onDropped");function pE(n){if(!n.startsWith("https://polyhaven.com/"))return n;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(n).pathname.split("/").pop(),s=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",n,"\u2192",s),s}var Gu;(n=>{async function e(s,o,r){const l=r.guid,c=new Dt(l),h=new Blob([s],{type:s.type||qx(s.name)||void 0}),d=URL.createObjectURL(h),u=await ws().loadSync(o,d,s.name,c).catch(p=>(console.error(`Failed to load file "${s.name}" (${s.type}):`,p),null));return URL.revokeObjectURL(d),u?new Promise((p,g)=>{const f=new FileReader;f.readAsArrayBuffer(s),f.onloadend=async y=>{const v=f.result,b=Ar.hashMD5(v);return p({model:u,contentMD5:b})}}):(console.warn(`Failed to load "${s.name}" (${s.type})`),null)}n.loadFile=e;async function t(s,o){return new Promise(async(r,l)=>{const c=new Dt(o.guid),h=s.toString();Fi&&G.DrawWireSphere(o.point,.1,16711680,3);const d=Uo.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await ws().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(f=>f.arrayBuffer()),g=Ar.hashMD5(p);Fi?setTimeout(()=>Uo.removePreview(o.guid),3e3):Uo.removePreview(o.guid),r({model:u,contentMD5:g})}else Fi?setTimeout(()=>Uo.removePreview(o.guid),3e3):Uo.removePreview(o.guid),console.warn("Unsupported file type: "+s.toString())})}n.loadFileFromURL=t})(Gu||(Gu={}));var mE=Object.defineProperty,d0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&mE(e,t,o),o};const qu=class _C extends j{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var e,t;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const o=new Dt(this.guid);this.object=P.instantiate(this.object,{idProvider:o,keepWorldPosition:!1});const r=P.getComponent(this.object,_C);r?.destroy();let l=this.object.getComponentInChildren(Hr);l||(l=this.object.addComponent(Hr,{dragMode:l0.SnapToSurfaces}),l.guid=o.generateUUID());let c=P.getComponent(l.gameObject,sn);c||(c=l.gameObject.addComponent(sn),c.guid=o.generateUUID())}this.object.visible=!1;const s=this.gameObject.getComponent(Hr);s&&(s.enabled=!1),this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new S(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(ji)||this.gameObject.addComponent(ji)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const s=P.getComponent(t,Hr);s?(s.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,s)):console.warn("Duplicated object does not have DragControls",t)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield xf(1)}handleDuplication(){var e;if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const t=new Bs;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((e=this.parent.userData)==null?void 0:e.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const s=P.instantiateSynced(this.object,t);return console.assert(s!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),s}};d0([m(A)],qu.prototype,"parent"),d0([m(A)],qu.prototype,"object"),d0([m()],qu.prototype,"limitCount");let u0=qu;var qn=(n=>(n[n.PointerEnter=0]="PointerEnter",n[n.PointerExit=1]="PointerExit",n[n.PointerDown=2]="PointerDown",n[n.PointerUp=3]="PointerUp",n[n.PointerClick=4]="PointerClick",n[n.Drag=5]="Drag",n[n.Drop=6]="Drop",n[n.Scroll=7]="Scroll",n[n.UpdateSelected=8]="UpdateSelected",n[n.Select=9]="Select",n[n.Deselect=10]="Deselect",n[n.Move=11]="Move",n[n.InitializePotentialDrag=12]="InitializePotentialDrag",n[n.BeginDrag=13]="BeginDrag",n[n.EndDrag=14]="EndDrag",n[n.Submit=15]="Submit",n[n.Cancel=16]="Cancel",n))(qn||{}),gE=Object.defineProperty,p0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&gE(e,t,o),o};class m0{constructor(){a(this,"eventID"),a(this,"callback",new xe)}}p0([m()],m0.prototype,"eventID"),p0([m(xe)],m0.prototype,"callback");class Xu extends j{constructor(){super(...arguments),a(this,"triggers",[])}invoke(e){var t;if(this.triggers)for(const s of this.triggers)s.eventID===e&&((t=s.callback)==null||t.invoke())}hasTrigger(e){var t;return((t=this.triggers)==null?void 0:t.some(s=>s.eventID===e))??!1}shouldChangeCursor(){return this.hasTrigger(qn.PointerClick)||this.hasTrigger(qn.PointerDown)||this.hasTrigger(qn.PointerUp)}onPointerClick(e){this.invoke(qn.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(qn.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(qn.PointerExit)}onPointerDown(e){this.invoke(qn.PointerDown)}onPointerUp(e){this.invoke(qn.PointerUp)}}p0([m(m0)],Xu.prototype,"triggers");class Yx{constructor(e){a(this,"writer"),this.writer=e}writeNode(e){}}class fE extends Yx{beforeWriteNode(e,t){G.isGizmo(e)&&(t.keep=!1)}}class Kx extends Yx{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Cf(new he(1,1,1,0)))}}function g0(n){const e=Bu.DontExport;return!(n.hideFlags&e)}const f0=C("debugexr");class yE{constructor(e){a(this,"parser"),this.parser=e,f0&&console.log(e)}get name(){return"EXT_texture_exr"}loadTexture(e){const t=this.name,s=this.parser,o=s.json.textures[e];if(f0&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],l=new Pd(s.options.manager);return f0&&console.log("EXT_texture_exr.loadTexture",r),s.loadTextureImage(e,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",n=>{});const Xn=wt,Qu="$___Export_Components",vE="NEEDLE_components";var Zx;Zx=wr;class bE{constructor(){a(this,Zx)}}class _E{constructor(e,t,s){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=e,this.nodeIndex=t,this.nodeDef=s}}class Jx{constructor(){a(this,"parser"),a(this,"nodeToObjectMap",{}),a(this,"gltf",null),a(this,"exportContext"),a(this,"objectToNodeMap",{}),a(this,"context"),a(this,"writer")}get name(){return vE}registerExport(e){e.register(t=>{if("serializeUserData"in t){const s=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(t.extensionsUsed[this.name]=!0),s(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){var s;const o=(s=e.userData)==null?void 0:s.components;return!o||o.length<=0?!1:(delete e.userData.components,e[Qu]=o,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Xn&&console.log("DONE",JSON.stringify(t)),e[Qu]===void 0)return;const s=e[Qu];delete e[Qu],s!==null&&(e.userData.components=s)}writeNode(e,t){const s=this.writer.json.nodes.length;Xn&&console.log(e.name,s,e.uuid);const o=new _E(e,s,t);this.exportContext[s]=o,this.objectToNodeMap[e.uuid]=s}afterParse(e){var t;Xn&&console.log("AFTER",e);for(const s in this.exportContext){const o=this.exportContext[s],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(t=r.userData)==null?void 0:t.components;if(!h||h.length<=0)continue;const d=new bE;l.extensions=l.extensions||{},l.extensions[this.name]=d,this.context.object=r,this.context.nodeId=c,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of h){this.context.target=p;const g=ws().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[wr]=u,Xn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Xn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,s=t?.extensions;if(!s)return;const o=s[this.name];Xn&&console.log("After root",e,this.parser,s);const r=[];if(o===!0){const l=t.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await t.getDependency("node",c);this.nodeToObjectMap[c]=h}for(let c=0;c<l.length;c++){const h=l[c],d=c,u=h.extensions;if(!u)continue;const p=u[this.name];if(!p)continue;Xn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,t);continue}ru(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of t.associations.keys()){const c=t.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;$M(l,h)}}}async createComponents(e,t){if(!t)return;const s=t[wr];if(s){const o=new Array;Xn&&console.log(e.name,s);for(const r in s){const l=s[r];Xn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(cf(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
|
|
966
|
+
Binary:`,s)}else console.debug("Could not determine file type from binary data");return"unknown"}var hE=Object.defineProperty,nl=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&hE(e,t,o),o};const Fi=C("debugdroplistener");class dE extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const uE="blob";class Gn extends j{constructor(){super(...arguments),a(this,"useNetworking",!0),a(this,"dropArea"),a(this,"fitIntoVolume",!1),a(this,"fitVolumeSize",new S(1,1,1)),a(this,"placeAtHitPosition",!0),a(this,"onDropped",new xe),a(this,"onNetworkEvent",e=>{var t;if(!this.useNetworking){Fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if((t=e.guid)!=null&&t.startsWith(this.guid)){const s=e.url;if(console.debug("[DropListener] Received networked event",e),s)if(Array.isArray(s))for(const o of s)this.addFromUrl(o,{screenposition:new ie,point:e.point,size:e.size},!0);else this.addFromUrl(s,{screenposition:new ie,point:e.point,size:e.size},!0)}}),a(this,"handlePaste",e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const s={screenposition:new ie(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(s)&&this.addFromUrl(t,s,!1)}}).catch(console.warn)}),a(this,"onDrag",e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()}),a(this,"onDrop",async e=>{if(this.context.connection.allowEditing===!1||(Fi&&console.log(e),!(e!=null&&e.dataTransfer))||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new ie(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const s=e.dataTransfer.items;if(!s)return;const o=[];for(const r in s){const l=s[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,t,!1)})}o.length>0&&await this.addDroppedFiles(o,t)}),a(this,"_abort",null),a(this,"_addedObjects",new Array),a(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(e,t){this.addFromUrl(e,{screenposition:new ie,point:t?.point,size:t?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(e,t,s){Fi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const l=e.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");e=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else e.startsWith("https://polyhaven.com/a")&&(e=pE(e));if(!e)return null;const o=e.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await Gu.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(r&&this._addedObjects.length<=0)return t.url=e,this.addObject(r,t,s)}catch{console.warn("String is not a valid URL",e)}return null}async addDroppedFiles(e,t){var s,o;if(Fi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),ql(uE,null),(s=this._abort)==null||s.abort("New files dropped"),this._abort=new AbortController;for(const r of e){if(!r)continue;if(r.type.startsWith("image/")){Fi&&console.warn("Ignoring dropped image file",r.name,r.type);continue}else if(r.name.endsWith(".bin")){Fi&&console.warn("Ignoring dropped binary file",r.name,r.type);continue}console.debug("Load file "+r.name+" + "+r.type);const l=await Gu.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),t.file=r;const c=this.addObject(l,t,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Ar.upload(r,{abort:(o=this._abort)==null?void 0:o.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&Ai(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(e,t,s){var o,r;const{model:l,contentMD5:c}=e;if(Fi&&console.log(`Dropped ${this.gameObject.name}`,l),!(l!=null&&l.scene))return console.warn("No object specified to add to scene",l),null;this.removePreviouslyAddedObjects();const h=l.scene;this.gameObject.attach(h),h.position.set(0,0,0),h.quaternion.identity(),this._addedObjects.push(h),this._addedModels.push(l);const d=new Ci().setFromCenterAndSize(new S(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Fi&&G.DrawWireBox3(d,255,5),this.fitIntoVolume&&Wb(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const f=g.point.clone();Fi&&console.log("Place object at hit",g),Vb(h,f);break}}Ga.assignAnimationsFromFile(l,{createAnimationComponent:p=>Ei(p,Ft)});const u=new dE({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!s&&(r=t.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(t.url,h,c),h}async sendDropEvent(e,t,s){if(!this.useNetworking){Fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const o=ni([t]),r={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:o.getSize(new S),contentMD5:s};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:t,recursive:!0,testObject:s=>!this._addedObjects.includes(s)}).length)return B()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}nl([m()],Gn.prototype,"useNetworking"),nl([m(A)],Gn.prototype,"dropArea"),nl([m()],Gn.prototype,"fitIntoVolume"),nl([m(S)],Gn.prototype,"fitVolumeSize"),nl([m()],Gn.prototype,"placeAtHitPosition"),nl([m(xe)],Gn.prototype,"onDropped");function pE(n){if(!n.startsWith("https://polyhaven.com/"))return n;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(n).pathname.split("/").pop(),s=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",n,"\u2192",s),s}var Gu;(n=>{async function e(s,o,r){const l=r.guid,c=new jt(l),h=new Blob([s],{type:s.type||qx(s.name)||void 0}),d=URL.createObjectURL(h),u=await ws().loadSync(o,d,s.name,c).catch(p=>(console.error(`Failed to load file "${s.name}" (${s.type}):`,p),null));return URL.revokeObjectURL(d),u?new Promise((p,g)=>{const f=new FileReader;f.readAsArrayBuffer(s),f.onloadend=async y=>{const v=f.result,b=Ar.hashMD5(v);return p({model:u,contentMD5:b})}}):(console.warn(`Failed to load "${s.name}" (${s.type})`),null)}n.loadFile=e;async function t(s,o){return new Promise(async(r,l)=>{const c=new jt(o.guid),h=s.toString();Fi&&G.DrawWireSphere(o.point,.1,16711680,3);const d=Uo.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await ws().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(f=>f.arrayBuffer()),g=Ar.hashMD5(p);Fi?setTimeout(()=>Uo.removePreview(o.guid),3e3):Uo.removePreview(o.guid),r({model:u,contentMD5:g})}else Fi?setTimeout(()=>Uo.removePreview(o.guid),3e3):Uo.removePreview(o.guid),console.warn("Unsupported file type: "+s.toString())})}n.loadFileFromURL=t})(Gu||(Gu={}));var mE=Object.defineProperty,d0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&mE(e,t,o),o};const qu=class _C extends j{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var e,t;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const o=new jt(this.guid);this.object=P.instantiate(this.object,{idProvider:o,keepWorldPosition:!1});const r=P.getComponent(this.object,_C);r?.destroy();let l=this.object.getComponentInChildren(Hr);l||(l=this.object.addComponent(Hr,{dragMode:l0.SnapToSurfaces}),l.guid=o.generateUUID());let c=P.getComponent(l.gameObject,sn);c||(c=l.gameObject.addComponent(sn),c.guid=o.generateUUID())}this.object.visible=!1;const s=this.gameObject.getComponent(Hr);s&&(s.enabled=!1),this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new S(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(ji)||this.gameObject.addComponent(ji)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const s=P.getComponent(t,Hr);s?(s.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,s)):console.warn("Duplicated object does not have DragControls",t)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield xf(1)}handleDuplication(){var e;if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const t=new Bs;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((e=this.parent.userData)==null?void 0:e.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const s=P.instantiateSynced(this.object,t);return console.assert(s!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),s}};d0([m(A)],qu.prototype,"parent"),d0([m(A)],qu.prototype,"object"),d0([m()],qu.prototype,"limitCount");let u0=qu;var qn=(n=>(n[n.PointerEnter=0]="PointerEnter",n[n.PointerExit=1]="PointerExit",n[n.PointerDown=2]="PointerDown",n[n.PointerUp=3]="PointerUp",n[n.PointerClick=4]="PointerClick",n[n.Drag=5]="Drag",n[n.Drop=6]="Drop",n[n.Scroll=7]="Scroll",n[n.UpdateSelected=8]="UpdateSelected",n[n.Select=9]="Select",n[n.Deselect=10]="Deselect",n[n.Move=11]="Move",n[n.InitializePotentialDrag=12]="InitializePotentialDrag",n[n.BeginDrag=13]="BeginDrag",n[n.EndDrag=14]="EndDrag",n[n.Submit=15]="Submit",n[n.Cancel=16]="Cancel",n))(qn||{}),gE=Object.defineProperty,p0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&gE(e,t,o),o};class m0{constructor(){a(this,"eventID"),a(this,"callback",new xe)}}p0([m()],m0.prototype,"eventID"),p0([m(xe)],m0.prototype,"callback");class Xu extends j{constructor(){super(...arguments),a(this,"triggers",[])}invoke(e){var t;if(this.triggers)for(const s of this.triggers)s.eventID===e&&((t=s.callback)==null||t.invoke())}hasTrigger(e){var t;return((t=this.triggers)==null?void 0:t.some(s=>s.eventID===e))??!1}shouldChangeCursor(){return this.hasTrigger(qn.PointerClick)||this.hasTrigger(qn.PointerDown)||this.hasTrigger(qn.PointerUp)}onPointerClick(e){this.invoke(qn.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(qn.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(qn.PointerExit)}onPointerDown(e){this.invoke(qn.PointerDown)}onPointerUp(e){this.invoke(qn.PointerUp)}}p0([m(m0)],Xu.prototype,"triggers");class Yx{constructor(e){a(this,"writer"),this.writer=e}writeNode(e){}}class fE extends Yx{beforeWriteNode(e,t){G.isGizmo(e)&&(t.keep=!1)}}class Kx extends Yx{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Cf(new he(1,1,1,0)))}}function g0(n){const e=Bu.DontExport;return!(n.hideFlags&e)}const f0=C("debugexr");class yE{constructor(e){a(this,"parser"),this.parser=e,f0&&console.log(e)}get name(){return"EXT_texture_exr"}loadTexture(e){const t=this.name,s=this.parser,o=s.json.textures[e];if(f0&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],l=new Pd(s.options.manager);return f0&&console.log("EXT_texture_exr.loadTexture",r),s.loadTextureImage(e,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",n=>{});const Xn=wt,Qu="$___Export_Components",vE="NEEDLE_components";var Zx;Zx=wr;class bE{constructor(){a(this,Zx)}}class _E{constructor(e,t,s){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=e,this.nodeIndex=t,this.nodeDef=s}}class Jx{constructor(){a(this,"parser"),a(this,"nodeToObjectMap",{}),a(this,"gltf",null),a(this,"exportContext"),a(this,"objectToNodeMap",{}),a(this,"context"),a(this,"writer")}get name(){return vE}registerExport(e){e.register(t=>{if("serializeUserData"in t){const s=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(t.extensionsUsed[this.name]=!0),s(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){var s;const o=(s=e.userData)==null?void 0:s.components;return!o||o.length<=0?!1:(delete e.userData.components,e[Qu]=o,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Xn&&console.log("DONE",JSON.stringify(t)),e[Qu]===void 0)return;const s=e[Qu];delete e[Qu],s!==null&&(e.userData.components=s)}writeNode(e,t){const s=this.writer.json.nodes.length;Xn&&console.log(e.name,s,e.uuid);const o=new _E(e,s,t);this.exportContext[s]=o,this.objectToNodeMap[e.uuid]=s}afterParse(e){var t;Xn&&console.log("AFTER",e);for(const s in this.exportContext){const o=this.exportContext[s],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(t=r.userData)==null?void 0:t.components;if(!h||h.length<=0)continue;const d=new bE;l.extensions=l.extensions||{},l.extensions[this.name]=d,this.context.object=r,this.context.nodeId=c,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of h){this.context.target=p;const g=ws().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[wr]=u,Xn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Xn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,s=t?.extensions;if(!s)return;const o=s[this.name];Xn&&console.log("After root",e,this.parser,s);const r=[];if(o===!0){const l=t.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await t.getDependency("node",c);this.nodeToObjectMap[c]=h}for(let c=0;c<l.length;c++){const h=l[c],d=c,u=h.extensions;if(!u)continue;const p=u[this.name];if(!p)continue;Xn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,t);continue}ru(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of t.associations.keys()){const c=t.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;$M(l,h)}}}async createComponents(e,t){if(!t)return;const s=t[wr];if(s){const o=new Array;Xn&&console.log(e.name,s);for(const r in s){const l=s[r];Xn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(cf(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
|
|
967
967
|
`,c,e,l))),e.userData=e.userData||{},e.userData[wr]=e.userData[wr]||[],e.userData[wr].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const e1="NEEDLE_gameobject_data";class wE{constructor(e){a(this,"parser"),this.parser=e}get name(){return e1}afterRoot(e){var t;const s=[];for(let o=0;o<((t=this.parser.json.nodes)==null?void 0:t.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[e1];if(l){const c=this.findAndApplyExtensionData(o,l);s.push(c)}}}return Promise.all(s).then(()=>null)}async findAndApplyExtensionData(e,t){const s=await this.parser.getDependency("node",e);s&&this.applyExtensionData(s,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 t1="NEEDLE_lighting_settings",ol=C("debugenvlight");class xE{constructor(e,t,s){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=e,this.sourceId=t,this.context=s}get name(){return t1}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[t1];if(s){ol&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',s);let o;if(e.scene.children.length===1){const r=e.scene.children[0];o=P.addComponent(r,Yu,{},{callAwake:!1})}else{const r=new A;r.name="LightSettings "+this.sourceId,e.scene.add(r),o=P.addComponent(r,Yu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=s.ambientIntensity,o.ambientLight=new re().fromArray(s.ambientLight),Array.isArray(s.ambientTrilight)&&(o.ambientTrilight=s.ambientTrilight.map(r=>new re().fromArray(r))),o.ambientMode=s.ambientMode,o.environmentReflectionSource=s.environmentReflectionSource}}return null}}pe.registerCallback(me.ContextCreated,n=>{const e=n.context,t=P.findObjectOfType(Yu,e);t!=null&&t.sourceId&&(t.enabled=!0)});class Yu extends j{constructor(){super(...arguments),a(this,"ambientMode",Xa.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",gu.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var e;if(this.sourceId){const s=this.environmentReflectionSource===gu.Skybox?Ys.Skybox:Ys.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,s,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ol&&window.addEventListener("keydown",s=>{if(!this.destroyed)switch(s.key){case"l":this.enabled=!this.enabled;break}});const t=(e=this.gameObject.userData)==null?void 0:e.components;if(t){const s=t.indexOf(this);t.splice(s,1),t.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*W.lerp(0,1.33,t)}onEnable(){if(ol&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Xa.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new tP(this.ambientLight,this.ambientIntensity*e),ol&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Xa.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],s=this.calculateIntensityFactor(t);this._hemisphereLightObj=new iP(t,e,this.ambientIntensity*s),this.gameObject.add(this._hemisphereLightObj),ol&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,s)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){ol&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const y0=C("debugstencil");function SE(n,e){return(n&1<<e.layer)!=0}const CE=Symbol("stencils"),i1=class Ul{constructor(e,t){a(this,"parser"),a(this,"source"),this.parser=e,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(e){if(!e)return;const t=e.sourceId;if(y0&&console.log(t,Ul.stencils),!t)return;const s=Ul.stencils[t];if(s)for(let o=s.length-1;o>=0;o--){const r=s[o];if(SE(r.layer,e)){y0&&console.log(r),setTimeout(()=>{Xt()&&lu(e.gameObject)&&(be("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let l=0;l<e.sharedMaterials.length;l++){let c=e.sharedMaterials[l];c&&(c=c.clone(),c[CE]=!0,c.stencilWrite=!0,c.stencilWriteMask=255,c.stencilFuncMask=255,c.stencilRef=r.value,c.stencilFunc=r.compareFunc,c.stencilZPass=r.passOp,c.stencilFail=r.failOp,c.stencilZFail=r.zFailOp,e.sharedMaterials[l]=c)}e.gameObject.renderOrder=r.event*1e3+r.index*50;break}}}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[OE];if(s){y0&&console.log(s);const o=s.stencil;if(o&&Array.isArray(o))for(const r of o){const l={...r};l.compareFunc=PE(l.compareFunc),l.passOp=v0(l.passOp),l.failOp=v0(l.failOp),l.zFailOp=v0(l.zFailOp),Ul.stencils[this.source]||(Ul.stencils[this.source]=[]),Ul.stencils[this.source].push(l)}}}return null}};a(i1,"stencils",{});let s1=i1;function v0(n){switch(n){case 0:return yP;case 1:return fP;case 2:return gP;case 3:return mP;case 4:return pP;case 6:return uP;case 7:return dP;case 5:return hP}return 0}function PE(n){switch(n){case 1:return Fv;case 2:return cP;case 3:return lP;case 4:return aP;case 5:return rP;case 6:return oP;case 7:return nP;case 8:return sP}return Fv}const OE="NEEDLE_render_objects";var n1=(n=>(n[n.INT=5124]="INT",n[n.FLOAT=5126]="FLOAT",n[n.FLOAT_VEC2=35664]="FLOAT_VEC2",n[n.FLOAT_VEC3=35665]="FLOAT_VEC3",n[n.FLOAT_VEC4=35666]="FLOAT_VEC4",n[n.INT_VEC2=35667]="INT_VEC2",n[n.INT_VEC3=35668]="INT_VEC3",n[n.INT_VEC4=35669]="INT_VEC4",n[n.BOOL=35670]="BOOL",n[n.BOOL_VEC2=35671]="BOOL_VEC2",n[n.BOOL_VEC3=35672]="BOOL_VEC3",n[n.BOOL_VEC4=35673]="BOOL_VEC4",n[n.FLOAT_MAT2=35674]="FLOAT_MAT2",n[n.FLOAT_MAT3=35675]="FLOAT_MAT3",n[n.FLOAT_MAT4=35676]="FLOAT_MAT4",n[n.SAMPLER_2D=35678]="SAMPLER_2D",n[n.SAMPLER_3D=35680]="SAMPLER_3D",n[n.SAMPLER_CUBE=35681]="SAMPLER_CUBE",n[n.UNKNOWN=0]="UNKNOWN",n))(n1||{});const ln=C("debugcustomshader"),rl="NEEDLE_techniques_webgl";class kE{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),mu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),mu(this.worldToObjectMatrix,this.worldToObject)}}const cn=class $e extends Uv{constructor(e,...t){super(...t),a(this,"identifier"),a(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),a(this,"_sphericalHarmonicsName","unity_SpecCube0"),a(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),a(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),a(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),a(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),a(this,"_rendererData",new kE),this.identifier=e,ln&&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)&&J.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const e=super.clone();return r1(e),e}dispose(){super.dispose();const e=J.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&J.Current.pre_render_callbacks.splice(e,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&J.Current.setRequireColor(!0),this.depthTextureUniform&&J.Current.setRequireDepth(!0)}onBeforeRender(e,t,s,o,r,l){o.attributes.tangent||o.computeTangents(),this.onUpdateUniforms(s,r)}onUpdateUniforms(e,t){const s=J.Current;if(e&&($e.viewProjection&&this.uniforms[this._viewProjectionName]&&($e.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),mu($e.viewProjection,$e._viewProjectionValues)),$e.viewMatrix&&this.uniforms[this._viewMatrixName]&&($e.viewMatrix.copy(e.matrixWorldInverse),mu($e.viewMatrix,$e._viewMatrixValues)),this.uniforms[$e._worldSpaceCameraPosName]&&$e._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=s.sceneLighting.timeVec4),this.uniforms._Time){const c=this.uniforms._Time.value;c.x=s.sceneLighting.timeVec4.x/20,c.y=s.sceneLighting.timeVec4.x,c.z=s.sceneLighting.timeVec4.x*2,c.w=s.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const c=this.uniforms._SinTime.value;c.x=Math.sin(s.sceneLighting.timeVec4.x/8),c.y=Math.sin(s.sceneLighting.timeVec4.x/4),c.z=Math.sin(s.sceneLighting.timeVec4.x/2),c.w=Math.sin(s.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const c=this.uniforms._CosTime.value;c.x=Math.cos(s.sceneLighting.timeVec4.x/8),c.y=Math.cos(s.sceneLighting.timeVec4.x/4),c.z=Math.cos(s.sceneLighting.timeVec4.x/2),c.w=Math.cos(s.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const c=this.uniforms.unity_DeltaTime.value;c.x=s.time.deltaTime,c.y=1/s.time.deltaTime,c.z=s.time.smoothedDeltaTime,c.w=1/s.time.smoothedDeltaTime}const o=s.mainLight;if(o){const c=ee(o.gameObject,$e._mainLightPosition);this.uniforms._MainLightPosition={value:c.normalize()},$e._mainLightColor.set(o.color.r,o.color.g,o.color.b,0),this.uniforms._MainLightColor={value:$e._mainLightColor};const h=o.intensity;$e._lightData.z=h,this.uniforms.unity_LightData={value:$e._lightData}}if(e&&($e.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=$e._viewProjectionValues),$e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=$e._viewMatrixValues),this.uniforms[$e._worldSpaceCameraPosName]&&(this.uniforms[$e._worldSpaceCameraPosName]={value:$e._worldSpaceCameraPos}),s.mainCameraComponent)){if(this.uniforms._ProjectionParams){const c=this.uniforms._ProjectionParams.value;c.x=1,c.y=s.mainCameraComponent.nearClipPlane,c.z=s.mainCameraComponent.farClipPlane,c.w=1/c.z,this.uniforms._ProjectionParams.value=c}if(this.uniforms._ZBufferParams){const c=this.uniforms._ZBufferParams.value,h=s.mainCameraComponent;c.x=1-h.farClipPlane/h.nearClipPlane,c.y=h.farClipPlane/h.nearClipPlane,c.z=c.x/h.farClipPlane,c.w=c.y/h.farClipPlane,this.uniforms._ZBufferParams.value=c}if(this.uniforms._ScreenParams){const c=this.uniforms._ScreenParams.value;c.x=s.domWidth,c.y=s.domHeight,c.z=1+1/c.x,c.w=1+1/c.y,this.uniforms._ScreenParams.value=c}if(this.uniforms._ScaledScreenParams){const c=this.uniforms._ScaledScreenParams.value;c.x=s.domWidth,c.y=s.domHeight,c.z=1+1/c.x,c.w=1+1/c.y,this.uniforms._ScaledScreenParams.value=c}}const r=this.depthTextureUniform;r&&(r.value=s.depthTexture);const l=this.opaqueTextureUniform;if(l&&(l.value=s.opaqueColorTexture),t){const c=this._rendererData;c.updateFrom(t),this.uniforms[this._worldToObjectName].value=c.worldToObject,this.uniforms[this._objToWorldName].value=c.objectToWorld}this.uniformsNeedUpdate=!0}};a(cn,"viewProjection",new ne),a(cn,"_viewProjectionValues",[]),a(cn,"viewMatrix",new ne),a(cn,"_viewMatrixValues",[]),a(cn,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(cn,"_worldSpaceCameraPos",new S),a(cn,"_mainLightColor",new fe),a(cn,"_mainLightPosition",new S),a(cn,"_lightData",new fe);let o1=cn;class ME{constructor(e,t){a(this,"parser"),a(this,"identifier"),this.parser=e,this.identifier=t}get name(){return rl}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return ln&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[rl])return ln&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;ln&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const s=t.extensions[rl].technique;if(s<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const o=this.parser.json.extensions[rl];if(!o)return ln?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;ln&&console.log(o);const r=o.techniques[s];return r?new Promise(async(l,c)=>{var h,d,u;const p=await _R(o,r.program),g=p?.fragmentShader,f=p?.vertexShader;if(!g||!f)return c();ln&&console.log("loadMaterial",t,p);const y={},v=r.uniforms;(f.includes("_Time")||g.includes("_Time"))&&(y._Time={value:new fe(0,0,0,0)}),(f.includes("_SinTime")||g.includes("_SinTime"))&&(y._SinTime={value:new fe(0,0,0,0)}),(f.includes("_CosTime")||g.includes("_CosTime"))&&(y._CosTime={value:new fe(0,0,0,0)}),(f.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(y.unity_DeltaTime={value:new fe(0,0,0,0)});for(const w in v){const x=w;switch(x){case"_TimeParameters":const k=new fe;y[x]={value:k};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":y[x]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":y[x]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":y[x]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":y[x]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":y[x]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[rl]){const w=t.extensions[rl];if(w.technique===s){ln&&console.log(t.name,"Material Properties",w);for(const x in w.values){const k=w.values[x];if(typeof k=="string"){if(k.startsWith("/textures/")){const M=k.substring(10),T=Number.parseInt(M);if(T>=0){const D=await this.parser.getDependency("texture",T);D instanceof je&&(D.colorSpace=On,D.needsUpdate=!0),y[x]={value:D};continue}}switch(x){case"alphaMode":k==="BLEND"&&(b=!0);continue}}if(Array.isArray(k)&&k.length===4){y[x]={value:new fe(k[0],k[1],k[2],k[3])};continue}y[x]={value:k}}}}const _=new o1(this.identifier,{name:t.name??"",uniforms:y,vertexShader:f,fragmentShader:g,lights:!1});switch(_.glslVersion=vP,_.vertexShader=_.vertexShader.replace("#version 300 es",""),_.fragmentShader=_.fragmentShader.replace("#version 300 es",""),(h=y._Cull)==null?void 0:h.value){case 0:_.side=Oi;break;case 1:_.side=xd;break;case 2:_.side=yo;break;default:_.side=yo;break}switch((d=y._ZTest)==null?void 0:d.value){case 3:_.depthTest=!0,_.depthFunc=PP;break;case 6:_.depthTest=!0,_.depthFunc=CP;break;case 2:_.depthTest=!0,_.depthFunc=SP;break;case 4:_.depthTest=!0,_.depthFunc=xP;break;case 5:_.depthTest=!0,_.depthFunc=wP;break;case 7:_.depthTest=!0,_.depthFunc=_P;break;case 8:_.depthTest=!1,_.depthFunc=bP;break}_.transparent=b,b&&(_.depthWrite=!1),vR(y),_.onUpdateUniforms();for(const w in v){const x=w,k=v[w].type;if(((u=y[x])==null?void 0:u.value)===void 0)switch(k){case n1.SAMPLER_2D:y[x]={value:fR},console.warn("Missing/unassigned texture, fallback to white: "+x);break;default:x==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+x,v[w]);break}}ln&&console.log(_.uuid,y),r1(_),l(_)}):null}}function r1(n){if(n.uniforms){ln&&console.log("Uniforms:",n.uniforms);for(const t in n.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,s){Object.getOwnPropertyDescriptor(n,t)||Object.defineProperty(n,t,{get:()=>n.uniforms[s].value,set:o=>{n.uniforms[s].value=o,n.needsUpdate=!0}})}}const RE=C("debugextensions");let Ku;const TE=import("./three-examples-BMOhDaYR.min.js").then(n=>n.GLTFLoaderAnimationPointer).then(async n=>(Ku=n.GLTFAnimationPointerExtension,Ku)).catch(n=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",n)}),Gr=new Array;function EE(n){Gr.includes(n)||Gr.push(n)}function AE(n){const e=Gr.indexOf(n);e>=0&&Gr.splice(e,1)}function b0(n){if(n instanceof Rn){const e=new Jx;return n.register(t=>(e.parser=t,e)),e}return null}class IE{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 Zu(n,e,t){const s=t.indexOf("?");s>=0&&(t=t.substring(0,s)),n.register(o=>new wE(o)),n.register(o=>new GM(o)),n.register(o=>new uR(o,e.lightmaps,t)),n.register(o=>new xE(o,t,e)),n.register(o=>new ME(o,t)),n.register(o=>new s1(o,t)),n.register(o=>new Xe(o,t)),n.register(o=>new yE(o)),U_()&&n.register(o=>new D_(o)),await TE.catch(o=>{}),n.register(o=>{if(Ku){const r=new Ku(o);return r.setAnimationPointerResolver.bind(r)(new IE),r}else return(RE||B())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Gr)o.onImport&&o.onImport(n,t,e)}function _0(n,e){for(const t of Gr)t.onExport&&t.onExport(n,e)}function a1(n,e,t){for(const s of Gr)s.onLoaded&&s.onLoaded(n,e,t)}class l1{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const s=this.writer,o=s.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,l);let y=new S,v=new V,b=new S;l.decompose(y,v,b),c.push(y.x,y.y,y.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:s.processAccessor(new _t(u,3)),ROTATION:s.processAccessor(new _t(p,4)),SCALE:s.processAccessor(new _t(g,3))},o[this.name]=!0}}var LE=Object.defineProperty,c1=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&LE(e,t,o),o};const qc=C("debugreflectionprobe"),h1=C("noreflectionprobe"),w0=Symbol("reflectionProbeKey"),d1=Symbol("original material");var rs;const x0=(rs=class extends j{constructor(){var n;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),rs._probes.has(this.context)||rs._probes.set(this.context,[]),(n=rs._probes.get(this.context))==null||n.push(this)}static isUsingReflectionProbe(n){var e;return!!(n[w0]||(e=n[d1])!=null&&e[w0])}static get(n,e,t,s){if(!n||n.isObject3D!==!0||h1)return null;const o=rs._probes.get(e);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(s){if(r.gameObject===s)return r}else if(r.isInBox(n))return qc&&console.log("Found reflection probe",n.name,r.name),r}}return qc&&console.debug("Did not find reflection probe",n.name,t,n),null}set texture(n){if(n&&!(n instanceof je)){console.error("ReflectionProbe.texture must be a Texture",n);return}this._texture=n,n&&(n.mapping=kn,n.colorSpace=On,n.needsUpdate=!0)}get texture(){return this._texture}isInBox(n){var e;return(e=this._boxHelper)==null?void 0:e.isInBox(n)}awake(){this._boxHelper=this.gameObject.addComponent(Do),this._boxHelper.updateBox(!0),qc&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=kn,this._texture.colorSpace=On,this._texture.needsUpdate=!0)}start(){!this._texture&&B()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),be("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const n=rs._probes.get(this.context);if(n){const e=n.indexOf(this);e>=0&&n.splice(e,1)}}onSet(n){var e;if(h1||!this.enabled||((e=n.sharedMaterials)==null?void 0:e.length)<=0||!this.texture)return;let t=rs._rendererMaterialsCache.get(n);t||(t=[],rs._rendererMaterialsCache.set(n,t));for(let s=0;s<n.sharedMaterials.length;s++){const o=n.sharedMaterials[s];if(!o||o.envMap===void 0||o instanceof Me)continue;let r=t[s];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(qc){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
|
|
968
968
|
`,o.uuid,`
|
|
969
969
|
`,r?.copy.uuid,`
|
|
@@ -1249,7 +1249,7 @@ ${d.join(`
|
|
|
1249
1249
|
`)}`:""}
|
|
1250
1250
|
}`}function B1(n){return`(${n.r}, ${n.g}, ${n.b})`}function F1(n){return`(${n.x}, ${n.y})`}const j0=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];C("debugusdz");const U1=class xC{constructor(e,t,s){a(this,"id"),a(this,"trigger"),a(this,"action"),a(this,"exclusive",!1),this.id="Behavior_"+as(e)+"_"+xC.global_id++,this.trigger=t,this.action=s}makeExclusive(e){return this.exclusive=e,this}writeTo(e,t,s){if(!this.trigger||!this.action)return;s.beginBlock(`def Preliminary_Behavior "${this.id}"`);let o="";if(Array.isArray(this.trigger)){o="[";for(let r=0;r<this.trigger.length;r++){const l=this.trigger[r];o+="<"+l.id+">",r+1<this.trigger.length&&(o+=", ")}o+="]"}else o=`<${this.trigger.id}>`;if(s.appendLine(`rel triggers = ${o}`),s.appendLine(`rel actions = <${this.action.id}>`),s.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),s.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(t,s),s.appendLine();else this.trigger.writeTo(t,s);s.appendLine(),this.action.writeTo(t,s),s.closeBlock()}};a(U1,"global_id",0);let ei=U1;const dl=new Set;function D0(n,e){var t,s;let o="";if(Array.isArray(n)){dl.clear();let r="[ ";for(let l=0;l<n.length;l++){let c=n[l];if(!c){console.warn("Invalid target object in behavior",n+". Is the object exported?");continue}if(typeof c=="string"){if(dl.has(c))continue;r+=c,dl.add(c)}else if(typeof c=="object"){if(c.isObject3D&&(c=e.findById(c.uuid),!c)){console.warn("Invalid target object in behavior",n+". Is the object exported?");continue}const h=(t=c.getPath)==null?void 0:t.call(c);if(dl.has(h))continue;r+=h,dl.add(h)}l+1<n.length&&(r+=", ")}r+=" ]",o=r,dl.clear()}else if(typeof n=="object"){const r=n;if(r.isObject3D&&(n=e.findById(r.uuid)),!n)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",r),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${r.uuid}.`);o=(s=n.getPath)==null?void 0:s.call(n)}return o}const z1=class SC{constructor(e,t){a(this,"id"),a(this,"targetId"),a(this,"tokenId"),a(this,"type"),a(this,"distance"),e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+SC.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=D0(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()}};a(z1,"global_id",0);let ul=z1;function N1(n,e={direct:!0,indirect:!0}){const t=gi.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=s=>{s.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),s.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),s.appendLine('uniform token info:id = "RealityKit.InputTarget"')},n.add(t)}class At{static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new ul(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const s=new ul(e);if(Array.isArray(e)&&e.length>1)for(const o of e)o instanceof gi&&N1(o,t);else e instanceof gi&&N1(e,t);return s.tokenId="TapGesture",s}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const s=new ul(e);return s.tokenId="ProximityToCamera",s.distance=t,s}}a(At,"__sceneStartTrigger");class No{constructor(e,t){a(this,"id"),a(this,"actions"),a(this,"loops",0),a(this,"performCount",1),a(this,"type","serial"),a(this,"multiplePerformOperation"),this.id=e,this.actions=t}static getId(){return this.global_id++}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 s of this.actions){if(!s)continue;const o=s===this.actions[this.actions.length-1];t.appendLine("<"+s.id+">"+(o?"":", "))}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 s of this.actions)s&&(s.writeTo(e,t),t.appendLine());t.closeBlock()}}a(No,"global_id",0);const W1=class wv{constructor(e,t){a(this,"id"),a(this,"tokenId"),a(this,"affectedObjects"),a(this,"easeType"),a(this,"motionType"),a(this,"duration"),a(this,"moveDistance"),a(this,"style"),a(this,"type"),a(this,"front"),a(this,"up"),a(this,"start"),a(this,"animationSpeed"),a(this,"reversed"),a(this,"pingPong"),a(this,"xFormTarget"),a(this,"audio"),a(this,"gain"),a(this,"auralMode"),a(this,"multiplePerformOperation"),a(this,"velocity"),a(this,"comment"),a(this,"animationName"),e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+wv.global_id++}clone(){const e=new wv,t=e.id;return Object.assign(e,this),e.id=t,e}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=D0(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=D0(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()}};a(W1,"global_id",0);let Os=W1;class fs{constructor(e,t,s){a(this,"x",0),a(this,"y",0),a(this,"z",0),this.x=e,this.y=t,this.z=s}static get up(){return new fs(0,1,0)}static get right(){return new fs(1,0,0)}static get forward(){return new fs(0,0,1)}static get back(){return new fs(0,0,-1)}static get zero(){return new fs(0,0,0)}}class ve{static sequence(...e){return new No("Group_"+No.getId(),e).makeSequence()}static parallel(...e){return new No("Group_"+No.getId(),e).makeParallel()}static fadeAction(e,t,s){const o=new Os(e);return o.tokenId="Visibility",o.type=s?"show":"hide",o.duration=t,o.style="basic",o.motionType="none",o.moveDistance=0,o.easeType="none",o}static startAnimationAction(e,t,s=!1,o=!1){const r=new Os(e);r.tokenId="StartAnimation";const l=t.start,c=t.duration,h=t.speed,d=t.clipName;if(r.comment=`Animation: ${d}, start=${l*60}, length=${c*60}, end=${(l+c)*60}`,r.animationName=d,r.start=l,r.duration=c,r.animationSpeed=h,r.reversed=s,r.pingPong=o,r.multiplePerformOperation="allow",s&&(r.start-=c),o){r.pingPong=!1;const u=r.clone();return u.reversed=!s,u.start=r.start,u.reversed&&(u.start-=c),ve.sequence(r,u)}return r}static waitAction(e){const t=new Os;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,s,o){const r=new Os(e);return r.tokenId="LookAtCamera",r.duration=t===void 0?9999999999999:t,r.front=s??fs.forward,r.up=o??fs.up,r}static emphasize(e,t,s="bounce",o=1,r="basic"){const l=new Os(e);return l.tokenId="Emphasize",l.duration=t,l.style=r??"basic",l.motionType=s,l.moveDistance=o,l}static transformAction(e,t,s,o,r="inout"){const l=new Os(e);return l.tokenId="Transform",l.duration=s,l.duration=Math.max(1e-6,s),l.type=o,l.easeType=s>0?r:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),l.xFormTarget=t,l}static playAudioAction(e,t,s="play",o=1,r="spatial"){const l=new Os(e);return l.tokenId="Audio",l.type=s,l.audio=t,l.gain=o,l.auralMode=r,l.multiplePerformOperation="allow",l}static impulseAction(e,t){const s=new Os(e);return s.tokenId="Impulse",s.velocity=t,s}}class rA{constructor(e){a(this,"object"),a(this,"model"),this.object=e}get id(){return this.object.uuid}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 B0 extends rA{constructor(e,t,s,o){super(e),a(this,"matrix"),a(this,"material"),a(this,"geometry"),a(this,"_enableAction"),a(this,"_disableAction"),this.matrix=t,this.material=s,this.geometry=o}onApply(e){var t,s;const o=this.model;if(!o)return;(t=o.parent)!=null&&t.isDynamic||gi.createEmptyParent(o);const r=o.clone();this.matrix&&r.setMatrix(this.matrix),this.material&&(r.material=this.material),this.geometry&&(r.geometry=this.geometry),(s=o.parent)==null||s.add(r)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ve.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ve.fadeAction(this.object,0,!1),this._disableAction)}}class V1{constructor(e){a(this,"actions"),a(this,"sortedActions"),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 dn=C("debugusdzanimation"),F0=C("debugusdzanimationserialization");class pr{constructor(e,t,s){a(this,"_start"),a(this,"ext"),a(this,"root"),a(this,"_nearestAnimatedRoot"),a(this,"clip"),a(this,"speed"),this.ext=e,this.root=t,this.clip=s,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){var e;return((e=this.clip)==null?void 0:e.duration)??ut.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){var e;return((e=this.clip)==null?void 0:e.name)??"rest"}static isDescendantOf(e,t){let s=t;if(!s||!e)return!1;for(;s;){if(!s)return!1;if(s===e)return!0;s=s.parent}return!1}getNearestAnimatedRoot(){var e;let t;try{for(const s of((e=this.clip)==null?void 0:e.tracks)??[]){const o=Ca.parseTrackName(s.name);let r=Ca.findNode(this.root,o.nodeName);if(r)if(!t)t=r;else{if(r===t||pr.isDescendantOf(t,r))continue;if(!pr.isDescendantOf(r,t)){for(;!pr.isDescendantOf(r,t)&&r.parent;)r=r.parent;pr.isDescendantOf(r,t)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,t,r)}t=r}}}catch(s){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",s),t=void 0}return t}}const dp=class Cm{constructor(e,t,s){if(a(this,"clip"),a(this,"pos"),a(this,"rot"),a(this,"scale"),a(this,"root"),a(this,"target"),a(this,"duration",0),a(this,"useRootMotion",!1),this.root=e,this.target=t,this.clip=s,s?this.duration=s.duration:this.duration=Cm.restPoseClipDuration,s&&s.tracks){const r=Math.max(...s.tracks.map(l=>l.times[l.times.length-1]));r!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",s,r,this.duration),this.duration=r)}const o=P.getComponent(e,Rt);o&&(this.useRootMotion=o.applyRootMotion)}addTrack(e){var t,s;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 "+(((t=this.root)==null?void 0:t.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 "+(((s=this.root)==null?void 0:s.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),B()&&be("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var e,t,s,o,r,l;return this.clip?Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((o=(s=this.rot)==null?void 0:s.times)==null?void 0:o.length)??0,((l=(r=this.scale)==null?void 0:r.times)==null?void 0:l.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,s=!0){var o,r,l;if(!this.clip)return[0,this.duration];const c=(o=this.pos)==null?void 0:o.times,h=(r=this.rot)==null?void 0:r.times,d=(l=this.scale)==null?void 0:l.times,u=[];if(e&&c)for(const p of c)u.push(p);if(t&&h)for(const p of h)u.push(p);if(s&&d)for(const p of d)u.push(p);return u.includes(0)||u.push(0),u.sort((p,g)=>p-g),[...new Set(u)]}*getValues(e,t=!0,s=!0,o=!0){var r,l,c;const h=new S,d=new V,u=new S(1,1,1),p=this.target,g=t?(r=this.pos)==null?void 0:r.createInterpolant():void 0,f=s?(l=this.rot)==null?void 0:l.createInterpolant():void 0,y=o?(c=this.scale)==null?void 0:c.createInterpolant():void 0;g||h.set(p.position.x,p.position.y,p.position.z),f||d.set(p.quaternion.x,p.quaternion.y,p.quaternion.z,p.quaternion.w),y||u.set(p.scale.x,p.scale.y,p.scale.z),g&&g.valueSize!==3&&(g.valueSize=3),f&&f.valueSize!==4&&(f.valueSize=4),y&&y.valueSize!==3&&(y.valueSize=3);const v=0;for(let b=0-v;b<e.length+v;b++){let _=0,w=0;if(b<0?(_=e[0],w=_-Cm.animationDurationPadding/2+1/60):b>=e.length?(_=e[e.length-1],w=_+Cm.animationDurationPadding/2-1/60):(_=e[b],w=_),g){const x=g.evaluate(_);h.set(x[0],x[1],x[2])}if(f){const x=f.evaluate(_);d.set(x[0],x[1],x[2],x[3])}if(y){const x=y.evaluate(_);u.set(x[0],x[1],x[2])}if(this.useRootMotion&&p===this.root){const x=new ne;x.compose(h,d,u),x.multiply(p.matrix),x.decompose(h,d,u)}yield{time:w,translation:h,rotation:d,scale:u,index:b}}}};a(dp,"frameRate",60),a(dp,"animationDurationPadding",6/60),a(dp,"restPoseClipDuration",6/60);let ut=dp;class up{constructor(e){a(this,"dict",new Map),a(this,"rootTargetMap",new Map),a(this,"rootAndClipToRegisteredAnimationMap",new Map),a(this,"rootToRegisteredClip",new Map),a(this,"lastClipEndTime",0),a(this,"clipToStartTime",new Map),a(this,"clipToHoldClip",new Map),a(this,"serializers",[]),a(this,"injectRestPoses",!1),a(this,"injectImplicitBehaviours",!1),this.injectRestPoses=e,this.injectImplicitBehaviours=e}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}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(ut.restPoseClipDuration+ut.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,s]of this.rootAndClipToRegisteredAnimationMap){const o=s.start+s.duration;o>e&&(e=o)}return e*60}getClipCount(e){var t;return((t=this.rootToRegisteredClip.get(e))==null?void 0:t.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){var s;if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const o=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(o))return this.rootAndClipToRegisteredAnimationMap.get(o);dn&&console.log("registerAnimation",e,t);const r=this.injectRestPoses?1:0,l=(((s=this.rootToRegisteredClip.get(e))==null?void 0:s.length)??0)+r,c=this.rootTargetMap.get(e),h=new Set(c);if(t&&t.tracks)for(const u of t.tracks){const p=Ca.parseTrackName(u.name),g=Ca.findNode(e,p.nodeName);if(!g){console.warn("no object found for track",u.name,"using "+e.name+" instead");continue}this.dict.has(g)||this.dict.set(g,[]);const f=this.dict.get(g);if(!f){console.warn("no transform data found for target ",g,"at slot "+l+", this is likely a bug");continue}h.delete(g),this.injectRestPoses&&!f[0]&&(console.log("Injecting rest pose",g,t,"at slot",l),f[0]=new ut(null,g,null));let y=f[l];y||(y=new ut(e,g,t),f[l]=y),y.addTrack(u),c!=null&&c.includes(g)||c==null||c.push(g)}dn&&console.log("Unregistered nodes for this clip",h,"clip",t,"at slot",l,"for root",e,"targets",c);for(const u of h){const p=this.dict.get(u);if(!p)continue;if(this.injectRestPoses&&!p[0]){console.warn("Adding rest pose for ",u,t,"at slot",l,"This is likely a bug, should have been added earlier.");const f=new ut(null,u,null);p[0]=f}let g=p[l];g||(dn&&console.log("Adding padding clip for ",u,t,"at slot",l),g=new ut(e,u,t),p[l]=g)}const d=new pr(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(o,d),dn&&console.log({root:e,clip:t,info:d}),t){const u=this.rootToRegisteredClip.get(e);if(u?u.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=ut.restPoseClipDuration);let p=this.lastClipEndTime+ut.animationDurationPadding,g=p+t.duration;const f=Math.round(p*60)/60,y=Math.round(g*60)/60;Math.abs(f-p)<.01&&(p=f),Math.abs(y-g)<.01&&(g=y),p=Math.ceil(p),g=p+t.duration,this.clipToStartTime.set(t,p),this.lastClipEndTime=g}}return d}onAfterHierarchy(e){dn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,s;dn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const o of this.rootTargetMap.keys()){const r=this.rootTargetMap.get(o);if(!r)continue;let l;const c=[];for(const h of r){const d=this.dict.get(h);if(!d){console.error("No data found for target on USDZ export \u2013 please report a bug!",h);continue}l===void 0&&(l=d?.length),l!==d?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",d);for(let u=0;u<d.length;u++){let p=d[u];if(!p){const f=u-(this.injectRestPoses?1:0);d[u]=new ut(null,h,this.rootToRegisteredClip.get(o)[f]),p=d[u]}const g=p.getDuration();if(c[u]===void 0)c[u]=g;else if(c[u]!==g){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:d,target:h}),c[u]=g;continue}}}}for(const o of this.serializers){const r=(t=o.model)==null?void 0:t.parent,l=r?.isDynamic===!0;F0&&console.log(l,(s=o.model)==null?void 0:s.parent),l&&o.registerCallback(r)}}onExportObject(e,t,s){P.foreachComponent(e,r=>{const l=r;typeof l.createAnimation=="function"&&l.createAnimation(this,t,s)},!1);const o=new aA(e,this);this.serializers.push(o),o.registerCallback(t)}}class aA{constructor(e,t){a(this,"model"),a(this,"object"),a(this,"animationData"),a(this,"ext"),a(this,"callback"),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)),F0&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,s){var o;const r=this.model,l=this.animationData;if(r&&r.skinnedMesh){let c=function(F){const I=[];for(const[Y,te]of F){let ae=`${Y} : [`;const le=[];for(const ye of te)le.push(`(${ue(ye.x)}, ${ue(ye.y)}, ${ue(ye.z)})`);ae=ae.concat(le.join(", ")),ae=ae.concat("],"),I.push(ae)}return I},h=function(F){const I=[];for(const[Y,te]of F){let ae=`${Y} : [`;const le=[];for(const ye of te)le.push(`(${ue(ye.w)}, ${ue(ye.x)}, ${ue(ye.y)}, ${ue(ye.z)})`);ae=ae.concat(le.join(", ")),ae=ae.concat("],"),I.push(ae)}return I},d=function(F){let I,Y=!0;const te=new Map;for(const[le,ye]of F){I===void 0&&(I=ye.length),I!==ye.length&&(Y=!1);let He=0;for(const vt of ye)He++,vt||(te.has(le)||te.set(le,[]),te.get(le).push(He))}dn&&console.log("Bone count: ",F.size,"TransformData entries per bone: ",I,"Undefined bone entries: ",te),console.assert(Y,"All bones should have the same number of TransformData entries",F),console.assert(te.size===0,"All TransformData entries should be set",te);const ae=[];for(const[le,ye]of F)for(let He=0;He<ye.length;He++){const vt=ye[He],mr=s.getStartTimeByClip(vt.clip);ae.length<=He&&ae.push({pos:[],rot:[],scale:[],timeOffset:mr});const uo=ae[He];uo.pos.push(...vt.getSortedTimesArray(!0,!1,!1)),uo.rot.push(...vt.getSortedTimesArray(!1,!0,!1)),uo.scale.push(...vt.getSortedTimesArray(!1,!1,!0))}for(const le of ae)le.pos.sort((ye,He)=>ye-He),le.rot.sort((ye,He)=>ye-He),le.scale.sort((ye,He)=>ye-He),le.pos=[...new Set(le.pos)],le.rot=[...new Set(le.rot)],le.scale=[...new Set(le.scale)];return ae},u=function(F,I,Y){const te=new Map,ae=new Map,le=new Map,ye=I.length;for(const He of Y){const vt=F.get(He);let mr;vt?console.assert(vt.length===ye,"We should have the same number of TransformData entries for each bone",vt,I):mr=new ut(null,He,null);for(let uo=0;uo<ye;uo++){const km=vt?vt[uo]:mr,wa=I[uo];for(const{time:Vl,translation:$l}of km.getValues(wa.pos,!0,!1,!1)){const ys=(Vl+wa.timeOffset)*60;te.has(ys)||te.set(ys,new Array),te.get(ys).push($l.clone())}for(const{time:Vl,rotation:$l}of km.getValues(wa.rot,!1,!0,!1)){const ys=(Vl+wa.timeOffset)*60;ae.has(ys)||ae.set(ys,new Array),ae.get(ys).push($l.clone())}for(const{time:Vl,scale:$l}of km.getValues(wa.scale,!1,!1,!0)){const ys=(Vl+wa.timeOffset)*60;le.has(ys)||le.set(ys,new Array),le.get(ys).push($l.clone())}}}return{position:te.size==0?void 0:te,quaternion:ae.size==0?void 0:ae,scale:le.size==0?void 0:le}},p=function(F){const I=[];for(const Y of F)I.push(`(${ue(Y.x)}, ${ue(Y.y)}, ${ue(Y.z)})`);return I.join(", ")},g=function(F){const I=[];for(const Y of F)I.push(`(${ue(Y.w)}, ${ue(Y.x)}, ${ue(Y.y)}, ${ue(Y.z)})`);return I.join(", ")},f=function(F){const I=new Map;if(dn){const Y=new Array;for(const[te,ae]of l)Y.push(te.uuid+": "+ae.length+" "+ae.map(le=>{var ye;return(ye=le.clip)==null?void 0:ye.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
|
|
1251
1251
|
`+Y.join(`
|
|
1252
|
-
`))}for(const Y of F){const te=l.get(Y);te&&I.set(Y,te)}return I},y=function(F){const I=f(F),Y=d(I);return u(I,Y,F)};const v=r.skinnedMesh.skeleton,b=new Array,_=[],w=[];for(const F of v.bones){_.push(F),w.push(F.uuid);const I=v.boneInverses[v.bones.indexOf(F)];b.push({bone:F,inverse:I})}let x=1e4;for(;w.length<v.bones.length&&x-- >0;)for(const F of _){const I=F.children;for(const Y of I)if(w.indexOf(Y.uuid)===-1&&v.bones.indexOf(Y)!==-1){_.push(Y),w.push(Y.uuid);const te=v.boneInverses[v.bones.indexOf(Y)];b.push({bone:Y,inverse:te})}}x<=0&&console.error("Failed to sort bones in skinned mesh",r.skinnedMesh,v.bones,w);for(const F of x1(v.bones))b.push({bone:F,inverse:F.matrixWorld.clone().invert()});const k=b[0].bone.parent;k||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),b.sort((F,I)=>hl(F.bone,k)>hl(I.bone,k)?1:-1);const M=t.quickLookCompatible,T=[],D=[],z=[],U=[];for(const{bone:F}of b){if(M){const I=F.scale;I.x==0&&(I.x=1e-5),I.y==0&&(I.y=1e-5),I.z==0&&(I.z=1e-5),T.push(new ne().compose(F.position,F.quaternion,F.scale))}else T.push(F.matrix.clone());D.push(F.position),z.push(F.quaternion),U.push(F.scale)}const E=b.map(F=>'"'+hl(F.bone,k)+'"').join(", "),$=b.map(F=>L1(F.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${$}]`),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${T.map(F=>L1(F)).join(", ")}]`);const H=y(b.map(F=>F.bone));if(dn){let F=1e7,I=0;for(const Y of((o=H.position)==null?void 0:o.keys())??[])F=Math.min(F,Y),I=Math.max(I,Y);console.log("Time samples",F,I,H)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine(`quatf[] rotations = [${g(z)}]`),H&&H.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const F=h(H.quaternion);for(const I of F)e.appendLine(I);e.closeBlock()}if(e.appendLine(`half3[] scales = [${p(U)}]`),H&&H.scale){e.beginBlock("half3[] scales.timeSamples = {","");const F=c(H.scale);for(const I of F)e.appendLine(I);e.closeBlock()}if(e.appendLine(`float3[] translations = [${p(D)}]`),H&&H.position){e.beginBlock("float3[] translations.timeSamples = {","");const F=c(H.position);for(const I of F)e.appendLine(I);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const s=this.animationData.get(this.object);if(s)for(let u=0;u<s.length;u++)s[u]===void 0&&(s[u]=new ut(null,this.object,null));const o=this.ext;this.skinnedMeshExport(e,t,o);const r=this.object,l=this.model,c=this.animationData.get(r);if(!c||r.isSkinnedMesh)return;F0&&console.log("SERIALIZE",this.model.name,this.object.type,c);const h=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function d(u,p){var g;if(u.some(f=>f&&{position:f.pos,rotation:f.rot,scale:f.scale}[p])){switch(p){case"position":l.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":l.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":l.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let f=0;f<u.length;f++){const y=u[f];if(!y)continue;const v=o.getStartTimeByClip(y.clip),b=y.getSortedTimesArray(p==="position",p==="rotation",p==="scale");if(!b||b.length===0){console.error("got an animated object but no time values?",r,y);continue}const _=!y.clip,w=p==="position"&&(y.pos||_),x=p==="rotation"&&(y.rot||_),k=p==="scale"&&(y.scale||_);if(w||x||k){const M=((g=y.clip)==null?void 0:g.name)??"rest",T=y.getDuration();dn&&console.log("Write .timeSamples:",M,v,T,u),e.appendLine("# "+M+": start="+h.format(v*ut.frameRate)+", length="+h.format(T*ut.frameRate)+", frames="+y.getFrames())}if(w)for(const{time:M,translation:T}of y.getValues(b,!0,!1,!1)){const D=`${h.format((v+M)*ut.frameRate)}: (${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(D)}if(x)for(const{time:M,rotation:T}of y.getValues(b,!1,!0,!1)){const D=`${h.format((v+M)*ut.frameRate)}: (${ue(T.w)}, ${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(D)}if(k)for(const{time:M,scale:T}of y.getValues(b,!1,!1,!0)){const D=`${h.format((v+M)*ut.frameRate)}: (${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(D)}}e.closeBlock()}}d(c,"position"),d(c,"rotation"),d(c,"scale")}}const lA=C("debugusdz");class _a{constructor(){a(this,"files",new Array)}static getName(e){var t;const s=e.split(".").pop();let o=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return o||(o="Audio_"+Math.random().toString(36).substring(2,15)),as(o)+"."+s}get extensionName(){return"Audio"}onExportObject(e,t,s){const o=P.getComponents(e,ns);if(o.length)for(const r of o){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const l=r.clip.split("/").pop()||"Audio",c=_a.getName(r.clip),h=as(c);if(!this.files.some(d=>d.path===r.clip)){this.files.push({path:r.clip,name:c});const d=c.toLowerCase();s.quickLookCompatible&&!d.endsWith(".mp3")&&!d.endsWith(".wav")&&!d.endsWith(".m4a")&&console.error("Audio file "+r.clip+" from "+r.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}s.quickLookCompatible||t.addEventListener("serialize",(d,u)=>{d.appendLine(),d.beginBlock(`def SpatialAudio "${h}"`,"(",!1),d.appendLine(`displayName = "${l}"`),d.closeBlock(")"),d.beginBlock(),d.appendLine(`uniform asset filePath = @audio/${c}@`),d.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),d.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),d.appendLine(`uniform float gain = ${r.volume}`),d.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const s="audio/"+t.name;if(e.files[s]){lA&&console.warn("Audio file with name "+s+" already exists in the context. Skipping.");continue}const o=await(await(await fetch(t.path)).blob()).arrayBuffer(),r=new Uint8Array(o);e.files[s]=r}}}var cA=Object.defineProperty,Ne=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&cA(e,t,o),o};const $1=C("debugusdzbehaviours");function Zc(n){n&&(n.getComponentInParent(Ka)||(B()&&console.debug('Raycaster on "'+n.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),n.addComponent(ji)))}class Xr extends j{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new S),a(this,"targetRot",new V),a(this,"targetScale",new S)}start(){Zc(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=ee(this.object).clone(),t=ee(this.target).clone(),s=Se(this.object).clone(),o=Se(this.target).clone(),r=Ge(this.object).clone(),l=Ge(this.target).clone(),c=e.distanceTo(t),h=s.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){lt(this.object,t),Yi(this.object,o),Ta(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,p),this.targetRot.slerpQuaternions(s,o,p),this.targetScale.lerpVectors(r,l,p),lt(this.object,this.targetPos),Yi(this.object,this.targetRot),Ta(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(),s=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,h),this.object.quaternion.slerpQuaternions(t,this.targetRot,h),this.object.scale.lerpVectors(s,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const s=new ei("Move to "+((t=this.target)==null?void 0:t.name),At.tapTrigger(this.gameObject),ve.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(s)}}}Ne([m(A)],Xr.prototype,"object"),Ne([m(A)],Xr.prototype,"target"),Ne([m()],Xr.prototype,"duration"),Ne([m()],Xr.prototype,"relativeMotion");var tt;const pp=(tt=class extends j{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var n;this._objectsWithThisMaterial=this.objectsWithThisMaterial,Zc(this.gameObject),B()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((n=this.materialToSwitch)==null?void 0:n.name)+'"')}onPointerEnter(n){this.context.input.setCursor("pointer")}onPointerExit(n){this.context.input.unsetCursor("pointer")}onPointerClick(n){if(n.use(),!!this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){const t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(n=>{if(n instanceof q)if(Array.isArray(n.material)){for(const e of n.material)if(e===this.materialToSwitch){this.objectsWithThisMaterial.push(n);break}}else n.material===this.materialToSwitch?this.objectsWithThisMaterial.push(n):nw(n.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(n)}),this._objectsWithThisMaterial)}async beforeCreateDocument(n,e){this.targetModels=[],tt._materialTriggersPerId={},tt.variantSwitchIndex=0,this.materialToSwitch&&await Xe.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Xe.assignTextureLOD(this.variantMaterial,0)}createBehaviours(n,e,t){this.objectsWithThisMaterial.find(s=>s.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(tt._materialTriggersPerId[this.materialToSwitch.uuid]||(tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(n,e){if(!this.materialToSwitch)return;const t=tt._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const o of t){const r=o.createVariants();r&&r.length>0&&(s[o.selfModel.uuid]=r)}for(const o of t){const r=[];for(const l in s)l!==o.selfModel.uuid&&r.push(...s[l]);o.createAndAttachBehaviors(n,s[o.selfModel.uuid],r)}}delete tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(n,e,t){const s=[],o=Math.max(0,this.fadeDuration);s.push(ve.fadeAction([...this.targetModels,...t],o,!1)),s.push(ve.fadeAction(e,o,!0)),n.addBehavior(new ei("Select_"+this.selfModel.name,At.tapTrigger(this.selfModel),ve.parallel(...s))),tt._parallelStartHiddenActions.push(...e),tt._startHiddenBehaviour||(tt._startHiddenBehaviour=new ei("StartHidden_"+this.selfModel.name,At.sceneStartTrigger(),ve.fadeAction(tt._parallelStartHiddenActions,o,!1)),n.addBehavior(tt._startHiddenBehaviour))}static getMaterialName(n){return as(n.name||"Material")+"_"+n.id}createVariants(){if(!this.variantMaterial)return null;const n=[];for(const e of this.targetModels){const t=e.clone();t.name+="_Variant_"+tt.variantSwitchIndex+++"_"+tt.getMaterialName(this.variantMaterial),t.displayName=t.displayName+": Variant with material "+this.variantMaterial.name,t.material=this.variantMaterial,t.geometry=e.geometry,t.transform=e.transform,(!e.parent||!e.parent.isEmpty())&&gi.createEmptyParent(e),e.parent&&e.parent.add(t),n.push(t)}return n}},a(tt,"_materialTriggersPerId",{}),a(tt,"_startHiddenBehaviour",null),a(tt,"_parallelStartHiddenActions",[]),a(tt,"variantSwitchIndex",0),tt);Ne([m(Pe)],pp.prototype,"materialToSwitch"),Ne([m(Pe)],pp.prototype,"variantMaterial"),Ne([m()],pp.prototype,"fadeDuration");let U0=pp;var ke;const Jc=(ke=class extends j{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){Zc(this.gameObject)}onPointerClick(n){n.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ke.wasVisible]===void 0&&(this.gameObject[ke.wasVisible]=this.gameObject.activeSelf),this.target[ke.wasVisible]===void 0&&(this.target[ke.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ke.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ke.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(n,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&M0.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ke.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+ke.clonedToggleIndex++,t.add(c),this.gameObject[ke.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[ke.toggleClone];if(!this.gameObject[ke.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+ke.clonedToggleIndex++,t.add(c),this.gameObject[ke.reverseToggleClone]=c}this.toggleModel=this.gameObject[ke.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),s=l,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ve.fadeAction(s,0,!1)),l.push(ve.fadeAction(this.toggleModel,0,!0)),l.push(ve.fadeAction(this.targetModel,0,o)),n.addBehavior(new ei("Toggle_"+s.name+"_ToggleTo"+(o?"On":"Off"),At.tapTrigger(s),ve.parallel(...l)));const c=[];c.push(ve.fadeAction(this.toggleModel,0,!1)),c.push(ve.fadeAction(s,0,!0)),c.push(ve.fadeAction(this.targetModel,0,!o)),n.addBehavior(new ei("Toggle_"+s.name+"_ToggleTo"+(o?"Off":"On"),At.tapTrigger(this.toggleModel),ve.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ve.fadeAction(s,0,!1)),l.push(ve.fadeAction(this.targetModel,0,o)),n.addBehavior(new ei("Toggle_"+s.name+"_ToggleTo"+(o?"On":"Off"),At.tapTrigger(s),l.length>1?ve.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(t),this.toggleModel&&r.push(this.toggleModel),mp.add(r,n)}}afterSerialize(n,e){this.gameObject[ke.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ke.wasVisible],delete this.gameObject[ke.wasVisible]),this.target&&this.target[ke.wasVisible]!==void 0&&(this.target.visible=this.target[ke.wasVisible],delete this.target[ke.wasVisible]),delete this.gameObject[ke.toggleClone],delete this.gameObject[ke.reverseToggleClone]}},a(ke,"clonedToggleIndex",0),a(ke,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(ke,"toggleClone",Symbol("clone for toggling")),a(ke,"reverseToggleClone",Symbol("clone for reverse toggling")),ke);Ne([m(A)],Jc.prototype,"target"),Ne([m()],Jc.prototype,"toggleOnClick"),Ne([m()],Jc.prototype,"targetState"),Ne([m()],Jc.prototype,"hideSelf");let z0=Jc;const N0=class ur extends j{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(e,t){const s=Array.isArray(e)?e:[e];for(const o of s)ur._fadeObjects.includes(o)||(console.log("adding hide on start",o),ur._fadeObjects.push(o));ur._fadeBehaviour===void 0&&(ur._fadeBehaviour=new ei("HideOnStart",At.sceneStartTrigger(),ve.fadeAction(ur._fadeObjects,0,!1)),t.addBehavior(ur._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&(this.wasVisible||ur.add(t,e))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}};a(N0,"_fadeBehaviour"),a(N0,"_fadeObjects",[]);let mp=N0;class pl extends j{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const o=new ei("emphasize "+this.name,At.tapTrigger(this.gameObject),ve.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(o)}}afterCreateDocument(e,t){}}Ne([m()],pl.prototype,"target"),Ne([m()],pl.prototype,"duration"),Ne([m()],pl.prototype,"motionType");class Wo extends j{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){Zc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(ns);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.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,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;_a.getName(o);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof q&&g.visible&&(h=!0)}),h=!0;const d=e.addAudioClip(o);let u=ve.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ve.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new ei("playAudio"+p,At.tapTrigger(t),u);e.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&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 g=new ei("playAudioOnStart"+p,At.sceneStartTrigger(),u);e.addBehavior(g)}}}}Ne([m(ns)],Wo.prototype,"target"),Ne([m(URL)],Wo.prototype,"clip"),Ne([m()],Wo.prototype,"toggleOnClick");var zi;const W0=(zi=class extends j{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var n,e;return((n=this.animator)==null?void 0:n.gameObject)||((e=this.animation)==null?void 0:e.gameObject)}start(){Zc(this.gameObject)}onPointerClick(n){var e;n.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(zi.rootsWithExclusivePlayback.size>1){const n='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.';B()&&be(n),console.warn(n,...zi.rootsWithExclusivePlayback)}zi.animationActions=[],zi.rootsWithExclusivePlayback=new Set}afterCreateDocument(n,e){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const t=e.document,s=e.extensions.find(l=>l instanceof up);if(!s)return;const o=s.getClipCount(this.target)>1;o&&(B()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),zi.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";t.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=zi.getActionForSequences(t,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new ei(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?At.tapTrigger(this.selfModel):At.sceneStartTrigger(),d);o&&u.makeExclusive(!0),n.addBehavior(u)}})}static getActionForSequences(n,e,t,s,o){const r=(c,h)=>{let d=zi.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ve.startAnimationAction(c,h),zi.animationActions.push(d)),d},l=ve.sequence();if(t&&t.length>0)for(const c of t)l.addAction(r(e,c));if(s&&s.length>0){const c=l.actions.length==0?l:ve.sequence();for(const h of s)c.addAction(r(e,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(ve.waitAction(o)),l}static getAndRegisterAnimationSequences(n,e,t){var s,o,r,l,c,h,d,u;if(!e)return;const p=e.getComponent(Rt),g=e.getComponent(Ut);if(!p&&!g)return;if(p&&!t)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+e.name);let f=[],y=[];if(g){const M=n.registerAnimation(e,g.clip);M&&(g.loop?y.push(M):f.push(M));let T=0;if(g.minMaxOffsetNormalized){const D=g.minMaxOffsetNormalized.x,z=g.minMaxOffsetNormalized.y;T=(((s=g.clip)==null?void 0:s.duration)||1)*(D+Math.random()*(z-D))}return{animationSequence:f,animationLoopAfterSequence:y,randomTimeOffset:T}}const v=p?.runtimeAnimatorController;let b=v?.findState(t),_=[],w=[];if(v&&b){const M=new Array;M.push(b);let T=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(T=!0);break}const D=b.transitions.find(U=>U.conditions.length===0),z=D?v.getState(D.destinationState,0):null;if(z&&M.includes(z)){b=z,T=!0;break}else if(D){if(b=z,!b)break;M.push(b)}else{T=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&b){const D=M.indexOf(b);_=M.slice(0,D),w=M.slice(D),$1&&console.log("found loop from "+t,"states until loop",_,"states looping",w)}else _=M,w=[],$1&&console.log("found no loop from "+t,"states",_);if(!w.length){const D=_[_.length-1],z=(l=D.motion)==null?void 0:l.clip;if(z){let U;if(n.holdClipMap.has(z))U=n.holdClipMap.get(z);else{const E=D.name+"_hold";U=z.clone(),U.duration=1,U.name=E;const $=z.duration;U.tracks=z.tracks.map(H=>{const F=H.clone();F.times=new Float32Array([0,$]);const I=H.values.length,Y=H.getValueSize(),te=H.values.slice(I-Y,I);return F.values=new Float32Array(2*Y),F.values.set(te,0),F.values.set(te,Y),F}),U.name=E,n.holdClipMap.set(z,U)}if(U){const E={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:D.hash+1};w.push(E)}}}}if(_.length===1&&(!((c=_[0].motion)!=null&&c.clip)||((d=(h=_[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){f=new Array;const M=n.registerAnimation(e,null);M&&f.push(M);return}if(_=_.filter(M=>{var T,D,z;return((T=M.motion)==null?void 0:T.clip)&&((z=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:z.length)>0}),w=w.filter(M=>{var T,D,z;return((T=M.motion)==null?void 0:T.clip)&&((z=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:z.length)>0}),_.length===0&&w.length===0){console.warn("No clips found for state "+t+" on "+p?.name+", can't export animation data");return}const x=(M,T)=>{if(!e)return;const D=n.registerAnimation(e,M.motion.clip??null);D?(D.speed=M.speed,T.push(D)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(_.length>0){f=new Array;for(const M of _)x(M,f)}if(w.length>0){y=new Array;for(const M of w)x(M,y)}let k=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,D=_.length?_[0]:w.length?w[0]:null;k=(((u=D?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:f,animationLoopAfterSequence:y,randomTimeOffset:k}}createAnimation(n,e,t){if(!this.target||!this.animator&&!this.animation)return;const s=zi.getAndRegisterAnimationSequences(n,this.target,this.stateName);s&&(this.animationSequence=s.animationSequence,this.animationLoopAfterSequence=s.animationLoopAfterSequence,this.randomOffsetNormalized=s.randomTimeOffset,this.stateAnimationModel=e)}},a(zi,"animationActions",[]),a(zi,"rootsWithExclusivePlayback",new Set),zi);Ne([m(Rt)],W0.prototype,"animator"),Ne([m()],W0.prototype,"stateName");let eh=W0;class ml extends j{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}Ne([m(A)],ml.prototype,"target");class th extends j{constructor(){super(...arguments),a(this,"target")}}Ne([m(ml)],th.prototype,"target");class ih extends ml{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ne([m()],ih.prototype,"type"),Ne([m()],ih.prototype,"duration");class V0 extends th{}const H1=class CC{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new CC}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return Po.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=Q.supportsQuickLookAR();e.innerText="View in AR",e.prepend(Mt("view_in_ar"));let s=!1,o=null;return e.addEventListener("click",()=>{o=Sc(gn),o||(s=!0,o=new gn),s&&(o.objectToExport=J.Current.scene),o?(e.classList.add("this-mode-is-requested"),o.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){var t;if(this._arButton)return this._arButton;const s="immersive-ar",o=document.createElement("button");return this._arButton=o,o.classList.add("webxr-button"),o.dataset.needle="webxr-ar-button",o.innerText="Enter AR",o.prepend(Mt("view_in_ar")),o.title="Click to start an AR session",o.addEventListener("click",()=>oe.start(s,e)),this.updateSessionSupported(o,s),this.listenToXRSessionState(o,s),this.hideElementDuringXRSession(o),this.isSecureConnection||(o.disabled=!0,o.title="WebXR requires a secure connection (HTTPS)"),Q.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(o,s)),o}createVRButton(e){var t;if(this._vrButton)return this._vrButton;const s="immersive-vr",o=document.createElement("button");return this._vrButton=o,o.classList.add("webxr-button"),o.dataset.needle="webxr-vr-button",o.innerText="Enter VR",o.prepend(Mt("panorama_photosphere")),o.title="Click to start a VR session",o.addEventListener("click",()=>oe.start(s,e)),this.updateSessionSupported(o,s),this.listenToXRSessionState(o,s),this.hideElementDuringXRSession(o),this.isSecureConnection||(o.disabled=!0,o.title="WebXR requires a secure connection (HTTPS)"),Q.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(o,s)),o}createSendToQuestButton(){var e;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",s=document.createElement("button");return this._sendToQuestButton=s,s.dataset.needle="webxr-sendtoquest-button",s.innerText="Open on Quest",s.prepend(Mt("share_windows")),s.title="Click to send this page to the Oculus Browser on your Quest",s.addEventListener("click",()=>{const o=encodeURIComponent(window.location.href),r=t+o;window.open(r)==null&&De("This page doesn't allow popups. Please paste "+r+" into your browser.")}),this.listenToXRSessionState(s),this.hideElementDuringXRSession(s),Q.isMozillaXR()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>{var o;(o=navigator.xr)!=null&&o.isSessionSupported("immersive-vr")?s.style.display="none":s.style.display=""}),s}createQRCode(){return Po.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}oe.isSessionSupported(t).then(s=>{e.style.display=s?"":"none",B()&&!s&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Ud(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Pg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(oe.onSessionRequestStart(s=>{s.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),oe.onSessionRequestEnd(s=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}};a(H1,"_instance");let gl=H1;var hA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,St=(n,e,t,s)=>{for(var o=s>1?void 0:s?dA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&hA(e,t,o),o};const gp=C("debugspriterenderer"),uA=C("wireframe"),G1=class xv{static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&xv.cache[e.guid])return gp&&console.log("Take cached geometry for sprite",e.guid),xv.cache[e.guid];const t=new Ws;e.__cached_geometry=t;const s=new Float32Array(e.triangles.length*3),o=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){const l=e.triangles[r];s[r*3]=-e.vertices[l].x,s[r*3+1]=e.vertices[l].y,s[r*3+2]=0;const c=e.uv[l];o[r*2]=c.x,o[r*2+1]=1-c.y}return t.setAttribute("position",new _t(s,3)),t.setAttribute("uv",new _t(o,2)),e.guid&&(this.cache[e.guid]=t),gp&&console.log("Built sprite geometry",e,t),t}};a(G1,"cache",{});let fp=G1;class pA{constructor(){a(this,"x"),a(this,"y")}}function q1(n){n&&(n.colorSpace!=Mn&&(n.colorSpace=Mn,n.needsUpdate=!0),n.minFilter==wd&&n.magFilter==wd&&(n.anisotropy=1,n.needsUpdate=!0))}let Yn=class{constructor(n){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),n&&(this.texture=n,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}])}get mesh(){return this._mesh||(this._mesh=new q(fp.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&q1(this.texture),this._material=new Me({map:this.texture,color:16777215,side:Oi,transparent:!0})),this._material}getGeometry(){return fp.getOrCreateGeometry(this)}};St([m()],Yn.prototype,"guid",2),St([m(je)],Yn.prototype,"texture",2),St([jr()],Yn.prototype,"triangles",2),St([jr()],Yn.prototype,"uv",2),St([jr()],Yn.prototype,"vertices",2);const $0=Symbol("spriteOwner");class fl{constructor(){a(this,"sprites"),this.sprites=[]}}St([m(Yn)],fl.prototype,"sprites",2);const H0=class Sv{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const e=new Sv;return e.spriteSheet=new fl,e}clone(){const e=new Sv;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 fl,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const s=this.spriteSheet.sprites[t],o=s?.texture;if(o&&(q1(o),!s.__hasLoadedProgressive)){s.__hasLoadedProgressive=!0;const r=o;Xe.assignTextureLOD(o,0).then(l=>{l instanceof je&&(s.texture=l,e?.map===r&&(e.map=l,e.needsUpdate=!0))})}}};St([m(fl)],H0.prototype,"spriteSheet",2),St([m()],H0.prototype,"index",2);let yl=H0;class fi extends j{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(e){var t;if(!this._spriteSheet)return;const s=(t=this._spriteSheet.spriteSheet)==null?void 0:t.sprites[this.spriteIndex];s&&(s.texture=e,this.updateSprite())}addSprite(e,t=!1){var s,o;if(this._spriteSheet||(this._spriteSheet=yl.create()),!this._spriteSheet.spriteSheet)return-1;(s=this._spriteSheet.spriteSheet)==null||s.sprites.push(e);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return t&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t}else e instanceof Yn?(this._spriteSheet||(this._spriteSheet=yl.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(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=yl.create(),gp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){var t;if(!this.__didAwake&&!e)return!1;const s=this._spriteSheet;if(!((t=s?.spriteSheet)!=null&&t.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=s.spriteSheet.sprites[this.spriteIndex];if(!o)return gp&&console.warn("Sprite not found",this.spriteIndex,s.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=fp.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Me({color:16777215,side:Oi});if(uA&&(r.wireframe=!0),this.color&&(r.color||(r.color=new re),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,r.depthWrite=!1,o.texture&&!r.wireframe){let l=o.texture;l[$0]!==void 0&&l[$0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[$0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new q(fp.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),Xe.assignTextureLOD(r,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,s?.update(this.sharedMaterial),!0}}St([m()],fi.prototype,"drawMode",2),St([m(pA)],fi.prototype,"size",2),St([m(he)],fi.prototype,"color",2),St([m(Pe)],fi.prototype,"sharedMaterial",2),St([m()],fi.prototype,"transparent",2),St([m()],fi.prototype,"cutoutThreshold",2),St([m()],fi.prototype,"castShadows",2),St([m()],fi.prototype,"renderOrder",2),St([m()],fi.prototype,"toneMapped",2),St([m(yl)],fi.prototype,"sprite",1);const X1=C("debugwebxr"),mA=new ne().makeRotationY(Math.PI),G0=class rd extends j{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new Si),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",e=>{var t;if(this._isPlacing==!1||e!=null&&e.used)return;let s=this._reticle[0];if(!s){console.warn("No reticle to place...");return}if(!s.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((t=oe.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let o=this._hits[0];if(e&&e.origin instanceof Og){const r=this._reticle[e.origin.index];r&&(s=r,o=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(),s.position.copy(s.lastPos),s.quaternion.copy(s.lastQuat),this.onApplyPose(s),rd._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(oe.active,o),this.context.xr)for(const r of this.context.xr.controllers)r.cancelHitTestSource()}),a(this,"upVec",new S(0,1,0)),a(this,"lookPoint",new S),a(this,"worldUpVec",new S(0,1,0))}static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const s=this._eventListeners[t].indexOf(e);s>=0&&this._eventListeners[t].splice(s,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){X1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,rd._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new A;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let s=this.context.scene.children.length-1;s>=0;s--){const o=this.context.scene.children[s];this._placementScene.add(o)}if(this.context.scene.add(t),this.autoCenter){const s=ni(this._placementScene.children),o=s.getCenter(new S),r=s.getSize(new S),l=new ne;l.makeTranslation(o.x,o.y-r.y*.5,o.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(t,this);for(const s of this._reticle)Ai(s);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ri.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ri.Early}),this.onRevertSceneChanges(),this._anchor=null,rd._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){var t,s,o,r;if(e.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(t=e.xr.rig)==null?void 0:t.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const h of e.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(e.xr,h.index,d,e.xr.rigScale))}if(!c){const h=e.xr.getHitTest();h&&this.updateReticleAndHits(e.xr,0,h,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const l=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=e.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new gA(this.context)),(s=this.userInput)==null||s.enable()):(o=this.userInput)==null||o.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(e.xr.rig){const l=e.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,s,o){this._hits[t]=s.hit;let r=this._reticle[t];if(!r){if(this.customReticle)if(this.customReticle.asset)r=Ha(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new q(new kP(.07,.09,32).rotateX(-Math.PI/2),new Me({side:Oi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if(X1){const l=new Pi(1);l.position.y+=.01,r.add(l)}this._reticle[t]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||s.position.clone(),r.lastQuat=r.lastQuat||s.quaternion.clone(),r.position.copy(r.lastPos.lerp(s.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(s.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(o,o,o),this.customReticle&&this.applyViewBasedTransform(r),r.updateMatrix(),r.visible=!0,r.parent!==this.context.scene&&this.context.scene.add(r),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(r.quaternion),this.upVec.dot(X(0,1,0))>.9){let l=r["autoplace:timer"]||0;l>=1?(r.visible=!1,this.onPlaceScene(null)):(l+=this.context.time.deltaTime,r["autoplace:timer"]=l)}else r["autoplace:timer"]=0}onSetScale(){var e,t,s;if(!rd._hasPlaced)return;const o=(t=(e=oe.active)==null?void 0:e.rig)==null?void 0:t.gameObject;if(o){const r=((s=oe.active)==null?void 0:s.rigScale)||1,l=1/this._arScale*r,c=new ne().makeScale(l,l,l).invert();o.matrix.premultiply(c),o.matrix.decompose(o.position,o.quaternion,o.scale)}}onRevertSceneChanges(){var e;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const s=this._placementScene.children[t];this.context.scene.add(s)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const t of this._reparentedComponents)P.addComponent(t.originalObject,t.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),B()&&be("Hit does not support creating an anchor");return}else{const s=await t.createAnchor(e.viewerPose.transform);e.running&&s&&(this._anchor=s)}}applyViewBasedTransform(e){const t=this.context.mainCamera,s=e,o=t.worldPosition,r=s.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const l=t.worldPosition;l&&e.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(o.y=r.y,e.lookAt(o))}onApplyPose(e){var t,s,o;const r=(s=(t=oe.active)==null?void 0:t.rig)==null?void 0:s.gameObject;if(!r){console.warn("No rig object to place");return}const l=r.parent||this.context.scene;this._rigPlacementMatrix?(o=this._rigPlacementMatrix)==null||o.decompose(r.position,r.quaternion,r.scale):this._rigPlacementMatrix=r.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(r),e.removeFromParent(),r.scale.set(this.arScale,this.arScale,this.arScale),r.position.multiplyScalar(this.arScale),r.updateMatrix(),this.invertForward&&r.matrix.premultiply(mA),r.matrix.premultiply(this._startOffset),r.matrix.decompose(r.position,r.quaternion,r.scale),l.add(r)}};a(G0,"_eventListeners",{}),a(G0,"_hasPlaced",!1);let Vo=G0;const yp=class Cv{constructor(e){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=Q.isAndroidDevice()&&o.clientY<window.innerHeight*.1;this.prev.has(o.identifier)||this.prev.set(o.identifier,{ignore:r,x:0,z:0,screenx:0,screeny:0});const l=this.prev.get(o.identifier);if(l){const c=this.getPositionOnPlane(o.clientX,o.clientY);l.x=c.x,l.z=c.z,l.screenx=o.clientX,l.screeny=o.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s];this.prev.delete(o.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const s=t.touches[0],o=this.prev.get(s.identifier);if(!o||o.ignore)return;const r=this.getPositionOnPlane(s.clientX,s.clientY),l=r.x-o.x,c=r.z-o.z;if(l===0&&c===0)return;this.oneFingerDrag&&this.addMovement(l,c),o.x=r.x,o.z=r.z,o.screenx=s.clientX,o.screeny=s.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const s=t.touches[0],o=t.touches[1],r=this.prev.get(s.identifier),l=this.prev.get(o.identifier);if(!r||!l)return;if(this.twoFingerRotate){const c=Math.atan2(s.clientY-o.clientY,s.clientX-o.clientX),h=Math.atan2(r.screeny-l.screeny,r.screenx-l.screenx),d=c-h;Math.abs(d)>.001&&this.addRotation(d)}if(this.twoFingerScale){const c=s.clientX-o.clientX,h=s.clientY-o.clientY,d=Math.sqrt(c*c+h*h),u=r.screenx-l.screenx,p=r.screeny-l.screeny,g=Math.sqrt(u*u+p*p),f=d-g;Math.abs(f)>2&&this.addScale(f)}r.screenx=s.clientX,r.screeny=s.clientY,l.screenx=o.clientX,l.screeny=o.clientY}}}),a(this,"_raycaster",new gd),a(this,"_intersection",new S),a(this,"_screenPos",new S),a(this,"_tempMatrix",new ne),this.context=e,this.offset=new ne,this.plane=new fr,this.plane.setFromNormalAndCoplanarPoint(Cv.up,Cv.zero)}get scale(){return this._scale}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)}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:ri.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ri.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:ri.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ri.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(e,t){const s=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(s),this._raycaster.set(s.position,this._screenPos.sub(s.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)}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)}};a(yp,"up",new S(0,1,0)),a(yp,"zero",new S(0,0,0)),a(yp,"one",new S(1,1,1));let gA=yp;const $o=C("debugautosync"),q0=Symbol("syncerId");class fA{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new yA(e);return t[q0]=e.guid,this._syncers[t[q0]]=t,t}removeSyncer(e){delete this._syncers[e[q0]]}}const X0=new fA;class yA{constructor(e){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const s in this.changedProperties)delete this.changedProperties[s];return}for(const s in this.changedProperties){const o=this.changedProperties[s];$o&&console.log("SEND",this.comp.guid,this.networkingKey),t.send(this.networkingKey,{guid:this.comp.guid,property:s,data:o},xs.Queued),delete this.changedProperties[s]}}),a(this,"onHandleReceiving",t=>{if($o&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,t),!!this._isInit&&this.comp&&t.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[t.property]=t.data}catch(s){console.error(s)}finally{this._isReceiving=!1}}),this.comp=e}get networkingKey(){return this.comp.guid}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||($o&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}}function vA(n,e){let t=e!==n;return!t&&n&&e&&(Array.isArray(n)&&Array.isArray(e)||typeof n=="object"&&typeof e=="object")&&(t=!0),t}const sh=Symbol("AutoSyncHandler");function bA(n){if(n[sh])return n[sh];const e=X0.getOrCreateSyncer(n);return e?.init(n),n[sh]=e,e}function _A(n){const e=n[sh];e&&(X0.removeSyncer(e),e.destroy(),delete n[sh])}const Q0=function(n=null){return function(e,t){var s;let o="";typeof t=="string"?o=t:o=t.name;let r=null,l;typeof n=="string"?l=e[n]:typeof n=="function"&&(l=n),l==null&&(B()||$o)&&n!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+n+'"');const c=e,h=c.__internalAwake;if(typeof h!="function"){($o||B())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((s=e?.constructor)==null?void 0:s.name)+'" is not supported',e);return}$o&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=X0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(f){var y;const v=this[d];if(this[d]=f,g){(B()||$o)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=vA(f,v);$o&&console.log("SyncField assignment",o,"changed?",b,f,l),b&&l?.call(this,f,v)!==!1&&((y=bA(this))==null||y.notifyChanged(o,f))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){_A(this),u.call(this)}}};var wA=Object.defineProperty,vp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&wA(e,t,o),o};const ti=C("debugplayersync"),bp=class PC extends j{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ti&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(t=>{ti&&console.log("PlayerSync.destroyInstance",t),yc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(e,t){const s=ce.getOrCreateFromUrl(e);if(!s.asset){const l=await s.loadAssetAsync();l&&P.getOrAddComponent(l,ks)}const o=new PC;o._internalInit(t),o.asset=s;const r=new A;return r.guid=e,P.addComponent(r,o),o}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new xe)}onEnable(){this.context.connection.beginListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.destroyInstance)}async getInstance(){var e,t,s,o,r,l;if(this._localInstance)return this._localInstance;if(ti&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.url),!((t=this.asset)!=null&&t.asset)&&!((s=this.asset)!=null&&s.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=(o=this.asset)==null?void 0:o.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const c=await this._localInstance;if(c){const h=P.getComponentsInChildren(c,ks);if(ti&&console.log(`PlayerSync.createInstance: found ${h?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),h!=null&&h.length){for(const d of h)d.owner=this.context.connection.connectionId;(r=this.onPlayerSpawned)==null||r.invoke(c)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((l=this.asset)==null?void 0:l.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(c)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=ks.all.length-1;t>=0;t--){const s=ks.all[t];(!s.owner||!this.context.connection.userIsInRoom(s.owner))&&s.doDestroy()}})}};vp([m()],bp.prototype,"autoSync"),vp([m(ce)],bp.prototype,"asset"),vp([m(xe)],bp.prototype,"onPlayerSpawned");let Y0=bp;var Q1=(n=>(n.OwnerChanged="ownerChanged",n))(Q1||{}),Ke;const K0=(Ke=class extends j{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new xe),a(this,"onFirstOwnerChangeEvent",new xe),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",n=>{if(n.userId===this.owner){ti&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Ke._all}static get local(){return Ke._local}static getFor(n){if(n instanceof A)return P.getComponentInParent(n,Ke);if(n instanceof j)return P.getComponentInParent(n.gameObject,Ke)}static isLocalPlayer(n){const e=Ke.getFor(n);return e?.isLocalPlayer??!1}static addEventListener(n,e){return this._callbacks[n]||(this._callbacks[n]=[]),this._callbacks[n].push(e),e}static removeEventListener(n,e){if(!this._callbacks[n])return;const t=this._callbacks[n].indexOf(e);t>=0&&this._callbacks[n].splice(t,1)}static dispatchEvent(n,e){if(this._callbacks[n])for(const t of this._callbacks[n])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(n,e){var t,s;ti&&console.log(`PlayerSync.onOwnerChange: ${e} \u2192 ${n} (me: ${this.context.connection.connectionId})`);const o=Ke._local.indexOf(this);o>=0&&Ke._local.splice(o,1);const r={playerState:this,oldValue:e,newValue:n};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(r)),(s=this.onOwnerChangeEvent)==null||s.invoke(r),this.owner===this.context.connection.connectionId){Ke._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Ke.dispatchEvent("ownerChanged",l)}awake(){Ke.all.push(this),ti&&console.log("Registered new PlayerState",this.guid,Ke.all.length-1,Ke.all),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeftRoom)}async start(){ti&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await $s(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ti&&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||(ti&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ti&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ti&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ti&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ti&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),yc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ti&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeftRoom),Ke.all.splice(Ke.all.indexOf(this),1),this.isLocalPlayer){const n=Ke._local.indexOf(this);n>=0&&Ke._local.splice(n,1)}}},a(Ke,"_all",[]),a(Ke,"_local",[]),a(Ke,"_callbacks",{}),Ke);vp([Q0(K0.prototype.onOwnerChange)],K0.prototype,"owner");let ks=K0;var xA=Object.defineProperty,vl=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&xA(e,t,o),o};class un extends j{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!1),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"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&&(Q.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}vl([m()],un.prototype,"position"),vl([m()],un.prototype,"showNeedleLogo"),vl([m()],un.prototype,"showSpatialMenu"),vl([m()],un.prototype,"createFullscreenButton"),vl([m()],un.prototype,"createMuteButton"),vl([m()],un.prototype,"createQRCodeButton");var SA=Object.defineProperty,Z0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SA(e,t,o),o};const nh=C("debugwebxr"),Y1=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class Ho extends j{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;nh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=ks.getFor(this);if(t!=null&&t.owner){const s=this.gameObject.addComponent(di);s.avatar=this.gameObject,s.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(di);t&&t.destroy()}onUpdateXR(e){var t,s;if(!this.activeAndEnabled)return;const o=ks.isLocalPlayer(this);if(!o)return;const r=e.xr;if(r.rig&&r.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),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&o)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=P.getComponentsInChildren(this.head.asset,os);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=e.xr.leftController,c=(t=this.leftHand)==null?void 0:t.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(Y1),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=e.xr.rightController,d=(s=this.rightHand)==null?void 0:s.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(Y1),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,s){if(s){const o=e.model&&e.model.visible&&e.model!==t;s.forEach(r=>{Fn(r,!o)})}}updateRemoteAvatarVisibility(){var e,t,s;if(this.context.connection.isConnected){const o=ks.getFor(this);if(o&&o.isLocalPlayer==!1){const r=oe.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(e=this.leftHand)==null?void 0:e.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(t=this.rightHand)==null?void 0:t.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((s=this.head)!=null&&s.asset){const l=P.getComponentsInChildren(this.head.asset,os);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};M_.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(){var e,t;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof A&&(this.head=new ce("",this.sourceId,this.head));else{const s=new A;s.name="Head";const o=xo.createPrimitive(Sr.Cube);s.add(o),this.gameObject.add(s),this.head=new ce("",this.sourceId,s),nh&&console.log("Create head",s)}if(this.rightHand)this.rightHand instanceof A&&(this.rightHand=new ce("",this.sourceId,this.rightHand));else{const s=new A;s.name="Right Hand",this.gameObject.add(s),this.rightHand=new ce("",this.sourceId,s),nh&&console.log("Create right hand",s)}if(this.leftHand)this.leftHand instanceof A&&(this.leftHand=new ce("",this.sourceId,this.leftHand));else{const s=new A;s.name="Left Hand",this.gameObject.add(s),this.leftHand=new ce("",this.sourceId,s),nh&&console.log("Create left hand",s)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(e=this.leftHand.asset)==null||e.traverse(s=>{s!=null&&s.isMesh&&this._leftHandMeshes.push(s)}),this._rightHandMeshes=[],(t=this.rightHand.asset)==null||t.traverse(s=>{s!=null&&s.isMesh&&this._rightHandMeshes.push(s)}),ks.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,sn))}async loadAvatarObjects(e,t,s){const o=e.loadAssetAsync(),r=t.loadAssetAsync(),l=s.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await eg(c);nh&&console.log("Avatar loaded results:",h)}}Z0([m(ce)],Ho.prototype,"head"),Z0([m(ce)],Ho.prototype,"leftHand"),Z0([m(ce)],Ho.prototype,"rightHand");var CA=Object.defineProperty,_p=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&CA(e,t,o),o};const Kn=C("debugwebxr"),Go=new Array;class pn extends j{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}async onXRControllerAdded(e){var t;if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:s}=e;if(Kn&&console.warn("Add Controller Model for",s.side,s.index),this.createControllerModel||this.createHandModel){if(s.hand){if(this.createHandModel){const o=await this.loadHandModel(this,s);if(!o||!s.connected||!s.isHand){o!=null&&o.handObject&&$a(o.handObject,!1),(t=o?.handObject)==null||t.destroy();return}this._models.push({controller:s,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),s.model=o.handObject}}else if(this.createControllerModel){const o=await s.getModelUrl();if(o){const r=await this.loadModel(s,o);if(!r||!s.connected||s.isHand)return;this._models.push({controller:s,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),s.model=r}else s.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+s.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(o=>o.controller===e.controller),s=this._models[t];s&&(this._models.splice(t,1),s.model&&($a(s.model,!1),s.model.destroy(),s.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&&($a(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(oe.active&&(Kn&&(Go[0]=Date.now()),this.updateRendering(oe.active),Kn)){const e=Date.now()-Go[0];Go.push(e),Go.length>=30&&(Go[0]=0,Go.reduce((t,s)=>t+s,0)/Go.length,Go.length=0)}}updateRendering(e){var t,s,o,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Kn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(t=e.rig)==null||t.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=e.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&e.frame.getJointPose){for(const g of d.inputSource.hand.values()){const f=p.joints[g.jointName];if(f){const y=d.getHandJointPose(g);if(y){const v=y.transform.position,b=y.transform.orientation;f.position.copy(v),f.quaternion.copy(b),f.matrixAutoUpdate=!1}f.visible=y!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((s=e.rig)==null?void 0:s.gameObject)&&((o=e.rig)==null||o.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(La))}}}}async loadModel(e,t){var s;if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const o=await ce.getOrCreate("",t).instantiate();return $a(o),(s=oe.active)!=null&&s.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(e,t){const s=this.context,o=s.renderer.xr.getHand(t.index);o||(Kn?G.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const r=new Rn;Bf(r,s),await Zu(r,s,this.sourceId??"");const l=b0(r);let c="";const h=t.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=t.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new A;$a(d);const u=new rO(d,o,r.path,c,r,p=>{var g;const f=l?.gltf;((g=f?.scene.children)==null?void 0:g.length)===0&&(f.scene.children[0]=p),l!=null&&l.gltf&&ws().createBuiltinComponents(e.context,e.sourceId||c,l.gltf,null,l),p.traverse(y=>{var v;y.layers.set(2),(v=oe.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(y),y instanceof q&&Xe.assignMeshLOD(y,0)}),t.connected||(Kn&&G.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Kn&&d.add(new Pi(.5)),t.inputSource.hand){Kn&&console.log(t.inputSource.hand);for(const p of t.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new go;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else Kn&&G.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(e){if(e instanceof q){let t=e.material;t instanceof Pe&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}a(pn,"factory",new oO),_p([m()],pn.prototype,"createControllerModel"),_p([m()],pn.prototype,"createHandModel"),_p([m(ce)],pn.prototype,"customLeftHand"),_p([m(ce)],pn.prototype,"customRightHand");class wp extends j{}var PA=Object.defineProperty,qo=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&PA(e,t,o),o};const J0=C("debugwebxr");class Ni extends j{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const s=e.xr.leftController,o=e.xr.rightController;s&&this.onHandleMovement(s,t.gameObject),o&&(this.onHandleRotation(o,t.gameObject),this.useTeleport&&this.onHandleTeleport(o,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const s=e.getStick("xr-standard-thumbstick");if(s.x!=0||s.y!=0){const o=X(s.x,0,s.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ge(t);o.multiplyScalar(r.x),o.applyQuaternion(e.xr.poseOrientation),o.y=0,o.applyQuaternion(t.worldQuaternion),t.position.add(o),t.updateWorldMatrix(!1,!1);for(const l of t.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const s=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(s)<.3&&(this._didApplyRotation=!1);else if(Math.abs(s)>.5){this._didApplyRotation=!0;const o=s>0?1:-1,r=ee(this.context.mainCamera).clone();t.rotateY(o*W.toRadians(this.rotationStep));const l=ee(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}onHandleTeleport(e,t){var s,o,r,l,c;let h=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const d=e.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=e.getGesture("pinch");u&&(h=u.value)}else h=(s=e.getStick("xr-standard-thumbstick"))==null?void 0:s.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(e.ray)[0];if(d&&d.object instanceof ka){const p=(o=d.normal)==null?void 0:o.dot(X(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new fr(new S(0,1,0),0));const p=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new S(0,1,0),p);const g=e.ray;u=p.clone(),this._plane.intersectLine(new MP(g.origin,X(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>t.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,wp))return;const p=u.clone();if(J0&&G.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),J0&&G.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=e.xr.fadeTransition())==null||c.then(()=>{t.worldPosition=p}):t.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(t.position,t.quaternion,t.scale)}}renderRays(e){var t;for(let s=0;s<this._lines.length;s++){const o=this._lines[s];o&&(o.visible=!1)}for(let s=0;s<e.controllers.length;s++){const o=e.controllers[s];let r=this._lines[s];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[s]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=e.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[s],p=this._hitDistances[s]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let f=r.material.opacity;d?f=1:this.showHits&&g<e.rigScale*.5?f=0:(t=o.getButton("primary"))!=null&&t.pressed?f=.5:f=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(e){var t;for(const s of this._hitDiscs){if(!s)continue;const o=s.controller;if(!o||!o.connected||!o.isTracking){s.visible=!1;continue}}for(let s=0;s<e.controllers.length;s++){const o=e.controllers[s];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[s],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[s]=null,this._lastHitDistances[s]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[s];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[s]=u?.distance||null,u){this._lastHitDistances[s]=u.distance;const p=e.rigScale??1;J0&&(G.DrawWireSphere(u.point,.025*p,16711680),G.DrawLabel(X(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[s]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const f=(t=o.getButton("primary"))==null?void 0:t.pressed;f&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let y=r.material.opacity;if(f?y=1:y=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Se(u.object));r.quaternion.setFromUnitVectors(OA,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[s]&&(this._hitDiscs[s].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Ru(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,s){const o=X(e.rayWorldPosition);o.add(X(0,0,s-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const e=new q(new md(.3,6,6),new Me({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 aO;e.layers.disableAll(),e.layers.enable(2);const t=new lO;e.geometry=t;const s=new Float32Array(9);s.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(s);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(o);const r=new cO({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Nv,dashed:!1});return e.material=r,e}}qo([m()],Ni.prototype,"movementSpeed"),qo([m()],Ni.prototype,"rotationStep"),qo([m()],Ni.prototype,"useTeleport"),qo([m()],Ni.prototype,"usePinchToTeleport"),qo([m()],Ni.prototype,"useTeleportTarget"),qo([m()],Ni.prototype,"useTeleportFade"),qo([m()],Ni.prototype,"showRays"),qo([m()],Ni.prototype,"showHits");const OA=new S(0,1,0);var kA=Object.defineProperty,Ct=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kA(e,t,o),o};const oh=C("debugwebxr"),MA=C("debugusdz");var Xo;const pt=(Xo=class extends j{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"_activeWebARSessionRoot",null),a(this,"onAvatarSpawned",n=>{oh&&console.log("WebXR.onAvatarSpawned",n),P.getComponentInChildren(n,Ho)??(i=P.addComponent(n,Ho))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){oe.getXRSync(this.context)}onEnable(){var n,e;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).'),this.useQuicklookExport&&(P.findObjectOfType(gn)||(oh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,gn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(oh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ce("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Y0),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(n=this._playerSync.onPlayerSpawned)==null||n.removeEventListener(this.onAvatarSpawned),(e=this._playerSync.onPlayerSpawned)==null||e.addEventListener(this.onAvatarSpawned))}onDisable(){var n;(n=this._usdzExporter)==null||n.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await oe.isVRSupported()&&this.createVRButton?oe.offerSession("immersive-vr","default",this.context):this.createARButton&&await oe.isARSupported()&&this.createARButton?oe.offerSession("immersive-ar","default",this.context):!1}get session(){return oe.active??null}get sessionMode(){return oe.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(n){return oe.start("immersive-vr",n,this.context)}async enterAR(n){return oe.start("immersive-ar",n,this.context)}exitXR(){oe.stop()}get isActiveWebXR(){return!Xo.activeWebXRComponent||Xo.activeWebXRComponent===this}onBeforeXR(n,e){var t;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(t=Xo.activeWebXRComponent)==null?void 0:t.name}). This is ignored: ${this.name}`);return}Xo.activeWebXRComponent=this,n=="immersive-ar"&&this.useDepthSensing&&(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.push("depth-sensing"))}async onEnterXR(n){if(!this.isActiveWebXR)return;oh&&console.log("WebXR onEnterXR"),this._previousXRState=Di.Global.Mask;const e=n.xr.isVR;if(Di.Global.Set(e?rn.VR:rn.AR),n.xr.isAR){let t=P.findObjectOfType(Vo);if(!t)if(this.usePlacementReticle){const s=new A;for(const o of this.context.scene.children)s.add(o);this.context.scene.add(s),t=P.addComponent(s,Vo),this._createdComponentsInSession.push(t)}else(oh||B())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=t,t&&(t.customReticle=this.customARPlacementReticle,t.arScale=this.arScale,t.arTouchTransform=this.usePlacementAdjustment,t.autoPlace=this.autoPlace,t.autoCenter=this.autoCenter,t.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Bc)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Bc))),this.createLocalAvatar(n.xr),n.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(n){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(n){var e,t;if((e=this._exitXRMenuButton)==null||e.remove(),!!this.isActiveWebXR){Di.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const s of this._createdComponentsInSession)s.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Ql(1).then(()=>Xo.activeWebXRComponent=null)}}setDefaultMovementEnabled(n){let e=this.gameObject.getComponent(Ni);return!e&&n&&(e=this.gameObject.addComponent(Ni),this._createdComponentsInSession.push(e)),e&&(e.enabled=n),e}setDefaultControllerRenderingEnabled(n){let e=this.gameObject.getComponent(pn);return!e&&n&&(e=this.gameObject.addComponent(pn),this._createdComponentsInSession.push(e),e.createControllerModel=this.showControllerModels,e.createHandModel==this.showHandModels),e&&(e.enabled=n),e}async createLocalAvatar(n){this._playerSync&&n.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=gl.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((Q.isiOS()&&Q.isSafari()||MA)&&this.useQuicklookExport){const n=P.findObjectOfType(gn);if(!n||n&&n.allowCreateQuicklookButton){const e=this.getButtonsFactory().createQuicklookButton();this.addButton(e,50)}}if(this.createARButton){const n=this.getButtonsFactory().createARButton();this.addButton(n,50)}if(this.createVRButton){const n=this.getButtonsFactory().createVRButton();this.addButton(n,50)}}if(this.createSendToQuestButton&&!Q.isQuest()&&oe.isVRSupported().then(n=>{if(!n){const e=this.getButtonsFactory().createSendToQuestButton();this.addButton(e,50)}}),this.createQRCode){const n=Sc(un);if(n&&n.createQRCodeButton===!1)B()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!Q.isMobileDevice()){const e=Po.getOrCreate().createQRCode();this.addButton(e,50)}}}addButton(n,e){this._buttons.push(n),n.setAttribute("priority",e.toString()),this.context.menu.appendChild(n)}removeButtons(){for(const n of this._buttons)n.remove();this._buttons.length=0}},a(Xo,"activeWebXRComponent",null),Xo);Ct([m()],pt.prototype,"createVRButton"),Ct([m()],pt.prototype,"createARButton"),Ct([m()],pt.prototype,"createSendToQuestButton"),Ct([m()],pt.prototype,"createQRCode"),Ct([m()],pt.prototype,"useDefaultControls"),Ct([m()],pt.prototype,"showControllerModels"),Ct([m()],pt.prototype,"showHandModels"),Ct([m()],pt.prototype,"usePlacementReticle"),Ct([m(ce)],pt.prototype,"customARPlacementReticle"),Ct([m()],pt.prototype,"usePlacementAdjustment"),Ct([m()],pt.prototype,"arScale"),Ct([m()],pt.prototype,"useXRAnchor"),Ct([m()],pt.prototype,"autoPlace"),Ct([m()],pt.prototype,"autoCenter"),Ct([m()],pt.prototype,"useQuicklookExport"),Ct([m()],pt.prototype,"useDepthSensing"),Ct([m()],pt.prototype,"useSpatialGrab"),Ct([m(ce)],pt.prototype,"defaultAvatar");let xp=pt;const Sp=C("debugusdzbehaviours");class ey{constructor(){a(this,"behaviours",[]),a(this,"behaviourComponents",[]),a(this,"behaviourComponentsCopy",[]),a(this,"audioClips",[]),a(this,"audioClipsCopy",[]),a(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+_a.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(s=>{P.foreachComponent(s,o=>{var r;const l=o;if(typeof l.createBehaviours=="function"||typeof l.beforeCreateDocument=="function"||typeof l.afterCreateDocument=="function"||typeof l.afterSerialize=="function"){this.behaviourComponents.push(l);const c=(r=l.beforeCreateDocument)==null?void 0:r.call(l,this,e);c instanceof Promise&&t.push(c)}},!1)}),Sp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,s){var o;for(const r of this.behaviourComponents)(o=r.createBehaviours)==null||o.call(r,this,t,s)}onAfterBuildDocument(e){for(const p of this.behaviourComponents)typeof p.afterCreateDocument=="function"&&p.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,s=new Set,o=new Set,r=new Set,l=Sp;let c=`graph LR
|
|
1252
|
+
`))}for(const Y of F){const te=l.get(Y);te&&I.set(Y,te)}return I},y=function(F){const I=f(F),Y=d(I);return u(I,Y,F)};const v=r.skinnedMesh.skeleton,b=new Array,_=[],w=[];for(const F of v.bones){_.push(F),w.push(F.uuid);const I=v.boneInverses[v.bones.indexOf(F)];b.push({bone:F,inverse:I})}let x=1e4;for(;w.length<v.bones.length&&x-- >0;)for(const F of _){const I=F.children;for(const Y of I)if(w.indexOf(Y.uuid)===-1&&v.bones.indexOf(Y)!==-1){_.push(Y),w.push(Y.uuid);const te=v.boneInverses[v.bones.indexOf(Y)];b.push({bone:Y,inverse:te})}}x<=0&&console.error("Failed to sort bones in skinned mesh",r.skinnedMesh,v.bones,w);for(const F of x1(v.bones))b.push({bone:F,inverse:F.matrixWorld.clone().invert()});const k=b[0].bone.parent;k||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),b.sort((F,I)=>hl(F.bone,k)>hl(I.bone,k)?1:-1);const M=t.quickLookCompatible,T=[],D=[],z=[],U=[];for(const{bone:F}of b){if(M){const I=F.scale;I.x==0&&(I.x=1e-5),I.y==0&&(I.y=1e-5),I.z==0&&(I.z=1e-5),T.push(new ne().compose(F.position,F.quaternion,F.scale))}else T.push(F.matrix.clone());D.push(F.position),z.push(F.quaternion),U.push(F.scale)}const E=b.map(F=>'"'+hl(F.bone,k)+'"').join(", "),$=b.map(F=>L1(F.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${$}]`),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${T.map(F=>L1(F)).join(", ")}]`);const H=y(b.map(F=>F.bone));if(dn){let F=1e7,I=0;for(const Y of((o=H.position)==null?void 0:o.keys())??[])F=Math.min(F,Y),I=Math.max(I,Y);console.log("Time samples",F,I,H)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine(`quatf[] rotations = [${g(z)}]`),H&&H.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const F=h(H.quaternion);for(const I of F)e.appendLine(I);e.closeBlock()}if(e.appendLine(`half3[] scales = [${p(U)}]`),H&&H.scale){e.beginBlock("half3[] scales.timeSamples = {","");const F=c(H.scale);for(const I of F)e.appendLine(I);e.closeBlock()}if(e.appendLine(`float3[] translations = [${p(D)}]`),H&&H.position){e.beginBlock("float3[] translations.timeSamples = {","");const F=c(H.position);for(const I of F)e.appendLine(I);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const s=this.animationData.get(this.object);if(s)for(let u=0;u<s.length;u++)s[u]===void 0&&(s[u]=new ut(null,this.object,null));const o=this.ext;this.skinnedMeshExport(e,t,o);const r=this.object,l=this.model,c=this.animationData.get(r);if(!c||r.isSkinnedMesh)return;F0&&console.log("SERIALIZE",this.model.name,this.object.type,c);const h=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function d(u,p){var g;if(u.some(f=>f&&{position:f.pos,rotation:f.rot,scale:f.scale}[p])){switch(p){case"position":l.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":l.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":l.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let f=0;f<u.length;f++){const y=u[f];if(!y)continue;const v=o.getStartTimeByClip(y.clip),b=y.getSortedTimesArray(p==="position",p==="rotation",p==="scale");if(!b||b.length===0){console.error("got an animated object but no time values?",r,y);continue}const _=!y.clip,w=p==="position"&&(y.pos||_),x=p==="rotation"&&(y.rot||_),k=p==="scale"&&(y.scale||_);if(w||x||k){const M=((g=y.clip)==null?void 0:g.name)??"rest",T=y.getDuration();dn&&console.log("Write .timeSamples:",M,v,T,u),e.appendLine("# "+M+": start="+h.format(v*ut.frameRate)+", length="+h.format(T*ut.frameRate)+", frames="+y.getFrames())}if(w)for(const{time:M,translation:T}of y.getValues(b,!0,!1,!1)){const D=`${h.format((v+M)*ut.frameRate)}: (${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(D)}if(x)for(const{time:M,rotation:T}of y.getValues(b,!1,!0,!1)){const D=`${h.format((v+M)*ut.frameRate)}: (${ue(T.w)}, ${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(D)}if(k)for(const{time:M,scale:T}of y.getValues(b,!1,!1,!0)){const D=`${h.format((v+M)*ut.frameRate)}: (${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(D)}}e.closeBlock()}}d(c,"position"),d(c,"rotation"),d(c,"scale")}}const lA=C("debugusdz");class _a{constructor(){a(this,"files",new Array)}static getName(e){var t;const s=e.split(".").pop();let o=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return o||(o="Audio_"+Math.random().toString(36).substring(2,15)),as(o)+"."+s}get extensionName(){return"Audio"}onExportObject(e,t,s){const o=P.getComponents(e,ns);if(o.length)for(const r of o){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const l=r.clip.split("/").pop()||"Audio",c=_a.getName(r.clip),h=as(c);if(!this.files.some(d=>d.path===r.clip)){this.files.push({path:r.clip,name:c});const d=c.toLowerCase();s.quickLookCompatible&&!d.endsWith(".mp3")&&!d.endsWith(".wav")&&!d.endsWith(".m4a")&&console.error("Audio file "+r.clip+" from "+r.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}s.quickLookCompatible||t.addEventListener("serialize",(d,u)=>{d.appendLine(),d.beginBlock(`def SpatialAudio "${h}"`,"(",!1),d.appendLine(`displayName = "${l}"`),d.closeBlock(")"),d.beginBlock(),d.appendLine(`uniform asset filePath = @audio/${c}@`),d.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),d.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),d.appendLine(`uniform float gain = ${r.volume}`),d.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const s="audio/"+t.name;if(e.files[s]){lA&&console.warn("Audio file with name "+s+" already exists in the context. Skipping.");continue}const o=await(await(await fetch(t.path)).blob()).arrayBuffer(),r=new Uint8Array(o);e.files[s]=r}}}var cA=Object.defineProperty,Ne=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&cA(e,t,o),o};const $1=C("debugusdzbehaviours");function Zc(n){n&&(n.getComponentInParent(Ka)||(B()&&console.debug('Raycaster on "'+n.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),n.addComponent(ji)))}class Xr extends j{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new S),a(this,"targetRot",new V),a(this,"targetScale",new S)}start(){Zc(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=ee(this.object).clone(),t=ee(this.target).clone(),s=Se(this.object).clone(),o=Se(this.target).clone(),r=Ge(this.object).clone(),l=Ge(this.target).clone(),c=e.distanceTo(t),h=s.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){lt(this.object,t),Yi(this.object,o),Ta(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,p),this.targetRot.slerpQuaternions(s,o,p),this.targetScale.lerpVectors(r,l,p),lt(this.object,this.targetPos),Yi(this.object,this.targetRot),Ta(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(),s=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,h),this.object.quaternion.slerpQuaternions(t,this.targetRot,h),this.object.scale.lerpVectors(s,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const s=new ei("Move to "+((t=this.target)==null?void 0:t.name),At.tapTrigger(this.gameObject),ve.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(s)}}}Ne([m(A)],Xr.prototype,"object"),Ne([m(A)],Xr.prototype,"target"),Ne([m()],Xr.prototype,"duration"),Ne([m()],Xr.prototype,"relativeMotion");var tt;const pp=(tt=class extends j{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var n;this._objectsWithThisMaterial=this.objectsWithThisMaterial,Zc(this.gameObject),B()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((n=this.materialToSwitch)==null?void 0:n.name)+'"')}onPointerEnter(n){this.context.input.setCursor("pointer")}onPointerExit(n){this.context.input.unsetCursor("pointer")}onPointerClick(n){if(n.use(),!!this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){const t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(n=>{if(n instanceof q)if(Array.isArray(n.material)){for(const e of n.material)if(e===this.materialToSwitch){this.objectsWithThisMaterial.push(n);break}}else n.material===this.materialToSwitch?this.objectsWithThisMaterial.push(n):nw(n.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(n)}),this._objectsWithThisMaterial)}async beforeCreateDocument(n,e){this.targetModels=[],tt._materialTriggersPerId={},tt.variantSwitchIndex=0,this.materialToSwitch&&await Xe.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Xe.assignTextureLOD(this.variantMaterial,0)}createBehaviours(n,e,t){this.objectsWithThisMaterial.find(s=>s.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(tt._materialTriggersPerId[this.materialToSwitch.uuid]||(tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(n,e){if(!this.materialToSwitch)return;const t=tt._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const o of t){const r=o.createVariants();r&&r.length>0&&(s[o.selfModel.uuid]=r)}for(const o of t){const r=[];for(const l in s)l!==o.selfModel.uuid&&r.push(...s[l]);o.createAndAttachBehaviors(n,s[o.selfModel.uuid],r)}}delete tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(n,e,t){const s=[],o=Math.max(0,this.fadeDuration);s.push(ve.fadeAction([...this.targetModels,...t],o,!1)),s.push(ve.fadeAction(e,o,!0)),n.addBehavior(new ei("Select_"+this.selfModel.name,At.tapTrigger(this.selfModel),ve.parallel(...s))),tt._parallelStartHiddenActions.push(...e),tt._startHiddenBehaviour||(tt._startHiddenBehaviour=new ei("StartHidden_"+this.selfModel.name,At.sceneStartTrigger(),ve.fadeAction(tt._parallelStartHiddenActions,o,!1)),n.addBehavior(tt._startHiddenBehaviour))}static getMaterialName(n){return as(n.name||"Material")+"_"+n.id}createVariants(){if(!this.variantMaterial)return null;const n=[];for(const e of this.targetModels){const t=e.clone();t.name+="_Variant_"+tt.variantSwitchIndex+++"_"+tt.getMaterialName(this.variantMaterial),t.displayName=t.displayName+": Variant with material "+this.variantMaterial.name,t.material=this.variantMaterial,t.geometry=e.geometry,t.transform=e.transform,(!e.parent||!e.parent.isEmpty())&&gi.createEmptyParent(e),e.parent&&e.parent.add(t),n.push(t)}return n}},a(tt,"_materialTriggersPerId",{}),a(tt,"_startHiddenBehaviour",null),a(tt,"_parallelStartHiddenActions",[]),a(tt,"variantSwitchIndex",0),tt);Ne([m(Pe)],pp.prototype,"materialToSwitch"),Ne([m(Pe)],pp.prototype,"variantMaterial"),Ne([m()],pp.prototype,"fadeDuration");let U0=pp;var ke;const Jc=(ke=class extends j{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){Zc(this.gameObject)}onPointerClick(n){n.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ke.wasVisible]===void 0&&(this.gameObject[ke.wasVisible]=this.gameObject.activeSelf),this.target[ke.wasVisible]===void 0&&(this.target[ke.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ke.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ke.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(n,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&M0.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ke.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+ke.clonedToggleIndex++,t.add(c),this.gameObject[ke.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[ke.toggleClone];if(!this.gameObject[ke.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+ke.clonedToggleIndex++,t.add(c),this.gameObject[ke.reverseToggleClone]=c}this.toggleModel=this.gameObject[ke.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),s=l,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ve.fadeAction(s,0,!1)),l.push(ve.fadeAction(this.toggleModel,0,!0)),l.push(ve.fadeAction(this.targetModel,0,o)),n.addBehavior(new ei("Toggle_"+s.name+"_ToggleTo"+(o?"On":"Off"),At.tapTrigger(s),ve.parallel(...l)));const c=[];c.push(ve.fadeAction(this.toggleModel,0,!1)),c.push(ve.fadeAction(s,0,!0)),c.push(ve.fadeAction(this.targetModel,0,!o)),n.addBehavior(new ei("Toggle_"+s.name+"_ToggleTo"+(o?"Off":"On"),At.tapTrigger(this.toggleModel),ve.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ve.fadeAction(s,0,!1)),l.push(ve.fadeAction(this.targetModel,0,o)),n.addBehavior(new ei("Toggle_"+s.name+"_ToggleTo"+(o?"On":"Off"),At.tapTrigger(s),l.length>1?ve.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(t),this.toggleModel&&r.push(this.toggleModel),mp.add(r,n)}}afterSerialize(n,e){this.gameObject[ke.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ke.wasVisible],delete this.gameObject[ke.wasVisible]),this.target&&this.target[ke.wasVisible]!==void 0&&(this.target.visible=this.target[ke.wasVisible],delete this.target[ke.wasVisible]),delete this.gameObject[ke.toggleClone],delete this.gameObject[ke.reverseToggleClone]}},a(ke,"clonedToggleIndex",0),a(ke,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(ke,"toggleClone",Symbol("clone for toggling")),a(ke,"reverseToggleClone",Symbol("clone for reverse toggling")),ke);Ne([m(A)],Jc.prototype,"target"),Ne([m()],Jc.prototype,"toggleOnClick"),Ne([m()],Jc.prototype,"targetState"),Ne([m()],Jc.prototype,"hideSelf");let z0=Jc;const N0=class ur extends j{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(e,t){const s=Array.isArray(e)?e:[e];for(const o of s)ur._fadeObjects.includes(o)||(console.log("adding hide on start",o),ur._fadeObjects.push(o));ur._fadeBehaviour===void 0&&(ur._fadeBehaviour=new ei("HideOnStart",At.sceneStartTrigger(),ve.fadeAction(ur._fadeObjects,0,!1)),t.addBehavior(ur._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&(this.wasVisible||ur.add(t,e))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}};a(N0,"_fadeBehaviour"),a(N0,"_fadeObjects",[]);let mp=N0;class pl extends j{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const o=new ei("emphasize "+this.name,At.tapTrigger(this.gameObject),ve.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(o)}}afterCreateDocument(e,t){}}Ne([m()],pl.prototype,"target"),Ne([m()],pl.prototype,"duration"),Ne([m()],pl.prototype,"motionType");class Wo extends j{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){Zc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(ns);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.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,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;_a.getName(o);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof q&&g.visible&&(h=!0)}),h=!0;const d=e.addAudioClip(o);let u=ve.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ve.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new ei("playAudio"+p,At.tapTrigger(t),u);e.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&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 g=new ei("playAudioOnStart"+p,At.sceneStartTrigger(),u);e.addBehavior(g)}}}}Ne([m(ns)],Wo.prototype,"target"),Ne([m(URL)],Wo.prototype,"clip"),Ne([m()],Wo.prototype,"toggleOnClick");var zi;const W0=(zi=class extends j{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var n,e;return((n=this.animator)==null?void 0:n.gameObject)||((e=this.animation)==null?void 0:e.gameObject)}start(){Zc(this.gameObject)}onPointerClick(n){var e;n.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(n,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(zi.rootsWithExclusivePlayback.size>1){const n='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.';B()&&be(n),console.warn(n,...zi.rootsWithExclusivePlayback)}zi.animationActions=[],zi.rootsWithExclusivePlayback=new Set}afterCreateDocument(n,e){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const t=e.document,s=e.extensions.find(l=>l instanceof up);if(!s)return;const o=s.getClipCount(this.target)>1;o&&(B()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),zi.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";t.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=zi.getActionForSequences(t,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new ei(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?At.tapTrigger(this.selfModel):At.sceneStartTrigger(),d);o&&u.makeExclusive(!0),n.addBehavior(u)}})}static getActionForSequences(n,e,t,s,o){const r=(c,h)=>{let d=zi.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ve.startAnimationAction(c,h),zi.animationActions.push(d)),d},l=ve.sequence();if(t&&t.length>0)for(const c of t)l.addAction(r(e,c));if(s&&s.length>0){const c=l.actions.length==0?l:ve.sequence();for(const h of s)c.addAction(r(e,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(ve.waitAction(o)),l}static getAndRegisterAnimationSequences(n,e,t){var s,o,r,l,c,h,d,u;if(!e)return;const p=e.getComponent(Rt),g=e.getComponent(Ft);if(!p&&!g)return;if(p&&!t)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+e.name);let f=[],y=[];if(g){const M=n.registerAnimation(e,g.clip);M&&(g.loop?y.push(M):f.push(M));let T=0;if(g.minMaxOffsetNormalized){const D=g.minMaxOffsetNormalized.x,z=g.minMaxOffsetNormalized.y;T=(((s=g.clip)==null?void 0:s.duration)||1)*(D+Math.random()*(z-D))}return{animationSequence:f,animationLoopAfterSequence:y,randomTimeOffset:T}}const v=p?.runtimeAnimatorController;let b=v?.findState(t),_=[],w=[];if(v&&b){const M=new Array;M.push(b);let T=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(T=!0);break}const D=b.transitions.find(U=>U.conditions.length===0),z=D?v.getState(D.destinationState,0):null;if(z&&M.includes(z)){b=z,T=!0;break}else if(D){if(b=z,!b)break;M.push(b)}else{T=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&b){const D=M.indexOf(b);_=M.slice(0,D),w=M.slice(D),$1&&console.log("found loop from "+t,"states until loop",_,"states looping",w)}else _=M,w=[],$1&&console.log("found no loop from "+t,"states",_);if(!w.length){const D=_[_.length-1],z=(l=D.motion)==null?void 0:l.clip;if(z){let U;if(n.holdClipMap.has(z))U=n.holdClipMap.get(z);else{const E=D.name+"_hold";U=z.clone(),U.duration=1,U.name=E;const $=z.duration;U.tracks=z.tracks.map(H=>{const F=H.clone();F.times=new Float32Array([0,$]);const I=H.values.length,Y=H.getValueSize(),te=H.values.slice(I-Y,I);return F.values=new Float32Array(2*Y),F.values.set(te,0),F.values.set(te,Y),F}),U.name=E,n.holdClipMap.set(z,U)}if(U){const E={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:D.hash+1};w.push(E)}}}}if(_.length===1&&(!((c=_[0].motion)!=null&&c.clip)||((d=(h=_[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){f=new Array;const M=n.registerAnimation(e,null);M&&f.push(M);return}if(_=_.filter(M=>{var T,D,z;return((T=M.motion)==null?void 0:T.clip)&&((z=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:z.length)>0}),w=w.filter(M=>{var T,D,z;return((T=M.motion)==null?void 0:T.clip)&&((z=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:z.length)>0}),_.length===0&&w.length===0){console.warn("No clips found for state "+t+" on "+p?.name+", can't export animation data");return}const x=(M,T)=>{if(!e)return;const D=n.registerAnimation(e,M.motion.clip??null);D?(D.speed=M.speed,T.push(D)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(_.length>0){f=new Array;for(const M of _)x(M,f)}if(w.length>0){y=new Array;for(const M of w)x(M,y)}let k=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,D=_.length?_[0]:w.length?w[0]:null;k=(((u=D?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:f,animationLoopAfterSequence:y,randomTimeOffset:k}}createAnimation(n,e,t){if(!this.target||!this.animator&&!this.animation)return;const s=zi.getAndRegisterAnimationSequences(n,this.target,this.stateName);s&&(this.animationSequence=s.animationSequence,this.animationLoopAfterSequence=s.animationLoopAfterSequence,this.randomOffsetNormalized=s.randomTimeOffset,this.stateAnimationModel=e)}},a(zi,"animationActions",[]),a(zi,"rootsWithExclusivePlayback",new Set),zi);Ne([m(Rt)],W0.prototype,"animator"),Ne([m()],W0.prototype,"stateName");let eh=W0;class ml extends j{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}Ne([m(A)],ml.prototype,"target");class th extends j{constructor(){super(...arguments),a(this,"target")}}Ne([m(ml)],th.prototype,"target");class ih extends ml{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ne([m()],ih.prototype,"type"),Ne([m()],ih.prototype,"duration");class V0 extends th{}const H1=class CC{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new CC}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return Po.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=Q.supportsQuickLookAR();e.innerText="View in AR",e.prepend(Mt("view_in_ar"));let s=!1,o=null;return e.addEventListener("click",()=>{o=Sc(gn),o||(s=!0,o=new gn),s&&(o.objectToExport=J.Current.scene),o?(e.classList.add("this-mode-is-requested"),o.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){var t;if(this._arButton)return this._arButton;const s="immersive-ar",o=document.createElement("button");return this._arButton=o,o.classList.add("webxr-button"),o.dataset.needle="webxr-ar-button",o.innerText="Enter AR",o.prepend(Mt("view_in_ar")),o.title="Click to start an AR session",o.addEventListener("click",()=>oe.start(s,e)),this.updateSessionSupported(o,s),this.listenToXRSessionState(o,s),this.hideElementDuringXRSession(o),this.isSecureConnection||(o.disabled=!0,o.title="WebXR requires a secure connection (HTTPS)"),Q.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(o,s)),o}createVRButton(e){var t;if(this._vrButton)return this._vrButton;const s="immersive-vr",o=document.createElement("button");return this._vrButton=o,o.classList.add("webxr-button"),o.dataset.needle="webxr-vr-button",o.innerText="Enter VR",o.prepend(Mt("panorama_photosphere")),o.title="Click to start a VR session",o.addEventListener("click",()=>oe.start(s,e)),this.updateSessionSupported(o,s),this.listenToXRSessionState(o,s),this.hideElementDuringXRSession(o),this.isSecureConnection||(o.disabled=!0,o.title="WebXR requires a secure connection (HTTPS)"),Q.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(o,s)),o}createSendToQuestButton(){var e;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",s=document.createElement("button");return this._sendToQuestButton=s,s.dataset.needle="webxr-sendtoquest-button",s.innerText="Open on Quest",s.prepend(Mt("share_windows")),s.title="Click to send this page to the Oculus Browser on your Quest",s.addEventListener("click",()=>{const o=encodeURIComponent(window.location.href),r=t+o;window.open(r)==null&&De("This page doesn't allow popups. Please paste "+r+" into your browser.")}),this.listenToXRSessionState(s),this.hideElementDuringXRSession(s),Q.isMozillaXR()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>{var o;(o=navigator.xr)!=null&&o.isSessionSupported("immersive-vr")?s.style.display="none":s.style.display=""}),s}createQRCode(){return Po.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}oe.isSessionSupported(t).then(s=>{e.style.display=s?"":"none",B()&&!s&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Ud(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Pg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(oe.onSessionRequestStart(s=>{s.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),oe.onSessionRequestEnd(s=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}};a(H1,"_instance");let gl=H1;var hA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,St=(n,e,t,s)=>{for(var o=s>1?void 0:s?dA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&hA(e,t,o),o};const gp=C("debugspriterenderer"),uA=C("wireframe"),G1=class xv{static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&xv.cache[e.guid])return gp&&console.log("Take cached geometry for sprite",e.guid),xv.cache[e.guid];const t=new Ws;e.__cached_geometry=t;const s=new Float32Array(e.triangles.length*3),o=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){const l=e.triangles[r];s[r*3]=-e.vertices[l].x,s[r*3+1]=e.vertices[l].y,s[r*3+2]=0;const c=e.uv[l];o[r*2]=c.x,o[r*2+1]=1-c.y}return t.setAttribute("position",new _t(s,3)),t.setAttribute("uv",new _t(o,2)),e.guid&&(this.cache[e.guid]=t),gp&&console.log("Built sprite geometry",e,t),t}};a(G1,"cache",{});let fp=G1;class pA{constructor(){a(this,"x"),a(this,"y")}}function q1(n){n&&(n.colorSpace!=Mn&&(n.colorSpace=Mn,n.needsUpdate=!0),n.minFilter==wd&&n.magFilter==wd&&(n.anisotropy=1,n.needsUpdate=!0))}let Yn=class{constructor(n){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),n&&(this.texture=n,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}])}get mesh(){return this._mesh||(this._mesh=new q(fp.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&q1(this.texture),this._material=new Me({map:this.texture,color:16777215,side:Oi,transparent:!0})),this._material}getGeometry(){return fp.getOrCreateGeometry(this)}};St([m()],Yn.prototype,"guid",2),St([m(je)],Yn.prototype,"texture",2),St([jr()],Yn.prototype,"triangles",2),St([jr()],Yn.prototype,"uv",2),St([jr()],Yn.prototype,"vertices",2);const $0=Symbol("spriteOwner");class fl{constructor(){a(this,"sprites"),this.sprites=[]}}St([m(Yn)],fl.prototype,"sprites",2);const H0=class Sv{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const e=new Sv;return e.spriteSheet=new fl,e}clone(){const e=new Sv;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 fl,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const s=this.spriteSheet.sprites[t],o=s?.texture;if(o&&(q1(o),!s.__hasLoadedProgressive)){s.__hasLoadedProgressive=!0;const r=o;Xe.assignTextureLOD(o,0).then(l=>{l instanceof je&&(s.texture=l,e?.map===r&&(e.map=l,e.needsUpdate=!0))})}}};St([m(fl)],H0.prototype,"spriteSheet",2),St([m()],H0.prototype,"index",2);let yl=H0;class fi extends j{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(e){var t;if(!this._spriteSheet)return;const s=(t=this._spriteSheet.spriteSheet)==null?void 0:t.sprites[this.spriteIndex];s&&(s.texture=e,this.updateSprite())}addSprite(e,t=!1){var s,o;if(this._spriteSheet||(this._spriteSheet=yl.create()),!this._spriteSheet.spriteSheet)return-1;(s=this._spriteSheet.spriteSheet)==null||s.sprites.push(e);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return t&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t}else e instanceof Yn?(this._spriteSheet||(this._spriteSheet=yl.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(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=yl.create(),gp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){var t;if(!this.__didAwake&&!e)return!1;const s=this._spriteSheet;if(!((t=s?.spriteSheet)!=null&&t.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=s.spriteSheet.sprites[this.spriteIndex];if(!o)return gp&&console.warn("Sprite not found",this.spriteIndex,s.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=fp.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Me({color:16777215,side:Oi});if(uA&&(r.wireframe=!0),this.color&&(r.color||(r.color=new re),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,r.depthWrite=!1,o.texture&&!r.wireframe){let l=o.texture;l[$0]!==void 0&&l[$0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[$0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new q(fp.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),Xe.assignTextureLOD(r,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,s?.update(this.sharedMaterial),!0}}St([m()],fi.prototype,"drawMode",2),St([m(pA)],fi.prototype,"size",2),St([m(he)],fi.prototype,"color",2),St([m(Pe)],fi.prototype,"sharedMaterial",2),St([m()],fi.prototype,"transparent",2),St([m()],fi.prototype,"cutoutThreshold",2),St([m()],fi.prototype,"castShadows",2),St([m()],fi.prototype,"renderOrder",2),St([m()],fi.prototype,"toneMapped",2),St([m(yl)],fi.prototype,"sprite",1);const X1=C("debugwebxr"),mA=new ne().makeRotationY(Math.PI),G0=class rd extends j{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new Si),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",e=>{var t;if(this._isPlacing==!1||e!=null&&e.used)return;let s=this._reticle[0];if(!s){console.warn("No reticle to place...");return}if(!s.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((t=oe.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let o=this._hits[0];if(e&&e.origin instanceof Og){const r=this._reticle[e.origin.index];r&&(s=r,o=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(),s.position.copy(s.lastPos),s.quaternion.copy(s.lastQuat),this.onApplyPose(s),rd._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(oe.active,o),this.context.xr)for(const r of this.context.xr.controllers)r.cancelHitTestSource()}),a(this,"upVec",new S(0,1,0)),a(this,"lookPoint",new S),a(this,"worldUpVec",new S(0,1,0))}static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const s=this._eventListeners[t].indexOf(e);s>=0&&this._eventListeners[t].splice(s,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){X1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,rd._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new A;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let s=this.context.scene.children.length-1;s>=0;s--){const o=this.context.scene.children[s];this._placementScene.add(o)}if(this.context.scene.add(t),this.autoCenter){const s=ni(this._placementScene.children),o=s.getCenter(new S),r=s.getSize(new S),l=new ne;l.makeTranslation(o.x,o.y-r.y*.5,o.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(t,this);for(const s of this._reticle)Ai(s);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ri.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ri.Early}),this.onRevertSceneChanges(),this._anchor=null,rd._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){var t,s,o,r;if(e.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(t=e.xr.rig)==null?void 0:t.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const h of e.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(e.xr,h.index,d,e.xr.rigScale))}if(!c){const h=e.xr.getHitTest();h&&this.updateReticleAndHits(e.xr,0,h,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const l=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=e.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new gA(this.context)),(s=this.userInput)==null||s.enable()):(o=this.userInput)==null||o.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(e.xr.rig){const l=e.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,s,o){this._hits[t]=s.hit;let r=this._reticle[t];if(!r){if(this.customReticle)if(this.customReticle.asset)r=Ha(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new q(new kP(.07,.09,32).rotateX(-Math.PI/2),new Me({side:Oi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if(X1){const l=new Pi(1);l.position.y+=.01,r.add(l)}this._reticle[t]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||s.position.clone(),r.lastQuat=r.lastQuat||s.quaternion.clone(),r.position.copy(r.lastPos.lerp(s.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(s.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(o,o,o),this.customReticle&&this.applyViewBasedTransform(r),r.updateMatrix(),r.visible=!0,r.parent!==this.context.scene&&this.context.scene.add(r),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(r.quaternion),this.upVec.dot(X(0,1,0))>.9){let l=r["autoplace:timer"]||0;l>=1?(r.visible=!1,this.onPlaceScene(null)):(l+=this.context.time.deltaTime,r["autoplace:timer"]=l)}else r["autoplace:timer"]=0}onSetScale(){var e,t,s;if(!rd._hasPlaced)return;const o=(t=(e=oe.active)==null?void 0:e.rig)==null?void 0:t.gameObject;if(o){const r=((s=oe.active)==null?void 0:s.rigScale)||1,l=1/this._arScale*r,c=new ne().makeScale(l,l,l).invert();o.matrix.premultiply(c),o.matrix.decompose(o.position,o.quaternion,o.scale)}}onRevertSceneChanges(){var e;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const s=this._placementScene.children[t];this.context.scene.add(s)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const t of this._reparentedComponents)P.addComponent(t.originalObject,t.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),B()&&be("Hit does not support creating an anchor");return}else{const s=await t.createAnchor(e.viewerPose.transform);e.running&&s&&(this._anchor=s)}}applyViewBasedTransform(e){const t=this.context.mainCamera,s=e,o=t.worldPosition,r=s.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const l=t.worldPosition;l&&e.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(o.y=r.y,e.lookAt(o))}onApplyPose(e){var t,s,o;const r=(s=(t=oe.active)==null?void 0:t.rig)==null?void 0:s.gameObject;if(!r){console.warn("No rig object to place");return}const l=r.parent||this.context.scene;this._rigPlacementMatrix?(o=this._rigPlacementMatrix)==null||o.decompose(r.position,r.quaternion,r.scale):this._rigPlacementMatrix=r.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(r),e.removeFromParent(),r.scale.set(this.arScale,this.arScale,this.arScale),r.position.multiplyScalar(this.arScale),r.updateMatrix(),this.invertForward&&r.matrix.premultiply(mA),r.matrix.premultiply(this._startOffset),r.matrix.decompose(r.position,r.quaternion,r.scale),l.add(r)}};a(G0,"_eventListeners",{}),a(G0,"_hasPlaced",!1);let Vo=G0;const yp=class Cv{constructor(e){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=Q.isAndroidDevice()&&o.clientY<window.innerHeight*.1;this.prev.has(o.identifier)||this.prev.set(o.identifier,{ignore:r,x:0,z:0,screenx:0,screeny:0});const l=this.prev.get(o.identifier);if(l){const c=this.getPositionOnPlane(o.clientX,o.clientY);l.x=c.x,l.z=c.z,l.screenx=o.clientX,l.screeny=o.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s];this.prev.delete(o.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const s=t.touches[0],o=this.prev.get(s.identifier);if(!o||o.ignore)return;const r=this.getPositionOnPlane(s.clientX,s.clientY),l=r.x-o.x,c=r.z-o.z;if(l===0&&c===0)return;this.oneFingerDrag&&this.addMovement(l,c),o.x=r.x,o.z=r.z,o.screenx=s.clientX,o.screeny=s.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const s=t.touches[0],o=t.touches[1],r=this.prev.get(s.identifier),l=this.prev.get(o.identifier);if(!r||!l)return;if(this.twoFingerRotate){const c=Math.atan2(s.clientY-o.clientY,s.clientX-o.clientX),h=Math.atan2(r.screeny-l.screeny,r.screenx-l.screenx),d=c-h;Math.abs(d)>.001&&this.addRotation(d)}if(this.twoFingerScale){const c=s.clientX-o.clientX,h=s.clientY-o.clientY,d=Math.sqrt(c*c+h*h),u=r.screenx-l.screenx,p=r.screeny-l.screeny,g=Math.sqrt(u*u+p*p),f=d-g;Math.abs(f)>2&&this.addScale(f)}r.screenx=s.clientX,r.screeny=s.clientY,l.screenx=o.clientX,l.screeny=o.clientY}}}),a(this,"_raycaster",new gd),a(this,"_intersection",new S),a(this,"_screenPos",new S),a(this,"_tempMatrix",new ne),this.context=e,this.offset=new ne,this.plane=new fr,this.plane.setFromNormalAndCoplanarPoint(Cv.up,Cv.zero)}get scale(){return this._scale}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)}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:ri.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ri.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:ri.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ri.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ri.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(e,t){const s=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(s),this._raycaster.set(s.position,this._screenPos.sub(s.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)}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)}};a(yp,"up",new S(0,1,0)),a(yp,"zero",new S(0,0,0)),a(yp,"one",new S(1,1,1));let gA=yp;const $o=C("debugautosync"),q0=Symbol("syncerId");class fA{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new yA(e);return t[q0]=e.guid,this._syncers[t[q0]]=t,t}removeSyncer(e){delete this._syncers[e[q0]]}}const X0=new fA;class yA{constructor(e){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const s in this.changedProperties)delete this.changedProperties[s];return}for(const s in this.changedProperties){const o=this.changedProperties[s];$o&&console.log("SEND",this.comp.guid,this.networkingKey),t.send(this.networkingKey,{guid:this.comp.guid,property:s,data:o},xs.Queued),delete this.changedProperties[s]}}),a(this,"onHandleReceiving",t=>{if($o&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,t),!!this._isInit&&this.comp&&t.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[t.property]=t.data}catch(s){console.error(s)}finally{this._isReceiving=!1}}),this.comp=e}get networkingKey(){return this.comp.guid}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||($o&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}}function vA(n,e){let t=e!==n;return!t&&n&&e&&(Array.isArray(n)&&Array.isArray(e)||typeof n=="object"&&typeof e=="object")&&(t=!0),t}const sh=Symbol("AutoSyncHandler");function bA(n){if(n[sh])return n[sh];const e=X0.getOrCreateSyncer(n);return e?.init(n),n[sh]=e,e}function _A(n){const e=n[sh];e&&(X0.removeSyncer(e),e.destroy(),delete n[sh])}const Q0=function(n=null){return function(e,t){var s;let o="";typeof t=="string"?o=t:o=t.name;let r=null,l;typeof n=="string"?l=e[n]:typeof n=="function"&&(l=n),l==null&&(B()||$o)&&n!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+n+'"');const c=e,h=c.__internalAwake;if(typeof h!="function"){($o||B())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((s=e?.constructor)==null?void 0:s.name)+'" is not supported',e);return}$o&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=X0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(f){var y;const v=this[d];if(this[d]=f,g){(B()||$o)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=vA(f,v);$o&&console.log("SyncField assignment",o,"changed?",b,f,l),b&&l?.call(this,f,v)!==!1&&((y=bA(this))==null||y.notifyChanged(o,f))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){_A(this),u.call(this)}}};var wA=Object.defineProperty,vp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&wA(e,t,o),o};const ti=C("debugplayersync"),bp=class PC extends j{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ti&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(t=>{ti&&console.log("PlayerSync.destroyInstance",t),yc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(e,t){const s=ce.getOrCreateFromUrl(e);if(!s.asset){const l=await s.loadAssetAsync();l&&P.getOrAddComponent(l,ks)}const o=new PC;o._internalInit(t),o.asset=s;const r=new A;return r.guid=e,P.addComponent(r,o),o}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new xe)}onEnable(){this.context.connection.beginListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.destroyInstance)}async getInstance(){var e,t,s,o,r,l;if(this._localInstance)return this._localInstance;if(ti&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.url),!((t=this.asset)!=null&&t.asset)&&!((s=this.asset)!=null&&s.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=(o=this.asset)==null?void 0:o.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const c=await this._localInstance;if(c){const h=P.getComponentsInChildren(c,ks);if(ti&&console.log(`PlayerSync.createInstance: found ${h?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),h!=null&&h.length){for(const d of h)d.owner=this.context.connection.connectionId;(r=this.onPlayerSpawned)==null||r.invoke(c)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((l=this.asset)==null?void 0:l.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(c)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=ks.all.length-1;t>=0;t--){const s=ks.all[t];(!s.owner||!this.context.connection.userIsInRoom(s.owner))&&s.doDestroy()}})}};vp([m()],bp.prototype,"autoSync"),vp([m(ce)],bp.prototype,"asset"),vp([m(xe)],bp.prototype,"onPlayerSpawned");let Y0=bp;var Q1=(n=>(n.OwnerChanged="ownerChanged",n))(Q1||{}),Ke;const K0=(Ke=class extends j{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new xe),a(this,"onFirstOwnerChangeEvent",new xe),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",n=>{if(n.userId===this.owner){ti&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Ke._all}static get local(){return Ke._local}static getFor(n){if(n instanceof A)return P.getComponentInParent(n,Ke);if(n instanceof j)return P.getComponentInParent(n.gameObject,Ke)}static isLocalPlayer(n){const e=Ke.getFor(n);return e?.isLocalPlayer??!1}static addEventListener(n,e){return this._callbacks[n]||(this._callbacks[n]=[]),this._callbacks[n].push(e),e}static removeEventListener(n,e){if(!this._callbacks[n])return;const t=this._callbacks[n].indexOf(e);t>=0&&this._callbacks[n].splice(t,1)}static dispatchEvent(n,e){if(this._callbacks[n])for(const t of this._callbacks[n])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(n,e){var t,s;ti&&console.log(`PlayerSync.onOwnerChange: ${e} \u2192 ${n} (me: ${this.context.connection.connectionId})`);const o=Ke._local.indexOf(this);o>=0&&Ke._local.splice(o,1);const r={playerState:this,oldValue:e,newValue:n};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(r)),(s=this.onOwnerChangeEvent)==null||s.invoke(r),this.owner===this.context.connection.connectionId){Ke._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Ke.dispatchEvent("ownerChanged",l)}awake(){Ke.all.push(this),ti&&console.log("Registered new PlayerState",this.guid,Ke.all.length-1,Ke.all),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeftRoom)}async start(){ti&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await $s(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ti&&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||(ti&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ti&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ti&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ti&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ti&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),yc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ti&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeftRoom),Ke.all.splice(Ke.all.indexOf(this),1),this.isLocalPlayer){const n=Ke._local.indexOf(this);n>=0&&Ke._local.splice(n,1)}}},a(Ke,"_all",[]),a(Ke,"_local",[]),a(Ke,"_callbacks",{}),Ke);vp([Q0(K0.prototype.onOwnerChange)],K0.prototype,"owner");let ks=K0;var xA=Object.defineProperty,vl=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&xA(e,t,o),o};class un extends j{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!1),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"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&&(Q.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}vl([m()],un.prototype,"position"),vl([m()],un.prototype,"showNeedleLogo"),vl([m()],un.prototype,"showSpatialMenu"),vl([m()],un.prototype,"createFullscreenButton"),vl([m()],un.prototype,"createMuteButton"),vl([m()],un.prototype,"createQRCodeButton");var SA=Object.defineProperty,Z0=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SA(e,t,o),o};const nh=C("debugwebxr"),Y1=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class Ho extends j{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;nh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=ks.getFor(this);if(t!=null&&t.owner){const s=this.gameObject.addComponent(di);s.avatar=this.gameObject,s.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(di);t&&t.destroy()}onUpdateXR(e){var t,s;if(!this.activeAndEnabled)return;const o=ks.isLocalPlayer(this);if(!o)return;const r=e.xr;if(r.rig&&r.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),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&o)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=P.getComponentsInChildren(this.head.asset,os);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=e.xr.leftController,c=(t=this.leftHand)==null?void 0:t.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(Y1),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=e.xr.rightController,d=(s=this.rightHand)==null?void 0:s.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(Y1),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,s){if(s){const o=e.model&&e.model.visible&&e.model!==t;s.forEach(r=>{Fn(r,!o)})}}updateRemoteAvatarVisibility(){var e,t,s;if(this.context.connection.isConnected){const o=ks.getFor(this);if(o&&o.isLocalPlayer==!1){const r=oe.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(e=this.leftHand)==null?void 0:e.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(t=this.rightHand)==null?void 0:t.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((s=this.head)!=null&&s.asset){const l=P.getComponentsInChildren(this.head.asset,os);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};M_.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(){var e,t;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof A&&(this.head=new ce("",this.sourceId,this.head));else{const s=new A;s.name="Head";const o=xo.createPrimitive(Sr.Cube);s.add(o),this.gameObject.add(s),this.head=new ce("",this.sourceId,s),nh&&console.log("Create head",s)}if(this.rightHand)this.rightHand instanceof A&&(this.rightHand=new ce("",this.sourceId,this.rightHand));else{const s=new A;s.name="Right Hand",this.gameObject.add(s),this.rightHand=new ce("",this.sourceId,s),nh&&console.log("Create right hand",s)}if(this.leftHand)this.leftHand instanceof A&&(this.leftHand=new ce("",this.sourceId,this.leftHand));else{const s=new A;s.name="Left Hand",this.gameObject.add(s),this.leftHand=new ce("",this.sourceId,s),nh&&console.log("Create left hand",s)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(e=this.leftHand.asset)==null||e.traverse(s=>{s!=null&&s.isMesh&&this._leftHandMeshes.push(s)}),this._rightHandMeshes=[],(t=this.rightHand.asset)==null||t.traverse(s=>{s!=null&&s.isMesh&&this._rightHandMeshes.push(s)}),ks.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,sn))}async loadAvatarObjects(e,t,s){const o=e.loadAssetAsync(),r=t.loadAssetAsync(),l=s.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await eg(c);nh&&console.log("Avatar loaded results:",h)}}Z0([m(ce)],Ho.prototype,"head"),Z0([m(ce)],Ho.prototype,"leftHand"),Z0([m(ce)],Ho.prototype,"rightHand");var CA=Object.defineProperty,_p=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&CA(e,t,o),o};const Kn=C("debugwebxr"),Go=new Array;class pn extends j{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}async onXRControllerAdded(e){var t;if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:s}=e;if(Kn&&console.warn("Add Controller Model for",s.side,s.index),this.createControllerModel||this.createHandModel){if(s.hand){if(this.createHandModel){const o=await this.loadHandModel(this,s);if(!o||!s.connected||!s.isHand){o!=null&&o.handObject&&$a(o.handObject,!1),(t=o?.handObject)==null||t.destroy();return}this._models.push({controller:s,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),s.model=o.handObject}}else if(this.createControllerModel){const o=await s.getModelUrl();if(o){const r=await this.loadModel(s,o);if(!r||!s.connected||s.isHand)return;this._models.push({controller:s,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),s.model=r}else s.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+s.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(o=>o.controller===e.controller),s=this._models[t];s&&(this._models.splice(t,1),s.model&&($a(s.model,!1),s.model.destroy(),s.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&&($a(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(oe.active&&(Kn&&(Go[0]=Date.now()),this.updateRendering(oe.active),Kn)){const e=Date.now()-Go[0];Go.push(e),Go.length>=30&&(Go[0]=0,Go.reduce((t,s)=>t+s,0)/Go.length,Go.length=0)}}updateRendering(e){var t,s,o,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Kn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(t=e.rig)==null||t.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=e.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&e.frame.getJointPose){for(const g of d.inputSource.hand.values()){const f=p.joints[g.jointName];if(f){const y=d.getHandJointPose(g);if(y){const v=y.transform.position,b=y.transform.orientation;f.position.copy(v),f.quaternion.copy(b),f.matrixAutoUpdate=!1}f.visible=y!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((s=e.rig)==null?void 0:s.gameObject)&&((o=e.rig)==null||o.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(La))}}}}async loadModel(e,t){var s;if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const o=await ce.getOrCreate("",t).instantiate();return $a(o),(s=oe.active)!=null&&s.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(e,t){const s=this.context,o=s.renderer.xr.getHand(t.index);o||(Kn?G.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const r=new Rn;Bf(r,s),await Zu(r,s,this.sourceId??"");const l=b0(r);let c="";const h=t.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=t.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new A;$a(d);const u=new rO(d,o,r.path,c,r,p=>{var g;const f=l?.gltf;((g=f?.scene.children)==null?void 0:g.length)===0&&(f.scene.children[0]=p),l!=null&&l.gltf&&ws().createBuiltinComponents(e.context,e.sourceId||c,l.gltf,null,l),p.traverse(y=>{var v;y.layers.set(2),(v=oe.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(y),y instanceof q&&Xe.assignMeshLOD(y,0)}),t.connected||(Kn&&G.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Kn&&d.add(new Pi(.5)),t.inputSource.hand){Kn&&console.log(t.inputSource.hand);for(const p of t.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new go;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else Kn&&G.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(e){if(e instanceof q){let t=e.material;t instanceof Pe&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}a(pn,"factory",new oO),_p([m()],pn.prototype,"createControllerModel"),_p([m()],pn.prototype,"createHandModel"),_p([m(ce)],pn.prototype,"customLeftHand"),_p([m(ce)],pn.prototype,"customRightHand");class wp extends j{}var PA=Object.defineProperty,qo=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&PA(e,t,o),o};const J0=C("debugwebxr");class Ni extends j{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const s=e.xr.leftController,o=e.xr.rightController;s&&this.onHandleMovement(s,t.gameObject),o&&(this.onHandleRotation(o,t.gameObject),this.useTeleport&&this.onHandleTeleport(o,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const s=e.getStick("xr-standard-thumbstick");if(s.x!=0||s.y!=0){const o=X(s.x,0,s.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ge(t);o.multiplyScalar(r.x),o.applyQuaternion(e.xr.poseOrientation),o.y=0,o.applyQuaternion(t.worldQuaternion),t.position.add(o),t.updateWorldMatrix(!1,!1);for(const l of t.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const s=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(s)<.3&&(this._didApplyRotation=!1);else if(Math.abs(s)>.5){this._didApplyRotation=!0;const o=s>0?1:-1,r=ee(this.context.mainCamera).clone();t.rotateY(o*W.toRadians(this.rotationStep));const l=ee(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}onHandleTeleport(e,t){var s,o,r,l,c;let h=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const d=e.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=e.getGesture("pinch");u&&(h=u.value)}else h=(s=e.getStick("xr-standard-thumbstick"))==null?void 0:s.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(e.ray)[0];if(d&&d.object instanceof ka){const p=(o=d.normal)==null?void 0:o.dot(X(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new fr(new S(0,1,0),0));const p=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new S(0,1,0),p);const g=e.ray;u=p.clone(),this._plane.intersectLine(new MP(g.origin,X(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>t.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,wp))return;const p=u.clone();if(J0&&G.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),J0&&G.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=e.xr.fadeTransition())==null||c.then(()=>{t.worldPosition=p}):t.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(t.position,t.quaternion,t.scale)}}renderRays(e){var t;for(let s=0;s<this._lines.length;s++){const o=this._lines[s];o&&(o.visible=!1)}for(let s=0;s<e.controllers.length;s++){const o=e.controllers[s];let r=this._lines[s];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[s]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=e.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[s],p=this._hitDistances[s]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let f=r.material.opacity;d?f=1:this.showHits&&g<e.rigScale*.5?f=0:(t=o.getButton("primary"))!=null&&t.pressed?f=.5:f=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(e){var t;for(const s of this._hitDiscs){if(!s)continue;const o=s.controller;if(!o||!o.connected||!o.isTracking){s.visible=!1;continue}}for(let s=0;s<e.controllers.length;s++){const o=e.controllers[s];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[s],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[s]=null,this._lastHitDistances[s]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[s];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[s]=u?.distance||null,u){this._lastHitDistances[s]=u.distance;const p=e.rigScale??1;J0&&(G.DrawWireSphere(u.point,.025*p,16711680),G.DrawLabel(X(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[s]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const f=(t=o.getButton("primary"))==null?void 0:t.pressed;f&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let y=r.material.opacity;if(f?y=1:y=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Se(u.object));r.quaternion.setFromUnitVectors(OA,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[s]&&(this._hitDiscs[s].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Ru(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,s){const o=X(e.rayWorldPosition);o.add(X(0,0,s-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const e=new q(new md(.3,6,6),new Me({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 aO;e.layers.disableAll(),e.layers.enable(2);const t=new lO;e.geometry=t;const s=new Float32Array(9);s.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(s);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(o);const r=new cO({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Nv,dashed:!1});return e.material=r,e}}qo([m()],Ni.prototype,"movementSpeed"),qo([m()],Ni.prototype,"rotationStep"),qo([m()],Ni.prototype,"useTeleport"),qo([m()],Ni.prototype,"usePinchToTeleport"),qo([m()],Ni.prototype,"useTeleportTarget"),qo([m()],Ni.prototype,"useTeleportFade"),qo([m()],Ni.prototype,"showRays"),qo([m()],Ni.prototype,"showHits");const OA=new S(0,1,0);var kA=Object.defineProperty,Ct=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kA(e,t,o),o};const oh=C("debugwebxr"),MA=C("debugusdz");var Xo;const pt=(Xo=class extends j{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"_activeWebARSessionRoot",null),a(this,"onAvatarSpawned",n=>{oh&&console.log("WebXR.onAvatarSpawned",n),P.getComponentInChildren(n,Ho)??(i=P.addComponent(n,Ho))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){oe.getXRSync(this.context)}onEnable(){var n,e;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).'),this.useQuicklookExport&&(P.findObjectOfType(gn)||(oh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,gn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(oh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ce("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Y0),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(n=this._playerSync.onPlayerSpawned)==null||n.removeEventListener(this.onAvatarSpawned),(e=this._playerSync.onPlayerSpawned)==null||e.addEventListener(this.onAvatarSpawned))}onDisable(){var n;(n=this._usdzExporter)==null||n.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await oe.isVRSupported()&&this.createVRButton?oe.offerSession("immersive-vr","default",this.context):this.createARButton&&await oe.isARSupported()&&this.createARButton?oe.offerSession("immersive-ar","default",this.context):!1}get session(){return oe.active??null}get sessionMode(){return oe.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(n){return oe.start("immersive-vr",n,this.context)}async enterAR(n){return oe.start("immersive-ar",n,this.context)}exitXR(){oe.stop()}get isActiveWebXR(){return!Xo.activeWebXRComponent||Xo.activeWebXRComponent===this}onBeforeXR(n,e){var t;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(t=Xo.activeWebXRComponent)==null?void 0:t.name}). This is ignored: ${this.name}`);return}Xo.activeWebXRComponent=this,n=="immersive-ar"&&this.useDepthSensing&&(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.push("depth-sensing"))}async onEnterXR(n){if(!this.isActiveWebXR)return;oh&&console.log("WebXR onEnterXR"),this._previousXRState=Di.Global.Mask;const e=n.xr.isVR;if(Di.Global.Set(e?rn.VR:rn.AR),n.xr.isAR){let t=P.findObjectOfType(Vo);if(!t)if(this.usePlacementReticle){const s=new A;for(const o of this.context.scene.children)s.add(o);this.context.scene.add(s),t=P.addComponent(s,Vo),this._createdComponentsInSession.push(t)}else(oh||B())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=t,t&&(t.customReticle=this.customARPlacementReticle,t.arScale=this.arScale,t.arTouchTransform=this.usePlacementAdjustment,t.autoPlace=this.autoPlace,t.autoCenter=this.autoCenter,t.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Bc)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Bc))),this.createLocalAvatar(n.xr),n.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(n){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(n){var e,t;if((e=this._exitXRMenuButton)==null||e.remove(),!!this.isActiveWebXR){Di.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const s of this._createdComponentsInSession)s.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Ql(1).then(()=>Xo.activeWebXRComponent=null)}}setDefaultMovementEnabled(n){let e=this.gameObject.getComponent(Ni);return!e&&n&&(e=this.gameObject.addComponent(Ni),this._createdComponentsInSession.push(e)),e&&(e.enabled=n),e}setDefaultControllerRenderingEnabled(n){let e=this.gameObject.getComponent(pn);return!e&&n&&(e=this.gameObject.addComponent(pn),this._createdComponentsInSession.push(e),e.createControllerModel=this.showControllerModels,e.createHandModel==this.showHandModels),e&&(e.enabled=n),e}async createLocalAvatar(n){this._playerSync&&n.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=gl.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((Q.isiOS()&&Q.isSafari()||MA)&&this.useQuicklookExport){const n=P.findObjectOfType(gn);if(!n||n&&n.allowCreateQuicklookButton){const e=this.getButtonsFactory().createQuicklookButton();this.addButton(e,50)}}if(this.createARButton){const n=this.getButtonsFactory().createARButton();this.addButton(n,50)}if(this.createVRButton){const n=this.getButtonsFactory().createVRButton();this.addButton(n,50)}}if(this.createSendToQuestButton&&!Q.isQuest()&&oe.isVRSupported().then(n=>{if(!n){const e=this.getButtonsFactory().createSendToQuestButton();this.addButton(e,50)}}),this.createQRCode){const n=Sc(un);if(n&&n.createQRCodeButton===!1)B()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!Q.isMobileDevice()){const e=Po.getOrCreate().createQRCode();this.addButton(e,50)}}}addButton(n,e){this._buttons.push(n),n.setAttribute("priority",e.toString()),this.context.menu.appendChild(n)}removeButtons(){for(const n of this._buttons)n.remove();this._buttons.length=0}},a(Xo,"activeWebXRComponent",null),Xo);Ct([m()],pt.prototype,"createVRButton"),Ct([m()],pt.prototype,"createARButton"),Ct([m()],pt.prototype,"createSendToQuestButton"),Ct([m()],pt.prototype,"createQRCode"),Ct([m()],pt.prototype,"useDefaultControls"),Ct([m()],pt.prototype,"showControllerModels"),Ct([m()],pt.prototype,"showHandModels"),Ct([m()],pt.prototype,"usePlacementReticle"),Ct([m(ce)],pt.prototype,"customARPlacementReticle"),Ct([m()],pt.prototype,"usePlacementAdjustment"),Ct([m()],pt.prototype,"arScale"),Ct([m()],pt.prototype,"useXRAnchor"),Ct([m()],pt.prototype,"autoPlace"),Ct([m()],pt.prototype,"autoCenter"),Ct([m()],pt.prototype,"useQuicklookExport"),Ct([m()],pt.prototype,"useDepthSensing"),Ct([m()],pt.prototype,"useSpatialGrab"),Ct([m(ce)],pt.prototype,"defaultAvatar");let xp=pt;const Sp=C("debugusdzbehaviours");class ey{constructor(){a(this,"behaviours",[]),a(this,"behaviourComponents",[]),a(this,"behaviourComponentsCopy",[]),a(this,"audioClips",[]),a(this,"audioClipsCopy",[]),a(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+_a.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(s=>{P.foreachComponent(s,o=>{var r;const l=o;if(typeof l.createBehaviours=="function"||typeof l.beforeCreateDocument=="function"||typeof l.afterCreateDocument=="function"||typeof l.afterSerialize=="function"){this.behaviourComponents.push(l);const c=(r=l.beforeCreateDocument)==null?void 0:r.call(l,this,e);c instanceof Promise&&t.push(c)}},!1)}),Sp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,s){var o;for(const r of this.behaviourComponents)(o=r.createBehaviours)==null||o.call(r,this,t,s)}onAfterBuildDocument(e){for(const p of this.behaviourComponents)typeof p.afterCreateDocument=="function"&&p.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,s=new Set,o=new Set,r=new Set,l=Sp;let c=`graph LR
|
|
1253
1253
|
`,h="";function d(p){if(p instanceof No){l&&(c+=`subgraph Group_${p.id}
|
|
1254
1254
|
`);for(const g of p.actions)l&&(c+=`${p.id}[${p.id}] -- ${p.type},loops:${p.loops} --> ${g.id}[${g.id}]
|
|
1255
1255
|
`),d(g);l&&(c+=`end
|
|
@@ -1271,7 +1271,7 @@ dateFormat X
|
|
|
1271
1271
|
axisFormat %s
|
|
1272
1272
|
`;const g=Array.from(r),f=new Set;for(const _ of g)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const w of _.affectedObjects)f.add(w);else f.add(_.affectedObjects);l&&(p+=`section ${_.animationName} (${_.id})
|
|
1273
1273
|
`,p+=`${_.id} : ${_.start}, ${_.duration}s
|
|
1274
|
-
`)}l&&r.size&&console.log(p);const y=new Set;for(const _ of f){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let w=_.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:_})}const v=Array.from(y).sort((_,w)=>_.path.length-w.path.length),b=new Array;for(let _=0;_<v.length;_++)for(let w=_+1;w<v.length;w++)if(v[w].path.startsWith(v[_].path)){const x=v[w],k=v[_];b.push({child:x.obj.displayName+" ("+x.path+")",parent:k.obj.displayName+" ("+k.path+")"})}b.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:b,playAnimationActions:r})}for(const p of new Set([...t,...s]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);Sp&&console.log("All Behavior trigger sources and action targets",t,s,o),this.targetUuids=new Set(o)}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Sp&&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:s}of this.audioClipsCopy){if(e.files[s])return;const o=await(await(await fetch(t)).blob()).arrayBuffer(),r=new Uint8Array(o);e.files[s]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class ty{get extensionName(){return"Physics"}onExportObject(e,t,s){const o=P.getComponents(e,dt).filter(h=>h.enabled),r=P.getComponents(e,pi).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new dt,l.isKinematic=!0),l&&t.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const f=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const y=f.sharedMaterial;y&&y.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),y&&y.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=f.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(t.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof tl){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Wu){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof Vn){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Bo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const f=c.sharedMesh.geometry.boundingBox;f&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}const RA=C("debugshadowcomponents");ib.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};class ps extends j{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){si.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,rh)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var s;if(!e)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ps),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Ri]=this,this.setShadowComponentOwner(e);let r=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(e),r=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),vc&&e.add(new Pi(.5)),this.onAfterAddedToScene(),r&&kO(),RA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ri]===void 0||e[Ri]===this)&&(e[Ri]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[Ri]===t){s(e);for(const o of e.children)this.traverseOwnedShadowComponents(o,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class rh extends ps{awake(){super.awake()}}var TA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,ah=(n,e,t,s)=>{for(var o=s>1?void 0:s?EA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&TA(e,t,o),o};const iy=C("debugui"),sy=C("debuguilayout");class K1{constructor(){a(this,"width"),a(this,"height")}}class Z1{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Ms=new S,lh=new ne,Cp=new V,bl=class OC extends ps{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new ie(100,100)),a(this,"pivot",new ie(.5,.5)),a(this,"anchorMin",new ie(0,0)),a(this,"anchorMax",new ie(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new ie),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,s=this.anchorMax.x-this.anchorMin.x;e=t*s,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,s=this.anchorMax.y-this.anchorMin.y;e=t*s,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new A,this.rectBlock.name=this.name,this.lastMatrix=new ne,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new ie),Za(this,"_anchoredPosition",()=>{this.markDirty()}),Za(this,"sizeDelta",()=>{this.markDirty()}),Za(this,"pivot",()=>{this.markDirty()}),Za(this,"anchorMin",()=>{this.markDirty()}),Za(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new A),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new ie),this._initialPosition||(this._initialPosition=new S),this._anchoredPosition||(this._anchoredPosition=new ie),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(sy?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(sy&&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){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const s=this.shadowComponent;if(!s)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,OC):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,sy&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(s.rotation.y=Math.PI):(s.matrix.identity(),s.matrixAutoUpdate=!1,Ms.set(0,0,0),this.applyPivot(Ms),s.matrix.setPosition(Ms.x,Ms.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Cp.copy(this.gameObject.quaternion),Cp.x*=-1,Cp.z*=-1,lh.makeRotationFromQuaternion(Cp),s.matrix.premultiply(lh)),Ms.set(0,0,0),this.applyAnchoring(Ms),(t=this.canvas)!=null&&t.screenspace?Ms.z+=.1:Ms.z+=.01,lh.identity(),lh.setPosition(Ms.x,Ms.y,Ms.z),s.matrix.premultiply(lh),s.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const o=!0;for(const r of du(this.gameObject,ps,o,1)){if(r===this||!r.activeAndEnabled)continue;const l=r;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new ie);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 s=this._parentRectTransform;if(s){let o=0;const r=1-this.anchorMax.y-this.anchorMin.y;o-=s.height*.5*r,e.y+=o;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=s.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const s=this.pivot.y-.5;e.y-=s*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}createNewBlock(e){e={...this.getBasicOptions(),...e},iy&&console.log(this.name,e);const t=new ib(e);return this._createdBlocks.push(t),t}createNewText(e){iy&&console.log(e),e={...this.getBasicOptions(),...e},iy&&console.log(this.name,e);const t=new tb(e);return this._createdTextBlocks.push(t),t}};ah([m(ie)],bl.prototype,"anchoredPosition",1),ah([m(ie)],bl.prototype,"sizeDelta",2),ah([m(ie)],bl.prototype,"pivot",2),ah([m(ie)],bl.prototype,"anchorMin",2),ah([m(ie)],bl.prototype,"anchorMax",2);let Rs=bl;var AA=Object.defineProperty,J1=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&AA(e,t,o),o};class _l extends j{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}J1([m(he)],_l.prototype,"effectColor"),J1([m(ie)],_l.prototype,"effectDistance");var IA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,eS=(n,e,t,s)=>{for(var o=s>1?void 0:s?LA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&IA(e,t,o),o};const Pp={backgroundColor:new re(1,1,1),backgroundOpacity:1,borderColor:new re(1,1,1),borderOpacity:1};var Qr;const ny=(Qr=class extends ps{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new re(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(n){(!this._color||this._color.r!==n.r||this._color.g!==n.g||this._color.b!==n.b||this._color.alpha!==n.alpha)&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(n),this.onColorChanged())}setAlphaFactor(n){this._alphaFactor=n,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Pp.backgroundColor=this.sRGBColor,Pp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Pp,this._alphaFactor),this.uiObject.set(Pp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Rs)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var n;(n=this.uiObject)==null||n.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(n){return super.__internalNewInstanceCreated(n),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(n){this.makePanel(),this.uiObject&&(this.uiObject.setState(n),this==null||this.markDirty())}setupState(n){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new MO(this.uiObject)),this.uiObject.setupState(n.state,n.attributes))}setOptions(n){this.makePanel(),this.uiObject&&this.uiObject.set(n)}awake(){super.awake(),this.makePanel(),Za(this,"_color",()=>RT(this,this.onColorChanged))}onEnable(){var n;super.onEnable(),this.uiObject&&((n=this.rectTransform.shadowComponent)==null||n.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const n={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(n),this.applyEffects(n),this.onCreate(n),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(n){}onCreate(n){this.uiObject=this.rectTransform.createNewBlock(n),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(n,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(_l);s&&(s.effectDistance&&(n.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(n.borderColor=s.effectColor,n.borderOpacity=s.effectColor.alpha*e))}async setTexture(n){if(this.setOptions({backgroundOpacity:0}),n){if(Qr.textureCache.has(n))n=Qr.textureCache.get(n);else if(!n.isRenderTargetTexture){const e=n.clone();e.colorSpace=On,Qr.textureCache.set(n,e),n=e}this.setOptions({backgroundImage:n,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Xe.assignTextureLOD(n,0).then(e=>{e instanceof je&&(n&&Qr.textureCache.set(n,e),this.setOptions({backgroundImage:e}),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)}},a(Qr,"textureCache",new Map),Qr);eS([m(he)],ny.prototype,"color",1),eS([m()],ny.prototype,"raycastTarget",2);let ch=ny;class hh extends ch{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var jA=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,Zn=(n,e,t,s)=>{for(var o=s>1?void 0:s?DA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&jA(e,t,o),o};const Yr=C("debugtext");var mt=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(mt||{}),tS=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(tS||{});class Wt extends ch{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new re(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0)}onCreate(e){Yr&&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,Yr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Yr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}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(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,o,r;if(Yr&&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 l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new qm({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),d={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(e,l,h),this.handleTag(l,d,c);const u=new qm(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=e.substring(l.endIndex),this.handleTag(l,d,c);const u=new qm(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Lu(l,s),e[r]=!0)}if(!o)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const o=new oy(e,{color:t.color});if(s.push(o),e.type.length>6){const r=parseInt("0x"+e.type.substring(7));t.color=r}else t.color=new re(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const o=new oy(e,{fontWeight:700});s.push(o)}else if(e.type=="i"){this.setFont(t,2);const o=new oy(e,{fontStyle:"italic"});s.push(o)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),o=e.indexOf(">",s);if(s>=0&&o>=0){const r=e.substring(s+1,o);return{type:r,startIndex:s,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,o=this.getFamilyNameWithCorrectSuffix(s,t);Yr&&console.log("Selected font family:"+o);let r=sb.getFontFamily(o);switch(r||(r=sb.addFontFamily(o)),e.fontFamily=r,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 l=r.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(e.fontWeight,e.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const o=e.lastIndexOf("-");if(o<0)return e;const r=(s=e.substring(o+1))==null?void 0:s.toLowerCase();if(BA.includes(r))return Yr&&console.warn("Unsupported font style: "+r),e;const l=e.lastIndexOf("/");let c=e;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=e.substring(0,o);switch(Yr&&console.log("Select font: ",e,tS[t],c,h,d),t){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return e}}}Zn([m()],Wt.prototype,"alignment",2),Zn([m()],Wt.prototype,"verticalOverflow",2),Zn([m()],Wt.prototype,"horizontalOverflow",2),Zn([m()],Wt.prototype,"lineSpacing",2),Zn([m()],Wt.prototype,"supportRichText",2),Zn([m(URL)],Wt.prototype,"font",2),Zn([m()],Wt.prototype,"fontStyle",2),Zn([m()],Wt.prototype,"text",1),Zn([m()],Wt.prototype,"fontSize",1);class oy{constructor(e,t){a(this,"tag"),a(this,"previousValues"),this.tag=e,this.previousValues=t}}const BA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Kr{constructor(e){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=e}static getId(){return this.global_id++}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}writeTo(e,t){var s;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=[]),(s=this.font)==null||s.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");t.appendLine(`string[] font = [ ${o} ]`),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/${lp(this.material)}>`),t.closeBlock()}}a(Kr,"global_id",0);class ry{static singleLine(e,t,s){const o=new Kr("text_"+Kr.getId());return o.content=e,t&&(o.pointSize=t),s&&(o.depth=s),o}static multiLine(e,t,s,o,r,l){const c=new Kr("text_"+Kr.getId());return c.content=e,c.width=t,c.height=s,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const FA=new ne().makeRotationY(Math.PI),UA=new ne().makeScale(-1,1,-1);class Op{get extensionName(){return"text"}exportText(e,t,s){const o=P.getComponent(e,Wt);if(!o)return;const r=P.getComponent(e,Rs);let l=100,c=100;r&&(l=r.width,c=r.height);const h=FA.clone();r&&h.premultiply(UA),t.setMatrix(h);const d=o.color.clone();t.material=new bt({color:d,emissive:d}),t.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const f=ry.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(f,o.alignment),this.setOverflow(f,o),t.material&&(f.material=t.material),f.pointSize=this.convertToTextSize(o.fontSize),f.depth=.001,f.writeTo(void 0,u)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:e.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:e.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:e.horizontalAlignment="right";break}switch(t){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:e.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:e.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:e.verticalAlignment="top";break}}}var zA=Object.defineProperty,it=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&zA(e,t,o),o};const iS=C("debuguilayout");class Zr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}it([m()],Zr.prototype,"left"),it([m()],Zr.prototype,"right"),it([m()],Zr.prototype,"top"),it([m()],Zr.prototype,"bottom");class Wi extends j{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(iS&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){iS&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Rs);const e=this.gameObject.getComponentInParent(wl);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(wl);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}it([m()],Wi.prototype,"childAlignment"),it([m()],Wi.prototype,"reverseArrangement"),it([m()],Wi.prototype,"spacing"),it([m(Zr)],Wi.prototype,"padding"),it([m()],Wi.prototype,"minWidth"),it([m()],Wi.prototype,"minHeight"),it([m()],Wi.prototype,"flexibleHeight"),it([m()],Wi.prototype,"flexibleWidth"),it([m()],Wi.prototype,"preferredHeight"),it([m()],Wi.prototype,"preferredWidth");class Qo extends Wi{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,o=e.width;let r=o;const l=e.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const h=s==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,f=h?this.childForceExpandHeight:this.childForceExpandWidth,y=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let _=0;h?_+=this.padding.left:_+=this.padding.top;let w=0,x=0;for(let z=0;z<this.gameObject.children.length;z++){const U=this.gameObject.children[z],E=P.getComponent(U,Rs);E!=null&&E.activeAndEnabled&&(x+=1,h?w+=E.width:w+=E.height)}let k=0;const M=this.spacing*(x-1);if(g||u){let z=0;h?z=r-=M:z=c-=M,x>0&&(k=z/x)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(_=v-w,_*=b,_-=M*b,h?(_-=this.padding.right*b,_+=this.padding.left*(1-b),_<this.padding.left&&(_=this.padding.left)):(_-=this.padding.bottom*b,_+=this.padding.top*(1-b),_<this.padding.top&&(_=this.padding.top)));let D=1;for(let z=0;z<this.gameObject.children.length;z++){const U=this.gameObject.children[z],E=P.getComponent(U,Rs);if(E!=null&&E.activeAndEnabled){(t=E.pivot)==null||t.set(.5,.5),E.anchorMin.set(0,1),E.anchorMax.set(0,1);const $=o*.5+T*.5;E.anchoredPosition.x!==$&&(E.anchoredPosition.x=$);const H=l*-.5;E.anchoredPosition.y!==H&&(E.anchoredPosition.y=H),f&&p&&E.sizeDelta[d]!==y&&(E.sizeDelta[d]=y),g&&u&&E.sizeDelta[s]!==k&&(E.sizeDelta[s]=k);const F=h?E.width:E.height,I=F*.5;if(_+=I,g){const te=k*D-k*.5;te>_&&(_=te-k*.5+F+this.padding.left,_-=I)}let Y=_;s==="y"&&(Y=-Y),E.anchoredPosition[s]!==Y&&(E.anchoredPosition[s]=Y),_+=I,_+=this.spacing,D+=1}}}}it([m()],Qo.prototype,"childControlHeight"),it([m()],Qo.prototype,"childControlWidth"),it([m()],Qo.prototype,"childForceExpandHeight"),it([m()],Qo.prototype,"childForceExpandWidth"),it([m()],Qo.prototype,"childScaleHeight"),it([m()],Qo.prototype,"childScaleWidth");class ay extends Qo{get primaryAxis(){return"y"}}class ly extends Qo{get primaryAxis(){return"x"}}class cy extends Wi{onCalculateLayout(){}}var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,mn=(n,e,t,s)=>{for(var o=s>1?void 0:s?WA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NA(e,t,o),o},sS=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(sS||{});const hy=C("debuguilayout"),cs=class kC extends rh{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var e,t,s,o;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),(o=this.shadowComponent)==null||o.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(nb,this.context))}),a(this,"onAfterRenderRoutine",()=>{var e,t,s,o,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(s=this.previousParent)==null||s.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(o=this.shadowComponent)==null||o.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(nb,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}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)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof kC||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,hy&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,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)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}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 Ql(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);hy&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(Wi)),(t.isDirty||s!=null&&s.isDirty)&&(hy&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Oe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Lu(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,ps))Lu(e.shadowComponent,this)}}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,s=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(s=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(s=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const o=s+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-o,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Rs);let l=!1;r.sizeDelta.x!==this.context.domWidth&&(l=!0),r.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=t.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(o);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};mn([m()],cs.prototype,"renderOnTop",1),mn([m()],cs.prototype,"depthWrite",1),mn([m()],cs.prototype,"doubleSided",1),mn([m()],cs.prototype,"castShadows",1),mn([m()],cs.prototype,"receiveShadows",1),mn([m()],cs.prototype,"renderMode",1),mn([m(cs)],cs.prototype,"rootCanvas",1),mn([m()],cs.prototype,"scaleFactor",1),mn([m(hi)],cs.prototype,"worldCamera",2),mn([m()],cs.prototype,"planeDistance",2);let wl=cs;var VA=Object.defineProperty,$A=Object.getOwnPropertyDescriptor,dy=(n,e,t,s)=>{for(var o=s>1?void 0:s?$A(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&VA(e,t,o),o};class Yo extends j{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Oe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,ps,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}dy([m()],Yo.prototype,"alpha",1),dy([m()],Yo.prototype,"interactable",2),dy([m()],Yo.prototype,"blocksRaycasts",2);class uy{get extensionName(){return"tmui"}onExportObject(e,t,s){const o=P.getComponent(e,wl);if(o&&o.enabled&&o.renderMode===sS.WorldSpace){const r=new Op,l=P.getComponent(e,Rs),c=P.getComponent(e,Yo),h=new Array;if(l){if(!P.isActiveSelf(e)){const p=P.isActiveSelf(e);P.setActive(e,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(e,p)})}e.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const f=P.getComponent(p,ps);f&&(f.onEnable(),h.push(()=>{f.onDisable()}));const y=P.getComponent(p,Rs);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),h.push(()=>{y.onDisable()}));const v=P.getComponent(p,Wt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=gi.createEmpty(),u=l.shadowComponent;if(t.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,f=new Map;g.set(u,d),f.set(u,c?c.alpha:1),u.traverse(y=>{if(y===u)return;const v=gi.createEmpty();v.setMatrix(y.matrix);const b=y.parent,_=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let w=f.get(b)||1;const x=P.getComponent(y,Yo);if(x&&(w*=x.alpha),y instanceof q&&_){const M=y[Ri];M?r.exportText(M.gameObject,v,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof q&&!_){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new re,D=y.material.opacity;T.copy(y.material.color),v.material=new Me({color:T,opacity:D*w,map:y.material.map,transparent:!0})}g.set(y,v),f.set(y,w);const k=g.get(b);if(!k){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}k.add(v)})}}for(const d of h)d()}}flipWindingOrder(e){const t=e.index.array;for(let s=0,o=t.length/3;s<o;s++){const r=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=r}e.index.needsUpdate=!0}}const dh=C("debugusdz");function HA(n,e){var t;const s=[],o=P.getComponentsInChildren(n,Rt),r=P.getComponentsInChildren(n,Ut),l=new Array,c=new Array;if(e.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((t=d.motion.clip.tracks)==null?void 0:t.length)<1||l.includes(h))continue;const u=new eh;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new A;P.addComponent(p,u),c.push(p),l.push(h),n.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;dh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){dh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}s.push({root:h.gameObject,clips:d})}if(e.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new eh;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new A;P.addComponent(u,d),c.push(u),l.push(h),n.add(u)}else for(const h of r){dh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);s.push({root:h.gameObject,clips:d})}dh&&s?.length>0&&console.log("USDZ Animation Clips without behaviours",s);for(const h of s)for(const d of h.clips)e.registerAnimation(h.root,d);return c}function GA(n,e){const t=P.getComponentsInChildren(n,ns),s=P.getComponentsInChildren(n,Wo),o=new Array,r=new Array;dh&&console.log({audioSources:t,playAudioOnClicks:s});for(const l of s){if(!l.target)continue;const c=t.indexOf(l.target);c>-1&&t.splice(c,1)}for(const l of t){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Wo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new A;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),n.add(h)}return r}function qA(n){return new ei("DisableAtStart",At.sceneStartTrigger(),ve.fadeAction(n,0,!1))}function nS(n,e){const t=n.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const s=document.createElement("div");s.classList.add("menu"),s.classList.add("quicklook-menu"),s.style.display="none",s.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",e?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),s.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",s.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),n.domElement.shadowRoot.appendChild(s),r}var XA=Object.defineProperty,It=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&XA(e,t,o),o};const Vi=C("debugusdz"),QA=C("debugusdzpruning");class Jr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}It([m()],Jr.prototype,"callToAction"),It([m()],Jr.prototype,"checkoutTitle"),It([m()],Jr.prototype,"checkoutSubtitle"),It([m()],Jr.prototype,"callToActionURL");var xl;const yi=(xl=class extends j{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",n=>{n.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new S),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new S)}start(){var n,e,t;Vi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=Q.supportsQuickLookAR(),t=Q.isiOS()||Q.isiPad();!this.button&&(Vi||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=nS(this.context,e),this.link.addEventListener("message",this.lastCallback)),Vi&&De("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),hc.registerExporter(this)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Vi&&De("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement),hc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+b1(),Zs()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=nS(this.context,Q.supportsQuickLookAR())),this.customUsdzFile)return Vi&&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;const t=await this.export(this.objectToExport);return t?(Vi&&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(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(s=>(this._currentExportTasks.delete(n),s)).catch(s=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",s),null))):t}async internalExport(n){de.start("export-usdz",{onProgress:x=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:x}}))}}),de.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),de.report("export-usdz",{message:"Load progressive textures",autoStep:5}),de.start("export-usdz-textures","export-usdz");const e=P.getComponentsInChildren(n,fi);for(const x of e)x&&x.enabled&&x.updateSprite(!0);const t=P.getComponentsInChildren(n,Ui),s=new Array;let o=0;for(const x of t){for(const k of x.sharedMeshes)if(k){const M=Xe.assignMeshLOD(k,0);M instanceof Promise&&s.push(new Promise((T,D)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:s.length}),T()}).catch(z=>D(z))}))}for(const k of x.sharedMaterials)if(k){const M=Xe.assignTextureLOD(k,0);M instanceof Promise&&s.push(new Promise((T,D)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:s.length}),T()}).catch(z=>D(z))}))}}Vi&&De("Progressive Loading: "+s.length),await Promise.all(s),Vi&&De("Progressive Loading: done"),de.end("export-usdz-textures");const r=Di.Global.Mask;Di.Global.Set(rn.AR);const l=new P1,c=new up(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new ey),d.push(new _a),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(n,dt).length>0&&(this.physics?(h=new ty,d.push(h)):B()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Op),d.push(new uy));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:n};de.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,de.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...HA(n,c)),u.find(x=>x.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...GA(n)),l.debug=Vi,l.pruneUnusedNodes=!QA;const f=ep.instance.objs.map(x=>x.batchedMesh);l.keepObject=x=>{let k=!0;const M=P.getComponent(x,Ui);return M&&!M.enabled&&(k=!1),k&&f.includes(x)&&(k=!1),k&&P.getComponentInParent(x,$c)&&(k=!1),k&&P.getComponentInParent(x,en)&&(k=!1),Vi&&!k&&console.log("USDZExporter: Discarding object",x),k},l.beforeWritingDocument=()=>{if(B()&&c&&h){const x=c.animatedRoots;for(const k of x){const M=P.getComponentsInChildren(k,dt).filter(D=>D.enabled),T=P.getComponents(k,pi).filter(D=>D.enabled&&!D.isTrigger);(M.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(x=>{x.visible||y.push(x)});const v=u.find(x=>x.extensionName==="Behaviour");this.interactive&&v&&y.length>0&&v.addBehavior(qA(y));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),de.report("export-usdz","Invoking exporter.parse");const _=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,de.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const x of g)P.destroy(x);return Di.Global.Set(r),de.end("export-usdz"),w}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,s=this.buildQuicklookOverlay();Vi&&console.log("QuickLook Overlay",s);const o=s.callToAction?encodeURIComponent(s.callToAction):"",r=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",l=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){xl.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Vi&&be("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Vi&&De("Quicklook url: "+s),s&&(Zs()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,e,t,s,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),Zs()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((n=l.callToAction)==null?void 0:n.length)||((e=l.checkoutTitle)==null?void 0:e.length)||((t=l.checkoutSubtitle)==null?void 0:t.length))&&((s=l.callToAction)!=null&&s.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const n=P.findObjectOfType(xp);let e=P.getComponentInParent(this.objectToExport,Vo);e||(e=P.getComponentInChildren(this.objectToExport,Vo));let t=1,s=!1;const o=this.objectToExport;return n?t=n.arScale:e&&(t=e.arScale,s=e.invertForward),{scale:1/t,_invertForward:s,target:o,sessionRoot:e?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:s}=this.getARScaleAndTarget(),o=s?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(xl.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),s&&o&&t.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=gl.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},a(xl,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(xl,"invertForwardQuaternion",new V().setFromEuler(new Bt(0,Math.PI,0))),xl);It([m(A)],yi.prototype,"objectToExport"),It([m()],yi.prototype,"autoExportAnimations"),It([m()],yi.prototype,"autoExportAudioSources"),It([m()],yi.prototype,"exportFileName"),It([m(URL)],yi.prototype,"customUsdzFile"),It([m(Jr)],yi.prototype,"customBranding"),It([m()],yi.prototype,"anchoringType"),It([m()],yi.prototype,"maxTextureSize"),It([m()],yi.prototype,"planeAnchoringAlignment"),It([m()],yi.prototype,"interactive"),It([m()],yi.prototype,"physics"),It([m()],yi.prototype,"allowCreateQuicklookButton"),It([m()],yi.prototype,"quickLookCompatible");let gn=yi;var YA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,py=(n,e,t,s)=>{for(var o=KA(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YA(e,t,o),o};class Sl extends j{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Av(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}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}py([m()],Sl.prototype,"near"),py([m()],Sl.prototype,"far"),py([m(re)],Sl.prototype,"color");var ZA=Object.defineProperty,my=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&ZA(e,t,o),o};class ea extends j{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!vc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new RP(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=$g(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Oe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}my([m()],ea.prototype,"objectBounds"),my([m(re)],ea.prototype,"color"),my([m()],ea.prototype,"isGizmo");var JA=Object.defineProperty,gy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&JA(e,t,o),o};class Cl extends j{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!vc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Rm(e,t,this.color0??new re(.4,.4,.4),this.color1??new re(.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)}}gy([m()],Cl.prototype,"isGizmo"),gy([m(re)],Cl.prototype,"color0"),gy([m(re)],Cl.prototype,"color1");var e2=Object.defineProperty,fy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&e2(e,t,o),o};class yy extends j{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(dt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}fy([m(dt)],yy.prototype,"connectedBody");class vy extends yy{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class uh extends yy{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}fy([m(S)],uh.prototype,"anchor"),fy([m(S)],uh.prototype,"axis");var t2=Object.defineProperty,i2=Object.getOwnPropertyDescriptor,fn=(n,e,t,s)=>{for(var o=s>1?void 0:s?i2(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&t2(e,t,o),o};function by(n){return n*Math.PI/180}const oS=300,Ko=C("debuglights");class vi extends j{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new re(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var t,s;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.camera)!==void 0)){const o=this.light.shadow.camera;o.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var t,s;e!==this._shadowBias&&(this._shadowBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var t,s;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var t;if(this._intensity=e,this.light){let s=1;if(this.context.isInXR&&this._webARRoot){const o=(t=this._webARRoot)==null?void 0:t.arScale;typeof o=="number"&&o>0&&(s/=o)}this.light.intensity=e*s}Ko&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t!=null&&t.shadow){const s=t.shadow.camera;s.far=e,s.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t!=null&&t.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!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}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new re(this.color??16777215),Ko&&console.log(this.name,this)}onEnable(){Ko&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ko&&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(),Oe.LateUpdate))}onDisable(){Ko&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=P.getComponentInParent(this.gameObject,Vo)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new Tm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-oS*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),vr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ko){const l=new EP(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const s=new TP(this.color,this.intensity*Math.PI,this.range,by(this.spotAngle/2),1-by(this.innerSpotAngle/2)/by(this.spotAngle/2),2);s.position.set(0,0,0),s.rotation.set(0,0,0),this.light=s;const o=s.target;s.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Em(this.color,this.intensity*Math.PI,this.range);this.light=r;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),Ko&&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=oS*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 s=this.gameObject.scale.x;t.left*=s,t.right*=s}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const s=this.gameObject.scale.y;t.top*=s,t.bottom*=s}this.light.shadow.needsUpdate=!0,Ko&&this.context.scene.add(new AP(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}}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)}}a(vi,"allowChangingRendererShadowMapType",!0),fn([m()],vi.prototype,"type",2),fn([m(re)],vi.prototype,"color",1),fn([m()],vi.prototype,"shadowNearPlane",1),fn([m()],vi.prototype,"shadowBias",1),fn([m()],vi.prototype,"shadowNormalBias",1),fn([m()],vi.prototype,"shadows",1),fn([m()],vi.prototype,"lightmapBakeType",2),fn([m()],vi.prototype,"intensity",1),fn([m()],vi.prototype,"shadowDistance",1),fn([m()],vi.prototype,"shadowResolution",1),new S(0,0,0);var s2=Object.defineProperty,ph=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&s2(e,t,o),o};const _y=C("debuglods"),n2=C("nolods");class Pl{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}ph([m()],Pl.prototype,"screenRelativeTransitionHeight"),ph([m()],Pl.prototype,"distance"),ph([m(Ui)],Pl.prototype,"renderers");class o2{constructor(e){a(this,"model"),this.model=e}get renderers(){return this.model.renderers}}class mh extends j{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(_y&&console.log("LODGROUP",this.name,this.lodModels,this),!n2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const s of this.lodModels){const o=new o2(s);this._lods.push(o);for(const r of o.renderers)e.includes(r)||e.push(r)}this._lodsHandler=new Array;for(let s=0;s<e.length;s++){const o=new IP;this._lodsHandler.push(o),this.gameObject.add(o)}const t=new A;t.name="Cull "+this.name;for(let s=0;s<e.length;s++){const o=e[s],r=this._lodsHandler[s],l=o.gameObject;_y&&console.log(s,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=t,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}_y&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.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 s=t.getCurrentLevel(),o=t.levels[s];t.layers.mask=o.object.layers.mask}}onAddLodLevel(e,t,s){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,s*this._distanceFactor,.01);const o={lod:e,levelIndex:e.levels.length-1,distance:s};this._settings.push(o)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const s=t.lod.levels[t.levelIndex];s.distance=t.distance*e}}}}ph([m(S)],mh.prototype,"localReferencePoint"),ph([m(Pl)],mh.prototype,"lodModels");var r2=Object.defineProperty,a2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&r2(e,t,o),o};const kp=C("debugnestedgltf");class Mp extends j{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var t;(t=this.filePath)==null||t.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var e,t,s,o,r;if(this._isLoadingOrDoneLoading)return;kp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Bs;c.idProvider=new Dt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;kp&&console.log("Load nested:",((e=this.filePath)==null?void 0:e.url)??this.filePath,this.gameObject.position);const d=await((s=(t=this.filePath)==null?void 0:t.instantiate)==null?void 0:s.call(this.filePath,c));kp&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),kp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}a2([m(ce)],Mp.prototype,"filePath");var l2=Object.defineProperty,wy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&l2(e,t,o),o};const c2=C("debugnet"),Rp=class Pv extends j{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){c2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Pv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const s=C(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t!=null&&t.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let s=e;const o=Pv.IsLocalNetwork()&&t;if(o&&(s=t),e!=null&&e.startsWith("/")){const r=o?s:window.location.origin;r!=null&&r.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),s=r+e}return s}static IsLocalNetwork(e=window.location.hostname){return Xt(e)}};wy([m()],Rp.prototype,"url"),wy([m()],Rp.prototype,"urlParameterName"),wy([m()],Rp.prototype,"localhost");let xy=Rp;var h2=Object.defineProperty,Tp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&h2(e,t,o),o};class ta extends j{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new S(0,0,0)),a(this,"rotationOffset",new S(0,0,0)),a(this,"offset",new S(0,0,0))}update(){if(!this.from)return;var e=ee(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const s=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(s),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new fr(this.gameObject.up,0),h=ee(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new S(0,0,0);c.projectPoint(e,d),e.copy(d)}this.affectPosition&<(this.gameObject,e);const o=new Bt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Yi(this.gameObject,t.multiply(r));const l=new S;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Tp([m(P)],ta.prototype,"referenceSpace"),Tp([m(P)],ta.prototype,"from"),Tp([m(S)],ta.prototype,"positionOffset"),Tp([m(S)],ta.prototype,"rotationOffset");var d2=Object.defineProperty,Zo=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&d2(e,t,o),o};class bi{constructor(e=0,t=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=e,this.value=t}}Zo([m()],bi.prototype,"time"),Zo([m()],bi.prototype,"value"),Zo([m()],bi.prototype,"inTangent"),Zo([m()],bi.prototype,"inWeight"),Zo([m()],bi.prototype,"outTangent"),Zo([m()],bi.prototype,"outWeight"),Zo([m()],bi.prototype,"weightedMode");const rS=class ad{constructor(){a(this,"keys",[])}static linearFromTo(e,t,s){const o=new ad,r=new bi;r.time=0,r.value=e;const l=new bi;return l.time=s,l.value=t,o.keys.push(r,l),o}static constant(e){const t=new ad,s=new bi;return s.time=0,s.value=e,t.keys.push(s),t}clone(){var e;const t=new ad;return t.keys=((e=this.keys)==null?void 0:e.map(s=>{const o=new bi;return o.time=s.time,o.value=s.value,o.inTangent=s.inTangent,o.inWeight=s.inWeight,o.outTangent=s.outTangent,o.outWeight=s.outWeight,o.weightedMode=s.weightedMode,o}))||[],t}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 s=this.keys[t];if(s.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(s.outTangent)||!isFinite(o.inTangent)?s.value:ad.interpolateValue(e,s,o)}else return s.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,s){const o=t.time,r=t.value,l=t.outTangent,c=s.time,h=s.value,d=s.inTangent,u=c-o,p=u*u,g=p*u,f=((l+d)*u-2*(h-r))/g,y=(3*(h-r)-(d+2*l)*u)/p,v=l,b=r,_=e-o,w=_*_,x=w*_;return f*x+y*w+v*_+b}};Zo([m(bi)],rS.prototype,"keys");let gh=rS;var u2=Object.defineProperty,O=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&u2(e,t,o),o};const Ep=C("debugparticles");var Jn=(n=>(n[n.Billboard=0]="Billboard",n[n.Stretch=1]="Stretch",n[n.HorizontalBillboard=2]="HorizontalBillboard",n[n.VerticalBillboard=3]="VerticalBillboard",n[n.Mesh=4]="Mesh",n))(Jn||{});class ia{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(e,t){let s,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<e||!s)&&(s=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<e||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(e,r.time,c.time,0,1);t.r=W.lerp(r.color.r,c.color.r,h),t.g=W.lerp(r.color.g,c.color.g,h),t.b=W.lerp(r.color.b,c.color.b,h)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(s)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(e,s.time,c.time,0,1);t.alpha=W.lerp(s.alpha,c.alpha,h)}else t.alpha=s.alpha;return t}}O([m()],ia.prototype,"alphaKeys"),O([m()],ia.prototype,"colorKeys");var fh=(n=>(n[n.Local=0]="Local",n[n.World=1]="World",n[n.Custom=2]="Custom",n))(fh||{}),Ap=(n=>(n[n.Sphere=0]="Sphere",n[n.SphereShell=1]="SphereShell",n[n.Hemisphere=2]="Hemisphere",n[n.HemisphereShell=3]="HemisphereShell",n[n.Cone=4]="Cone",n[n.Box=5]="Box",n[n.Mesh=6]="Mesh",n[n.ConeShell=7]="ConeShell",n[n.ConeVolume=8]="ConeVolume",n[n.ConeVolumeShell=9]="ConeVolumeShell",n[n.Circle=10]="Circle",n[n.CircleEdge=11]="CircleEdge",n[n.SingleSidedEdge=12]="SingleSidedEdge",n[n.MeshRenderer=13]="MeshRenderer",n[n.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",n[n.BoxShell=15]="BoxShell",n[n.BoxEdge=16]="BoxEdge",n[n.Donut=17]="Donut",n[n.Rectangle=18]="Rectangle",n[n.Sprite=19]="Sprite",n[n.SpriteRenderer=20]="SpriteRenderer",n))(Ap||{});const eo=class ld{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(e){const t=new ld;return t.setConstant(e),t}static betweenTwoConstants(e,t){const s=new ld;return s.setMinMaxConstant(e,t),s}static curve(e,t=1){const s=new ld;return s.setCurve(e,t),s}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}clone(){var e,t,s;const o=new ld;return o.mode=this.mode,o.constant=this.constant,o.constantMin=this.constantMin,o.constantMax=this.constantMax,o.curve=(e=this.curve)==null?void 0:e.clone(),o.curveMin=(t=this.curveMin)==null?void 0:t.clone(),o.curveMax=(s=this.curveMax)==null?void 0:s.clone(),o.curveMultiplier=this.curveMultiplier,o}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=W.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const o=e*this.curveMin.duration,r=e*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(o),this.curveMax.evaluate(r),s%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,s%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 s=0;s<e.keys.length;s++){const o=e.keys[s];o.value>t&&(t=o.value)}return t}};O([m()],eo.prototype,"mode"),O([m()],eo.prototype,"constant"),O([m()],eo.prototype,"constantMin"),O([m()],eo.prototype,"constantMax"),O([m(gh)],eo.prototype,"curve"),O([m(gh)],eo.prototype,"curveMin"),O([m(gh)],eo.prototype,"curveMax"),O([m()],eo.prototype,"curveMultiplier");let Z=eo;var st;const Jo=(st=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(n){const e=new st;return e.constant(n),e}static betweenTwoColors(n,e){const t=new st;return t.betweenTwoColors(n,e),t}constant(n){return this.mode=0,this.color=n,this}betweenTwoColors(n,e){return this.mode=2,this.colorMin=n,this.colorMax=e,this}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(n,st._temp),st._temp;case 2:case"TwoColors":return st._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:case"TwoGradients":return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,t);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,s)}return st._temp.set(16777215),st._temp.alpha=1,st._temp}},a(st,"_temp",new he(0,0,0,1)),a(st,"_temp2",new he(0,0,0,1)),st);O([m()],Jo.prototype,"mode"),O([m(he)],Jo.prototype,"color"),O([m(he)],Jo.prototype,"colorMin"),O([m(he)],Jo.prototype,"colorMax"),O([m(ia)],Jo.prototype,"gradient"),O([m(ia)],Jo.prototype,"gradientMin"),O([m(ia)],Jo.prototype,"gradientMax");let sa=Jo;var Sy=(n=>(n[n.Hierarchy=0]="Hierarchy",n[n.Local=1]="Local",n[n.Shape=2]="Shape",n))(Sy||{});class Vt{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}O([m(Z)],Vt.prototype,"gravityModifier"),O([m(sa)],Vt.prototype,"startColor"),O([m(Z)],Vt.prototype,"startDelay"),O([m(Z)],Vt.prototype,"startLifetime"),O([m(Z)],Vt.prototype,"startRotation"),O([m(Z)],Vt.prototype,"startRotationX"),O([m(Z)],Vt.prototype,"startRotationY"),O([m(Z)],Vt.prototype,"startRotationZ"),O([m(Z)],Vt.prototype,"startSize"),O([m(Z)],Vt.prototype,"startSizeX"),O([m(Z)],Vt.prototype,"startSizeY"),O([m(Z)],Vt.prototype,"startSizeZ"),O([m(Z)],Vt.prototype,"startSpeed");class Ip{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_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 s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();t=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return t}}class to{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];this.system.main.loop&&s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}O([m()],to.prototype,"enabled"),O([m()],to.prototype,"bursts"),O([m(Z)],to.prototype,"rateOverTime"),O([m()],to.prototype,"rateOverTimeMultiplier"),O([m(Z)],to.prototype,"rateOverDistance"),O([m()],to.prototype,"rateOverDistanceMultiplier");class Lp{constructor(){a(this,"enabled"),a(this,"color")}}O([m(sa)],Lp.prototype,"color");class na{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new S)}evaluate(e,t,s){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,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const o=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=o}return t}}O([m(Z)],na.prototype,"size"),O([m(Z)],na.prototype,"x"),O([m(Z)],na.prototype,"y"),O([m(Z)],na.prototype,"z");var er;const nt=(er=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Bt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new S(0,0,0)),a(this,"_temp",new S(0,0,0)),a(this,"_triangle",new LP),a(this,"_dir",new S),a(this,"_loopTime",0),a(this,"_loopDirection",1),Ep&&console.log(this)}get type(){return Ap[this.shapeType]}initialize(n){this.onInitialize(n),n.position.x=this._vector.x,n.position.y=this._vector.y,n.position.z=this._vector.z}toJSON(){return this}clone(){return new er}setMesh(n){this.meshRenderer=n,n?(this._meshObj=n.sharedMeshes[Math.floor(Math.random()*n.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(n,e){}onUpdate(n,e,t,s){this.system=n,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(n){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",n.applyEuler(this._rotation)),e}onInitialize(n){this._vector.set(0,0,0),n.mesh=void 0,n.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let s=this.radius;if(t&&(s*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Ep&&G.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(e);break;case 4:this.randomConePoint(this.position,this.angle,s,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=n.mesh=this._meshObj,l=n.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,f=u*3+2;p=c.getX(p),g=c.getX(g),f=c.getX(f);const y=l.getAttribute("position");this._triangle.a.fromBufferAttribute(y,p),this._triangle.b.fromBufferAttribute(y,g),this._triangle.c.fromBufferAttribute(y,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),B()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ap[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Ep&&G.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(n,e){var 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 s=e.x,o=e.y,r=e.z;this._dir.set(s,o,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=n.mesh,c=n.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=n.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=n.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),f=c.getAttribute("position"),y=X(),v=X(),b=X();y.fromBufferAttribute(f,u),v.fromBufferAttribute(f,p),b.fromBufferAttribute(f,g),y.sub(v),b.sub(v),y.cross(b),this._dir.copy(y).multiplyScalar(-1);const _=Se(l);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),Ep&&(G.DrawSphere(e,.01,8925952,.5,!0),G.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(n,e){if(e<=0)return;const t=er._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,n.add(t)}randomizeDirection(n,e){if(e===0)return;const t=er._randomQuat,s=er._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),n.applyQuaternion(t)}spherizeDirection(n,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),o=Math.sin(s)*Math.cos(t),r=Math.sin(s)*Math.sin(t),l=Math.cos(s),c=new S(o,r,l);n.lerp(c,e)}randomSpherePoint(n,e,t,s,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(s/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=n.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=n.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=n.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(n,e,t,s,o){const r=Math.random(),l=2*Math.PI*r*(s/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=n.x+this.scale.x*c*Math.cos(l),d=n.y+this.scale.y*c*Math.sin(l),u=n.z;o.x=h,o.y=d,o.z=u}randomConePoint(n,e,t,s,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,g=n.x+-p*Math.sin(u)*Math.cos(d),f=n.y+p*Math.sin(u)*Math.sin(d),y=n.z;l.x=g*this.scale.x,l.y=f*this.scale.y,l.z=y*this.scale.z}},a(er,"_randomQuat",new V),a(er,"_tempVec",new S),er);O([m()],nt.prototype,"shapeType"),O([m()],nt.prototype,"enabled"),O([m()],nt.prototype,"alignToDirection"),O([m()],nt.prototype,"angle"),O([m()],nt.prototype,"arc"),O([m()],nt.prototype,"arcSpread"),O([m()],nt.prototype,"arcSpeedMultiplier"),O([m()],nt.prototype,"arcMode"),O([m(S)],nt.prototype,"boxThickness"),O([m(S)],nt.prototype,"position"),O([m(S)],nt.prototype,"rotation"),O([m(S)],nt.prototype,"scale"),O([m()],nt.prototype,"radius"),O([m()],nt.prototype,"radiusThickness"),O([m()],nt.prototype,"sphericalDirectionAmount"),O([m()],nt.prototype,"randomDirectionAmount"),O([m()],nt.prototype,"randomPositionAmount"),O([m()],nt.prototype,"meshShapeType"),O([m(Yc)],nt.prototype,"meshRenderer");let Cy=nt;class Ce{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,o,r,l){if(!this.enabled)return;this._noise||(this._noise=bO(()=>0));const c=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}O([m()],Ce.prototype,"damping"),O([m()],Ce.prototype,"enabled"),O([m()],Ce.prototype,"frequency"),O([m()],Ce.prototype,"octaveCount"),O([m()],Ce.prototype,"octaveMultiplier"),O([m()],Ce.prototype,"octaveScale"),O([m(Z)],Ce.prototype,"positionAmount"),O([m()],Ce.prototype,"quality"),O([m(Z)],Ce.prototype,"remap"),O([m()],Ce.prototype,"remapEnabled"),O([m()],Ce.prototype,"remapMultiplier"),O([m(Z)],Ce.prototype,"remapX"),O([m()],Ce.prototype,"remapXMultiplier"),O([m(Z)],Ce.prototype,"remapY"),O([m()],Ce.prototype,"remapYMultiplier"),O([m(Z)],Ce.prototype,"remapZ"),O([m()],Ce.prototype,"remapZMultiplier"),O([m()],Ce.prototype,"scrollSpeedMultiplier"),O([m()],Ce.prototype,"separateAxes"),O([m()],Ce.prototype,"strengthMultiplier"),O([m(Z)],Ce.prototype,"strengthX"),O([m()],Ce.prototype,"strengthXMultiplier"),O([m(Z)],Ce.prototype,"strengthY"),O([m()],Ce.prototype,"strengthYMultiplier"),O([m(Z)],Ce.prototype,"strengthZ"),O([m()],Ce.prototype,"strengthZMultiplier");class We{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(e,t,s,o){const r=this.widthOverTrail.evaluate(s,o);return e*=r,e}getColor(e,t,s){const o=this.colorOverTrail.evaluate(s),r=this.colorOverLifetime.evaluate(t);e.x*=o.r*r.r,e.y*=o.g*r.g,e.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(e.w*=o.alpha*r.alpha)}}O([m()],We.prototype,"enabled"),O([m()],We.prototype,"attachRibbonToTransform"),O([m(sa)],We.prototype,"colorOverLifetime"),O([m(sa)],We.prototype,"colorOverTrail"),O([m()],We.prototype,"dieWithParticles"),O([m()],We.prototype,"inheritParticleColor"),O([m(Z)],We.prototype,"lifetime"),O([m()],We.prototype,"lifetimeMultiplier"),O([m()],We.prototype,"minVertexDistance"),O([m()],We.prototype,"mode"),O([m()],We.prototype,"ratio"),O([m()],We.prototype,"ribbonCount"),O([m()],We.prototype,"shadowBias"),O([m()],We.prototype,"sizeAffectsLifetime"),O([m()],We.prototype,"sizeAffectsWidth"),O([m()],We.prototype,"splitSubEmitterRibbons"),O([m()],We.prototype,"textureMode"),O([m(Z)],We.prototype,"widthOverTrail"),O([m()],We.prototype,"widthOverTrailMultiplier"),O([m()],We.prototype,"worldSpace");class qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new S),a(this,"_temp2",new S),a(this,"_temp3",new S),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new ne)}update(e){this._system=e}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,s,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),f=this.z.evaluate(d);if(this._temp.set(-p,g,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const y=this._temp2.set(s.x,s.y,s.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,_=this.orbitalZMultiplier,w=u*Math.PI*2*10,x=Math.cos(w*v),k=Math.sin(w*v),M=Math.cos(w*b),T=Math.sin(w*b),D=Math.cos(w*_),z=Math.sin(w*_),U=y.x*(M*D)+y.y*(M*z)+y.z*-T,E=y.x*(k*T*D-x*z)+y.y*(k*T*z+x*D)+y.z*(k*M),$=y.x*(x*T*D+k*z)+y.y*(x*T*z-k*D)+y.z*(x*M),H=this._temp3.set(y.x-U,y.y-E,y.z-$);H.normalize(),H.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=H.x,o.y+=H.y,o.z+=H.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}O([m()],qe.prototype,"enabled"),O([m()],qe.prototype,"space"),O([m(Z)],qe.prototype,"orbitalX"),O([m(Z)],qe.prototype,"orbitalY"),O([m(Z)],qe.prototype,"orbitalZ"),O([m()],qe.prototype,"orbitalXMultiplier"),O([m()],qe.prototype,"orbitalYMultiplier"),O([m()],qe.prototype,"orbitalZMultiplier"),O([m()],qe.prototype,"orbitalOffsetX"),O([m()],qe.prototype,"orbitalOffsetY"),O([m()],qe.prototype,"orbitalOffsetZ"),O([m(Z)],qe.prototype,"speedModifier"),O([m()],qe.prototype,"speedModifierMultiplier"),O([m(Z)],qe.prototype,"x"),O([m()],qe.prototype,"xMultiplier"),O([m(Z)],qe.prototype,"y"),O([m()],qe.prototype,"yMultiplier"),O([m(Z)],qe.prototype,"z"),O([m()],qe.prototype,"zMultiplier");class $t{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"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 s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}O([m()],$t.prototype,"animation"),O([m()],$t.prototype,"enabled"),O([m()],$t.prototype,"cycleCount"),O([m(Z)],$t.prototype,"frameOverTime"),O([m()],$t.prototype,"frameOverTimeMultiplier"),O([m()],$t.prototype,"numTilesX"),O([m()],$t.prototype,"numTilesY"),O([m(Z)],$t.prototype,"startFrame"),O([m()],$t.prototype,"startFrameMultiplier"),O([m()],$t.prototype,"rowMode"),O([m()],$t.prototype,"rowIndex"),O([m()],$t.prototype,"spriteCount"),O([m()],$t.prototype,"timeMode");class Ts{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}O([m()],Ts.prototype,"enabled"),O([m()],Ts.prototype,"separateAxes"),O([m(Z)],Ts.prototype,"x"),O([m()],Ts.prototype,"xMultiplier"),O([m(Z)],Ts.prototype,"y"),O([m()],Ts.prototype,"yMultiplier"),O([m(Z)],Ts.prototype,"z"),O([m()],Ts.prototype,"zMultiplier");class hs{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=W.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}O([m()],hs.prototype,"enabled"),O([m()],hs.prototype,"range"),O([m()],hs.prototype,"separateAxes"),O([m(Z)],hs.prototype,"x"),O([m()],hs.prototype,"xMultiplier"),O([m(Z)],hs.prototype,"y"),O([m()],hs.prototype,"yMultiplier"),O([m(Z)],hs.prototype,"z"),O([m()],hs.prototype,"zMultiplier");class gt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new S),a(this,"_temp2",new S)}apply(e,t,s,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>h){this._temp.copy(t).normalize().multiplyScalar(h);const d=this.dampen*.5;t.x=W.lerp(t.x,this._temp.x,d),t.y=W.lerp(t.y,this._temp.y,d),t.z=W.lerp(t.z,this._temp.z,d),s.x=W.lerp(s.x,this._temp.x,d),s.y=W.lerp(s.y,this._temp.y,d),s.z=W.lerp(s.z,this._temp.z,d)}}}}O([m()],gt.prototype,"enabled"),O([m()],gt.prototype,"dampen"),O([m(Z)],gt.prototype,"drag"),O([m()],gt.prototype,"dragMultiplier"),O([m(Z)],gt.prototype,"limit"),O([m()],gt.prototype,"limitMultiplier"),O([m()],gt.prototype,"separateAxes"),O([m(Z)],gt.prototype,"limitX"),O([m()],gt.prototype,"limitXMultiplier"),O([m(Z)],gt.prototype,"limitY"),O([m()],gt.prototype,"limitYMultiplier"),O([m(Z)],gt.prototype,"limitZ"),O([m()],gt.prototype,"limitZMultiplier"),O([m()],gt.prototype,"multiplyDragByParticleSize"),O([m()],gt.prototype,"multiplyDragByParticleVelocity"),O([m()],gt.prototype,"space");const yh=class MC{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new S),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var e;const t=new MC;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new S),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new S),this.system._iv_velocity}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}}applyCurrent(e,t,s){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const o=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(o),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};O([m()],yh.prototype,"enabled"),O([m(Z)],yh.prototype,"curve"),O([m()],yh.prototype,"curveMultiplier"),O([m()],yh.prototype,"mode");let Py=yh;class _i{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t,s,o){const r=e.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,s);return o.x*=c,o.y*=c,o.z*=c,o}}O([m()],_i.prototype,"enabled"),O([m(ie)],_i.prototype,"range"),O([m()],_i.prototype,"separateAxes"),O([m(Z)],_i.prototype,"size"),O([m()],_i.prototype,"sizeMultiplier"),O([m(Z)],_i.prototype,"x"),O([m()],_i.prototype,"xMultiplier"),O([m(Z)],_i.prototype,"y"),O([m()],_i.prototype,"yMultiplier"),O([m(Z)],_i.prototype,"z"),O([m()],_i.prototype,"zMultiplier");class Ol{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(e,t,s){const o=e.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,t);s.x*=l.r,s.y*=l.g,s.z*=l.b,"alpha"in l&&(s.w*=l.alpha)}}O([m()],Ol.prototype,"enabled"),O([m(ie)],Ol.prototype,"range"),O([m(sa)],Ol.prototype,"color"),new S(1,1,1),new S(0,0,1);class Oy{constructor(e,t,s,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new S),a(this,"v2_",new S),a(this,"_emitterMatrix",new Gm),a(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=s,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new ki(()=>new Gm,r)}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===ky.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===ky.Death){let o=e.life;if(e[kl]!==void 0&&(o=e[kl]),!(e.age+t*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const s=new Gm;s.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||s.multiplyMatrices(this._emitterMatrix,s),this.subParticleSystem.emit(t,e.emissionState,s)}}var p2=Object.defineProperty,Ve=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&p2(e,t,o),o};const tr=C("debugparticles"),m2=C("noprogressive"),g2=C("debugprogressive");var ky=(n=>(n[n.Birth=0]="Birth",n[n.Collision=1]="Collision",n[n.Death=2]="Death",n[n.Trigger=3]="Trigger",n[n.Manual=4]="Manual",n))(ky||{});class ds extends j{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&B()){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(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){tr&&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=On,t.map.premultiplyAlpha=!1);const s=new Me;s.copy(t),e?this.trailMaterial=s:this.particleMaterial=s}t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1),e&&t.side===yo&&(t=t.clone(),t.side=xd,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!m2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,g2&&console.log("Load material LOD",t.name),Xe.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof q&&(t=this.particleMesh.geometry),t===null)){t=new zs(1,1);const s=t.attributes.uv;for(let o=0;o<s.count;o++)s.setX(o,1-s.getX(o))}return new q(t,this.getMaterial())}}Ve([m()],ds.prototype,"renderMode"),Ve([m(Pe)],ds.prototype,"particleMaterial"),Ve([m(Pe)],ds.prototype,"trailMaterial"),Ve([m()],ds.prototype,"maxParticleSize"),Ve([m()],ds.prototype,"minParticleSize"),Ve([m()],ds.prototype,"velocityScale"),Ve([m()],ds.prototype,"cameraVelocityScale"),Ve([m()],ds.prototype,"lengthScale");class jp{constructor(e,t=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=e,this._factor=t}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 My{constructor(e){a(this,"type","value"),a(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}}class f2 extends My{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class y2 extends My{constructor(){super(...arguments),a(this,"_lastPosition",new S),a(this,"_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 o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const s=this.system.maxParticles-this.system.currentParticles;return W.clamp(e,0,s/this.system.deltaTime)}}class v2 extends My{genValue(){return this.system.isPlaying,0}}class ir{constructor(e){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class b2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(e,t){const s=this.system.textureSheetAnimation;if(s.enabled){const o=e.age/e.life,r=s.evaluate(o);r!==void 0&&(e.uvTile=r)}}}const aS=Symbol("particleRotation");class _2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(e){e[aS]=Math.random()}update(e,t){if(e.rotation===void 0)return;const s=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(s,e[aS])*t:this.system.renderer.renderMode===Jn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(s,o)*t}}}const lS=Symbol("sizeLerpFactor"),w2=new S;class x2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(e){e[lS]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const s=e.age/e.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(s,void 0,e[lS]).x);let r=1;this.system.renderer.renderMode!==Jn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=X(e.startSize).multiplyScalar(o*r);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=pS(this.system,w2);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const kl=Symbol("particleLife"),Ry=Symbol("trailLifetime"),cS=Symbol("trailStartLength"),Ty=Symbol("trailWidthRandom");class S2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(e){e instanceof eb&&(e[kl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Ry]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Ry]),e[cS]=e.length,e[Ty]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof eb){const s=e,o=e.age/e[kl],r=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=e.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,s[Ty]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,s[Ty]),h.color.copy(e.color),this.system.trails.getColor(h.color,o,d)}if(e.age>e[kl]){e.velocity.set(0,0,0);const c=(e.age-e[kl])/e[Ry];s.length=W.lerp(e[cS],0,c)}}}}const Dp=Symbol("startVelocity"),hS=Symbol("gravityModifier"),Ey=Symbol("gravitySpeed"),Bp=Symbol("velocity lerp factor"),Ay=new S;class C2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new S)}initialize(e){var t,s;const o=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(e,e.position);e.velocity.x=r.x*e.startSpeed,e.velocity.y=r.y*e.startSpeed,e.velocity.z=r.z*e.startSpeed,(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Dp]?e[Dp].copy(e.velocity):e[Dp]=e.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[hS]=l*o,e[Ey]=l*o*.5,e[Bp]=Math.random(),(s=this.system.velocityOverLifetime)==null||s.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===fh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var s;const o=e[Dp],r=e[hS];if(r!==0){const g=r*e[Ey];Ay.copy(this._gravityDirection).multiplyScalar(g),e[Ey]+=t*.05,o.add(Ay)}e.velocity.copy(o);const l=e.age/e.life;(s=this.system.inheritVelocity)!=null&&s.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,l,e[Bp]);const c=this.system.noise;c.enabled&&c.apply(0,e.position,e.velocity,t,e.age,e.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(e.size=h.evaluate(e.velocity,l,e[Bp],e.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(e.velocity,e[Bp],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(e.position,o,e.velocity,e.size,l,t,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const dS=Symbol("colorLerpFactor"),uS=new he(1,1,1,1),oa=new he(1,1,1,1);class P2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;oa.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(uS.copy(t.color),oa.multiply(uS)),oa.convertLinearToSRGB(),e.startColor.set(oa.r,oa.g,oa.b,oa.alpha),e.color.copy(e.startColor),e[dS]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const s=e.age/e.life,o=this.system.colorOverLifetime.color.evaluate(s,e[dS]);e.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class O2{constructor(e){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new CO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new y2(this.system)}get anim(){return this.system.textureSheetAnimation}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()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new jp(this.system.main.startLifetime)}get startSpeed(){return new jp(this.system.main.startSpeed)}get startRotation(){return new jp(this.system.main.startRotation)}get startSize(){return new jp(this.system.main.startSize)}get startColor(){return new xO(new SO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new v2(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Tn.Trail;switch(this.system.renderer.renderMode){case Jn.Billboard:return Tn.BillBoard;case Jn.Stretch:return Tn.StretchedBillBoard;case Jn.HorizontalBillboard:return Tn.HorizontalBillBoard;case Jn.VerticalBillboard:return Tn.VerticalBillBoard;case Jn.Mesh:return Tn.Mesh}return Tn.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Jn.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const s=t.clone();s.premultiplyAlpha=!1,s.colorSpace=On,this.clonedTexture.original=t,this.clonedTexture.clone=s}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Cf(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new f2(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??jP}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===fh.World}}class k2{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const Ht=class Pm extends j{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new S),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new S),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(e=!1){var t;e&&P.foreachComponent(this.gameObject,s=>{s instanceof Pm&&s!==this&&s.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Pm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,s=>{s instanceof Pm&&s!==this&&s.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new k2),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}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.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}get container(){return this._container}get worldspace(){return this.main.simulationSpace===fh.World}get localspace(){return this.main.simulationSpace===fh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}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 ir&&(e.system=this),tr&&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,s=t.indexOf(e);return s!==-1&&((B()||tr)&&console.debug("Remove custom ParticleSystem Behaviour",s,e),t.splice(s,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}set bursts(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Ip)){const o=new Ip;Na(o,s),e[t]=o}}this._bursts=e}set subEmitterSystems(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Fp)){const o=new Fp;Na(o,s),e[t]=o}}tr&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}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(ds),!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 A,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new _O,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new O2(this),this._particleSystem=new wO(this._interface),this._particleSystem.addBehavior(new x2(this)),this._particleSystem.addBehavior(new P2(this)),this._particleSystem.addBehavior(new b2(this)),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new C2(this)),this._particleSystem.addBehavior(new S2(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),tr&&(console.log(this),this.gameObject.add(new Pi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof q&&this._interface.renderMode==Tn.Mesh&&Xe.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Tn.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,t,s,o;(e=this._container)==null||e.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(s=this._particleSystem)==null||s.emitter.removeFromParent(),(o=this._particleSystem)==null||o.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(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var e;if(!((e=this.emission)!=null&&e.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,s=this.main.duration,o=this.main.startLifetime.getMax(),r=Math.min(Math.max(s,o)/Math.max(.01,this.main.simulationSpeed),1e3),l=Math.ceil(r/t),c=Date.now();tr&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${s}, Lifetime: ${o}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}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 s=this.layer;t.layers.mask=1<<s}}onUpdate(){var e,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const s=this.context.mainCamera;if(s){const l=Ge(s);this._cameraScale=l.x}const o=!this.worldspace,r=this.gameObject;if(Se(r,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ge(this.gameObject,this._worldScale),o&&this._container&&(e=this.gameObject)!=null&&e.parent){const l=pS(this,Ay);this._container.matrix.makeScale(l.x,l.y,l.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),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():B()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const s=(e=t.particleSystem)==null?void 0:e._particleSystem;if(s){t.particleSystem._isUsedAsSubsystem=!0;const o=new Oy(this,this._particleSystem,t.particleSystem,s);o.emitterType=t.type,o.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(o)}else tr&&console.warn("Could not add SubParticleSystem",t,this)}}};Ve([m(Lp)],Ht.prototype,"colorOverLifetime"),Ve([m(Vt)],Ht.prototype,"main"),Ve([m(to)],Ht.prototype,"emission"),Ve([m(na)],Ht.prototype,"sizeOverLifetime"),Ve([m(Cy)],Ht.prototype,"shape"),Ve([m(Ce)],Ht.prototype,"noise"),Ve([m(We)],Ht.prototype,"trails"),Ve([m(qe)],Ht.prototype,"velocityOverLifetime"),Ve([m(gt)],Ht.prototype,"limitVelocityOverLifetime"),Ve([m(Py)],Ht.prototype,"inheritVelocity"),Ve([m(Ol)],Ht.prototype,"colorBySpeed"),Ve([m($t)],Ht.prototype,"textureSheetAnimation"),Ve([m(Ts)],Ht.prototype,"rotationOverLifetime"),Ve([m(hs)],Ht.prototype,"rotationBySpeed"),Ve([m(_i)],Ht.prototype,"sizeBySpeed");let vh=Ht;class Fp{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(e,t){const s=this.particleSystem;if(s instanceof vh)return;let o="";s&&typeof s.guid=="string"&&(o=s.guid,this.particleSystem=P.findByGuid(o,t)),tr&&!(this.particleSystem instanceof vh)&&console.warn("Could not find particle system for sub emitter",o,t,this)}}function pS(n,e){if(e.set(1,1,1),n.gameObject.parent&&n.localspace)switch(n.main.scalingMode){case Sy.Local:e=Ge(n.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!n.unsupported_scaling_mode){n.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+Sy[n.main.scalingMode]+" is not supported";B()&&be(t),console.warn(t,n.name,n)}e=Ge(n.gameObject,e);break}return e}class Wl extends j{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const e=P.getComponentInParent(this.gameObject,ks);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,di);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(se.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(se.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield xf(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Wl.hashCode(e),s=Wl.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(s,e,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(s,e,r)}}assignColor(e,t,s){let o=s.material;o&&(o._playerMaterial!==t&&(o=o.clone(),o._playerMaterial=t,s.material=o),o.color=e)}static hashCode(e){var t=0,s,o;if(e.length===0)return t;for(s=0;s<e.length;s++)o=e.charCodeAt(s),t=(t<<5)-t+o,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,s=(e&65280)>>8,o=e&255;return new re(t/255,s/255,o/255)}}const bh=C("debugpost");let Iy=null;function M2(n){Iy=n}function mS(n){let e=n.gameObject;for(;e;){for(const t of du(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function R2(n){let e=mS(n);if(!e)if(Iy){bh&&console.warn("Adding postprocessing manager to the scene.");const t=n.scene;e=Ei(t,Iy)}else B()&&console.warn("No post processing manager found");return e}const ft={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 ot=null;function T2(n){bh==="verbose"&&console.debug("Before ordering effects",[...n]),ot||(ot=new Map,ot.set(L.POSTPROCESSING.MODULE.NormalPass,ft.NormalPass),ot.set(L.POSTPROCESSING.MODULE.DepthDownsamplingPass,ft.DepthDownsamplingPass),ot.set(L.POSTPROCESSING.MODULE.SMAAEffect,ft.SMAA),ot.set(L.POSTPROCESSING.MODULE.SSAOEffect,ft.SSAO),ot.set(L.POSTPROCESSING_AO.MODULE.N8AOPostPass,ft.SSAO),ot.set(L.POSTPROCESSING_AO.MODULE.N8AOPass,ft.SSAO),ot.set(L.POSTPROCESSING.MODULE.TiltShiftEffect,ft.TiltShift),ot.set(L.POSTPROCESSING.MODULE.DepthOfFieldEffect,ft.DepthOfField),ot.set(L.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ft.ChromaticAberration),ot.set(L.POSTPROCESSING.MODULE.BloomEffect,ft.Bloom),ot.set(L.POSTPROCESSING.MODULE.SelectiveBloomEffect,ft.Bloom),ot.set(L.POSTPROCESSING.MODULE.VignetteEffect,ft.Vignette),ot.set(L.POSTPROCESSING.MODULE.PixelationEffect,ft.Pixelation),ot.set(L.POSTPROCESSING.MODULE.ToneMappingEffect,ft.ToneMapping),ot.set(L.POSTPROCESSING.MODULE.HueSaturationEffect,ft.HueSaturation),ot.set(L.POSTPROCESSING.MODULE.BrightnessContrastEffect,ft.BrightnessContrast)),n.sort((e,t)=>{const s=typeof e.priority=="number"?e.priority:ot.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,o=typeof t.priority=="number"?t.priority:ot.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return s===Number.NEGATIVE_INFINITY?(bh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):o===Number.NEGATIVE_INFINITY?(bh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):s-o}),bh==="verbose"&&console.debug("After ordering effects",[...n])}var E2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,gS=(n,e,t,s)=>{for(var o=A2(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&E2(e,t,o),o};const I2=C("debugpost");class N{constructor(e){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),e!==void 0&&this.initialize(e)}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)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;I2&&typeof s=="number"&&typeof e=="number"&&(s?.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,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}gS([m()],N.prototype,"overrideState"),gS([m()],N.prototype,"value");class L2 extends es{constructor(){super([N])}onSerialize(e,t){}onDeserialize(e,t){const s=t.target,o=t.path;let r;if(s&&o&&(r=s[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof e=="object"&&"value"in e){const l=e.value;r.initialize(l),r.overrideState=e.overrideState}else r.value=e;return r}}new L2;var j2=Object.defineProperty,D2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&j2(e,t,o),o};const Ly=C("debugpost");class rt extends j{constructor(e=void 0){if(super(),a(this,"order"),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const s=e[t],o=this[t];o instanceof N?o.initialize(s):o!==void 0&&(this[t]=s)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Ly&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),Ly&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=R2(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Ly&&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 s=this[t];s instanceof N&&s.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const s=e.value;return this[t].value=s,!0}}}D2([m()],rt.prototype,"active");var B2=Object.defineProperty,F2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&B2(e,t,o),o};const U2=C("debugpost"),jy={};function us(n,e){jy[n]=e}function z2(n){return n.__type in jy?jy[n.__type]:(U2&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),rt)}class Up{constructor(){a(this,"components",[])}__init(e){var t;(t=this.components)==null||t.forEach(s=>{s.gameObject===void 0&&e.gameObject.addComponent(s),s.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}F2([jr([n=>z2(n),rt])],Up.prototype,"components");var N2=Object.defineProperty,W2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&N2(e,t,o),o};const V2=C("debugpost");class _h extends rt{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var e;const t=new L.POSTPROCESSING.MODULE.SMAAEffect({preset:((e=this.preset)==null?void 0:e.value)??L.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:L.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=s=>{V2&&console.log("Antialiasing preset changed to",s),t.applyPreset(s)},t}}W2([m(N)],_h.prototype,"preset"),us("Antialiasing",_h);var $2=Object.defineProperty,Dy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&$2(e,t,o),o},zp;const Np=(zp=class extends rt{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.7)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=n=>n,this.intensity.valueProcessor=n=>n,this.scatter.valueProcessor=n=>n}onCreateEffect(){let n;if(this.selectiveBloom==null&&(this.selectiveBloom=zp.useSelectiveBloom),this.selectiveBloom){const e=n=new L.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else n=new L.POSTPROCESSING.MODULE.BloomEffect({blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{n.intensity=e},this.threshold.onValueChanged=e=>{n.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{n.luminancePass.enabled=!0,n.luminanceMaterial.smoothing=e,n.mipmapBlurPass&&(n.mipmapBlurPass.radius=Cn.lerp(.1,.9,e))},n}},a(zp,"useSelectiveBloom",!1),zp);Dy([m(N)],Np.prototype,"threshold"),Dy([m(N)],Np.prototype,"intensity"),Dy([m(N)],Np.prototype,"scatter");let Wp=Np;us("Bloom",Wp);var H2=Object.defineProperty,G2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&H2(e,t,o),o};class wh extends rt{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new L.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new ie(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}}G2([m(N)],wh.prototype,"intensity"),us("ChromaticAberration",wh);var xh=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n[n.AgX=3]="AgX",n[n.KhronosNeutral=4]="KhronosNeutral",n))(xh||{});const fS=new Map;function By(n){switch(n){case 0:return zm;case 1:return Um;case 2:return bd;case 3:return vd;case 4:return Pa;default:return fS.has(n)||(fS.set(n,!0),console.warn("[Postprocessing] Unknown tone mapping mode",n)),Pa}}function q2(n){switch(n){case zm:return 0;case bd:return 2;case vd:return 3;case Pa:return 1;case Um:return 1;default:return 0}}function Vp(n){switch(n){case zm:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case bd:return L.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case vd:return L.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Pa:return L.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Um:return L.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var X2=Object.defineProperty,yS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&X2(e,t,o),o};const Fy=C("debugpost");class sr extends rt{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1)),a(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const t=xh[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=mS(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var e;if(this.mode.isInitialized==!1){const o=q2(this.context.renderer.toneMapping);Fy&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+o),this.mode.initialize(o)}(e=this._tonemappingEffect)==null||e.dispose();const t=By(this.mode.value),s=this._tonemappingEffect=new L.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vp(t)});return this.mode.onValueChanged=o=>{if(typeof o=="string")o=qw(o),s.mode=Vp(o);else{const r=By(o);s.mode=Vp(r)}s.name="ToneMapping ("+xh[o]+")",Fy&&console.log("[PostProcessing] ToneMapping mode changed to",xh[o],t,s.mode)},Fy&&console.log("[PostProcessing] Use ToneMapping",xh[this.mode.value],t,s.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),s}onBeforeRender(){var e;if(this._tonemappingEffect&&(e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=By(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const t=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=t}}}yS([m(N)],sr.prototype,"mode"),yS([m(N)],sr.prototype,"exposure"),us("Tonemapping",sr);var Q2=Object.defineProperty,$p=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Q2(e,t,o),o};class nr extends rt{constructor(){super(...arguments),a(this,"remap",!0),a(this,"postExposure",new N(1)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}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(){var e,t;const s=[];let o=(e=this.postprocessingContext)==null?void 0:e.components.find(c=>c instanceof sr);o||(o=new sr,(t=this.postprocessingContext)==null||t.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&o?o.exposure.value=c: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 r=new L.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new L.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,s.push(r),s.push(l),s}}$p([m(N)],nr.prototype,"postExposure"),$p([m(N)],nr.prototype,"contrast"),$p([m(N)],nr.prototype,"hueShift"),$p([m(N)],nr.prototype,"saturation"),us("ColorAdjustments",nr);var Y2=Object.defineProperty,ra=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Y2(e,t,o),o};const K2=C("debugpost");class Es extends rt{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300;return W.lerp(2,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return W.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){K2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new L.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(){}}ra([m()],Es.prototype,"mode"),ra([m(N)],Es.prototype,"focusDistance"),ra([m(N)],Es.prototype,"focalLength"),ra([m(N)],Es.prototype,"aperture"),ra([m(N)],Es.prototype,"gaussianMaxRadius"),ra([m(N)],Es.prototype,"resolutionScale"),ra([m(N)],Es.prototype,"bokehScale"),us("DepthOfField",Es);class Sh extends rt{constructor(e){super(),a(this,"effect"),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Z2=Object.defineProperty,J2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Z2(e,t,o),o};class Ch extends rt{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new L.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}J2([m(N)],Ch.prototype,"granularity"),us("PixelationEffect",Ch);var eI=Object.defineProperty,Ph=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&eI(e,t,o),o};class io extends rt{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new re(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof we){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,t=new L.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),s=new L.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),o=this._ssao=new L.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:s.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new re),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(t),r.push(s),r.push(o),r}}Ph([m(N)],io.prototype,"intensity"),Ph([m(N)],io.prototype,"falloff"),Ph([m(N)],io.prototype,"samples"),Ph([m(N)],io.prototype,"color"),Ph([m(N)],io.prototype,"luminanceInfluence"),us("ScreenSpaceAmbientOcclusion",io);var tI=Object.defineProperty,aa=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&tI(e,t,o),o};const iI=C("debugN8AO");var Uy=(n=>(n[n.Performance=0]="Performance",n[n.Low=1]="Low",n[n.Medium=2]="Medium",n[n.High=3]="High",n[n.Ultra=4]="Ultra",n))(Uy||{});class As extends rt{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new re(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Uy[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,s=this.context.domHeight,o=this._ssao=new L.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,s);o.name="SSAO_N8";const r=Uy[this.quality];o.setQualityMode(r),o.configuration.transparencyAware=!1;const l=new Vs(t,s);return o.configuration.beautyRenderTarget=l,o.configuration.autoRenderBeauty=!1,o.configuration.gammaCorrection=this.gammaCorrection,o.configuration.screenSpaceRadius=this.screenspaceRadius,iI&&(o.enableDebugMode(),console.log(o),setInterval(()=>{console.log("SSAO",o.lastTime)},1e3),setInterval(()=>{console.log("SSAO",o.enabled,{ssao:o,autoRenderBeauty:o.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{o.configuration.intensity=c},this.falloff.onValueChanged=c=>{o.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{o.configuration.aoRadius=c},this.color.onValueChanged=c=>{o.color||(o.color=new re),o.configuration.color.copy(c)},o}}aa([Tt(),m()],As.prototype,"gammaCorrection"),aa([m(N)],As.prototype,"aoRadius"),aa([m(N)],As.prototype,"falloff"),aa([m(N)],As.prototype,"intensity"),aa([m(N)],As.prototype,"color"),aa([Tt(),m()],As.prototype,"screenspaceRadius"),aa([Tt(),m()],As.prototype,"quality"),us("ScreenSpaceAmbientOcclusionN8",As);var sI=Object.defineProperty,nI=Object.getOwnPropertyDescriptor,vS=(n,e,t,s)=>{for(var o=nI(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sI(e,t,o),o};class Oh extends rt{constructor(){super(...arguments),a(this,"order",ft.Sharpening),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(oI())),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}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}}vS([m()],Oh.prototype,"amount"),vS([m()],Oh.prototype,"radius");function oI(){const n=`
|
|
1274
|
+
`)}l&&r.size&&console.log(p);const y=new Set;for(const _ of f){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let w=_.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:_})}const v=Array.from(y).sort((_,w)=>_.path.length-w.path.length),b=new Array;for(let _=0;_<v.length;_++)for(let w=_+1;w<v.length;w++)if(v[w].path.startsWith(v[_].path)){const x=v[w],k=v[_];b.push({child:x.obj.displayName+" ("+x.path+")",parent:k.obj.displayName+" ("+k.path+")"})}b.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:b,playAnimationActions:r})}for(const p of new Set([...t,...s]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);Sp&&console.log("All Behavior trigger sources and action targets",t,s,o),this.targetUuids=new Set(o)}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Sp&&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:s}of this.audioClipsCopy){if(e.files[s])return;const o=await(await(await fetch(t)).blob()).arrayBuffer(),r=new Uint8Array(o);e.files[s]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class ty{get extensionName(){return"Physics"}onExportObject(e,t,s){const o=P.getComponents(e,dt).filter(h=>h.enabled),r=P.getComponents(e,pi).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new dt,l.isKinematic=!0),l&&t.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const f=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const y=f.sharedMaterial;y&&y.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),y&&y.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=f.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(t.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof tl){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Wu){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof Vn){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Bo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const f=c.sharedMesh.geometry.boundingBox;f&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}const RA=C("debugshadowcomponents");ib.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};class ps extends j{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){si.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,rh)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var s;if(!e)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ps),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Ri]=this,this.setShadowComponentOwner(e);let r=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(e),r=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),vc&&e.add(new Pi(.5)),this.onAfterAddedToScene(),r&&kO(),RA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ri]===void 0||e[Ri]===this)&&(e[Ri]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[Ri]===t){s(e);for(const o of e.children)this.traverseOwnedShadowComponents(o,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class rh extends ps{awake(){super.awake()}}var TA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,ah=(n,e,t,s)=>{for(var o=s>1?void 0:s?EA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&TA(e,t,o),o};const iy=C("debugui"),sy=C("debuguilayout");class K1{constructor(){a(this,"width"),a(this,"height")}}class Z1{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Ms=new S,lh=new ne,Cp=new V,bl=class OC extends ps{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new ie(100,100)),a(this,"pivot",new ie(.5,.5)),a(this,"anchorMin",new ie(0,0)),a(this,"anchorMax",new ie(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new ie),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,s=this.anchorMax.x-this.anchorMin.x;e=t*s,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,s=this.anchorMax.y-this.anchorMin.y;e=t*s,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new A,this.rectBlock.name=this.name,this.lastMatrix=new ne,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new ie),Za(this,"_anchoredPosition",()=>{this.markDirty()}),Za(this,"sizeDelta",()=>{this.markDirty()}),Za(this,"pivot",()=>{this.markDirty()}),Za(this,"anchorMin",()=>{this.markDirty()}),Za(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new A),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new ie),this._initialPosition||(this._initialPosition=new S),this._anchoredPosition||(this._anchoredPosition=new ie),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(sy?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(sy&&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){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const s=this.shadowComponent;if(!s)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,OC):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,sy&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(s.rotation.y=Math.PI):(s.matrix.identity(),s.matrixAutoUpdate=!1,Ms.set(0,0,0),this.applyPivot(Ms),s.matrix.setPosition(Ms.x,Ms.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Cp.copy(this.gameObject.quaternion),Cp.x*=-1,Cp.z*=-1,lh.makeRotationFromQuaternion(Cp),s.matrix.premultiply(lh)),Ms.set(0,0,0),this.applyAnchoring(Ms),(t=this.canvas)!=null&&t.screenspace?Ms.z+=.1:Ms.z+=.01,lh.identity(),lh.setPosition(Ms.x,Ms.y,Ms.z),s.matrix.premultiply(lh),s.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const o=!0;for(const r of du(this.gameObject,ps,o,1)){if(r===this||!r.activeAndEnabled)continue;const l=r;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new ie);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 s=this._parentRectTransform;if(s){let o=0;const r=1-this.anchorMax.y-this.anchorMin.y;o-=s.height*.5*r,e.y+=o;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=s.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const s=this.pivot.y-.5;e.y-=s*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}createNewBlock(e){e={...this.getBasicOptions(),...e},iy&&console.log(this.name,e);const t=new ib(e);return this._createdBlocks.push(t),t}createNewText(e){iy&&console.log(e),e={...this.getBasicOptions(),...e},iy&&console.log(this.name,e);const t=new tb(e);return this._createdTextBlocks.push(t),t}};ah([m(ie)],bl.prototype,"anchoredPosition",1),ah([m(ie)],bl.prototype,"sizeDelta",2),ah([m(ie)],bl.prototype,"pivot",2),ah([m(ie)],bl.prototype,"anchorMin",2),ah([m(ie)],bl.prototype,"anchorMax",2);let Rs=bl;var AA=Object.defineProperty,J1=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&AA(e,t,o),o};class _l extends j{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}J1([m(he)],_l.prototype,"effectColor"),J1([m(ie)],_l.prototype,"effectDistance");var IA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,eS=(n,e,t,s)=>{for(var o=s>1?void 0:s?LA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&IA(e,t,o),o};const Pp={backgroundColor:new re(1,1,1),backgroundOpacity:1,borderColor:new re(1,1,1),borderOpacity:1};var Qr;const ny=(Qr=class extends ps{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new re(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(n){(!this._color||this._color.r!==n.r||this._color.g!==n.g||this._color.b!==n.b||this._color.alpha!==n.alpha)&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(n),this.onColorChanged())}setAlphaFactor(n){this._alphaFactor=n,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Pp.backgroundColor=this.sRGBColor,Pp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Pp,this._alphaFactor),this.uiObject.set(Pp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Rs)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var n;(n=this.uiObject)==null||n.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(n){return super.__internalNewInstanceCreated(n),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(n){this.makePanel(),this.uiObject&&(this.uiObject.setState(n),this==null||this.markDirty())}setupState(n){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new MO(this.uiObject)),this.uiObject.setupState(n.state,n.attributes))}setOptions(n){this.makePanel(),this.uiObject&&this.uiObject.set(n)}awake(){super.awake(),this.makePanel(),Za(this,"_color",()=>RT(this,this.onColorChanged))}onEnable(){var n;super.onEnable(),this.uiObject&&((n=this.rectTransform.shadowComponent)==null||n.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const n={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(n),this.applyEffects(n),this.onCreate(n),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(n){}onCreate(n){this.uiObject=this.rectTransform.createNewBlock(n),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(n,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(_l);s&&(s.effectDistance&&(n.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(n.borderColor=s.effectColor,n.borderOpacity=s.effectColor.alpha*e))}async setTexture(n){if(this.setOptions({backgroundOpacity:0}),n){if(Qr.textureCache.has(n))n=Qr.textureCache.get(n);else if(!n.isRenderTargetTexture){const e=n.clone();e.colorSpace=On,Qr.textureCache.set(n,e),n=e}this.setOptions({backgroundImage:n,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Xe.assignTextureLOD(n,0).then(e=>{e instanceof je&&(n&&Qr.textureCache.set(n,e),this.setOptions({backgroundImage:e}),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)}},a(Qr,"textureCache",new Map),Qr);eS([m(he)],ny.prototype,"color",1),eS([m()],ny.prototype,"raycastTarget",2);let ch=ny;class hh extends ch{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var jA=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,Zn=(n,e,t,s)=>{for(var o=s>1?void 0:s?DA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&jA(e,t,o),o};const Yr=C("debugtext");var mt=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(mt||{}),tS=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(tS||{});class Nt extends ch{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new re(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0)}onCreate(e){Yr&&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,Yr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Yr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}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(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,o,r;if(Yr&&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 l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new qm({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),d={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(e,l,h),this.handleTag(l,d,c);const u=new qm(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=e.substring(l.endIndex),this.handleTag(l,d,c);const u=new qm(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Lu(l,s),e[r]=!0)}if(!o)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const o=new oy(e,{color:t.color});if(s.push(o),e.type.length>6){const r=parseInt("0x"+e.type.substring(7));t.color=r}else t.color=new re(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const o=new oy(e,{fontWeight:700});s.push(o)}else if(e.type=="i"){this.setFont(t,2);const o=new oy(e,{fontStyle:"italic"});s.push(o)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),o=e.indexOf(">",s);if(s>=0&&o>=0){const r=e.substring(s+1,o);return{type:r,startIndex:s,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,o=this.getFamilyNameWithCorrectSuffix(s,t);Yr&&console.log("Selected font family:"+o);let r=sb.getFontFamily(o);switch(r||(r=sb.addFontFamily(o)),e.fontFamily=r,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 l=r.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(e.fontWeight,e.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const o=e.lastIndexOf("-");if(o<0)return e;const r=(s=e.substring(o+1))==null?void 0:s.toLowerCase();if(BA.includes(r))return Yr&&console.warn("Unsupported font style: "+r),e;const l=e.lastIndexOf("/");let c=e;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=e.substring(0,o);switch(Yr&&console.log("Select font: ",e,tS[t],c,h,d),t){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return e}}}Zn([m()],Nt.prototype,"alignment",2),Zn([m()],Nt.prototype,"verticalOverflow",2),Zn([m()],Nt.prototype,"horizontalOverflow",2),Zn([m()],Nt.prototype,"lineSpacing",2),Zn([m()],Nt.prototype,"supportRichText",2),Zn([m(URL)],Nt.prototype,"font",2),Zn([m()],Nt.prototype,"fontStyle",2),Zn([m()],Nt.prototype,"text",1),Zn([m()],Nt.prototype,"fontSize",1);class oy{constructor(e,t){a(this,"tag"),a(this,"previousValues"),this.tag=e,this.previousValues=t}}const BA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Kr{constructor(e){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=e}static getId(){return this.global_id++}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}writeTo(e,t){var s;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=[]),(s=this.font)==null||s.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");t.appendLine(`string[] font = [ ${o} ]`),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/${lp(this.material)}>`),t.closeBlock()}}a(Kr,"global_id",0);class ry{static singleLine(e,t,s){const o=new Kr("text_"+Kr.getId());return o.content=e,t&&(o.pointSize=t),s&&(o.depth=s),o}static multiLine(e,t,s,o,r,l){const c=new Kr("text_"+Kr.getId());return c.content=e,c.width=t,c.height=s,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const FA=new ne().makeRotationY(Math.PI),UA=new ne().makeScale(-1,1,-1);class Op{get extensionName(){return"text"}exportText(e,t,s){const o=P.getComponent(e,Nt);if(!o)return;const r=P.getComponent(e,Rs);let l=100,c=100;r&&(l=r.width,c=r.height);const h=FA.clone();r&&h.premultiply(UA),t.setMatrix(h);const d=o.color.clone();t.material=new bt({color:d,emissive:d}),t.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const f=ry.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(f,o.alignment),this.setOverflow(f,o),t.material&&(f.material=t.material),f.pointSize=this.convertToTextSize(o.fontSize),f.depth=.001,f.writeTo(void 0,u)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:e.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:e.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:e.horizontalAlignment="right";break}switch(t){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:e.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:e.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:e.verticalAlignment="top";break}}}var zA=Object.defineProperty,it=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&zA(e,t,o),o};const iS=C("debuguilayout");class Zr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}it([m()],Zr.prototype,"left"),it([m()],Zr.prototype,"right"),it([m()],Zr.prototype,"top"),it([m()],Zr.prototype,"bottom");class Wi extends j{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(iS&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){iS&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Rs);const e=this.gameObject.getComponentInParent(wl);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(wl);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}it([m()],Wi.prototype,"childAlignment"),it([m()],Wi.prototype,"reverseArrangement"),it([m()],Wi.prototype,"spacing"),it([m(Zr)],Wi.prototype,"padding"),it([m()],Wi.prototype,"minWidth"),it([m()],Wi.prototype,"minHeight"),it([m()],Wi.prototype,"flexibleHeight"),it([m()],Wi.prototype,"flexibleWidth"),it([m()],Wi.prototype,"preferredHeight"),it([m()],Wi.prototype,"preferredWidth");class Qo extends Wi{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,o=e.width;let r=o;const l=e.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const h=s==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,f=h?this.childForceExpandHeight:this.childForceExpandWidth,y=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let _=0;h?_+=this.padding.left:_+=this.padding.top;let w=0,x=0;for(let z=0;z<this.gameObject.children.length;z++){const U=this.gameObject.children[z],E=P.getComponent(U,Rs);E!=null&&E.activeAndEnabled&&(x+=1,h?w+=E.width:w+=E.height)}let k=0;const M=this.spacing*(x-1);if(g||u){let z=0;h?z=r-=M:z=c-=M,x>0&&(k=z/x)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(_=v-w,_*=b,_-=M*b,h?(_-=this.padding.right*b,_+=this.padding.left*(1-b),_<this.padding.left&&(_=this.padding.left)):(_-=this.padding.bottom*b,_+=this.padding.top*(1-b),_<this.padding.top&&(_=this.padding.top)));let D=1;for(let z=0;z<this.gameObject.children.length;z++){const U=this.gameObject.children[z],E=P.getComponent(U,Rs);if(E!=null&&E.activeAndEnabled){(t=E.pivot)==null||t.set(.5,.5),E.anchorMin.set(0,1),E.anchorMax.set(0,1);const $=o*.5+T*.5;E.anchoredPosition.x!==$&&(E.anchoredPosition.x=$);const H=l*-.5;E.anchoredPosition.y!==H&&(E.anchoredPosition.y=H),f&&p&&E.sizeDelta[d]!==y&&(E.sizeDelta[d]=y),g&&u&&E.sizeDelta[s]!==k&&(E.sizeDelta[s]=k);const F=h?E.width:E.height,I=F*.5;if(_+=I,g){const te=k*D-k*.5;te>_&&(_=te-k*.5+F+this.padding.left,_-=I)}let Y=_;s==="y"&&(Y=-Y),E.anchoredPosition[s]!==Y&&(E.anchoredPosition[s]=Y),_+=I,_+=this.spacing,D+=1}}}}it([m()],Qo.prototype,"childControlHeight"),it([m()],Qo.prototype,"childControlWidth"),it([m()],Qo.prototype,"childForceExpandHeight"),it([m()],Qo.prototype,"childForceExpandWidth"),it([m()],Qo.prototype,"childScaleHeight"),it([m()],Qo.prototype,"childScaleWidth");class ay extends Qo{get primaryAxis(){return"y"}}class ly extends Qo{get primaryAxis(){return"x"}}class cy extends Wi{onCalculateLayout(){}}var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,mn=(n,e,t,s)=>{for(var o=s>1?void 0:s?WA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NA(e,t,o),o},sS=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(sS||{});const hy=C("debuguilayout"),cs=class kC extends rh{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var e,t,s,o;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),(o=this.shadowComponent)==null||o.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(nb,this.context))}),a(this,"onAfterRenderRoutine",()=>{var e,t,s,o,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(s=this.previousParent)==null||s.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(o=this.shadowComponent)==null||o.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(nb,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}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)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof kC||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,hy&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,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)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}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 Ql(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);hy&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(Wi)),(t.isDirty||s!=null&&s.isDirty)&&(hy&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Oe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Lu(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,ps))Lu(e.shadowComponent,this)}}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,s=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(s=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(s=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const o=s+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-o,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Rs);let l=!1;r.sizeDelta.x!==this.context.domWidth&&(l=!0),r.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=t.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(o);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};mn([m()],cs.prototype,"renderOnTop",1),mn([m()],cs.prototype,"depthWrite",1),mn([m()],cs.prototype,"doubleSided",1),mn([m()],cs.prototype,"castShadows",1),mn([m()],cs.prototype,"receiveShadows",1),mn([m()],cs.prototype,"renderMode",1),mn([m(cs)],cs.prototype,"rootCanvas",1),mn([m()],cs.prototype,"scaleFactor",1),mn([m(hi)],cs.prototype,"worldCamera",2),mn([m()],cs.prototype,"planeDistance",2);let wl=cs;var VA=Object.defineProperty,$A=Object.getOwnPropertyDescriptor,dy=(n,e,t,s)=>{for(var o=s>1?void 0:s?$A(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&VA(e,t,o),o};class Yo extends j{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Oe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,ps,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}dy([m()],Yo.prototype,"alpha",1),dy([m()],Yo.prototype,"interactable",2),dy([m()],Yo.prototype,"blocksRaycasts",2);class uy{get extensionName(){return"tmui"}onExportObject(e,t,s){const o=P.getComponent(e,wl);if(o&&o.enabled&&o.renderMode===sS.WorldSpace){const r=new Op,l=P.getComponent(e,Rs),c=P.getComponent(e,Yo),h=new Array;if(l){if(!P.isActiveSelf(e)){const p=P.isActiveSelf(e);P.setActive(e,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(e,p)})}e.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const f=P.getComponent(p,ps);f&&(f.onEnable(),h.push(()=>{f.onDisable()}));const y=P.getComponent(p,Rs);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),h.push(()=>{y.onDisable()}));const v=P.getComponent(p,Nt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=gi.createEmpty(),u=l.shadowComponent;if(t.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,f=new Map;g.set(u,d),f.set(u,c?c.alpha:1),u.traverse(y=>{if(y===u)return;const v=gi.createEmpty();v.setMatrix(y.matrix);const b=y.parent,_=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let w=f.get(b)||1;const x=P.getComponent(y,Yo);if(x&&(w*=x.alpha),y instanceof q&&_){const M=y[Ri];M?r.exportText(M.gameObject,v,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof q&&!_){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new re,D=y.material.opacity;T.copy(y.material.color),v.material=new Me({color:T,opacity:D*w,map:y.material.map,transparent:!0})}g.set(y,v),f.set(y,w);const k=g.get(b);if(!k){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}k.add(v)})}}for(const d of h)d()}}flipWindingOrder(e){const t=e.index.array;for(let s=0,o=t.length/3;s<o;s++){const r=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=r}e.index.needsUpdate=!0}}const dh=C("debugusdz");function HA(n,e){var t;const s=[],o=P.getComponentsInChildren(n,Rt),r=P.getComponentsInChildren(n,Ft),l=new Array,c=new Array;if(e.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((t=d.motion.clip.tracks)==null?void 0:t.length)<1||l.includes(h))continue;const u=new eh;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new A;P.addComponent(p,u),c.push(p),l.push(h),n.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;dh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){dh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}s.push({root:h.gameObject,clips:d})}if(e.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new eh;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new A;P.addComponent(u,d),c.push(u),l.push(h),n.add(u)}else for(const h of r){dh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);s.push({root:h.gameObject,clips:d})}dh&&s?.length>0&&console.log("USDZ Animation Clips without behaviours",s);for(const h of s)for(const d of h.clips)e.registerAnimation(h.root,d);return c}function GA(n,e){const t=P.getComponentsInChildren(n,ns),s=P.getComponentsInChildren(n,Wo),o=new Array,r=new Array;dh&&console.log({audioSources:t,playAudioOnClicks:s});for(const l of s){if(!l.target)continue;const c=t.indexOf(l.target);c>-1&&t.splice(c,1)}for(const l of t){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Wo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new A;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),n.add(h)}return r}function qA(n){return new ei("DisableAtStart",At.sceneStartTrigger(),ve.fadeAction(n,0,!1))}function nS(n,e){const t=n.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const s=document.createElement("div");s.classList.add("menu"),s.classList.add("quicklook-menu"),s.style.display="none",s.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",e?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),s.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",s.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),n.domElement.shadowRoot.appendChild(s),r}var XA=Object.defineProperty,It=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&XA(e,t,o),o};const Vi=C("debugusdz"),QA=C("debugusdzpruning");class Jr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}It([m()],Jr.prototype,"callToAction"),It([m()],Jr.prototype,"checkoutTitle"),It([m()],Jr.prototype,"checkoutSubtitle"),It([m()],Jr.prototype,"callToActionURL");var xl;const yi=(xl=class extends j{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",n=>{n.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new S),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new S)}start(){var n,e,t;Vi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=Q.supportsQuickLookAR(),t=Q.isiOS()||Q.isiPad();!this.button&&(Vi||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=nS(this.context,e),this.link.addEventListener("message",this.lastCallback)),Vi&&De("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),hc.registerExporter(this)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Vi&&De("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement),hc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+b1(),Zs()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=nS(this.context,Q.supportsQuickLookAR())),this.customUsdzFile)return Vi&&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;const t=await this.export(this.objectToExport);return t?(Vi&&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(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(s=>(this._currentExportTasks.delete(n),s)).catch(s=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",s),null))):t}async internalExport(n){de.start("export-usdz",{onProgress:x=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:x}}))}}),de.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),de.report("export-usdz",{message:"Load progressive textures",autoStep:5}),de.start("export-usdz-textures","export-usdz");const e=P.getComponentsInChildren(n,fi);for(const x of e)x&&x.enabled&&x.updateSprite(!0);const t=P.getComponentsInChildren(n,Ui),s=new Array;let o=0;for(const x of t){for(const k of x.sharedMeshes)if(k){const M=Xe.assignMeshLOD(k,0);M instanceof Promise&&s.push(new Promise((T,D)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:s.length}),T()}).catch(z=>D(z))}))}for(const k of x.sharedMaterials)if(k){const M=Xe.assignTextureLOD(k,0);M instanceof Promise&&s.push(new Promise((T,D)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:s.length}),T()}).catch(z=>D(z))}))}}Vi&&De("Progressive Loading: "+s.length),await Promise.all(s),Vi&&De("Progressive Loading: done"),de.end("export-usdz-textures");const r=Di.Global.Mask;Di.Global.Set(rn.AR);const l=new P1,c=new up(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new ey),d.push(new _a),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(n,dt).length>0&&(this.physics?(h=new ty,d.push(h)):B()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Op),d.push(new uy));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:n};de.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,de.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...HA(n,c)),u.find(x=>x.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...GA(n)),l.debug=Vi,l.pruneUnusedNodes=!QA;const f=ep.instance.objs.map(x=>x.batchedMesh);l.keepObject=x=>{let k=!0;const M=P.getComponent(x,Ui);return M&&!M.enabled&&(k=!1),k&&f.includes(x)&&(k=!1),k&&P.getComponentInParent(x,$c)&&(k=!1),k&&P.getComponentInParent(x,en)&&(k=!1),Vi&&!k&&console.log("USDZExporter: Discarding object",x),k},l.beforeWritingDocument=()=>{if(B()&&c&&h){const x=c.animatedRoots;for(const k of x){const M=P.getComponentsInChildren(k,dt).filter(D=>D.enabled),T=P.getComponents(k,pi).filter(D=>D.enabled&&!D.isTrigger);(M.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(x=>{x.visible||y.push(x)});const v=u.find(x=>x.extensionName==="Behaviour");this.interactive&&v&&y.length>0&&v.addBehavior(qA(y));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),de.report("export-usdz","Invoking exporter.parse");const _=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,de.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const x of g)P.destroy(x);return Di.Global.Set(r),de.end("export-usdz"),w}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,s=this.buildQuicklookOverlay();Vi&&console.log("QuickLook Overlay",s);const o=s.callToAction?encodeURIComponent(s.callToAction):"",r=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",l=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){xl.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Vi&&be("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Vi&&De("Quicklook url: "+s),s&&(Zs()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,e,t,s,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),Zs()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((n=l.callToAction)==null?void 0:n.length)||((e=l.checkoutTitle)==null?void 0:e.length)||((t=l.checkoutSubtitle)==null?void 0:t.length))&&((s=l.callToAction)!=null&&s.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const n=P.findObjectOfType(xp);let e=P.getComponentInParent(this.objectToExport,Vo);e||(e=P.getComponentInChildren(this.objectToExport,Vo));let t=1,s=!1;const o=this.objectToExport;return n?t=n.arScale:e&&(t=e.arScale,s=e.invertForward),{scale:1/t,_invertForward:s,target:o,sessionRoot:e?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:s}=this.getARScaleAndTarget(),o=s?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(xl.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),s&&o&&t.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=gl.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},a(xl,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(xl,"invertForwardQuaternion",new V().setFromEuler(new Dt(0,Math.PI,0))),xl);It([m(A)],yi.prototype,"objectToExport"),It([m()],yi.prototype,"autoExportAnimations"),It([m()],yi.prototype,"autoExportAudioSources"),It([m()],yi.prototype,"exportFileName"),It([m(URL)],yi.prototype,"customUsdzFile"),It([m(Jr)],yi.prototype,"customBranding"),It([m()],yi.prototype,"anchoringType"),It([m()],yi.prototype,"maxTextureSize"),It([m()],yi.prototype,"planeAnchoringAlignment"),It([m()],yi.prototype,"interactive"),It([m()],yi.prototype,"physics"),It([m()],yi.prototype,"allowCreateQuicklookButton"),It([m()],yi.prototype,"quickLookCompatible");let gn=yi;var YA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,py=(n,e,t,s)=>{for(var o=KA(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YA(e,t,o),o};class Sl extends j{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Av(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}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}py([m()],Sl.prototype,"near"),py([m()],Sl.prototype,"far"),py([m(re)],Sl.prototype,"color");var ZA=Object.defineProperty,my=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&ZA(e,t,o),o};class ea extends j{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!vc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new RP(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=$g(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Oe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}my([m()],ea.prototype,"objectBounds"),my([m(re)],ea.prototype,"color"),my([m()],ea.prototype,"isGizmo");var JA=Object.defineProperty,gy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&JA(e,t,o),o};class Cl extends j{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!vc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Rm(e,t,this.color0??new re(.4,.4,.4),this.color1??new re(.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)}}gy([m()],Cl.prototype,"isGizmo"),gy([m(re)],Cl.prototype,"color0"),gy([m(re)],Cl.prototype,"color1");var e2=Object.defineProperty,fy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&e2(e,t,o),o};class yy extends j{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(dt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}fy([m(dt)],yy.prototype,"connectedBody");class vy extends yy{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class uh extends yy{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}fy([m(S)],uh.prototype,"anchor"),fy([m(S)],uh.prototype,"axis");var t2=Object.defineProperty,i2=Object.getOwnPropertyDescriptor,fn=(n,e,t,s)=>{for(var o=s>1?void 0:s?i2(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&t2(e,t,o),o};function by(n){return n*Math.PI/180}const oS=300,Ko=C("debuglights");class vi extends j{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new re(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var t,s;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.camera)!==void 0)){const o=this.light.shadow.camera;o.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var t,s;e!==this._shadowBias&&(this._shadowBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var t,s;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var t;if(this._intensity=e,this.light){let s=1;if(this.context.isInXR&&this._webARRoot){const o=(t=this._webARRoot)==null?void 0:t.arScale;typeof o=="number"&&o>0&&(s/=o)}this.light.intensity=e*s}Ko&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t!=null&&t.shadow){const s=t.shadow.camera;s.far=e,s.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t!=null&&t.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!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}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new re(this.color??16777215),Ko&&console.log(this.name,this)}onEnable(){Ko&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ko&&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(),Oe.LateUpdate))}onDisable(){Ko&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=P.getComponentInParent(this.gameObject,Vo)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new Tm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-oS*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),vr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ko){const l=new EP(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const s=new TP(this.color,this.intensity*Math.PI,this.range,by(this.spotAngle/2),1-by(this.innerSpotAngle/2)/by(this.spotAngle/2),2);s.position.set(0,0,0),s.rotation.set(0,0,0),this.light=s;const o=s.target;s.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Em(this.color,this.intensity*Math.PI,this.range);this.light=r;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),Ko&&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=oS*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 s=this.gameObject.scale.x;t.left*=s,t.right*=s}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const s=this.gameObject.scale.y;t.top*=s,t.bottom*=s}this.light.shadow.needsUpdate=!0,Ko&&this.context.scene.add(new AP(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}}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)}}a(vi,"allowChangingRendererShadowMapType",!0),fn([m()],vi.prototype,"type",2),fn([m(re)],vi.prototype,"color",1),fn([m()],vi.prototype,"shadowNearPlane",1),fn([m()],vi.prototype,"shadowBias",1),fn([m()],vi.prototype,"shadowNormalBias",1),fn([m()],vi.prototype,"shadows",1),fn([m()],vi.prototype,"lightmapBakeType",2),fn([m()],vi.prototype,"intensity",1),fn([m()],vi.prototype,"shadowDistance",1),fn([m()],vi.prototype,"shadowResolution",1),new S(0,0,0);var s2=Object.defineProperty,ph=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&s2(e,t,o),o};const _y=C("debuglods"),n2=C("nolods");class Pl{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}ph([m()],Pl.prototype,"screenRelativeTransitionHeight"),ph([m()],Pl.prototype,"distance"),ph([m(Ui)],Pl.prototype,"renderers");class o2{constructor(e){a(this,"model"),this.model=e}get renderers(){return this.model.renderers}}class mh extends j{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(_y&&console.log("LODGROUP",this.name,this.lodModels,this),!n2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const s of this.lodModels){const o=new o2(s);this._lods.push(o);for(const r of o.renderers)e.includes(r)||e.push(r)}this._lodsHandler=new Array;for(let s=0;s<e.length;s++){const o=new IP;this._lodsHandler.push(o),this.gameObject.add(o)}const t=new A;t.name="Cull "+this.name;for(let s=0;s<e.length;s++){const o=e[s],r=this._lodsHandler[s],l=o.gameObject;_y&&console.log(s,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=t,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}_y&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.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 s=t.getCurrentLevel(),o=t.levels[s];t.layers.mask=o.object.layers.mask}}onAddLodLevel(e,t,s){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,s*this._distanceFactor,.01);const o={lod:e,levelIndex:e.levels.length-1,distance:s};this._settings.push(o)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const s=t.lod.levels[t.levelIndex];s.distance=t.distance*e}}}}ph([m(S)],mh.prototype,"localReferencePoint"),ph([m(Pl)],mh.prototype,"lodModels");var r2=Object.defineProperty,a2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&r2(e,t,o),o};const kp=C("debugnestedgltf");class Mp extends j{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var t;(t=this.filePath)==null||t.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var e,t,s,o,r;if(this._isLoadingOrDoneLoading)return;kp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Bs;c.idProvider=new jt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;kp&&console.log("Load nested:",((e=this.filePath)==null?void 0:e.url)??this.filePath,this.gameObject.position);const d=await((s=(t=this.filePath)==null?void 0:t.instantiate)==null?void 0:s.call(this.filePath,c));kp&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),kp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}a2([m(ce)],Mp.prototype,"filePath");var l2=Object.defineProperty,wy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&l2(e,t,o),o};const c2=C("debugnet"),Rp=class Pv extends j{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){c2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Pv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const s=C(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t!=null&&t.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let s=e;const o=Pv.IsLocalNetwork()&&t;if(o&&(s=t),e!=null&&e.startsWith("/")){const r=o?s:window.location.origin;r!=null&&r.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),s=r+e}return s}static IsLocalNetwork(e=window.location.hostname){return Xt(e)}};wy([m()],Rp.prototype,"url"),wy([m()],Rp.prototype,"urlParameterName"),wy([m()],Rp.prototype,"localhost");let xy=Rp;var h2=Object.defineProperty,Tp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&h2(e,t,o),o};class ta extends j{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new S(0,0,0)),a(this,"rotationOffset",new S(0,0,0)),a(this,"offset",new S(0,0,0))}update(){if(!this.from)return;var e=ee(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const s=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(s),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new fr(this.gameObject.up,0),h=ee(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new S(0,0,0);c.projectPoint(e,d),e.copy(d)}this.affectPosition&<(this.gameObject,e);const o=new Dt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Yi(this.gameObject,t.multiply(r));const l=new S;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Tp([m(P)],ta.prototype,"referenceSpace"),Tp([m(P)],ta.prototype,"from"),Tp([m(S)],ta.prototype,"positionOffset"),Tp([m(S)],ta.prototype,"rotationOffset");var d2=Object.defineProperty,Zo=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&d2(e,t,o),o};class bi{constructor(e=0,t=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=e,this.value=t}}Zo([m()],bi.prototype,"time"),Zo([m()],bi.prototype,"value"),Zo([m()],bi.prototype,"inTangent"),Zo([m()],bi.prototype,"inWeight"),Zo([m()],bi.prototype,"outTangent"),Zo([m()],bi.prototype,"outWeight"),Zo([m()],bi.prototype,"weightedMode");const rS=class ad{constructor(){a(this,"keys",[])}static linearFromTo(e,t,s){const o=new ad,r=new bi;r.time=0,r.value=e;const l=new bi;return l.time=s,l.value=t,o.keys.push(r,l),o}static constant(e){const t=new ad,s=new bi;return s.time=0,s.value=e,t.keys.push(s),t}clone(){var e;const t=new ad;return t.keys=((e=this.keys)==null?void 0:e.map(s=>{const o=new bi;return o.time=s.time,o.value=s.value,o.inTangent=s.inTangent,o.inWeight=s.inWeight,o.outTangent=s.outTangent,o.outWeight=s.outWeight,o.weightedMode=s.weightedMode,o}))||[],t}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 s=this.keys[t];if(s.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(s.outTangent)||!isFinite(o.inTangent)?s.value:ad.interpolateValue(e,s,o)}else return s.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,s){const o=t.time,r=t.value,l=t.outTangent,c=s.time,h=s.value,d=s.inTangent,u=c-o,p=u*u,g=p*u,f=((l+d)*u-2*(h-r))/g,y=(3*(h-r)-(d+2*l)*u)/p,v=l,b=r,_=e-o,w=_*_,x=w*_;return f*x+y*w+v*_+b}};Zo([m(bi)],rS.prototype,"keys");let gh=rS;var u2=Object.defineProperty,O=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&u2(e,t,o),o};const Ep=C("debugparticles");var Jn=(n=>(n[n.Billboard=0]="Billboard",n[n.Stretch=1]="Stretch",n[n.HorizontalBillboard=2]="HorizontalBillboard",n[n.VerticalBillboard=3]="VerticalBillboard",n[n.Mesh=4]="Mesh",n))(Jn||{});class ia{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(e,t){let s,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<e||!s)&&(s=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<e||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(e,r.time,c.time,0,1);t.r=W.lerp(r.color.r,c.color.r,h),t.g=W.lerp(r.color.g,c.color.g,h),t.b=W.lerp(r.color.b,c.color.b,h)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(s)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(e,s.time,c.time,0,1);t.alpha=W.lerp(s.alpha,c.alpha,h)}else t.alpha=s.alpha;return t}}O([m()],ia.prototype,"alphaKeys"),O([m()],ia.prototype,"colorKeys");var fh=(n=>(n[n.Local=0]="Local",n[n.World=1]="World",n[n.Custom=2]="Custom",n))(fh||{}),Ap=(n=>(n[n.Sphere=0]="Sphere",n[n.SphereShell=1]="SphereShell",n[n.Hemisphere=2]="Hemisphere",n[n.HemisphereShell=3]="HemisphereShell",n[n.Cone=4]="Cone",n[n.Box=5]="Box",n[n.Mesh=6]="Mesh",n[n.ConeShell=7]="ConeShell",n[n.ConeVolume=8]="ConeVolume",n[n.ConeVolumeShell=9]="ConeVolumeShell",n[n.Circle=10]="Circle",n[n.CircleEdge=11]="CircleEdge",n[n.SingleSidedEdge=12]="SingleSidedEdge",n[n.MeshRenderer=13]="MeshRenderer",n[n.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",n[n.BoxShell=15]="BoxShell",n[n.BoxEdge=16]="BoxEdge",n[n.Donut=17]="Donut",n[n.Rectangle=18]="Rectangle",n[n.Sprite=19]="Sprite",n[n.SpriteRenderer=20]="SpriteRenderer",n))(Ap||{});const eo=class ld{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(e){const t=new ld;return t.setConstant(e),t}static betweenTwoConstants(e,t){const s=new ld;return s.setMinMaxConstant(e,t),s}static curve(e,t=1){const s=new ld;return s.setCurve(e,t),s}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}clone(){var e,t,s;const o=new ld;return o.mode=this.mode,o.constant=this.constant,o.constantMin=this.constantMin,o.constantMax=this.constantMax,o.curve=(e=this.curve)==null?void 0:e.clone(),o.curveMin=(t=this.curveMin)==null?void 0:t.clone(),o.curveMax=(s=this.curveMax)==null?void 0:s.clone(),o.curveMultiplier=this.curveMultiplier,o}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=W.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const o=e*this.curveMin.duration,r=e*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(o),this.curveMax.evaluate(r),s%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,s%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 s=0;s<e.keys.length;s++){const o=e.keys[s];o.value>t&&(t=o.value)}return t}};O([m()],eo.prototype,"mode"),O([m()],eo.prototype,"constant"),O([m()],eo.prototype,"constantMin"),O([m()],eo.prototype,"constantMax"),O([m(gh)],eo.prototype,"curve"),O([m(gh)],eo.prototype,"curveMin"),O([m(gh)],eo.prototype,"curveMax"),O([m()],eo.prototype,"curveMultiplier");let Z=eo;var st;const Jo=(st=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(n){const e=new st;return e.constant(n),e}static betweenTwoColors(n,e){const t=new st;return t.betweenTwoColors(n,e),t}constant(n){return this.mode=0,this.color=n,this}betweenTwoColors(n,e){return this.mode=2,this.colorMin=n,this.colorMax=e,this}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(n,st._temp),st._temp;case 2:case"TwoColors":return st._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:case"TwoGradients":return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,t);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,s)}return st._temp.set(16777215),st._temp.alpha=1,st._temp}},a(st,"_temp",new he(0,0,0,1)),a(st,"_temp2",new he(0,0,0,1)),st);O([m()],Jo.prototype,"mode"),O([m(he)],Jo.prototype,"color"),O([m(he)],Jo.prototype,"colorMin"),O([m(he)],Jo.prototype,"colorMax"),O([m(ia)],Jo.prototype,"gradient"),O([m(ia)],Jo.prototype,"gradientMin"),O([m(ia)],Jo.prototype,"gradientMax");let sa=Jo;var Sy=(n=>(n[n.Hierarchy=0]="Hierarchy",n[n.Local=1]="Local",n[n.Shape=2]="Shape",n))(Sy||{});class Wt{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}O([m(Z)],Wt.prototype,"gravityModifier"),O([m(sa)],Wt.prototype,"startColor"),O([m(Z)],Wt.prototype,"startDelay"),O([m(Z)],Wt.prototype,"startLifetime"),O([m(Z)],Wt.prototype,"startRotation"),O([m(Z)],Wt.prototype,"startRotationX"),O([m(Z)],Wt.prototype,"startRotationY"),O([m(Z)],Wt.prototype,"startRotationZ"),O([m(Z)],Wt.prototype,"startSize"),O([m(Z)],Wt.prototype,"startSizeX"),O([m(Z)],Wt.prototype,"startSizeY"),O([m(Z)],Wt.prototype,"startSizeZ"),O([m(Z)],Wt.prototype,"startSpeed");class Ip{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_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 s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();t=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return t}}class to{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];this.system.main.loop&&s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}O([m()],to.prototype,"enabled"),O([m()],to.prototype,"bursts"),O([m(Z)],to.prototype,"rateOverTime"),O([m()],to.prototype,"rateOverTimeMultiplier"),O([m(Z)],to.prototype,"rateOverDistance"),O([m()],to.prototype,"rateOverDistanceMultiplier");class Lp{constructor(){a(this,"enabled"),a(this,"color")}}O([m(sa)],Lp.prototype,"color");class na{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new S)}evaluate(e,t,s){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,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const o=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=o}return t}}O([m(Z)],na.prototype,"size"),O([m(Z)],na.prototype,"x"),O([m(Z)],na.prototype,"y"),O([m(Z)],na.prototype,"z");var er;const nt=(er=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Dt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new S(0,0,0)),a(this,"_temp",new S(0,0,0)),a(this,"_triangle",new LP),a(this,"_dir",new S),a(this,"_loopTime",0),a(this,"_loopDirection",1),Ep&&console.log(this)}get type(){return Ap[this.shapeType]}initialize(n){this.onInitialize(n),n.position.x=this._vector.x,n.position.y=this._vector.y,n.position.z=this._vector.z}toJSON(){return this}clone(){return new er}setMesh(n){this.meshRenderer=n,n?(this._meshObj=n.sharedMeshes[Math.floor(Math.random()*n.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(n,e){}onUpdate(n,e,t,s){this.system=n,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(n){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",n.applyEuler(this._rotation)),e}onInitialize(n){this._vector.set(0,0,0),n.mesh=void 0,n.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let s=this.radius;if(t&&(s*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Ep&&G.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(e);break;case 4:this.randomConePoint(this.position,this.angle,s,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=n.mesh=this._meshObj,l=n.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,f=u*3+2;p=c.getX(p),g=c.getX(g),f=c.getX(f);const y=l.getAttribute("position");this._triangle.a.fromBufferAttribute(y,p),this._triangle.b.fromBufferAttribute(y,g),this._triangle.c.fromBufferAttribute(y,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),B()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ap[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Ep&&G.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(n,e){var 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 s=e.x,o=e.y,r=e.z;this._dir.set(s,o,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=n.mesh,c=n.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=n.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=n.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),f=c.getAttribute("position"),y=X(),v=X(),b=X();y.fromBufferAttribute(f,u),v.fromBufferAttribute(f,p),b.fromBufferAttribute(f,g),y.sub(v),b.sub(v),y.cross(b),this._dir.copy(y).multiplyScalar(-1);const _=Se(l);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),Ep&&(G.DrawSphere(e,.01,8925952,.5,!0),G.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(n,e){if(e<=0)return;const t=er._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,n.add(t)}randomizeDirection(n,e){if(e===0)return;const t=er._randomQuat,s=er._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),n.applyQuaternion(t)}spherizeDirection(n,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),o=Math.sin(s)*Math.cos(t),r=Math.sin(s)*Math.sin(t),l=Math.cos(s),c=new S(o,r,l);n.lerp(c,e)}randomSpherePoint(n,e,t,s,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(s/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=n.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=n.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=n.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(n,e,t,s,o){const r=Math.random(),l=2*Math.PI*r*(s/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=n.x+this.scale.x*c*Math.cos(l),d=n.y+this.scale.y*c*Math.sin(l),u=n.z;o.x=h,o.y=d,o.z=u}randomConePoint(n,e,t,s,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,g=n.x+-p*Math.sin(u)*Math.cos(d),f=n.y+p*Math.sin(u)*Math.sin(d),y=n.z;l.x=g*this.scale.x,l.y=f*this.scale.y,l.z=y*this.scale.z}},a(er,"_randomQuat",new V),a(er,"_tempVec",new S),er);O([m()],nt.prototype,"shapeType"),O([m()],nt.prototype,"enabled"),O([m()],nt.prototype,"alignToDirection"),O([m()],nt.prototype,"angle"),O([m()],nt.prototype,"arc"),O([m()],nt.prototype,"arcSpread"),O([m()],nt.prototype,"arcSpeedMultiplier"),O([m()],nt.prototype,"arcMode"),O([m(S)],nt.prototype,"boxThickness"),O([m(S)],nt.prototype,"position"),O([m(S)],nt.prototype,"rotation"),O([m(S)],nt.prototype,"scale"),O([m()],nt.prototype,"radius"),O([m()],nt.prototype,"radiusThickness"),O([m()],nt.prototype,"sphericalDirectionAmount"),O([m()],nt.prototype,"randomDirectionAmount"),O([m()],nt.prototype,"randomPositionAmount"),O([m()],nt.prototype,"meshShapeType"),O([m(Yc)],nt.prototype,"meshRenderer");let Cy=nt;class Ce{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,o,r,l){if(!this.enabled)return;this._noise||(this._noise=bO(()=>0));const c=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}O([m()],Ce.prototype,"damping"),O([m()],Ce.prototype,"enabled"),O([m()],Ce.prototype,"frequency"),O([m()],Ce.prototype,"octaveCount"),O([m()],Ce.prototype,"octaveMultiplier"),O([m()],Ce.prototype,"octaveScale"),O([m(Z)],Ce.prototype,"positionAmount"),O([m()],Ce.prototype,"quality"),O([m(Z)],Ce.prototype,"remap"),O([m()],Ce.prototype,"remapEnabled"),O([m()],Ce.prototype,"remapMultiplier"),O([m(Z)],Ce.prototype,"remapX"),O([m()],Ce.prototype,"remapXMultiplier"),O([m(Z)],Ce.prototype,"remapY"),O([m()],Ce.prototype,"remapYMultiplier"),O([m(Z)],Ce.prototype,"remapZ"),O([m()],Ce.prototype,"remapZMultiplier"),O([m()],Ce.prototype,"scrollSpeedMultiplier"),O([m()],Ce.prototype,"separateAxes"),O([m()],Ce.prototype,"strengthMultiplier"),O([m(Z)],Ce.prototype,"strengthX"),O([m()],Ce.prototype,"strengthXMultiplier"),O([m(Z)],Ce.prototype,"strengthY"),O([m()],Ce.prototype,"strengthYMultiplier"),O([m(Z)],Ce.prototype,"strengthZ"),O([m()],Ce.prototype,"strengthZMultiplier");class We{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(e,t,s,o){const r=this.widthOverTrail.evaluate(s,o);return e*=r,e}getColor(e,t,s){const o=this.colorOverTrail.evaluate(s),r=this.colorOverLifetime.evaluate(t);e.x*=o.r*r.r,e.y*=o.g*r.g,e.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(e.w*=o.alpha*r.alpha)}}O([m()],We.prototype,"enabled"),O([m()],We.prototype,"attachRibbonToTransform"),O([m(sa)],We.prototype,"colorOverLifetime"),O([m(sa)],We.prototype,"colorOverTrail"),O([m()],We.prototype,"dieWithParticles"),O([m()],We.prototype,"inheritParticleColor"),O([m(Z)],We.prototype,"lifetime"),O([m()],We.prototype,"lifetimeMultiplier"),O([m()],We.prototype,"minVertexDistance"),O([m()],We.prototype,"mode"),O([m()],We.prototype,"ratio"),O([m()],We.prototype,"ribbonCount"),O([m()],We.prototype,"shadowBias"),O([m()],We.prototype,"sizeAffectsLifetime"),O([m()],We.prototype,"sizeAffectsWidth"),O([m()],We.prototype,"splitSubEmitterRibbons"),O([m()],We.prototype,"textureMode"),O([m(Z)],We.prototype,"widthOverTrail"),O([m()],We.prototype,"widthOverTrailMultiplier"),O([m()],We.prototype,"worldSpace");class qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new S),a(this,"_temp2",new S),a(this,"_temp3",new S),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new ne)}update(e){this._system=e}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,s,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),f=this.z.evaluate(d);if(this._temp.set(-p,g,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const y=this._temp2.set(s.x,s.y,s.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,_=this.orbitalZMultiplier,w=u*Math.PI*2*10,x=Math.cos(w*v),k=Math.sin(w*v),M=Math.cos(w*b),T=Math.sin(w*b),D=Math.cos(w*_),z=Math.sin(w*_),U=y.x*(M*D)+y.y*(M*z)+y.z*-T,E=y.x*(k*T*D-x*z)+y.y*(k*T*z+x*D)+y.z*(k*M),$=y.x*(x*T*D+k*z)+y.y*(x*T*z-k*D)+y.z*(x*M),H=this._temp3.set(y.x-U,y.y-E,y.z-$);H.normalize(),H.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=H.x,o.y+=H.y,o.z+=H.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}O([m()],qe.prototype,"enabled"),O([m()],qe.prototype,"space"),O([m(Z)],qe.prototype,"orbitalX"),O([m(Z)],qe.prototype,"orbitalY"),O([m(Z)],qe.prototype,"orbitalZ"),O([m()],qe.prototype,"orbitalXMultiplier"),O([m()],qe.prototype,"orbitalYMultiplier"),O([m()],qe.prototype,"orbitalZMultiplier"),O([m()],qe.prototype,"orbitalOffsetX"),O([m()],qe.prototype,"orbitalOffsetY"),O([m()],qe.prototype,"orbitalOffsetZ"),O([m(Z)],qe.prototype,"speedModifier"),O([m()],qe.prototype,"speedModifierMultiplier"),O([m(Z)],qe.prototype,"x"),O([m()],qe.prototype,"xMultiplier"),O([m(Z)],qe.prototype,"y"),O([m()],qe.prototype,"yMultiplier"),O([m(Z)],qe.prototype,"z"),O([m()],qe.prototype,"zMultiplier");class Vt{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"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 s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}O([m()],Vt.prototype,"animation"),O([m()],Vt.prototype,"enabled"),O([m()],Vt.prototype,"cycleCount"),O([m(Z)],Vt.prototype,"frameOverTime"),O([m()],Vt.prototype,"frameOverTimeMultiplier"),O([m()],Vt.prototype,"numTilesX"),O([m()],Vt.prototype,"numTilesY"),O([m(Z)],Vt.prototype,"startFrame"),O([m()],Vt.prototype,"startFrameMultiplier"),O([m()],Vt.prototype,"rowMode"),O([m()],Vt.prototype,"rowIndex"),O([m()],Vt.prototype,"spriteCount"),O([m()],Vt.prototype,"timeMode");class Ts{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}O([m()],Ts.prototype,"enabled"),O([m()],Ts.prototype,"separateAxes"),O([m(Z)],Ts.prototype,"x"),O([m()],Ts.prototype,"xMultiplier"),O([m(Z)],Ts.prototype,"y"),O([m()],Ts.prototype,"yMultiplier"),O([m(Z)],Ts.prototype,"z"),O([m()],Ts.prototype,"zMultiplier");class hs{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=W.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}O([m()],hs.prototype,"enabled"),O([m()],hs.prototype,"range"),O([m()],hs.prototype,"separateAxes"),O([m(Z)],hs.prototype,"x"),O([m()],hs.prototype,"xMultiplier"),O([m(Z)],hs.prototype,"y"),O([m()],hs.prototype,"yMultiplier"),O([m(Z)],hs.prototype,"z"),O([m()],hs.prototype,"zMultiplier");class gt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new S),a(this,"_temp2",new S)}apply(e,t,s,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>h){this._temp.copy(t).normalize().multiplyScalar(h);const d=this.dampen*.5;t.x=W.lerp(t.x,this._temp.x,d),t.y=W.lerp(t.y,this._temp.y,d),t.z=W.lerp(t.z,this._temp.z,d),s.x=W.lerp(s.x,this._temp.x,d),s.y=W.lerp(s.y,this._temp.y,d),s.z=W.lerp(s.z,this._temp.z,d)}}}}O([m()],gt.prototype,"enabled"),O([m()],gt.prototype,"dampen"),O([m(Z)],gt.prototype,"drag"),O([m()],gt.prototype,"dragMultiplier"),O([m(Z)],gt.prototype,"limit"),O([m()],gt.prototype,"limitMultiplier"),O([m()],gt.prototype,"separateAxes"),O([m(Z)],gt.prototype,"limitX"),O([m()],gt.prototype,"limitXMultiplier"),O([m(Z)],gt.prototype,"limitY"),O([m()],gt.prototype,"limitYMultiplier"),O([m(Z)],gt.prototype,"limitZ"),O([m()],gt.prototype,"limitZMultiplier"),O([m()],gt.prototype,"multiplyDragByParticleSize"),O([m()],gt.prototype,"multiplyDragByParticleVelocity"),O([m()],gt.prototype,"space");const yh=class MC{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new S),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var e;const t=new MC;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new S),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new S),this.system._iv_velocity}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}}applyCurrent(e,t,s){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const o=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(o),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};O([m()],yh.prototype,"enabled"),O([m(Z)],yh.prototype,"curve"),O([m()],yh.prototype,"curveMultiplier"),O([m()],yh.prototype,"mode");let Py=yh;class _i{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t,s,o){const r=e.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,s);return o.x*=c,o.y*=c,o.z*=c,o}}O([m()],_i.prototype,"enabled"),O([m(ie)],_i.prototype,"range"),O([m()],_i.prototype,"separateAxes"),O([m(Z)],_i.prototype,"size"),O([m()],_i.prototype,"sizeMultiplier"),O([m(Z)],_i.prototype,"x"),O([m()],_i.prototype,"xMultiplier"),O([m(Z)],_i.prototype,"y"),O([m()],_i.prototype,"yMultiplier"),O([m(Z)],_i.prototype,"z"),O([m()],_i.prototype,"zMultiplier");class Ol{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(e,t,s){const o=e.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,t);s.x*=l.r,s.y*=l.g,s.z*=l.b,"alpha"in l&&(s.w*=l.alpha)}}O([m()],Ol.prototype,"enabled"),O([m(ie)],Ol.prototype,"range"),O([m(sa)],Ol.prototype,"color"),new S(1,1,1),new S(0,0,1);class Oy{constructor(e,t,s,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new S),a(this,"v2_",new S),a(this,"_emitterMatrix",new Gm),a(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=s,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new ki(()=>new Gm,r)}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===ky.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===ky.Death){let o=e.life;if(e[kl]!==void 0&&(o=e[kl]),!(e.age+t*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const s=new Gm;s.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||s.multiplyMatrices(this._emitterMatrix,s),this.subParticleSystem.emit(t,e.emissionState,s)}}var p2=Object.defineProperty,Ve=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&p2(e,t,o),o};const tr=C("debugparticles"),m2=C("noprogressive"),g2=C("debugprogressive");var ky=(n=>(n[n.Birth=0]="Birth",n[n.Collision=1]="Collision",n[n.Death=2]="Death",n[n.Trigger=3]="Trigger",n[n.Manual=4]="Manual",n))(ky||{});class ds extends j{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&B()){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(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){tr&&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=On,t.map.premultiplyAlpha=!1);const s=new Me;s.copy(t),e?this.trailMaterial=s:this.particleMaterial=s}t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1),e&&t.side===yo&&(t=t.clone(),t.side=xd,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!m2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,g2&&console.log("Load material LOD",t.name),Xe.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof q&&(t=this.particleMesh.geometry),t===null)){t=new zs(1,1);const s=t.attributes.uv;for(let o=0;o<s.count;o++)s.setX(o,1-s.getX(o))}return new q(t,this.getMaterial())}}Ve([m()],ds.prototype,"renderMode"),Ve([m(Pe)],ds.prototype,"particleMaterial"),Ve([m(Pe)],ds.prototype,"trailMaterial"),Ve([m()],ds.prototype,"maxParticleSize"),Ve([m()],ds.prototype,"minParticleSize"),Ve([m()],ds.prototype,"velocityScale"),Ve([m()],ds.prototype,"cameraVelocityScale"),Ve([m()],ds.prototype,"lengthScale");class jp{constructor(e,t=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=e,this._factor=t}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 My{constructor(e){a(this,"type","value"),a(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}}class f2 extends My{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class y2 extends My{constructor(){super(...arguments),a(this,"_lastPosition",new S),a(this,"_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 o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const s=this.system.maxParticles-this.system.currentParticles;return W.clamp(e,0,s/this.system.deltaTime)}}class v2 extends My{genValue(){return this.system.isPlaying,0}}class ir{constructor(e){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class b2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(e,t){const s=this.system.textureSheetAnimation;if(s.enabled){const o=e.age/e.life,r=s.evaluate(o);r!==void 0&&(e.uvTile=r)}}}const aS=Symbol("particleRotation");class _2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(e){e[aS]=Math.random()}update(e,t){if(e.rotation===void 0)return;const s=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(s,e[aS])*t:this.system.renderer.renderMode===Jn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(s,o)*t}}}const lS=Symbol("sizeLerpFactor"),w2=new S;class x2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(e){e[lS]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const s=e.age/e.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(s,void 0,e[lS]).x);let r=1;this.system.renderer.renderMode!==Jn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=X(e.startSize).multiplyScalar(o*r);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=pS(this.system,w2);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const kl=Symbol("particleLife"),Ry=Symbol("trailLifetime"),cS=Symbol("trailStartLength"),Ty=Symbol("trailWidthRandom");class S2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(e){e instanceof eb&&(e[kl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Ry]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Ry]),e[cS]=e.length,e[Ty]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof eb){const s=e,o=e.age/e[kl],r=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=e.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,s[Ty]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,s[Ty]),h.color.copy(e.color),this.system.trails.getColor(h.color,o,d)}if(e.age>e[kl]){e.velocity.set(0,0,0);const c=(e.age-e[kl])/e[Ry];s.length=W.lerp(e[cS],0,c)}}}}const Dp=Symbol("startVelocity"),hS=Symbol("gravityModifier"),Ey=Symbol("gravitySpeed"),Bp=Symbol("velocity lerp factor"),Ay=new S;class C2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new S)}initialize(e){var t,s;const o=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(e,e.position);e.velocity.x=r.x*e.startSpeed,e.velocity.y=r.y*e.startSpeed,e.velocity.z=r.z*e.startSpeed,(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Dp]?e[Dp].copy(e.velocity):e[Dp]=e.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[hS]=l*o,e[Ey]=l*o*.5,e[Bp]=Math.random(),(s=this.system.velocityOverLifetime)==null||s.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===fh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var s;const o=e[Dp],r=e[hS];if(r!==0){const g=r*e[Ey];Ay.copy(this._gravityDirection).multiplyScalar(g),e[Ey]+=t*.05,o.add(Ay)}e.velocity.copy(o);const l=e.age/e.life;(s=this.system.inheritVelocity)!=null&&s.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,l,e[Bp]);const c=this.system.noise;c.enabled&&c.apply(0,e.position,e.velocity,t,e.age,e.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(e.size=h.evaluate(e.velocity,l,e[Bp],e.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(e.velocity,e[Bp],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(e.position,o,e.velocity,e.size,l,t,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const dS=Symbol("colorLerpFactor"),uS=new he(1,1,1,1),oa=new he(1,1,1,1);class P2 extends ir{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;oa.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(uS.copy(t.color),oa.multiply(uS)),oa.convertLinearToSRGB(),e.startColor.set(oa.r,oa.g,oa.b,oa.alpha),e.color.copy(e.startColor),e[dS]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const s=e.age/e.life,o=this.system.colorOverLifetime.color.evaluate(s,e[dS]);e.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class O2{constructor(e){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new CO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new y2(this.system)}get anim(){return this.system.textureSheetAnimation}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()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new jp(this.system.main.startLifetime)}get startSpeed(){return new jp(this.system.main.startSpeed)}get startRotation(){return new jp(this.system.main.startRotation)}get startSize(){return new jp(this.system.main.startSize)}get startColor(){return new xO(new SO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new v2(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Tn.Trail;switch(this.system.renderer.renderMode){case Jn.Billboard:return Tn.BillBoard;case Jn.Stretch:return Tn.StretchedBillBoard;case Jn.HorizontalBillboard:return Tn.HorizontalBillBoard;case Jn.VerticalBillboard:return Tn.VerticalBillBoard;case Jn.Mesh:return Tn.Mesh}return Tn.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Jn.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const s=t.clone();s.premultiplyAlpha=!1,s.colorSpace=On,this.clonedTexture.original=t,this.clonedTexture.clone=s}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Cf(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new f2(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??jP}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===fh.World}}class k2{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const $t=class Pm extends j{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new S),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new S),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(e=!1){var t;e&&P.foreachComponent(this.gameObject,s=>{s instanceof Pm&&s!==this&&s.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Pm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,s=>{s instanceof Pm&&s!==this&&s.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new k2),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}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.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}get container(){return this._container}get worldspace(){return this.main.simulationSpace===fh.World}get localspace(){return this.main.simulationSpace===fh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}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 ir&&(e.system=this),tr&&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,s=t.indexOf(e);return s!==-1&&((B()||tr)&&console.debug("Remove custom ParticleSystem Behaviour",s,e),t.splice(s,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}set bursts(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Ip)){const o=new Ip;Na(o,s),e[t]=o}}this._bursts=e}set subEmitterSystems(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Fp)){const o=new Fp;Na(o,s),e[t]=o}}tr&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}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(ds),!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 A,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new _O,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new O2(this),this._particleSystem=new wO(this._interface),this._particleSystem.addBehavior(new x2(this)),this._particleSystem.addBehavior(new P2(this)),this._particleSystem.addBehavior(new b2(this)),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new C2(this)),this._particleSystem.addBehavior(new S2(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),tr&&(console.log(this),this.gameObject.add(new Pi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof q&&this._interface.renderMode==Tn.Mesh&&Xe.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Tn.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,t,s,o;(e=this._container)==null||e.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(s=this._particleSystem)==null||s.emitter.removeFromParent(),(o=this._particleSystem)==null||o.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(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var e;if(!((e=this.emission)!=null&&e.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,s=this.main.duration,o=this.main.startLifetime.getMax(),r=Math.min(Math.max(s,o)/Math.max(.01,this.main.simulationSpeed),1e3),l=Math.ceil(r/t),c=Date.now();tr&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${s}, Lifetime: ${o}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}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 s=this.layer;t.layers.mask=1<<s}}onUpdate(){var e,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const s=this.context.mainCamera;if(s){const l=Ge(s);this._cameraScale=l.x}const o=!this.worldspace,r=this.gameObject;if(Se(r,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ge(this.gameObject,this._worldScale),o&&this._container&&(e=this.gameObject)!=null&&e.parent){const l=pS(this,Ay);this._container.matrix.makeScale(l.x,l.y,l.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),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():B()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const s=(e=t.particleSystem)==null?void 0:e._particleSystem;if(s){t.particleSystem._isUsedAsSubsystem=!0;const o=new Oy(this,this._particleSystem,t.particleSystem,s);o.emitterType=t.type,o.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(o)}else tr&&console.warn("Could not add SubParticleSystem",t,this)}}};Ve([m(Lp)],$t.prototype,"colorOverLifetime"),Ve([m(Wt)],$t.prototype,"main"),Ve([m(to)],$t.prototype,"emission"),Ve([m(na)],$t.prototype,"sizeOverLifetime"),Ve([m(Cy)],$t.prototype,"shape"),Ve([m(Ce)],$t.prototype,"noise"),Ve([m(We)],$t.prototype,"trails"),Ve([m(qe)],$t.prototype,"velocityOverLifetime"),Ve([m(gt)],$t.prototype,"limitVelocityOverLifetime"),Ve([m(Py)],$t.prototype,"inheritVelocity"),Ve([m(Ol)],$t.prototype,"colorBySpeed"),Ve([m(Vt)],$t.prototype,"textureSheetAnimation"),Ve([m(Ts)],$t.prototype,"rotationOverLifetime"),Ve([m(hs)],$t.prototype,"rotationBySpeed"),Ve([m(_i)],$t.prototype,"sizeBySpeed");let vh=$t;class Fp{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(e,t){const s=this.particleSystem;if(s instanceof vh)return;let o="";s&&typeof s.guid=="string"&&(o=s.guid,this.particleSystem=P.findByGuid(o,t)),tr&&!(this.particleSystem instanceof vh)&&console.warn("Could not find particle system for sub emitter",o,t,this)}}function pS(n,e){if(e.set(1,1,1),n.gameObject.parent&&n.localspace)switch(n.main.scalingMode){case Sy.Local:e=Ge(n.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!n.unsupported_scaling_mode){n.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+Sy[n.main.scalingMode]+" is not supported";B()&&be(t),console.warn(t,n.name,n)}e=Ge(n.gameObject,e);break}return e}class Wl extends j{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const e=P.getComponentInParent(this.gameObject,ks);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,di);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(se.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(se.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield xf(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Wl.hashCode(e),s=Wl.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(s,e,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(s,e,r)}}assignColor(e,t,s){let o=s.material;o&&(o._playerMaterial!==t&&(o=o.clone(),o._playerMaterial=t,s.material=o),o.color=e)}static hashCode(e){var t=0,s,o;if(e.length===0)return t;for(s=0;s<e.length;s++)o=e.charCodeAt(s),t=(t<<5)-t+o,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,s=(e&65280)>>8,o=e&255;return new re(t/255,s/255,o/255)}}const bh=C("debugpost");let Iy=null;function M2(n){Iy=n}function mS(n){let e=n.gameObject;for(;e;){for(const t of du(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function R2(n){let e=mS(n);if(!e)if(Iy){bh&&console.warn("Adding postprocessing manager to the scene.");const t=n.scene;e=Ei(t,Iy)}else B()&&console.warn("No post processing manager found");return e}const ft={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 ot=null;function T2(n){bh==="verbose"&&console.debug("Before ordering effects",[...n]),ot||(ot=new Map,ot.set(L.POSTPROCESSING.MODULE.NormalPass,ft.NormalPass),ot.set(L.POSTPROCESSING.MODULE.DepthDownsamplingPass,ft.DepthDownsamplingPass),ot.set(L.POSTPROCESSING.MODULE.SMAAEffect,ft.SMAA),ot.set(L.POSTPROCESSING.MODULE.SSAOEffect,ft.SSAO),ot.set(L.POSTPROCESSING_AO.MODULE.N8AOPostPass,ft.SSAO),ot.set(L.POSTPROCESSING_AO.MODULE.N8AOPass,ft.SSAO),ot.set(L.POSTPROCESSING.MODULE.TiltShiftEffect,ft.TiltShift),ot.set(L.POSTPROCESSING.MODULE.DepthOfFieldEffect,ft.DepthOfField),ot.set(L.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ft.ChromaticAberration),ot.set(L.POSTPROCESSING.MODULE.BloomEffect,ft.Bloom),ot.set(L.POSTPROCESSING.MODULE.SelectiveBloomEffect,ft.Bloom),ot.set(L.POSTPROCESSING.MODULE.VignetteEffect,ft.Vignette),ot.set(L.POSTPROCESSING.MODULE.PixelationEffect,ft.Pixelation),ot.set(L.POSTPROCESSING.MODULE.ToneMappingEffect,ft.ToneMapping),ot.set(L.POSTPROCESSING.MODULE.HueSaturationEffect,ft.HueSaturation),ot.set(L.POSTPROCESSING.MODULE.BrightnessContrastEffect,ft.BrightnessContrast)),n.sort((e,t)=>{const s=typeof e.priority=="number"?e.priority:ot.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,o=typeof t.priority=="number"?t.priority:ot.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return s===Number.NEGATIVE_INFINITY?(bh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):o===Number.NEGATIVE_INFINITY?(bh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):s-o}),bh==="verbose"&&console.debug("After ordering effects",[...n])}var E2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,gS=(n,e,t,s)=>{for(var o=A2(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&E2(e,t,o),o};const I2=C("debugpost");class N{constructor(e){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),e!==void 0&&this.initialize(e)}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)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;I2&&typeof s=="number"&&typeof e=="number"&&(s?.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,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}gS([m()],N.prototype,"overrideState"),gS([m()],N.prototype,"value");class L2 extends es{constructor(){super([N])}onSerialize(e,t){}onDeserialize(e,t){const s=t.target,o=t.path;let r;if(s&&o&&(r=s[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof e=="object"&&"value"in e){const l=e.value;r.initialize(l),r.overrideState=e.overrideState}else r.value=e;return r}}new L2;var j2=Object.defineProperty,D2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&j2(e,t,o),o};const Ly=C("debugpost");class rt extends j{constructor(e=void 0){if(super(),a(this,"order"),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const s=e[t],o=this[t];o instanceof N?o.initialize(s):o!==void 0&&(this[t]=s)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Ly&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),Ly&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=R2(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Ly&&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 s=this[t];s instanceof N&&s.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const s=e.value;return this[t].value=s,!0}}}D2([m()],rt.prototype,"active");var B2=Object.defineProperty,F2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&B2(e,t,o),o};const U2=C("debugpost"),jy={};function us(n,e){jy[n]=e}function z2(n){return n.__type in jy?jy[n.__type]:(U2&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),rt)}class Up{constructor(){a(this,"components",[])}__init(e){var t;(t=this.components)==null||t.forEach(s=>{s.gameObject===void 0&&e.gameObject.addComponent(s),s.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}F2([jr([n=>z2(n),rt])],Up.prototype,"components");var N2=Object.defineProperty,W2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&N2(e,t,o),o};const V2=C("debugpost");class _h extends rt{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var e;const t=new L.POSTPROCESSING.MODULE.SMAAEffect({preset:((e=this.preset)==null?void 0:e.value)??L.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:L.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=s=>{V2&&console.log("Antialiasing preset changed to",s),t.applyPreset(s)},t}}W2([m(N)],_h.prototype,"preset"),us("Antialiasing",_h);var $2=Object.defineProperty,Dy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&$2(e,t,o),o},zp;const Np=(zp=class extends rt{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.7)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=n=>n,this.intensity.valueProcessor=n=>n,this.scatter.valueProcessor=n=>n}onCreateEffect(){let n;if(this.selectiveBloom==null&&(this.selectiveBloom=zp.useSelectiveBloom),this.selectiveBloom){const e=n=new L.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else n=new L.POSTPROCESSING.MODULE.BloomEffect({blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{n.intensity=e},this.threshold.onValueChanged=e=>{n.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{n.luminancePass.enabled=!0,n.luminanceMaterial.smoothing=e,n.mipmapBlurPass&&(n.mipmapBlurPass.radius=Cn.lerp(.1,.9,e))},n}},a(zp,"useSelectiveBloom",!1),zp);Dy([m(N)],Np.prototype,"threshold"),Dy([m(N)],Np.prototype,"intensity"),Dy([m(N)],Np.prototype,"scatter");let Wp=Np;us("Bloom",Wp);var H2=Object.defineProperty,G2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&H2(e,t,o),o};class wh extends rt{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new L.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new ie(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}}G2([m(N)],wh.prototype,"intensity"),us("ChromaticAberration",wh);var xh=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n[n.AgX=3]="AgX",n[n.KhronosNeutral=4]="KhronosNeutral",n))(xh||{});const fS=new Map;function By(n){switch(n){case 0:return zm;case 1:return Um;case 2:return bd;case 3:return vd;case 4:return Pa;default:return fS.has(n)||(fS.set(n,!0),console.warn("[Postprocessing] Unknown tone mapping mode",n)),Pa}}function q2(n){switch(n){case zm:return 0;case bd:return 2;case vd:return 3;case Pa:return 1;case Um:return 1;default:return 0}}function Vp(n){switch(n){case zm:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case bd:return L.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case vd:return L.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Pa:return L.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Um:return L.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var X2=Object.defineProperty,yS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&X2(e,t,o),o};const Fy=C("debugpost");class sr extends rt{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1)),a(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const t=xh[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=mS(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var e;if(this.mode.isInitialized==!1){const o=q2(this.context.renderer.toneMapping);Fy&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+o),this.mode.initialize(o)}(e=this._tonemappingEffect)==null||e.dispose();const t=By(this.mode.value),s=this._tonemappingEffect=new L.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vp(t)});return this.mode.onValueChanged=o=>{if(typeof o=="string")o=qw(o),s.mode=Vp(o);else{const r=By(o);s.mode=Vp(r)}s.name="ToneMapping ("+xh[o]+")",Fy&&console.log("[PostProcessing] ToneMapping mode changed to",xh[o],t,s.mode)},Fy&&console.log("[PostProcessing] Use ToneMapping",xh[this.mode.value],t,s.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),s}onBeforeRender(){var e;if(this._tonemappingEffect&&(e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=By(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const t=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=t}}}yS([m(N)],sr.prototype,"mode"),yS([m(N)],sr.prototype,"exposure"),us("Tonemapping",sr);var Q2=Object.defineProperty,$p=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Q2(e,t,o),o};class nr extends rt{constructor(){super(...arguments),a(this,"remap",!0),a(this,"postExposure",new N(1)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}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(){var e,t;const s=[];let o=(e=this.postprocessingContext)==null?void 0:e.components.find(c=>c instanceof sr);o||(o=new sr,(t=this.postprocessingContext)==null||t.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&o?o.exposure.value=c: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 r=new L.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new L.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,s.push(r),s.push(l),s}}$p([m(N)],nr.prototype,"postExposure"),$p([m(N)],nr.prototype,"contrast"),$p([m(N)],nr.prototype,"hueShift"),$p([m(N)],nr.prototype,"saturation"),us("ColorAdjustments",nr);var Y2=Object.defineProperty,ra=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Y2(e,t,o),o};const K2=C("debugpost");class Es extends rt{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300;return W.lerp(2,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return W.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){K2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new L.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(){}}ra([m()],Es.prototype,"mode"),ra([m(N)],Es.prototype,"focusDistance"),ra([m(N)],Es.prototype,"focalLength"),ra([m(N)],Es.prototype,"aperture"),ra([m(N)],Es.prototype,"gaussianMaxRadius"),ra([m(N)],Es.prototype,"resolutionScale"),ra([m(N)],Es.prototype,"bokehScale"),us("DepthOfField",Es);class Sh extends rt{constructor(e){super(),a(this,"effect"),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Z2=Object.defineProperty,J2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Z2(e,t,o),o};class Ch extends rt{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new L.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}J2([m(N)],Ch.prototype,"granularity"),us("PixelationEffect",Ch);var eI=Object.defineProperty,Ph=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&eI(e,t,o),o};class io extends rt{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new re(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof we){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,t=new L.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),s=new L.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),o=this._ssao=new L.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:s.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new re),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(t),r.push(s),r.push(o),r}}Ph([m(N)],io.prototype,"intensity"),Ph([m(N)],io.prototype,"falloff"),Ph([m(N)],io.prototype,"samples"),Ph([m(N)],io.prototype,"color"),Ph([m(N)],io.prototype,"luminanceInfluence"),us("ScreenSpaceAmbientOcclusion",io);var tI=Object.defineProperty,aa=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&tI(e,t,o),o};const iI=C("debugN8AO");var Uy=(n=>(n[n.Performance=0]="Performance",n[n.Low=1]="Low",n[n.Medium=2]="Medium",n[n.High=3]="High",n[n.Ultra=4]="Ultra",n))(Uy||{});class As extends rt{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new re(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Uy[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,s=this.context.domHeight,o=this._ssao=new L.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,s);o.name="SSAO_N8";const r=Uy[this.quality];o.setQualityMode(r),o.configuration.transparencyAware=!1;const l=new Vs(t,s);return o.configuration.beautyRenderTarget=l,o.configuration.autoRenderBeauty=!1,o.configuration.gammaCorrection=this.gammaCorrection,o.configuration.screenSpaceRadius=this.screenspaceRadius,iI&&(o.enableDebugMode(),console.log(o),setInterval(()=>{console.log("SSAO",o.lastTime)},1e3),setInterval(()=>{console.log("SSAO",o.enabled,{ssao:o,autoRenderBeauty:o.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{o.configuration.intensity=c},this.falloff.onValueChanged=c=>{o.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{o.configuration.aoRadius=c},this.color.onValueChanged=c=>{o.color||(o.color=new re),o.configuration.color.copy(c)},o}}aa([Tt(),m()],As.prototype,"gammaCorrection"),aa([m(N)],As.prototype,"aoRadius"),aa([m(N)],As.prototype,"falloff"),aa([m(N)],As.prototype,"intensity"),aa([m(N)],As.prototype,"color"),aa([Tt(),m()],As.prototype,"screenspaceRadius"),aa([Tt(),m()],As.prototype,"quality"),us("ScreenSpaceAmbientOcclusionN8",As);var sI=Object.defineProperty,nI=Object.getOwnPropertyDescriptor,vS=(n,e,t,s)=>{for(var o=nI(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sI(e,t,o),o};class Oh extends rt{constructor(){super(...arguments),a(this,"order",ft.Sharpening),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(oI())),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}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}}vS([m()],Oh.prototype,"amount"),vS([m()],Oh.prototype,"radius");function oI(){const n=`
|
|
1275
1275
|
void mainSupport() {
|
|
1276
1276
|
vUv = uv;
|
|
1277
1277
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
@@ -1318,11 +1318,11 @@ axisFormat %s
|
|
|
1318
1318
|
`;class t extends L.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:n,blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new Qi(1)],["radius",new Qi(1)]]),attributes:RO.CONVOLUTION})}}return t}var rI=Object.defineProperty,Ml=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&rI(e,t,o),o};class yn extends rt{constructor(){super(...arguments),a(this,"offset",new N(0)),a(this,"rotation",new N(0)),a(this,"focusArea",new N(.4)),a(this,"feather",new N(.3)),a(this,"kernelSize",new N(2)),a(this,"resolutionScale",new N(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=L.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new L.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:L.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}Ml([m(N)],yn.prototype,"offset"),Ml([m(N)],yn.prototype,"rotation"),Ml([m(N)],yn.prototype,"focusArea"),Ml([m(N)],yn.prototype,"feather"),Ml([m(N)],yn.prototype,"kernelSize"),Ml([m(N)],yn.prototype,"resolutionScale"),us("TiltShiftEffect",yn);var aI=Object.defineProperty,zy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&aI(e,t,o),o};class la extends rt{constructor(){super(...arguments),a(this,"color",new N({r:0,g:0,b:0,a:1})),a(this,"intensity",new N(0)),a(this,"center",new N({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new L.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}zy([m(N)],la.prototype,"color"),zy([m(N)],la.prototype,"intensity"),zy([m(N)],la.prototype,"center"),us("Vignette",la),globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const so=C("debugpost"),Ny=Symbol("needle:postprocessing-handler"),kh=Symbol("needle:previous-autoclear-state"),Mh=Symbol("needle:previous-tone-mapping");class Wy{constructor(e){a(this,"_composer",null),a(this,"_lastVolumeComponents"),a(this,"_effects",[]),a(this,"_isActive",!1),a(this,"context"),a(this,"_anyPassHasDepth",!1),a(this,"_anyPassHasNormal",!1),a(this,"_hasSmaaEffect",!1),a(this,"_customInputBuffer",null),a(this,"_customInputBufferId",0),a(this,"_multisampling",0),a(this,"_menuEntry",null),a(this,"_passIndices",null),this.context=e}getEffectIsActive(e){return e?this._isActive&&this._effects.some(t=>t.effect===e):!1}get isActive(){return this._isActive}get composer(){return this._composer}apply(e){return this._isActive=!0,this.onApply(this.context,e)}unapply(e=!0){var t,s;if(so&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const r of this._lastVolumeComponents)r.unapply();this._lastVolumeComponents.length=0}const o=this.context;o[Ny]===this&&(delete o[Ny],typeof o.renderer[kh]=="boolean"&&(o.renderer.autoClear=o.renderer[kh]),typeof o.renderer[Mh]=="number"&&(o.renderer.toneMapping=o.renderer[Mh])),(t=this._composer)==null||t.removeAllPasses(),e&&((s=this._composer)==null||s.dispose()),o.composer===this._composer&&(o.composer=null)}dispose(){this.unapply(!0);for(const e of this._effects)e.effect.dispose();this._effects.length=0,this._composer=null}async onApply(e,t){if(!t)return;await Promise.all([L.POSTPROCESSING.load(),L.POSTPROCESSING_AO.load()]),e[Ny]=this,so&&console.log("Apply Postprocessing Effects",t),this._lastVolumeComponents=[...t],this._effects.length=0;const s={handler:this,components:this._lastVolumeComponents};for(let o=0;o<this._lastVolumeComponents.length;o++){const r=this._lastVolumeComponents[o];if(r.context=e,r.apply){if(r.active){let l=function(d,u){return u?(u instanceof L.POSTPROCESSING.MODULE.Effect||u instanceof L.POSTPROCESSING.MODULE.Pass||console.warn(`PostprocessingEffect ${d} created neither Effect nor Pass - this might be caused by a bundler error or false import. Below you find some possible solutions:
|
|
1319
1319
|
- If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const c=r.apply(s);if(!c)continue;const h=r.typeName||r.constructor.name;if(Array.isArray(c))for(const d of c)l(h,d)&&this._effects.push({effect:d,typeName:r.typeName,priority:r.order});else{if(!l(h,c))continue;this._effects.push({effect:c,typeName:r.typeName,priority:r.order})}}}else r.active&&be("Volume component is not a VolumeComponent: "+r.__type)}this.applyEffects(e)}get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){var t;if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const s=e.mainCameraComponent,o=e.renderer,r=e.scene,l=s.threeCamera;if(typeof o[kh]=="boolean"&&(o.autoClear=o[kh]),o[kh]=o.autoClear,typeof o[Mh]=="number"&&(o.toneMapping=o[Mh]),o[Mh]=o.toneMapping,o.toneMapping!=_d&&!this._effects.find(p=>p instanceof L.POSTPROCESSING.MODULE.ToneMappingEffect)){const p=new L.POSTPROCESSING.MODULE.ToneMappingEffect;p.name=`ToneMapping (${o.toneMapping})`,p.mode=Vp(o.toneMapping),this._effects.push({typeName:"ToneMapping",effect:p,priority:ft.ToneMapping})}this._composer||(this._composer=new L.POSTPROCESSING.MODULE.EffectComposer(o,{frameBufferType:Nm,stencilBuffer:!0})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const c=e.composer;c.setMainCamera(l),c.setRenderer(o),c.setMainScene(r),c.autoRenderToScreen=!0,c.multisampling=0;for(const p of c.passes)p.dispose();c.removeAllPasses();const h=new L.POSTPROCESSING.MODULE.RenderPass(r,l);h.name="RenderPass",h.mainScene=r,c.addPass(h);const d=h.render;(t=this._customInputBuffer)==null||t.dispose(),this._customInputBuffer=null,h.render=(p,g,f,y,v)=>{var b;g&&(g.samples=0,f&&(f.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==g.width||this._customInputBuffer.height!==g.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==g.texture.format||this._customInputBuffer.texture.type!==Nm)&&((b=this._customInputBuffer)==null||b.dispose(),this._customInputBuffer=new Vs(g.width,g.height,{format:g.texture.format,type:Nm,depthBuffer:g.depthBuffer,depthTexture:g.depthTexture?new Dv(g.width,g.height):void 0,stencilBuffer:g.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:g.texture.minFilter??Sd,magFilter:g.texture.magFilter??Sd,generateMipmaps:g.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&g.depthTexture&&(this._customInputBuffer.depthTexture.format=g.depthTexture.format,this._customInputBuffer.depthTexture.type=g.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),so&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),d.call(h,p,this._customInputBuffer,f,y,v),ec.blit(this._customInputBuffer.texture,g,{renderer:p,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{T2(this._effects);let p=!1,g=null;for(let v=this._effects.length-1;v>=0;v--){const b=this._effects[v].effect;if(b instanceof L.POSTPROCESSING.MODULE.ToneMappingEffect){if(p){so&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${b.name} and ${g?.name}. Only the last one added will be used.`),this._effects.splice(v,1);continue}g=b,p=!0}}const f=[];let y=!1;for(let v=0;v<this._effects.length;v++){const b=this._effects[v].effect;if(b instanceof L.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:b instanceof L.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(b instanceof L.POSTPROCESSING.MODULE.ToneMappingEffect&&g!==b))if(b instanceof L.POSTPROCESSING.MODULE.Effect){const _=b.getAttributes(),w=L.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;_&w&&(so&&console.log("[PostProcessing] Convolution effect: "+b.name),y&&(so&&console.log("[PostProcessing] \u2192 Merging effects ["+f.map(x=>x.name).join(", ")+"]"),this.createPassForMergeableEffects(f,c,l,r)),y=!0),f.push(b)}else b instanceof L.POSTPROCESSING.MODULE.Pass?(y=!1,this.createPassForMergeableEffects(f,c,l,r),b.renderToScreen=!1,c.addPass(b)):(y=!1,this.createPassForMergeableEffects(f,c,l,r),c.addPass(b))}this.createPassForMergeableEffects(f,c,l,r)}catch(p){console.error("Error while applying postprocessing effects",p),c.passes.forEach(g=>g.dispose()),c.removeAllPasses()}let u=!1;for(let p=c.passes.length-1;p>=0;p--){const g=c.passes[p];let f=!1,y=!1;g.enabled&&(u||(f=!0,y=!0),u=!0),g.renderToScreen=y,g?.configuration!==void 0?g.configuration.gammaCorrection=f:"autosetGamma"in g&&(g.autosetGamma=f),this._anyPassHasDepth||(this._anyPassHasDepth=g.needsDepthTexture)}so&&console.log("[PostProcessing] Passes \u2192",[...c.passes],`
|
|
1320
1320
|
---------------------------------
|
|
1321
|
-
\u2022 `+c.passes.map(p=>p.name).join(`
|
|
1321
|
+
\u2022 `+c.passes.map(p=>p.name||p.constructor.name+"*").join(`
|
|
1322
1322
|
\u2022 `)+`
|
|
1323
|
-
`),so&&this._onCreateEffectsDebug(this._composer,l)}createPassForMergeableEffects(e,t,s,o){if(e.length>0){const r=new L.POSTPROCESSING.MODULE.EffectPass(s,...e);r.name=e.map(l=>l.name).join(", "),r.mainScene=o,r.enabled=!0,r.renderToScreen=!1,t.addPass(r),e.length=0}}_onCreateEffectsDebug(e,t){if(so==="passes"){const s=new L.POSTPROCESSING.MODULE.DepthEffect({blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});s.name="Depth Effect";const o=new L.POSTPROCESSING.MODULE.EffectPass(t,s);if(o.name="Depth Effect Pass",o.enabled=!1,e.passes.push(o),this._passIndices!==null){const l=[e.passes[0]];this._passIndices.length>0&&l.push(...this._passIndices.filter(c=>c!==0).map(c=>e.passes[c]).filter(c=>c)),l.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",l),e.passes.length=0;for(const c of l)c.enabled=!0,c.renderToScreen=!1,e.addPass(c)}const r=this.context.menu;if(r&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const l=document.createElement("select");l.multiple=!0;const c=document.createElement("option");c.innerText="Final Output",c.value="-1",l.appendChild(c);for(const h of e.passes){const d=document.createElement("option");d.innerText=h.name,d.value=`${e.passes.indexOf(h)}`,d.title=h.name,l.appendChild(d)}r.appendChild(l),this._menuEntry=l,l.addEventListener("change",()=>{const h=Array.from(l.selectedOptions).map(d=>parseInt(d.value));h.length===1&&h[0]===-1?this._passIndices=null:this._passIndices=h,this.applyEffects(this.context)})}}}}var lI=Object.defineProperty,bS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&lI(e,t,o),o};const ca=C("debugpost");class Rl extends j{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let t=e;return t instanceof rt||(t=new Sh(t)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){var t,s,o,r;let l=-1;if(e instanceof rt?l=this._effects.indexOf(e):l=this._effects.findIndex(c=>c instanceof Sh&&c.effect===e),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,e;if(e instanceof rt){const c=(s=(t=this.sharedProfile)==null?void 0:t.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(o=this.sharedProfile)==null?void 0:o.components)==null||r.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;ca&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,De("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(ca||B())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
|
|
1323
|
+
`),so&&this._onCreateEffectsDebug(this._composer,l)}createPassForMergeableEffects(e,t,s,o){if(e.length>0){const r=new L.POSTPROCESSING.MODULE.EffectPass(s,...e);r.name=e.map(l=>l.name).join(", "),r.mainScene=o,r.enabled=!0,r.renderToScreen=!1,t.addPass(r),e.length=0}}_onCreateEffectsDebug(e,t){if(so==="passes"){const s=new L.POSTPROCESSING.MODULE.DepthEffect({blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});s.name="Depth Effect";const o=new L.POSTPROCESSING.MODULE.EffectPass(t,s);if(o.name="Depth Effect Pass",o.enabled=!1,e.passes.push(o),this._passIndices!==null){const l=[e.passes[0]];this._passIndices.length>0&&l.push(...this._passIndices.filter(c=>c!==0).map(c=>e.passes[c]).filter(c=>c)),l.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",l),e.passes.length=0;for(const c of l)c.enabled=!0,c.renderToScreen=!1,e.addPass(c)}const r=this.context.menu;if(r&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const l=document.createElement("select");l.multiple=!0;const c=document.createElement("option");c.innerText="Final Output",c.value="-1",l.appendChild(c);for(const h of e.passes){const d=document.createElement("option");d.innerText=h.name,d.value=`${e.passes.indexOf(h)}`,d.title=h.name,l.appendChild(d)}r.appendChild(l),this._menuEntry=l,l.addEventListener("change",()=>{const h=Array.from(l.selectedOptions).map(d=>parseInt(d.value));h.length===1&&h[0]===-1?this._passIndices=null:this._passIndices=h,this.applyEffects(this.context)})}}}}var lI=Object.defineProperty,bS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&lI(e,t,o),o};const ca=C("debugpost");class Rl extends j{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let t=e;return t instanceof rt||(t=new Sh(t),typeof e.order=="number"&&(t.order=e.order)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){var t,s,o,r;let l=-1;if(e instanceof rt?l=this._effects.indexOf(e):l=this._effects.findIndex(c=>c instanceof Sh&&c.effect===e),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,e;if(e instanceof rt){const c=(s=(t=this.sharedProfile)==null?void 0:t.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(o=this.sharedProfile)==null?void 0:o.components)==null||r.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;ca&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,De("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(ca||B())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
|
|
1324
1324
|
|
|
1325
|
-
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling*.5;s=Math.floor(s),s!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;s=Math.floor(s),s!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t,s;if(ca&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),B()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const o=this.sharedProfile.components;for(const r of o)r.active&&r.enabled&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const o of this._effects)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new Wy(this.context)),(t=this._postprocessing.apply(this._activeEffects))==null||t.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=Q.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ca&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${Q.isMobileDevice()})`)):ca&&console.warn("[PostProcessing] No composer found"))})):(s=this._postprocessing)==null||s.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const r=o[1],l=o[2];for(const c of this._activeEffects)if(((s=c.typeName)==null?void 0:s.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!Hp.has(r)){const h=new Array;Hp.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if(Hp.has(r)){const h=l.toLowerCase(),d=Hp.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(o.length===4&&o[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}bS([jr(Up)],Rl.prototype,"sharedProfile"),bS([jr()],Rl.prototype,"multisampling");const Hp=new Map;M2(Rl);async function Vy(n){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>FL);e.observedAttributes.includes(n)||e.observedAttributes.push(n)}var cI=Object.defineProperty,Pt=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&cI(e,t,o),o};const Gt=C("debugsceneswitcher"),hI=C("sceneswitcher:clearscene"),Gp="scene";Vy(Gp);const or=Promise.resolve(!1);class Ze extends j{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new xe),a(this,"sceneLoadingProgress",new xe),a(this,"sceneLoaded",new xe),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let s=!1;if(this.queryParameterName&&(s=await this.tryLoadFromQueryParam()),!s){const o=e?.state;if(o&&o.startsWith(this.guid)){const r=o.substr(this.guid.length+2);Gt&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=t}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const s=t.x/this.context.domWidth;s>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):s<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const s=parseInt(t)-1;if(s>=0){this.trySelectSceneFromValue(s);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof A?P.remove(e.asset):e instanceof A&&P.remove(e);Gt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Be.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Gp){const s=this.context.domElement.getAttribute(Gp);s!==null&&this.trySelectSceneFromValue(s)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new dI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Gp);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Be.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const t of this._menuButtons)t.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ce(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,s,o;if(Gt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(t=this.scenes)==null?void 0:t.find(c=>c.url===e);if(!l){const c=ce.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return or}if(!((o=this.scenes)!=null&&o.length))return or;if(e<0){if(this.clamp)return or;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return or;e=0}const r=this.scenes[e];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var t;if(!(e instanceof ce)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof A){const o=(t=this.scenes)==null?void 0:t.indexOf(e);e=new ce(e.name,void 0,e),o>=0&&(this.scenes[o]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Gt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t!=null&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}e.hasUrl?e.unload():e.asset instanceof A&&P.remove(e.asset)}}async __internalSwitchScene(e){var t,s,o,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:c}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((u,p)=>{var g;if(Gt){const f=p.loaded/p.total,y="["+"=".repeat(Math.floor(f*20))+"-".repeat(20-Math.floor(f*20))+"]";console.debug(`[SceneSwitcher] Download ${(f*100).toFixed(1)} % ${y}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return Gt&&console.warn("Adding loaded scene prevented:",e,d),!1;if(!e.asset)return Gt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===c){if(Gt&&console.log("ADD",e.url),this._currentScene=e,hI){const g=((o=this.context.mainCameraComponent)==null?void 0:o.gameObject)||this.context.mainCamera;g?.removeFromParent();const f=this.gameObject.removeFromParent();Ai(this.context.scene,!0,!0),this.context.scene=new Si,this.context.scene.add(f),g&&this.context.scene.add(g)}if(P.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=kn,this.context.scene.background=g):Gt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(e instanceof A?g=e.name:e.url&&(g=_S(e.url))),(r=this.queryParameterName)!=null&&r.length)ql(this.queryParameterName,g,this.useHistory);else{const f=history.state,y=this.guid+"::"+c;f!==y&&history.pushState(y,"unused",location.href)}}const u=this.tryGetSceneEventListener(e.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ce)return t.preload()}return or}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return or;const t=C(this.queryParameterName);return typeof t=="boolean"?or:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const s=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const r=this.scenes[o];if(!!r&&(r instanceof A?r.name:_S(r.url)).toLowerCase().includes(s))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Xt()&&console.warn('Can not find scene: "'+e+'"',this),or}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(s=>s!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Gt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const s=this.loadingScene.asset;P.add(s,this.gameObject);const o=this.tryGetSceneEventListener(s);if(o!=null&&o.sceneOpened){const r=o.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const s=this.tryGetSceneEventListener(this.gameObject);if(s&&s.sceneOpened){const o=s.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Gt&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,s=this.tryGetSceneEventListener(t);if(typeof s?.sceneClosing=="function"){const o=s.sceneClosing();o instanceof Promise&&await o}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const s=P.foreachComponent(e,o=>{const r=o;if(r.sceneClosing||r.sceneOpened)return r});if(t===0&&!s&&e.children.length)for(const o of e.children){const r=this.tryGetSceneEventListener(o,t+1);if(r)return r}return s||null}}Pt([m()],Ze.prototype,"autoLoadFirstScene"),Pt([m(ce)],Ze.prototype,"scenes"),Pt([m(ce)],Ze.prototype,"loadingScene"),Pt([m()],Ze.prototype,"queryParameterName"),Pt([m()],Ze.prototype,"useSceneName"),Pt([m()],Ze.prototype,"clamp"),Pt([m()],Ze.prototype,"useHistory"),Pt([m()],Ze.prototype,"useKeyboard"),Pt([m()],Ze.prototype,"useSwipe"),Pt([m()],Ze.prototype,"useSceneLighting"),Pt([m()],Ze.prototype,"useSceneBackground"),Pt([m()],Ze.prototype,"preloadNext"),Pt([m()],Ze.prototype,"preloadPrevious"),Pt([m()],Ze.prototype,"preloadConcurrent"),Pt([m()],Ze.prototype,"createMenuButtons"),Pt([m(xe)],Ze.prototype,"sceneLoadingStart"),Pt([m(xe)],Ze.prototype,"sceneLoadingProgress"),Pt([m(xe)],Ze.prototype,"sceneLoaded");function _S(n){const e=n.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:n}class dI{constructor(e,t=1,s=1,o=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=s,this.maxConcurrent=o}begin(e){if(this._isRunning)return;Gt&&console.log("Preload begin",{delay:e}),this._isRunning=!0;let t=-10,s,o;const r=this._switcher.scenes,l=Date.now()+e,c=setInterval(()=>{if(this.allLoaded()&&(Gt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,o=0,s=0);const h=o%2===0;h&&(s+=1),o+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(s>d)return;const u=h?t+s:t-s;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];Gt&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new uI(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e!=null&&e.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class uI{constructor(e,t,s){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=e,this.asset=t,this.tasks=s,s.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Gt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Gt&&console.log("Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function pI(){return new Promise((n,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),n())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function mI(n){await pI(),n()}var gI=Object.defineProperty,fI=Object.getOwnPropertyDescriptor,$i=(n,e,t,s)=>{for(var o=s>1?void 0:s?fI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&gI(e,t,o),o};const Ot=C("debugvideo");var wS=(n=>(n[n.None=0]="None",n[n.AdjustHeight=1]="AdjustHeight",n[n.AdjustWidth=2]="AdjustWidth",n))(wS||{}),xS=(n=>(n[n.VideoClip=0]="VideoClip",n[n.Url=1]="Url",n))(xS||{}),SS=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(SS||{});class yt extends j{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var e;Ot&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Ot&&console.log("HLS: loaded",this.clip))}),mI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&B()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Ot&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Ot&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Ot&&console.log("VideoPlayer.onEnable",xS[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Ot&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Ot&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(s=>{var o;console.log(s),Ot&&console.error("Error playing video",s,"CODE="+s.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Ot&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Ot&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Ot&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Ot&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Ot&&console.log("Set Video src",t),this._videoElement.src=t):(Ot&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new DP(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Mn,e&&this.handleBeginPlaying(e),Ot&&console.log("Video: handle playing done...",t,e),!0):(Ot&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new yI(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Ot&&console.log("created video element",e),e}handleBeginPlaying(e){var t,s;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let o=this.gameObject;switch(this.renderMode){case 3:o=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,o||(o=(s=P.getComponent(this.gameObject,Ui))==null?void 0:s.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!o){console.error("Missing target for video material renderer",this.name,SS[this.renderMode],this);return}const r=o.material;if(r){this._targetObjects.push(o),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),o.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,s=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&s===this.clip&&this._isPlaying;){if(!s||typeof s=="string")return;let o;for(const r of s.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===o){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ge(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/o*r.scale.x*l;break;case 2:r.scale.x=o*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Ot&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}$i([m()],yt.prototype,"playOnAwake",2),$i([m()],yt.prototype,"aspectMode",2),$i([m(URL)],yt.prototype,"clip",2),$i([m()],yt.prototype,"source",2),$i([m(URL)],yt.prototype,"url",1),$i([m()],yt.prototype,"renderMode",2),$i([m()],yt.prototype,"targetMaterialProperty",2),$i([m(Ui)],yt.prototype,"targetMaterialRenderer",2),$i([m(je)],yt.prototype,"targetTexture",2),$i([m()],yt.prototype,"time",2),$i([m()],yt.prototype,"playbackSpeed",1),$i([m()],yt.prototype,"isLooping",1),$i([m()],yt.prototype,"audioOutputMode",1);class yI{constructor(e){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=e,this._input=new vI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=xo.createPrimitive(Sr.Quad,{material:new bI(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const s=this._screenspaceModeQuad;this.context.scene.add(s),this.updateScreenspaceMaterialUniforms();const o=s.material;o?.reset(),(e=this._input)==null||e.enable(o)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class vI{constructor(e){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=o=>{o.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=o=>{this.overlay.enabled&&(e.zoom+=o.deltaY*5e-4,o.preventDefault())},{passive:!1});const t=new ie;window.addEventListener("mousemove",o=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new ie(o.movementX,o.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",o=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(o.movementX,o.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let s=0;window.addEventListener("touchstart",o=>{if(o.touches.length<2){this.context.time.time-s<.3&&this.overlay.stop(),s=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",o=>{if(!this._isPinching||!this._material)return;const r=o.touches[0],l=o.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class bI extends Ns{constructor(e){super(),a(this,"_offset",new ie),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new fe(0,0,1,1)}},this.vertexShader=`
|
|
1325
|
+
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling*.5;s=Math.floor(s),s!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;s=Math.floor(s),s!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t,s;if(ca&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),B()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const o=this.sharedProfile.components;for(const r of o)r.active&&r.enabled&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const o of this._effects)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new Wy(this.context)),(t=this._postprocessing.apply(this._activeEffects))==null||t.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=Q.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ca&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${Q.isMobileDevice()})`)):ca&&console.warn("[PostProcessing] No composer found"))})):(s=this._postprocessing)==null||s.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const r=o[1],l=o[2];for(const c of this._activeEffects)if(((s=c.typeName)==null?void 0:s.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!Hp.has(r)){const h=new Array;Hp.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if(Hp.has(r)){const h=l.toLowerCase(),d=Hp.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(o.length===4&&o[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}bS([jr(Up)],Rl.prototype,"sharedProfile"),bS([jr()],Rl.prototype,"multisampling");const Hp=new Map;M2(Rl);async function Vy(n){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>FL);e.observedAttributes.includes(n)||e.observedAttributes.push(n)}var cI=Object.defineProperty,Pt=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&cI(e,t,o),o};const Ht=C("debugsceneswitcher"),hI=C("sceneswitcher:clearscene"),Gp="scene";Vy(Gp);const or=Promise.resolve(!1);class Ze extends j{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new xe),a(this,"sceneLoadingProgress",new xe),a(this,"sceneLoaded",new xe),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let s=!1;if(this.queryParameterName&&(s=await this.tryLoadFromQueryParam()),!s){const o=e?.state;if(o&&o.startsWith(this.guid)){const r=o.substr(this.guid.length+2);Ht&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=t}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const s=t.x/this.context.domWidth;s>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):s<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const s=parseInt(t)-1;if(s>=0){this.trySelectSceneFromValue(s);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof A?P.remove(e.asset):e instanceof A&&P.remove(e);Ht&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Be.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Gp){const s=this.context.domElement.getAttribute(Gp);s!==null&&this.trySelectSceneFromValue(s)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new dI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Gp);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Be.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const t of this._menuButtons)t.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ce(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,s,o;if(Ht&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(t=this.scenes)==null?void 0:t.find(c=>c.url===e);if(!l){const c=ce.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return or}if(!((o=this.scenes)!=null&&o.length))return or;if(e<0){if(this.clamp)return or;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return or;e=0}const r=this.scenes[e];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var t;if(!(e instanceof ce)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof A){const o=(t=this.scenes)==null?void 0:t.indexOf(e);e=new ce(e.name,void 0,e),o>=0&&(this.scenes[o]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ht&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t!=null&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}e.hasUrl?e.unload():e.asset instanceof A&&P.remove(e.asset)}}async __internalSwitchScene(e){var t,s,o,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:c}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((u,p)=>{var g;if(Ht){const f=p.loaded/p.total,y="["+"=".repeat(Math.floor(f*20))+"-".repeat(20-Math.floor(f*20))+"]";console.debug(`[SceneSwitcher] Download ${(f*100).toFixed(1)} % ${y}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return Ht&&console.warn("Adding loaded scene prevented:",e,d),!1;if(!e.asset)return Ht&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===c){if(Ht&&console.log("ADD",e.url),this._currentScene=e,hI){const g=((o=this.context.mainCameraComponent)==null?void 0:o.gameObject)||this.context.mainCamera;g?.removeFromParent();const f=this.gameObject.removeFromParent();Ai(this.context.scene,!0,!0),this.context.scene=new Si,this.context.scene.add(f),g&&this.context.scene.add(g)}if(P.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=kn,this.context.scene.background=g):Ht&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(e instanceof A?g=e.name:e.url&&(g=_S(e.url))),(r=this.queryParameterName)!=null&&r.length)ql(this.queryParameterName,g,this.useHistory);else{const f=history.state,y=this.guid+"::"+c;f!==y&&history.pushState(y,"unused",location.href)}}const u=this.tryGetSceneEventListener(e.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ce)return t.preload()}return or}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return or;const t=C(this.queryParameterName);return typeof t=="boolean"?or:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const s=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const r=this.scenes[o];if(!!r&&(r instanceof A?r.name:_S(r.url)).toLowerCase().includes(s))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Xt()&&console.warn('Can not find scene: "'+e+'"',this),or}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(s=>s!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Ht&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const s=this.loadingScene.asset;P.add(s,this.gameObject);const o=this.tryGetSceneEventListener(s);if(o!=null&&o.sceneOpened){const r=o.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const s=this.tryGetSceneEventListener(this.gameObject);if(s&&s.sceneOpened){const o=s.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Ht&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,s=this.tryGetSceneEventListener(t);if(typeof s?.sceneClosing=="function"){const o=s.sceneClosing();o instanceof Promise&&await o}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const s=P.foreachComponent(e,o=>{const r=o;if(r.sceneClosing||r.sceneOpened)return r});if(t===0&&!s&&e.children.length)for(const o of e.children){const r=this.tryGetSceneEventListener(o,t+1);if(r)return r}return s||null}}Pt([m()],Ze.prototype,"autoLoadFirstScene"),Pt([m(ce)],Ze.prototype,"scenes"),Pt([m(ce)],Ze.prototype,"loadingScene"),Pt([m()],Ze.prototype,"queryParameterName"),Pt([m()],Ze.prototype,"useSceneName"),Pt([m()],Ze.prototype,"clamp"),Pt([m()],Ze.prototype,"useHistory"),Pt([m()],Ze.prototype,"useKeyboard"),Pt([m()],Ze.prototype,"useSwipe"),Pt([m()],Ze.prototype,"useSceneLighting"),Pt([m()],Ze.prototype,"useSceneBackground"),Pt([m()],Ze.prototype,"preloadNext"),Pt([m()],Ze.prototype,"preloadPrevious"),Pt([m()],Ze.prototype,"preloadConcurrent"),Pt([m()],Ze.prototype,"createMenuButtons"),Pt([m(xe)],Ze.prototype,"sceneLoadingStart"),Pt([m(xe)],Ze.prototype,"sceneLoadingProgress"),Pt([m(xe)],Ze.prototype,"sceneLoaded");function _S(n){const e=n.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:n}class dI{constructor(e,t=1,s=1,o=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=s,this.maxConcurrent=o}begin(e){if(this._isRunning)return;Ht&&console.log("Preload begin",{delay:e}),this._isRunning=!0;let t=-10,s,o;const r=this._switcher.scenes,l=Date.now()+e,c=setInterval(()=>{if(this.allLoaded()&&(Ht&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,o=0,s=0);const h=o%2===0;h&&(s+=1),o+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(s>d)return;const u=h?t+s:t-s;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];Ht&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new uI(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e!=null&&e.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class uI{constructor(e,t,s){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=e,this.asset=t,this.tasks=s,s.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ht&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ht&&console.log("Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function pI(){return new Promise((n,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),n())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function mI(n){await pI(),n()}var gI=Object.defineProperty,fI=Object.getOwnPropertyDescriptor,$i=(n,e,t,s)=>{for(var o=s>1?void 0:s?fI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&gI(e,t,o),o};const Ot=C("debugvideo");var wS=(n=>(n[n.None=0]="None",n[n.AdjustHeight=1]="AdjustHeight",n[n.AdjustWidth=2]="AdjustWidth",n))(wS||{}),xS=(n=>(n[n.VideoClip=0]="VideoClip",n[n.Url=1]="Url",n))(xS||{}),SS=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(SS||{});class yt extends j{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var e;Ot&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Ot&&console.log("HLS: loaded",this.clip))}),mI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&B()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Ot&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Ot&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Ot&&console.log("VideoPlayer.onEnable",xS[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Ot&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Ot&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(s=>{var o;console.log(s),Ot&&console.error("Error playing video",s,"CODE="+s.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Ot&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Ot&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Ot&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Ot&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Ot&&console.log("Set Video src",t),this._videoElement.src=t):(Ot&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new DP(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Mn,e&&this.handleBeginPlaying(e),Ot&&console.log("Video: handle playing done...",t,e),!0):(Ot&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new yI(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Ot&&console.log("created video element",e),e}handleBeginPlaying(e){var t,s;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let o=this.gameObject;switch(this.renderMode){case 3:o=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,o||(o=(s=P.getComponent(this.gameObject,Ui))==null?void 0:s.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!o){console.error("Missing target for video material renderer",this.name,SS[this.renderMode],this);return}const r=o.material;if(r){this._targetObjects.push(o),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),o.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,s=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&s===this.clip&&this._isPlaying;){if(!s||typeof s=="string")return;let o;for(const r of s.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===o){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ge(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/o*r.scale.x*l;break;case 2:r.scale.x=o*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Ot&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}$i([m()],yt.prototype,"playOnAwake",2),$i([m()],yt.prototype,"aspectMode",2),$i([m(URL)],yt.prototype,"clip",2),$i([m()],yt.prototype,"source",2),$i([m(URL)],yt.prototype,"url",1),$i([m()],yt.prototype,"renderMode",2),$i([m()],yt.prototype,"targetMaterialProperty",2),$i([m(Ui)],yt.prototype,"targetMaterialRenderer",2),$i([m(je)],yt.prototype,"targetTexture",2),$i([m()],yt.prototype,"time",2),$i([m()],yt.prototype,"playbackSpeed",1),$i([m()],yt.prototype,"isLooping",1),$i([m()],yt.prototype,"audioOutputMode",1);class yI{constructor(e){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=e,this._input=new vI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=xo.createPrimitive(Sr.Quad,{material:new bI(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const s=this._screenspaceModeQuad;this.context.scene.add(s),this.updateScreenspaceMaterialUniforms();const o=s.material;o?.reset(),(e=this._input)==null||e.enable(o)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class vI{constructor(e){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=o=>{o.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=o=>{this.overlay.enabled&&(e.zoom+=o.deltaY*5e-4,o.preventDefault())},{passive:!1});const t=new ie;window.addEventListener("mousemove",o=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new ie(o.movementX,o.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",o=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(o.movementX,o.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let s=0;window.addEventListener("touchstart",o=>{if(o.touches.length<2){this.context.time.time-s<.3&&this.overlay.stop(),s=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",o=>{if(!this._isPinching||!this._material)return;const r=o.touches[0],l=o.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class bI extends Ns{constructor(e){super(),a(this,"_offset",new ie),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new fe(0,0,1,1)}},this.vertexShader=`
|
|
1326
1326
|
uniform sampler2D map;
|
|
1327
1327
|
uniform float screenAspect;
|
|
1328
1328
|
uniform vec4 offsetScale;
|
|
@@ -1386,12 +1386,12 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
|
|
|
1386
1386
|
// be blended onto the scene.
|
|
1387
1387
|
gl_FragColor = vec4(direct, max);
|
|
1388
1388
|
return;
|
|
1389
|
-
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new Rv;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 Me;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)}}PS([m()],Th.prototype,"mode"),PS([m(he)],Th.prototype,"shadowColor");var SI=Object.defineProperty,Eh=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SI(e,t,o),o};const jt=C("debugskybox");Vy("background-image"),Vy("environment-image");function OS(n,e,t,s,o){if(e==="transparent"||e!=null&&e.startsWith("rgb")||e!=null&&e.startsWith("#"))return console.warn(`Needle Engine: Invalid ${o} value (${e}). Did you mean to set background-color instead?`),null;const r=new Xp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(n.scene,r);const l=c=>{typeof c=="string"&&(jt&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return gb(n.domElement,o,l),r.addEventListener("destroy",()=>{jt&&console.log("Destroyed attribute remote skybox",o),fb(n.domElement,o,l)}),r.setSkybox(e)}const qp=new Array;pe.registerCallback(me.ContextCreationStart,n=>{const e=n.context,t=e.domElement.getAttribute("background-image"),s=e.domElement.getAttribute("environment-image");if(t){jt&&console.log("Creating remote skybox to load "+t);const o=OS(e,t,!0,!1,"background-image");o&&qp.push(o)}if(s){jt&&console.log("Creating remote environment to load "+s);const o=OS(e,s,!1,!0,"environment-image");o&&qp.push(o)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(qp).finally(()=>{qp.length=0}));function kS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function MS(n){const e=kS().find(t=>t.src===n);return e?(jt&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function CI(n){const e=await n;Xg(e,!0),Te(e)}function PI(n,e){const t=kS();for(;t.length>5;){const s=t.shift();s&&CI(s.texture)}e.then(s=>Xg(s,!1)),t.push({src:n,texture:e})}const ha=class extends j{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",n=>{if(this.allowDrop&&n.dataTransfer)for(const e of n.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&n.preventDefault()}),a(this,"onDrop",n=>{var e,t,s,o;if(this.allowDrop&&n.dataTransfer){for(const r of n.dataTransfer.types)if(jt&&console.log(r),r==="text/uri-list"){const l=n.dataTransfer.getData(r);jt&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),jt&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),n.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),n.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. 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 h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:n,url:l,apply:d=>{n.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=n.dataTransfer.files.item(0);if(jt&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(MS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);n.preventDefault(),this.setSkybox(h,l.name)}else n.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var n;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,hi.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(n=this.context.mainCameraComponent)==null||n.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):jt&&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(n,e){var t;if(!this.activeAndEnabled||(n=OI(n,this.environment,this.background),!n))return!1;try{n.startsWith("/")||n.startsWith(".")?new URL(n,window.location.href):new URL(n)}catch{return jt&&console.warn("RemoteSkybox: Invalid URL",n,this.name),!1}if(e??(e=n),this.isValidTextureType(e)||console.warn("Potentially invalid skybox url",e,"on",this.name),jt&&console.log("Set remote skybox url: "+n),this._prevUrl===n&&this._prevLoadedEnvironment)return this.apply(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=n;const s=await this.loadTexture(n,e);if(!s)return jt&&console.warn("RemoteSkybox: Failed to load texture from url",n),!1;if(!this.enabled)return jt&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==n)return jt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=n;const o=n.lastIndexOf("/");return s.name=n.substring(o>=0?o+1:0),this._loader instanceof Sa&&(s.colorSpace=Mn),this._prevLoadedEnvironment=s,this.apply(),!0}async loadTexture(n,e){var t,s,o,r,l;if(!n)return Promise.resolve(null);e??(e=n);const c=MS(e);if(c){const g=await c;if(((s=(t=g.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(o=g.source)==null?void 0:o.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof Pd||(this._loader=new Pd);else if(d)this._loader instanceof Vm||(this._loader=new Vm);else if(u){if(!(this._loader instanceof hO)){const{ktx2Loader:g}=Wm(this.context.renderer);this._loader=g}}else this._loader instanceof Sa||(this._loader=new Sa);jt&&console.log("Loading skybox: "+n);const p=this._loader.loadAsync(n);return PI(e,p),await p}apply(){var n;const e=this._prevLoadedEnvironment;e&&(e instanceof BP||e instanceof FP||(e.mapping=UP,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),jt&&console.log("Set remote skybox",this.url,!hi.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!hi.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((n=this.context.mainCameraComponent)==null?void 0:n.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(n){return n.startsWith("http://")||n.startsWith("https://")}isValidTextureType(n){for(const e of this.validTextureTypes)if(n.endsWith(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)}};Eh([Q0(ha.prototype.urlChangedSyncField),m(URL)],ha.prototype,"url"),Eh([m()],ha.prototype,"allowDrop"),Eh([m()],ha.prototype,"background"),Eh([m()],ha.prototype,"environment"),Eh([m()],ha.prototype,"allowNetworking");let Xp=ha;function OI(n,e,t){const s=e&&!t;switch(n?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var kI=Object.defineProperty,Qp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kI(e,t,o),o},Yp;const Ah=(Yp=class extends j{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Qa.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=ee(this.target),t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Qa.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&Qa.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&Qa.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply(Yp._invertForward);const t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a(Yp,"_invertForward",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),Yp);Qp([m(A)],Ah.prototype,"target"),Qp([m()],Ah.prototype,"followFactor"),Qp([m()],Ah.prototype,"rotateFactor"),Qp([m()],Ah.prototype,"positionAxes");let Kp=Ah;var MI=Object.defineProperty,Ih=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&MI(e,t,o),o};const Lh=C("debugspatialtrigger"),RS=new po,TS=new po;function RI(n,e){return RS.mask=n,TS.mask=e,RS.test(TS)}class vn extends j{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Lh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Zp.triggers)RI(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)}onEnterTrigger(e){var t;Lh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Lh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Ih([m()],vn.prototype,"triggerMask"),Ih([m(xe)],vn.prototype,"onEnter"),Ih([m(xe)],vn.prototype,"onStay"),Ih([m(xe)],vn.prototype,"onExit");var Tl;const ES=(Tl=class extends j{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Lh&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;Tl.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Do),(n=this.boxHelper)==null||n.showHelper(null,Lh))}onDisable(){Tl.triggers.splice(Tl.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Tl,"triggers",[]),Tl);Ih([m()],ES.prototype,"triggerMask");let Zp=ES;var TI=Object.defineProperty,EI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TI(e,t,o),o};const Hi=C("debugspectator");class Jp extends j{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.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){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,o=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&o?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new LI(this.context,this),this._networking=new BI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,hi),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new AI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Co.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new re(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of di.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const o=t.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of di.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const o of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?o.UpdateVisible(rn.FirstPerson):o.UpdateVisible(rn.ThirdPerson)}}}EI([m()],Jp.prototype,"useKeys");class AI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}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=P.addComponent(this.cam.gameObject,Kp)),this.target||(this.target=new A),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&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(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,o,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Co.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Co.Browser?d.quaternion.copy(II):d.quaternion.identity()}}}const II=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class LI{constructor(e,t){a(this,"context"),a(this,"spectator"),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",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Be.PointerDown,o=>{s=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Dn;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const o=s.object,r=P.getComponentInParent(o,di),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class jI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class DI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class BI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),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(se.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(se.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,o=s?t:e?.userId,r=new jI(this.context.connection.connectionId,o,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new DI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const o=this.followers.indexOf(s);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"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)}}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 Hi&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}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):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Jv),(t||new Sn).__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 Fr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Fr).__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 FI=Object.defineProperty,UI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&FI(e,t,o),o};const em="SCAM";Eg(em,Sn.getRootAsSyncedCameraModel);const Gi=new Hm;class zI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Gi.clear();const s=Gi.createString(this.guid),o=Gi.createString(this.userId);Sn.startSyncedCameraModel(Gi),Sn.addGuid(Gi,s),Sn.addUserId(Gi,o);const r=ee(e),l=Id(e);Sn.addPos(Gi,Fr.createVec3(Gi,r.x,r.y,r.z)),Sn.addRot(Gi,Fr.createVec3(Gi,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel(Gi);Gi.finish(c,em),t.sendBinary(Gi.asUint8Array())}}}var jh;const AS=(jh=class extends j{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].obj: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(em,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(em,this._receiveCallback)}update(){for(const s in this.remoteCams){const o=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){B()&&console.log("Remote cam timeout",s),o!=null&&o.obj&&P.destroy(o.obj),delete this.remoteCams[s],o&&delete this.userToCamMap[o.userId],jh.instances.push(o),this.context.players.removePlayerView(o.userId,Co.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=ee(n),t=Se(n);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Co.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Bs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,jh.instances.push(s);const d=P.getOrAddComponent(h,di);d.connectionId=t,d.avatar=h}else return;const o=s.obj;this.context.players.setPlayerView(t,o,Co.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ms.markDirty(o);const r=n.pos();r&&vr(o,r.x(),r.y(),r.z());const l=n.rot();l&&Jl(o,l.x(),l.y(),l.z())}},a(jh,"instances",[]),jh);UI([m([A,ce])],AS.prototype,"cameraPrefab");let $y=AS;var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,ar=(n,e,t,s)=>{for(var o=s>1?void 0:s?WI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NI(e,t,o),o};const Hy="view",Gy=C("debugsyncedroom");class Is extends j{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(s),De("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(Mt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Hy)||C(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),Gy&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Hy);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(){var e;(e=this._roomButton)==null||e.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){var t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){s=!0;const r=pb(o.toString());this.roomName=r}else if(this.joinRandomRoom&&(console.log("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&&!s?((Gy||B())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1389
|
+
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new Rv;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 Me;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)}}PS([m()],Th.prototype,"mode"),PS([m(he)],Th.prototype,"shadowColor");var SI=Object.defineProperty,Eh=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SI(e,t,o),o};const Gt=C("debugskybox");Vy("background-image"),Vy("environment-image");function OS(n,e,t,s,o){if(e==="transparent"||e!=null&&e.startsWith("rgb")||e!=null&&e.startsWith("#"))return console.warn(`Needle Engine: Invalid ${o} value (${e}). Did you mean to set background-color instead?`),null;const r=new Xp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(n.scene,r);const l=c=>{typeof c=="string"&&(Gt&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return gb(n.domElement,o,l),r.addEventListener("destroy",()=>{Gt&&console.log("Destroyed attribute remote skybox",o),fb(n.domElement,o,l)}),r.setSkybox(e)}const qp=new Array;pe.registerCallback(me.ContextCreationStart,n=>{const e=n.context,t=e.domElement.getAttribute("background-image"),s=e.domElement.getAttribute("environment-image");if(t){Gt&&console.log("Creating remote skybox to load "+t);const o=OS(e,t,!0,!1,"background-image");o&&qp.push(o)}if(s){Gt&&console.log("Creating remote environment to load "+s);const o=OS(e,s,!1,!0,"environment-image");o&&qp.push(o)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(qp).finally(()=>{qp.length=0}));function kS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function MS(n){const e=kS().find(t=>t.src===n);return e?(Gt&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function CI(n){const e=await n;e&&(Xg(e,!0),Te(e))}function PI(n,e){const t=kS();for(;t.length>5;){const s=t.shift();s&&CI(s.texture)}e.then(s=>Xg(s,!1)),t.push({src:n,texture:e})}const ha=class extends j{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validProtocols",["file:","blob:","data:"]),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",n=>{if(this.allowDrop&&n.dataTransfer)for(const e of n.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&n.preventDefault()}),a(this,"onDrop",n=>{var e,t,s,o;if(this.allowDrop&&n.dataTransfer){for(const r of n.dataTransfer.types)if(Gt&&console.log(r),r==="text/uri-list"){const l=n.dataTransfer.getData(r);Gt&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Gt&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),n.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),n.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. 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 h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:n,url:l,apply:d=>{n.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=n.dataTransfer.files.item(0);if(Gt&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(MS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);n.preventDefault(),this.setSkybox(h,l.name)}else n.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var n;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,hi.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(n=this.context.mainCameraComponent)==null||n.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Gt&&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(n,e){var t,s;if(!this.activeAndEnabled||(n=OI(n,this.environment,this.background),!n))return!1;if(e??(e=n),this.isValidTextureType(e)||console.warn('Potentially invalid skybox URL: "'+e+'" on '+(this.name||((t=this.gameObject)==null?void 0:t.name)||"context")),Gt&&console.log("Set remote skybox url: "+n),this._prevUrl===n&&this._prevLoadedEnvironment)return this.apply(),!0;(s=this._prevLoadedEnvironment)==null||s.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=n;const o=await this.loadTexture(n,e);if(!o)return Gt&&console.warn("RemoteSkybox: Failed to load texture from url",n),!1;if(!this.enabled)return Gt&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==n)return Gt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=n;const r=n.lastIndexOf("/");return o.name=n.substring(r>=0?r+1:0),this._loader instanceof Sa&&(o.colorSpace=Mn),this._prevLoadedEnvironment=o,this.apply(),!0}async loadTexture(n,e){var t,s,o,r,l;if(!n)return Promise.resolve(null);e??(e=n);const c=MS(e);if(c){const g=await c;if(((s=(t=g?.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(o=g?.source)==null?void 0:o.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof Pd||(this._loader=new Pd);else if(d)this._loader instanceof Vm||(this._loader=new Vm);else if(u){if(!(this._loader instanceof hO)){const{ktx2Loader:g}=Wm(this.context.renderer);this._loader=g}}else this._loader instanceof Sa||(this._loader=new Sa);Gt&&console.log("Loading skybox: "+n);const p=this._loader.loadAsync(n).catch(g=>(console.warn("RemoteSkybox: Failed to load texture from url:",n),null));return PI(e,p),await p}apply(){var n;const e=this._prevLoadedEnvironment;e&&(e instanceof BP||e instanceof FP||(e.mapping=UP,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),Gt&&console.log("Set remote skybox",this.url,!hi.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!hi.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((n=this.context.mainCameraComponent)==null?void 0:n.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(n){return n.startsWith("http://")||n.startsWith("https://")}isValidTextureType(n){for(const e of this.validTextureTypes)if(n.endsWith(e))return!0;for(const e of this.validProtocols)if(n.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)}};Eh([Q0(ha.prototype.urlChangedSyncField),m(URL)],ha.prototype,"url"),Eh([m()],ha.prototype,"allowDrop"),Eh([m()],ha.prototype,"background"),Eh([m()],ha.prototype,"environment"),Eh([m()],ha.prototype,"allowNetworking");let Xp=ha;function OI(n,e,t){const s=e&&!t;switch(n?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var kI=Object.defineProperty,Qp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kI(e,t,o),o},Yp;const Ah=(Yp=class extends j{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Qa.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=ee(this.target),t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Qa.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&Qa.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&Qa.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply(Yp._invertForward);const t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a(Yp,"_invertForward",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),Yp);Qp([m(A)],Ah.prototype,"target"),Qp([m()],Ah.prototype,"followFactor"),Qp([m()],Ah.prototype,"rotateFactor"),Qp([m()],Ah.prototype,"positionAxes");let Kp=Ah;var MI=Object.defineProperty,Ih=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&MI(e,t,o),o};const Lh=C("debugspatialtrigger"),RS=new po,TS=new po;function RI(n,e){return RS.mask=n,TS.mask=e,RS.test(TS)}class vn extends j{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Lh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Zp.triggers)RI(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)}onEnterTrigger(e){var t;Lh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Lh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Ih([m()],vn.prototype,"triggerMask"),Ih([m(xe)],vn.prototype,"onEnter"),Ih([m(xe)],vn.prototype,"onStay"),Ih([m(xe)],vn.prototype,"onExit");var Tl;const ES=(Tl=class extends j{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Lh&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;Tl.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Do),(n=this.boxHelper)==null||n.showHelper(null,Lh))}onDisable(){Tl.triggers.splice(Tl.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Tl,"triggers",[]),Tl);Ih([m()],ES.prototype,"triggerMask");let Zp=ES;var TI=Object.defineProperty,EI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TI(e,t,o),o};const Hi=C("debugspectator");class Jp extends j{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.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){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,o=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&o?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new LI(this.context,this),this._networking=new BI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,hi),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new AI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Co.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new re(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of di.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const o=t.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of di.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const o of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?o.UpdateVisible(rn.FirstPerson):o.UpdateVisible(rn.ThirdPerson)}}}EI([m()],Jp.prototype,"useKeys");class AI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}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=P.addComponent(this.cam.gameObject,Kp)),this.target||(this.target=new A),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&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(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,o,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Co.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Co.Browser?d.quaternion.copy(II):d.quaternion.identity()}}}const II=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class LI{constructor(e,t){a(this,"context"),a(this,"spectator"),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",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Be.PointerDown,o=>{s=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Dn;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const o=s.object,r=P.getComponentInParent(o,di),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class jI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class DI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class BI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),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(se.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(se.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,o=s?t:e?.userId,r=new jI(this.context.connection.connectionId,o,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new DI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const o=this.followers.indexOf(s);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"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)}}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 Hi&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}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):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Jv),(t||new Sn).__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 Fr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Fr).__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 FI=Object.defineProperty,UI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&FI(e,t,o),o};const em="SCAM";Eg(em,Sn.getRootAsSyncedCameraModel);const Gi=new Hm;class zI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Gi.clear();const s=Gi.createString(this.guid),o=Gi.createString(this.userId);Sn.startSyncedCameraModel(Gi),Sn.addGuid(Gi,s),Sn.addUserId(Gi,o);const r=ee(e),l=Id(e);Sn.addPos(Gi,Fr.createVec3(Gi,r.x,r.y,r.z)),Sn.addRot(Gi,Fr.createVec3(Gi,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel(Gi);Gi.finish(c,em),t.sendBinary(Gi.asUint8Array())}}}var jh;const AS=(jh=class extends j{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].obj: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(em,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(em,this._receiveCallback)}update(){for(const s in this.remoteCams){const o=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){B()&&console.log("Remote cam timeout",s),o!=null&&o.obj&&P.destroy(o.obj),delete this.remoteCams[s],o&&delete this.userToCamMap[o.userId],jh.instances.push(o),this.context.players.removePlayerView(o.userId,Co.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=ee(n),t=Se(n);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Co.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Bs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,jh.instances.push(s);const d=P.getOrAddComponent(h,di);d.connectionId=t,d.avatar=h}else return;const o=s.obj;this.context.players.setPlayerView(t,o,Co.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ms.markDirty(o);const r=n.pos();r&&vr(o,r.x(),r.y(),r.z());const l=n.rot();l&&Jl(o,l.x(),l.y(),l.z())}},a(jh,"instances",[]),jh);UI([m([A,ce])],AS.prototype,"cameraPrefab");let $y=AS;var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,ar=(n,e,t,s)=>{for(var o=s>1?void 0:s?WI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NI(e,t,o),o};const Hy="view",Gy=C("debugsyncedroom");class Is extends j{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(s),De("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(Mt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Hy)||C(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),Gy&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Hy);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(){var e;(e=this._roomButton)==null||e.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){var t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){s=!0;const r=pb(o.toString());this.roomName=r}else if(this.joinRandomRoom&&(console.log("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&&!s?((Gy||B())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1390
1390
|
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.
|
|
1391
1391
|
Please choose one of the following options to fix this:
|
|
1392
1392
|
A) Set a room name in the SyncedRoom component
|
|
1393
1393
|
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1394
|
-
C) Set "joinRandomRoom" to true`),!1):(Gy&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}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()):B()&&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(Hy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Gl(),t=this.generateRoomName();C(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Km(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}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&&ql(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=C(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?ql(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Mt("group"),this._roomButtonIconLeave=Mt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(se.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(se.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(se.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}ar([m()],Is.prototype,"roomName",2),ar([m()],Is.prototype,"urlParameterName",2),ar([m()],Is.prototype,"joinRandomRoom",2),ar([m()],Is.prototype,"requireRoomParameter",2),ar([m()],Is.prototype,"autoRejoin",2),ar([m()],Is.prototype,"createJoinButton",2),ar([m()],Is.prototype,"createViewOnlyButton",2),ar([m()],Is.prototype,"roomPrefix",1);function VI(){const n=C("testwindowcount")||0;n&&n>0&&$I(n)}function $I(n){if(C("testwindow"))return null;const e=new URL(window.location.href);Ym(e.searchParams,$T,1),Ym(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const h of s)h.close()};const o=.05,r=128;let l=0,c=0;for(let h=0;h<n;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+o))+window.screenLeft,u=c*(r*(1+o))+window.screenTop+90+60*c;l+=1;const p=window.open(t,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}s.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<s.length;g++){const f=s[g];f!==p&&f.close()}s.length=0}}}return s}class qy extends j{awake(){VI()}}class Xy extends j{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(jc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new IS(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}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 Hm(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=xx(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}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 IS{constructor(e,t){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),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)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const o=e.worldQuaternion;if(this.rotation.x=o.x,this.rotation.y=o.y,this.rotation.z=o.z,this.rotation.w=o.w,this.fast=!1,t){const r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}a(IS,"temp",new S);var HI=Object.defineProperty,tm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&HI(e,t,o),o};const GI=C("debugsignals");class im{constructor(){a(this,"guid")}}tm([m()],im.prototype,"guid");class Dh{constructor(){a(this,"signal"),a(this,"reaction")}}tm([m(im)],Dh.prototype,"signal"),tm([m(xe)],Dh.prototype,"reaction");var Ls;const LS=(Ls=class extends j{constructor(){super(...arguments),a(this,"events")}static invoke(n){if(Ls.receivers[n]){const e=Ls.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){GI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)Ls.receivers[n.signal.guid]||(Ls.receivers[n.signal.guid]=[]),Ls.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(Ls.receivers[n.signal.guid]){const e=Ls.receivers[n.signal.guid].indexOf(this);e>=0&&Ls.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(s){console.error(s)}}},a(Ls,"receivers",{}),Ls);tm([m(Dh)],LS.prototype,"events");let Bh=LS;var qi=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(qi||{}),bn=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(bn||{}),Qy=(n=>(n.Signal="SignalEmitter",n))(Qy||{});const _n=C("debugtimeline");class Fh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,o=!0){if(t<0||t>=s.length)return 0;const r=s[t];if(o||e>=r.start&&e<=r.end){let l=1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);l*=c}if(r.easeOutDuration>0){const c=Math.min((r.end-e)/r.easeOutDuration,1);l*=c}return l}return 0}}class qI{constructor(e){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),o=s.name+".position",r=s.name+".quaternion";_n&&console.log(t.name,t.tracks,o);for(const l of t.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(o))this.rootStartPosition=new S().fromArray(l.values,0),this.rootEndPosition=new S().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),_n&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new V().fromArray(l.values,0),this.rootEndQuaternion=new V().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),_n)){const c=new Bt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class sm extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new S),a(this,"_totalOffsetRotation",new V),a(this,"_totalOffsetPosition2",new S),a(this,"_totalOffsetRotation2",new V),a(this,"_summedPos",new S),a(this,"_tempPos",new S),a(this,"_summedRot",new V),a(this,"_tempRot",new V),a(this,"_clipRotQuat",new V)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&fx(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var s,o;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const r=t.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of t.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!d||!u){const p=(o=this.mixer)==null?void 0:o.getRoot(),g=t.tracks[0],f=g.name.lastIndexOf("."),y=g.name.substring(0,f),v=y.substring(y.lastIndexOf(".")+1),b=p.getObjectByName(v);if(b)if(d){if(!u){const _=t.tracks[0].name.substring(0,f)+".quaternion";_n&&console.warn("Create quaternion track",v,b);const w=b.quaternion,x=new NP(_,[0,t.duration],[w.x,w.y,w.z,w.w,w.x,w.y,w.z,w.w]);t.tracks.push(x),this.createRotationInterpolant(t,e,x)}}else{const _=y+".position";_n&&console.warn("Create position track",v,b);const w=b.position,x=new zP(_,[0,t.duration],[w.x,w.y,w.z,w.x,w.y,w.z]);t.tracks.push(x),this.createPositionInterpolant(t,e,x)}}}bind(){if(!this._didBind){this._didBind=!0,_n&&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 qI(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,Rt)??null,this._animator&&fx(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,s=t.position,o=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new S(s.x,s.y,s.z)),o.isQuaternion||(t.rotation=new V(o.x,o.y,o.z,o.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new V(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,s,o,r,l,c,h;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 d=0,u=0,p=!1,g=!1,f=0;for(let y=0;y<this.clips.length;y++){const v=this.models[y],b=this.actions[y],_=v.asset;b.weight=0;const w=e>=v.start&&e<=v.end,x=v.preExtrapolationMode,k=v.postExtrapolationMode,M=y<this.clips.length-1?this.models[y+1]:null;let T=w,D=!1;if(!T&&!p&&v.end<e&&k!==bn.None?(!M||M.start>e)&&(T=!0,p=!0):y==0&&!T&&!g&&v.start>e&&x!==bn.None&&(!M||M.start<e)&&(T=!0,D=!0,g=!0),T){let z=this.weight;z*=this.evaluateWeight(e,y,this.models,T),z*=this.director.weight;let U=w;if(D)switch(x){case bn.Hold:break;case bn.Loop:e+=v.start,U=!0;break;default:e+=v.start,U=!0;break}let E=this.getClipTime(e,v),$=0;const H=_.duration;if(D&&x===bn.Hold&&(E=0),U){if(_.loop)for($+=Math.floor(E/(H+1e-6));E>H;)E-=H}else if(!w&&p)switch(k){case bn.Hold:E=this.getClipTime(v.end,v);break;case bn.Loop:E%=H;break;case bn.PingPong:const I=Math.floor(E/H)%2!==0;E%=H,I&&(E=H-E);break}v.reversed===!0?b.time=b.getClip().duration-E:b.time=E,b.timeScale=0;const F=Math.max(0,z);if(b.weight=F,f+=F,b.clampWhenFinished=!1,b.isRunning()||b.play(),this._useclipOffsets){const I=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,Y=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-z),d+=1;const te=this._summedPos.set(0,0,0),ae=this._tempPos.set(0,0,0),le=this._summedRot.identity(),ye=this._tempRot.identity(),He=_.rotation;He&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(He,z));const vt=this._actionOffsets[y];if(vt.hasOffsets)for(let mr=0;mr<$;mr++)vt.rootPositionOffset?ae.copy(vt.rootPositionOffset):ae.set(0,0,0),ae.applyQuaternion(le),this._clipRotQuat&&ae.applyQuaternion(this._clipRotQuat),vt.rootQuaternionOffset&&(ye.copy(vt.rootQuaternionOffset),le.multiply(ye)),te.add(ae);this._clipRotQuat&&Y.multiply(this._clipRotQuat),Y.multiply(le),_.position&&te.add(_.position),I.add(te)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(_n||B())&&(s=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&s.mixer&&this.mixer!==((r=(o=this._animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:r.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)),(l=this._animator)!=null&&l.runtimeAnimatorController){const y=Math.max(0,1-f);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(y)}else this.mixer.update(e)}createRotationInterpolant(e,t,s){var o;const r=s.createInterpolant.bind(s),l=new V;this.ensureTrackOffsets();const c=(o=this.trackOffset)==null?void 0:o.rotation;s.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(e,t,s){var o,r;const l=s.createInterpolant.bind(s),c=new S;this.ensureTrackOffsets();const h=(o=this.trackOffset)==null?void 0:o.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;s.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=f=>{var y,v,b;const _=g(f);if(c.set(_[0],_[1],_[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(y=this._actionOffsets.find(w=>w.clip===e))==null?void 0:y.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const w of this.director.animationCallbackReceivers)(b=w?.onTimelinePosition)==null||b.call(w,this.director,this.target,f,c);return _[0]=c.x,_[1]=c.y,_[2]=c.z,_},p}}}const XI=C("mutetimeline"),jS=class cd extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return vo(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const s=this.models[t];this.audio[t].setVolume(e?s.asset.volume:0)}}addModel(e){const t=new WP(this.listener);this.audio.push(t);const s=e;s._didTriggerPlay=!1,this.models.push(s)}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!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(XI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const o=t?.1:0;for(let r=0;r<this.models.length;r++){const l=this.models[r],c=this.audio[r],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),ns.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,_n&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(o),l._didTriggerPlay=!0);else{const u=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(u-p)>.3&&(c.offset=u,c.stop(),c.play(o))}let d=h.volume;if(this.track.volume!==void 0&&(d*=this.track.volume),t&&(d=0),l.easeInDuration>0){const u=Math.min((e-l.start)/l.easeInDuration,1);d*=u}if(l.easeOutDuration>0){const u=Math.min((l.end-e)/l.easeOutDuration,1);d*=u}c.setVolume(d*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,t=0,s=0){let o=null;const r=e-s,l=e+t;for(const c of this.models)if(this.isInTimeRange(c,r,l)){const h=this.audio[this.models.indexOf(c)],d=this.handleAudioLoading(c,h);d!==null&&(o===null&&(o=[]),o.push(d))}return o!==null?Promise.all(o):null}isInTimeRange(e,t,s){return t<=e.start&&s>=e.end||t>=e.start&&t<=e.end||s>=e.start&&s<=e.end}static dispose(){cd._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Dm);const s=this.getAudioFilePath(e.asset.clip);if(cd._audioBuffers.get(s)){const r=cd._audioBuffers.get(s);return r.then(l=>{l&&t.setBuffer(l)}),r}_n&&console.warn("LOAD audio track",s,this.director.sourceId);const o=new Promise((r,l)=>{this._audioLoader.load(s,c=>{t.setBuffer(c),r(c)},void 0,c=>{console.error("Error loading audio",c),r(null)})});return cd._audioBuffers.set(s,o),o}};a(jS,"_audioBuffers",new Map);let nm=jS;class Uh extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const s=this.director.context.time.deltaTime*1.5;for(let o=0;o<this.models.length;o++){const r=this.models[o],l=this.didTrigger[o],c=r.time-e;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<s)&&(h=!0)}if(h){if(!l)if(_n&&console.log("Trigger signal",e,r.time,r),this.didTrigger[o]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Bh.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[o]=!1)}}}class om extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const o=P.getComponent(s.sourceObject,El);this.timelines.push(o),o&&s.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const o=this.models[s],r=o.asset;if(e>=o.start&&e<=o.end){this._previousActiveModel=o;const l=this.getClipTime(e,o);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(t=this._previousActiveModel)==null?void 0:t.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var QI=Object.defineProperty,DS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&QI(e,t,o),o};const no=C("debugtimeline");var zh;const Yy=(zh=class extends j{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(no||Xt())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t,s,o;no&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),!this.isValid()&&(no||B())&&(no?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(e=this.playableAsset)==null?void 0:e.tracks,"IsArray?",Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this):(o=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&o.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var n,e,t;for(const s of this._audioTracks)(n=s.onEnable)==null||n.call(s);for(const s of this._customTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onEnable)==null||t.call(s);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(){var n,e,t;this.stop();for(const s of this._audioTracks)(n=s.onDisable)==null||n.call(s);for(const s of this._customTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onDisable)==null||t.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!ns.userInteractionRegistered&&this.waitForAudio;)await $s(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Oe.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&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 n of this._allTracks)for(const e of n)yield e}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.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(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case qi.Activation:if(!n&&!this._isPlaying)continue;for(let o=0;o<s.outputs.length;o++){const r=s.outputs[o];if(typeof r=="object"){let l=!1;if(s.clips)for(const h of s.clips)h.start<=t&&t<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,no&&console.warn(this.name,"set ActivationTrack-"+o,c.name,l,t))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(t);for(const s of this._audioTracks)s.evaluate(t);for(const s of this._signalTracks)s.evaluate(t);for(const s of this._controlTracks)s.evaluate(t);for(const s of this._customTracks)s.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Xl(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=P.findByGuid(s,n);o===null||typeof o!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(no&&console.log("Resolved binding",s,"to",o),e.outputs[t]=o)}else if(s===null){if(e.outputs.splice(t,1),zh.createTrackFunctions[e.type])continue;e.type!==qi.Audio&&e.type!==qi.Control&&e.type!==qi.Marker&&e.type!==qi.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===qi.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let o=s.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=P.findByGuid(o,n);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,e.name,s):(no&&console.log("Resolved binding",o,"to",r),s.asset.sourceObject=r)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let s=P.findObjectOfType(Nn,this.context);for(const o of this.playableAsset.tracks){const r=o.type,l=zh.createTrackFunctions[r];if(l!=null){const c=l(this,o);if(typeof c.evaluate=="function"){c.director=this,c.track=o,this._customTracks.push(c);continue}}if(o.type===qi.Animation){if(!o.clips||o.clips.length<=0){no&&console.warn("Animation track has no clips",o);continue}for(let c=o.outputs.length-1;c>=0;c--){let h=o.outputs[c];if(h instanceof A){const u=P.getOrAddComponent(h,Rt);u&&(h=u)}const d=(n=h?.gameObject)==null?void 0:n.animations;if(d){const u=new sm;u.trackOffset=o.trackOffset,u.director=this,u.track=o;for(let p=0;p<o.clips.length;p++){const g=o.clips[p],f=g.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const y=f.clip;let v=y;if((typeof v=="string"||typeof v=="number")&&(v=d.find(_=>_.name===y)),no&&console.log(f,y,"\u2192",v),!v){console.warn("Could not find animationClip for model",g,o.name,this.name,(e=this.playableAsset)==null?void 0:e.name,d,h);continue}h instanceof Rt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new jm(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(g.asset,v);const b=u.mixer.clipAction(v);u.actions.push(b),u.models.push(g)}this._animationTracks.push(u)}}}else if(o.type===qi.Audio){if(!o.clips||o.clips.length<=0)continue;const c=new nm;c.director=this,c.track=o,c.audioSource=o.outputs.find(h=>h instanceof ns),this._audioTracks.push(c),s||(s=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addComponent(Nn)),c.listener=s.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];c.addModel(d)}}else if(o.type===qi.Marker){const c=new Uh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)switch(h.type){case Qy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=P.getComponent(this.gameObject,Bh);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(o.type===qi.Signal){const c=new Uh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of o.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(o.type===qi.Control){const c=new om;if(c.director=this,c.track=o,o.clips)for(const h of o.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},a(zh,"createTrackFunctions",{}),zh);DS([m()],Yy.prototype,"playOnAwake"),DS([m()],Yy.prototype,"extrapolationMode");let El=Yy;var YI=Object.defineProperty,rm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YI(e,t,o),o};class da extends j{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=P.getComponentInParent(this.gameObject,sn);s&&s.requestOwnership()}}),a(this,"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}}),a(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!vc)&&this.context.mainCamera&&(this._control||(this._control=new dO(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const s=t;if(s.layers.set(2),s){const o=s.material;o&&(o.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,_e)??void 0),this._control)){const t=this._control.getHelper();this.context.scene.add(t),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,t,s;(t=(e=this._control)==null?void 0:e.getHelper())==null||t.removeFromParent(),(s=this._control)==null||s.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(Cn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}rm([m()],da.prototype,"isGizmo"),rm([m()],da.prototype,"translationSnap"),rm([m()],da.prototype,"rotationSnapAngle"),rm([m()],da.prototype,"scaleSnap");var KI=Object.defineProperty,ZI=Object.getOwnPropertyDescriptor,am=(n,e,t,s)=>{for(var o=s>1?void 0:s?ZI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&KI(e,t,o),o};class Ky{constructor(){a(this,"texture",null),a(this,"rect")}}am([m(je)],Ky.prototype,"texture",2);let Al=class extends hh{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(n){this.sprite||(this.sprite=new Ky),this.sprite.texture=n,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(n){this._sprite!==n&&(this._sprite=n,this.onAfterCreated())}isBuiltinSprite(){var n,e,t,s,o,r,l;const c=this.sprite;switch((n=c?.texture)==null?void 0:n.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=c?.texture)==null?void 0:e.name)!=null&&t.length)&&((o=(s=c?.texture)==null?void 0:s.image)==null?void 0:o.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(n){var e,t;super.onBeforeCreate(n),this.isBuiltinSprite()&&(n.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(n.borderRadius=999))}onAfterCreated(){var n;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((n=this.sprite)==null?void 0:n.texture))}};am([m(Ky)],Al.prototype,"sprite",1),am([m()],Al.prototype,"pixelsPerUnitMultiplier",2);class lm extends hh{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}am([m(je)],lm.prototype,"mainTexture",1);var JI=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,Xi=(n,e,t,s)=>{for(var o=s>1?void 0:s?eL(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&JI(e,t,o),o};const ua=C("debugbutton");class lr{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}Xi([m()],lr.prototype,"colorMultiplier",2),Xi([m(he)],lr.prototype,"disabledColor",2),Xi([m()],lr.prototype,"fadeDuration",2),Xi([m(he)],lr.prototype,"highlightedColor",2),Xi([m(he)],lr.prototype,"normalColor",2),Xi([m(he)],lr.prototype,"pressedColor",2),Xi([m(he)],lr.prototype,"selectedColor",2);class tL{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class oo extends j{constructor(){super(...arguments),a(this,"onClick",new xe),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var t,s;const o=e.event.pointerType==="mouse"&&e.button===0;o&&(this._isHovered+=1),ua&&console.warn("Button Enter",o,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),o&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ua&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.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&&((t=this._image)==null||t.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var t,s;ua&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;ua&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.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&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===zd.Mouse)&&(ua&&(console.warn("Button Click",this.onClick),De("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ua))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),G.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}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}set_interactable(e){this.interactable=e}awake(){super.awake(),ua&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ka)||this.gameObject.addComponent(Iu)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,Al),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,o,r,l;e.setInteractable(this.interactable);const c=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(g);const f=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.selectedColor),y={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(y);const v=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.disabledColor),b={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};e.setupState(b)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Xi([m(xe)],oo.prototype,"onClick",2),Xi([m(lr)],oo.prototype,"colors",2),Xi([m()],oo.prototype,"transition",2),Xi([m(tL)],oo.prototype,"animationTriggers",2),Xi([m(Rt)],oo.prototype,"animator",2),Xi([m()],oo.prototype,"interactable",1);var iL=Object.defineProperty,cm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&iL(e,t,o),o};const cr=C("debuginputfield");var K;const Nh=(K=class extends j{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var n;return((n=this.textComponent)==null?void 0:n.text)??""}set text(n){this.textComponent&&(this.textComponent.text=n,this.placeholder&&(n.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return K.active===this}start(){cr&&console.log(this.name,this)}onEnable(){var n;K.htmlField||(K.htmlField=document.createElement("input"),K.htmlField.style.width="0px",K.htmlField.style.height="0px",K.htmlField.style.padding="0px",K.htmlField.style.border="none",K.htmlField.style.overflow="hidden",K.htmlField.style.caretColor="transparent",K.htmlField.style.outline="none",K.htmlField.classList.add("ar"),K.htmlField.onfocus=()=>K.htmlFieldFocused=!0,K.htmlField.onblur=()=>K.htmlFieldFocused=!1,document.body.append(K.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),K.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(n=this.textComponent)!=null&&n.text.length&&P.setActive(this.placeholder.gameObject,!1),Q.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var n;(n=K.htmlField)==null||n.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){K.active===this&&K.htmlField?(K.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(n){n.event.pointerType==="mouse"&&n.button===0&&this.context.input.setCursor("text")}onPointerExit(n){this.context.input.unsetCursor("text")}onPointerClick(n){cr&&console.log("CLICK",n,K.active),K.activeTime=this.context.time.time,K.active!==this&&this.startCoroutine(this.activeLoop(),Oe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();K.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-K.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var n,e,t,s;if(K.active!==this&&(cr&&console.log("Select",this.name,this,K.htmlField,this.context.isInXR,this.context.arOverlayElement,(n=this.textComponent)==null?void 0:n.text,(e=K.htmlField)==null?void 0:e.value),(t=K.active)==null||t.onDeselected(),K.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),K.htmlField)){if(K.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",cr&&console.log("set input field value",K.htmlField.value),this.context.isInXR){const o=this.context.arOverlayElement;o&&o.append(K.htmlField)}this.selectInputField()}}onDeselected(){var n;K.active===this&&(K.active=null,cr&&console.log("Deselect",this.name,this),K.htmlField&&(K.htmlField.blur(),document.body.append(K.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),K.htmlField&&((n=this.onEndEdit)==null||n.invoke(K.htmlField.value)))}update(){var n;K.active===this&&((n=this.textComponent)==null||n.markDirty())}onInput(n){var e,t;if(K.active===this){if(cr&&console.log(n.code,n,(e=K.htmlField)==null?void 0:e.value,(t=this.textComponent)==null?void 0:t.text),n.code==="Escape"||n.code==="Enter"){this.onDeselected();return}K.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var n;if(this.textComponent&&K.htmlField){const e=this.textComponent.text,t=K.htmlField.value,s=this.textComponent.text!==K.htmlField.value;this.textComponent.text=K.htmlField.value,s&&(cr&&console.log("[InputField] value changed:",t,e),(n=this.onValueChanged)==null||n.invoke(t,e))}}selectInputField(){K.htmlField&&(cr&&console.log("Focus Inputfield",K.htmlFieldFocused),K.htmlField.setSelectionRange(K.htmlField.value.length,K.htmlField.value.length),Q.isiOS()?K.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var n;return(n=K.htmlField)==null?void 0:n.focus()},1))}processInputOniOS(){const n=this.context.physics.raycast();if(!n.length)return;const e=n[0].object,t=Vf(e);(t?.gameObject===this.gameObject||t?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(K,"active",null),a(K,"activeTime",-1),a(K,"htmlField",null),a(K,"htmlFieldFocused",!1),K);cm([m(Wt)],Nh.prototype,"textComponent"),cm([m(Wt)],Nh.prototype,"placeholder"),cm([m(xe)],Nh.prototype,"onValueChanged"),cm([m(xe)],Nh.prototype,"onEndEdit");let Zy=Nh;var sL=Object.defineProperty,BS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sL(e,t,o),o};class Wh extends j{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_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 uO;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const s=new pO(e);t.add(s),s.visible=!1;const o=s.material;o.transparent=!0,setTimeout(()=>{s.visible=!0;const r=Id(this.gameObject).clone();Jl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new Ci;l.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?s.scale.set(1/c,1/h/u,1):s.scale.set(1/c*u,1/h,1)}else s.scale.set(1/c,1/h,1);const d=this.gameObject.scale;s.scale.multiply(d)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}BS([m()],Wh.prototype,"id"),BS([m()],Wh.prototype,"keepAspect");/* @license
|
|
1394
|
+
C) Set "joinRandomRoom" to true`),!1):(Gy&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}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()):B()&&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(Hy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Gl(),t=this.generateRoomName();C(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Km(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}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&&ql(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=C(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?ql(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Mt("group"),this._roomButtonIconLeave=Mt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(se.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(se.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(se.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}ar([m()],Is.prototype,"roomName",2),ar([m()],Is.prototype,"urlParameterName",2),ar([m()],Is.prototype,"joinRandomRoom",2),ar([m()],Is.prototype,"requireRoomParameter",2),ar([m()],Is.prototype,"autoRejoin",2),ar([m()],Is.prototype,"createJoinButton",2),ar([m()],Is.prototype,"createViewOnlyButton",2),ar([m()],Is.prototype,"roomPrefix",1);function VI(){const n=C("testwindowcount")||0;n&&n>0&&$I(n)}function $I(n){if(C("testwindow"))return null;const e=new URL(window.location.href);Ym(e.searchParams,$T,1),Ym(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const h of s)h.close()};const o=.05,r=128;let l=0,c=0;for(let h=0;h<n;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+o))+window.screenLeft,u=c*(r*(1+o))+window.screenTop+90+60*c;l+=1;const p=window.open(t,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}s.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<s.length;g++){const f=s[g];f!==p&&f.close()}s.length=0}}}return s}class qy extends j{awake(){VI()}}class Xy extends j{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(jc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new IS(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}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 Hm(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=xx(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}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 IS{constructor(e,t){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),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)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const o=e.worldQuaternion;if(this.rotation.x=o.x,this.rotation.y=o.y,this.rotation.z=o.z,this.rotation.w=o.w,this.fast=!1,t){const r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}a(IS,"temp",new S);var HI=Object.defineProperty,tm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&HI(e,t,o),o};const GI=C("debugsignals");class im{constructor(){a(this,"guid")}}tm([m()],im.prototype,"guid");class Dh{constructor(){a(this,"signal"),a(this,"reaction")}}tm([m(im)],Dh.prototype,"signal"),tm([m(xe)],Dh.prototype,"reaction");var Ls;const LS=(Ls=class extends j{constructor(){super(...arguments),a(this,"events")}static invoke(n){if(Ls.receivers[n]){const e=Ls.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){GI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)Ls.receivers[n.signal.guid]||(Ls.receivers[n.signal.guid]=[]),Ls.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(Ls.receivers[n.signal.guid]){const e=Ls.receivers[n.signal.guid].indexOf(this);e>=0&&Ls.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(s){console.error(s)}}},a(Ls,"receivers",{}),Ls);tm([m(Dh)],LS.prototype,"events");let Bh=LS;var qi=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(qi||{}),bn=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(bn||{}),Qy=(n=>(n.Signal="SignalEmitter",n))(Qy||{});const _n=C("debugtimeline");class Fh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,o=!0){if(t<0||t>=s.length)return 0;const r=s[t];if(o||e>=r.start&&e<=r.end){let l=1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);l*=c}if(r.easeOutDuration>0){const c=Math.min((r.end-e)/r.easeOutDuration,1);l*=c}return l}return 0}}class qI{constructor(e){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),o=s.name+".position",r=s.name+".quaternion";_n&&console.log(t.name,t.tracks,o);for(const l of t.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(o))this.rootStartPosition=new S().fromArray(l.values,0),this.rootEndPosition=new S().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),_n&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new V().fromArray(l.values,0),this.rootEndQuaternion=new V().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),_n)){const c=new Dt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class sm extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new S),a(this,"_totalOffsetRotation",new V),a(this,"_totalOffsetPosition2",new S),a(this,"_totalOffsetRotation2",new V),a(this,"_summedPos",new S),a(this,"_tempPos",new S),a(this,"_summedRot",new V),a(this,"_tempRot",new V),a(this,"_clipRotQuat",new V)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&fx(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var s,o;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const r=t.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of t.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!d||!u){const p=(o=this.mixer)==null?void 0:o.getRoot(),g=t.tracks[0],f=g.name.lastIndexOf("."),y=g.name.substring(0,f),v=y.substring(y.lastIndexOf(".")+1),b=p.getObjectByName(v);if(b)if(d){if(!u){const _=t.tracks[0].name.substring(0,f)+".quaternion";_n&&console.warn("Create quaternion track",v,b);const w=b.quaternion,x=new NP(_,[0,t.duration],[w.x,w.y,w.z,w.w,w.x,w.y,w.z,w.w]);t.tracks.push(x),this.createRotationInterpolant(t,e,x)}}else{const _=y+".position";_n&&console.warn("Create position track",v,b);const w=b.position,x=new zP(_,[0,t.duration],[w.x,w.y,w.z,w.x,w.y,w.z]);t.tracks.push(x),this.createPositionInterpolant(t,e,x)}}}bind(){if(!this._didBind){this._didBind=!0,_n&&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 qI(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,Rt)??null,this._animator&&fx(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,s=t.position,o=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new S(s.x,s.y,s.z)),o.isQuaternion||(t.rotation=new V(o.x,o.y,o.z,o.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new V(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,s,o,r,l,c,h;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 d=0,u=0,p=!1,g=!1,f=0;for(let y=0;y<this.clips.length;y++){const v=this.models[y],b=this.actions[y],_=v.asset;b.weight=0;const w=e>=v.start&&e<=v.end,x=v.preExtrapolationMode,k=v.postExtrapolationMode,M=y<this.clips.length-1?this.models[y+1]:null;let T=w,D=!1;if(!T&&!p&&v.end<e&&k!==bn.None?(!M||M.start>e)&&(T=!0,p=!0):y==0&&!T&&!g&&v.start>e&&x!==bn.None&&(!M||M.start<e)&&(T=!0,D=!0,g=!0),T){let z=this.weight;z*=this.evaluateWeight(e,y,this.models,T),z*=this.director.weight;let U=w;if(D)switch(x){case bn.Hold:break;case bn.Loop:e+=v.start,U=!0;break;default:e+=v.start,U=!0;break}let E=this.getClipTime(e,v),$=0;const H=_.duration;if(D&&x===bn.Hold&&(E=0),U){if(_.loop)for($+=Math.floor(E/(H+1e-6));E>H;)E-=H}else if(!w&&p)switch(k){case bn.Hold:E=this.getClipTime(v.end,v);break;case bn.Loop:E%=H;break;case bn.PingPong:const I=Math.floor(E/H)%2!==0;E%=H,I&&(E=H-E);break}v.reversed===!0?b.time=b.getClip().duration-E:b.time=E,b.timeScale=0;const F=Math.max(0,z);if(b.weight=F,f+=F,b.clampWhenFinished=!1,b.isRunning()||b.play(),this._useclipOffsets){const I=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,Y=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-z),d+=1;const te=this._summedPos.set(0,0,0),ae=this._tempPos.set(0,0,0),le=this._summedRot.identity(),ye=this._tempRot.identity(),He=_.rotation;He&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(He,z));const vt=this._actionOffsets[y];if(vt.hasOffsets)for(let mr=0;mr<$;mr++)vt.rootPositionOffset?ae.copy(vt.rootPositionOffset):ae.set(0,0,0),ae.applyQuaternion(le),this._clipRotQuat&&ae.applyQuaternion(this._clipRotQuat),vt.rootQuaternionOffset&&(ye.copy(vt.rootQuaternionOffset),le.multiply(ye)),te.add(ae);this._clipRotQuat&&Y.multiply(this._clipRotQuat),Y.multiply(le),_.position&&te.add(_.position),I.add(te)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(_n||B())&&(s=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&s.mixer&&this.mixer!==((r=(o=this._animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:r.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)),(l=this._animator)!=null&&l.runtimeAnimatorController){const y=Math.max(0,1-f);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(y)}else this.mixer.update(e)}createRotationInterpolant(e,t,s){var o;const r=s.createInterpolant.bind(s),l=new V;this.ensureTrackOffsets();const c=(o=this.trackOffset)==null?void 0:o.rotation;s.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(e,t,s){var o,r;const l=s.createInterpolant.bind(s),c=new S;this.ensureTrackOffsets();const h=(o=this.trackOffset)==null?void 0:o.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;s.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=f=>{var y,v,b;const _=g(f);if(c.set(_[0],_[1],_[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(y=this._actionOffsets.find(w=>w.clip===e))==null?void 0:y.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const w of this.director.animationCallbackReceivers)(b=w?.onTimelinePosition)==null||b.call(w,this.director,this.target,f,c);return _[0]=c.x,_[1]=c.y,_[2]=c.z,_},p}}}const XI=C("mutetimeline"),jS=class cd extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return vo(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const s=this.models[t];this.audio[t].setVolume(e?s.asset.volume:0)}}addModel(e){const t=new WP(this.listener);this.audio.push(t);const s=e;s._didTriggerPlay=!1,this.models.push(s)}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!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(XI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const o=t?.1:0;for(let r=0;r<this.models.length;r++){const l=this.models[r],c=this.audio[r],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),ns.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,_n&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(o),l._didTriggerPlay=!0);else{const u=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(u-p)>.3&&(c.offset=u,c.stop(),c.play(o))}let d=h.volume;if(this.track.volume!==void 0&&(d*=this.track.volume),t&&(d=0),l.easeInDuration>0){const u=Math.min((e-l.start)/l.easeInDuration,1);d*=u}if(l.easeOutDuration>0){const u=Math.min((l.end-e)/l.easeOutDuration,1);d*=u}c.setVolume(d*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,t=0,s=0){let o=null;const r=e-s,l=e+t;for(const c of this.models)if(this.isInTimeRange(c,r,l)){const h=this.audio[this.models.indexOf(c)],d=this.handleAudioLoading(c,h);d!==null&&(o===null&&(o=[]),o.push(d))}return o!==null?Promise.all(o):null}isInTimeRange(e,t,s){return t<=e.start&&s>=e.end||t>=e.start&&t<=e.end||s>=e.start&&s<=e.end}static dispose(){cd._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Dm);const s=this.getAudioFilePath(e.asset.clip);if(cd._audioBuffers.get(s)){const r=cd._audioBuffers.get(s);return r.then(l=>{l&&t.setBuffer(l)}),r}_n&&console.warn("LOAD audio track",s,this.director.sourceId);const o=new Promise((r,l)=>{this._audioLoader.load(s,c=>{t.setBuffer(c),r(c)},void 0,c=>{console.error("Error loading audio",c),r(null)})});return cd._audioBuffers.set(s,o),o}};a(jS,"_audioBuffers",new Map);let nm=jS;class Uh extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const s=this.director.context.time.deltaTime*1.5;for(let o=0;o<this.models.length;o++){const r=this.models[o],l=this.didTrigger[o],c=r.time-e;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<s)&&(h=!0)}if(h){if(!l)if(_n&&console.log("Trigger signal",e,r.time,r),this.didTrigger[o]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Bh.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[o]=!1)}}}class om extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const o=P.getComponent(s.sourceObject,El);this.timelines.push(o),o&&s.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const o=this.models[s],r=o.asset;if(e>=o.start&&e<=o.end){this._previousActiveModel=o;const l=this.getClipTime(e,o);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(t=this._previousActiveModel)==null?void 0:t.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var QI=Object.defineProperty,DS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&QI(e,t,o),o};const no=C("debugtimeline");var zh;const Yy=(zh=class extends j{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(no||Xt())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t,s,o;no&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),!this.isValid()&&(no||B())&&(no?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(e=this.playableAsset)==null?void 0:e.tracks,"IsArray?",Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this):(o=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&o.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var n,e,t;for(const s of this._audioTracks)(n=s.onEnable)==null||n.call(s);for(const s of this._customTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onEnable)==null||t.call(s);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(){var n,e,t;this.stop();for(const s of this._audioTracks)(n=s.onDisable)==null||n.call(s);for(const s of this._customTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onDisable)==null||t.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!ns.userInteractionRegistered&&this.waitForAudio;)await $s(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Oe.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&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 n of this._allTracks)for(const e of n)yield e}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.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(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case qi.Activation:if(!n&&!this._isPlaying)continue;for(let o=0;o<s.outputs.length;o++){const r=s.outputs[o];if(typeof r=="object"){let l=!1;if(s.clips)for(const h of s.clips)h.start<=t&&t<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,no&&console.warn(this.name,"set ActivationTrack-"+o,c.name,l,t))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(t);for(const s of this._audioTracks)s.evaluate(t);for(const s of this._signalTracks)s.evaluate(t);for(const s of this._controlTracks)s.evaluate(t);for(const s of this._customTracks)s.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Xl(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=P.findByGuid(s,n);o===null||typeof o!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(no&&console.log("Resolved binding",s,"to",o),e.outputs[t]=o)}else if(s===null){if(e.outputs.splice(t,1),zh.createTrackFunctions[e.type])continue;e.type!==qi.Audio&&e.type!==qi.Control&&e.type!==qi.Marker&&e.type!==qi.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===qi.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let o=s.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=P.findByGuid(o,n);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,e.name,s):(no&&console.log("Resolved binding",o,"to",r),s.asset.sourceObject=r)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let s=P.findObjectOfType(Nn,this.context);for(const o of this.playableAsset.tracks){const r=o.type,l=zh.createTrackFunctions[r];if(l!=null){const c=l(this,o);if(typeof c.evaluate=="function"){c.director=this,c.track=o,this._customTracks.push(c);continue}}if(o.type===qi.Animation){if(!o.clips||o.clips.length<=0){no&&console.warn("Animation track has no clips",o);continue}for(let c=o.outputs.length-1;c>=0;c--){let h=o.outputs[c];if(h instanceof A){const u=P.getOrAddComponent(h,Rt);u&&(h=u)}const d=(n=h?.gameObject)==null?void 0:n.animations;if(d){const u=new sm;u.trackOffset=o.trackOffset,u.director=this,u.track=o;for(let p=0;p<o.clips.length;p++){const g=o.clips[p],f=g.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const y=f.clip;let v=y;if((typeof v=="string"||typeof v=="number")&&(v=d.find(_=>_.name===y)),no&&console.log(f,y,"\u2192",v),!v){console.warn("Could not find animationClip for model",g,o.name,this.name,(e=this.playableAsset)==null?void 0:e.name,d,h);continue}h instanceof Rt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new jm(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(g.asset,v);const b=u.mixer.clipAction(v);u.actions.push(b),u.models.push(g)}this._animationTracks.push(u)}}}else if(o.type===qi.Audio){if(!o.clips||o.clips.length<=0)continue;const c=new nm;c.director=this,c.track=o,c.audioSource=o.outputs.find(h=>h instanceof ns),this._audioTracks.push(c),s||(s=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addComponent(Nn)),c.listener=s.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];c.addModel(d)}}else if(o.type===qi.Marker){const c=new Uh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)switch(h.type){case Qy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=P.getComponent(this.gameObject,Bh);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(o.type===qi.Signal){const c=new Uh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of o.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(o.type===qi.Control){const c=new om;if(c.director=this,c.track=o,o.clips)for(const h of o.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},a(zh,"createTrackFunctions",{}),zh);DS([m()],Yy.prototype,"playOnAwake"),DS([m()],Yy.prototype,"extrapolationMode");let El=Yy;var YI=Object.defineProperty,rm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YI(e,t,o),o};class da extends j{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=P.getComponentInParent(this.gameObject,sn);s&&s.requestOwnership()}}),a(this,"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}}),a(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!vc)&&this.context.mainCamera&&(this._control||(this._control=new dO(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const s=t;if(s.layers.set(2),s){const o=s.material;o&&(o.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,_e)??void 0),this._control)){const t=this._control.getHelper();this.context.scene.add(t),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,t,s;(t=(e=this._control)==null?void 0:e.getHelper())==null||t.removeFromParent(),(s=this._control)==null||s.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(Cn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}rm([m()],da.prototype,"isGizmo"),rm([m()],da.prototype,"translationSnap"),rm([m()],da.prototype,"rotationSnapAngle"),rm([m()],da.prototype,"scaleSnap");var KI=Object.defineProperty,ZI=Object.getOwnPropertyDescriptor,am=(n,e,t,s)=>{for(var o=s>1?void 0:s?ZI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&KI(e,t,o),o};class Ky{constructor(){a(this,"texture",null),a(this,"rect")}}am([m(je)],Ky.prototype,"texture",2);let Al=class extends hh{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(n){this.sprite||(this.sprite=new Ky),this.sprite.texture=n,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(n){this._sprite!==n&&(this._sprite=n,this.onAfterCreated())}isBuiltinSprite(){var n,e,t,s,o,r,l;const c=this.sprite;switch((n=c?.texture)==null?void 0:n.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=c?.texture)==null?void 0:e.name)!=null&&t.length)&&((o=(s=c?.texture)==null?void 0:s.image)==null?void 0:o.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(n){var e,t;super.onBeforeCreate(n),this.isBuiltinSprite()&&(n.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(n.borderRadius=999))}onAfterCreated(){var n;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((n=this.sprite)==null?void 0:n.texture))}};am([m(Ky)],Al.prototype,"sprite",1),am([m()],Al.prototype,"pixelsPerUnitMultiplier",2);class lm extends hh{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}am([m(je)],lm.prototype,"mainTexture",1);var JI=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,Xi=(n,e,t,s)=>{for(var o=s>1?void 0:s?eL(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&JI(e,t,o),o};const ua=C("debugbutton");class lr{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}Xi([m()],lr.prototype,"colorMultiplier",2),Xi([m(he)],lr.prototype,"disabledColor",2),Xi([m()],lr.prototype,"fadeDuration",2),Xi([m(he)],lr.prototype,"highlightedColor",2),Xi([m(he)],lr.prototype,"normalColor",2),Xi([m(he)],lr.prototype,"pressedColor",2),Xi([m(he)],lr.prototype,"selectedColor",2);class tL{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class oo extends j{constructor(){super(...arguments),a(this,"onClick",new xe),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var t,s;const o=e.event.pointerType==="mouse"&&e.button===0;o&&(this._isHovered+=1),ua&&console.warn("Button Enter",o,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),o&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ua&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.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&&((t=this._image)==null||t.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var t,s;ua&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;ua&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.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&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===zd.Mouse)&&(ua&&(console.warn("Button Click",this.onClick),De("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ua))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),G.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}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}set_interactable(e){this.interactable=e}awake(){super.awake(),ua&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ka)||this.gameObject.addComponent(Iu)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,Al),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,o,r,l;e.setInteractable(this.interactable);const c=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(g);const f=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.selectedColor),y={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(y);const v=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.disabledColor),b={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};e.setupState(b)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Xi([m(xe)],oo.prototype,"onClick",2),Xi([m(lr)],oo.prototype,"colors",2),Xi([m()],oo.prototype,"transition",2),Xi([m(tL)],oo.prototype,"animationTriggers",2),Xi([m(Rt)],oo.prototype,"animator",2),Xi([m()],oo.prototype,"interactable",1);var iL=Object.defineProperty,cm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&iL(e,t,o),o};const cr=C("debuginputfield");var K;const Nh=(K=class extends j{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var n;return((n=this.textComponent)==null?void 0:n.text)??""}set text(n){this.textComponent&&(this.textComponent.text=n,this.placeholder&&(n.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return K.active===this}start(){cr&&console.log(this.name,this)}onEnable(){var n;K.htmlField||(K.htmlField=document.createElement("input"),K.htmlField.style.width="0px",K.htmlField.style.height="0px",K.htmlField.style.padding="0px",K.htmlField.style.border="none",K.htmlField.style.overflow="hidden",K.htmlField.style.caretColor="transparent",K.htmlField.style.outline="none",K.htmlField.classList.add("ar"),K.htmlField.onfocus=()=>K.htmlFieldFocused=!0,K.htmlField.onblur=()=>K.htmlFieldFocused=!1,document.body.append(K.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),K.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(n=this.textComponent)!=null&&n.text.length&&P.setActive(this.placeholder.gameObject,!1),Q.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var n;(n=K.htmlField)==null||n.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){K.active===this&&K.htmlField?(K.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(n){n.event.pointerType==="mouse"&&n.button===0&&this.context.input.setCursor("text")}onPointerExit(n){this.context.input.unsetCursor("text")}onPointerClick(n){cr&&console.log("CLICK",n,K.active),K.activeTime=this.context.time.time,K.active!==this&&this.startCoroutine(this.activeLoop(),Oe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();K.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-K.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var n,e,t,s;if(K.active!==this&&(cr&&console.log("Select",this.name,this,K.htmlField,this.context.isInXR,this.context.arOverlayElement,(n=this.textComponent)==null?void 0:n.text,(e=K.htmlField)==null?void 0:e.value),(t=K.active)==null||t.onDeselected(),K.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),K.htmlField)){if(K.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",cr&&console.log("set input field value",K.htmlField.value),this.context.isInXR){const o=this.context.arOverlayElement;o&&o.append(K.htmlField)}this.selectInputField()}}onDeselected(){var n;K.active===this&&(K.active=null,cr&&console.log("Deselect",this.name,this),K.htmlField&&(K.htmlField.blur(),document.body.append(K.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),K.htmlField&&((n=this.onEndEdit)==null||n.invoke(K.htmlField.value)))}update(){var n;K.active===this&&((n=this.textComponent)==null||n.markDirty())}onInput(n){var e,t;if(K.active===this){if(cr&&console.log(n.code,n,(e=K.htmlField)==null?void 0:e.value,(t=this.textComponent)==null?void 0:t.text),n.code==="Escape"||n.code==="Enter"){this.onDeselected();return}K.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var n;if(this.textComponent&&K.htmlField){const e=this.textComponent.text,t=K.htmlField.value,s=this.textComponent.text!==K.htmlField.value;this.textComponent.text=K.htmlField.value,s&&(cr&&console.log("[InputField] value changed:",t,e),(n=this.onValueChanged)==null||n.invoke(t,e))}}selectInputField(){K.htmlField&&(cr&&console.log("Focus Inputfield",K.htmlFieldFocused),K.htmlField.setSelectionRange(K.htmlField.value.length,K.htmlField.value.length),Q.isiOS()?K.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var n;return(n=K.htmlField)==null?void 0:n.focus()},1))}processInputOniOS(){const n=this.context.physics.raycast();if(!n.length)return;const e=n[0].object,t=Vf(e);(t?.gameObject===this.gameObject||t?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(K,"active",null),a(K,"activeTime",-1),a(K,"htmlField",null),a(K,"htmlFieldFocused",!1),K);cm([m(Nt)],Nh.prototype,"textComponent"),cm([m(Nt)],Nh.prototype,"placeholder"),cm([m(xe)],Nh.prototype,"onValueChanged"),cm([m(xe)],Nh.prototype,"onEndEdit");let Zy=Nh;var sL=Object.defineProperty,BS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sL(e,t,o),o};class Wh extends j{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_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 uO;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const s=new pO(e);t.add(s),s.visible=!1;const o=s.material;o.transparent=!0,setTimeout(()=>{s.visible=!0;const r=Id(this.gameObject).clone();Jl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new Ci;l.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?s.scale.set(1/c,1/h/u,1):s.scale.set(1/c*u,1/h,1)}else s.scale.set(1/c,1/h,1);const d=this.gameObject.scale;s.scale.multiply(d)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}BS([m()],Wh.prototype,"id"),BS([m()],Wh.prototype,"keepAspect");/* @license
|
|
1395
1395
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
1396
1396
|
* Licensed under the Apache License, Version 2.0 (the 'License');
|
|
1397
1397
|
* you may not use this file except in compliance with the License.
|
|
@@ -1450,7 +1450,7 @@ void main() {
|
|
|
1450
1450
|
#include <colorspace_fragment>
|
|
1451
1451
|
}
|
|
1452
1452
|
`;var gL=Object.defineProperty,hr=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&gL(e,t,o),o};const WS=C("debugimagetracking"),iv=class Ov{constructor(e,t,s,o,r,l){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=e,this._trackedImage=t,this._bitmap=s,this.measuredSize=o,this.state=r,this._pose=l}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const s=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,s)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=Ov._positionBuffer.get(),this._rotation=Ov._rotationBuffer.get();const e=this._pose.transform,t=oe.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};a(iv,"_positionBuffer",new ki(()=>new S,20)),a(iv,"_rotationBuffer",new ki(()=>new V,20));let sv=iv;class ao{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}hr([m(URL)],ao.prototype,"image"),hr([m()],ao.prototype,"widthInMeters"),hr([m(ce)],ao.prototype,"object"),hr([m()],ao.prototype,"createObjectInstance"),hr([m()],ao.prototype,"imageDoesNotMove"),hr([m()],ao.prototype,"hideWhenTrackingIsLost");class fL{constructor(e,t,s){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=e,this.imageData=t,this.widthInMeters=s}get extensionName(){return"image-tracking"}onAfterHierarchy(e,t){const s=Q.getiOSVersion(),o=(s?parseInt(s.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.widthInMeters*o).toFixed(8)),t.closeBlock()}onBeforeBuildDocument(e){const t=P.findObjectOfType(qh);!t||!t.trackedImages||t.trackedImages.length>1&&(B()&&be("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(e){e.files["image_tracking/"+this.filename]=this.imageData}onExportObject(e,t,s){var o;const r=P.findObjectOfType(qh);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===e){const c=P.findObjectOfType(gn);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=e;const p=new ne;if(e!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();t.setMatrix(g.scale(new S(h,h,h)));break}}}}var pa;const nv=(pa=class extends j{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"webXRIncubationsWarning",`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`),a(this,"onImageTrackingUpdate",n=>{const e=oe.active;if(e)for(const t of n){const s=t.model,o=t.state==="tracked";if(!s.object)continue;let r=this.imageToObjectMap.get(s);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(s,r),s.object.loadAssetAsync().then(l=>{if(s.createObjectInstance&&l&&(l=P.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Ui))c.setInstancingEnabled(!1);e.rig?(e.rig.gameObject.add(l),t.applyToObject(l),l.activeSelf||P.setActive(l,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(r.lastTrackingTime=Date.now()),s.imageDoesNotMove&&r.frames>10||!r.object)continue;e.rig&&(e.rig.gameObject.add(r.object),t.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||P.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(WS&&console.log(this),!!this.trackedImages){for(const n of this.trackedImages)if(n.image&&!pa._imageElements.has(n.image)){const e=n.image;pa._imageElements.set(e,null);const t=document.createElement("img");t.src=e,t.addEventListener("load",async()=>{const s=await createImageBitmap(t);pa._imageElements.set(e,s);const o=await E1(s);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=P.findObjectOfType(gn);l&&this.trackedImages&&(l.extensions.push(new fL("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(n,e){var t;if(this.trackedImages){e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.includes("image-tracking")||e.optionalFeatures.push("image-tracking"),e.trackedImages=[];for(const s of this.trackedImages)if((t=s.image)!=null&&t.length&&s.widthInMeters>0){const o=pa._imageElements.get(s.image);o&&(this.trackedImageIndexMap.set(e.trackedImages.length,s),e.trackedImages.push({image:o,widthInMeters:s.widthInMeters}))}}}onEnterXR(n){var e;if(this.trackedImages){for(const t of this.trackedImages)if((e=t.object)!=null&&e.asset){const s=t.object.asset;s.userData||(s.userData={});const o={visible:s.visible,parent:s.parent,matrix:s.matrix.clone()};s.userData["image-tracking"]=o}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(n){var e,t;if(!this.supported&&Q.isAndroidDevice()&&be(this.webXRIncubationsWarning),this.trackedImages){for(const s of this.trackedImages)if((e=s.object)!=null&&e.asset){const o=s.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(t=r.parent)==null||t.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(n){var e;this.currentImages.length=0;const t=n.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(((e=n.xr.session.enabledFeatures)==null?void 0:e.includes("image-tracking"))===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const o=t.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=t.getPose(l.imageSpace,r),p=new sv(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else WS&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,be(this.webXRIncubationsWarning);return}const s=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=s){l=!0;break}}l||P.setActive(r.object,!1)}}},a(pa,"_imageElements",new Map),pa);hr([m(ao)],nv.prototype,"trackedImages"),hr([m()],nv.prototype,"smooth");let qh=nv;var yL=Object.defineProperty,jl=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&yL(e,t,o),o};const ma=C("debugplanetracking");class lo extends j{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new Ci),a(this,"center",new S),a(this,"labelOffset",new S),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(e,t,s=!1)=>{if(t){if(t instanceof Array){for(const o of t)this.makeOccluder(e,o,s);return}!s&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new ne().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const s=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=s.detectedPlanes,r=s.detectedMeshes,l=o!==void 0&&o.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in s.session&&(s.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(e.xr,t.gameObject,s,o,this._allPlanes),r!==void 0&&this.processFrameData(e.xr,t.gameObject,s,r,this._allMeshes),ma){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof q&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),G.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
|
|
1453
|
-
`+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,t){const s=t.get(e);if(!s)return;t.delete(e),ma&&console.log("Plane no longer tracked, id="+s.id),s.mesh&&(s.mesh.removeFromParent(),s.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ma&&console.warn("No normals helper found for mesh",s.mesh)}),Ai(s.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:s}});this.dispatchEvent(o)}processFrameData(e,t,s,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=s.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const f=this.createGeometry(c);if(p.mesh instanceof q)p.mesh.geometry.dispose(),p.mesh.geometry=f,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof go)for(const y of p.mesh.children)y instanceof q&&(y.geometry.dispose(),y.geometry=f,this.makeOccluder(y,y.material));if(p.collider){const y=p.mesh;p.collider.sharedMesh=y,p.collider.convex=this.checkIfContextShouldBeConvex(y,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ma&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(y=>{if(!(y instanceof q))return;const v=y.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new q;ma?p.material=new VP:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ce("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,gg(p,!1),p instanceof q)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof go)for(const y of p.children)y instanceof q&&(Te(y.geometry),y.geometry=this.createGeometry(c),this.makeOccluder(y,y.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Bo);if(g){const y=p;g.sharedMesh=y,g.convex=this.checkIfContextShouldBeConvex(y,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const f={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,f),ma&&console.log("New plane detected, id="+f.id,f,{hasCollider:!!g,isGroup:p instanceof go});try{const y=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:f}});this.dispatchEvent(y)}catch(y){console.error(y)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ma&&u.traverse(p=>{if(p instanceof q)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new mO(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const s=new Ci;s.expandByObject(e);const o=new S;s.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new Ws}createMeshGeometry(e,t){const s=e.toString()+"_"+t.toString();if(this._verticesCache.has(s))return this._verticesCache.get(s);const o=new Ws;o.setIndex(new _t(t,1)),o.setAttribute("position",new _t(e,3));const r=Array();for(let l=0;l<e.length;l+=3)r.push(e[l],e[l+2]);return o.setAttribute("uv",new _t(e,3)),o.computeVertexNormals(),this._verticesCache.set(s,o),o}createPlaneGeometry(e){const t=new Ws,s=[],o=[];e.forEach(g=>{s.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new S(s[0],s[1],s[2]),l=new S(s[3],s[4],s[5]),c=new S(s[6],s[7],s[8]),h=new S,d=new S;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<s.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return t.setAttribute("position",new _t(new Float32Array(s),3)),t.setAttribute("uv",new _t(new Float32Array(o),2)),t.setAttribute("normal",new _t(new Float32Array(u),3)),t.setIndex(p),t.computeBoundingBox(),t.computeBoundingSphere(),t}}jl([m(ce)],lo.prototype,"dataTemplate"),jl([m()],lo.prototype,"occluder"),jl([m()],lo.prototype,"initiateRoomCaptureIfNoData"),jl([m()],lo.prototype,"usePlaneData"),jl([m()],lo.prototype,"useMeshData"),jl([m()],lo.prototype,"runInVR");var vL=Object.defineProperty,bL=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&vL(e,t,o),o};const VS=C("debugwebxr");class pm extends j{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=oe.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(VS){const e=new A;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(ea);t&&(t.isGizmo=!1);const s=new Pi(.5);this.gameObject.add(s)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),VS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}bL([m()],pm.prototype,"priority");class _L extends j{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}R.add("AlignmentConstraint",Ec),R.add("Animation",Ut),R.add("Animator",Rt),R.add("AudioListener",Nn),R.add("AudioSource",ns),R.add("Avatar_Brain_LookAt",zc),R.add("Avatar_MouthShapes",Nc),R.add("Avatar_MustacheShake",Yf),R.add("AvatarBlink_Simple",zr),R.add("AvatarEyeLook_Rotation",Jf),R.add("AxesHelper",el),R.add("BasicIKConstraint",t0),R.add("BoxHelperComponent",Do),R.add("Camera",hi),R.add("CharacterController",Nr),R.add("CharacterControllerInput",Hn),R.add("Collider",pi),R.add("SphereCollider",tl),R.add("BoxCollider",Wu),R.add("MeshCollider",Bo),R.add("CapsuleCollider",Vn),R.add("ContactShadows",$c),R.add("LogStats",n0),R.add("DeleteBox",Vu),R.add("Deletable",r0),R.add("DeviceFlag",$u),R.add("DragControls",Hr),R.add("DropListener",Gn),R.add("Duplicatable",u0),R.add("EventListEvent",Tu),R.add("EventTrigger",Xu),R.add("GltfExportBox",P0),R.add("GltfExport",k0),R.add("VariantAction",B0),R.add("ChangeTransformOnClick",Xr),R.add("ChangeMaterialOnClick",U0),R.add("SetActiveOnClick",z0),R.add("HideOnStart",mp),R.add("EmphasizeOnClick",pl),R.add("PlayAudioOnClick",Wo),R.add("PlayAnimationOnClick",eh),R.add("PreliminaryAction",ml),R.add("PreliminaryTrigger",th),R.add("VisibilityAction",ih),R.add("TapGestureTrigger",V0),R.add("USDZExporter",gn),R.add("Fog",Sl),R.add("BoxGizmo",ea),R.add("GridHelper",Cl),R.add("GroundProjectedEnv",en),R.add("UsageMarker",Hc),R.add("Interactable",o0),R.add("FixedJoint",vy),R.add("HingeJoint",uh),R.add("Light",vi),R.add("LODGroup",mh),R.add("LookAtConstraint",Br),R.add("NeedleMenu",un),R.add("NestedGltf",Mp),R.add("Networking",xy),R.add("OffsetConstraint",ta),R.add("CameraTargetReachedEvent",Uc),R.add("OrbitControls",_e),R.add("ParticleSystemRenderer",ds),R.add("ParticleSystem",vh),R.add("PlayerColor",Wl),R.add("Antialiasing",_h),R.add("BloomEffect",Wp),R.add("ChromaticAberration",wh),R.add("ColorAdjustments",nr),R.add("DepthOfField",Es),R.add("EffectWrapper",Sh),R.add("PixelationEffect",Ch),R.add("ScreenSpaceAmbientOcclusion",io),R.add("ScreenSpaceAmbientOcclusionN8",As),R.add("SharpeningEffect",Oh),R.add("TiltShiftEffect",yn),R.add("ToneMappingEffect",sr),R.add("Vignette",la),R.add("Volume",Rl),R.add("ReflectionProbe",Xc),R.add("Renderer",Ui),R.add("MeshRenderer",Yc),R.add("SkinnedMeshRenderer",C0),R.add("Rigidbody",dt),R.add("SceneSwitcher",Ze),R.add("ScreenCapture",rr),R.add("ShadowCatcher",Th),R.add("RemoteSkybox",Xp),R.add("SmoothFollow",Kp),R.add("SpatialTriggerReceiver",vn),R.add("SpatialTrigger",Zp),R.add("SpectatorCamera",Jp),R.add("SpriteRenderer",fi),R.add("SyncedCamera",$y),R.add("SyncedRoom",Is),R.add("SyncedTransform",sn),R.add("TestRunner",qy),R.add("TestSimulateUserData",Xy),R.add("PlayableDirector",El),R.add("SignalReceiver",Bh),R.add("AnimationTrackHandler",sm),R.add("AudioTrackHandler",nm),R.add("SignalTrackHandler",Uh),R.add("ControlTrackHandler",om),R.add("TransformGizmo",da),R.add("BaseUIComponent",ps),R.add("UIRootComponent",rh),R.add("Button",oo),R.add("Canvas",wl),R.add("CanvasGroup",Yo),R.add("EventSystem",si),R.add("Graphic",ch),R.add("MaskableGraphic",hh),R.add("Image",Al),R.add("RawImage",lm),R.add("InputField",Zy),R.add("VerticalLayoutGroup",ay),R.add("HorizontalLayoutGroup",ly),R.add("GridLayoutGroup",cy),R.add("Outline",_l),R.add("ObjectRaycaster",ji),R.add("GraphicRaycaster",Iu),R.add("SpatialGrabRaycaster",Bc),R.add("RectTransform",Rs),R.add("SpatialHtml",Wh),R.add("Text",Wt),R.add("EnvironmentScene",hm),R.add("LookAt",Jy),R.add("OpenURL",Il),R.add("VideoPlayer",yt),R.add("Voip",jo),R.add("Avatar",Ho),R.add("XRControllerFollow",ro),R.add("XRControllerModel",pn),R.add("XRControllerMovement",Ni),R.add("TeleportTarget",wp),R.add("WebARCameraBackground",Gh),R.add("WebARSessionRoot",Vo),R.add("WebXR",xp),R.add("AvatarMarker",di),R.add("WebXRImageTracking",qh),R.add("WebXRPlaneTracking",lo),R.add("XRRig",pm),R.add("XRFlag",os),R.add("PlayerSync",Y0),R.add("PlayerState",ks),R.add("PresentationMode",_L);const Xh=wt,wL=C("debugtypestore");wL&&console.log(R);function xL(n,e){const t=lw(n,e);return t!==void 0?t:null}const SL=new XM,ov=Symbol("deserialize-queue");async function CL(n,e,t,s=null,o){if(!t){console.debug("Can not create component instances: gltf is null");return}let r=s;typeof r=="number"&&(r=new Dt(s));const l=e.indexOf("?");e=l===-1?e:e.substring(0,l);const c=new uf(t.scene);c.gltfId=e,c.context=n,c.gltf=t,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=SL;let h=n[ov];if(h||(h=n[ov]=[]),t.scenes)for(const d of t.scenes)await lv(c,d,h);if(t.children)for(const d of t.children)await lv(c,d,h);n.new_scripts_pre_setup_callbacks.push(()=>{const d=n[ov];if(d){for(const u of d)PL(u,c);d.length=0}if(r){const u={},p=[];av(t,r,u,p);for(const g of t.scenes)av(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const rv=Symbol("original-component-name"),Dl=new Map;function av(n,e,t,s){if(e===null||!n)return;const o=n.guid,r=n.guid;r!=null&&r.length&&(Dl.has(r)||(Xh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+n.name),Dl.set(r,new Dt(r))));const l=r&&Dl.get(r)||e;if(n.guid=l.generateUUID(),o&&o!=="invalid"&&(t[o]=n.guid),n&&n.userData&&n.userData.components)for(const c of n.userData.components){if(c===null)continue;const h=c.guid;h?Dl.has(h)||(Xh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[rv]),Dl.set(h,new Dt(h))):Xh&&console.warn("Can not create IdProvider: component "+c[rv]+" has no guid",c.guid);const d=Dl.get(h)||e,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(t[u]=c.guid),c.resolveGuids&&s.push(c)}if(n.children)for(const c of n.children)av(c,e,t,s)}const Qh=[];async function lv(n,e,t,s){var o,r,l,c,h;if(!e)return;const d=e.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=R.get(p.name);if(g!=null){const f=new g;f.sourceId=n.gltfId,Na(f,p,n.implementationInformation),f.context=n.context,"guid"in p&&(f[rc]=p.guid),f[rv]=p.name,kr(e,f,!1),t.push({instance:f,compData:p,obj:e}),f.isCamera&&n.context&&n.context.mainCamera===null&&f.tag==="MainCamera"&&n.context.setCurrentCamera(f),((l=(r=(o=n.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(f.isCollider||f.isRigidbody)&&((h=(c=n.context)==null?void 0:c.physics.engine)==null||h.initialize())}else Xh&&console.debug("unknown component: "+p.name),Qh.includes(p.name)||Qh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Qh.length>0){const p=Qh.join(", ");console.warn("unknown components: "+p),Qh.length=0,Xt()&&De(`<strong>Unknown components in scene</strong>:
|
|
1453
|
+
`+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,t){const s=t.get(e);if(!s)return;t.delete(e),ma&&console.log("Plane no longer tracked, id="+s.id),s.mesh&&(s.mesh.removeFromParent(),s.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ma&&console.warn("No normals helper found for mesh",s.mesh)}),Ai(s.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:s}});this.dispatchEvent(o)}processFrameData(e,t,s,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=s.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const f=this.createGeometry(c);if(p.mesh instanceof q)p.mesh.geometry.dispose(),p.mesh.geometry=f,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof go)for(const y of p.mesh.children)y instanceof q&&(y.geometry.dispose(),y.geometry=f,this.makeOccluder(y,y.material));if(p.collider){const y=p.mesh;p.collider.sharedMesh=y,p.collider.convex=this.checkIfContextShouldBeConvex(y,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ma&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(y=>{if(!(y instanceof q))return;const v=y.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new q;ma?p.material=new VP:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ce("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,gg(p,!1),p instanceof q)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof go)for(const y of p.children)y instanceof q&&(Te(y.geometry),y.geometry=this.createGeometry(c),this.makeOccluder(y,y.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Bo);if(g){const y=p;g.sharedMesh=y,g.convex=this.checkIfContextShouldBeConvex(y,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const f={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,f),ma&&console.log("New plane detected, id="+f.id,f,{hasCollider:!!g,isGroup:p instanceof go});try{const y=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:f}});this.dispatchEvent(y)}catch(y){console.error(y)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ma&&u.traverse(p=>{if(p instanceof q)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new mO(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const s=new Ci;s.expandByObject(e);const o=new S;s.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new Ws}createMeshGeometry(e,t){const s=e.toString()+"_"+t.toString();if(this._verticesCache.has(s))return this._verticesCache.get(s);const o=new Ws;o.setIndex(new _t(t,1)),o.setAttribute("position",new _t(e,3));const r=Array();for(let l=0;l<e.length;l+=3)r.push(e[l],e[l+2]);return o.setAttribute("uv",new _t(e,3)),o.computeVertexNormals(),this._verticesCache.set(s,o),o}createPlaneGeometry(e){const t=new Ws,s=[],o=[];e.forEach(g=>{s.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new S(s[0],s[1],s[2]),l=new S(s[3],s[4],s[5]),c=new S(s[6],s[7],s[8]),h=new S,d=new S;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<s.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return t.setAttribute("position",new _t(new Float32Array(s),3)),t.setAttribute("uv",new _t(new Float32Array(o),2)),t.setAttribute("normal",new _t(new Float32Array(u),3)),t.setIndex(p),t.computeBoundingBox(),t.computeBoundingSphere(),t}}jl([m(ce)],lo.prototype,"dataTemplate"),jl([m()],lo.prototype,"occluder"),jl([m()],lo.prototype,"initiateRoomCaptureIfNoData"),jl([m()],lo.prototype,"usePlaneData"),jl([m()],lo.prototype,"useMeshData"),jl([m()],lo.prototype,"runInVR");var vL=Object.defineProperty,bL=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&vL(e,t,o),o};const VS=C("debugwebxr");class pm extends j{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=oe.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(VS){const e=new A;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(ea);t&&(t.isGizmo=!1);const s=new Pi(.5);this.gameObject.add(s)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),VS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}bL([m()],pm.prototype,"priority");class _L extends j{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}R.add("AlignmentConstraint",Ec),R.add("Animation",Ft),R.add("Animator",Rt),R.add("AudioListener",Nn),R.add("AudioSource",ns),R.add("Avatar_Brain_LookAt",zc),R.add("Avatar_MouthShapes",Nc),R.add("Avatar_MustacheShake",Yf),R.add("AvatarBlink_Simple",zr),R.add("AvatarEyeLook_Rotation",Jf),R.add("AxesHelper",el),R.add("BasicIKConstraint",t0),R.add("BoxHelperComponent",Do),R.add("Camera",hi),R.add("CharacterController",Nr),R.add("CharacterControllerInput",Hn),R.add("Collider",pi),R.add("SphereCollider",tl),R.add("BoxCollider",Wu),R.add("MeshCollider",Bo),R.add("CapsuleCollider",Vn),R.add("ContactShadows",$c),R.add("LogStats",n0),R.add("DeleteBox",Vu),R.add("Deletable",r0),R.add("DeviceFlag",$u),R.add("DragControls",Hr),R.add("DropListener",Gn),R.add("Duplicatable",u0),R.add("EventListEvent",Tu),R.add("EventTrigger",Xu),R.add("GltfExportBox",P0),R.add("GltfExport",k0),R.add("VariantAction",B0),R.add("ChangeTransformOnClick",Xr),R.add("ChangeMaterialOnClick",U0),R.add("SetActiveOnClick",z0),R.add("HideOnStart",mp),R.add("EmphasizeOnClick",pl),R.add("PlayAudioOnClick",Wo),R.add("PlayAnimationOnClick",eh),R.add("PreliminaryAction",ml),R.add("PreliminaryTrigger",th),R.add("VisibilityAction",ih),R.add("TapGestureTrigger",V0),R.add("USDZExporter",gn),R.add("Fog",Sl),R.add("BoxGizmo",ea),R.add("GridHelper",Cl),R.add("GroundProjectedEnv",en),R.add("UsageMarker",Hc),R.add("Interactable",o0),R.add("FixedJoint",vy),R.add("HingeJoint",uh),R.add("Light",vi),R.add("LODGroup",mh),R.add("LookAtConstraint",Br),R.add("NeedleMenu",un),R.add("NestedGltf",Mp),R.add("Networking",xy),R.add("OffsetConstraint",ta),R.add("CameraTargetReachedEvent",Uc),R.add("OrbitControls",_e),R.add("ParticleSystemRenderer",ds),R.add("ParticleSystem",vh),R.add("PlayerColor",Wl),R.add("Antialiasing",_h),R.add("BloomEffect",Wp),R.add("ChromaticAberration",wh),R.add("ColorAdjustments",nr),R.add("DepthOfField",Es),R.add("EffectWrapper",Sh),R.add("PixelationEffect",Ch),R.add("ScreenSpaceAmbientOcclusion",io),R.add("ScreenSpaceAmbientOcclusionN8",As),R.add("SharpeningEffect",Oh),R.add("TiltShiftEffect",yn),R.add("ToneMappingEffect",sr),R.add("Vignette",la),R.add("Volume",Rl),R.add("ReflectionProbe",Xc),R.add("Renderer",Ui),R.add("MeshRenderer",Yc),R.add("SkinnedMeshRenderer",C0),R.add("Rigidbody",dt),R.add("SceneSwitcher",Ze),R.add("ScreenCapture",rr),R.add("ShadowCatcher",Th),R.add("RemoteSkybox",Xp),R.add("SmoothFollow",Kp),R.add("SpatialTriggerReceiver",vn),R.add("SpatialTrigger",Zp),R.add("SpectatorCamera",Jp),R.add("SpriteRenderer",fi),R.add("SyncedCamera",$y),R.add("SyncedRoom",Is),R.add("SyncedTransform",sn),R.add("TestRunner",qy),R.add("TestSimulateUserData",Xy),R.add("PlayableDirector",El),R.add("SignalReceiver",Bh),R.add("AnimationTrackHandler",sm),R.add("AudioTrackHandler",nm),R.add("SignalTrackHandler",Uh),R.add("ControlTrackHandler",om),R.add("TransformGizmo",da),R.add("BaseUIComponent",ps),R.add("UIRootComponent",rh),R.add("Button",oo),R.add("Canvas",wl),R.add("CanvasGroup",Yo),R.add("EventSystem",si),R.add("Graphic",ch),R.add("MaskableGraphic",hh),R.add("Image",Al),R.add("RawImage",lm),R.add("InputField",Zy),R.add("VerticalLayoutGroup",ay),R.add("HorizontalLayoutGroup",ly),R.add("GridLayoutGroup",cy),R.add("Outline",_l),R.add("ObjectRaycaster",ji),R.add("GraphicRaycaster",Iu),R.add("SpatialGrabRaycaster",Bc),R.add("RectTransform",Rs),R.add("SpatialHtml",Wh),R.add("Text",Nt),R.add("EnvironmentScene",hm),R.add("LookAt",Jy),R.add("OpenURL",Il),R.add("VideoPlayer",yt),R.add("Voip",jo),R.add("Avatar",Ho),R.add("XRControllerFollow",ro),R.add("XRControllerModel",pn),R.add("XRControllerMovement",Ni),R.add("TeleportTarget",wp),R.add("WebARCameraBackground",Gh),R.add("WebARSessionRoot",Vo),R.add("WebXR",xp),R.add("AvatarMarker",di),R.add("WebXRImageTracking",qh),R.add("WebXRPlaneTracking",lo),R.add("XRRig",pm),R.add("XRFlag",os),R.add("PlayerSync",Y0),R.add("PlayerState",ks),R.add("PresentationMode",_L);const Xh=wt,wL=C("debugtypestore");wL&&console.log(R);function xL(n,e){const t=lw(n,e);return t!==void 0?t:null}const SL=new XM,ov=Symbol("deserialize-queue");async function CL(n,e,t,s=null,o){if(!t){console.debug("Can not create component instances: gltf is null");return}let r=s;typeof r=="number"&&(r=new jt(s));const l=e.indexOf("?");e=l===-1?e:e.substring(0,l);const c=new uf(t.scene);c.gltfId=e,c.context=n,c.gltf=t,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=SL;let h=n[ov];if(h||(h=n[ov]=[]),t.scenes)for(const d of t.scenes)await lv(c,d,h);if(t.children)for(const d of t.children)await lv(c,d,h);n.new_scripts_pre_setup_callbacks.push(()=>{const d=n[ov];if(d){for(const u of d)PL(u,c);d.length=0}if(r){const u={},p=[];av(t,r,u,p);for(const g of t.scenes)av(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const rv=Symbol("original-component-name"),Dl=new Map;function av(n,e,t,s){if(e===null||!n)return;const o=n.guid,r=n.guid;r!=null&&r.length&&(Dl.has(r)||(Xh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+n.name),Dl.set(r,new jt(r))));const l=r&&Dl.get(r)||e;if(n.guid=l.generateUUID(),o&&o!=="invalid"&&(t[o]=n.guid),n&&n.userData&&n.userData.components)for(const c of n.userData.components){if(c===null)continue;const h=c.guid;h?Dl.has(h)||(Xh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[rv]),Dl.set(h,new jt(h))):Xh&&console.warn("Can not create IdProvider: component "+c[rv]+" has no guid",c.guid);const d=Dl.get(h)||e,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(t[u]=c.guid),c.resolveGuids&&s.push(c)}if(n.children)for(const c of n.children)av(c,e,t,s)}const Qh=[];async function lv(n,e,t,s){var o,r,l,c,h;if(!e)return;const d=e.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=R.get(p.name);if(g!=null){const f=new g;f.sourceId=n.gltfId,Na(f,p,n.implementationInformation),f.context=n.context,"guid"in p&&(f[rc]=p.guid),f[rv]=p.name,kr(e,f,!1),t.push({instance:f,compData:p,obj:e}),f.isCamera&&n.context&&n.context.mainCamera===null&&f.tag==="MainCamera"&&n.context.setCurrentCamera(f),((l=(r=(o=n.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(f.isCollider||f.isRigidbody)&&((h=(c=n.context)==null?void 0:c.physics.engine)==null||h.initialize())}else Xh&&console.debug("unknown component: "+p.name),Qh.includes(p.name)||Qh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Qh.length>0){const p=Qh.join(", ");console.warn("unknown components: "+p),Qh.length=0,Xt()&&De(`<strong>Unknown components in scene</strong>:
|
|
1454
1454
|
|
|
1455
1455
|
${p}
|
|
1456
1456
|
|
|
@@ -1604,4 +1604,4 @@ Error:`,c),null}}updateColliderCollisionGroups(e){const t=e[ii],s=e.membership;l
|
|
|
1604
1604
|
justify-content: center;
|
|
1605
1605
|
gap: .5rem;
|
|
1606
1606
|
}
|
|
1607
|
-
`),ge(this,ya).innerHTML=ge(this,xi).innerHTML,ge(this,ya).style.cssText="display: flex; align-items: center; justify-content: center;",ge(this,xi).innerHTML=ge(this,ya).outerHTML,ge(this,fa).innerHTML=ge(this,xi).outerHTML,ge(this,fa).prepend(ge(this,va)),yu(Mf,{element:ge(this,fa)}),(e=ge(this,Bl))==null||e.disconnect(),ge(this,Bl)??Us(this,Bl,new MutationObserver(()=>ud(this,mm,cC).call(this))),ge(this,Bl).observe(ge(this,xi),{attributes:!0}),fv&&console.log("Needle Button updated")},cC=function(){ge(this,xi)&&(ge(this,xi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},gm=new WeakMap,a(yv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aC)&&window.customElements.define(aC,yv);const sd=C("debugavatar");class vv{constructor(e,t,s,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Bs;s=P.instantiate(Ma(t,e.scene),r)}}else s=t;if(!s)return null;const o=this.findAvatar(s);return o.isValid?(sd&&console.log("[Custom Avatar] valid config",t,sd?o:""),o):(console.warn("[Custom Avatar] config isn't valid",t,sd?o:""),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(sd&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+t);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await ws().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return Bf(s,e),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await ws().createBuiltinComponents(e,l,c,null,void 0),o(c.scene)},c=>{sd&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let o=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!o){o=t;const c=new S;new Ci().setFromObject(o).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&o.scale.multiplyScalar(1/h*.3)}return new vv(t,o,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let o=!0;for(const r of t){if(!o)break;s.indexOf(r)===-1&&(o=!1)}if(o)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class uC{}const XL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:V1,ActionModel:Os,AlignmentConstraint:Ec,Animation:Ut,AnimationCurve:gh,AnimationExtension:up,AnimationTrackHandler:sm,Animator:Rt,AnimatorController:gs,Antialiasing:_h,AudioExtension:_a,AudioListener:Nn,AudioSource:ns,AudioTrackHandler:nm,Avatar:Ho,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Jf,AvatarLoader:hC,AvatarMarker:di,AvatarModel:vv,Avatar_Brain_LookAt:zc,Avatar_MouthShapes:Nc,Avatar_MustacheShake:Yf,Avatar_POI:Wn,AxesHelper:el,BaseUIComponent:ps,BasicIKConstraint:t0,BehaviorExtension:ey,BehaviorModel:ei,BloomEffect:Wp,BoxCollider:Wu,BoxGizmo:ea,BoxHelperComponent:Do,Button:oo,CallInfo:zn,Camera:hi,CameraTargetReachedEvent:Uc,Canvas:wl,CanvasGroup:Yo,CapsuleCollider:Vn,ChangeMaterialOnClick:U0,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:Hn,ChromaticAberration:wh,Collider:pi,ColorAdjustments:nr,ColorBySpeedModule:Ol,ColorOverLifetimeModule:Lp,ContactShadows:$c,ControlTrackHandler:om,CustomBranding:Jr,Deletable:r0,DeleteBox:Vu,DepthOfField:Es,DeviceFlag:$u,DocumentExtension:dC,DragControls:Hr,DropListener:Gn,Duplicatable:u0,EffectWrapper:Sh,EmissionModule:to,EmphasizeOnClick:pl,EnvironmentScene:hm,EventList:xe,EventListEvent:Tu,EventSystem:si,EventTrigger:Xu,FieldWithDefault:y1,FixedJoint:vy,Fog:Sl,GltfExport:k0,GltfExportBox:P0,Gradient:ia,Graphic:ch,GraphicRaycaster:Iu,GridHelper:Cl,GridLayoutGroup:cy,GroundProjectedEnv:en,GroupActionModel:No,HideOnStart:mp,HingeJoint:uh,HorizontalLayoutGroup:ly,Image:Al,InheritVelocityModule:Py,InputField:Zy,InstanceHandle:S0,InstancingHandler:ep,Interactable:o0,Keyframe:bi,LODGroup:mh,LODModel:Pl,Light:vi,LimitVelocityOverLifetimeModule:gt,LogStats:n0,LookAt:Jy,LookAtConstraint:Br,MainModule:Vt,MaskableGraphic:hh,MeshCollider:Bo,MeshRenderer:Yc,MinMaxCurve:Z,MinMaxGradient:sa,NeedleMenu:un,NestedGltf:Mp,Networking:xy,NoiseModule:Ce,ObjectRaycaster:ji,OffsetConstraint:ta,OpenURL:Il,OrbitControls:_e,Outline:_l,Padding:Zr,ParticleBurst:Ip,ParticleSubEmitter:Oy,ParticleSystem:vh,ParticleSystemRenderer:ds,PhysicsExtension:ty,PixelationEffect:Ch,PlayAnimationOnClick:eh,PlayAudioOnClick:Wo,PlayableDirector:El,PlayerColor:Wl,PointerEventData:hd,PostProcessingHandler:Wy,PreliminaryAction:ml,PreliminaryTrigger:th,RawImage:lm,Rect:Z1,RectTransform:Rs,ReflectionProbe:Xc,RegisteredAnimationInfo:pr,RemoteSkybox:Xp,Renderer:Ui,RendererLightmap:tp,Rigidbody:dt,RotationBySpeedModule:hs,RotationOverLifetimeModule:Ts,SceneSwitcher:Ze,ScreenCapture:rr,ScreenSpaceAmbientOcclusion:io,ScreenSpaceAmbientOcclusionN8:As,SetActiveOnClick:z0,ShadowCatcher:Th,ShapeModule:Cy,SharpeningEffect:Oh,SignalAsset:im,SignalReceiver:Bh,SignalReceiverEvent:Dh,SignalTrackHandler:Uh,Size:K1,SizeBySpeedModule:_i,SizeOverLifetimeModule:na,SkinnedMeshRenderer:C0,SmoothFollow:Kp,SpatialGrabRaycaster:Bc,SpatialHtml:Wh,SpatialTrigger:Zp,SpatialTriggerReceiver:vn,SpectatorCamera:Jp,SphereCollider:tl,Sprite:Yn,SpriteData:yl,SpriteRenderer:fi,SpriteSheet:fl,SubEmitterSystem:Fp,SyncedCamera:$y,SyncedRoom:Is,SyncedTransform:sn,TapGestureTrigger:V0,TeleportTarget:wp,TestRunner:qy,TestSimulateUserData:Xy,Text:Wt,TextBuilder:ry,TextExtension:Op,TextureSheetAnimationModule:$t,TiltShiftEffect:yn,ToneMappingEffect:sr,TrailModule:We,TransformData:ut,TransformGizmo:da,TriggerBuilder:At,TriggerModel:ul,UIRaycastUtils:Wf,UIRootComponent:rh,USDZExporter:gn,USDZText:Kr,USDZUIExtension:uy,UsageMarker:Hc,VariantAction:B0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:ay,VideoPlayer:yt,Vignette:la,VisibilityAction:ih,Voip:jo,Volume:Rl,VolumeParameter:N,VolumeProfile:Up,WebARCameraBackground:Gh,WebARSessionRoot:Vo,WebXR:xp,WebXRImageTracking:qh,WebXRImageTrackingModel:ao,WebXRPlaneTracking:lo,WebXRTrackedImage:sv,XRControllerFollow:ro,XRControllerModel:pn,XRControllerMovement:Ni,XRFlag:os,XRRig:pm,XRState:Di,__Ignore:uC},Symbol.toStringTag,{value:"Module"})),fm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,n=>{var e,t,s;fm&&console.warn("Creating missing camera");const o=n.context.scene,r=new we;r.name="Default Fallback Camera",o.add(r);const l=new hi;if(l.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",l.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null)l.clearFlags=Ur.Uninitialized;else if((s=n.context.domElement.getAttribute("background-image"))!=null&&s.length||n.context.lightmaps.tryGetSkybox(l.sourceId))l.clearFlags=Ur.Skybox,n.context.domElement.getAttribute("background-blurriness")===null&&(n.context.scene.backgroundBlurriness=.2);else{if(l.clearFlags=Ur.SolidColor,!n.context.domElement.getAttribute("background-color")){let d="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(d="#1f1f1f"),o.background=new re(d)}if(!o.environment){const d=new HP(n.context.renderer),u=new hm("neutral");o.environment=d.fromScene(u,.025).texture}}const c=kr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=n.context.domElement;return h?.cameraControls!=!1&&pC(n.context,c),c}),pe.registerCallback(me.ContextCreated,n=>{if(!n.context.mainCamera){fm&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=Ob(n.context.mainCamera);if(t?.isCameraController==!0){fm&&console.log("Will not auto-fit because a camera controller exists");return}pC(n.context)}});function pC(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(fm&&console.log("Creating default camera controls",e?.name),t){const s=bc(t,_e);s.sourceId=e?.sourceId??"unknown";const o=n.domElement.getAttribute("auto-rotate");if(s.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ut&&s.playAutomatically||s instanceof Rt||s instanceof El&&s.playOnAwake===!0)return!0;if(s instanceof Ut)return s.playAutomatically=!0,!0;if(s instanceof El)return s.playOnAwake=!0,!0}},!0)!==!0&&Ga.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,o)=>Ei(s,Ut)})});class QL extends PO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((o,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.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=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=OO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const v=new _t(p.index,1,!1);t.setIndex(v)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new Ci)),s.onProgress&&s.onProgress(u.progress),o(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const YL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:QL},Symbol.toStringTag,{value:"Module"}));export{zT as $physicsKey,ve as ActionBuilder,V1 as ActionCollection,Os as ActionModel,Rw as Addressables,Ec as AlignmentConstraint,Xa as AmbientMode,Ut as Animation,gh as AnimationCurve,up as AnimationExtension,sm as AnimationTrackHandler,Ga as AnimationUtils,Rt as Animator,Mo as AnimatorConditionMode,gs as AnimatorController,Uf as AnimatorControllerParameterType,Ac as AnimatorStateInfo,_h as Antialiasing,Ln as Application,B_ as AssetDatabase,ce as AssetReference,_a as AudioExtension,Nn as AudioListener,ns as AudioSource,nm as AudioTrackHandler,Ho as Avatar,zr as AvatarBlink_Simple,Jf as AvatarEyeLook_Rotation,hC as AvatarLoader,di as AvatarMarker,vv as AvatarModel,zc as Avatar_Brain_LookAt,Nc as Avatar_MouthShapes,Yf as Avatar_MustacheShake,Wn as Avatar_POI,Qa as Axes,el as AxesHelper,wg as BUILD_TIME,ps as BaseUIComponent,t0 as BasicIKConstraint,ey as BehaviorExtension,ei as BehaviorModel,Ar as BlobStorage,Wp as BloomEffect,Wu as BoxCollider,ea as BoxGizmo,Do as BoxHelperComponent,oo as Button,Po as ButtonsFactory,jx as CallDirection,zn as CallInfo,hi as Camera,Uc as CameraTargetReachedEvent,wl as Canvas,Yo as CanvasGroup,Vn as CapsuleCollider,U0 as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,Hn as CharacterControllerInput,wh as ChromaticAberration,ki as CircularBuffer,Ur as ClearFlags,bn as ClipExtrapolation,pi as Collider,Ax as Collision,Mu as CollisionDetectionMode,nr as ColorAdjustments,Ol as ColorBySpeedModule,Lp as ColorOverLifetimeModule,XR as Component,j as Component$1,pc as ComponentLifecycleEvents,XL as Components,b_ as ConnectionEvents,Ex as ContactPoint,$c as ContactShadows,J as Context,IR as ContextArgs,me as ContextEvent,pe as ContextRegistry,om as ControlTrackHandler,Jr as CustomBranding,o1 as CustomShader,gu as DefaultReflectionMode,r0 as Deletable,Vu as DeleteBox,Es as DepthOfField,$u as DeviceFlag,Q as DeviceUtilities,dC as DocumentExtension,Hr as DragControls,l0 as DragMode,Gn as DropListener,u0 as Duplicatable,Sh as EffectWrapper,to as EmissionModule,pl as EmphasizeOnClick,JS as EngineLoadingView,hm as EnvironmentScene,xe as EventList,Tu as EventListEvent,si as EventSystem,Xu as EventTrigger,y1 as FieldWithDefault,wf as FileReference,Lw as FileReferenceSerializer,cE as FileSpawnModel,Gx as File_Event,vy as FixedJoint,Sl as Fog,Oe as FrameEvent,Dd as GENERATOR,P as GameObject,G as Gizmos,k0 as GltfExport,P0 as GltfExportBox,ia as Gradient,ch as Graphic,Iu as GraphicRaycaster,ec as Graphics,Cl as GridHelper,cy as GridLayoutGroup,en as GroundProjectedEnv,No as GroupActionModel,Bu as HideFlags,mp as HideOnStart,uh as HingeJoint,ly as HorizontalLayoutGroup,DM as HostData,Al as Image,_f as ImageReference,Aw as ImageReferenceSerializer,Py as InheritVelocityModule,r_ as Input,ri as InputEventQueue,Be as InputEvents,Zy as InputField,S0 as InstanceHandle,ep as InstancingHandler,ms as InstancingUtil,Y_ as InstantiateEvent,Dt as InstantiateIdProvider,Bs as InstantiateOptions,o0 as Interactable,Hh as InternalScreenshotUtils,aM as JoinedRoomResponse,Yk as KeyEventArgs,bi as Keyframe,mh as LODGroup,Pl as LODModel,lM as LeftRoomResponse,vi as Light,Ww as LightData,gt as LimitVelocityOverLifetimeModule,IL as LoadingElementOptions,n0 as LogStats,Mi as LogType,Jy as LookAt,Br as LookAtConstraint,L as MODULES,Vt as MainModule,Qy as MarkerType,hh as MaskableGraphic,W as Mathf,Bo as MeshCollider,Yc as MeshRenderer,Z as MinMaxCurve,sa as MinMaxGradient,ac as NEKeyboardEvent,An as NEPointerEvent,yv as NeedleButtonElement,h0 as NeedleEngineModelLoader,dv as NeedleEngineWebComponent,un as NeedleMenu,Fd as NeedlePatchesKey,Og as NeedleXRController,oe as NeedleXRSession,x_ as NeedleXRSync,M_ as NeedleXRUtils,Mp as NestedGltf,w_ as NetworkConnection,nn as NetworkedStreamEvents,dd as NetworkedStreams,xy as Networking,Z_ as NewInstanceModel,Ce as NoiseModule,ji as ObjectRaycaster,xo as ObjectUtils,ta as OffsetConstraint,Rd as OneEuroFilter,rg as OneEuroFilterXYZ,Il as OpenURL,_e as OrbitControls,_l as Outline,__ as OwnershipEvent,Ig as OwnershipModel,Ea as PUBLIC_KEY,Zr as Padding,Ip as ParticleBurst,Oy as ParticleSubEmitter,vh as ParticleSystem,ir as ParticleSystemBaseBehaviour,ds as ParticleSystemRenderer,Ap as ParticleSystemShapeType,Fu as PeerHandle,y_ as PeerNetworking,qg as Physics,ty as PhysicsExtension,xt as PhysicsMaterialCombine,Ch as PixelationEffect,eh as PlayAnimationOnClick,Wo as PlayAudioOnClick,El as PlayableDirector,Wl as PlayerColor,ks as PlayerState,Q1 as PlayerStateEvent,Y0 as PlayerSync,Bw as PlayerView,Fw as PlayerViewManager,hd as PointerEventData,zd as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,Wy as PostProcessingHandler,ml as PreliminaryAction,th as PreliminaryTrigger,Uo as PreviewHelper,Sr as PrimitiveType,de as Progress,eg as PromiseAllWithErrors,Jm as PromiseErrorResult,he as RGBAColor,nC as RapierPhysics,lm as RawImage,Dn as RaycastOptions,Z1 as Rect,Rs as RectTransform,Xc as ReflectionProbe,pr as RegisteredAnimationInfo,Xp as RemoteSkybox,Ic as RenderTexture,Cx as RenderTextureSerializer,Ui as Renderer,Nw as RendererData,tp as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,se as RoomEvents,hs as RotationBySpeedModule,Ts as RotationOverLifetimeModule,Yu as SceneLightSettings,Ze as SceneSwitcher,rr as ScreenCapture,io as ScreenSpaceAmbientOcclusion,As as ScreenSpaceAmbientOcclusionN8,xs as SendQueue,uf as SerializationContext,z0 as SetActiveOnClick,Th as ShadowCatcher,Cy as ShapeModule,Oh as SharpeningEffect,im as SignalAsset,Bh as SignalReceiver,Dh as SignalReceiverEvent,Uh as SignalTrackHandler,K1 as Size,_i as SizeBySpeedModule,na as SizeOverLifetimeModule,C0 as SkinnedMeshRenderer,Kp as SmoothFollow,Bc as SpatialGrabRaycaster,Wh as SpatialHtml,Zp as SpatialTrigger,vn as SpatialTriggerReceiver,Jp as SpectatorCamera,tl as SphereCollider,Gg as SphereIntersection,Ix as SphereOverlapResult,Yn as Sprite,yl as SpriteData,fi as SpriteRenderer,fl as SpriteSheet,eT as StateMachineBehaviour,Xf as StreamEndedEvent,Lx as StreamReceivedEvent,Fp as SubEmitterSystem,$y as SyncedCamera,Is as SyncedRoom,sn as SyncedTransform,V0 as TapGestureTrigger,wp as TeleportTarget,qy as TestRunner,WL as TestSceneUtils,Xy as TestSimulateUserData,Wt as Text,ry as TextBuilder,Op as TextExtension,$t as TextureSheetAnimationModule,yn as TiltShiftEffect,$w as Time,sr as ToneMappingEffect,Fh as TrackHandler,qi as TrackType,We as TrailModule,ut as TransformData,da as TransformGizmo,At as TriggerBuilder,ul as TriggerModel,R as TypeStore,Wf as UIRaycastUtils,rh as UIRootComponent,M0 as USDDocument,gi as USDObject,C1 as USDWriter,gn as USDZExporter,P1 as USDZExporter$1,Kr as USDZText,uy as USDZUIExtension,Px as UriSerializer,Hc as UsageMarker,cM as UserJoinedOrLeftRoomModel,_s as VERSION,B0 as VariantAction,qe as VelocityOverLifetimeModule,ay as VerticalLayoutGroup,yt as VideoPlayer,Co as ViewDevice,la as Vignette,ih as VisibilityAction,jo as Voip,Rl as Volume,N as VolumeParameter,Up as VolumeProfile,dR as WaitForFrames,jw as WaitForPromise,xf as WaitForSeconds,co as Watch,Gh as WebARCameraBackground,Vo as WebARSessionRoot,xp as WebXR,gl as WebXRButtonFactory,qh as WebXRImageTracking,ao as WebXRImageTrackingModel,lo as WebXRPlaneTracking,sv as WebXRTrackedImage,ro as XRControllerFollow,pn as XRControllerModel,Ni as XRControllerMovement,os as XRFlag,pm as XRRig,Di as XRState,rn as XRStateFlag,uC as __Ignore,W_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,gb as addAttributeChangeCallback,Ei as addComponent,EE as addCustomExtensionPlugin,kr as addNewComponent,Bd as addPatch,ru as apply,qR as applyHMRChanges,mw as applyPrototypeExtensions,K_ as beginListenDestroy,ew as beginListenInstantiate,Tg as binaryIdentifierCasts,AR as build_scene_functions,wr as builtinComponentKeyName,hv as calculateProgress01,hk as clearMessages,vT as colorSerializer,nw as compareAssociation,Eu as componentSerializer,zb as copyTexture,yx as createMotion,ai as debugNet,lc as debugOwner,T1 as decompressGpuTexture,Xl as deepClone,$s as delay,Ql as delayForFrames,nu as deserializeObject,Ai as destroy,vw as destroyComponentInstance,qx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,rc as editorGuidKeyName,_r as enableSpatialConsole,_T as euler,CT as eventListSerializer,HL as exportAsGLTF,ff as findByGuid,Sc as findObjectOfType,ww as findObjectsOfType,Qg as findResourceUsers,Wb as fitObjectIntoVolume,Er as foreachComponent,du as foreachComponentEnumerator,Pk as forward,yb as generateQRCode,J_ as generateSeed,ni as getBoundingBox,Ob as getCameraController,Mr as getComponent,wc as getComponentInChildren,xc as getComponentInParent,_c as getComponents,Wa as getComponentsInChildren,ou as getComponentsInParent,b1 as getFormattedDate,Mt as getIconElement,kf as getIconTexture,ws as getLoader,bc as getOrAddComponent,C as getParam,Mk as getParentHierarchyPath,VO as getPath,sM as getPeerOptions,g_ as getPeerjsInstance,kM as getResourceUserCount,Rb as getTempColor,vs as getTempQuaternion,X as getTempVector,Gl as getUrlParams,Nb as getVisibleInCustomShadowRendering,Ib as getWorldDirection,pg as getWorldEuler,ee as getWorldPosition,Se as getWorldQuaternion,Id as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,Mc as hasIndieLicense,Ru as hasPointerEventComponent,Zs as hasProLicense,qb as hideDebugConsole,E1 as imageToCanvas,Ha as instantiate,a1 as invokeLoadedImportPluginHooks,o_ as invokeXRSessionEnd,n_ as invokeXRSessionStart,xw as isActiveInHierarchy,Va as isActiveSelf,QO as isAndroidDevice,Bb as isAnimationAction,Tx as isComponent,UO as isDebugMode,HO as isDesktop,Tr as isDestroyed,B as isDevEnvironment,PM as isDisposed,VL as isExporting,Rx as isGLTFModel,ob as isHostedOnGlitch,Ff as isHotReloadEnabled,HR as isHotReloading,qO as isIPad,Xw as isIconElement,Xt as isLocalNetwork,KO as isMacOS,GO as isMobileDevice,YO as isMozillaXR,ek as isQuest,U_ as isResourceTrackingEnabled,JO as isSafari,lu as isUsingInstancing,ZO as isiOS,XO as isiPad,kL as loadAsset,cv as loadSync,Ld as logHierarchy,yk as lookAtInverse,Zl as lookAtObject,vk as lookAtScreenPoint,NO as makeId,ub as makeIdFromRandomWords,as as makeNameSafe,Sw as markAsInstancedRendered,tk as microphonePermissionsGranted,FO as nameof,lb as nameofFactory,Sx as objectSerializer,Qk as offXRSessionEnd,Xk as offXRSessionStart,VR as onAfterRender,WR as onBeforeRender,zR as onClear,NR as onDestroy,nx as onInitialized,jf as onStart,ox as onUpdate,Pg as onXRSessionEnd,Ud as onXRSessionStart,qS as parseSync,Vb as placeOnSurface,fg as postprocessFBXMaterials,uT as prefix,cb as pushState,WO as randomNumber,Eg as registerBinaryType,_u as registerComponent,b0 as registerComponentExtension,us as registerCustomEffectType,_0 as registerExportExtensions,Zu as registerExtensions,dx as registerHotReloadType,xg as registerLoader,iw as registerPrefabProvider,gw as registerPrototypeExtensions,NM as registerType,mb as relativePathPrefix,fb as removeAttributeChangeCallback,gf as removeComponent,AE as removeCustomImportExtensionType,Gk as removePatch,vo as resolveUrl,pb as sanitizeString,zS as saveImage,hL as screenshot,tv as screenshot2,of as sendDestroyed,m as serializable,lw as serializeObject,jr as serializeable,Cc as setActive,wb as setAllowBalloonMessages,rk as setAllowOverlayMessages,Ed as setAutoFitEnabled,ag as setCameraController,Pw as setDestroyed,Dk as setDevEnvironment,Xg as setDisposable,$a as setDontDestroy,Ym as setOrAddParamsToUrl,zO as setParam,ql as setParamWithoutReload,nM as setPeerOptions,CM as setResourceTrackingEnabled,Km as setState,gg as setVisibleInCustomShadowRendering,mg as setWorldEuler,lt as setWorldPosition,vr as setWorldPositionXYZ,Yi as setWorldQuaternion,ug as setWorldQuaternionXYZW,Db as setWorldRotation,Jl as setWorldRotationXYZ,Ta as setWorldScale,sc as showBalloonError,De as showBalloonMessage,be as showBalloonWarning,_g as showDebugConsole,fk as slerp,yc as syncDestroy,Q0 as syncField,rf as syncInstantiate,Rk as textureToCanvas,p_ as tryCastBinary,Qx as tryDetermineMimetypeFromBinary,Xx as tryDetermineMimetypeFromURL,Ma as tryFindObject,m_ as tryGetGuid,ux as unregisterHotReloadType,Zm as unwatchWrite,kb as useForAutoFit,Tt as validate,kd as watchWrite};
|
|
1607
|
+
`),ge(this,ya).innerHTML=ge(this,xi).innerHTML,ge(this,ya).style.cssText="display: flex; align-items: center; justify-content: center;",ge(this,xi).innerHTML=ge(this,ya).outerHTML,ge(this,fa).innerHTML=ge(this,xi).outerHTML,ge(this,fa).prepend(ge(this,va)),yu(Mf,{element:ge(this,fa)}),(e=ge(this,Bl))==null||e.disconnect(),ge(this,Bl)??Us(this,Bl,new MutationObserver(()=>ud(this,mm,cC).call(this))),ge(this,Bl).observe(ge(this,xi),{attributes:!0}),fv&&console.log("Needle Button updated")},cC=function(){ge(this,xi)&&(ge(this,xi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},gm=new WeakMap,a(yv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aC)&&window.customElements.define(aC,yv);const sd=C("debugavatar");class vv{constructor(e,t,s,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Bs;s=P.instantiate(Ma(t,e.scene),r)}}else s=t;if(!s)return null;const o=this.findAvatar(s);return o.isValid?(sd&&console.log("[Custom Avatar] valid config",t,sd?o:""),o):(console.warn("[Custom Avatar] config isn't valid",t,sd?o:""),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(sd&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+t);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await ws().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return Bf(s,e),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await ws().createBuiltinComponents(e,l,c,null,void 0),o(c.scene)},c=>{sd&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let o=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!o){o=t;const c=new S;new Ci().setFromObject(o).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&o.scale.multiplyScalar(1/h*.3)}return new vv(t,o,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let o=!0;for(const r of t){if(!o)break;s.indexOf(r)===-1&&(o=!1)}if(o)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class uC{}const XL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:V1,ActionModel:Os,AlignmentConstraint:Ec,Animation:Ft,AnimationCurve:gh,AnimationExtension:up,AnimationTrackHandler:sm,Animator:Rt,AnimatorController:gs,Antialiasing:_h,AudioExtension:_a,AudioListener:Nn,AudioSource:ns,AudioTrackHandler:nm,Avatar:Ho,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Jf,AvatarLoader:hC,AvatarMarker:di,AvatarModel:vv,Avatar_Brain_LookAt:zc,Avatar_MouthShapes:Nc,Avatar_MustacheShake:Yf,Avatar_POI:Wn,AxesHelper:el,BaseUIComponent:ps,BasicIKConstraint:t0,BehaviorExtension:ey,BehaviorModel:ei,BloomEffect:Wp,BoxCollider:Wu,BoxGizmo:ea,BoxHelperComponent:Do,Button:oo,CallInfo:zn,Camera:hi,CameraTargetReachedEvent:Uc,Canvas:wl,CanvasGroup:Yo,CapsuleCollider:Vn,ChangeMaterialOnClick:U0,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:Hn,ChromaticAberration:wh,Collider:pi,ColorAdjustments:nr,ColorBySpeedModule:Ol,ColorOverLifetimeModule:Lp,ContactShadows:$c,ControlTrackHandler:om,CustomBranding:Jr,Deletable:r0,DeleteBox:Vu,DepthOfField:Es,DeviceFlag:$u,DocumentExtension:dC,DragControls:Hr,DropListener:Gn,Duplicatable:u0,EffectWrapper:Sh,EmissionModule:to,EmphasizeOnClick:pl,EnvironmentScene:hm,EventList:xe,EventListEvent:Tu,EventSystem:si,EventTrigger:Xu,FieldWithDefault:y1,FixedJoint:vy,Fog:Sl,GltfExport:k0,GltfExportBox:P0,Gradient:ia,Graphic:ch,GraphicRaycaster:Iu,GridHelper:Cl,GridLayoutGroup:cy,GroundProjectedEnv:en,GroupActionModel:No,HideOnStart:mp,HingeJoint:uh,HorizontalLayoutGroup:ly,Image:Al,InheritVelocityModule:Py,InputField:Zy,InstanceHandle:S0,InstancingHandler:ep,Interactable:o0,Keyframe:bi,LODGroup:mh,LODModel:Pl,Light:vi,LimitVelocityOverLifetimeModule:gt,LogStats:n0,LookAt:Jy,LookAtConstraint:Br,MainModule:Wt,MaskableGraphic:hh,MeshCollider:Bo,MeshRenderer:Yc,MinMaxCurve:Z,MinMaxGradient:sa,NeedleMenu:un,NestedGltf:Mp,Networking:xy,NoiseModule:Ce,ObjectRaycaster:ji,OffsetConstraint:ta,OpenURL:Il,OrbitControls:_e,Outline:_l,Padding:Zr,ParticleBurst:Ip,ParticleSubEmitter:Oy,ParticleSystem:vh,ParticleSystemRenderer:ds,PhysicsExtension:ty,PixelationEffect:Ch,PlayAnimationOnClick:eh,PlayAudioOnClick:Wo,PlayableDirector:El,PlayerColor:Wl,PointerEventData:hd,PostProcessingHandler:Wy,PreliminaryAction:ml,PreliminaryTrigger:th,RawImage:lm,Rect:Z1,RectTransform:Rs,ReflectionProbe:Xc,RegisteredAnimationInfo:pr,RemoteSkybox:Xp,Renderer:Ui,RendererLightmap:tp,Rigidbody:dt,RotationBySpeedModule:hs,RotationOverLifetimeModule:Ts,SceneSwitcher:Ze,ScreenCapture:rr,ScreenSpaceAmbientOcclusion:io,ScreenSpaceAmbientOcclusionN8:As,SetActiveOnClick:z0,ShadowCatcher:Th,ShapeModule:Cy,SharpeningEffect:Oh,SignalAsset:im,SignalReceiver:Bh,SignalReceiverEvent:Dh,SignalTrackHandler:Uh,Size:K1,SizeBySpeedModule:_i,SizeOverLifetimeModule:na,SkinnedMeshRenderer:C0,SmoothFollow:Kp,SpatialGrabRaycaster:Bc,SpatialHtml:Wh,SpatialTrigger:Zp,SpatialTriggerReceiver:vn,SpectatorCamera:Jp,SphereCollider:tl,Sprite:Yn,SpriteData:yl,SpriteRenderer:fi,SpriteSheet:fl,SubEmitterSystem:Fp,SyncedCamera:$y,SyncedRoom:Is,SyncedTransform:sn,TapGestureTrigger:V0,TeleportTarget:wp,TestRunner:qy,TestSimulateUserData:Xy,Text:Nt,TextBuilder:ry,TextExtension:Op,TextureSheetAnimationModule:Vt,TiltShiftEffect:yn,ToneMappingEffect:sr,TrailModule:We,TransformData:ut,TransformGizmo:da,TriggerBuilder:At,TriggerModel:ul,UIRaycastUtils:Wf,UIRootComponent:rh,USDZExporter:gn,USDZText:Kr,USDZUIExtension:uy,UsageMarker:Hc,VariantAction:B0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:ay,VideoPlayer:yt,Vignette:la,VisibilityAction:ih,Voip:jo,Volume:Rl,VolumeParameter:N,VolumeProfile:Up,WebARCameraBackground:Gh,WebARSessionRoot:Vo,WebXR:xp,WebXRImageTracking:qh,WebXRImageTrackingModel:ao,WebXRPlaneTracking:lo,WebXRTrackedImage:sv,XRControllerFollow:ro,XRControllerModel:pn,XRControllerMovement:Ni,XRFlag:os,XRRig:pm,XRState:Di,__Ignore:uC},Symbol.toStringTag,{value:"Module"})),fm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,n=>{var e,t,s;fm&&console.warn("Creating missing camera");const o=n.context.scene,r=new we;r.name="Default Fallback Camera",o.add(r);const l=new hi;if(l.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",l.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null)l.clearFlags=Ur.Uninitialized;else if((s=n.context.domElement.getAttribute("background-image"))!=null&&s.length||n.context.lightmaps.tryGetSkybox(l.sourceId))l.clearFlags=Ur.Skybox,n.context.domElement.getAttribute("background-blurriness")===null&&(n.context.scene.backgroundBlurriness=.2);else{if(l.clearFlags=Ur.SolidColor,!n.context.domElement.getAttribute("background-color")){let d="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(d="#1f1f1f"),o.background=new re(d)}if(!o.environment){const d=new HP(n.context.renderer),u=new hm("neutral");o.environment=d.fromScene(u,.025).texture}}const c=kr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=n.context.domElement;return h?.cameraControls!=!1&&pC(n.context,c),c}),pe.registerCallback(me.ContextCreated,n=>{if(!n.context.mainCamera){fm&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=Ob(n.context.mainCamera);if(t?.isCameraController==!0){fm&&console.log("Will not auto-fit because a camera controller exists");return}pC(n.context)}});function pC(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(fm&&console.log("Creating default camera controls",e?.name),t){const s=bc(t,_e);s.sourceId=e?.sourceId??"unknown";const o=n.domElement.getAttribute("auto-rotate");if(s.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ft&&s.playAutomatically||s instanceof Rt||s instanceof El&&s.playOnAwake===!0)return!0;if(s instanceof Ft)return s.playAutomatically=!0,!0;if(s instanceof El)return s.playOnAwake=!0,!0}},!0)!==!0&&Ga.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,o)=>Ei(s,Ft)})});class QL extends PO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((o,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.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=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=OO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const v=new _t(p.index,1,!1);t.setIndex(v)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new Ci)),s.onProgress&&s.onProgress(u.progress),o(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const YL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:QL},Symbol.toStringTag,{value:"Module"}));export{zT as $physicsKey,ve as ActionBuilder,V1 as ActionCollection,Os as ActionModel,Rw as Addressables,Ec as AlignmentConstraint,Xa as AmbientMode,Ft as Animation,gh as AnimationCurve,up as AnimationExtension,sm as AnimationTrackHandler,Ga as AnimationUtils,Rt as Animator,Mo as AnimatorConditionMode,gs as AnimatorController,Uf as AnimatorControllerParameterType,Ac as AnimatorStateInfo,_h as Antialiasing,Ln as Application,B_ as AssetDatabase,ce as AssetReference,_a as AudioExtension,Nn as AudioListener,ns as AudioSource,nm as AudioTrackHandler,Ho as Avatar,zr as AvatarBlink_Simple,Jf as AvatarEyeLook_Rotation,hC as AvatarLoader,di as AvatarMarker,vv as AvatarModel,zc as Avatar_Brain_LookAt,Nc as Avatar_MouthShapes,Yf as Avatar_MustacheShake,Wn as Avatar_POI,Qa as Axes,el as AxesHelper,wg as BUILD_TIME,ps as BaseUIComponent,t0 as BasicIKConstraint,ey as BehaviorExtension,ei as BehaviorModel,Ar as BlobStorage,Wp as BloomEffect,Wu as BoxCollider,ea as BoxGizmo,Do as BoxHelperComponent,oo as Button,Po as ButtonsFactory,jx as CallDirection,zn as CallInfo,hi as Camera,Uc as CameraTargetReachedEvent,wl as Canvas,Yo as CanvasGroup,Vn as CapsuleCollider,U0 as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,Hn as CharacterControllerInput,wh as ChromaticAberration,ki as CircularBuffer,Ur as ClearFlags,bn as ClipExtrapolation,pi as Collider,Ax as Collision,Mu as CollisionDetectionMode,nr as ColorAdjustments,Ol as ColorBySpeedModule,Lp as ColorOverLifetimeModule,XR as Component,j as Component$1,pc as ComponentLifecycleEvents,XL as Components,b_ as ConnectionEvents,Ex as ContactPoint,$c as ContactShadows,J as Context,IR as ContextArgs,me as ContextEvent,pe as ContextRegistry,om as ControlTrackHandler,Jr as CustomBranding,o1 as CustomShader,gu as DefaultReflectionMode,r0 as Deletable,Vu as DeleteBox,Es as DepthOfField,$u as DeviceFlag,Q as DeviceUtilities,dC as DocumentExtension,Hr as DragControls,l0 as DragMode,Gn as DropListener,u0 as Duplicatable,Sh as EffectWrapper,to as EmissionModule,pl as EmphasizeOnClick,JS as EngineLoadingView,hm as EnvironmentScene,xe as EventList,Tu as EventListEvent,si as EventSystem,Xu as EventTrigger,y1 as FieldWithDefault,wf as FileReference,Lw as FileReferenceSerializer,cE as FileSpawnModel,Gx as File_Event,vy as FixedJoint,Sl as Fog,Oe as FrameEvent,Dd as GENERATOR,P as GameObject,G as Gizmos,k0 as GltfExport,P0 as GltfExportBox,ia as Gradient,ch as Graphic,Iu as GraphicRaycaster,ec as Graphics,Cl as GridHelper,cy as GridLayoutGroup,en as GroundProjectedEnv,No as GroupActionModel,Bu as HideFlags,mp as HideOnStart,uh as HingeJoint,ly as HorizontalLayoutGroup,DM as HostData,Al as Image,_f as ImageReference,Aw as ImageReferenceSerializer,Py as InheritVelocityModule,r_ as Input,ri as InputEventQueue,Be as InputEvents,Zy as InputField,S0 as InstanceHandle,ep as InstancingHandler,ms as InstancingUtil,Y_ as InstantiateEvent,jt as InstantiateIdProvider,Bs as InstantiateOptions,o0 as Interactable,Hh as InternalScreenshotUtils,aM as JoinedRoomResponse,Yk as KeyEventArgs,bi as Keyframe,mh as LODGroup,Pl as LODModel,lM as LeftRoomResponse,vi as Light,Ww as LightData,gt as LimitVelocityOverLifetimeModule,IL as LoadingElementOptions,n0 as LogStats,Mi as LogType,Jy as LookAt,Br as LookAtConstraint,L as MODULES,Wt as MainModule,Qy as MarkerType,hh as MaskableGraphic,W as Mathf,Bo as MeshCollider,Yc as MeshRenderer,Z as MinMaxCurve,sa as MinMaxGradient,ac as NEKeyboardEvent,An as NEPointerEvent,yv as NeedleButtonElement,h0 as NeedleEngineModelLoader,dv as NeedleEngineWebComponent,un as NeedleMenu,Fd as NeedlePatchesKey,Og as NeedleXRController,oe as NeedleXRSession,x_ as NeedleXRSync,M_ as NeedleXRUtils,Mp as NestedGltf,w_ as NetworkConnection,nn as NetworkedStreamEvents,dd as NetworkedStreams,xy as Networking,Z_ as NewInstanceModel,Ce as NoiseModule,ji as ObjectRaycaster,xo as ObjectUtils,ta as OffsetConstraint,Rd as OneEuroFilter,rg as OneEuroFilterXYZ,Il as OpenURL,_e as OrbitControls,_l as Outline,__ as OwnershipEvent,Ig as OwnershipModel,Ea as PUBLIC_KEY,Zr as Padding,Ip as ParticleBurst,Oy as ParticleSubEmitter,vh as ParticleSystem,ir as ParticleSystemBaseBehaviour,ds as ParticleSystemRenderer,Ap as ParticleSystemShapeType,Fu as PeerHandle,y_ as PeerNetworking,qg as Physics,ty as PhysicsExtension,xt as PhysicsMaterialCombine,Ch as PixelationEffect,eh as PlayAnimationOnClick,Wo as PlayAudioOnClick,El as PlayableDirector,Wl as PlayerColor,ks as PlayerState,Q1 as PlayerStateEvent,Y0 as PlayerSync,Bw as PlayerView,Fw as PlayerViewManager,hd as PointerEventData,zd as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,Wy as PostProcessingHandler,ml as PreliminaryAction,th as PreliminaryTrigger,Uo as PreviewHelper,Sr as PrimitiveType,de as Progress,eg as PromiseAllWithErrors,Jm as PromiseErrorResult,he as RGBAColor,nC as RapierPhysics,lm as RawImage,Dn as RaycastOptions,Z1 as Rect,Rs as RectTransform,Xc as ReflectionProbe,pr as RegisteredAnimationInfo,Xp as RemoteSkybox,Ic as RenderTexture,Cx as RenderTextureSerializer,Ui as Renderer,Nw as RendererData,tp as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,se as RoomEvents,hs as RotationBySpeedModule,Ts as RotationOverLifetimeModule,Yu as SceneLightSettings,Ze as SceneSwitcher,rr as ScreenCapture,io as ScreenSpaceAmbientOcclusion,As as ScreenSpaceAmbientOcclusionN8,xs as SendQueue,uf as SerializationContext,z0 as SetActiveOnClick,Th as ShadowCatcher,Cy as ShapeModule,Oh as SharpeningEffect,im as SignalAsset,Bh as SignalReceiver,Dh as SignalReceiverEvent,Uh as SignalTrackHandler,K1 as Size,_i as SizeBySpeedModule,na as SizeOverLifetimeModule,C0 as SkinnedMeshRenderer,Kp as SmoothFollow,Bc as SpatialGrabRaycaster,Wh as SpatialHtml,Zp as SpatialTrigger,vn as SpatialTriggerReceiver,Jp as SpectatorCamera,tl as SphereCollider,Gg as SphereIntersection,Ix as SphereOverlapResult,Yn as Sprite,yl as SpriteData,fi as SpriteRenderer,fl as SpriteSheet,eT as StateMachineBehaviour,Xf as StreamEndedEvent,Lx as StreamReceivedEvent,Fp as SubEmitterSystem,$y as SyncedCamera,Is as SyncedRoom,sn as SyncedTransform,V0 as TapGestureTrigger,wp as TeleportTarget,qy as TestRunner,WL as TestSceneUtils,Xy as TestSimulateUserData,Nt as Text,ry as TextBuilder,Op as TextExtension,Vt as TextureSheetAnimationModule,yn as TiltShiftEffect,$w as Time,sr as ToneMappingEffect,Fh as TrackHandler,qi as TrackType,We as TrailModule,ut as TransformData,da as TransformGizmo,At as TriggerBuilder,ul as TriggerModel,R as TypeStore,Wf as UIRaycastUtils,rh as UIRootComponent,M0 as USDDocument,gi as USDObject,C1 as USDWriter,gn as USDZExporter,P1 as USDZExporter$1,Kr as USDZText,uy as USDZUIExtension,Px as UriSerializer,Hc as UsageMarker,cM as UserJoinedOrLeftRoomModel,_s as VERSION,B0 as VariantAction,qe as VelocityOverLifetimeModule,ay as VerticalLayoutGroup,yt as VideoPlayer,Co as ViewDevice,la as Vignette,ih as VisibilityAction,jo as Voip,Rl as Volume,N as VolumeParameter,Up as VolumeProfile,dR as WaitForFrames,jw as WaitForPromise,xf as WaitForSeconds,co as Watch,Gh as WebARCameraBackground,Vo as WebARSessionRoot,xp as WebXR,gl as WebXRButtonFactory,qh as WebXRImageTracking,ao as WebXRImageTrackingModel,lo as WebXRPlaneTracking,sv as WebXRTrackedImage,ro as XRControllerFollow,pn as XRControllerModel,Ni as XRControllerMovement,os as XRFlag,pm as XRRig,Di as XRState,rn as XRStateFlag,uC as __Ignore,W_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,gb as addAttributeChangeCallback,Ei as addComponent,EE as addCustomExtensionPlugin,kr as addNewComponent,Bd as addPatch,ru as apply,qR as applyHMRChanges,mw as applyPrototypeExtensions,K_ as beginListenDestroy,ew as beginListenInstantiate,Tg as binaryIdentifierCasts,AR as build_scene_functions,wr as builtinComponentKeyName,hv as calculateProgress01,hk as clearMessages,vT as colorSerializer,nw as compareAssociation,Eu as componentSerializer,zb as copyTexture,yx as createMotion,ai as debugNet,lc as debugOwner,T1 as decompressGpuTexture,Xl as deepClone,$s as delay,Ql as delayForFrames,nu as deserializeObject,Ai as destroy,vw as destroyComponentInstance,qx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,rc as editorGuidKeyName,_r as enableSpatialConsole,_T as euler,CT as eventListSerializer,HL as exportAsGLTF,ff as findByGuid,Sc as findObjectOfType,ww as findObjectsOfType,Qg as findResourceUsers,Wb as fitObjectIntoVolume,Er as foreachComponent,du as foreachComponentEnumerator,Pk as forward,yb as generateQRCode,J_ as generateSeed,ni as getBoundingBox,Ob as getCameraController,Mr as getComponent,wc as getComponentInChildren,xc as getComponentInParent,_c as getComponents,Wa as getComponentsInChildren,ou as getComponentsInParent,b1 as getFormattedDate,Mt as getIconElement,kf as getIconTexture,ws as getLoader,bc as getOrAddComponent,C as getParam,Mk as getParentHierarchyPath,VO as getPath,sM as getPeerOptions,g_ as getPeerjsInstance,kM as getResourceUserCount,Rb as getTempColor,vs as getTempQuaternion,X as getTempVector,Gl as getUrlParams,Nb as getVisibleInCustomShadowRendering,Ib as getWorldDirection,pg as getWorldEuler,ee as getWorldPosition,Se as getWorldQuaternion,Id as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,Mc as hasIndieLicense,Ru as hasPointerEventComponent,Zs as hasProLicense,qb as hideDebugConsole,E1 as imageToCanvas,Ha as instantiate,a1 as invokeLoadedImportPluginHooks,o_ as invokeXRSessionEnd,n_ as invokeXRSessionStart,xw as isActiveInHierarchy,Va as isActiveSelf,QO as isAndroidDevice,Bb as isAnimationAction,Tx as isComponent,UO as isDebugMode,HO as isDesktop,Tr as isDestroyed,B as isDevEnvironment,PM as isDisposed,VL as isExporting,Rx as isGLTFModel,ob as isHostedOnGlitch,Ff as isHotReloadEnabled,HR as isHotReloading,qO as isIPad,Xw as isIconElement,Xt as isLocalNetwork,KO as isMacOS,GO as isMobileDevice,YO as isMozillaXR,ek as isQuest,U_ as isResourceTrackingEnabled,JO as isSafari,lu as isUsingInstancing,ZO as isiOS,XO as isiPad,kL as loadAsset,cv as loadSync,Ld as logHierarchy,yk as lookAtInverse,Zl as lookAtObject,vk as lookAtScreenPoint,NO as makeId,ub as makeIdFromRandomWords,as as makeNameSafe,Sw as markAsInstancedRendered,tk as microphonePermissionsGranted,FO as nameof,lb as nameofFactory,Sx as objectSerializer,Qk as offXRSessionEnd,Xk as offXRSessionStart,VR as onAfterRender,WR as onBeforeRender,zR as onClear,NR as onDestroy,nx as onInitialized,jf as onStart,ox as onUpdate,Pg as onXRSessionEnd,Ud as onXRSessionStart,qS as parseSync,Vb as placeOnSurface,fg as postprocessFBXMaterials,uT as prefix,cb as pushState,WO as randomNumber,Eg as registerBinaryType,_u as registerComponent,b0 as registerComponentExtension,us as registerCustomEffectType,_0 as registerExportExtensions,Zu as registerExtensions,dx as registerHotReloadType,xg as registerLoader,iw as registerPrefabProvider,gw as registerPrototypeExtensions,NM as registerType,mb as relativePathPrefix,fb as removeAttributeChangeCallback,gf as removeComponent,AE as removeCustomImportExtensionType,Gk as removePatch,vo as resolveUrl,pb as sanitizeString,zS as saveImage,hL as screenshot,tv as screenshot2,of as sendDestroyed,m as serializable,lw as serializeObject,jr as serializeable,Cc as setActive,wb as setAllowBalloonMessages,rk as setAllowOverlayMessages,Ed as setAutoFitEnabled,ag as setCameraController,Pw as setDestroyed,Dk as setDevEnvironment,Xg as setDisposable,$a as setDontDestroy,Ym as setOrAddParamsToUrl,zO as setParam,ql as setParamWithoutReload,nM as setPeerOptions,CM as setResourceTrackingEnabled,Km as setState,gg as setVisibleInCustomShadowRendering,mg as setWorldEuler,lt as setWorldPosition,vr as setWorldPositionXYZ,Yi as setWorldQuaternion,ug as setWorldQuaternionXYZW,Db as setWorldRotation,Jl as setWorldRotationXYZ,Ta as setWorldScale,sc as showBalloonError,De as showBalloonMessage,be as showBalloonWarning,_g as showDebugConsole,fk as slerp,yc as syncDestroy,Q0 as syncField,rf as syncInstantiate,Rk as textureToCanvas,p_ as tryCastBinary,Qx as tryDetermineMimetypeFromBinary,Xx as tryDetermineMimetypeFromURL,Ma as tryFindObject,m_ as tryGetGuid,ux as unregisterHotReloadType,Zm as unwatchWrite,kb as useForAutoFit,Tt as validate,kd as watchWrite};
|