@needle-tools/engine 2.25.0-pre → 2.25.1-pre

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.
@@ -6336,7 +6336,7 @@ void main() {
6336
6336
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
6337
6337
  gl_FragColor = lightMapTexel;
6338
6338
  }
6339
- `,defines:{USE_LIGHTMAP:""}})}};var se=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=rO(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=rO(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let n=e.$serializedTypes=e.$serializedTypes||{};n[t]=o}};function rO(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var BM=be("debugstencil");function n5(o,e){return(o&1<<e.layer)!=0}var dh=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(BM&&console.log(t,dh.stencils),!t)return;let n=dh.stencils[t];if(!!n)for(let i=n.length-1;i>=0;i--){let s=n[i];if(n5(s.layer,e)){BM&&console.log(s);let r=e.material?.clone();r&&(e.material=r,e.gameObject.renderOrder=s.event*1e3+s.index*50,r.stencilWrite=!0,r.stencilWriteMask=255,r.stencilFuncMask=255,r.stencilRef=s.value,r.stencilFunc=s.compareFunc,r.stencilZPass=s.passOp,r.stencilFail=s.failOp,r.stencilZFail=s.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[s5];if(n){BM&&console.log(n);let i=n.stencil;if(i&&Array.isArray(i))for(let s of i){let r={...s};r.compareFunc=i5(r.compareFunc),r.passOp=NM(r.passOp),r.failOp=NM(r.failOp),r.zFailOp=NM(r.zFailOp),dh.stencils[this.source]||(dh.stencils[this.source]=[]),dh.stencils[this.source].push(r)}}}return null}},fh=dh;Se(fh,"stencils",{});function NM(o){switch(o){case 0:return td;case 1:return IS;case 2:return LS;case 3:return OS;case 4:return DS;case 6:return kS;case 7:return FS;case 5:return BS}return 0}function i5(o){switch(o){case 1:return NS;case 2:return US;case 3:return HS;case 4:return zS;case 5:return VS;case 6:return GS;case 7:return WS;case 8:return Q0}return 0}var s5="NEEDLE_render_objects";import{GLTFLoader as r5}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as UM}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as oO}from"three/examples/jsm/loaders/KTX2Loader.js";var Jm=be("debugdecoders"),Sr,pl;function HM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Jm&&console.log("Setting draco decoder path to",o),Sr.setDecoderPath(o))}function zM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Jm&&console.log("Setting draco decoder type to",o),Sr.setDecoderConfig({type:o}))}function VM(o){o!==void 0&&typeof o=="string"&&(pl||(pl=new oO),Jm&&console.log("Setting ktx2 transcoder path to",o),pl.setTranscoderPath(o))}function ph(o,e){Sr||(Sr=new UM,Sr.setDecoderPath("./include/draco/"),Sr.setDecoderConfig({type:"js"}),Jm&&console.log("Setting draco decoder path to","./include/draco/")),pl||(pl=new oO,pl.setTranscoderPath("./include/ktx2/"),Jm&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&pl.detectSupport(e.renderer)),o.setDRACOLoader(Sr),o.setKTX2Loader(pl)}var GM="NEEDLE_deferred_texture",ml=be("debugdeferredtextures"),Qm=class{static assignTextureLOD(e,t,n=0){if(!!t)for(let i of Object.keys(t)){let s=t[i];s?.isTexture===!0&&(ml&&console.log("FIND",i,s?.name,s?.userData,s),Qm.getOrLoadTexture(e,t,i,s,n).then(r=>{r?.isTexture===!0&&(r.needsUpdate=!0,t[i]=r,t.needsUpdate=!0)}))}}get name(){return GM}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return ml&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[GM];if(i){let s=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),s.then(r=>{ml&&console.log("register texture",r.name,r.uuid,i),r.userData.deferred=i,Qm.cache.set(r.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,s){let r=i.uuid,a=Qm.cache.get(r)||i.userData.deferred;if(a){ml&&console.log(r,a.uri,a.guid);let l=a.uri;if(l.endsWith(".glb")||l.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;let c=a.uri+"_"+a.guid;if(this.resolved[c])return this.resolved[c];let h=new r5;ph(h,e),ml&&console.log("Load "+l,t.name,n);let u=await h.loadAsync(l),d=u.parser,f=-1,g=!1;for(let m of u.parser.json.textures)if(f++,m?.extensions){let y=m?.extensions[GM];if(y?.guid&&y.guid===a.guid){g=!0;break}}if(!g)return null;let p=await d.getDependency("texture",f);return this.resolved[c]=p,ml&&console.log(t.name,n,'change "'+i.name+'" \u2192 "'+p.name+'"',l,f,p,t),p}else{let h=await new No().loadAsync(a.uri);return h&&ml?console.log(a,h):console.warn("failed loading",a.uri),h}}else ml&&console.warn("unknown uuid",i.name,i.uuid,i);return null}},Yo=Qm;Se(Yo,"cache",new Map),Se(Yo,"resolved",{});var lO=be("noInstancing"),cO=!!be("debuglightmaps"),o5=be("debuginstancing"),a5=be("debugprogressiveload"),Hd=class{path=null;asset=null;default};var WM=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),n=this.getMaterial.bind(this),i=e.gameObject;if(this._targets=[],i)switch(i.type){case"Group":this._targets=[...i.children];break;case"Mesh":this._targets.push(i);break}return new Proxy(this,{get(s,r){if(typeof r=="string"){let a=parseInt(r);if(!isNaN(a))return n(a)}return s[r]},set(s,r,a){return typeof r=="string"&&t(a,Number.parseInt(r)),Reflect.set(s,r,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let n=this._targets[t];!n||(n.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let n=t[e];return n?n.material:null}},ZM=class extends le{receiveShadows=!1;shadowCastingMode=jM.Off;lightmapIndex=-1;lightmapScaleOffset=new rt(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new WM(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return lO}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}get activeSelf(){return this.enabled}set activeSelf(e){let t=typeof e=="number"?e>.5:e;this.enabled=t,t&&(this.gameObject.visible=!0)}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let n=0;n<this.gameObject.children.length;n++){let i=this.gameObject.children[n];if(!(i.type!=="Mesh"||K.getComponent(i,ZM))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}i.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let n=new qo(this.gameObject,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,cO)}}else if(e==="Group"){for(let n of this.gameObject.children)if(!n.material?.isMeshBasicMaterial){let i=new qo(n,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,cO),i.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=l5.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return K.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return K.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!lO&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){fh.applyStencil(this)}onBeforeRenderThree(e,t,n,i,s,r){if(s._didRequestTextureLOD===void 0&&(s._didRequestTextureLOD=0,a5?(console.log("Load material LOD (with delay)",s.name),setTimeout(()=>{Yo.assignTextureLOD(this.context,s)},2e3)):Yo.assignTextureLOD(this.context,s)),s.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;s.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(s)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[XM]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[XM],this.handles)){for(let n=this.handles.length-1;n>=0;n--)this.handles[n].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&K.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let n=this.handles[t];this.prevLayers||(this.prevLayers=[]);let i=n.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(i):this.prevLayers[t]=i,n.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==jM.On?e.castShadow=!0:e.castShadow=!1}},Sn=ZM;re([se()],Sn.prototype,"receiveShadows",2),re([se()],Sn.prototype,"shadowCastingMode",2),re([se()],Sn.prototype,"lightmapIndex",2),re([se(rt)],Sn.prototype,"lightmapScaleOffset",2),re([se()],Sn.prototype,"enableInstancing",2),re([se()],Sn.prototype,"renderOrder",2),re([se()],Sn.prototype,"allowOcclusionWhenDynamic",2);var mh=class extends Sn{},zd=class extends mh{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},jM=(i=>(i[i.Off=0]="Off",i[i.On=1]="On",i[i.TwoSided=2]="TwoSided",i[i.ShadowsOnly=3]="ShadowsOnly",i))(jM||{}),XM="NEEDLE_NEED_UPDATE_INSTANCE",Qt=class{static markDirty(e,t=!0){if(!!e&&(K.isUsingInstancing(e)&&(e[XM]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let n of e.children)Qt.markDirty(n,!0)}},qM=class{objs=[];setup(e,t,n,i,s=0){let r=this.tryCreateOrAddInstance(e,t,i);if(r)return n===null&&(n=[]),n.push(r),n;if(s<=0&&e.type!=="Mesh"){let a=s+1;for(let l of e.children)n=this.setup(l,t,n,i,a)}return n}tryCreateOrAddInstance(e,t,n){if(e.type==="Mesh"){let i=n.foundMeshes;if(n.foundMeshes+=1,!n.rend.enableInstancing||i>=n.rend.enableInstancing.length||!n.rend.enableInstancing[i])return null;let s=e,r=s.geometry,a=s.material;for(let c of this.objs)if(!c.isFull()&&c.geo===r&&c.material===a)return c.addInstance(s);let l=new Ay(e.name,r,a,200,t);return this.objs.push(l),l.addInstance(s)}return null}},l5=new qM,YM=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,n){this.instanceIndex=e,this.object=t,this.instancer=n,K.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},JM=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,n,i,s){this.name=e,this.geo=t,this.material=n,this.context=s,this.maxCount=i,o5&&(n=new Jt({color:this.randomColor()})),this.inst=new pd(t,n,i),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new q(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new YM(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let n=this.handles.indexOf(e);if(n<0)return;e.instanceIndex=n}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,JM.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let n=this.handles[this.currentCount-1];n&&(n.instanceIndex=e.instanceIndex,n.updateInstanceMatrix(),this.handles[e.instanceIndex]=n,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},Ay=JM;Se(Ay,"nullMatrix",new it);var $m=be("debugphysics"),c5=be("debugcollisions"),Py=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},Km=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},QM=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var Zn=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new _e),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Fi);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};Se(Zn,"AllLayers",4294967295);var $M=class{distance;point;object;constructor(e,t,n){this.object=e,this.distance=t,this.point=n}},Iy=class{raycaster=new Ho;defaultRaycastOptions=new Zn;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Fi;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new gr(e,t),i=this.sphereMask;i.enableAll(),i.disable(2);for(let s of this.context.scene.children){let r=this.onSphereOverlap(s,n,i);r&&this.sphereResults.push(r)}return this.sphereResults.sort((s,r)=>s.distance-r.distance)}tempBoundingBox=new On;onSphereOverlap(e,t,n){if(e.type==="Mesh"){if(!e.layers.test(n))return null;let i=e,s=i.geometry;if(s.boundingBox||s.computeBoundingBox(),!s.boundingBox)return null;i.matrixWorldNeedsUpdate&&i.updateMatrixWorld();let r=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(i.matrixWorld);if(t.intersectsBox(r)){let l=ot(e).distanceTo(t.center);return new $M(e,l,t.center.clone())}}else if(e.children)for(let i of e.children){let s=this.onSphereOverlap(i,t,n);if(s)return s}return null}raycastFromRay(e,t=null){let n=t??this.defaultRaycastOptions;return n.ray=e,this.raycast(n)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold?n.params.Line={threshold:e.lineThreshold}:n.params.Line={threshold:0},e.ray)n.ray.copy(e.ray);else{let a=this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];n.setFromCamera(t,a)}let i=e.targets;i||(i=this.targetBuffer,i[0]=this.context.scene);let s=e.results;s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Fi?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),s.length=0,n.intersectObjects(i,e.recursive,s);let r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),s}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new Ry;objects=[];tempPosition=new O;tempQuaternion=new Oe;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),$m){let t={};t.onInit=(n,i,s)=>{i.layers.set(-1)},sO(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let n=0;n<this.objects.length;n++){let i=this.objects[n];if(i.obj===e){i._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,n=!0){this.world.removeBody(t);for(let i=0;i<this.objects.length;i++){let s=this.objects[i];if(s.obj===e){s._hasRigidbody=!1,n&&this.objects.splice(i,1);break}}}removeShape(e,t){for(let n of this.objects)if(n.obj===e){n.body&&(n.body.removeShape(t),n.body.updateMassProperties());return}}createBody(e,t){let n=this.internalCreateBody(e,null);t.mass&&(n.mass=t.mass),t.kinematic?n.type=qe.KINEMATIC:n.type=qe.DYNAMIC,t.drag&&(n.linearDamping=t.drag),t.angularDrag&&(n.angularDamping=t.angularDrag),t.sleepThreshold&&(n.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(n);let i=new Km(e,n);return i._hasRigidbody=!0,this.objects.push(i),$m&&console.log("created new body",e.name,n,n.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(i),n}addBoxCollider(e,t,n,i,s){let r=this.tempPosition;e.getWorldScale(r);let a=new H(.5*r.x*i.x,.5*r.y*i.y,.5*r.z*i.z),l=new hh(a);l.collisionResponse=!t,n=n.clone(),n.multiply(r);let c=this.addShape(e,l,n,s);if(c!==null){if(this.isAlreadyRegistered(c))return l;let h=new Km(e,c);this.objects.push(h)}return l}addSphereCollider(e,t,n,i){let s=this.tempPosition;e.getWorldScale(s);let r=Math.max(s.x,s.y,s.z),a=new Ty(n*r);t=t.clone(),t.multiply(s);let l=this.addShape(e,a,t,i);if(l!==null){if(this.isAlreadyRegistered(l))return a;let c=new Km(e,l);this.objects.push(c)}return a}addMeshCollider(e){$m&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,n,i){let s=null;if(i?(i.initialize(),console.assert(!!i.body,"rigidbody didn't initialize / produce a physics body",i),s=i.body):(s=this.internalCreateBody(e,null),s.type=qe.KINEMATIC,this.world.addBody(s)),s){n.x*=-1;let r=cn(e),a=ot(e);a.add(n);let l=new Oe(s.quaternion.x,s.quaternion.y,s.quaternion.z,s.quaternion.w);r.multiply(l.invert());let c=s.position,h=new H(a.x-c.x,a.y-c.y,a.z-c.z),u=new jt(r.x,r.y,r.z,r.w);s.addShape(t,h,u),s.updateMassProperties()}return s}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,$m&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new O;tempQuat=new Oe;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],n=t.body;if(!n||!n.world)continue;n.sleepTick(this.context.time.time),$m&&(!t._didSleepLastStep&&n.sleepState===qe.SLEEPING?console.log("BODY SLEEPING",n):t._didSleepLastStep&&n.sleepState!==qe.SLEEPING&&console.log("BODY WOKE UP",n)),t._didSleepLastStep=n.sleepState===qe.SLEEPING;let i=t.obj;if(n.type===qe.KINEMATIC){let s=ot(i,this.temp);n.position.set(s.x,s.y,s.z);let r=cn(i,this.tempQuat);n.quaternion.set(r.x,r.y,r.z,r.w);continue}if(t.parent&&i.parent===t.parent){JL(i,n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w);let s=n.position;Dd(i,s.x,s.y,s.z),n.velocity.length()>n.sleepSpeedLimit&&Qt.markDirty(i)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let n=new qe;n._owner=e,n._name=e.name,e.getWorldPosition(this.tempPosition);let i=this.tempPosition;n.position=new H(i.x,i.y,i.z);let s=this.tempQuaternion;return e.getWorldQuaternion(s),n.quaternion=new jt(s.x,s.y,s.z,s.w),n.type=qe.KINEMATIC,t&&(n.addShape(t),n.updateMassProperties()),n}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=n=>this.raiseCollisionEvents(e.obj,n);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let n=new QM(t.contact,t.type),i=0,s=this.objects;function r(){if(!(i>0))for(let a=0;a<s.length;a++){if(i==2)return;let l=s[a];l.body==t.body?(n.obj=l.obj,++i):l.body==t.target&&(n.target=l.obj,++i)}}c5&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let a=0;a<e.userData?.components?.length;a++){let l=e.userData.components[a];l.onCollision&&(r(),l.onCollision(n))}}};var Ly=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new Rd;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};var TO=Lu(bO(),1);function xO(o=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(o)===!0}var ys=class extends le{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?ys.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let s=be(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=ys.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return xO(e)}};var Zr=new Int32Array(2),Uy=new Float32Array(Zr.buffer),Hy=new Float64Array(Zr.buffer),Gd=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var _i=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?_i.ZERO:new _i(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};_i.ZERO=new _i(0,0);var eg;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(eg||(eg={}));var Jr=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Jr(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new _i(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new _i(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Zr[0]=this.readInt32(e),Uy[0]}readFloat64(e){return Zr[Gd?0:1]=this.readInt32(e),Zr[Gd?1:0]=this.readInt32(e+4),Hy[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){Uy[0]=t,this.writeInt32(e,Zr[0])}writeFloat64(e,t){Hy[0]=t,this.writeInt32(e,Zr[Gd?0:1]),this.writeInt32(e+4,Zr[Gd?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e),i="",s=0;if(e+=4,t===eg.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;s<n;){let r,a=this.readUint8(e+s++);if(a<192)r=a;else{let l=this.readUint8(e+s++);if(a<224)r=(a&31)<<6|l&63;else{let c=this.readUint8(e+s++);if(a<240)r=(a&15)<<12|(l&63)<<6|c&63;else{let h=this.readUint8(e+s++);r=(a&7)<<18|(l&63)<<12|(c&63)<<6|h&63}}}r<65536?i+=String.fromCharCode(r):(r-=65536,i+=String.fromCharCode((r>>10)+55296,(r&(1<<10)-1)+56320))}return i}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return _i.create(e,t)}createScalarList(e,t){let n=[];for(let i=0;i<t;++i)e(i)!==null&&n.push(e(i));return n}createObjList(e,t){let n=[];for(let i=0;i<t;++i){let s=e(i);s!==null&&n.push(s.unpack())}return n}};var _s=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=Jr.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){let i=this.bb.capacity();this.bb=_s.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let n=t<<1,i=Jr.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let i=2;this.addInt16(e-this.object_start);let s=(n+i)*2;this.addInt16(s);let r=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let l=this.bb.capacity()-this.vtables[t];if(s==this.bb.readInt16(l)){for(let c=2;c<s;c+=2)if(this.bb.readInt16(a+c)!=this.bb.readInt16(l+c))continue e;r=this.vtables[t];break}}return r?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,r-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let i=n?4:0;if(t){let s=t;if(this.prep(this.minalign,4+4+i),s.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let r=4-1;r>=0;r--)this.writeInt8(s.charCodeAt(r))}this.prep(this.minalign,4+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,i=n-this.bb.readInt32(n);if(!(this.bb.readInt16(i+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let i,s=e.charCodeAt(n++);if(s<55296||s>=56320)i=s;else{let r=e.charCodeAt(n++);i=(s<<10)+r+(65536-(55296<<10)-56320)}i<128?t.push(i):(i<2048?t.push(i>>6&31|192):(i<65536?t.push(i>>12&15|224):t.push(i>>18&7|240,i>>12&63|128),t.push(i>>6&63|128)),t.push(i&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,i=this.space,s=this.bb.bytes();n<t.length;n++)s[i++]=t[n];return this.endVector()}createLong(e,t){return _i.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let i=e[n];if(i!==null)t.push(this.createObjectOffset(i));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var wO={};function jd(o,e){wO[o]=e}function EO(o){let e=o.getBufferIdentifier(),t=wO[e];return t(o)}function SO(o){return typeof o.guid=="function"?o.guid():null}var nT=Lu(tT(),1);var Vy=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new nT.default(e);t.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),t.on("open",n=>{this._host=new sT(t)})}trySetupClient(e){this._client=new nT.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}},iT=class{_peer;constructor(e){this._peer=e}};var sT=class extends iT{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(n=>n.metadata?.id).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let n=this._peer.connections[t];if(!!n)if(Array.isArray(n))for(let i of n)!i||i.send(e);else console.warn(n)}}}};var rT="wss://needle-tiny-starter.glitch.me/socket",bs=!!be("debugnet"),Gy=!!(bs||be("debugowner"));var vl=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Gy&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0,i=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):i()},100)};i()})}requestOwnership(){return Gy&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Gy&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Gy&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var Wy=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Vy),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return bs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),bs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,n=2){if(t===null&&(t={}),n===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){bs&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let n in this._defaultMessagesBuffer){let i=this._defaultMessagesBuffer[n];if(e<=1){this.sendWithWebsocket(i.key,i.value,3);break}let s=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&bs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}connect(){if(this.connected)return;bs&&console.log("connecting");let t=K.findObjectOfType(ys,this.context,!1)?.getWebsocketUrl();t&&(rT=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+rT);let e=new TO.WebsocketBuilder(rT).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,n)=>{console.error(t,n)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}let i=JSON.parse(n);if(Array.isArray(i))for(let s of i)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(i);return}catch{bs&&n==="pong"&&console.log("<<",n)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var n=new Uint8Array(t);let i=new Jr(n),s=i.getBufferIdentifier(),r=this._listenersBinary[s],a=EO(i),l=SO(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;let c=a??i;for(let h of r)h(c)}handleIncomingStringMessage(e){if(bs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.log("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(bs&&console.log(e),e){this._isInRoom=!0;let r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),bs&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let r=e.data;this._currentInRoom.push(r.userId),bs&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(console.log(r.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),bs&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let i of t)i(e.data);let n=e.data;n&&(this._state[n.guid]=n)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=1){if(!this._ws){let s=this._waitingForSocket[n]||[];s.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=s;return}let i=JSON.stringify(this.toMessage(e,t));bs&&console.log(">>",e),this._ws.send(i)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let n of t)n();t.length=0}}};import{OrbitControls as _5}from"three/examples/jsm/controls/OrbitControls";var Jo=class extends le{constraintActive=!0;locked=!1;sources=[]};re([se(Fe)],Jo.prototype,"sources",2);var xs=class extends le{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;awake(){this._lookTargetPosition=new O}onEnable(){this._enableTime=this.context.time.time;let t=K.getComponent(this.gameObject,Bt)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new _5(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan)}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}start(){if(this._controls){let e=K.getComponent(this.gameObject,Bt);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new O(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Zn;e.screenPoint=new _e(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&K.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=ot(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};re([se(Jo)],xs.prototype,"lookAtConstraint",2);var gn=class extends q{alpha=1;constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"&&(this.alpha=e.alpha),typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let n=e;return n.alpha&&(this.alpha=gt.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};var CO=be("debugcam"),Bt=class extends le{get aspect(){return this._cam instanceof Wt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof Wt&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera()}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){CO&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Wt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new Ka(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.context.isInXR&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this.backgroundColor){let e=this.backgroundColor.alpha;this.context.isInXR&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this.backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new oT(this)),this._skybox.enable()}};re([se()],Bt.prototype,"fieldOfView",1),re([se()],Bt.prototype,"nearClipPlane",1),re([se()],Bt.prototype,"farClipPlane",1),re([se()],Bt.prototype,"clearFlags",1),re([se()],Bt.prototype,"orthographic",2),re([se()],Bt.prototype,"orthographicSize",2),re([se()],Bt.prototype,"ARBackgroundAlpha",2),re([se(gn)],Bt.prototype,"backgroundColor",1);var oT=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(CO&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Ct,this._skybox.mapping=Ws,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function RO(o){let e="created/implictly",t=new Fe;o.add(t);let n=K.addNewComponent(t,Bt,!1);n.sourceId=e;let i=K.addNewComponent(t,xs,!1);return i.sourceId=e,n}import{EffectComposer as GY}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as WY}from"three/examples/jsm/postprocessing/RenderPass";var Xd=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,n,i){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=n,this._speed=i}};function AO(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Hm.generateUUID(),index:-1,clip:new br(o,1,[])}}var aT=class{_types={};add(e,t){let n=this._types[e];n===void 0?this._types[e]=t:n!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},pe=new aT;var Qr=be("gizmos"),Nn=be("debugextension");var Xy=be("debugresolvedependencies"),b5=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function qd(o,e){Xy&&console.log(o,e);let t=[];cT(b5,o,e,t);let n=await Promise.all(t);return typeof e=="string"&&n.length===1?n[0]:n}function cT(o,e,t,n){if(typeof t=="object"&&t!==void 0&&t!==null)for(let i of Object.keys(t)){let s=t[i];if(typeof s=="string"){let r=PO(e,s);if(r!==null)typeof r.then=="function"?n.push(r.then(a=>t[i]=a)):t[i]=r;else for(let a of o){let l=hT(a.prefix,s);if(l>=0){Xy&&console.log(a,l,a.dependencyName),n.push(e?.getDependency(a.dependencyName,l).then(c=>(t[i]=c,c)));break}}}else if(Array.isArray(s))for(let r=0;r<s.length;r++){let a=s[r],l=PO(e,a);if(l!==null){typeof l.then=="function"?n.push(l.then(c=>s[r]=c)):s[r]=l;continue}for(let c of o){let h=hT(c.prefix,a);if(h>=0){Xy&&console.log(c,h,c.dependencyName),n.push(e?.getDependency(c.dependencyName,h).then(u=>s[r]=u));break}}typeof a=="object"&&cT(o,e,a,n)}else typeof s=="object"&&cT(o,e,s,n)}else typeof t=="string"&&x5(o,e,t,n)}var lT="extensions/";function PO(o,e){if(o&&o.plugins&&typeof e=="string"&&e.startsWith(lT)){let t=e.substring(lT.length),n=t.indexOf("/");n>=0&&(t=t.substring(0,n));let i=o.plugins[t];if(Nn&&console.log(t,i),typeof i?.resolve=="function"){let s=e.substring(lT.length+t.length+1);return i.resolve(o,s)}}return null}function x5(o,e,t,n){for(let i of o){let s=hT(i.prefix,t);if(s>=0)return Xy&&console.log(i,s,i.dependencyName),n.push(e?.getDependency(i.dependencyName,s).then(r=>r)),!0}return!1}function hT(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),n=Number.parseInt(t);if(n>=0)return n}return-1}var uT="NEEDLE_persistent_assets";function IO(o){return o?.___persistentAsset===!0}var qy=class{get name(){return uT}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[uT];if(!t)return;Nn&&console.log(t);let n=new Array;for(let i of t?.assets){let s=qd(this.parser,i);s&&n.push(s)}await Promise.all(n)}resolve(e,t){let n=Number.parseInt(t);if(n>=0){Nn&&console.log(t);let i=e.json.extensions[uT];if(i){let s=i?.assets[n];if(s&&typeof s=="object"){s.___persistentAsset=!0;let r=s.__type;if(r){let a=pe.get(r)}}return s}}return null}};var vh=be("debugserializer"),dT=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}vh&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){vh&&console.log("invalid type");return}let n=e.name??e.constructor?.name;if(!n){vh&&console.log("invalid name",n);return}let i=this.getSerializer(n);if(i!==void 0)return vh&&console.log("FOUND "+n,e.name,e.constructor.name,i,this.typeMap),i;let s=Object.getPrototypeOf(e);if(!(s.prototype||s.constructor)){vh&&console.warn("No prototype for "+n,e,e.name,e.prototype,e.constructor.name);return}let a=s.prototype??s.constructor;if(a!==e){let l=this.getSerializerForConstructor(a,++t);if(l){vh&&console.log("FOUND "+a.constructor.name,a.name,a,l);let c=a.name??a.constructor.name;c==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,l):this.register(c,l)}return l}}},Zy=new dT,Qo=class{constructor(e){if(Array.isArray(e))for(let t of e)Zy.register(t.name,this);else Zy.register(e.name,this)}},Yd=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function pT(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let n={};for(let i in t){let s=o[i];if(s!=null&&typeof s=="object"){let r=Zy.getSerializerForConstructor(s);if(r){n[i]=r.onSerialize(s,e);continue}}n[i]=s}return n.name=o.constructor.name,typeof o.guid=="string"&&(n.guid=o.guid),n}var Yy=[];function LO(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return LO(t,e)}function tg(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let s=o.onBeforeDeserialize(e,t);if(typeof s=="boolean")return s}let n=LO(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),n)for(let s in n){let r=n[s],a=e[s];if(t.path=s,r===null)o[s]=a;else{let l=function(c){let u=c.type;return u?fT(a,u,t,void 0,o[s]):fT(a,c,t,void 0,o[s])};var i=l;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(s,a,t)===!0)continue;if(Array.isArray(r))for(let c=0;c<r.length;c++){let h=r[c],u=l(h);if(u!==void 0||c===r.length-1){o[s]=u;break}}else o[s]=l(r);Yy.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(s,a,t)}}w5(o,e)}return o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}function w5(o,e){for(let n of Object.keys(e)){let i=e[n];if(typeof i=="object"&&i!==null&&i!==void 0){let s=o[n];if(!s){vh&&console.log(n,"is undefined on",o);continue}for(let r of Object.keys(i))s[r]===void 0&&t(i[r])&&!t(s)&&(s[r]=i[r])}}function t(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}}function fT(o,e,t,n,i){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,i),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(!s&&i instanceof r)return i;if(i&&typeof i=="object"&&IO(i)){if(i.__concreteInstance)return i.__concreteInstance;let h=i;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&tg(h,o,t),i&&r!==void 0)try{let u=new r;Nn&&console.log("Create concrete instance for persistent asset",i,"instance:",u),ng(u,i),i.__concreteInstance=u,i=u}catch(u){console.error("Error creating instance or creating values on instance",u,i,r)}return i}if(n||(n={serializer:Zy.getSerializerForConstructor(r)}),Array.isArray(o)){let h=[];for(let u=0;u<o.length;u++){let d=o[u],f=fT(d,e,t,n,d);h.push(f)}return h}let a=n.serializer;if(a)return a.onDeserialize(o,t);let l;o&&(o.isMaterial||o.isTexture||o.isObject3D)?l=o:l=new r(...E5(o));let c=l;return c.$serializedTypes&&tg(c,o,t),l}function E5(o){if(Yy.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))Yy.push(o[e]);return Yy}function ng(o,e){if(e==null||o==null)return;let t=!1;for(let n of Object.keys(e)){let i=S5(o,n);t&&i===void 0||(!i||i.writable===!0||i?.set!==void 0)&&(o[n]=e[n])}}function S5(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var yl=be("debuganimatorcontroller"),mT=be("debugrootmotion"),Cr=class{Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let r=this.model.layers[t].stateMachine;for(let a of r.states)if(a.name===e||a.hash===e){yl&&console.log("transition to ",a),this.transitionTo(a,i,n);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??!1}SetFloat(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetInteger(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetTrigger(e){yl&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e)return n;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new Uo(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=zm(this.model,(n,i,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||s?.constructor?.name==="AnimationAction"||s.tracks!==void 0));return console.assert(e!==this.model),new Cr(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,yl&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],n=t.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{let i=n.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(yl&&console.debug("REMOVE",t.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,n=t.motion.action,i=0;for(let r of t.transitions){if(++i,!r.hasExitTime&&r.conditions.length<=0)continue;let a=!0;for(let l of r.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(!!a){yl&&a&&console.log("All conditions are met",r.conditions,n);for(let l of r.conditions){let c=this.model.parameters.find(h=>h.name===l.parameter);c?.type===9&&(c.value=!1)}if(n){let l=t.motion.clip.duration,c=l<=0?1:n.time/l;if(!r.hasExitTime||c>=r.exitTime&&n.time>=n.getClip().duration){n.clampWhenFinished=!0,yl&&(console.log("transition to "+r.destinationState,r),console.log(n.time,r.exitTime)),this.transitionTo(r.destinationState,r.duration,r.offset);return}}else{this.transitionTo(r.destinationState,r.duration,r.offset);return}break}}let s=!1;if(t.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&t&&!e&&n&&this.animator&&t.behaviours){let r=n?.getClip().duration,a=n.time/r,l=new Xd(this._activeState,a,r,this._speed);for(let c of t.behaviours)c.instance&&c.instance.onStateUpdate?.call(c.instance,this.animator,l,0)}}transitionTo(e,t,n){if(!this.animator)return;let i=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[i].stateMachine.defaultState),e=this.model.layers[i].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let s=this._activeState===e;if(s){let c=e.motion;!c.action_loopback&&c.clip&&(this._mixer.uncacheAction(c.clip,this.animator.gameObject),c.action_loopback=this.createAction(c.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let c=this._activeState?.motion.clip.duration,h=this._activeState.motion.action.time/c,u=new Xd(this._activeState,h,c,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateExit?.call(d.instance,this.animator,u,i)}let r=this._activeState?.motion.action;r&&r.fadeOut(t),s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);let a=this._activeState;this._activeState=e;let l=e.motion?.action;if(l){n=Math.max(0,Math.min(1,n)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,l.enabled=!0;let c=e.motion.clip.duration;if(l.time=n*c,l.clampWhenFinished=!0,l.setLoop(Pd,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let h=new Xd(e,n,c,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,h,i)}}else console.warn("No action",e.motion,this);yl&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new gT(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let n=t.stateMachine;for(let i=0;i<n.states.length;i++){let s=n.states[i];if(s.motion||(s.motion=AO(s.name)),this.animator&&s.motion.clips){let r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);s.motion.clip=r?.clip}if(!s.motion.clip){let r=new br;s.motion.clip=r}if(s.motion?.clip){let r=s.motion.clip,a=this.createAction(r);s.motion.action=a}if(s.behaviours&&Array.isArray(s.behaviours))for(let r of s.behaviours){if(!r?.typeName)continue;let a=pe.get(r.typeName),l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,ng(l,r.properties),r.instance=l),yl&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let n=0;n<t.states.length;n++){let i=t.states[n];i?.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}rootMotionHandler},Jy=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let n=e,i=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;let r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}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}},Mn=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new O;rotationChange=new Oe;constructor(e,t,n,i,s){if(this.context=e,this.root=t,this.clip=n,Mn.firstKeyframeRotation[n.uuid]||(Mn.firstKeyframeRotation[n.uuid]=new Oe),s){let r=s.values;Mn.firstKeyframeRotation[n.uuid].set(r[0],r[1],r[2],r[3])}Mn.spaceRotation[n.uuid]||(Mn.spaceRotation[n.uuid]=new Oe),Mn.effectiveSpaceRotation[n.uuid]||(Mn.effectiveSpaceRotation[n.uuid]=new Oe),Mn.clipOffsetRotation[n.uuid]=new Oe,s&&Mn.clipOffsetRotation[n.uuid].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(n,i),this.handleRotation(n,s)}onStart(e){if(e.getClip()!==this.clip)return;let t=Mn.lastObjRotation[this.root.uuid];Mn.spaceRotation[this.clip.uuid].copy(t);{let n=new Lt().setFromQuaternion(t);console.log("START",this.clip.name,gt.toDegrees(n.y))}}getClipRotationOffset(){return Mn.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let n=this.root;mT&&n.add(new xr),Mn.lastObjPosition[n.uuid]||(Mn.lastObjPosition[n.uuid]=new O);let i=new O,s=new O,r=0;this.positionWrapper=new Jy(t,(a,l)=>{let c=this.action.getEffectiveWeight();if(mT&&n.position.length()>8&&n.position.set(0,n.position.y,0),a>r){i.set(l[0],l[1],l[2]),i.sub(s),i.multiplyScalar(c),i.applyQuaternion(this.getClipRotationOffset());let h=this.clip.uuid;i.applyQuaternion(Mn.spaceRotation[h]),this.positionChange.copy(i)}return s.fromArray(l),r=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(mT){let a=t.values,l=new Lt().setFromQuaternion(new Oe(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",gt.toDegrees(l.y));let c=t.values.length-4,h=new Oe().set(a[c],a[c+1],a[c+2],a[c+3]),u=new Lt().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",gt.toDegrees(u.y))}let n=this.root;Mn.lastObjRotation[n.uuid]||(Mn.lastObjRotation[n.uuid]=new Oe);let i=0,s=new Oe,r=new Oe;this.rotationWrapper=new Jy(t,(a,l)=>(a>i&&(r.set(l[0],l[1],l[2],l[3]),s.invert(),r.multiply(s),this.rotationChange.copy(r)),s.fromArray(l),i=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Mn.identityQuaternion,1-e)}},Tr=Mn;Se(Tr,"lastObjPosition",{}),Se(Tr,"lastObjRotation",{}),Se(Tr,"firstKeyframeRotation",{}),Se(Tr,"spaceRotation",{}),Se(Tr,"effectiveSpaceRotation",{}),Se(Tr,"clipOffsetRotation",{}),Se(Tr,"identityQuaternion",new Oe);var gT=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,n){this.root=t;let i="";t&&"name"in t&&(i=t.name);let s=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),a=new Tr(this.controller.context,t,n,s,r);this.handler.push(a);let l=e.clipAction(n);return a.action=l,l}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new O;summedRotation=new Oe;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Tr.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let n=e.tracks;for(let i of n)if(i.name.endsWith(t))return i;return null}};var M5=be("debuganimator"),ws=class extends le{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Cr?this._animatorController=e:this._animatorController=new Cr(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){this.runtimeAnimatorController?.Play(e,t,n,i)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=gt.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=gt.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}M5&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};re([se()],ws.prototype,"applyRootMotion",2),re([se()],ws.prototype,"hasRootMotion",2),re([se()],ws.prototype,"keepAnimatorControllerStateOnDisable",2),re([se()],ws.prototype,"runtimeAnimatorController",1);var Rr=class extends le{playAutomatically=!0;randomStartTime=!0;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&Qt.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let n=e;if(typeof e=="number"){if(e>=this.animations.length)return;n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(s=>s.name===e));if(!n){console.error("Could not find clip",e);return}for(let s of this.actions)if(s.getClip()===n)return this.internalOnPlay(s,t);let i=this.mixer.clipAction(n);return this.actions.push(i),this.internalOnPlay(i,t)}internalOnPlay(e,t){var n=this.currentAction;if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let r=this.tryFindHandle(e);if(r)return r.getPromise()}let i=t?.exclusive??!0;t?.fadeDuration?(i&&n?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):i&&n?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Z0:Pd),e.play();let s=new vT(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Uo(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};re([se()],Rr.prototype,"playAutomatically",2),re([se()],Rr.prototype,"randomStartTime",2);var vT=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,n,i){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=i,this._options=n}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as BF}from"three/examples/jsm/loaders/GLTFLoader.js";var Zd=class extends le{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new O}update(){if(!this.from||!this.to)return;let e=ot(this.from).clone(),t=ot(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),kt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ot(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};var $r=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};re([se()],$r.prototype,"time",2),re([se()],$r.prototype,"value",2),re([se()],$r.prototype,"inTangent",2),re([se()],$r.prototype,"inWeight",2),re([se()],$r.prototype,"outTangent",2),re([se()],$r.prototype,"outWeight",2),re([se()],$r.prototype,"weightedMode",2);var yh=class{keys;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;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return gt.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};re([se($r)],yh.prototype,"keys",2);import{PositionalAudioHelper as T5}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Qy=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var es=be("debugaudio");var Jn=class extends le{static get userInteractionRegistered(){return Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction()),Jn._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!Jn._userInteractionRegistered){Jn._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(es&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Jn._userInteractionRegistered){let e=K.getComponent(this.context.mainCamera,Ar)??K.findObjectOfType(Ar,this.context);e?.listener&&(this.sound=new Lm(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new rl,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Jn._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Jn._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Jn._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){es&&console.log("audio buffer loaded"),Jn.registerWaitForAllowAudio(()=>{es&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),es&&console.log(this.name,this.shouldPlay,Jn.userInteractionRegistered,this),this.shouldPlay&&Jn._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(es&&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:break}this.spatialBlend>0?es&&!this.helper&&(this.helper=new T5(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(es&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new rl),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){es&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,es&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,es&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,es&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,es&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},$t=Jn;Se($t,"_didCallBeginWaitForUserInteraction",!1),Se($t,"callbacks",[]),Se($t,"_userInteractionRegistered",!1),re([se()],$t.prototype,"clip",2),re([se()],$t.prototype,"playOnAwake",2),re([se()],$t.prototype,"loop",1),re([se()],$t.prototype,"spatialBlend",1),re([se()],$t.prototype,"minDistance",1),re([se()],$t.prototype,"maxDistance",1),re([se()],$t.prototype,"volume",1),re([se()],$t.prototype,"rollOffMode",2);var Ar=class extends le{get listener(){return this._listener==null&&(this._listener=new Kc),this._listener}_listener=null;awake(){$t.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=K.getComponentInParent(this.gameObject,Bt);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as A5}from"three/examples/jsm/loaders/GLTFLoader";var zO=Lu(HO(),1),$y=class{success;filename;hash;size;url;constructor(e,t,n,i){this.success=e,this.filename=t,this.hash=n,this.size=i}};async function VO(o,e){let t=await o.arrayBuffer(),n=GO(t),i=o.name.split(".").pop(),s=n+"."+i,r=o.name.split(".").shift();console.assert(r!==void 0);let a={alias:r,filename:s},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",n),new $y(!0,s,n,o.size);console.log("begin uploading file",r,o.size);let h=new FormData;h.append("file",o);let u={};u.filesize=o.size,r&&(u.alias=r);let f=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===n,"hash sum did not match","received:",f.hash_sum,"expected:",n),f.success&&console.log("successfully uploaded",n,f.id);let g=new $y(f.success,s,n,o.size);return g.url=e,g}function GO(o){return(0,zO.default)(new Uint8Array(o))}async function Ky(o,e,t,n,i=!1){try{let s=await fetch(n+"/download/file",{method:"POST",body:o});if(s.status!==200)return console.error("download failed",s),null;let r=await s.blob(),a=await r.arrayBuffer();i||console.assert(r.size===t,"size mismatch","expected:",t,"got:",r.size);let l=GO(a);return i||console.assert(l===e,"hash mismatch, downloaded file is invalid"),r.arrayBuffer()}catch(s){console.error(s)}return null}async function WO(o,e){let t=await fetch(o),n=t.body?.getReader(),i=t.headers.get("Content-Length"),s=i?parseInt(i):0;if(!n)return null;let r=0,a=[];for(;;){let{done:h,value:u}=await n.read();if(u&&(a.push(u),r+=u.length,e.call(null,new ProgressEvent("progress",{loaded:r,total:s}))),h)break}let l=new Uint8Array(r),c=0;for(let h of a)l.set(h,c),c+=h.length;return l}var ig=be("debugavatar"),_h=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(s=>s.layers.set(2))}assignRandomColors(){$o.assignRandomPlayerColors(this)}},$o=class{avatarRegistryUrl=null;avatarModelCache=new Map;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let s=new hn;n=K.instantiate(cl(t,e.scene),s)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.assignRandomColors(),i.isValid?(ig&&console.log("[Custom Avatar] valid config",t,ig?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,ig?i:""),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(ig&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),s=null;if(i.ok){let a=await i.blob();a&&(s=await a.arrayBuffer())}return!s&&(s=await Ky(t,t,0,"no url here go away",!0),!s)?null:(await Jd(e,s,null,0))?.scene??null}let n=new A5;return ph(n,e),new Promise((i,s)=>{let r=this.avatarRegistryUrl+"/"+t;n.load(r,async a=>{await e_(e,r,a),i(a.scene)},a=>{ig&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,"head"),s=this.findAvatarPart(n,"left"),r=this.findAvatarPart(n,"right");if(!i){i=t;let l=new O;new On().setFromObject(i).getSize(l);let c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&i.scale.multiplyScalar(1/c*.3)}return new _h(t,i,s,r)}findAvatarPart(e,t){for(let n of e.children)if(n.name.toLowerCase().indexOf(t)>-1)return n;return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}static assignRandomPlayerColors(e){let t=new Map;function n(i){if(i.type==="Mesh"){let s=i,r=s.material;if(r&&r.name){if(t.has(r.uuid)){let a=t.get(r.uuid);a&&(s.material=a);return}if(r.name.endsWith("_playercolor")||r.name.endsWith("_player_color2")){let a=r.uuid;s.material=r.clone(),s.material.color=new q(Math.random(),Math.random(),Math.random()),t.set(a,s.material)}}}}e.head&&e.head.traverse(n),e.leftHand&&e.leftHand.traverse(n),e.rigthHand&&e.rigthHand.traverse(n)}};var Ko=class extends le{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Qr)return;this._axes||(this._axes=new xr(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};re([se()],Ko.prototype,"length",2),re([se()],Ko.prototype,"depthTest",2),re([se()],Ko.prototype,"isGizmo",2);var Qd=class extends le{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=ot(this.to).clone(),t=ot(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let s=t.clone();s.add(e),s.multiplyScalar(.5);let r=ot(this.hint).clone();r.sub(s);let a=new O;a.crossVectors(r,i),a.crossVectors(i,a),a.normalize();let l=n*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),u=a.clone();u.multiplyScalar(h),u.add(s),kt(this.gameObject,u);let d=s.clone();d.sub(a),this.gameObject.lookAt(d)}};var P5=new si(1,1,1);function t_(o=null){let e=new q(o??14540253),t=new yd(P5);return new Qi(t,new Fn({color:e}))}var L5=be("gizmos"),n_=class extends le{box=null;testBox=new On;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new On),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=ot(e,n_._position),n=QL(e,n_._size);this.testBox.setFromCenterAndSize(t,n)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new On),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new O(0,0,0),new O(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!L5&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=t_(e),this.gameObject.add(this._helper)}}},ts=n_;Se(ts,"_position",new O),Se(ts,"_size",new O(.01,.01,.01));function $d(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?mi:ps,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?mi:ps,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let n of o.children)$d(n,e)}function Kd(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let n=Proxy.revocable(o[e],{set(r,a,l,c){let h=r[a],u=Reflect.set(r,a,l,c);return t(l,h),u}}),i=n.revoke,s=o[e];return n.revoke=()=>{o[e]=s,i()},o[e]=n.proxy,n}function XO(o,e,t=3){let n=o.__scheduledActions;n||(n=o.__scheduledActions={});let i=e.name;n[t]||(n[t]={});let s=n[t];if(s[i])return;function*a(){e?.call(o),s[i]=null}let l=o.startCoroutine(a(),t);s[i]=l}var ef=class extends le{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?qe.KINEMATIC:qe.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new O,this._smoothedVelocity=new O,this.lastWorldPosition=ot(this.gameObject).clone()}start(){this.setBodyFromGameObject()}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this.transformProxy=Kd(this.gameObject.matrix,"elements",()=>{this.context.physics.isUpdating||(this.dirty=!0)})}onDisable(){this.transformProxy?.revoke(),this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}earlyUpdate(){this.dirty&&this.setBodyFromGameObject()}onBeforeRender(){this.updateVelocity()}initialize(){if(this._body)return;let e=new Py;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new H(e.x,e.y,e.z),t?new H(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?ef.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):ef.tempPosition.set(0,0,0)}setVelocity(e,t,n){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=n/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,n){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=n/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let n=this.worldQuaternion;if(this.body.quaternion.set(n.x,n.y,n.z,n.w),e){ef.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(ef.copyVector3,this.context.time.deltaTime/.1);let i=this._smoothedVelocity;this.body.velocity.x=i.x,this.body.velocity.y=i.y,this.body.velocity.z=i.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=ot(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},Xt=ef;Se(Xt,"tempPosition",new O),Se(Xt,"copyVector3",new O),re([se()],Xt.prototype,"mass",2),re([se()],Xt.prototype,"isKinematic",1),re([se()],Xt.prototype,"drag",2),re([se()],Xt.prototype,"angularDrag",2),re([se()],Xt.prototype,"detectCollision",2),re([se()],Xt.prototype,"sleepThreshold",2);var Kr=class extends le{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xt))}onDisable(){this._shape}};re([se(Xt)],Kr.prototype,"attachedRigidbody",2),re([se()],Kr.prototype,"isTrigger",2);var _l=class extends Kr{radius=.5;center=new O(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};re([se()],_l.prototype,"radius",2),re([se(O)],_l.prototype,"center",2);var bl=class extends Kr{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};re([se(O)],bl.prototype,"size",2),re([se(O)],bl.prototype,"center",2);var tf=class{};var qs=class extends le{canGrab=!0;onPointerClick(e){}},Ys=class extends le{isUsed=!0;usedBy=null};var bh=class extends ts{},nf=class extends le{deleteBoxes=[];awake(){this.deleteBoxes=K.findObjectsOfType(bh,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(K.getComponentInParent(this.gameObject,Ys)||kd(this.gameObject,this.context.connection))}}};var xh=class extends le{visibleOn;onEnable(){this.apply()}apply(){this.test()||K.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:O5()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};re([se()],xh.prototype,"visibleOn",2);var i_;function O5(){if(i_===!0||i_===!1)return i_;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),i_=o,o}var Tn=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,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(e,t,n,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var sf=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Tn).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Tn).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Tn).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Zs=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new sf).__init(this.bb_pos+t,this.bb):null}dontSave(){let 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 xl=be("debugsync"),rf="STRS";jd(rf,Zs.getRootAsSyncedTransformModel);var eo=new _s;function bT(o,e,t=!0){eo.clear();let n=eo.createString(o);Zs.startSyncedTransformModel(eo),Zs.addGuid(eo,n),Zs.addFast(eo,t);let i=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;Zs.addTransform(eo,sf.createTransform(eo,i.x,i.y,i.z,s.x,s.y,s.z,r.x,r.y,r.z));let a=Zs.endSyncedTransformModel(eo);return eo.finish(a,rf),eo.asUint8Array()}var bi=class extends le{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){xl&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){xl&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new O,this._targetRotation=new Oe,this.lastWorldPos=new O,this.lastWorldRotation=new Oe,this.rb=K.getComponentInChildren(this.gameObject,Xt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new vl(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(rf,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&s2(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(rf,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Lt;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){xl&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){Qt.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&$L(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){xl&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let s=e.distanceTo(this.lastWorldPos),r=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(s>a||r>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(xl&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qt.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let r=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){let l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&Qt.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(xl&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new O(0,0,0))>1e3&&(xl&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){xl&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let s=bT(this.guid,this,!!i);this.context.connection.sendBinary(s)}}};var r_=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var l=document.createElement("div");l.style.display="none",document.body.appendChild(l);var c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("width",38),c.setAttribute("height",38),c.style.position="absolute",c.style.right="20px",c.style.top="20px",c.addEventListener("click",function(){u.end()}),l.appendChild(c);var h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),h.setAttribute("stroke","#fff"),h.setAttribute("stroke-width",2),c.appendChild(h),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:l}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function d(g){g.addEventListener("end",f),await e.xr.setSession(g),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=g}function f(){u.removeEventListener("end",f),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(d):u.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="AR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(l){l?i():r()}).catch(r),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}};var o_=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let l=null;async function c(u){u.addEventListener("end",h),await e.xr.setSession(u),n.textContent="EXIT VR",l=u}function h(){l.removeEventListener("end",h),n.textContent="ENTER VR",l=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(l===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(c)}else l.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="VR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?i():r(),o_.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),o_.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},of=o_;Se(of,"xrSessionIsGranted",!1);of.registerSessionGrantedListener();var qO=Lu(tT(),1);var af="noVoip",ns=be("debugvoip"),k5=be("voip");var xT=class{id;constructor(e){this.id=e}};var wT=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){ns&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await Vi.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ns&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ns&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ns&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ns&&console.log("call closed",e)}},ET=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,$t.userInteractionRegistered||ns&&console.log("Incoming call, waiting for user interaction before opening audio"),$t.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ns&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Kc;this.audio=new ol(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let s of i)if(s.label==="Speakerphone"){n.sinkId=s.deviceId;break}}}),ns&&console.log("call is setup, you should hear something now"),this.analyzer=new Om(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Vi=class extends le{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(be(af)){console.log("VOIP is disabled by url parameter: "+af);return}if(this.requireParam&&!k5){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new qO.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new wT(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];ns&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){ns&&console.log("Peer connection established and received id"),this.model=new xT(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ns&&console.log("CONNECTION",t),t.on("data",function(n){ns&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,s=this.currentIncomingCalls[n];if(s&&s.close(),ns&&console.log("received call"),await Vi.HasMicrophonePermissions()){let r=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(r)}else e.answer(null);this.currentIncomingCalls[n]=new ET(this,this.gameObject,e),e.on("stream",r=>{ns&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(r)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var lf=be("debugflags");var ST=class{Mask=17;Has(e){let t=this.Mask&e;return lf&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Cn.Apply()}Enable(e){this.Mask|=e,Cn.Apply()}Disable(e){this.Mask&=~e,Cn.Apply()}Toggle(e){this.Mask^=e,Cn.Apply()}EnableAll(){this.Mask=-1,Cn.Apply()}DisableAll(){this.Mask=0,Cn.Apply()}},Es=ST;Se(Es,"Global",new ST);var to=class extends le{static Apply(){for(let e of this.registry)e.UpdateVisible(Es.Global)}awake(){to.registry.push(this)}onEnable(){to.firstApply||(to.firstApply=!0,to.Apply())}onDestroy(){let e=to.registry.indexOf(this);e>=0&&to.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),lf&&console.log(n),to.buffer.Mask=n,e=to.buffer);let i=e;if(i?(lf&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(lf&&console.log("use global mask"),Es.Global.Has(this.visibleIn)),t!==void 0)if(t)lf&&console.trace("is visible",this.name,this.gameObject.uuid),K.setActive(this.gameObject,!0);else{if(lf&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Cn=to;Se(Cn,"registry",[]),Se(Cn,"firstApply"),Se(Cn,"buffer",new Es);import{XRControllerModelFactory as F5}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as B5}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as N5}from"three/examples/jsm/webxr/OculusHandPointerModel.js";var wl=be("debugavatar"),ea=class extends le{static onAvatarMarkerCreated(e){return ea._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ea._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ea.instances.push(this),wl&&console.log(this);for(let e of ea._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ea.instances.splice(ea.instances.indexOf(this),1);for(let e of ea._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):K.setActive(this.avatar,e))}},sn=ea;Se(sn,"instances",[]),Se(sn,"_onNewAvatarMarkerAdded",[]),Se(sn,"_onAvatarMarkerDestroyed",[]);var sg=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new O(1,1,1);handLeftScale=new O(1,1,1);handRightScale=new O(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new Fe;_handLeftTarget=new Fe;_handRightTarget=new Fe;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){this._canInterpolate=!0;let n=this.isLocalAvatar?this.head:this._headTarget;if(n.position.set(e.position.x,e.position.y,e.position.z),n.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.headScale),this.handLeft){let i=this.isLocalAvatar?this.handLeft:this._handLeftTarget;i.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),i.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),i.quaternion.multiply(sg.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handLeftScale)}if(this.handRight){let i=this.isLocalAvatar?this.handRight:this._handRightTarget;i.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),i.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),i.quaternion.multiply(sg.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handRightScale)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){wl&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&vn.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&K.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(wl&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&vn.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;K.setActive(i,!1),e=K.instantiate(i),K.setActive(e,!0)}wl&&console.log(e);let n=await sg.loader.getOrCreateNewAvatarInstance(this.context,e);if(wl&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=K.addNewComponent(this.root,sn),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&vn.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...K.getComponentsInChildren(this.root,Cn)),this.flags.length<=0&&this.head){let i=K.addNewComponent(this.head,Cn);i.visibleIn=20,this.flags.push(i),wl&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return wl&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return wl&&console.warn("build avatar failed"),!1}},Js=sg;Se(Js,"loader",new $o),Se(Js,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI));var vn=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??bt.Current?.time.time;return}}}};Se(vn,"Pois",[]),Se(vn,"LastChangeTime",0);var MT=class{guid;position=new O},ta=class extends le{set controlledTarget(e){this.target=e;let t=pe.get("MoveRandom");if(t&&this.target){let n=K.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new MT;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=K.getComponentInParent(this.gameObject,sn),this.avatar){let e=K.getComponentInParent(this.gameObject,sn);this._model=new vl(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&kt(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(vn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=vn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=ot(this._currentTargetObject);kt(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;let t=vn.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};var wh=class extends le{},Qn=class extends le{static CreateRaycastLine(){let e=new Ji(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Ni(.5,22,22),t=new Jt({color:this.raycastColor}),n=new _t(e,t);return n.visible=!1,n.layers.set(1),n}static Create(e,t,n,i){let s=n?K.addNewComponent(n,Qn,!1):new Qn;s.webXR=e,s.index=t,s.type=i;let r=e.context;return s.controller=r.renderer.xr.getController(t),s.controllerGrip=r.renderer.xr.getControllerGrip(t),s.controllerModel=this.Factory.createControllerModel(s.controller),s.controllerGrip.add(s.controllerModel),s.hand=r.renderer.xr.getHand(t),s.hand.add(new B5(s.hand)),s.hand.traverse(a=>a.layers.set(2)),s.handPointerModel=new N5(s.hand,s.controller),s.controller.addEventListener("connected",a=>{s.setControllerLayers(s.controllerModel,2),s.setControllerLayers(s.controllerGrip,2),setTimeout(()=>{s.setControllerLayers(s.controllerGrip,2)},1e3)}),s.hand.addEventListener("connected",a=>{if(a.data.hand){e.Rig&&e.Rig.add(s.hand),s.type=0,s.handPointerModel.traverse(h=>h.layers.set(2)),s.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let c=s.hand.joints;if(c)for(let h of Object.keys(c)){let u=c[h];u.parent||s.hand.add(u)}}}),s}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Oe),cn(e).multiply(this._wristQuaternion.setFromEuler(new Lt(-Math.PI/4,0,0)))):null}movementVector=new O;worldRot=new Oe;joystick=new _e;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Qn.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Qn.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this.hand.add(this.handPointerModel),console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Oe;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Qn.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(cn(this.controller),this.useSmoothing?t:1);let n=ot(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,kt(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let r=this.getWristQuaternion();r&&this.rayRotation.copy(r)}Bn(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Bn(this.raycastLine,this.rayRotation),kt(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Qn.MovementSpeedFactor,s=2,r=gt.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,l=Math.pow(this.joystick.x,s);l*=a,l*=r;let c=this.joystick.y>0?1:-1,h=Math.pow(this.joystick.y,s);h*=c,l*=r,t.getWorldQuaternion(this.worldRot),this.movementVector.set(l,0,h),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(i*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,d=Math.abs(u);if(d<.4)this.didRotate=!1;else if(d>.5&&!this.didRotate){let f=u>0?-1:1;t.rotateY(gt.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5,s=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,r=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let l=t[a];if(a===4)if(l.pressed&&!this.didChangeScale){this.didChangeScale=!0;let c=this.webXR.Rig;if(c)if(s){s=!1,c.scale.set(1,1,1),r=1,Qn.MovementSpeedFactor=1;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance&&(h.far=Qn.PreviousCameraFarDistance)}else{s=!0,i=!0,r=.1,Qn.MovementSpeedFactor=r*2;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance=h.far,h.far/=r}}else l.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let l=a[0];if(s||this.isValidTeleportTarget(l.object)){let c=l.point;kt(e,c)}}}}else n<.1&&(this.didTeleport=!1);r!==null&&(e.scale.set(r,r,r),e.updateMatrixWorld())}isValidTeleportTarget(e){return K.getComponentInParent(e,wh)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Qn.raycastColor:i.color=Qn.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=gt.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),e&&e.length>0)for(let n of e){let i=n.object;if(!this.testIsVisible(i)){console.log("not visible");continue}this.lastSelectStartObject=i;let s={selected:i,grab:i},r=Qn.eventSubs["select-start"];if(r&&r.length>0)for(let a of r)a(this,s);s.grab!==i&&console.log("Grabbed object changed","original",i,"new",s.grab),s.grab&&(this.grabbed=is.TryTake(this,s.grab,n,t));break}else{let n=Qn.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let s of n)s(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Qn.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?K.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new vr;return e.origin.copy(ot(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=ot(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Zn;return e.layerMask=new Fi,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},Vt=Qn;Se(Vt,"Factory",new F5),Se(Vt,"raycastColor",new q(.9,.3,.3)),Se(Vt,"raycastNoHitColor",new q(.6,.6,.6)),Se(Vt,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,0,-1)])),Se(Vt,"handModels",{}),Se(Vt,"eventSubs",{}),Se(Vt,"PreviousCameraFarDistance"),Se(Vt,"MovementSpeedFactor",1);var Gi=class{static AddEventListener(e,t){return Gi.Events[e]||(Gi.Events[e]=[]),Gi.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Gi.Events[e])return;let n=Gi.Events[e].indexOf(t);n>=0&&Gi.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let s=K.getComponentInParent(t,qs);if(!s)return console.warn("Prevented taking object that is not interactable",t),null;let r=t,a=K.getComponentInParent(t,bi);a&&(a.requestOwnership(),r=a.gameObject);for(let c of this.Current)if(c.selected===r)return c.controller===e||(c.free(),c.Take(e,r,t,a,s,n,i)),c;let l=new Gi;return l.Take(e,r,t,a,s,n,i),l}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,s,r,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let l={controller:e,take:t,hit:n,sync:i,interactable:s};Gi.Events.WillTake?.forEach(f=>f(this,l));let c=n;c?.material&&(this.originalMaterial=c.material,Array.isArray(c.material)||(c.material=c.material.clone(),c.material&&c.material.emissive&&(c.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=c,this.controller=e,this.interactable=s,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=K.addNewComponent(this.selected,Ys),this.rigidbodies=K.getComponentsInChildren(this.selected,Xt),ot(this.positionSource,this.lastControllerWorldPos);let h=()=>a?this.lastControllerWorldPos.clone():r.point.clone();this.grabDistance=h().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(h());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();cn(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let d=this.controller.webXR.Rig;return d&&this.rigPositionLastFrame.copy(ot(d)),vn.Add(e.context,this.selected),Gi.Register(this),this.sync&&(this.sync.fastMode=!0),Gi.Events.DidTake?.forEach(f=>f(this,l)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Gi.Events.WillFree?.forEach(i=>i(this,e)),vn.Remove(this.controller.context,this.selected),Gi.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Gi.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new O;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new O;localQuaternionToGrab=new Oe(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new O;controllerWorldPos=new O;lastControllerWorldPos=new O;controllerPosDelta=new O;totalChangeAlongDirection=0;rigPositionLastFrame=new O;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ot(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=ot(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new O),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Bn(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ot(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),kt(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});Qt.markDirty(this.selected,!0)}}},is=Gi;Se(is,"Events",{}),Se(is,"Current",[]);var Qs=class extends le{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,n){if(n&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new it().fromArray(n.transform.matrix).invert(),e){if(this.invertForward){let i=new it().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),Qt.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new it().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};re([se()],Qs.prototype,"invertForward",2),re([se()],Qs.prototype,"arScale",1);var El=class extends le{awake(){}};var Eh=be("debugaddressables"),a_=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},Wi=class{static getOrCreate(e,t,n){let i=ty(e,t);Eh&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",i);let s=n.addressables,r=s.findAssetReference(i);if(r)return r;let a=new Wi(i);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,l2(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Eh&&console.log("Unload",this.asset),this.asset.scene?K.destroy(this.asset.scene):K.destroy(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Eh&&console.log("Preload",this.uri);let e=await WO(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=bt.Current;this._rawBinary?(this._loading=Jd(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Eh&&console.log("Load async",this.uri),this._loading=Sh(t,this.uri,null,!0,i=>{this.raiseProgressEvent(i)}));let n=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(n),this._loading=void 0,n)return Vo(t),n.scene!==void 0&&(this.asset=n),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,n){let i=bt.Current;if(e||(e=i.scene),this.mustLoad&&await this.loadAssetAsync(),Eh&&console.log("Instantiate",this.uri,"parent:",e),this.asset){Eh&&console.log("Add to scene",this.asset);let s=e instanceof hn?e:null;if(s||(s=new hn),typeof e=="object"&&(e instanceof Fe?s.parent=e:Object.assign(s,e)),t){s.context=i;let r=this.asset;r.guid=this.uri;let a=dy(r,s,void 0,n);if(a)return a}else{let r=K.instantiate(this.asset,s);if(r)return r}}else Eh&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},TT=class extends Qo{constructor(){super([Wi])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?Wi.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new TT;var no=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,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)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,s){return e.prep(4,16),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Un=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var ZO=be("debugxr"),rg=be("debugavatar");var RT="VRUS";jd(RT,Un.getRootAsVrUserStateBuffer);function CT(){return new Date().getTime()}function U5(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return _i.create(e,t)}var og=class{guid;time;avatarId;position=new O;rotation=new rt;scale=1;posLeftHand=new O;posRightHand=new O;rotLeftHand=new Oe;rotRightHand=new Oe;constructor(e){this.guid=e}update(e,t,n,i,s){this.time=CT(),this.avatarId=s,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let r=og.quat0,a=og.quat1;r.set(n.x,n.y,n.z,n.w),r=r.multiplyQuaternions(r,og.invertRotation),e&&(e.getWorldQuaternion(a),r.multiplyQuaternions(a,r)),this.rotation.set(r.x,r.y,r.z,r.w),this.scale=e.scale.x;let l=i.LeftController?.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand));let c=i.RightController?.controllerGrip;if(c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let h=i.LeftController.wrist;h&&(h.getWorldPosition(this.posLeftHand),h.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let h=i.RightController.wrist;h&&(h.getWorldPosition(this.posRightHand),h.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);Un.startVrUserStateBuffer(e),Un.addGuid(e,n),Un.addTime(e,U5(this.time)),Un.addAvatarId(e,i),Un.addPosition(e,Tn.createVec3(e,this.position.x,this.position.y,this.position.z)),Un.addRotation(e,no.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Un.addScale(e,this.scale),Un.addPosLeftHand(e,Tn.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Un.addPosRightHand(e,Tn.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Un.addRotLeftHand(e,no.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Un.addRotRightHand(e,no.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let s=Un.endVrUserStateBuffer(e);e.finish(s,RT);let r=e.asUint8Array();t.sendBinary(r)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let s=t.rotation();s&&this.rotation.set(s.x(),s.y(),s.z(),s.w());let r=t.posLeftHand();r&&this.posLeftHand.set(r.x(),r.y(),r.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());let c=t.rotRightHand();c&&this.rotRightHand.set(c.x(),c.y(),c.z(),c.w()),this.scale=t.scale()}},$s=og;Se($s,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI)),Se($s,"quat0",new Oe),Se($s,"quat1",new Oe);var na=class extends le{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent(wt)),this.webXR||(this.webXR=K.findObjectOfType(wt,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=K.findObjectOfType(wt,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=K.findObjectOfType(Vi,this.context)),rg){let e="debug-avatar-"+rg,t=new Js(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof rg=="string"&&rg.length>0)if(await t.setAvatarOverride(rg)){let n=new $s(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=K.getComponent(this.gameObject,wt),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),wt.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),wt.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),wt.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(RT,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new $s("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return ZO&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let s=new Js(this.context,e,this.webXR);i=s,this.avatars[e]=s}catch(s){this.avatars[e]=null,console.error(s)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),wt.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),wt.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),wt.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=CT();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=CT();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Js(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){ZO&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new _s(1024);onXRSessionUpdate(e){this.xrState??=new $s(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new vl(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,s=t.getViewerPose(n.getReferenceSpace());if(!s)return;let r=s?.transform,a=r.position,l=r.orientation;this.xrState.update(i,a,l,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return be("avatar")}};async function H5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function z5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var AT=!1,PT=!1;H5().then(o=>AT=o);z5().then(o=>PT=o);var $n=class extends le{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(AT||PT)}static get IsARSupported(){return AT}static get IsVRSupported(){return PT}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){$n.XRSupported||console.warn("WebXR is not supported on this device");let n=of.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={requiredFeatures:["hit-test"]};n&&(i.domOverlay={root:n},i.optionalFeatures=["dom-overlay"]);let s=r_.createButton(e.context.renderer,i);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),$n.resetButtonStyles(s),(t?.registerClick??!0)&&s.addEventListener("click",e.onClickedARButton.bind(e)),s}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Wi.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!K.findObjectOfType(na,this.context)){let e=K.addNewComponent(this.gameObject,na,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new Sl(this);let e=$n.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=$n.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(n=$n.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{$n.resetButtonStyles(n),$n.resetButtonStyles(t)},1e3)}_transformOrientation=new Oe;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let s of this.controllers)s.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}$n._isInXr===!1&&t&&this.onEnterXR(t,e),$n.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)Vt.Create(this,e,this.gameObject,0);$n.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(ot(this.context.mainCamera)),this._originalCameraRotation.copy(cn(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=K.findObjectOfType(El,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new zr,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new O;_originalCameraRotation=new Oe;onEnterXR(e,t){console.log("[XR] session begin",e),$n._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let l=new Oe(a.x,a.y,a.z,a.w),c=new Lt().setFromQuaternion(l);this.rig.rotateY(c.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let r=i.getCamera(this.context.mainCamera);for(let a of r.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let s=this._requestedAR?2:4;switch(Es.Global.Set(s),s){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),$n._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),$n.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),kt(this.context.mainCamera,this._originalCameraPosition),Bn(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),Es.Global.Set(17),$n.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!be("mirror")||setTimeout(()=>{if(!$n.IsInWebXR)return;let t=new URL(window.location.href);Od(t.searchParams,af,1),Od(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{$n.IsInWebXR&&e.end()})})},1e3)}},wt=$n;Se(wt,"_isInXr",!1),Se(wt,"events",new ms),re([se(Wi)],wt.prototype,"defaultAvatar",2);var cf=class{webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this.webxr=e}arDomOverlay=null;arOverlayElement=null;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let n=0;n<4;n++)Vt.Create(this.webxr,n,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=K.findObjectOfType(Qs,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(i=>{this.hitTestSource=i})}),!this.reticle&&this.sessionRoot&&(this.reticle=new _t(new Do(.07,.09,32).rotateX(-Math.PI/2),new Jt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,cf.tempWebXRObject||(cf.tempWebXRObject=new Fe),this.context.scene.add(cf.tempWebXRObject),K.addComponent(cf.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),K.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],s=this.webxr.context.renderer.xr.getReferenceSpace();if(s){let r=i.getPose(s);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,r),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&r)){let a=r.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Sl=cf;Se(Sl,"tempWebXRObject");var IT=!1;var hf=class extends qs{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new _e}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||wt.IsInWebXR)return;let t=K.getComponentInParent(e.object,hf);!t||t!==this||(hf.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||hf.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(wt.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!wt.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&!this._dragHelper?.hasSelected&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new l_(this.context.mainCamera);else return;if(!e||!e.object)return;let t=K.getComponentInParent(e.object,hf);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let l of this.selectStartEventListener)l(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context);let s=K.getComponentInChildren(n,bi);IT&&console.log("DRAG START",s,n),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=K.addNewComponent(n,Ys),this._draggingRigidbodies.length=0;let r=K.getComponentsInChildren(n,Xt);r&&this._draggingRigidbodies.push(...r);let a=tM();K.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(IT&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let i=K.getComponentInChildren(e.object,bi);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=tM();K.invokeOnChildren(t,n("onDragEnd"))}},Ss=hf;Se(Ss,"_active",null),Se(Ss,"lastHovered");var OT=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Oi;_hasGroundPlane=!1;_groundPlane=new Oi;_groundOffset=new O;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new O;_raycaster=new Ho;_cameraPlaneOffset=new O;_intersection=new O;_worldPosition=new O;_inverseMatrix=new it;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Ji(OT.geometry),n=t.material;n.color=new q(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Ni(.5,22,22),s=new Jt({color:n.color}),r=new _t(i,s);r.visible=!1,r.layers.set(2),this._groundMarker=r}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);if(this._selected&&vn.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}vn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=K.getComponentsInChildren(this._selected,Xt),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new O(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,n=68,i=83,s=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),r=this._context.input.getTouchesPressedCount()>=2||s;if(r){let l=this._context.input.getPointerPositionDelta(0);l&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,l.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){IT&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let l=ot(this._camera).clone().sub(ot(this._selected)).normalize(),c=Math.abs(l.dot(this._groundOffsetVector)),h=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!r&&c>.2&&!h&&this._context.input.getPointerPressedCount()<=1,d=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||d)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,u){this._groundOffsetVector.set(0,1,0);let g=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(g,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);d&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=ot(this._selected);i.y=e.y,e=i}if(kt(this._selected,e),kt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=ot(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),kt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=ot(this._selected),t=new vr(new O(0,.1,0).add(e),new O(0,-1,0)),n=new Zn;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let s=0;s<i.length;s++){let r=i[s];if(!r.face||this.contains(this._selected,r.object))continue;let a=new O(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){Qt.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},l_=OT;Se(l_,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,-1,0)]));var Ml=class extends le{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?ys.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let s=i.getAsFile();if(!s)continue;console.log("Register file "+s.name+" to",this.filesBackendUrl,s);let r=await QO(s,this.context,this.filesBackendUrl);r&&this.addObject(e,r)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async s=>{console.log("dropped url",s);try{let r=new URL(s);if(!r)return;let a=await $O(r,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",s)}})}}async addObject(e,t){console.log("Dropped",t);let n=new Zn;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),s=t.scene;if(i&&i.length>0)for(let r of i){s.position.copy(r.point);break}this.gameObject.add(s),this.dispatchEvent(new CustomEvent("object-added",{detail:s}))}};re([se()],Ml.prototype,"filesBackendUrl",2),re([se()],Ml.prototype,"localhost",2);var io=class extends qs{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new O(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Oe(0,0,0,1)}let e=K.getComponentInParent(this.gameObject,Ss);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),Vt.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new hn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=K.instantiateSynced(this.object,t);return console.assert(n!==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),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};re([se(Fe)],io.prototype,"parent",2),re([se(Fe)],io.prototype,"object",2),re([se()],io.prototype,"limitCount",2),re([se()],io.prototype,"limitInterval",2);var so=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},G5=o=>/^[A-Z]*$/.test(o),Mh=class extends Event{args},Rn=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let s of this.key)i&&G5(s)&&(n+="-"),i=!0,n+=s.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Mh(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new so(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var uf=class extends le{};import{FlyControls as W5}from"three/examples/jsm/controls/FlyControls";var df=class extends le{_controls=null;onEnable(){let e=K.getComponent(this.gameObject,Bt)?.cam;this._controls=new W5(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};var ia=class extends le{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Qr||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new th(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=t_(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};re([se()],ia.prototype,"objectBounds",2),re([se(q)],ia.prototype,"color",2),re([se()],ia.prototype,"isGizmo",2);import{GLTFExporter as X5}from"three/examples/jsm/exporters/GLTFExporter.js";var ag=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new it,a=new Array,l=new Array,c=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,r);let g=new O,p=new Oe,m=new O;r.decompose(g,p,m),a.push(g.x,g.y,g.z),l.push(p.x,p.y,p.z,p.w),c.push(m.x,m.y,m.z)}let h=new Float32Array(a),u=new Float32Array(l),d=new Float32Array(c);s.attributes={TRANSLATION:n.processAccessor(new Mt(h,3)),ROTATION:n.processAccessor(new Mt(u,4)),SCALE:n.processAccessor(new Mt(d,3))},i[this.name]=!0}};var Tl=Nn,c_="$___Export_Components",j5="NEEDLE_components",DT=class{[ih]},kT=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},ff=class{get name(){return j5}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let n=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(i,s)=>{try{this.serializeUserData(i,s),n(i,s)}finally{this.afterSerializeUserData(i,s)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;!n||n.length<=0||(delete e.userData.components,e[c_]=n)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Tl&&console.log("DONE",JSON.stringify(t)),e[c_]===void 0)return;let n=e[c_];delete e[c_],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;console.log(e.name,n,e.uuid);let i=new kT(e,n,t);this.exportContext[n]=i,this.objectToNodeMap[e.uuid]=n}afterParse(e){Tl&&console.log("AFTER",e);for(let t in this.exportContext){let n=this.exportContext[t],i=n.node,s=n.nodeDef,r=n.nodeIndex,a=i.userData?.components;if(!a||a.length<=0)continue;let l=new DT;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=i,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;let c=[];for(let h of a){this.context.target=h;let u=eD(h,this.context);u!==null&&c.push(u)}c.length>0&&(l[ih]=c,Tl&&console.log("DID WRITE",i,"nodeIndex",r,c))}}beforeRoot(){return Tl&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,n=t?.extensions;if(!n)return;let i=n[this.name];Tl&&console.log("After root",e,this.parser,n);let s=[];if(i===!0){let r=t.json.nodes;for(let a=0;a<r.length;a++){let l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){let l=r[a],c=a,h=l.extensions;if(!h)continue;let u=h[this.name];if(!u)continue;Tl&&console.log("NODE",l);let d=this.nodeToObjectMap[c];if(!d){console.error("Could not find object for node index: "+c,l,t);continue}s.push(this.createComponents(d,u))}}await Promise.all(s)}async createComponents(e,t){if(!t)return;let n=t[ih];if(n){Tl&&console.log(e.name,n);for(let i in n){let s=n[i];Tl&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&await qd(this.parser,s),e.userData=e.userData||{},e.userData[ih]=e.userData[ih]||[],e.userData[ih].push(s)}}}};var pf=class extends ts{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Ks=class extends le{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Ks.calculateCenter(this.objects)},n=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ks.saveArrayBuffer(n,e):Ks.saveJson(n,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new X5,this.exporter.register(a=>new ag(a)),this.ext=new ff,this.ext.registerExport(this.exporter)),Ks.filterTopmostParent(e);let n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Ks.collectAnimations(e)},i=new Fe;t?.pivot&&i.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(i.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),K.getComponentsInChildren(a,Sn).forEach(l=>{K.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))});let s=new Yd(i);return this.ext.context=s,new Promise((a,l)=>{try{this.exporter?.parse(i,c=>{r(),a(c)},c=>{r(),l(c)},n)}catch(c){console.error(c),l(c)}finally{console.log("FINALLY")}});function r(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,K.getComponentsInChildren(a,Sn).forEach(l=>{K.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}static collectAnimations(e,t){t=t||[];for(let n of e)!n||n.traverseVisible(i=>{i.animations&&i.animations.length>0&&t.push(...i.animations)});return t}static calculateCenter(e,t){let n=t||new O;return n.set(0,0,0),e.forEach(i=>{n.add(ot(i))}),console.log(n),n.divideScalar(e.length),n}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let n=e[t];if(!n){e.splice(t,1),t--;continue}for(;n.parent;){if(e.includes(n.parent)){e.splice(t,1),t--;break}n=n.parent}}}};var sa=class extends le{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Qr)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Dm(e,t,this.color0??new q(.4,.4,.4),this.color1??new q(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};re([se()],sa.prototype,"isGizmo",2),re([se(q)],sa.prototype,"color0",2),re([se(q)],sa.prototype,"color1",2);import{GroundProjectedEnv as q5}from"three/examples/jsm/objects/GroundProjectedEnv.js";var ra=class extends le{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.updateProjection(),this._watcher||(this._watcher=new ey(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new q5(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2))}};re([se()],ra.prototype,"scale",1),re([se()],ra.prototype,"radius",1),re([se()],ra.prototype,"height",1);function FT(o){return o*Math.PI/180}var tD=300,nD=be("debuglights");var xi=class extends le{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new q(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let n=this._webARRoot?.arScale;typeof n=="number"&&n>0&&(t/=n)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let n=t.shadow.camera;n.far=e,n.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new q(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=wt.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=wt.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){wt.removeEventListener("xrStarted",this._webXRStartedListener),wt.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Qs)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new Sd(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-tD*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Dd(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),nD){let r=new km(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:let n=new wd(this.color,this.intensity*Math.PI,this.range,FT(this.spotAngle/2),1-FT(this.innerSpotAngle/2)/FT(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;let i=n.target;n.add(i),i.position.set(0,0,this.range),i.rotation.set(0,0,0);break;case 2:let s=new Ed(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,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),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=tD*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{let n=this.gameObject.scale.x;t.left*=n,t.right*=n}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let n=this.gameObject.scale.y;t.top*=n,t.bottom*=n}this.light.shadow.needsUpdate=!0,nD&&this.context.scene.add(new Fm(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}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};re([se()],xi.prototype,"type",2),re([se(q)],xi.prototype,"color",2),re([se()],xi.prototype,"shadowNearPlane",1),re([se()],xi.prototype,"shadowBias",1),re([se()],xi.prototype,"shadowNormalBias",1),re([se()],xi.prototype,"shadows",1),re([se()],xi.prototype,"lightmapBakeType",2),re([se()],xi.prototype,"intensity",1),re([se()],xi.prototype,"shadowDistance",1),re([se()],xi.prototype,"shadowResolution",1);var fre=new O(0,0,0);var mf=be("debugLODs"),Y5=be("noLODs");var ro=class{screenRelativeTransitionHeight;distance;renderers};re([se()],ro.prototype,"screenRelativeTransitionHeight",2),re([se()],ro.prototype,"distance",2),re([se()],ro.prototype,"renderers",2);var BT=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let n of t.renderers){let i=this.findRenderer(n,e.gameObject);i&&i.gameObject?this.renderers.push(i):mf&&console.warn("Renderer not found: "+n,e.gameObject)}}findRenderer(e,t){let n=K.foreachComponent(t,i=>i.guid===e||Object.getPrototypeOf(i)?.guid===e?i:null);if(n)return n;for(let i of t.children){let s=this.findRenderer(e,i);if(s)return s}return null}},Cl=class extends le{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!Y5&&!this._lodsHandler&&!!this.gameObject&&(mf&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let i of this.lodModels){e=Math.max(i.distance,e);let s=new BT(this,i);this._lods.push(s);for(let r of s.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let i=0;i<t.length;i++){let s=new dd;this._lodsHandler.push(s),this.gameObject.add(s)}let n=new Fe;mf&&console.log(t);for(let i=0;i<t.length;i++){let s=t[i],r=this._lodsHandler[i],a=s.gameObject,l=0,c=0;mf&&console.log(i,a.name);for(let u of this._lods){let d=null;u.renderers.includes(s)?d=a:d=n,mf&&console.log("add",u.model.distance,d.name);let f=u.model.distance;c=f-l,l=Math.max(f,l),this.onAddLodLevel(r,d,f)}let h=l+c;mf&&console.log("cull",h),this.onAddLodLevel(r,n,h)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,n){e.addLevel(t,n*this._distanceFactor);let i={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(i)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let n=t.lod.levels[t.levelIndex];n.distance=t.distance*e}}}};re([se(O)],Cl.prototype,"localReferencePoint",2),re([se(ro)],Cl.prototype,"lodModels",2);var gf=class extends le{onEnable(){this.enabled&&this.context.physics.addMeshCollider(this.gameObject)}};var vf=class extends le{},yf=class extends le{};var NT=be("debugnestedgltf"),Th=class extends le{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;NT&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new hn;t.idProvider=new li(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let n=this.gameObject.matrix;NT&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let i=await this.filePath?.instantiate?.call(this.filePath,t);i&&(i.matrixAutoUpdate=!1,i.matrix.identity(),i.applyMatrix4(n),i.matrixAutoUpdate=!0),this.destroy(),NT&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,i)}}hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}};re([se(Wi)],Th.prototype,"filePath",2);var _f=class extends le{from;affectPosition;affectRotation;alignLookDirection;levelLookDirection;positionOffset;rotationOffset;update(){if(!this.from)return;var e=ot(this.from),t=cn(this.from);this.affectPosition&&kt(this.gameObject,e.add(this.positionOffset));let n=new Lt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),i=new Oe().setFromEuler(n);this.affectRotation&&Bn(this.gameObject,t.multiply(i));let s=new O;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};var bf=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new q(1,1,1);startColor1=new q(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new _e(0,1);cullingMode=0},xf=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},wf=class{shapeType=UT.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new O(1,1,1);boxThickness=new O(0,0,0);position=new O(0,0,0);rotation=new O(0,0,0);scale=new O(1,1,1);radius=1;sphericalDirectionAmount=0},UT=(v=>(v[v.Sphere=0]="Sphere",v[v.SphereShell=1]="SphereShell",v[v.Hemisphere=2]="Hemisphere",v[v.HemisphereShell=3]="HemisphereShell",v[v.Cone=4]="Cone",v[v.Box=5]="Box",v[v.Mesh=6]="Mesh",v[v.ConeVolume=7]="ConeVolume",v[v.Circle=10]="Circle",v[v.SingleSidedEdge=11]="SingleSidedEdge",v[v.MeshRenderer=12]="MeshRenderer",v[v.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",v[v.BoxShell=14]="BoxShell",v[v.BoxEdge=15]="BoxEdge",v[v.Donut=16]="Donut",v[v.Rectangle=17]="Rectangle",v[v.Sprite=18]="Sprite",v[v.SpriteRenderer=19]="SpriteRenderer",v))(UT||{});var iD=be("debugparticles"),HT=class{age=0;lifetime=0;position;velocity;color},Ch=class extends le{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){iD&&console.log(this)}},Ef=class extends le{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Oe;tempVec3=new O;tempQuat=new Oe;awake(){this.renderer=K.getComponent(this.gameObject,Ch),iD&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Lt(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new ht,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Qe(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let n=0;n<e.length;n++)e[n*3]=1,e[n*3+1]=1,e[n*3+2]=1;let t=new Qe(e,3);this.geometry.setAttribute("color",t),this.material=new Fc({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new md(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let n=this.particleStates[t];if(!n)continue;let i=n.velocity.x*e,s=n.velocity.y*e,r=n.velocity.z*e;n.position.x+=i,n.position.y+=s,n.position.z+=r,this.updateOverLifetime(t,n),this.geometry.attributes.position.setXYZ(t,n.position.x,n.position.y,n.position.z),this.geometry.attributes.color.setXYZ(t,n.color.r,n.color.g,n.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let n=0;n<t;n+=1){if(n>=this.particleStates.length){let s=new HT;s.lifetime=this.main.startLifetime??1,s.position=new O,s.velocity=new O,s.color=new q(1,0,0),this.particleStates.push(s),this.initializeParticle(n,s),s.age=s.lifetime*Math.random()}let i=this.particleStates[n];if(i.age>i.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(n,i);continue}i.age+=e,this.particleStates[n]=i}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let n=t.position;n.multiply(this.shape.scale),n.applyQuaternion(this.shapeRotation),n.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let n=new O(0,1,0);t.copy(n);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*gt.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};function*sD(o,e=null){let t=e?e.time:bt.Current.time,n=t.time;for(;t.time-n<o;)yield}var ss=class extends le{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield sD(.2),!this.tryAssignColor()););}tryAssignColor(){let e=K.getComponentInParent(this.gameObject,sn);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ss.hashCode(e),n=ss.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let i=this.gameObject;this.assignColor(n,e,i)}else if(this.gameObject.children)for(let i of this.gameObject.children){let s=i;s.material&&s.material.color&&this.assignColor(n,e,s)}}assignColor(e,t,n){let i=n.material;!i||(i._playerMaterial!==t?(i=i.clone(),i._playerMaterial=t,n.material=i):console.log("DONT CLONE",i),i.color=e)}static hashCode(e){var t=0,n,i;if(e.length===0)return t;for(n=0;n<e.length;n++)i=e.charCodeAt(n),t=(t<<5)-t+i,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,n=(e&65280)>>8,i=e&255;return new q(t/255,n/255,i/255)}};function J5(){return new Promise((o,e)=>{let n=()=>{n!=null&&(document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n),o())};document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)})}async function rD(o){await J5(),o()}var zT=be("debugvideo");var ji=class extends le{renderer=null;playOnAwake=!0;playOnEnable;targetMaterialProperty;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setClipURL(e){this.url!==e&&(this.url=e,this.source=1,zT&&console.log("set url",e),this.videoElement&&(this.videoElement.src=e,this._isPlaying&&this.videoElement.play()))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0)}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this.videoTexture&&(this.videoTexture.dispose(),this.videoTexture=null)}_receivedInput=!1;constructor(){super(),rD(()=>{this._receivedInput=!0,this.updateVideoElementSettings()})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),zT&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new vm(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ct,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),zT&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;let t=this.gameObject.material;if(t)if(t!==this.videoMaterial&&(this.videoMaterial=t.clone(),this.gameObject.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this.videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=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.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none")}};re([se(Fe)],ji.prototype,"renderer",2),re([se()],ji.prototype,"playOnAwake",2),re([se()],ji.prototype,"playOnEnable",2),re([se()],ji.prototype,"targetMaterialProperty",2),re([se()],ji.prototype,"time",2),re([se()],ji.prototype,"playbackSpeed",1),re([se()],ji.prototype,"isLooping",1);var Sf=class extends le{streamOnAwake=!0;start(){this.streamOnAwake&&this.open()}requestOpen=!1;captureStream=null;async open(e=!1){if(!(this.captureStream&&!e)){this.close(),this.requestOpen=!0;try{let t=K.getComponentInChildren(this.gameObject,ji);if(t){let n={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(n),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};var Rl=class extends le{mode=0;shadowColor=new gn(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=K.getComponent(this.gameObject,Sn);if(e){let t=e.material;t.blending=em,this.applyMaterialOptions(t),t.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
6339
+ `,defines:{USE_LIGHTMAP:""}})}};var se=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=rO(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=rO(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let n=e.$serializedTypes=e.$serializedTypes||{};n[t]=o}};function rO(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var BM=be("debugstencil");function n5(o,e){return(o&1<<e.layer)!=0}var dh=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(BM&&console.log(t,dh.stencils),!t)return;let n=dh.stencils[t];if(!!n)for(let i=n.length-1;i>=0;i--){let s=n[i];if(n5(s.layer,e)){BM&&console.log(s);let r=e.material?.clone();r&&(e.material=r,e.gameObject.renderOrder=s.event*1e3+s.index*50,r.stencilWrite=!0,r.stencilWriteMask=255,r.stencilFuncMask=255,r.stencilRef=s.value,r.stencilFunc=s.compareFunc,r.stencilZPass=s.passOp,r.stencilFail=s.failOp,r.stencilZFail=s.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[s5];if(n){BM&&console.log(n);let i=n.stencil;if(i&&Array.isArray(i))for(let s of i){let r={...s};r.compareFunc=i5(r.compareFunc),r.passOp=NM(r.passOp),r.failOp=NM(r.failOp),r.zFailOp=NM(r.zFailOp),dh.stencils[this.source]||(dh.stencils[this.source]=[]),dh.stencils[this.source].push(r)}}}return null}},fh=dh;Se(fh,"stencils",{});function NM(o){switch(o){case 0:return td;case 1:return IS;case 2:return LS;case 3:return OS;case 4:return DS;case 6:return kS;case 7:return FS;case 5:return BS}return 0}function i5(o){switch(o){case 1:return NS;case 2:return US;case 3:return HS;case 4:return zS;case 5:return VS;case 6:return GS;case 7:return WS;case 8:return Q0}return 0}var s5="NEEDLE_render_objects";import{GLTFLoader as r5}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as UM}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as oO}from"three/examples/jsm/loaders/KTX2Loader.js";var Jm=be("debugdecoders"),Sr,pl;function HM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Jm&&console.log("Setting draco decoder path to",o),Sr.setDecoderPath(o))}function zM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Jm&&console.log("Setting draco decoder type to",o),Sr.setDecoderConfig({type:o}))}function VM(o){o!==void 0&&typeof o=="string"&&(pl||(pl=new oO),Jm&&console.log("Setting ktx2 transcoder path to",o),pl.setTranscoderPath(o))}function ph(o,e){Sr||(Sr=new UM,Sr.setDecoderPath("./include/draco/"),Sr.setDecoderConfig({type:"js"}),Jm&&console.log("Setting draco decoder path to","./include/draco/")),pl||(pl=new oO,pl.setTranscoderPath("./include/ktx2/"),Jm&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&pl.detectSupport(e.renderer)),o.setDRACOLoader(Sr),o.setKTX2Loader(pl)}var GM="NEEDLE_deferred_texture",ml=be("debugdeferredtextures"),Qm=class{static assignTextureLOD(e,t,n=0){if(!!t)for(let i of Object.keys(t)){let s=t[i];s?.isTexture===!0&&(ml&&console.log("FIND",i,s?.name,s?.userData,s),Qm.getOrLoadTexture(e,t,i,s,n).then(r=>{r?.isTexture===!0&&(r.needsUpdate=!0,t[i]=r,t.needsUpdate=!0)}))}}get name(){return GM}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return ml&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[GM];if(i){let s=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),s.then(r=>{ml&&console.log("register texture",r.name,r.uuid,i),r.userData.deferred=i,Qm.cache.set(r.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,s){let r=i.uuid,a=Qm.cache.get(r)||i.userData.deferred;if(a){ml&&console.log(r,a.uri,a.guid);let l=a.uri;if(l.endsWith(".glb")||l.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;let c=a.uri+"_"+a.guid;if(this.resolved[c])return this.resolved[c];let h=new r5;ph(h,e),ml&&console.log("Load "+l,t.name,n);let u=await h.loadAsync(l),d=u.parser,f=-1,g=!1;for(let m of u.parser.json.textures)if(f++,m?.extensions){let y=m?.extensions[GM];if(y?.guid&&y.guid===a.guid){g=!0;break}}if(!g)return null;let p=await d.getDependency("texture",f);return this.resolved[c]=p,ml&&console.log(t.name,n,'change "'+i.name+'" \u2192 "'+p.name+'"',l,f,p,t),p}else{let h=await new No().loadAsync(a.uri);return h&&ml?console.log(a,h):console.warn("failed loading",a.uri),h}}else ml&&console.warn("unknown uuid",i.name,i.uuid,i);return null}},Yo=Qm;Se(Yo,"cache",new Map),Se(Yo,"resolved",{});var lO=be("noInstancing"),cO=!!be("debuglightmaps"),o5=be("debuginstancing"),a5=be("debugprogressiveload"),Hd=class{path=null;asset=null;default};var WM=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),n=this.getMaterial.bind(this),i=e.gameObject;if(this._targets=[],i)switch(i.type){case"Group":this._targets=[...i.children];break;case"Mesh":this._targets.push(i);break}return new Proxy(this,{get(s,r){if(typeof r=="string"){let a=parseInt(r);if(!isNaN(a))return n(a)}return s[r]},set(s,r,a){return typeof r=="string"&&t(a,Number.parseInt(r)),Reflect.set(s,r,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let n=this._targets[t];!n||(n.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let n=t[e];return n?n.material:null}},ZM=class extends le{receiveShadows=!1;shadowCastingMode=jM.Off;lightmapIndex=-1;lightmapScaleOffset=new rt(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new WM(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return lO}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}get activeSelf(){return this.enabled}set activeSelf(e){let t=typeof e=="number"?e>.5:e;this.enabled=t,t&&(this.gameObject.visible=!0)}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let n=0;n<this.gameObject.children.length;n++){let i=this.gameObject.children[n];if(!(i.type!=="Mesh"||K.getComponent(i,ZM))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}i.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let n=new qo(this.gameObject,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,cO)}}else if(e==="Group"){for(let n of this.gameObject.children)if(!n.material?.isMeshBasicMaterial){let i=new qo(n,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,cO),i.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=l5.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return K.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return K.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!lO&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){fh.applyStencil(this)}onBeforeRenderThree(e,t,n,i,s,r){if(s._didRequestTextureLOD===void 0&&(s._didRequestTextureLOD=0,a5?(console.log("Load material LOD (with delay)",s.name),setTimeout(()=>{Yo.assignTextureLOD(this.context,s)},2e3)):Yo.assignTextureLOD(this.context,s)),s.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;s.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(s)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[XM]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[XM],this.handles)){for(let n=this.handles.length-1;n>=0;n--)this.handles[n].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&K.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let n=this.handles[t];this.prevLayers||(this.prevLayers=[]);let i=n.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(i):this.prevLayers[t]=i,n.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==jM.On?e.castShadow=!0:e.castShadow=!1}},Sn=ZM;re([se()],Sn.prototype,"receiveShadows",2),re([se()],Sn.prototype,"shadowCastingMode",2),re([se()],Sn.prototype,"lightmapIndex",2),re([se(rt)],Sn.prototype,"lightmapScaleOffset",2),re([se()],Sn.prototype,"enableInstancing",2),re([se()],Sn.prototype,"renderOrder",2),re([se()],Sn.prototype,"allowOcclusionWhenDynamic",2);var mh=class extends Sn{},zd=class extends mh{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},jM=(i=>(i[i.Off=0]="Off",i[i.On=1]="On",i[i.TwoSided=2]="TwoSided",i[i.ShadowsOnly=3]="ShadowsOnly",i))(jM||{}),XM="NEEDLE_NEED_UPDATE_INSTANCE",Qt=class{static markDirty(e,t=!0){if(!!e&&(K.isUsingInstancing(e)&&(e[XM]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let n of e.children)Qt.markDirty(n,!0)}},qM=class{objs=[];setup(e,t,n,i,s=0){let r=this.tryCreateOrAddInstance(e,t,i);if(r)return n===null&&(n=[]),n.push(r),n;if(s<=0&&e.type!=="Mesh"){let a=s+1;for(let l of e.children)n=this.setup(l,t,n,i,a)}return n}tryCreateOrAddInstance(e,t,n){if(e.type==="Mesh"){let i=n.foundMeshes;if(n.foundMeshes+=1,!n.rend.enableInstancing||i>=n.rend.enableInstancing.length||!n.rend.enableInstancing[i])return null;let s=e,r=s.geometry,a=s.material;for(let c of this.objs)if(!c.isFull()&&c.geo===r&&c.material===a)return c.addInstance(s);let l=new Ay(e.name,r,a,200,t);return this.objs.push(l),l.addInstance(s)}return null}},l5=new qM,YM=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,n){this.instanceIndex=e,this.object=t,this.instancer=n,K.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},JM=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,n,i,s){this.name=e,this.geo=t,this.material=n,this.context=s,this.maxCount=i,o5&&(n=new Jt({color:this.randomColor()})),this.inst=new pd(t,n,i),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new q(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new YM(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let n=this.handles.indexOf(e);if(n<0)return;e.instanceIndex=n}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,JM.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let n=this.handles[this.currentCount-1];n&&(n.instanceIndex=e.instanceIndex,n.updateInstanceMatrix(),this.handles[e.instanceIndex]=n,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},Ay=JM;Se(Ay,"nullMatrix",new it);var $m=be("debugphysics"),c5=be("debugcollisions"),Py=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},Km=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},QM=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var Zn=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new _e),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Fi);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};Se(Zn,"AllLayers",4294967295);var $M=class{distance;point;object;constructor(e,t,n){this.object=e,this.distance=t,this.point=n}},Iy=class{raycaster=new Ho;defaultRaycastOptions=new Zn;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Fi;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new gr(e,t),i=this.sphereMask;i.enableAll(),i.disable(2);for(let s of this.context.scene.children){let r=this.onSphereOverlap(s,n,i);r&&this.sphereResults.push(r)}return this.sphereResults.sort((s,r)=>s.distance-r.distance)}tempBoundingBox=new On;onSphereOverlap(e,t,n){if(e.type==="Mesh"){if(!e.layers.test(n))return null;let i=e,s=i.geometry;if(s.boundingBox||s.computeBoundingBox(),!s.boundingBox)return null;i.matrixWorldNeedsUpdate&&i.updateMatrixWorld();let r=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(i.matrixWorld);if(t.intersectsBox(r)){let l=ot(e).distanceTo(t.center);return new $M(e,l,t.center.clone())}}else if(e.children)for(let i of e.children){let s=this.onSphereOverlap(i,t,n);if(s)return s}return null}raycastFromRay(e,t=null){let n=t??this.defaultRaycastOptions;return n.ray=e,this.raycast(n)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold?n.params.Line={threshold:e.lineThreshold}:n.params.Line={threshold:0},e.ray)n.ray.copy(e.ray);else{let a=this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];n.setFromCamera(t,a)}let i=e.targets;i||(i=this.targetBuffer,i[0]=this.context.scene);let s=e.results;s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Fi?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),s.length=0,n.intersectObjects(i,e.recursive,s);let r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),s}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new Ry;objects=[];tempPosition=new O;tempQuaternion=new Oe;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),$m){let t={};t.onInit=(n,i,s)=>{i.layers.set(-1)},sO(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let n=0;n<this.objects.length;n++){let i=this.objects[n];if(i.obj===e){i._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,n=!0){this.world.removeBody(t);for(let i=0;i<this.objects.length;i++){let s=this.objects[i];if(s.obj===e){s._hasRigidbody=!1,n&&this.objects.splice(i,1);break}}}removeShape(e,t){for(let n of this.objects)if(n.obj===e){n.body&&(n.body.removeShape(t),n.body.updateMassProperties());return}}createBody(e,t){let n=this.internalCreateBody(e,null);t.mass&&(n.mass=t.mass),t.kinematic?n.type=qe.KINEMATIC:n.type=qe.DYNAMIC,t.drag&&(n.linearDamping=t.drag),t.angularDrag&&(n.angularDamping=t.angularDrag),t.sleepThreshold&&(n.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(n);let i=new Km(e,n);return i._hasRigidbody=!0,this.objects.push(i),$m&&console.log("created new body",e.name,n,n.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(i),n}addBoxCollider(e,t,n,i,s){let r=this.tempPosition;e.getWorldScale(r);let a=new H(.5*r.x*i.x,.5*r.y*i.y,.5*r.z*i.z),l=new hh(a);l.collisionResponse=!t,n=n.clone(),n.multiply(r);let c=this.addShape(e,l,n,s);if(c!==null){if(this.isAlreadyRegistered(c))return l;let h=new Km(e,c);this.objects.push(h)}return l}addSphereCollider(e,t,n,i){let s=this.tempPosition;e.getWorldScale(s);let r=Math.max(s.x,s.y,s.z),a=new Ty(n*r);t=t.clone(),t.multiply(s);let l=this.addShape(e,a,t,i);if(l!==null){if(this.isAlreadyRegistered(l))return a;let c=new Km(e,l);this.objects.push(c)}return a}addMeshCollider(e){$m&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,n,i){let s=null;if(i?(i.initialize(),console.assert(!!i.body,"rigidbody didn't initialize / produce a physics body",i),s=i.body):(s=this.internalCreateBody(e,null),s.type=qe.KINEMATIC,this.world.addBody(s)),s){n.x*=-1;let r=cn(e),a=ot(e);a.add(n);let l=new Oe(s.quaternion.x,s.quaternion.y,s.quaternion.z,s.quaternion.w);r.multiply(l.invert());let c=s.position,h=new H(a.x-c.x,a.y-c.y,a.z-c.z),u=new jt(r.x,r.y,r.z,r.w);s.addShape(t,h,u),s.updateMassProperties()}return s}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,$m&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new O;tempQuat=new Oe;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],n=t.body;if(!n||!n.world)continue;n.sleepTick(this.context.time.time),$m&&(!t._didSleepLastStep&&n.sleepState===qe.SLEEPING?console.log("BODY SLEEPING",n):t._didSleepLastStep&&n.sleepState!==qe.SLEEPING&&console.log("BODY WOKE UP",n)),t._didSleepLastStep=n.sleepState===qe.SLEEPING;let i=t.obj;if(n.type===qe.KINEMATIC){let s=ot(i,this.temp);n.position.set(s.x,s.y,s.z);let r=cn(i,this.tempQuat);n.quaternion.set(r.x,r.y,r.z,r.w);continue}if(t.parent&&i.parent===t.parent){JL(i,n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w);let s=n.position;Dd(i,s.x,s.y,s.z),n.velocity.length()>n.sleepSpeedLimit&&Qt.markDirty(i)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let n=new qe;n._owner=e,n._name=e.name,e.getWorldPosition(this.tempPosition);let i=this.tempPosition;n.position=new H(i.x,i.y,i.z);let s=this.tempQuaternion;return e.getWorldQuaternion(s),n.quaternion=new jt(s.x,s.y,s.z,s.w),n.type=qe.KINEMATIC,t&&(n.addShape(t),n.updateMassProperties()),n}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=n=>this.raiseCollisionEvents(e.obj,n);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let n=new QM(t.contact,t.type),i=0,s=this.objects;function r(){if(!(i>0))for(let a=0;a<s.length;a++){if(i==2)return;let l=s[a];l.body==t.body?(n.obj=l.obj,++i):l.body==t.target&&(n.target=l.obj,++i)}}c5&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let a=0;a<e.userData?.components?.length;a++){let l=e.userData.components[a];l.onCollision&&(r(),l.onCollision(n))}}};var Ly=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new Rd;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};var TO=Lu(bO(),1);function xO(o=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(o)===!0}var ys=class extends le{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?ys.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let s=be(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=ys.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return xO(e)}};var Zr=new Int32Array(2),Uy=new Float32Array(Zr.buffer),Hy=new Float64Array(Zr.buffer),Gd=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var _i=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?_i.ZERO:new _i(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};_i.ZERO=new _i(0,0);var eg;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(eg||(eg={}));var Jr=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Jr(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new _i(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new _i(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Zr[0]=this.readInt32(e),Uy[0]}readFloat64(e){return Zr[Gd?0:1]=this.readInt32(e),Zr[Gd?1:0]=this.readInt32(e+4),Hy[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){Uy[0]=t,this.writeInt32(e,Zr[0])}writeFloat64(e,t){Hy[0]=t,this.writeInt32(e,Zr[Gd?0:1]),this.writeInt32(e+4,Zr[Gd?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e),i="",s=0;if(e+=4,t===eg.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;s<n;){let r,a=this.readUint8(e+s++);if(a<192)r=a;else{let l=this.readUint8(e+s++);if(a<224)r=(a&31)<<6|l&63;else{let c=this.readUint8(e+s++);if(a<240)r=(a&15)<<12|(l&63)<<6|c&63;else{let h=this.readUint8(e+s++);r=(a&7)<<18|(l&63)<<12|(c&63)<<6|h&63}}}r<65536?i+=String.fromCharCode(r):(r-=65536,i+=String.fromCharCode((r>>10)+55296,(r&(1<<10)-1)+56320))}return i}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return _i.create(e,t)}createScalarList(e,t){let n=[];for(let i=0;i<t;++i)e(i)!==null&&n.push(e(i));return n}createObjList(e,t){let n=[];for(let i=0;i<t;++i){let s=e(i);s!==null&&n.push(s.unpack())}return n}};var _s=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=Jr.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){let i=this.bb.capacity();this.bb=_s.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let n=t<<1,i=Jr.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let i=2;this.addInt16(e-this.object_start);let s=(n+i)*2;this.addInt16(s);let r=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let l=this.bb.capacity()-this.vtables[t];if(s==this.bb.readInt16(l)){for(let c=2;c<s;c+=2)if(this.bb.readInt16(a+c)!=this.bb.readInt16(l+c))continue e;r=this.vtables[t];break}}return r?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,r-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let i=n?4:0;if(t){let s=t;if(this.prep(this.minalign,4+4+i),s.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let r=4-1;r>=0;r--)this.writeInt8(s.charCodeAt(r))}this.prep(this.minalign,4+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,i=n-this.bb.readInt32(n);if(!(this.bb.readInt16(i+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let i,s=e.charCodeAt(n++);if(s<55296||s>=56320)i=s;else{let r=e.charCodeAt(n++);i=(s<<10)+r+(65536-(55296<<10)-56320)}i<128?t.push(i):(i<2048?t.push(i>>6&31|192):(i<65536?t.push(i>>12&15|224):t.push(i>>18&7|240,i>>12&63|128),t.push(i>>6&63|128)),t.push(i&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,i=this.space,s=this.bb.bytes();n<t.length;n++)s[i++]=t[n];return this.endVector()}createLong(e,t){return _i.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let i=e[n];if(i!==null)t.push(this.createObjectOffset(i));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var wO={};function jd(o,e){wO[o]=e}function EO(o){let e=o.getBufferIdentifier(),t=wO[e];return t(o)}function SO(o){return typeof o.guid=="function"?o.guid():null}var nT=Lu(tT(),1);var Vy=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new nT.default(e);t.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),t.on("open",n=>{this._host=new sT(t)})}trySetupClient(e){this._client=new nT.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}},iT=class{_peer;constructor(e){this._peer=e}};var sT=class extends iT{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(n=>n.metadata?.id).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let n=this._peer.connections[t];if(!!n)if(Array.isArray(n))for(let i of n)!i||i.send(e);else console.warn(n)}}}};var rT="wss://needle-tiny-starter.glitch.me/socket",bs=!!be("debugnet"),Gy=!!(bs||be("debugowner"));var vl=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Gy&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0,i=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):i()},100)};i()})}requestOwnership(){return Gy&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Gy&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Gy&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var Wy=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Vy),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return bs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),bs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,n=2){if(t===null&&(t={}),n===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){bs&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let n in this._defaultMessagesBuffer){let i=this._defaultMessagesBuffer[n];if(e<=1){this.sendWithWebsocket(i.key,i.value,3);break}let s=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&bs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}connect(){if(this.connected)return;bs&&console.log("connecting");let t=K.findObjectOfType(ys,this.context,!1)?.getWebsocketUrl();t&&(rT=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+rT);let e=new TO.WebsocketBuilder(rT).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,n)=>{console.error(t,n)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}let i=JSON.parse(n);if(Array.isArray(i))for(let s of i)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(i);return}catch{bs&&n==="pong"&&console.log("<<",n)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var n=new Uint8Array(t);let i=new Jr(n),s=i.getBufferIdentifier(),r=this._listenersBinary[s],a=EO(i),l=SO(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;let c=a??i;for(let h of r)h(c)}handleIncomingStringMessage(e){if(bs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.log("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(bs&&console.log(e),e){this._isInRoom=!0;let r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),bs&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let r=e.data;this._currentInRoom.push(r.userId),bs&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(console.log(r.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),bs&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let i of t)i(e.data);let n=e.data;n&&(this._state[n.guid]=n)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=1){if(!this._ws){let s=this._waitingForSocket[n]||[];s.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=s;return}let i=JSON.stringify(this.toMessage(e,t));bs&&console.log(">>",e),this._ws.send(i)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let n of t)n();t.length=0}}};import{OrbitControls as _5}from"three/examples/jsm/controls/OrbitControls";var Jo=class extends le{constraintActive=!0;locked=!1;sources=[]};re([se(Fe)],Jo.prototype,"sources",2);var xs=class extends le{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;awake(){this._lookTargetPosition=new O}onEnable(){this._enableTime=this.context.time.time;let t=K.getComponent(this.gameObject,Bt)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new _5(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan)}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}start(){if(this._controls){let e=K.getComponent(this.gameObject,Bt);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new O(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Zn;e.screenPoint=new _e(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&K.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=ot(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};re([se(Jo)],xs.prototype,"lookAtConstraint",2);var gn=class extends q{alpha=1;constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"&&(this.alpha=e.alpha),typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let n=e;return n.alpha&&(this.alpha=gt.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};var CO=be("debugcam"),Bt=class extends le{get aspect(){return this._cam instanceof Wt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof Wt&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera()}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){CO&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Wt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new Ka(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.context.isInXR&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this.backgroundColor){let e=this.backgroundColor.alpha;this.context.isInXR&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this.backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new oT(this)),this._skybox.enable()}};re([se()],Bt.prototype,"fieldOfView",1),re([se()],Bt.prototype,"nearClipPlane",1),re([se()],Bt.prototype,"farClipPlane",1),re([se()],Bt.prototype,"clearFlags",1),re([se()],Bt.prototype,"orthographic",2),re([se()],Bt.prototype,"orthographicSize",2),re([se()],Bt.prototype,"ARBackgroundAlpha",2),re([se(gn)],Bt.prototype,"backgroundColor",1);var oT=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(CO&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Ct,this._skybox.mapping=Ws,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function RO(o){let e="created/implictly",t=new Fe;o.add(t);let n=K.addNewComponent(t,Bt,!1);n.sourceId=e;let i=K.addNewComponent(t,xs,!1);return i.sourceId=e,n}import{EffectComposer as GY}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as WY}from"three/examples/jsm/postprocessing/RenderPass";var Xd=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,n,i){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=n,this._speed=i}};function AO(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Hm.generateUUID(),index:-1,clip:new br(o,1,[])}}var aT=class{_types={};add(e,t){let n=this._types[e];n===void 0?this._types[e]=t:n!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},pe=new aT;var Qr=be("gizmos"),Nn=be("debugextension");var Xy=be("debugresolvedependencies"),b5=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function qd(o,e){Xy&&console.log(o,e);let t=[];cT(b5,o,e,t);let n=await Promise.all(t);return typeof e=="string"&&n.length===1?n[0]:n}function cT(o,e,t,n){if(typeof t=="object"&&t!==void 0&&t!==null)for(let i of Object.keys(t)){let s=t[i];if(typeof s=="string"){let r=PO(e,s);if(r!==null)typeof r.then=="function"?n.push(r.then(a=>t[i]=a)):t[i]=r;else for(let a of o){let l=hT(a.prefix,s);if(l>=0){Xy&&console.log(a,l,a.dependencyName),n.push(e?.getDependency(a.dependencyName,l).then(c=>(t[i]=c,c)));break}}}else if(Array.isArray(s))for(let r=0;r<s.length;r++){let a=s[r],l=PO(e,a);if(l!==null){typeof l.then=="function"?n.push(l.then(c=>s[r]=c)):s[r]=l;continue}for(let c of o){let h=hT(c.prefix,a);if(h>=0){Xy&&console.log(c,h,c.dependencyName),n.push(e?.getDependency(c.dependencyName,h).then(u=>s[r]=u));break}}typeof a=="object"&&cT(o,e,a,n)}else typeof s=="object"&&cT(o,e,s,n)}else typeof t=="string"&&x5(o,e,t,n)}var lT="extensions/";function PO(o,e){if(o&&o.plugins&&typeof e=="string"&&e.startsWith(lT)){let t=e.substring(lT.length),n=t.indexOf("/");n>=0&&(t=t.substring(0,n));let i=o.plugins[t];if(Nn&&console.log(t,i),typeof i?.resolve=="function"){let s=e.substring(lT.length+t.length+1);return i.resolve(o,s)}}return null}function x5(o,e,t,n){for(let i of o){let s=hT(i.prefix,t);if(s>=0)return Xy&&console.log(i,s,i.dependencyName),n.push(e?.getDependency(i.dependencyName,s).then(r=>r)),!0}return!1}function hT(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),n=Number.parseInt(t);if(n>=0)return n}return-1}var uT="NEEDLE_persistent_assets";function IO(o){return o?.___persistentAsset===!0}var qy=class{get name(){return uT}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[uT];if(!t)return;Nn&&console.log(t);let n=new Array;for(let i of t?.assets){let s=qd(this.parser,i);s&&n.push(s)}await Promise.all(n)}resolve(e,t){let n=Number.parseInt(t);if(n>=0){Nn&&console.log(t);let i=e.json.extensions[uT];if(i){let s=i?.assets[n];if(s&&typeof s=="object"){s.___persistentAsset=!0;let r=s.__type;if(r){let a=pe.get(r)}}return s}}return null}};var vh=be("debugserializer"),dT=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}vh&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){vh&&console.log("invalid type");return}let n=e.name??e.constructor?.name;if(!n){vh&&console.log("invalid name",n);return}let i=this.getSerializer(n);if(i!==void 0)return vh&&console.log("FOUND "+n,e.name,e.constructor.name,i,this.typeMap),i;let s=Object.getPrototypeOf(e);if(!(s.prototype||s.constructor)){vh&&console.warn("No prototype for "+n,e,e.name,e.prototype,e.constructor.name);return}let a=s.prototype??s.constructor;if(a!==e){let l=this.getSerializerForConstructor(a,++t);if(l){vh&&console.log("FOUND "+a.constructor.name,a.name,a,l);let c=a.name??a.constructor.name;c==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,l):this.register(c,l)}return l}}},Zy=new dT,Qo=class{constructor(e){if(Array.isArray(e))for(let t of e)Zy.register(t.name,this);else Zy.register(e.name,this)}},Yd=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function pT(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let n={};for(let i in t){let s=o[i];if(s!=null&&typeof s=="object"){let r=Zy.getSerializerForConstructor(s);if(r){n[i]=r.onSerialize(s,e);continue}}n[i]=s}return n.name=o.constructor.name,typeof o.guid=="string"&&(n.guid=o.guid),n}var Yy=[];function LO(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return LO(t,e)}function tg(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let s=o.onBeforeDeserialize(e,t);if(typeof s=="boolean")return s}let n=LO(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),n)for(let s in n){let r=n[s],a=e[s];if(t.path=s,r===null)o[s]=a;else{let l=function(c){let u=c.type;return u?fT(a,u,t,void 0,o[s]):fT(a,c,t,void 0,o[s])};var i=l;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(s,a,t)===!0)continue;if(Array.isArray(r))for(let c=0;c<r.length;c++){let h=r[c],u=l(h);if(u!==void 0||c===r.length-1){o[s]=u;break}}else o[s]=l(r);Yy.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(s,a,t)}}w5(o,e)}return o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}function w5(o,e){for(let n of Object.keys(e)){let i=e[n];if(typeof i=="object"&&i!==null&&i!==void 0){let s=o[n];if(!s){vh&&console.log(n,"is undefined on",o);continue}for(let r of Object.keys(i))s[r]===void 0&&t(i[r])&&!t(s)&&(s[r]=i[r])}}function t(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}}function fT(o,e,t,n,i){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,i),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(!s&&i instanceof r)return i;if(i&&typeof i=="object"&&IO(i)){if(i.__concreteInstance)return i.__concreteInstance;let h=i;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&tg(h,o,t),i&&r!==void 0)try{let u=new r;Nn&&console.log("Create concrete instance for persistent asset",i,"instance:",u),ng(u,i),i.__concreteInstance=u,i=u}catch(u){console.error("Error creating instance or creating values on instance",u,i,r)}return i}if(n||(n={serializer:Zy.getSerializerForConstructor(r)}),Array.isArray(o)){let h=[];for(let u=0;u<o.length;u++){let d=o[u],f=fT(d,e,t,n,d);h.push(f)}return h}let a=n.serializer;if(a)return a.onDeserialize(o,t);let l;o&&(o.isMaterial||o.isTexture||o.isObject3D)?l=o:l=new r(...E5(o));let c=l;return c.$serializedTypes&&tg(c,o,t),l}function E5(o){if(Yy.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))Yy.push(o[e]);return Yy}function ng(o,e){if(e==null||o==null)return;let t=!1;for(let n of Object.keys(e)){let i=S5(o,n);t&&i===void 0||(!i||i.writable===!0||i?.set!==void 0)&&(o[n]=e[n])}}function S5(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var yl=be("debuganimatorcontroller"),mT=be("debugrootmotion"),Cr=class{Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let r=this.model.layers[t].stateMachine;for(let a of r.states)if(a.name===e||a.hash===e){yl&&console.log("transition to ",a),this.transitionTo(a,i,n);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??!1}SetFloat(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetInteger(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetTrigger(e){yl&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e)return n;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new Uo(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=zm(this.model,(n,i,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||s?.constructor?.name==="AnimationAction"||s.tracks!==void 0));return console.assert(e!==this.model),new Cr(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,yl&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],n=t.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{let i=n.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(yl&&console.debug("REMOVE",t.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,n=t.motion.action,i=0;for(let r of t.transitions){if(++i,!r.hasExitTime&&r.conditions.length<=0)continue;let a=!0;for(let l of r.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(!!a){yl&&a&&console.log("All conditions are met",r.conditions,n);for(let l of r.conditions){let c=this.model.parameters.find(h=>h.name===l.parameter);c?.type===9&&(c.value=!1)}if(n){let l=t.motion.clip.duration,c=l<=0?1:n.time/l;if(!r.hasExitTime||c>=r.exitTime&&n.time>=n.getClip().duration){n.clampWhenFinished=!0,yl&&(console.log("transition to "+r.destinationState,r),console.log(n.time,r.exitTime)),this.transitionTo(r.destinationState,r.duration,r.offset);return}}else{this.transitionTo(r.destinationState,r.duration,r.offset);return}break}}let s=!1;if(t.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&t&&!e&&n&&this.animator&&t.behaviours){let r=n?.getClip().duration,a=n.time/r,l=new Xd(this._activeState,a,r,this._speed);for(let c of t.behaviours)c.instance&&c.instance.onStateUpdate?.call(c.instance,this.animator,l,0)}}transitionTo(e,t,n){if(!this.animator)return;let i=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[i].stateMachine.defaultState),e=this.model.layers[i].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let s=this._activeState===e;if(s){let c=e.motion;!c.action_loopback&&c.clip&&(this._mixer.uncacheAction(c.clip,this.animator.gameObject),c.action_loopback=this.createAction(c.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let c=this._activeState?.motion.clip.duration,h=this._activeState.motion.action.time/c,u=new Xd(this._activeState,h,c,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateExit?.call(d.instance,this.animator,u,i)}let r=this._activeState?.motion.action;r&&r.fadeOut(t),s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);let a=this._activeState;this._activeState=e;let l=e.motion?.action;if(l){n=Math.max(0,Math.min(1,n)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,l.enabled=!0;let c=e.motion.clip.duration;if(l.time=n*c,l.clampWhenFinished=!0,l.setLoop(Pd,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let h=new Xd(e,n,c,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,h,i)}}else console.warn("No action",e.motion,this);yl&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new gT(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let n=t.stateMachine;for(let i=0;i<n.states.length;i++){let s=n.states[i];if(s.motion||(s.motion=AO(s.name)),this.animator&&s.motion.clips){let r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);s.motion.clip=r?.clip}if(!s.motion.clip){let r=new br;s.motion.clip=r}if(s.motion?.clip){let r=s.motion.clip,a=this.createAction(r);s.motion.action=a}if(s.behaviours&&Array.isArray(s.behaviours))for(let r of s.behaviours){if(!r?.typeName)continue;let a=pe.get(r.typeName),l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,ng(l,r.properties),r.instance=l),yl&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let n=0;n<t.states.length;n++){let i=t.states[n];i?.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}rootMotionHandler},Jy=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let n=e,i=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;let r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}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}},Mn=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new O;rotationChange=new Oe;constructor(e,t,n,i,s){if(this.context=e,this.root=t,this.clip=n,Mn.firstKeyframeRotation[n.uuid]||(Mn.firstKeyframeRotation[n.uuid]=new Oe),s){let r=s.values;Mn.firstKeyframeRotation[n.uuid].set(r[0],r[1],r[2],r[3])}Mn.spaceRotation[n.uuid]||(Mn.spaceRotation[n.uuid]=new Oe),Mn.effectiveSpaceRotation[n.uuid]||(Mn.effectiveSpaceRotation[n.uuid]=new Oe),Mn.clipOffsetRotation[n.uuid]=new Oe,s&&Mn.clipOffsetRotation[n.uuid].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(n,i),this.handleRotation(n,s)}onStart(e){if(e.getClip()!==this.clip)return;let t=Mn.lastObjRotation[this.root.uuid];Mn.spaceRotation[this.clip.uuid].copy(t);{let n=new Lt().setFromQuaternion(t);console.log("START",this.clip.name,gt.toDegrees(n.y))}}getClipRotationOffset(){return Mn.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let n=this.root;mT&&n.add(new xr),Mn.lastObjPosition[n.uuid]||(Mn.lastObjPosition[n.uuid]=new O);let i=new O,s=new O,r=0;this.positionWrapper=new Jy(t,(a,l)=>{let c=this.action.getEffectiveWeight();if(mT&&n.position.length()>8&&n.position.set(0,n.position.y,0),a>r){i.set(l[0],l[1],l[2]),i.sub(s),i.multiplyScalar(c),i.applyQuaternion(this.getClipRotationOffset());let h=this.clip.uuid;i.applyQuaternion(Mn.spaceRotation[h]),this.positionChange.copy(i)}return s.fromArray(l),r=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(mT){let a=t.values,l=new Lt().setFromQuaternion(new Oe(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",gt.toDegrees(l.y));let c=t.values.length-4,h=new Oe().set(a[c],a[c+1],a[c+2],a[c+3]),u=new Lt().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",gt.toDegrees(u.y))}let n=this.root;Mn.lastObjRotation[n.uuid]||(Mn.lastObjRotation[n.uuid]=new Oe);let i=0,s=new Oe,r=new Oe;this.rotationWrapper=new Jy(t,(a,l)=>(a>i&&(r.set(l[0],l[1],l[2],l[3]),s.invert(),r.multiply(s),this.rotationChange.copy(r)),s.fromArray(l),i=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Mn.identityQuaternion,1-e)}},Tr=Mn;Se(Tr,"lastObjPosition",{}),Se(Tr,"lastObjRotation",{}),Se(Tr,"firstKeyframeRotation",{}),Se(Tr,"spaceRotation",{}),Se(Tr,"effectiveSpaceRotation",{}),Se(Tr,"clipOffsetRotation",{}),Se(Tr,"identityQuaternion",new Oe);var gT=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,n){this.root=t;let i="";t&&"name"in t&&(i=t.name);let s=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),a=new Tr(this.controller.context,t,n,s,r);this.handler.push(a);let l=e.clipAction(n);return a.action=l,l}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new O;summedRotation=new Oe;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Tr.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let n=e.tracks;for(let i of n)if(i.name.endsWith(t))return i;return null}};var M5=be("debuganimator"),ws=class extends le{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Cr?this._animatorController=e:this._animatorController=new Cr(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){this.runtimeAnimatorController?.Play(e,t,n,i)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=gt.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=gt.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}M5&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};re([se()],ws.prototype,"applyRootMotion",2),re([se()],ws.prototype,"hasRootMotion",2),re([se()],ws.prototype,"keepAnimatorControllerStateOnDisable",2),re([se()],ws.prototype,"runtimeAnimatorController",1);var Rr=class extends le{playAutomatically=!0;randomStartTime=!0;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&Qt.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let n=e;if(typeof e=="number"){if(e>=this.animations.length)return;n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(s=>s.name===e));if(!n){console.error("Could not find clip",e);return}for(let s of this.actions)if(s.getClip()===n)return this.internalOnPlay(s,t);let i=this.mixer.clipAction(n);return this.actions.push(i),this.internalOnPlay(i,t)}internalOnPlay(e,t){var n=this.currentAction;if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let r=this.tryFindHandle(e);if(r)return r.getPromise()}let i=t?.exclusive??!0;t?.fadeDuration?(i&&n?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):i&&n?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Z0:Pd),e.play();let s=new vT(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Uo(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};re([se()],Rr.prototype,"playAutomatically",2),re([se()],Rr.prototype,"randomStartTime",2);var vT=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,n,i){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=i,this._options=n}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as BF}from"three/examples/jsm/loaders/GLTFLoader.js";var Zd=class extends le{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new O}update(){if(!this.from||!this.to)return;let e=ot(this.from).clone(),t=ot(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),kt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ot(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};var $r=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};re([se()],$r.prototype,"time",2),re([se()],$r.prototype,"value",2),re([se()],$r.prototype,"inTangent",2),re([se()],$r.prototype,"inWeight",2),re([se()],$r.prototype,"outTangent",2),re([se()],$r.prototype,"outWeight",2),re([se()],$r.prototype,"weightedMode",2);var yh=class{keys;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;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return gt.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};re([se($r)],yh.prototype,"keys",2);import{PositionalAudioHelper as T5}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Qy=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var es=be("debugaudio");var Jn=class extends le{static get userInteractionRegistered(){return Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction()),Jn._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!Jn._userInteractionRegistered){Jn._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(es&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Jn._userInteractionRegistered){let e=K.getComponent(this.context.mainCamera,Ar)??K.findObjectOfType(Ar,this.context);e?.listener&&(this.sound=new Lm(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new rl,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Jn._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Jn._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Jn._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){es&&console.log("audio buffer loaded"),Jn.registerWaitForAllowAudio(()=>{es&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),es&&console.log(this.name,this.shouldPlay,Jn.userInteractionRegistered,this),this.shouldPlay&&Jn._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(es&&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:break}this.spatialBlend>0?es&&!this.helper&&(this.helper=new T5(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(es&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new rl),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){es&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,es&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,es&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,es&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,es&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},$t=Jn;Se($t,"_didCallBeginWaitForUserInteraction",!1),Se($t,"callbacks",[]),Se($t,"_userInteractionRegistered",!1),re([se()],$t.prototype,"clip",2),re([se()],$t.prototype,"playOnAwake",2),re([se()],$t.prototype,"loop",1),re([se()],$t.prototype,"spatialBlend",1),re([se()],$t.prototype,"minDistance",1),re([se()],$t.prototype,"maxDistance",1),re([se()],$t.prototype,"volume",1),re([se()],$t.prototype,"rollOffMode",2);var Ar=class extends le{get listener(){return this._listener==null&&(this._listener=new Kc),this._listener}_listener=null;awake(){$t.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=K.getComponentInParent(this.gameObject,Bt);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as A5}from"three/examples/jsm/loaders/GLTFLoader";var zO=Lu(HO(),1),$y=class{success;filename;hash;size;url;constructor(e,t,n,i){this.success=e,this.filename=t,this.hash=n,this.size=i}};async function VO(o,e){let t=await o.arrayBuffer(),n=GO(t),i=o.name.split(".").pop(),s=n+"."+i,r=o.name.split(".").shift();console.assert(r!==void 0);let a={alias:r,filename:s},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",n),new $y(!0,s,n,o.size);console.log("begin uploading file",r,o.size);let h=new FormData;h.append("file",o);let u={};u.filesize=o.size,r&&(u.alias=r);let f=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===n,"hash sum did not match","received:",f.hash_sum,"expected:",n),f.success&&console.log("successfully uploaded",n,f.id);let g=new $y(f.success,s,n,o.size);return g.url=e,g}function GO(o){return(0,zO.default)(new Uint8Array(o))}async function Ky(o,e,t,n,i=!1){try{let s=await fetch(n+"/download/file",{method:"POST",body:o});if(s.status!==200)return console.error("download failed",s),null;let r=await s.blob(),a=await r.arrayBuffer();i||console.assert(r.size===t,"size mismatch","expected:",t,"got:",r.size);let l=GO(a);return i||console.assert(l===e,"hash mismatch, downloaded file is invalid"),r.arrayBuffer()}catch(s){console.error(s)}return null}async function WO(o,e){let t=await fetch(o),n=t.body?.getReader(),i=t.headers.get("Content-Length"),s=i?parseInt(i):0;if(!n)return null;let r=0,a=[];for(;;){let{done:h,value:u}=await n.read();if(u&&(a.push(u),r+=u.length,e.call(null,new ProgressEvent("progress",{loaded:r,total:s}))),h)break}let l=new Uint8Array(r),c=0;for(let h of a)l.set(h,c),c+=h.length;return l}var ig=be("debugavatar"),_h=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(s=>s.layers.set(2))}assignRandomColors(){$o.assignRandomPlayerColors(this)}},$o=class{avatarRegistryUrl=null;avatarModelCache=new Map;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let s=new hn;n=K.instantiate(cl(t,e.scene),s)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.assignRandomColors(),i.isValid?(ig&&console.log("[Custom Avatar] valid config",t,ig?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,ig?i:""),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(ig&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),s=null;if(i.ok){let a=await i.blob();a&&(s=await a.arrayBuffer())}return!s&&(s=await Ky(t,t,0,"no url here go away",!0),!s)?null:(await Jd(e,s,null,0))?.scene??null}let n=new A5;return ph(n,e),new Promise((i,s)=>{let r=this.avatarRegistryUrl+"/"+t;n.load(r,async a=>{await e_(e,r,a),i(a.scene)},a=>{ig&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,"head"),s=this.findAvatarPart(n,"left"),r=this.findAvatarPart(n,"right");if(!i){i=t;let l=new O;new On().setFromObject(i).getSize(l);let c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&i.scale.multiplyScalar(1/c*.3)}return new _h(t,i,s,r)}findAvatarPart(e,t){for(let n of e.children)if(n.name.toLowerCase().indexOf(t)>-1)return n;return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}static assignRandomPlayerColors(e){let t=new Map;function n(i){if(i.type==="Mesh"){let s=i,r=s.material;if(r&&r.name){if(t.has(r.uuid)){let a=t.get(r.uuid);a&&(s.material=a);return}if(r.name.endsWith("_playercolor")||r.name.endsWith("_player_color2")){let a=r.uuid;s.material=r.clone(),s.material.color=new q(Math.random(),Math.random(),Math.random()),t.set(a,s.material)}}}}e.head&&e.head.traverse(n),e.leftHand&&e.leftHand.traverse(n),e.rigthHand&&e.rigthHand.traverse(n)}};var Ko=class extends le{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Qr)return;this._axes||(this._axes=new xr(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};re([se()],Ko.prototype,"length",2),re([se()],Ko.prototype,"depthTest",2),re([se()],Ko.prototype,"isGizmo",2);var Qd=class extends le{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=ot(this.to).clone(),t=ot(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let s=t.clone();s.add(e),s.multiplyScalar(.5);let r=ot(this.hint).clone();r.sub(s);let a=new O;a.crossVectors(r,i),a.crossVectors(i,a),a.normalize();let l=n*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),u=a.clone();u.multiplyScalar(h),u.add(s),kt(this.gameObject,u);let d=s.clone();d.sub(a),this.gameObject.lookAt(d)}};var P5=new si(1,1,1);function t_(o=null){let e=new q(o??14540253),t=new yd(P5);return new Qi(t,new Fn({color:e}))}var L5=be("gizmos"),n_=class extends le{box=null;testBox=new On;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new On),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=ot(e,n_._position),n=QL(e,n_._size);this.testBox.setFromCenterAndSize(t,n)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new On),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new O(0,0,0),new O(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!L5&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=t_(e),this.gameObject.add(this._helper)}}},ts=n_;Se(ts,"_position",new O),Se(ts,"_size",new O(.01,.01,.01));function $d(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?mi:ps,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?mi:ps,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let n of o.children)$d(n,e)}function Kd(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let n=Proxy.revocable(o[e],{set(r,a,l,c){let h=r[a],u=Reflect.set(r,a,l,c);return t(l,h),u}}),i=n.revoke,s=o[e];return n.revoke=()=>{o[e]=s,i()},o[e]=n.proxy,n}function XO(o,e,t=3){let n=o.__scheduledActions;n||(n=o.__scheduledActions={});let i=e.name;n[t]||(n[t]={});let s=n[t];if(s[i])return;function*a(){e?.call(o),s[i]=null}let l=o.startCoroutine(a(),t);s[i]=l}var ef=class extends le{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?qe.KINEMATIC:qe.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new O,this._smoothedVelocity=new O,this.lastWorldPosition=ot(this.gameObject).clone()}start(){this.setBodyFromGameObject()}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this.transformProxy=Kd(this.gameObject.matrix,"elements",()=>{this.context.physics.isUpdating||(this.dirty=!0)})}onDisable(){this.transformProxy?.revoke(),this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}earlyUpdate(){this.dirty&&this.setBodyFromGameObject()}onBeforeRender(){this.updateVelocity()}initialize(){if(this._body)return;let e=new Py;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new H(e.x,e.y,e.z),t?new H(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?ef.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):ef.tempPosition.set(0,0,0)}setVelocity(e,t,n){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=n/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,n){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=n/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let n=this.worldQuaternion;if(this.body.quaternion.set(n.x,n.y,n.z,n.w),e){ef.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(ef.copyVector3,this.context.time.deltaTime/.1);let i=this._smoothedVelocity;this.body.velocity.x=i.x,this.body.velocity.y=i.y,this.body.velocity.z=i.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=ot(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},Xt=ef;Se(Xt,"tempPosition",new O),Se(Xt,"copyVector3",new O),re([se()],Xt.prototype,"mass",2),re([se()],Xt.prototype,"isKinematic",1),re([se()],Xt.prototype,"drag",2),re([se()],Xt.prototype,"angularDrag",2),re([se()],Xt.prototype,"detectCollision",2),re([se()],Xt.prototype,"sleepThreshold",2);var Kr=class extends le{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xt))}onDisable(){this._shape}};re([se(Xt)],Kr.prototype,"attachedRigidbody",2),re([se()],Kr.prototype,"isTrigger",2);var _l=class extends Kr{radius=.5;center=new O(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};re([se()],_l.prototype,"radius",2),re([se(O)],_l.prototype,"center",2);var bl=class extends Kr{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};re([se(O)],bl.prototype,"size",2),re([se(O)],bl.prototype,"center",2);var tf=class{};var qs=class extends le{canGrab=!0;onPointerClick(e){}},Ys=class extends le{isUsed=!0;usedBy=null};var bh=class extends ts{},nf=class extends le{deleteBoxes=[];awake(){this.deleteBoxes=K.findObjectsOfType(bh,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(K.getComponentInParent(this.gameObject,Ys)||kd(this.gameObject,this.context.connection))}}};var xh=class extends le{visibleOn;onEnable(){this.apply()}apply(){this.test()||K.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:O5()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};re([se()],xh.prototype,"visibleOn",2);var i_;function O5(){if(i_===!0||i_===!1)return i_;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),i_=o,o}var Tn=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,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(e,t,n,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var sf=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Tn).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Tn).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Tn).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Zs=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new sf).__init(this.bb_pos+t,this.bb):null}dontSave(){let 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 xl=be("debugsync"),rf="STRS";jd(rf,Zs.getRootAsSyncedTransformModel);var eo=new _s;function bT(o,e,t=!0){eo.clear();let n=eo.createString(o);Zs.startSyncedTransformModel(eo),Zs.addGuid(eo,n),Zs.addFast(eo,t);let i=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;Zs.addTransform(eo,sf.createTransform(eo,i.x,i.y,i.z,s.x,s.y,s.z,r.x,r.y,r.z));let a=Zs.endSyncedTransformModel(eo);return eo.finish(a,rf),eo.asUint8Array()}var bi=class extends le{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){xl&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){xl&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new O,this._targetRotation=new Oe,this.lastWorldPos=new O,this.lastWorldRotation=new Oe,this.rb=K.getComponentInChildren(this.gameObject,Xt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new vl(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(rf,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&s2(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(rf,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Lt;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){xl&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){Qt.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&$L(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){xl&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let s=e.distanceTo(this.lastWorldPos),r=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(s>a||r>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(xl&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qt.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let r=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){let l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&Qt.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(xl&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new O(0,0,0))>1e3&&(xl&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){xl&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let s=bT(this.guid,this,!!i);this.context.connection.sendBinary(s)}}};var r_=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var l=document.createElement("div");l.style.display="none",document.body.appendChild(l);var c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("width",38),c.setAttribute("height",38),c.style.position="absolute",c.style.right="20px",c.style.top="20px",c.addEventListener("click",function(){u.end()}),l.appendChild(c);var h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),h.setAttribute("stroke","#fff"),h.setAttribute("stroke-width",2),c.appendChild(h),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:l}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function d(g){g.addEventListener("end",f),await e.xr.setSession(g),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=g}function f(){u.removeEventListener("end",f),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(d):u.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="AR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(l){l?i():r()}).catch(r),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}};var o_=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let l=null;async function c(u){u.addEventListener("end",h),await e.xr.setSession(u),n.textContent="EXIT VR",l=u}function h(){l.removeEventListener("end",h),n.textContent="ENTER VR",l=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(l===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(c)}else l.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="VR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?i():r(),o_.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),o_.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},of=o_;Se(of,"xrSessionIsGranted",!1);of.registerSessionGrantedListener();var qO=Lu(tT(),1);var af="noVoip",ns=be("debugvoip"),k5=be("voip");var xT=class{id;constructor(e){this.id=e}};var wT=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){ns&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await Vi.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ns&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ns&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ns&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ns&&console.log("call closed",e)}},ET=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,$t.userInteractionRegistered||ns&&console.log("Incoming call, waiting for user interaction before opening audio"),$t.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ns&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Kc;this.audio=new ol(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let s of i)if(s.label==="Speakerphone"){n.sinkId=s.deviceId;break}}}),ns&&console.log("call is setup, you should hear something now"),this.analyzer=new Om(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Vi=class extends le{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(be(af)){console.log("VOIP is disabled by url parameter: "+af);return}if(this.requireParam&&!k5){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new qO.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new wT(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];ns&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){ns&&console.log("Peer connection established and received id"),this.model=new xT(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ns&&console.log("CONNECTION",t),t.on("data",function(n){ns&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,s=this.currentIncomingCalls[n];if(s&&s.close(),ns&&console.log("received call"),await Vi.HasMicrophonePermissions()){let r=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(r)}else e.answer(null);this.currentIncomingCalls[n]=new ET(this,this.gameObject,e),e.on("stream",r=>{ns&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(r)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var lf=be("debugflags");var ST=class{Mask=17;Has(e){let t=this.Mask&e;return lf&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Cn.Apply()}Enable(e){this.Mask|=e,Cn.Apply()}Disable(e){this.Mask&=~e,Cn.Apply()}Toggle(e){this.Mask^=e,Cn.Apply()}EnableAll(){this.Mask=-1,Cn.Apply()}DisableAll(){this.Mask=0,Cn.Apply()}},Es=ST;Se(Es,"Global",new ST);var to=class extends le{static Apply(){for(let e of this.registry)e.UpdateVisible(Es.Global)}awake(){to.registry.push(this)}onEnable(){to.firstApply||(to.firstApply=!0,to.Apply())}onDestroy(){let e=to.registry.indexOf(this);e>=0&&to.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),lf&&console.log(n),to.buffer.Mask=n,e=to.buffer);let i=e;if(i?(lf&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(lf&&console.log("use global mask"),Es.Global.Has(this.visibleIn)),t!==void 0)if(t)lf&&console.trace("is visible",this.name,this.gameObject.uuid),K.setActive(this.gameObject,!0);else{if(lf&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Cn=to;Se(Cn,"registry",[]),Se(Cn,"firstApply"),Se(Cn,"buffer",new Es);import{XRControllerModelFactory as F5}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as B5}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as N5}from"three/examples/jsm/webxr/OculusHandPointerModel.js";var wl=be("debugavatar"),ea=class extends le{static onAvatarMarkerCreated(e){return ea._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ea._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ea.instances.push(this),wl&&console.log(this);for(let e of ea._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ea.instances.splice(ea.instances.indexOf(this),1);for(let e of ea._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):K.setActive(this.avatar,e))}},sn=ea;Se(sn,"instances",[]),Se(sn,"_onNewAvatarMarkerAdded",[]),Se(sn,"_onAvatarMarkerDestroyed",[]);var sg=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new O(1,1,1);handLeftScale=new O(1,1,1);handRightScale=new O(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new Fe;_handLeftTarget=new Fe;_handRightTarget=new Fe;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){this._canInterpolate=!0;let n=this.isLocalAvatar?this.head:this._headTarget;if(n.position.set(e.position.x,e.position.y,e.position.z),n.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.headScale),this.handLeft){let i=this.isLocalAvatar?this.handLeft:this._handLeftTarget;i.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),i.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),i.quaternion.multiply(sg.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handLeftScale)}if(this.handRight){let i=this.isLocalAvatar?this.handRight:this._handRightTarget;i.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),i.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),i.quaternion.multiply(sg.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handRightScale)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){wl&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&vn.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&K.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(wl&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&vn.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;K.setActive(i,!1),e=K.instantiate(i),K.setActive(e,!0)}wl&&console.log(e);let n=await sg.loader.getOrCreateNewAvatarInstance(this.context,e);if(wl&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=K.addNewComponent(this.root,sn),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&vn.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...K.getComponentsInChildren(this.root,Cn)),this.flags.length<=0&&this.head){let i=K.addNewComponent(this.head,Cn);i.visibleIn=20,this.flags.push(i),wl&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return wl&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return wl&&console.warn("build avatar failed"),!1}},Js=sg;Se(Js,"loader",new $o),Se(Js,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI));var vn=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??bt.Current?.time.time;return}}}};Se(vn,"Pois",[]),Se(vn,"LastChangeTime",0);var MT=class{guid;position=new O},ta=class extends le{set controlledTarget(e){this.target=e;let t=pe.get("MoveRandom");if(t&&this.target){let n=K.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new MT;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=K.getComponentInParent(this.gameObject,sn),this.avatar){let e=K.getComponentInParent(this.gameObject,sn);this._model=new vl(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&kt(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(vn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=vn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=ot(this._currentTargetObject);kt(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;let t=vn.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};var wh=class extends le{},Qn=class extends le{static CreateRaycastLine(){let e=new Ji(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Ni(.5,22,22),t=new Jt({color:this.raycastColor}),n=new _t(e,t);return n.visible=!1,n.layers.set(1),n}static Create(e,t,n,i){let s=n?K.addNewComponent(n,Qn,!1):new Qn;s.webXR=e,s.index=t,s.type=i;let r=e.context;return s.controller=r.renderer.xr.getController(t),s.controllerGrip=r.renderer.xr.getControllerGrip(t),s.controllerModel=this.Factory.createControllerModel(s.controller),s.controllerGrip.add(s.controllerModel),s.hand=r.renderer.xr.getHand(t),s.hand.add(new B5(s.hand)),s.hand.traverse(a=>a.layers.set(2)),s.handPointerModel=new N5(s.hand,s.controller),s.controller.addEventListener("connected",a=>{s.setControllerLayers(s.controllerModel,2),s.setControllerLayers(s.controllerGrip,2),setTimeout(()=>{s.setControllerLayers(s.controllerGrip,2)},1e3)}),s.hand.addEventListener("connected",a=>{if(a.data.hand){e.Rig&&e.Rig.add(s.hand),s.type=0,s.handPointerModel.traverse(h=>h.layers.set(2)),s.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let c=s.hand.joints;if(c)for(let h of Object.keys(c)){let u=c[h];u.parent||s.hand.add(u)}}}),s}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Oe),cn(e).multiply(this._wristQuaternion.setFromEuler(new Lt(-Math.PI/4,0,0)))):null}movementVector=new O;worldRot=new Oe;joystick=new _e;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Qn.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Qn.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this.hand.add(this.handPointerModel),console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Oe;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Qn.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(cn(this.controller),this.useSmoothing?t:1);let n=ot(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,kt(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let r=this.getWristQuaternion();r&&this.rayRotation.copy(r)}Bn(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Bn(this.raycastLine,this.rayRotation),kt(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Qn.MovementSpeedFactor,s=2,r=gt.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,l=Math.pow(this.joystick.x,s);l*=a,l*=r;let c=this.joystick.y>0?1:-1,h=Math.pow(this.joystick.y,s);h*=c,l*=r,t.getWorldQuaternion(this.worldRot),this.movementVector.set(l,0,h),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(i*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,d=Math.abs(u);if(d<.4)this.didRotate=!1;else if(d>.5&&!this.didRotate){let f=u>0?-1:1;t.rotateY(gt.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5,s=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,r=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let l=t[a];if(a===4)if(l.pressed&&!this.didChangeScale){this.didChangeScale=!0;let c=this.webXR.Rig;if(c)if(s){s=!1,c.scale.set(1,1,1),r=1,Qn.MovementSpeedFactor=1;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance&&(h.far=Qn.PreviousCameraFarDistance)}else{s=!0,i=!0,r=.1,Qn.MovementSpeedFactor=r*2;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance=h.far,h.far/=r}}else l.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let l=a[0];if(s||this.isValidTeleportTarget(l.object)){let c=l.point;kt(e,c)}}}}else n<.1&&(this.didTeleport=!1);r!==null&&(e.scale.set(r,r,r),e.updateMatrixWorld())}isValidTeleportTarget(e){return K.getComponentInParent(e,wh)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Qn.raycastColor:i.color=Qn.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=gt.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),e&&e.length>0)for(let n of e){let i=n.object;if(!this.testIsVisible(i)){console.log("not visible");continue}this.lastSelectStartObject=i;let s={selected:i,grab:i},r=Qn.eventSubs["select-start"];if(r&&r.length>0)for(let a of r)a(this,s);s.grab!==i&&console.log("Grabbed object changed","original",i,"new",s.grab),s.grab&&(this.grabbed=is.TryTake(this,s.grab,n,t));break}else{let n=Qn.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let s of n)s(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Qn.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?K.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new vr;return e.origin.copy(ot(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=ot(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Zn;return e.layerMask=new Fi,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},Vt=Qn;Se(Vt,"Factory",new F5),Se(Vt,"raycastColor",new q(.9,.3,.3)),Se(Vt,"raycastNoHitColor",new q(.6,.6,.6)),Se(Vt,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,0,-1)])),Se(Vt,"handModels",{}),Se(Vt,"eventSubs",{}),Se(Vt,"PreviousCameraFarDistance"),Se(Vt,"MovementSpeedFactor",1);var Gi=class{static AddEventListener(e,t){return Gi.Events[e]||(Gi.Events[e]=[]),Gi.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Gi.Events[e])return;let n=Gi.Events[e].indexOf(t);n>=0&&Gi.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let s=K.getComponentInParent(t,qs);if(!s)return console.warn("Prevented taking object that is not interactable",t),null;let r=t,a=K.getComponentInParent(t,bi);a&&(a.requestOwnership(),r=a.gameObject);for(let c of this.Current)if(c.selected===r)return c.controller===e||(c.free(),c.Take(e,r,t,a,s,n,i)),c;let l=new Gi;return l.Take(e,r,t,a,s,n,i),l}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,s,r,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let l={controller:e,take:t,hit:n,sync:i,interactable:s};Gi.Events.WillTake?.forEach(f=>f(this,l));let c=n;c?.material&&(this.originalMaterial=c.material,Array.isArray(c.material)||(c.material=c.material.clone(),c.material&&c.material.emissive&&(c.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=c,this.controller=e,this.interactable=s,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=K.addNewComponent(this.selected,Ys),this.rigidbodies=K.getComponentsInChildren(this.selected,Xt),ot(this.positionSource,this.lastControllerWorldPos);let h=()=>a?this.lastControllerWorldPos.clone():r.point.clone();this.grabDistance=h().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(h());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();cn(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let d=this.controller.webXR.Rig;return d&&this.rigPositionLastFrame.copy(ot(d)),vn.Add(e.context,this.selected),Gi.Register(this),this.sync&&(this.sync.fastMode=!0),Gi.Events.DidTake?.forEach(f=>f(this,l)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Gi.Events.WillFree?.forEach(i=>i(this,e)),vn.Remove(this.controller.context,this.selected),Gi.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Gi.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new O;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new O;localQuaternionToGrab=new Oe(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new O;controllerWorldPos=new O;lastControllerWorldPos=new O;controllerPosDelta=new O;totalChangeAlongDirection=0;rigPositionLastFrame=new O;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ot(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=ot(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new O),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Bn(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ot(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),kt(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});Qt.markDirty(this.selected,!0)}}},is=Gi;Se(is,"Events",{}),Se(is,"Current",[]);var Qs=class extends le{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,n){if(n&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new it().fromArray(n.transform.matrix).invert(),e){if(this.invertForward){let i=new it().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),Qt.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new it().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};re([se()],Qs.prototype,"invertForward",2),re([se()],Qs.prototype,"arScale",1);var El=class extends le{awake(){}};var Eh=be("debugaddressables"),a_=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},Wi=class{static getOrCreate(e,t,n){let i=ty(e,t);Eh&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",i);let s=n.addressables,r=s.findAssetReference(i);if(r)return r;let a=new Wi(i);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,l2(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Eh&&console.log("Unload",this.asset),this.asset.scene?K.destroy(this.asset.scene):K.destroy(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Eh&&console.log("Preload",this.uri);let e=await WO(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=bt.Current;this._rawBinary?(this._loading=Jd(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Eh&&console.log("Load async",this.uri),this._loading=Sh(t,this.uri,null,!0,i=>{this.raiseProgressEvent(i)}));let n=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(n),this._loading=void 0,n)return Vo(t),n.scene!==void 0&&(this.asset=n),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,n){let i=bt.Current;if(e||(e=i.scene),this.mustLoad&&await this.loadAssetAsync(),Eh&&console.log("Instantiate",this.uri,"parent:",e),this.asset){Eh&&console.log("Add to scene",this.asset);let s=e instanceof hn?e:null;if(s||(s=new hn),typeof e=="object"&&(e instanceof Fe?s.parent=e:Object.assign(s,e)),t){s.context=i;let r=this.asset;r.guid=this.uri;let a=dy(r,s,void 0,n);if(a)return a}else{let r=K.instantiate(this.asset,s);if(r)return r}}else Eh&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},TT=class extends Qo{constructor(){super([Wi])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?Wi.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new TT;var no=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,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)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,s){return e.prep(4,16),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Un=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var ZO=be("debugxr"),rg=be("debugavatar");var RT="VRUS";jd(RT,Un.getRootAsVrUserStateBuffer);function CT(){return new Date().getTime()}function U5(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return _i.create(e,t)}var og=class{guid;time;avatarId;position=new O;rotation=new rt;scale=1;posLeftHand=new O;posRightHand=new O;rotLeftHand=new Oe;rotRightHand=new Oe;constructor(e){this.guid=e}update(e,t,n,i,s){this.time=CT(),this.avatarId=s,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let r=og.quat0,a=og.quat1;r.set(n.x,n.y,n.z,n.w),r=r.multiplyQuaternions(r,og.invertRotation),e&&(e.getWorldQuaternion(a),r.multiplyQuaternions(a,r)),this.rotation.set(r.x,r.y,r.z,r.w),this.scale=e.scale.x;let l=i.LeftController?.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand));let c=i.RightController?.controllerGrip;if(c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let h=i.LeftController.wrist;h&&(h.getWorldPosition(this.posLeftHand),h.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let h=i.RightController.wrist;h&&(h.getWorldPosition(this.posRightHand),h.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);Un.startVrUserStateBuffer(e),Un.addGuid(e,n),Un.addTime(e,U5(this.time)),Un.addAvatarId(e,i),Un.addPosition(e,Tn.createVec3(e,this.position.x,this.position.y,this.position.z)),Un.addRotation(e,no.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Un.addScale(e,this.scale),Un.addPosLeftHand(e,Tn.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Un.addPosRightHand(e,Tn.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Un.addRotLeftHand(e,no.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Un.addRotRightHand(e,no.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let s=Un.endVrUserStateBuffer(e);e.finish(s,RT);let r=e.asUint8Array();t.sendBinary(r)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let s=t.rotation();s&&this.rotation.set(s.x(),s.y(),s.z(),s.w());let r=t.posLeftHand();r&&this.posLeftHand.set(r.x(),r.y(),r.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());let c=t.rotRightHand();c&&this.rotRightHand.set(c.x(),c.y(),c.z(),c.w()),this.scale=t.scale()}},$s=og;Se($s,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI)),Se($s,"quat0",new Oe),Se($s,"quat1",new Oe);var na=class extends le{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent(wt)),this.webXR||(this.webXR=K.findObjectOfType(wt,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=K.findObjectOfType(wt,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=K.findObjectOfType(Vi,this.context)),rg){let e="debug-avatar-"+rg,t=new Js(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof rg=="string"&&rg.length>0)if(await t.setAvatarOverride(rg)){let n=new $s(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=K.getComponent(this.gameObject,wt),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),wt.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),wt.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),wt.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(RT,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new $s("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return ZO&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let s=new Js(this.context,e,this.webXR);i=s,this.avatars[e]=s}catch(s){this.avatars[e]=null,console.error(s)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),wt.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),wt.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),wt.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=CT();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=CT();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Js(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){ZO&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new _s(1024);onXRSessionUpdate(e){this.xrState??=new $s(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new vl(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,s=t.getViewerPose(n.getReferenceSpace());if(!s)return;let r=s?.transform,a=r.position,l=r.orientation;this.xrState.update(i,a,l,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return be("avatar")}};async function H5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function z5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var AT=!1,PT=!1;H5().then(o=>AT=o);z5().then(o=>PT=o);var $n=class extends le{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(AT||PT)}static get IsARSupported(){return AT}static get IsVRSupported(){return PT}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){$n.XRSupported||console.warn("WebXR is not supported on this device");let n=of.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={requiredFeatures:["hit-test"]};n&&(i.domOverlay={root:n},i.optionalFeatures=["dom-overlay"]);let s=r_.createButton(e.context.renderer,i);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),$n.resetButtonStyles(s),(t?.registerClick??!0)&&s.addEventListener("click",e.onClickedARButton.bind(e)),s}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Wi.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!K.findObjectOfType(na,this.context)){let e=K.addNewComponent(this.gameObject,na,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new Sl(this);let e=$n.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=$n.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(n=$n.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{$n.resetButtonStyles(n),$n.resetButtonStyles(t)},1e3)}_transformOrientation=new Oe;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let s of this.controllers)s.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}$n._isInXr===!1&&t&&this.onEnterXR(t,e),$n.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)Vt.Create(this,e,this.gameObject,0);$n.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(ot(this.context.mainCamera)),this._originalCameraRotation.copy(cn(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=K.findObjectOfType(El,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new zr,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new O;_originalCameraRotation=new Oe;onEnterXR(e,t){console.log("[XR] session begin",e),$n._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let l=new Oe(a.x,a.y,a.z,a.w),c=new Lt().setFromQuaternion(l);this.rig.rotateY(c.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let r=i.getCamera(this.context.mainCamera);for(let a of r.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let s=this._requestedAR?2:4;switch(Es.Global.Set(s),s){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),$n._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),$n.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),kt(this.context.mainCamera,this._originalCameraPosition),Bn(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),Es.Global.Set(17),$n.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!be("mirror")||setTimeout(()=>{if(!$n.IsInWebXR)return;let t=new URL(window.location.href);Od(t.searchParams,af,1),Od(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{$n.IsInWebXR&&e.end()})})},1e3)}},wt=$n;Se(wt,"_isInXr",!1),Se(wt,"events",new ms),re([se(Wi)],wt.prototype,"defaultAvatar",2);var cf=class{webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this.webxr=e}arDomOverlay=null;arOverlayElement=null;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let n=0;n<4;n++)Vt.Create(this.webxr,n,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=K.findObjectOfType(Qs,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(i=>{this.hitTestSource=i})}),!this.reticle&&this.sessionRoot&&(this.reticle=new _t(new Do(.07,.09,32).rotateX(-Math.PI/2),new Jt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,cf.tempWebXRObject||(cf.tempWebXRObject=new Fe),this.context.scene.add(cf.tempWebXRObject),K.addComponent(cf.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),K.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],s=this.webxr.context.renderer.xr.getReferenceSpace();if(s){let r=i.getPose(s);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,r),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&r)){let a=r.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Sl=cf;Se(Sl,"tempWebXRObject");var IT=!1;var hf=class extends qs{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new _e}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||wt.IsInWebXR)return;let t=K.getComponentInParent(e.object,hf);!t||t!==this||(hf.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||hf.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(wt.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!wt.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&!this._dragHelper?.hasSelected&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new l_(this.context.mainCamera);else return;if(!e||!e.object)return;let t=K.getComponentInParent(e.object,hf);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let l of this.selectStartEventListener)l(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context);let s=K.getComponentInChildren(n,bi);IT&&console.log("DRAG START",s,n),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=K.addNewComponent(n,Ys),this._draggingRigidbodies.length=0;let r=K.getComponentsInChildren(n,Xt);r&&this._draggingRigidbodies.push(...r);let a=tM();K.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(IT&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let i=K.getComponentInChildren(e.object,bi);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=tM();K.invokeOnChildren(t,n("onDragEnd"))}},Ss=hf;Se(Ss,"_active",null),Se(Ss,"lastHovered");var OT=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Oi;_hasGroundPlane=!1;_groundPlane=new Oi;_groundOffset=new O;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new O;_raycaster=new Ho;_cameraPlaneOffset=new O;_intersection=new O;_worldPosition=new O;_inverseMatrix=new it;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Ji(OT.geometry),n=t.material;n.color=new q(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Ni(.5,22,22),s=new Jt({color:n.color}),r=new _t(i,s);r.visible=!1,r.layers.set(2),this._groundMarker=r}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);if(this._selected&&vn.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}vn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=K.getComponentsInChildren(this._selected,Xt),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new O(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,n=68,i=83,s=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),r=this._context.input.getTouchesPressedCount()>=2||s;if(r){let l=this._context.input.getPointerPositionDelta(0);l&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,l.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){IT&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let l=ot(this._camera).clone().sub(ot(this._selected)).normalize(),c=Math.abs(l.dot(this._groundOffsetVector)),h=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!r&&c>.2&&!h&&this._context.input.getPointerPressedCount()<=1,d=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||d)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,u){this._groundOffsetVector.set(0,1,0);let g=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(g,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);d&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=ot(this._selected);i.y=e.y,e=i}if(kt(this._selected,e),kt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=ot(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),kt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=ot(this._selected),t=new vr(new O(0,.1,0).add(e),new O(0,-1,0)),n=new Zn;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let s=0;s<i.length;s++){let r=i[s];if(!r.face||this.contains(this._selected,r.object))continue;let a=new O(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){Qt.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},l_=OT;Se(l_,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,-1,0)]));var Ml=class extends le{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?ys.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let s=i.getAsFile();if(!s)continue;console.log("Register file "+s.name+" to",this.filesBackendUrl,s);let r=await QO(s,this.context,this.filesBackendUrl);r&&this.addObject(e,r)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async s=>{console.log("dropped url",s);try{let r=new URL(s);if(!r)return;let a=await $O(r,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",s)}})}}async addObject(e,t){console.log("Dropped",t);let n=new Zn;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),s=t.scene;if(i&&i.length>0)for(let r of i){s.position.copy(r.point);break}this.gameObject.add(s),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};re([se()],Ml.prototype,"filesBackendUrl",2),re([se()],Ml.prototype,"localhost",2);var io=class extends qs{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new O(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Oe(0,0,0,1)}let e=K.getComponentInParent(this.gameObject,Ss);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),Vt.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new hn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=K.instantiateSynced(this.object,t);return console.assert(n!==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),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};re([se(Fe)],io.prototype,"parent",2),re([se(Fe)],io.prototype,"object",2),re([se()],io.prototype,"limitCount",2),re([se()],io.prototype,"limitInterval",2);var so=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},G5=o=>/^[A-Z]*$/.test(o),Mh=class extends Event{args},Rn=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let s of this.key)i&&G5(s)&&(n+="-"),i=!0,n+=s.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Mh(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new so(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var uf=class extends le{};import{FlyControls as W5}from"three/examples/jsm/controls/FlyControls";var df=class extends le{_controls=null;onEnable(){let e=K.getComponent(this.gameObject,Bt)?.cam;this._controls=new W5(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};var ia=class extends le{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Qr||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new th(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=t_(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};re([se()],ia.prototype,"objectBounds",2),re([se(q)],ia.prototype,"color",2),re([se()],ia.prototype,"isGizmo",2);import{GLTFExporter as X5}from"three/examples/jsm/exporters/GLTFExporter.js";var ag=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new it,a=new Array,l=new Array,c=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,r);let g=new O,p=new Oe,m=new O;r.decompose(g,p,m),a.push(g.x,g.y,g.z),l.push(p.x,p.y,p.z,p.w),c.push(m.x,m.y,m.z)}let h=new Float32Array(a),u=new Float32Array(l),d=new Float32Array(c);s.attributes={TRANSLATION:n.processAccessor(new Mt(h,3)),ROTATION:n.processAccessor(new Mt(u,4)),SCALE:n.processAccessor(new Mt(d,3))},i[this.name]=!0}};var Tl=Nn,c_="$___Export_Components",j5="NEEDLE_components",DT=class{[ih]},kT=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},ff=class{get name(){return j5}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let n=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(i,s)=>{try{this.serializeUserData(i,s),n(i,s)}finally{this.afterSerializeUserData(i,s)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;!n||n.length<=0||(delete e.userData.components,e[c_]=n)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Tl&&console.log("DONE",JSON.stringify(t)),e[c_]===void 0)return;let n=e[c_];delete e[c_],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;console.log(e.name,n,e.uuid);let i=new kT(e,n,t);this.exportContext[n]=i,this.objectToNodeMap[e.uuid]=n}afterParse(e){Tl&&console.log("AFTER",e);for(let t in this.exportContext){let n=this.exportContext[t],i=n.node,s=n.nodeDef,r=n.nodeIndex,a=i.userData?.components;if(!a||a.length<=0)continue;let l=new DT;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=i,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;let c=[];for(let h of a){this.context.target=h;let u=eD(h,this.context);u!==null&&c.push(u)}c.length>0&&(l[ih]=c,Tl&&console.log("DID WRITE",i,"nodeIndex",r,c))}}beforeRoot(){return Tl&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,n=t?.extensions;if(!n)return;let i=n[this.name];Tl&&console.log("After root",e,this.parser,n);let s=[];if(i===!0){let r=t.json.nodes;for(let a=0;a<r.length;a++){let l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){let l=r[a],c=a,h=l.extensions;if(!h)continue;let u=h[this.name];if(!u)continue;Tl&&console.log("NODE",l);let d=this.nodeToObjectMap[c];if(!d){console.error("Could not find object for node index: "+c,l,t);continue}s.push(this.createComponents(d,u))}}await Promise.all(s)}async createComponents(e,t){if(!t)return;let n=t[ih];if(n){Tl&&console.log(e.name,n);for(let i in n){let s=n[i];Tl&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&await qd(this.parser,s),e.userData=e.userData||{},e.userData[ih]=e.userData[ih]||[],e.userData[ih].push(s)}}}};var pf=class extends ts{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Ks=class extends le{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Ks.calculateCenter(this.objects)},n=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ks.saveArrayBuffer(n,e):Ks.saveJson(n,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new X5,this.exporter.register(a=>new ag(a)),this.ext=new ff,this.ext.registerExport(this.exporter)),Ks.filterTopmostParent(e);let n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Ks.collectAnimations(e)},i=new Fe;t?.pivot&&i.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(i.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),K.getComponentsInChildren(a,Sn).forEach(l=>{K.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))});let s=new Yd(i);return this.ext.context=s,new Promise((a,l)=>{try{this.exporter?.parse(i,c=>{r(),a(c)},c=>{r(),l(c)},n)}catch(c){console.error(c),l(c)}finally{console.log("FINALLY")}});function r(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,K.getComponentsInChildren(a,Sn).forEach(l=>{K.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}static collectAnimations(e,t){t=t||[];for(let n of e)!n||n.traverseVisible(i=>{i.animations&&i.animations.length>0&&t.push(...i.animations)});return t}static calculateCenter(e,t){let n=t||new O;return n.set(0,0,0),e.forEach(i=>{n.add(ot(i))}),console.log(n),n.divideScalar(e.length),n}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let n=e[t];if(!n){e.splice(t,1),t--;continue}for(;n.parent;){if(e.includes(n.parent)){e.splice(t,1),t--;break}n=n.parent}}}};var sa=class extends le{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Qr)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Dm(e,t,this.color0??new q(.4,.4,.4),this.color1??new q(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};re([se()],sa.prototype,"isGizmo",2),re([se(q)],sa.prototype,"color0",2),re([se(q)],sa.prototype,"color1",2);import{GroundProjectedEnv as q5}from"three/examples/jsm/objects/GroundProjectedEnv.js";var ra=class extends le{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.updateProjection(),this._watcher||(this._watcher=new ey(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new q5(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2))}};re([se()],ra.prototype,"scale",1),re([se()],ra.prototype,"radius",1),re([se()],ra.prototype,"height",1);function FT(o){return o*Math.PI/180}var tD=300,nD=be("debuglights");var xi=class extends le{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new q(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let n=this._webARRoot?.arScale;typeof n=="number"&&n>0&&(t/=n)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let n=t.shadow.camera;n.far=e,n.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new q(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=wt.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=wt.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){wt.removeEventListener("xrStarted",this._webXRStartedListener),wt.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Qs)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new Sd(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-tD*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Dd(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),nD){let r=new km(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:let n=new wd(this.color,this.intensity*Math.PI,this.range,FT(this.spotAngle/2),1-FT(this.innerSpotAngle/2)/FT(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;let i=n.target;n.add(i),i.position.set(0,0,this.range),i.rotation.set(0,0,0);break;case 2:let s=new Ed(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,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),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=tD*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{let n=this.gameObject.scale.x;t.left*=n,t.right*=n}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let n=this.gameObject.scale.y;t.top*=n,t.bottom*=n}this.light.shadow.needsUpdate=!0,nD&&this.context.scene.add(new Fm(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}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};re([se()],xi.prototype,"type",2),re([se(q)],xi.prototype,"color",2),re([se()],xi.prototype,"shadowNearPlane",1),re([se()],xi.prototype,"shadowBias",1),re([se()],xi.prototype,"shadowNormalBias",1),re([se()],xi.prototype,"shadows",1),re([se()],xi.prototype,"lightmapBakeType",2),re([se()],xi.prototype,"intensity",1),re([se()],xi.prototype,"shadowDistance",1),re([se()],xi.prototype,"shadowResolution",1);var fre=new O(0,0,0);var mf=be("debugLODs"),Y5=be("noLODs");var ro=class{screenRelativeTransitionHeight;distance;renderers};re([se()],ro.prototype,"screenRelativeTransitionHeight",2),re([se()],ro.prototype,"distance",2),re([se()],ro.prototype,"renderers",2);var BT=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let n of t.renderers){let i=this.findRenderer(n,e.gameObject);i&&i.gameObject?this.renderers.push(i):mf&&console.warn("Renderer not found: "+n,e.gameObject)}}findRenderer(e,t){let n=K.foreachComponent(t,i=>i.guid===e||Object.getPrototypeOf(i)?.guid===e?i:null);if(n)return n;for(let i of t.children){let s=this.findRenderer(e,i);if(s)return s}return null}},Cl=class extends le{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!Y5&&!this._lodsHandler&&!!this.gameObject&&(mf&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let i of this.lodModels){e=Math.max(i.distance,e);let s=new BT(this,i);this._lods.push(s);for(let r of s.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let i=0;i<t.length;i++){let s=new dd;this._lodsHandler.push(s),this.gameObject.add(s)}let n=new Fe;mf&&console.log(t);for(let i=0;i<t.length;i++){let s=t[i],r=this._lodsHandler[i],a=s.gameObject,l=0,c=0;mf&&console.log(i,a.name);for(let u of this._lods){let d=null;u.renderers.includes(s)?d=a:d=n,mf&&console.log("add",u.model.distance,d.name);let f=u.model.distance;c=f-l,l=Math.max(f,l),this.onAddLodLevel(r,d,f)}let h=l+c;mf&&console.log("cull",h),this.onAddLodLevel(r,n,h)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,n){e.addLevel(t,n*this._distanceFactor);let i={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(i)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let n=t.lod.levels[t.levelIndex];n.distance=t.distance*e}}}};re([se(O)],Cl.prototype,"localReferencePoint",2),re([se(ro)],Cl.prototype,"lodModels",2);var gf=class extends le{onEnable(){this.enabled&&this.context.physics.addMeshCollider(this.gameObject)}};var vf=class extends le{},yf=class extends le{};var NT=be("debugnestedgltf"),Th=class extends le{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;NT&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new hn;t.idProvider=new li(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let n=this.gameObject.matrix;NT&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let i=await this.filePath?.instantiate?.call(this.filePath,t);i&&(i.matrixAutoUpdate=!1,i.matrix.identity(),i.applyMatrix4(n),i.matrixAutoUpdate=!0),this.destroy(),NT&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,i)}}hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}};re([se(Wi)],Th.prototype,"filePath",2);var _f=class extends le{from;affectPosition;affectRotation;alignLookDirection;levelLookDirection;positionOffset;rotationOffset;update(){if(!this.from)return;var e=ot(this.from),t=cn(this.from);this.affectPosition&&kt(this.gameObject,e.add(this.positionOffset));let n=new Lt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),i=new Oe().setFromEuler(n);this.affectRotation&&Bn(this.gameObject,t.multiply(i));let s=new O;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};var bf=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new q(1,1,1);startColor1=new q(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new _e(0,1);cullingMode=0},xf=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},wf=class{shapeType=UT.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new O(1,1,1);boxThickness=new O(0,0,0);position=new O(0,0,0);rotation=new O(0,0,0);scale=new O(1,1,1);radius=1;sphericalDirectionAmount=0},UT=(v=>(v[v.Sphere=0]="Sphere",v[v.SphereShell=1]="SphereShell",v[v.Hemisphere=2]="Hemisphere",v[v.HemisphereShell=3]="HemisphereShell",v[v.Cone=4]="Cone",v[v.Box=5]="Box",v[v.Mesh=6]="Mesh",v[v.ConeVolume=7]="ConeVolume",v[v.Circle=10]="Circle",v[v.SingleSidedEdge=11]="SingleSidedEdge",v[v.MeshRenderer=12]="MeshRenderer",v[v.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",v[v.BoxShell=14]="BoxShell",v[v.BoxEdge=15]="BoxEdge",v[v.Donut=16]="Donut",v[v.Rectangle=17]="Rectangle",v[v.Sprite=18]="Sprite",v[v.SpriteRenderer=19]="SpriteRenderer",v))(UT||{});var iD=be("debugparticles"),HT=class{age=0;lifetime=0;position;velocity;color},Ch=class extends le{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){iD&&console.log(this)}},Ef=class extends le{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Oe;tempVec3=new O;tempQuat=new Oe;awake(){this.renderer=K.getComponent(this.gameObject,Ch),iD&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Lt(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new ht,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Qe(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let n=0;n<e.length;n++)e[n*3]=1,e[n*3+1]=1,e[n*3+2]=1;let t=new Qe(e,3);this.geometry.setAttribute("color",t),this.material=new Fc({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new md(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let n=this.particleStates[t];if(!n)continue;let i=n.velocity.x*e,s=n.velocity.y*e,r=n.velocity.z*e;n.position.x+=i,n.position.y+=s,n.position.z+=r,this.updateOverLifetime(t,n),this.geometry.attributes.position.setXYZ(t,n.position.x,n.position.y,n.position.z),this.geometry.attributes.color.setXYZ(t,n.color.r,n.color.g,n.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let n=0;n<t;n+=1){if(n>=this.particleStates.length){let s=new HT;s.lifetime=this.main.startLifetime??1,s.position=new O,s.velocity=new O,s.color=new q(1,0,0),this.particleStates.push(s),this.initializeParticle(n,s),s.age=s.lifetime*Math.random()}let i=this.particleStates[n];if(i.age>i.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(n,i);continue}i.age+=e,this.particleStates[n]=i}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let n=t.position;n.multiply(this.shape.scale),n.applyQuaternion(this.shapeRotation),n.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let n=new O(0,1,0);t.copy(n);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*gt.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};function*sD(o,e=null){let t=e?e.time:bt.Current.time,n=t.time;for(;t.time-n<o;)yield}var ss=class extends le{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield sD(.2),!this.tryAssignColor()););}tryAssignColor(){let e=K.getComponentInParent(this.gameObject,sn);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ss.hashCode(e),n=ss.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let i=this.gameObject;this.assignColor(n,e,i)}else if(this.gameObject.children)for(let i of this.gameObject.children){let s=i;s.material&&s.material.color&&this.assignColor(n,e,s)}}assignColor(e,t,n){let i=n.material;!i||(i._playerMaterial!==t?(i=i.clone(),i._playerMaterial=t,n.material=i):console.log("DONT CLONE",i),i.color=e)}static hashCode(e){var t=0,n,i;if(e.length===0)return t;for(n=0;n<e.length;n++)i=e.charCodeAt(n),t=(t<<5)-t+i,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,n=(e&65280)>>8,i=e&255;return new q(t/255,n/255,i/255)}};function J5(){return new Promise((o,e)=>{let n=()=>{n!=null&&(document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n),o())};document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)})}async function rD(o){await J5(),o()}var zT=be("debugvideo");var ji=class extends le{renderer=null;playOnAwake=!0;playOnEnable;targetMaterialProperty;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setClipURL(e){this.url!==e&&(this.url=e,this.source=1,zT&&console.log("set url",e),this.videoElement&&(this.videoElement.src=e,this._isPlaying&&this.videoElement.play()))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0)}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this.videoTexture&&(this.videoTexture.dispose(),this.videoTexture=null)}_receivedInput=!1;constructor(){super(),rD(()=>{this._receivedInput=!0,this.updateVideoElementSettings()})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),zT&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new vm(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ct,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),zT&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;let t=this.gameObject.material;if(t)if(t!==this.videoMaterial&&(this.videoMaterial=t.clone(),this.gameObject.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this.videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=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.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none")}};re([se(Fe)],ji.prototype,"renderer",2),re([se()],ji.prototype,"playOnAwake",2),re([se()],ji.prototype,"playOnEnable",2),re([se()],ji.prototype,"targetMaterialProperty",2),re([se()],ji.prototype,"time",2),re([se()],ji.prototype,"playbackSpeed",1),re([se()],ji.prototype,"isLooping",1);var Sf=class extends le{streamOnAwake=!0;start(){this.streamOnAwake&&this.open()}requestOpen=!1;captureStream=null;async open(e=!1){if(!(this.captureStream&&!e)){this.close(),this.requestOpen=!0;try{let t=K.getComponentInChildren(this.gameObject,ji);if(t){let n={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(n),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};var Rl=class extends le{mode=0;shadowColor=new gn(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=K.getComponent(this.gameObject,Sn);if(e){let t=e.material;t.blending=em,this.applyMaterialOptions(t),t.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
6340
6340
 
6341
6341
  // diffuse-only lighting with overdrive to somewhat compensate
6342
6342
  // for the loss of indirect lighting and to make it more visible.