@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.
@@ -120,7 +120,7 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
120
120
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
121
121
  gl_FragColor = lightMapTexel;
122
122
  }
123
- `,defines:{USE_LIGHTMAP:""}})}};var A=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=Bu(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=Bu(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function Bu(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}import{Vector4 as Kb}from"three";import{NeverStencilFunc as Ib,LessStencilFunc as Mb,EqualStencilFunc as Lb,LessEqualStencilFunc as Db,GreaterStencilFunc as Hb,NotEqualStencilFunc as jb,GreaterEqualStencilFunc as Bb,AlwaysStencilFunc as Fb,ZeroStencilOp as Nb,KeepStencilOp as zb,ReplaceStencilOp as Gb,IncrementStencilOp as Vb,DecrementStencilOp as Wb,IncrementWrapStencilOp as Ub,DecrementWrapStencilOp as qb,InvertStencilOp as Xb}from"three";var rc=N("debugstencil");function Qb(l,e){return(l&1<<e.layer)!=0}var Kn=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(rc&&console.log(t,Kn.stencils),!t)return;let i=Kn.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Qb(r.layer,e)){rc&&console.log(r);let o=e.material?.clone();o&&(e.material=o,e.gameObject.renderOrder=r.event*1e3+r.index*50,o.stencilWrite=!0,o.stencilWriteMask=255,o.stencilFuncMask=255,o.stencilRef=r.value,o.stencilFunc=r.compareFunc,o.stencilZPass=r.passOp,o.stencilFail=r.failOp,o.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Zb];if(i){rc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Yb(o.compareFunc),o.passOp=oc(o.passOp),o.failOp=oc(o.failOp),o.zFailOp=oc(o.zFailOp),Kn.stencils[this.source]||(Kn.stencils[this.source]=[]),Kn.stencils[this.source].push(o)}}}return null}},er=Kn;z(er,"stencils",{});function oc(l){switch(l){case 0:return zb;case 1:return Nb;case 2:return Gb;case 3:return Vb;case 4:return Wb;case 6:return Ub;case 7:return qb;case 5:return Xb}return 0}function Yb(l){switch(l){case 1:return Ib;case 2:return Mb;case 3:return Lb;case 4:return Db;case 5:return Hb;case 6:return jb;case 7:return Bb;case 8:return Fb}return 0}var Zb="NEEDLE_render_objects";import{TextureLoader as Jb}from"three";import{GLTFLoader as $b}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as sc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Fu}from"three/examples/jsm/loaders/KTX2Loader.js";var os=N("debugdecoders"),Ut,bn;function ac(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),os&&console.log("Setting draco decoder path to",l),Ut.setDecoderPath(l))}function lc(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),os&&console.log("Setting draco decoder type to",l),Ut.setDecoderConfig({type:l}))}function cc(l){l!==void 0&&typeof l=="string"&&(bn||(bn=new Fu),os&&console.log("Setting ktx2 transcoder path to",l),bn.setTranscoderPath(l))}function tr(l,e){Ut||(Ut=new sc,Ut.setDecoderPath("./include/draco/"),Ut.setDecoderConfig({type:"js"}),os&&console.log("Setting draco decoder path to","./include/draco/")),bn||(bn=new Fu,bn.setTranscoderPath("./include/ktx2/"),os&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&bn.detectSupport(e.renderer)),l.setDRACOLoader(Ut),l.setKTX2Loader(bn)}var dc="NEEDLE_deferred_texture",vn=N("debugdeferredtextures"),ss=class{static assignTextureLOD(e,t,i=0){if(!!t)for(let n of Object.keys(t)){let r=t[n];r?.isTexture===!0&&(vn&&console.log("FIND",n,r?.name,r?.userData,r),ss.getOrLoadTexture(e,t,n,r,i).then(o=>{o?.isTexture===!0&&(o.needsUpdate=!0,t[n]=o,t.needsUpdate=!0)}))}}get name(){return dc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return vn&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[dc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{vn&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,ss.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r){let o=n.uuid,s=ss.cache.get(o)||n.userData.deferred;if(s){vn&&console.log(o,s.uri,s.guid);let c=s.uri;if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!s.guid)return console.warn("missing pointer for glb/gltf texture",s),null;let d=s.uri+"_"+s.guid;if(this.resolved[d])return this.resolved[d];let a=new $b;tr(a,e),vn&&console.log("Load "+c,t.name,i);let h=await a.loadAsync(c),u=h.parser,f=-1,E=!1;for(let y of h.parser.json.textures)if(f++,y?.extensions){let g=y?.extensions[dc];if(g?.guid&&g.guid===s.guid){E=!0;break}}if(!E)return null;let b=await u.getDependency("texture",f);return this.resolved[d]=b,vn&&console.log(t.name,i,'change "'+n.name+'" \u2192 "'+b.name+'"',c,f,b,t),b}else{let a=await new Jb().loadAsync(s.uri);return a&&vn?console.log(s,a):console.warn("failed loading",s.uri),a}}else vn&&console.warn("unknown uuid",n.name,n.uuid,n);return null}},ji=ss;z(ji,"cache",new Map),z(ji,"resolved",{});var zu=N("noInstancing"),Gu=!!N("debuglightmaps"),ev=N("debuginstancing"),tv=N("debugprogressiveload"),Hr=class{path=null;asset=null;default};var hc=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,o){if(typeof o=="string"){let s=parseInt(o);if(!isNaN(s))return i(s)}return r[o]},set(r,o,s){return typeof o=="string"&&t(s,Number.parseInt(o)),Reflect.set(r,o,s)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},gc=class extends M{receiveShadows=!1;shadowCastingMode=uc.Off;lightmapIndex=-1;lightmapScaleOffset=new li.Vector4(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 hc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return zu}_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 i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||O.getComponent(n,gc))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.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 i=new Hi(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Gu)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Hi(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Gu),n.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=iv.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return O.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return O.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&&!zu&&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(){er.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,tv?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{ji.assignTextureLOD(this.context,r)},2e3)):ji.assignTextureLOD(this.context,r)),r.envMapIntensity!==void 0){let s=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/s)}if(this._lightmaps)for(let s of this._lightmaps)s.onBeforeRenderThree(r)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[pc]===!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[pc],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&O.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.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==uc.On?e.castShadow=!0:e.castShadow=!1}},Te=gc;k([A()],Te.prototype,"receiveShadows",2),k([A()],Te.prototype,"shadowCastingMode",2),k([A()],Te.prototype,"lightmapIndex",2),k([A(Kb)],Te.prototype,"lightmapScaleOffset",2),k([A()],Te.prototype,"enableInstancing",2),k([A()],Te.prototype,"renderOrder",2),k([A()],Te.prototype,"allowOcclusionWhenDynamic",2);var ir=class extends Te{},jr=class extends ir{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},uc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(uc||{}),pc="NEEDLE_NEED_UPDATE_INSTANCE",he=class{static markDirty(e,t=!0){if(!!e&&(O.isUsingInstancing(e)&&(e[pc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)he.markDirty(i,!0)}},fc=class{objs=[];setup(e,t,i,n,r=0){let o=this.tryCreateOrAddInstance(e,t,n);if(o)return i===null&&(i=[]),i.push(o),i;if(r<=0&&e.type!=="Mesh"){let s=r+1;for(let c of e.children)i=this.setup(c,t,i,n,s)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,o=r.geometry,s=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===o&&d.material===s)return d.addInstance(r);let c=new aa(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},iv=new fc,mc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,O.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)}},bc=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,ev&&(i=new li.MeshBasicMaterial({color:this.randomColor()})),this.inst=new li.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new li.Color(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 mc(-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 i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,bc.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,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}},aa=bc;z(aa,"nullMatrix",new li.Matrix4);var as=N("debugphysics"),nv=N("debugcollisions"),la=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ls=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},vc=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var je=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 ke.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new ke.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(je,"AllLayers",4294967295);var yc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},ca=class{raycaster=new ke.Raycaster;defaultRaycastOptions=new je;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ke.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new ke.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new ke.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new yc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let s=this.context.mainCamera;if(!s)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,s)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ke.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(s=>!o.includes(s.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new sa;objects=[];tempPosition=new ke.Vector3;tempQuaternion=new ke.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),as){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},ju(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 i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(i);let n=new ls(e,i);return n._hasRigidbody=!0,this.objects.push(n),as&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let o=this.tempPosition;e.getWorldScale(o);let s=new _(.5*o.x*n.x,.5*o.y*n.y,.5*o.z*n.z),c=new Jn(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.isAlreadyRegistered(d))return c;let a=new ls(e,d);this.objects.push(a)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new ra(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.isAlreadyRegistered(c))return s;let d=new ls(e,c);this.objects.push(d)}return s}addMeshCollider(e){as&&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,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC,this.world.addBody(r)),r){i.x*=-1;let o=ve(e),s=q(e);s.add(i);let c=new ke.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);o.multiply(c.invert());let d=r.position,a=new _(s.x-d.x,s.y-d.y,s.z-d.z),h=new le(o.x,o.y,o.z,o.w);r.addShape(t,a,h),r.updateMassProperties()}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,as&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new ke.Vector3;tempQuat=new ke.Quaternion;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;i.sleepTick(this.context.time.time),as&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING;let n=t.obj;if(i.type===G.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=ve(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Ch(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Ar(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&he.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new le(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);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 i=new vc(t.contact,t.type),n=0,r=this.objects;function o(){if(!(n>0))for(let s=0;s<r.length;s++){if(n==2)return;let c=r[s];c.body==t.body?(i.obj=c.obj,++n):c.body==t.target&&(i.target=c.obj,++n)}}nv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let s=0;s<e.userData?.components?.length;s++){let c=e.userData.components[s];c.onCollision&&(o(),c.onCollision(i))}}};import{Clock as rv}from"three";var da=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 rv;_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)}};import{WebsocketBuilder as sv}from"websocket-ts";function Vu(l=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(l)===!0}var pt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?pt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=N(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=pt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Vu(e)}};var ci=new Int32Array(2),ha=new Float32Array(ci.buffer),ua=new Float64Array(ci.buffer),Br=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var cs;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(cs||(cs={}));var di=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new di(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 Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ci[0]=this.readInt32(e),ha[0]}readFloat64(e){return ci[Br?0:1]=this.readInt32(e),ci[Br?1:0]=this.readInt32(e+4),ua[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){ha[0]=t,this.writeInt32(e,ci[0])}writeFloat64(e,t){ua[0]=t,this.writeInt32(e,ci[Br?0:1]),this.writeInt32(e+4,ci[Br?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 i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+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 i=this.readInt32(e),n="",r=0;if(e+=4,t===cs.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let o,s=this.readUint8(e+r++);if(s<192)o=s;else{let c=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(c&63)<<6|d&63;else{let a=this.readUint8(e+r++);o=(s&7)<<18|(c&63)<<12|(d&63)<<6|a&63}}}o<65536?n+=String.fromCharCode(o):(o-=65536,n+=String.fromCharCode((o>>10)+55296,(o&(1<<10)-1)+56320))}return n}__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 Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var ft=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=di.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 i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=ft.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}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,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(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 i=t<<1,n=di.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}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 i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(c+d))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let o=4-1;o>=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,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 i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let o=e.charCodeAt(i++);n=(r<<10)+o+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));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 Wu={};function Nr(l,e){Wu[l]=e}function Uu(l){let e=l.getBufferIdentifier(),t=Wu[e];return t(l)}function qu(l){return typeof l.guid=="function"?l.guid():null}var _c=vl(wc(),1);var fa=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 _c.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Tc(t)})}trySetupClient(e){this._client=new _c.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",i=>{console.log("<<",i)})})}},xc=class{_peer;constructor(e){this._peer=e}};var Tc=class extends xc{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(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var Rc="wss://needle-tiny-starter.glitch.me/socket",mt=!!N("debugnet"),ma=!!(mt||N("debugowner"));var En=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||(ma&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return ma&&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?(ma&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(ma&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var ga=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new fa),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mt}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(),mt&&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,i=2){if(t===null&&(t={}),i===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){mt&&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 i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mt&&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 i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,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 i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}connect(){if(this.connected)return;mt&&console.log("connecting");let t=O.findObjectOfType(pt,this.context,!1)?.getWebsocketUrl();t&&(Rc=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 "+Rc);let e=new sv(Rc).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,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{mt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new di(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=Uu(n),c=qu(s);if(c&&typeof c=="string"&&(this._state[c]=s),!o)return;let d=s??n;for(let a of o)a(d)}handleIncomingStringMessage(e){if(mt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let o=e.data;o&&(console.assert(o.id!==void 0&&o.id!==null&&o.id.length>0,"server did not send connection id",o.id),console.log("Your id is: "+o.id,this.context.alias??""),this._connectionId=o.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mt&&console.log(e),e){this._isInRoom=!0;let o=e;this._currentRoomName=o.room,this._currentRoomViewId=o.viewId,this._currentRoomAllowEditing=o.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...o.inRoom),mt&&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 o=e.data;this._currentInRoom.push(o.userId),mt&&console.log(o.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let o=e.data,s=this._currentInRoom.indexOf(o.userId);s>=0&&(console.log(o.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),o.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),mt&&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 n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));mt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import*as Xt from"three";import{OrbitControls as lv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as av}from"three";var Bi=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(av)],Bi.prototype,"sources",2);import*as ds from"three";var gt=class extends M{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 ds.Vector3}onEnable(){this._enableTime=this.context.time.time;let t=O.getComponent(this.gameObject,ne)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new lv(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=O.getComponent(this.gameObject,ne);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new ds.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new je;e.screenPoint=new ds.Vector2(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 i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[e];if(n)return n.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&&O.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A(Bi)],gt.prototype,"lookAtConstraint",2);import{Color as cv}from"three";var we=class extends cv{alpha=1;constructor(e,t,i,n){super(e,t,i),this.alpha=n}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 i=e;return i.alpha&&(this.alpha=Q.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as dv}from"three";var Qu=N("debugcam"),ne=class extends M{get aspect(){return this._cam instanceof dv?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 Xt.PerspectiveCamera&&(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(){Qu&&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 Xt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Xt.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,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 Cc(this)),this._skybox.enable()}};k([A()],ne.prototype,"fieldOfView",1),k([A()],ne.prototype,"nearClipPlane",1),k([A()],ne.prototype,"farClipPlane",1),k([A()],ne.prototype,"clearFlags",1),k([A()],ne.prototype,"orthographic",2),k([A()],ne.prototype,"orthographicSize",2),k([A()],ne.prototype,"ARBackgroundAlpha",2),k([A(we)],ne.prototype,"backgroundColor",1);var Cc=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?(Qu&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Xt.sRGBEncoding,this._skybox.mapping=Xt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Yu(l){let e="created/implictly",t=new Xt.Object3D;l.add(t);let i=O.addNewComponent(t,ne,!1);i.sourceId=e;let n=O.addNewComponent(t,gt,!1);return n.sourceId=e,i}import{EffectComposer as SE}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as PE}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as hv,MathUtils as uv}from"three";var zr=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,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Zu(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??uv.generateUUID(),index:-1,clip:new hv(l,1,[])}}import{AnimationClip as vv,AnimationMixer as yv,AxesHelper as Ev,Euler as ep,LoopOnce as wv,Quaternion as Qt,Vector3 as ps}from"three";import*as xa from"three";var Sc=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},D=new Sc;var hi=N("gizmos"),Ie=N("debugextension");var va=N("debugresolvedependencies"),pv=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Gr(l,e){va&&console.log(l,e);let t=[];Oc(pv,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Oc(l,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let o=Ju(e,r);if(o!==null)typeof o.then=="function"?i.push(o.then(s=>t[n]=s)):t[n]=o;else for(let s of l){let c=Ac(s.prefix,r);if(c>=0){va&&console.log(s,c,s.dependencyName),i.push(e?.getDependency(s.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],c=Ju(e,s);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[o]=d)):r[o]=c;continue}for(let d of l){let a=Ac(d.prefix,s);if(a>=0){va&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(h=>r[o]=h));break}}typeof s=="object"&&Oc(l,e,s,i)}else typeof r=="object"&&Oc(l,e,r,i)}else typeof t=="string"&&fv(l,e,t,i)}var Pc="extensions/";function Ju(l,e){if(l&&l.plugins&&typeof e=="string"&&e.startsWith(Pc)){let t=e.substring(Pc.length),i=t.indexOf("/");i>=0&&(t=t.substring(0,i));let n=l.plugins[t];if(Ie&&console.log(t,n),typeof n?.resolve=="function"){let r=e.substring(Pc.length+t.length+1);return n.resolve(l,r)}}return null}function fv(l,e,t,i){for(let n of l){let r=Ac(n.prefix,t);if(r>=0)return va&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function Ac(l,e){if(typeof e=="string"&&e.startsWith(l)){let t=e.substring(l.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var kc="NEEDLE_persistent_assets";function $u(l){return l?.___persistentAsset===!0}var ya=class{get name(){return kc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[kc];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Gr(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[kc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var nr=N("debugserializer"),Ic=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])}nr&&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){nr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){nr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return nr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){nr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let s=r.prototype??r.constructor;if(s!==e){let c=this.getSerializerForConstructor(s,++t);if(c){nr&&console.log("FOUND "+s.constructor.name,s.name,s,c);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,c):this.register(d,c)}return c}}},wa=new Ic,Fi=class{constructor(e){if(Array.isArray(e))for(let t of e)wa.register(t.name,this);else wa.register(e.name,this)}},Vr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Lc(l,e){let t=l.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=l[n];if(r!=null&&typeof r=="object"){let o=wa.getSerializerForConstructor(r);if(o){i[n]=o.onSerialize(r,e);continue}}i[n]=r}return i.name=l.constructor.name,typeof l.guid=="string"&&(i.guid=l.guid),i}var Ea=[];function Ku(l,e){if(!l)return e;typeof l.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,l.$serializedTypes));let t=Object.getPrototypeOf(l);return Ku(t,e)}function hs(l,e,t){if(!l)return!1;if(t.target=l,l.onBeforeDeserialize!==void 0){let r=l.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=Ku(l);if(e){if(typeof e.guid=="string"&&(l.guid=e.guid),i)for(let r in i){let o=i[r],s=e[r];if(t.path=r,o===null)l[r]=s;else{let c=function(d){let h=d.type;return h?Mc(s,h,t,void 0,l[r]):Mc(s,d,t,void 0,l[r])};var n=c;if(l.onBeforeDeserializeMember!==void 0&&l.onBeforeDeserializeMember(r,s,t)===!0)continue;if(Array.isArray(o))for(let d=0;d<o.length;d++){let a=o[d],h=c(a);if(h!==void 0||d===o.length-1){l[r]=h;break}}else l[r]=c(o);Ea.length=0,l.onAfterDeserializeMember!==void 0&&l.onAfterDeserializeMember(r,s,t)}}mv(l,e)}return l.onAfterDeserialize!==void 0&&l.onAfterDeserialize(e,t),t.path=void 0,!0}function mv(l,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=l[i];if(!r){nr&&console.log(i,"is undefined on",l);continue}for(let o of Object.keys(n))r[o]===void 0&&t(n[o])&&!t(r)&&(r[o]=n[o])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Mc(l,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e?.call(e,n),r=!1,o==null)return}catch(a){console.error("Error in callback",a,l)}if(!r&&n instanceof o)return n;if(n&&typeof n=="object"&&$u(n)){if(n.__concreteInstance)return n.__concreteInstance;let a=n;if(!a.$serializedTypes&&o.prototype.$serializedTypes&&(a.$serializedTypes=o.prototype.$serializedTypes),a.$serializedTypes&&hs(a,l,t),n&&o!==void 0)try{let h=new o;Ie&&console.log("Create concrete instance for persistent asset",n,"instance:",h),us(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,o)}return n}if(i||(i={serializer:wa.getSerializerForConstructor(o)}),Array.isArray(l)){let a=[];for(let h=0;h<l.length;h++){let u=l[h],f=Mc(u,e,t,i,u);a.push(f)}return a}let s=i.serializer;if(s)return s.onDeserialize(l,t);let c;l&&(l.isMaterial||l.isTexture||l.isObject3D)?c=l:c=new o(...gv(l));let d=c;return d.$serializedTypes&&hs(d,l,t),c}function gv(l){if(Ea.length=0,typeof l=="object"&&l!==null&&l!==void 0)for(let e of Object.keys(l))Ea.push(l[e]);return Ea}function us(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=bv(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function bv(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var wn=N("debuganimatorcontroller"),Dc=N("debugrootmotion"),Zt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let o=this.model.layers[t].stateMachine;for(let s of o.states)if(s.name===e||s.hash===e){wn&&console.log("transition to ",s),this.transitionTo(s,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){wn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.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 i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new yv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Qo(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new Zt(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,wn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(wn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){wn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(a=>a.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,wn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new zr(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,a=this._activeState.motion.action.time/d,h=new zr(this._activeState,a,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let o=this._activeState?.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);let s=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(wv,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let a=new zr(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);wn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Hc(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(i=>i.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 i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Zu(r.name)),this.animator&&r.motion.clips){let o=r.motion.clips?.find(s=>s.node.name===this.animator?.gameObject?.name);r.motion.clip=o?.clip}if(!r.motion.clip){let o=new vv;r.motion.clip=o}if(r.motion?.clip){let o=r.motion.clip,s=this.createAction(o);r.motion.action=s}if(r.behaviours&&Array.isArray(r.behaviours))for(let o of r.behaviours){if(!o?.typeName)continue;let s=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,us(c,o.properties),o.instance=c),wn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},_a=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let o=this.originalEvaluate(r);return t(r,o)},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}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new ps;rotationChange=new Qt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new xa.Quaternion),r){let o=r.values;Re.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new Qt),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new Qt),Re.clipOffsetRotation[i.uuid]=new Qt,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new xa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Q.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Dc&&i.add(new Ev),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new ps);let n=new ps,r=new ps,o=0;this.positionWrapper=new _a(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Dc&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(c),o=s,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Dc){let s=t.values,c=new ep().setFromQuaternion(new Qt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Q.toDegrees(c.y));let d=t.values.length-4,a=new Qt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new ep().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Q.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new Qt);let n=0,r=new Qt,o=new Qt;this.rotationWrapper=new _a(t,(s,c)=>(s>n&&(o.set(c[0],c[1],c[2],c[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(c),n=s,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}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(Re.identityQuaternion,1-e)}},Yt=Re;z(Yt,"lastObjPosition",{}),z(Yt,"lastObjRotation",{}),z(Yt,"firstKeyframeRotation",{}),z(Yt,"spaceRotation",{}),z(Yt,"effectiveSpaceRotation",{}),z(Yt,"clipOffsetRotation",{}),z(Yt,"identityQuaternion",new Qt);var Hc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),s=new Yt(this.controller.context,t,i,r,o);this.handler.push(s);let c=e.clipAction(i);return s.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new ps;summedRotation=new Qt;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),Yt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var _v=N("debuganimator"),bt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Zt?this._animatorController=e:this._animatorController=new Zt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}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=Q.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Q.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}_v&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],bt.prototype,"applyRootMotion",2),k([A()],bt.prototype,"hasRootMotion",2),k([A()],bt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],bt.prototype,"runtimeAnimatorController",1);import*as Wr from"three";var Jt=class extends M{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&&he.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let o=this.tryFindHandle(e);if(o)return o.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.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?Wr.LoopRepeat:Wr.LoopOnce),e.play();let r=new jc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.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 Wr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],Jt.prototype,"playAutomatically",2),k([A()],Jt.prototype,"randomStartTime",2);var jc=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}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 wf}from"three/examples/jsm/loaders/GLTFLoader.js";import*as tp from"three";var Ur=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new tp.Vector3}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};var ui=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],ui.prototype,"time",2),k([A()],ui.prototype,"value",2),k([A()],ui.prototype,"inTangent",2),k([A()],ui.prototype,"inWeight",2),k([A()],ui.prototype,"outTangent",2),k([A()],ui.prototype,"outWeight",2),k([A()],ui.prototype,"weightedMode",2);var rr=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 i of this.keys){if(t&&i.time>e&&e>t.time)return Q.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(ui)],rr.prototype,"keys",2);import*as ip from"three";import*as fs from"three";import{PositionalAudioHelper as xv}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Ta=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 at=N("debugaudio");var Be=class extends M{static get userInteractionRegistered(){return Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction()),Be._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Be._userInteractionRegistered){Be._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}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&&(at&&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&&Be._userInteractionRegistered){let e=O.getComponent(this.context.mainCamera,$t)??O.findObjectOfType($t,this.context);e?.listener&&(this.sound=new fs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new fs.AudioLoader,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&&Be._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Be._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Be._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){at&&console.log("audio buffer loaded"),Be.registerWaitForAllowAudio(()=>{at&&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(),at&&console.log(this.name,this.shouldPlay,Be.userInteractionRegistered,this),this.shouldPlay&&Be._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(at&&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?at&&!this.helper&&(this.helper=new xv(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(at&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new fs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){at&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,at&&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,at&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){at&&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(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,at&&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,at&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ue=Be;z(ue,"_didCallBeginWaitForUserInteraction",!1),z(ue,"callbacks",[]),z(ue,"_userInteractionRegistered",!1),k([A()],ue.prototype,"clip",2),k([A()],ue.prototype,"playOnAwake",2),k([A()],ue.prototype,"loop",1),k([A()],ue.prototype,"spatialBlend",1),k([A()],ue.prototype,"minDistance",1),k([A()],ue.prototype,"maxDistance",1),k([A()],ue.prototype,"volume",1),k([A()],ue.prototype,"rollOffMode",2);var $t=class extends M{get listener(){return this._listener==null&&(this._listener=new ip.AudioListener),this._listener}_listener=null;awake(){ue.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=O.getComponentInParent(this.gameObject,ne);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Cv}from"three/examples/jsm/loaders/GLTFLoader";import*as qr from"three";var hp=vl(dp(),1),Ra=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function up(l,e){let t=await l.arrayBuffer(),i=pp(t),n=l.name.split(".").pop(),r=i+"."+n,o=l.name.split(".").shift();console.assert(o!==void 0);let s={alias:o,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new Ra(!0,r,i,l.size);console.log("begin uploading file",o,l.size);let a=new FormData;a.append("file",l);let h={};h.filesize=l.size,o&&(h.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:h})).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===i,"hash sum did not match","received:",f.hash_sum,"expected:",i),f.success&&console.log("successfully uploaded",i,f.id);let E=new Ra(f.success,r,i,l.size);return E.url=e,E}function pp(l){return(0,hp.default)(new Uint8Array(l))}async function Ca(l,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:l});if(r.status!==200)return console.error("download failed",r),null;let o=await r.blob(),s=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);let c=pp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function fp(l,e){let t=await fetch(l),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0,s=[];for(;;){let{done:a,value:h}=await i.read();if(h&&(s.push(h),o+=h.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),a)break}let c=new Uint8Array(o),d=0;for(let a of s)c.set(a,d),d+=a.length;return c}var ms=N("debugavatar"),or=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}assignRandomColors(){Ni.assignRandomPlayerColors(this)}},Ni=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 i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new ye;i=O.instantiate(hn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.assignRandomColors(),n.isValid?(ms&&console.log("[Custom Avatar] valid config",t,ms?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ms?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ms&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let s=await n.blob();s&&(r=await s.arrayBuffer())}return!r&&(r=await Ca(t,t,0,"no url here go away",!0),!r)?null:(await Xr(e,r,null,0))?.scene??null}let i=new Cv;return tr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Sa(e,o,s),n(s.scene)},s=>{ms&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,"head"),r=this.findAvatarPart(i,"left"),o=this.findAvatarPart(i,"right");if(!n){n=t;let c=new qr.Vector3;new qr.Box3().setFromObject(n).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&n.scale.multiplyScalar(1/d*.3)}return new or(t,n,r,o)}findAvatarPart(e,t){for(let i of e.children)if(i.name.toLowerCase().indexOf(t)>-1)return i;return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}static assignRandomPlayerColors(e){let t=new Map;function i(n){if(n.type==="Mesh"){let r=n,o=r.material;if(o&&o.name){if(t.has(o.uuid)){let s=t.get(o.uuid);s&&(r.material=s);return}if(o.name.endsWith("_playercolor")||o.name.endsWith("_player_color2")){let s=o.uuid;r.material=o.clone(),r.material.color=new qr.Color(Math.random(),Math.random(),Math.random()),t.set(s,r.material)}}}}e.head&&e.head.traverse(i),e.leftHand&&e.leftHand.traverse(i),e.rigthHand&&e.rigthHand.traverse(i)}};import{AxesHelper as Sv}from"three";var zi=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!hi)return;this._axes||(this._axes=new Sv(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)}};k([A()],zi.prototype,"length",2),k([A()],zi.prototype,"depthTest",2),k([A()],zi.prototype,"isGizmo",2);import*as gp from"three";var Qr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let o=q(this.hint).clone();o.sub(r);let s=new gp.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),a=Math.sqrt(d*d-c*c),h=s.clone();h.multiplyScalar(a),h.add(r),ie(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Gi from"three";import*as pi from"three";var Pv=new pi.BoxGeometry(1,1,1);function Pa(l=null){let e=new pi.Color(l??14540253),t=new pi.EdgesGeometry(Pv);return new pi.LineSegments(t,new pi.LineBasicMaterial({color:e}))}var Av=N("gizmos"),Oa=class extends M{box=null;testBox=new Gi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Gi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Oa._position),i=Sh(e,Oa._size);this.testBox.setFromCenterAndSize(t,i)}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 Gi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Gi.Vector3(0,0,0),new Gi.Vector3(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(!(!Av&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Pa(e),this.gameObject.add(this._helper)}}},lt=Oa;z(lt,"_position",new Gi.Vector3),z(lt,"_size",new Gi.Vector3(.01,.01,.01));import*as gs from"three";import{FrontSide as bp,DoubleSide as vp}from"three";function Yr(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?vp:bp,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?vp:bp,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Yr(i,e)}function Zr(l,e,t){l[e]===void 0&&console.warn("Field",e,"is undefined on",l);let i=Proxy.revocable(l[e],{set(o,s,c,d){let a=o[s],h=Reflect.set(o,s,c,d);return t(c,a),h}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function yp(l,e,t=3){let i=l.__scheduledActions;i||(i=l.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(l),r[n]=null}let c=l.startCoroutine(s(),t);r[n]=c}var Jr=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.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 gs.Vector3,this._smoothedVelocity=new gs.Vector3,this.lastWorldPosition=q(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=Zr(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 la;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 _(e.x,e.y,e.z),t?new _(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?Jr.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):Jr.tempPosition.set(0,0,0)}setVelocity(e,t,i){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/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 i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){Jr.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(Jr.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=Jr;z(ce,"tempPosition",new gs.Vector3),z(ce,"copyVector3",new gs.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollision",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Aa}from"three";var fi=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],fi.prototype,"attachedRigidbody",2),k([A()],fi.prototype,"isTrigger",2);var _n=class extends fi{radius=.5;center=new Aa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],_n.prototype,"radius",2),k([A(Aa)],_n.prototype,"center",2);var xn=class extends fi{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Aa)],xn.prototype,"size",2),k([A(Aa)],xn.prototype,"center",2);var $r=class{};var kt=class extends M{canGrab=!0;onPointerClick(e){}},It=class extends M{isUsed=!0;usedBy=null};var sr=class extends lt{},Kr=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=O.findObjectsOfType(sr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(O.getComponentInParent(this.gameObject,It)||kr(this.gameObject,this.context.connection))}}};var ar=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||O.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:kv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],ar.prototype,"visibleOn",2);var ka;function kv(){if(ka===!0||ka===!1)return ka;let l=!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)))&&(l=!0)}(navigator.userAgent||navigator.vendor||window.opera),ka=l,l}import*as Vi from"three";var Ce=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,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var eo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,c,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Mt=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 Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__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 eo).__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 Tn=N("debugsync"),to="STRS";Nr(to,Mt.getRootAsSyncedTransformModel);var mi=new ft;function Nc(l,e,t=!0){mi.clear();let i=mi.createString(l);Mt.startSyncedTransformModel(mi),Mt.addGuid(mi,i),Mt.addFast(mi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Mt.addTransform(mi,eo.createTransform(mi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Mt.endSyncedTransformModel(mi);return mi.finish(s,to),mi.asUint8Array()}var Qe=class extends M{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(){Tn&&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(){Tn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Vi.Vector3,this._targetRotation=new Vi.Quaternion,this.lastWorldPos=new Vi.Vector3,this.lastWorldRotation=new Vi.Quaternion,this.rb=O.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new En(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(to,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Lh(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(to,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Vi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Tn&&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){he.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Ph(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){Tn&&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 r=e.distanceTo(this.lastWorldPos),o=t.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(Tn&&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),he.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let o=this._receivedFastUpdate||this.fastMode?.5:.3,s=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,o),this.worldPosition=c,s=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,o),this.worldQuaternion=c,s=!0}s&&he.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&&(Tn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Vi.Vector3(0,0,0))>1e3&&(Tn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){Tn&&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 r=Nc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Ma=class{static createButton(e,t={}){let i=document.createElement("button");function n(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){h.end()}),c.appendChild(d);var a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),a.setAttribute("stroke","#fff"),a.setAttribute("stroke-width",2),d.appendChild(a),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null;async function u(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}function f(){h.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="AR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():o()}).catch(o),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}};var La=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 i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",a),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function a(){c.removeEventListener("end",a),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():o(),La.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),La.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},io=La;z(io,"xrSessionIsGranted",!1);io.registerSessionGrantedListener();import*as Pe from"three";import*as Da from"three";var Ep=vl(wc(),1);import{AudioAnalyser as Mv}from"three";var no="noVoip",ct=N("debugvoip"),Lv=N("voip");var zc=class{id;constructor(e){this.id=e}};var Gc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ct&&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 i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ct&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ct&&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=>{ct&&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(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ct&&console.log("call closed",e)}},Vc=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,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);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,ue.userInteractionRegistered||ct&&console.log("Incoming call, waiting for user interaction before opening audio"),ue.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ct&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Da.AudioListener;this.audio=new Da.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ct&&console.log("call is setup, you should hear something now"),this.analyzer=new Mv(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()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.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 i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.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(N(no)){console.log("VOIP is disabled by url parameter: "+no);return}if(this.requireParam&&!Lv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Ep.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 i=new Gc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ct&&console.log("UserLeftRoom",e,t,n),n&&(n.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){ct&&console.log("Peer connection established and received id"),this.model=new zc(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){ct&&console.log("CONNECTION",t),t.on("data",function(i){ct&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ct&&console.log("received call"),await Ke.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Vc(this,this.gameObject,e),e.on("stream",o=>{ct&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(o)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var ro=N("debugflags");var Wc=class{Mask=17;Has(e){let t=this.Mask&e;return ro&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Se.Apply()}Enable(e){this.Mask|=e,Se.Apply()}Disable(e){this.Mask&=~e,Se.Apply()}Toggle(e){this.Mask^=e,Se.Apply()}EnableAll(){this.Mask=-1,Se.Apply()}DisableAll(){this.Mask=0,Se.Apply()}},vt=Wc;z(vt,"Global",new Wc);var gi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(vt.Global)}awake(){gi.registry.push(this)}onEnable(){gi.firstApply||(gi.firstApply=!0,gi.Apply())}onDestroy(){let e=gi.registry.indexOf(this);e>=0&&gi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),ro&&console.log(i),gi.buffer.Mask=i,e=gi.buffer);let n=e;if(n?(ro&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(ro&&console.log("use global mask"),vt.Global.Has(this.visibleIn)),t!==void 0)if(t)ro&&console.trace("is visible",this.name,this.gameObject.uuid),O.setActive(this.gameObject,!0);else{if(ro&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Se=gi;z(Se,"registry",[]),z(Se,"firstApply"),z(Se,"buffer",new vt);import*as K from"three";import{XRControllerModelFactory as Dv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Hv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as jv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as _p from"three";import*as Kt from"three";var Rn=N("debugavatar"),Wi=class extends M{static onAvatarMarkerCreated(e){return Wi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Wi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Wi.instances.push(this),Rn&&console.log(this);for(let e of Wi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Wi.instances.splice(Wi.instances.indexOf(this),1);for(let e of Wi._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):O.setActive(this.avatar,e))}},fe=Wi;z(fe,"instances",[]),z(fe,"_onNewAvatarMarkerAdded",[]),z(fe,"_onAvatarMarkerDestroyed",[]);var bs=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 Kt.Vector3(1,1,1);handLeftScale=new Kt.Vector3(1,1,1);handRightScale=new Kt.Vector3(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,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 Kt.Object3D;_handLeftTarget=new Kt.Object3D;_handRightTarget=new Kt.Object3D;_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 i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(e.position.x,e.position.y,e.position.z),i.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.headScale),this.handLeft){let n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),n.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),n.quaternion.multiply(bs.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handLeftScale)}if(this.handRight){let n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),n.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),n.quaternion.multiply(bs.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.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(){Rn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&_e.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&O.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Rn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&_e.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;O.setActive(n,!1),e=O.instantiate(n),O.setActive(e,!0)}Rn&&console.log(e);let i=await bs.loader.getOrCreateNewAvatarInstance(this.context,e);if(Rn&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.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=O.addNewComponent(this.root,fe),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&_e.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.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(...O.getComponentsInChildren(this.root,Se)),this.flags.length<=0&&this.head){let n=O.addNewComponent(this.head,Se);n.visibleIn=20,this.flags.push(n),Rn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return Rn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Rn&&console.warn("build avatar failed"),!1}},Lt=bs;z(Lt,"loader",new Ni),z(Lt,"invertRotation",new Kt.Quaternion().setFromAxisAngle(new Kt.Vector3(0,1,0),Math.PI));var _e=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??Z.Current?.time.time;return}}}};z(_e,"Pois",[]),z(_e,"LastChangeTime",0);var Uc=class{guid;position=new _p.Vector3},Ui=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=O.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Uc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=O.getComponentInParent(this.gameObject,fe),this.avatar){let e=O.getComponentInParent(this.gameObject,fe);this._model=new En(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&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(_e.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=_e.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);ie(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=_e.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var lr=class extends M{},Fe=class extends M{static CreateRaycastLine(){let e=new K.Line(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 K.SphereGeometry(.5,22,22),t=new K.MeshBasicMaterial({color:this.raycastColor}),i=new K.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?O.addNewComponent(i,Fe,!1):new Fe;r.webXR=e,r.index=t,r.type=n;let o=e.context;return r.controller=o.renderer.xr.getController(t),r.controllerGrip=o.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=o.renderer.xr.getHand(t),r.hand.add(new Hv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new jv(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(a=>a.layers.set(2)),r.handPointerModel.pointerObject?.traverse(a=>a.layers.set(2));let d=r.hand.joints;if(d)for(let a of Object.keys(d)){let h=d[a];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}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 K.Quaternion),ve(e).multiply(this._wristQuaternion.setFromEuler(new K.Euler(-Math.PI/4,0,0)))):null}movementVector=new K.Vector3;worldRot=new K.Quaternion;joystick=new K.Vector2;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=Fe.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Fe.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 K.Quaternion;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Fe.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(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(ve(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ie(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let o=this.getWristQuaternion();o&&this.rayRotation.copy(o)}Ae(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ae(this.raycastLine,this.rayRotation),ie(this.raycastLine,i);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 i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Fe.MovementSpeedFactor,r=2,o=Q.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=s,c*=o;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,c*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(n*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let f=h>0?-1:1;t.rotateY(Q.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let s=this.handPointerModel.isPinched();s&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),s&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),s||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,o=null;if(t&&this.input&&!this.input.hand)for(let s=0;s<t.length;s++){let c=t[s];if(s===4)if(c.pressed&&!this.didChangeScale){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,Fe.MovementSpeedFactor=1;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance&&(a.far=Fe.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,Fe.MovementSpeedFactor=o*2;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance=a.far,a.far/=o}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let c=s[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return O.getComponentInParent(e,lr)!=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 i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Fe.raycastColor:n.color=Fe.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=Q.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}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 i of e){let n=i.object;if(!this.testIsVisible(n)){console.log("not visible");continue}this.lastSelectStartObject=n;let r={selected:n,grab:n},o=Fe.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=dt.TryTake(this,r.grab,i,t));break}else{let i=Fe.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_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=Fe.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?O.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new K.Ray;return e.origin.copy(q(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=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new je;return e.layerMask=new K.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},se=Fe;z(se,"Factory",new Dv),z(se,"raycastColor",new K.Color(.9,.3,.3)),z(se,"raycastNoHitColor",new K.Color(.6,.6,.6)),z(se,"geometry",new K.BufferGeometry().setFromPoints([new K.Vector3(0,0,0),new K.Vector3(0,0,-1)])),z(se,"handModels",{}),z(se,"eventSubs",{}),z(se,"PreviousCameraFarDistance"),z(se,"MovementSpeedFactor",1);var et=class{static AddEventListener(e,t){return et.Events[e]||(et.Events[e]=[]),et.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!et.Events[e])return;let i=et.Events[e].indexOf(t);i>=0&&et.Events[e].splice(i,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,i,n){let r=O.getComponentInParent(t,kt);if(!r)return console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=O.getComponentInParent(t,Qe);s&&(s.requestOwnership(),o=s.gameObject);for(let d of this.Current)if(d.selected===o)return d.controller===e||(d.free(),d.Take(e,o,t,s,r,i,n)),d;let c=new et;return c.Take(e,o,t,s,r,i,n),c}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,i,n,r,o,s){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=s?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};et.Events.WillTake?.forEach(f=>f(this,c));let d=i;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=s,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=O.addNewComponent(this.selected,It),this.rigidbodies=O.getComponentsInChildren(this.selected,ce),q(this.positionSource,this.lastControllerWorldPos);let a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());let h=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ve(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),_e.Add(e.context,this.selected),et.Register(this),this.sync&&(this.sync.fastMode=!0),et.Events.DidTake?.forEach(f=>f(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};et.Events.WillFree?.forEach(n=>n(this,e)),_e.Remove(this.controller.context,this.selected),et.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}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 n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,et.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new K.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new K.Vector3;localQuaternionToGrab=new K.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new K.Vector3;controllerWorldPos=new K.Vector3;lastControllerWorldPos=new K.Vector3;controllerPosDelta=new K.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new K.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(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 i=q(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}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 K.Vector3),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ae(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});he.markDirty(this.selected,!0)}}},dt=et;z(dt,"Events",{}),z(dt,"Current",[]);import*as Ha from"three";var Dt=class extends M{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,i){if(i&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new Ha.Matrix4().fromArray(i.transform.matrix).invert(),e){if(this.invertForward){let n=new Ha.Matrix4().makeRotationY(Math.PI);this._placementPose.premultiply(n)}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),he.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 Ha.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};k([A()],Dt.prototype,"invertForward",2),k([A()],Dt.prototype,"arScale",1);var Cn=class extends M{awake(){}};import{Object3D as Bv}from"three";var cr=N("debugaddressables"),ja=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}},tt=class{static getOrCreate(e,t,i){let n=Ms(e,t);cr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new tt(n);return r.registerAssetReference(s),s}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,Bh(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&&(cr&&console.log("Unload",this.asset),this.asset.scene?O.destroy(this.asset.scene):O.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,cr&&console.log("Preload",this.uri);let e=await fp(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=Z.Current;this._rawBinary?(this._loading=Xr(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(cr&&console.log("Load async",this.uri),this._loading=dr(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return ki(t),i.scene!==void 0&&(this.asset=i),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,i){let n=Z.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),cr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){cr&&console.log("Add to scene",this.asset);let r=e instanceof ye?e:null;if(r||(r=new ye),typeof e=="object"&&(e instanceof Bv?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Ws(o,r,void 0,i);if(s)return s}else{let o=O.instantiate(this.asset,r);if(o)return o}}else cr&&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}},qc=class extends Fi{constructor(){super([tt])}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?tt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new qc;import*as yt from"three";var bi=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,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Me=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 Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__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 Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new bi).__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 Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new bi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new bi).__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 xp=N("debugxr"),vs=N("debugavatar");var Qc="VRUS";Nr(Qc,Me.getRootAsVrUserStateBuffer);function Xc(){return new Date().getTime()}function Fv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Xe.create(e,t)}var ys=class{guid;time;avatarId;position=new yt.Vector3;rotation=new yt.Vector4;scale=1;posLeftHand=new yt.Vector3;posRightHand=new yt.Vector3;rotLeftHand=new yt.Quaternion;rotRightHand=new yt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Xc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=ys.quat0,s=ys.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,ys.invertRotation),e&&(e.getWorldQuaternion(s),o.multiplyQuaternions(s,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let a=n.LeftController.wrist;a&&(a.getWorldPosition(this.posLeftHand),a.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let a=n.RightController.wrist;a&&(a.getWorldPosition(this.posRightHand),a.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,Fv(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,bi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,bi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,bi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,Qc);let o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());let s=t.posRightHand();s&&this.posRightHand.set(s.x(),s.y(),s.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},Ht=ys;z(Ht,"invertRotation",new yt.Quaternion().setFromAxisAngle(new yt.Vector3(0,1,0),Math.PI)),z(Ht,"quat0",new yt.Quaternion),z(Ht,"quat1",new yt.Quaternion);var qi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent($)),this.webXR||(this.webXR=O.findObjectOfType($,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=O.findObjectOfType($,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=O.findObjectOfType(Ke,this.context)),vs){let e="debug-avatar-"+vs,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof vs=="string"&&vs.length>0)if(await t.setAvatarOverride(vs)){let i=new Ht(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=O.getComponent(this.gameObject,$),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),$.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.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(Qc,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Ht("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return xp&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Lt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Xc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Xc();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.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 Lt(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(){xp&&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 ft(1024);onXRSessionUpdate(e){this.xrState??=new Ht(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new En(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:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let o=r?.transform,s=o.position,c=o.orientation;this.xrState.update(n,s,c,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 N("avatar")}};async function Nv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Yc=!1,Zc=!1;Nv().then(l=>Yc=l);zv().then(l=>Zc=l);var Ne=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Yc||Zc)}static get IsARSupported(){return Yc}static get IsVRSupported(){return Zc}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){Ne.XRSupported||console.warn("WebXR is not supported on this device");let i=io.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={requiredFeatures:["hit-test"]};i&&(n.domOverlay={root:i},n.optionalFeatures=["dom-overlay"]);let r=Ma.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ne.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}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=tt.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!O.findObjectOfType(qi,this.context)){let e=O.addNewComponent(this.gameObject,qi,!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 Sn(this);let e=Ne.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ne.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ne.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ne.resetButtonStyles(i),Ne.resetButtonStyles(t)},1e3)}_transformOrientation=new Pe.Quaternion;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 i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Ne._isInXr===!1&&t&&this.onEnterXR(t,e),Ne.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++)se.Create(this,e,this.gameObject,0);Ne.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ve(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=O.findObjectOfType(Cn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Pe.Group,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Pe.Vector3;_originalCameraRotation=new Pe.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ne._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let s=t.getViewerPose(i)?.transform.orientation;if(s){let c=new Pe.Quaternion(s.x,s.y,s.z,s.w),d=new Pe.Euler().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let o=n.getCamera(this.context.mainCamera);for(let s of o.cameras)s.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(vt.Global.Set(r),r){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"),Ne._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ne.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),ie(this.context.mainCamera,this._originalCameraPosition),Ae(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),vt.Global.Set(17),Ne.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){!N("mirror")||setTimeout(()=>{if(!Ne.IsInWebXR)return;let t=new URL(window.location.href);Or(t.searchParams,no,1),Or(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Ne.IsInWebXR&&e.end()})})},1e3)}},$=Ne;z($,"_isInXr",!1),z($,"events",new Pe.EventDispatcher),k([A(tt)],$.prototype,"defaultAvatar",2);var oo=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 i=0;i<4;i++)se.Create(this.webxr,i,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=O.findObjectOfType(Dt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(i=>{e.requestHitTestSource({space:i}).then(n=>{this.hitTestSource=n})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Pe.Mesh(new Pe.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new Pe.MeshBasicMaterial),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,oo.tempWebXRObject||(oo.tempWebXRObject=new Pe.Object3D),this.context.scene.add(oo.tempWebXRObject),O.addComponent(oo.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),O.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 i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let o=n.getPose(r);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,o),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&o)){let s=o.transform.matrix;this.reticle.matrix.fromArray(s),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)}},Sn=oo;z(Sn,"tempWebXRObject");var Jc=!1;var so=class extends kt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}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)||$.IsInWebXR)return;let t=O.getComponentInParent(e.object,so);!t||t!==this||(so.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||so.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&($.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!$.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 Ba(this.context.mainCamera);else return;if(!e||!e.object)return;let t=O.getComponentInParent(e.object,so);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=O.getComponentInChildren(i,Qe);Jc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=O.addNewComponent(i,It),this._draggingRigidbodies.length=0;let o=O.getComponentsInChildren(i,ce);o&&this._draggingRigidbodies.push(...o);let s=El();O.invokeOnChildren(this._dragHelper.selected,s("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(Jc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=O.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=El();O.invokeOnChildren(t,i("onDragEnd"))}},Et=so;z(Et,"_active",null),z(Et,"lastHovered");var Kc=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line(Kc.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),o=new ee.Mesh(n,r);o.visible=!1,o.layers.set(2),this._groundMarker=o}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&_e.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}_e.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=O.getComponentsInChildren(this._selected,ce),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,i=68,n=83,r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){Jc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&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,h){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&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,i){if(!!this._selected){if(i){let n=q(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(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=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new je;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let o=n[r];if(!o.face||this.contains(this._selected,o.object))continue;let s=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(s,o.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(){he.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 i of e.children)if(this.contains(i,t))return!0}return!1}},Ba=Kc;z(Ba,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Pn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?pt.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 i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let o=await Rp(r,this.context,this.filesBackendUrl);o&&this.addObject(e,o)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let o=new URL(r);if(!o)return;let s=await Cp(o,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new je;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let o of n){r.position.copy(o.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:r}))}};k([A()],Pn.prototype,"filesBackendUrl",2),k([A()],Pn.prototype,"localhost",2);import{Vector3 as Vv,Quaternion as Wv,Object3D as Sp}from"three";var vi=class extends kt{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 Vv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Wv(0,0,0,1)}let e=O.getComponentInParent(this.gameObject,Et);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),se.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),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 ye;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 i=O.instantiateSynced(this.object,t);return console.assert(i!==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),i}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 i of e.children)if(this.isInChildren(i,t))return!0}return!1}};k([A(Sp)],vi.prototype,"parent",2),k([A(Sp)],vi.prototype,"object",2),k([A()],vi.prototype,"limitCount",2),k([A()],vi.prototype,"limitInterval",2);var yi=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)}}},Uv=l=>/^[A-Z]*$/.test(l),hr=class extends Event{args},Oe=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Uv(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_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 i=new hr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new yi(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 ao=class extends M{};import{FlyControls as qv}from"three/examples/jsm/controls/FlyControls";var lo=class extends M{_controls=null;onEnable(){let e=O.getComponent(this.gameObject,ne)?.cam;this._controls=new qv(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)}};import*as Op from"three";import{Color as Xv}from"three";var Xi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!hi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Op.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Pa(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}};k([A()],Xi.prototype,"objectBounds",2),k([A(Xv)],Xi.prototype,"color",2),k([A()],Xi.prototype,"isGizmo",2);import{GLTFExporter as Jv}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as ed,Matrix4 as Qv,Vector3 as Ap,Quaternion as Yv}from"three";var Es=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let o=new Qv,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new Ap,b=new Yv,y=new Ap;o.decompose(E,b,y),s.push(E.x,E.y,E.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(s),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new ed(a,3)),ROTATION:i.processAccessor(new ed(h,4)),SCALE:i.processAccessor(new ed(u,3))},n[this.name]=!0}};import{Object3D as $v,Vector3 as Kv}from"three";var On=Ie,Fa="$___Export_Components",Zv="NEEDLE_components",td=class{[Wn]},id=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},co=class{get name(){return Zv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Fa]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&On&&console.log("DONE",JSON.stringify(t)),e[Fa]===void 0)return;let i=e[Fa];delete e[Fa],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new id(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){On&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,o=i.nodeIndex,s=n.userData?.components;if(!s||s.length<=0)continue;let c=new td;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=o,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let a of s){this.context.target=a;let h=kp(a,this.context);h!==null&&d.push(h)}d.length>0&&(c[Wn]=d,On&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return On&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];On&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let o=t.json.nodes;for(let s=0;s<o.length;s++){let c=await t.getDependency("node",s);this.nodeToObjectMap[s]=c}for(let s=0;s<o.length;s++){let c=o[s],d=s,a=c.extensions;if(!a)continue;let h=a[this.name];if(!h)continue;On&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Wn];if(i){On&&console.log(e.name,i);for(let n in i){let r=i[n];On&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Gr(this.parser,r),e.userData=e.userData||{},e.userData[Wn]=e.userData[Wn]||[],e.userData[Wn].push(r)}}}};var ho=class extends lt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},jt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?jt.saveArrayBuffer(i,e):jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Jv,this.exporter.register(s=>new Es(s)),this.ext=new co,this.ext.registerExport(this.exporter)),jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:jt.collectAnimations(e)},n=new $v;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(s=>{s&&(n.children.push(s),s.matrixAutoUpdate=!1,s.matrix.copy(s.matrixWorld),O.getComponentsInChildren(s,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Vr(n);return this.ext.context=r,new Promise((s,c)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,O.getComponentsInChildren(s,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.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 i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new Kv;return i.set(0,0,0),e.forEach(n=>{i.add(q(n))}),console.log(i),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};import{Color as Na,GridHelper as ey}from"three";var Qi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!hi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new ey(e,t,this.color0??new Na(.4,.4,.4),this.color1??new Na(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Qi.prototype,"isGizmo",2),k([A(Na)],Qi.prototype,"color0",2),k([A(Na)],Qi.prototype,"color1",2);import{GroundProjectedEnv as ty}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Yi=class extends M{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 Is(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 ty(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))}};k([A()],Yi.prototype,"scale",1),k([A()],Yi.prototype,"radius",1),k([A()],Yi.prototype,"height",1);import*as it from"three";import{Color as iy}from"three";function nd(l){return l*Math.PI/180}var Ip=300,Mp=N("debuglights");var Ye=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new it.Color(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 i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}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 i=t.shadow.camera;i.far=e,i.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 it.Color(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=$.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=$.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){$.removeEventListener("xrStarted",this._webXRStartedListener),$.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Dt)??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 it.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Ip*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Ar(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Mp){let o=new it.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new it.SpotLight(this.color,this.intensity*Math.PI,this.range,nd(this.spotAngle/2),1-nd(this.innerSpotAngle/2)/nd(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new it.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;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=Ip*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 i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Mp&&this.context.scene.add(new it.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};k([A()],Ye.prototype,"type",2),k([A(iy)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var VO=new it.Vector3(0,0,0);import*as za from"three";import{Vector3 as ny}from"three";var uo=N("debugLODs"),ry=N("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};k([A()],Ei.prototype,"screenRelativeTransitionHeight",2),k([A()],Ei.prototype,"distance",2),k([A()],Ei.prototype,"renderers",2);var rd=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):uo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=O.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},An=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!ry&&!this._lodsHandler&&!!this.gameObject&&(uo&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new rd(this,n);this._lods.push(r);for(let o of r.renderers)t.includes(o)||t.push(o)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new za.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new za.Object3D;uo&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,c=0,d=0;uo&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,uo&&console.log("add",h.model.distance,u.name);let f=h.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,u,f)}let a=c+d;uo&&console.log("cull",a),this.onAddLodLevel(o,i,a)}}}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,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};k([A(ny)],An.prototype,"localReferencePoint",2),k([A(Ei)],An.prototype,"lodModels",2);var po=class extends M{onEnable(){this.enabled&&this.context.physics.addMeshCollider(this.gameObject)}};var fo=class extends M{},mo=class extends M{};var od=N("debugnestedgltf"),ur=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;od&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ye;t.idProvider=new We(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;od&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),od&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};k([A(tt)],ur.prototype,"filePath",2);import*as bo from"three";var go=class extends M{from;affectPosition;affectRotation;alignLookDirection;levelLookDirection;positionOffset;rotationOffset;update(){if(!this.from)return;var e=q(this.from),t=ve(this.from);this.affectPosition&&ie(this.gameObject,e.add(this.positionOffset));let i=new bo.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),n=new bo.Quaternion().setFromEuler(i);this.affectRotation&&Ae(this.gameObject,t.multiply(n));let r=new bo.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}};import*as xe from"three";import*as ei from"three";var vo=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 ei.Color(1,1,1);startColor1=new ei.Color(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 ei.Vector2(0,1);cullingMode=0},yo=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Eo=class{shapeType=sd.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ei.Vector3(1,1,1);boxThickness=new ei.Vector3(0,0,0);position=new ei.Vector3(0,0,0);rotation=new ei.Vector3(0,0,0);scale=new ei.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},sd=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(sd||{});var Lp=N("debugparticles"),ad=class{age=0;lifetime=0;position;velocity;color},pr=class extends M{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(){Lp&&console.log(this)}},wo=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new xe.Quaternion;tempVec3=new xe.Vector3;tempQuat=new xe.Quaternion;awake(){this.renderer=O.getComponent(this.gameObject,pr),Lp&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new xe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new xe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new xe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new xe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new xe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new xe.Points(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 i=this.particleStates[t];if(!i)continue;let n=i.velocity.x*e,r=i.velocity.y*e,o=i.velocity.z*e;i.position.x+=n,i.position.y+=r,i.position.z+=o,this.updateOverLifetime(t,i),this.geometry.attributes.position.setXYZ(t,i.position.x,i.position.y,i.position.z),this.geometry.attributes.color.setXYZ(t,i.color.r,i.color.g,i.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new ad;r.lifetime=this.main.startLifetime??1,r.position=new xe.Vector3,r.velocity=new xe.Vector3,r.color=new xe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}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 i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.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 i=new xe.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Q.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)}};import*as Hp from"three";function*Dp(l,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<l;)yield}var ht=class extends M{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 Dp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=O.getComponentInParent(this.gameObject,fe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ht.hashCode(e),i=ht.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t?(n=n.clone(),n._playerMaterial=t,i.material=n):console.log("DONT CLONE",n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new Hp.Color(t/255,i/255,n/255)}};import*as Ga from"three";import{Object3D as ay}from"three";function sy(){return new Promise((l,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),l())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function jp(l){await sy(),l()}var ld=N("debugvideo");var nt=class extends M{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,ld&&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(),jp(()=>{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)}),ld&&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 Ga.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ga.sRGBEncoding,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ld&&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")}};k([A(ay)],nt.prototype,"renderer",2),k([A()],nt.prototype,"playOnAwake",2),k([A()],nt.prototype,"playOnEnable",2),k([A()],nt.prototype,"targetMaterialProperty",2),k([A()],nt.prototype,"time",2),k([A()],nt.prototype,"playbackSpeed",1),k([A()],nt.prototype,"isLooping",1);var _o=class extends M{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=O.getComponentInChildren(this.gameObject,nt);if(t){let i={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(i),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}}};import{ShadowMaterial as ly,AdditiveBlending as cy}from"three";var kn=class extends M{mode=0;shadowColor=new we(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=O.getComponent(this.gameObject,Te);if(e){let t=e.material;t.blending=cy,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
123
+ `,defines:{USE_LIGHTMAP:""}})}};var A=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=Bu(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=Bu(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function Bu(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}import{Vector4 as Kb}from"three";import{NeverStencilFunc as Ib,LessStencilFunc as Mb,EqualStencilFunc as Lb,LessEqualStencilFunc as Db,GreaterStencilFunc as Hb,NotEqualStencilFunc as jb,GreaterEqualStencilFunc as Bb,AlwaysStencilFunc as Fb,ZeroStencilOp as Nb,KeepStencilOp as zb,ReplaceStencilOp as Gb,IncrementStencilOp as Vb,DecrementStencilOp as Wb,IncrementWrapStencilOp as Ub,DecrementWrapStencilOp as qb,InvertStencilOp as Xb}from"three";var rc=N("debugstencil");function Qb(l,e){return(l&1<<e.layer)!=0}var Kn=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(rc&&console.log(t,Kn.stencils),!t)return;let i=Kn.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Qb(r.layer,e)){rc&&console.log(r);let o=e.material?.clone();o&&(e.material=o,e.gameObject.renderOrder=r.event*1e3+r.index*50,o.stencilWrite=!0,o.stencilWriteMask=255,o.stencilFuncMask=255,o.stencilRef=r.value,o.stencilFunc=r.compareFunc,o.stencilZPass=r.passOp,o.stencilFail=r.failOp,o.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Zb];if(i){rc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Yb(o.compareFunc),o.passOp=oc(o.passOp),o.failOp=oc(o.failOp),o.zFailOp=oc(o.zFailOp),Kn.stencils[this.source]||(Kn.stencils[this.source]=[]),Kn.stencils[this.source].push(o)}}}return null}},er=Kn;z(er,"stencils",{});function oc(l){switch(l){case 0:return zb;case 1:return Nb;case 2:return Gb;case 3:return Vb;case 4:return Wb;case 6:return Ub;case 7:return qb;case 5:return Xb}return 0}function Yb(l){switch(l){case 1:return Ib;case 2:return Mb;case 3:return Lb;case 4:return Db;case 5:return Hb;case 6:return jb;case 7:return Bb;case 8:return Fb}return 0}var Zb="NEEDLE_render_objects";import{TextureLoader as Jb}from"three";import{GLTFLoader as $b}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as sc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Fu}from"three/examples/jsm/loaders/KTX2Loader.js";var os=N("debugdecoders"),Ut,bn;function ac(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),os&&console.log("Setting draco decoder path to",l),Ut.setDecoderPath(l))}function lc(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),os&&console.log("Setting draco decoder type to",l),Ut.setDecoderConfig({type:l}))}function cc(l){l!==void 0&&typeof l=="string"&&(bn||(bn=new Fu),os&&console.log("Setting ktx2 transcoder path to",l),bn.setTranscoderPath(l))}function tr(l,e){Ut||(Ut=new sc,Ut.setDecoderPath("./include/draco/"),Ut.setDecoderConfig({type:"js"}),os&&console.log("Setting draco decoder path to","./include/draco/")),bn||(bn=new Fu,bn.setTranscoderPath("./include/ktx2/"),os&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&bn.detectSupport(e.renderer)),l.setDRACOLoader(Ut),l.setKTX2Loader(bn)}var dc="NEEDLE_deferred_texture",vn=N("debugdeferredtextures"),ss=class{static assignTextureLOD(e,t,i=0){if(!!t)for(let n of Object.keys(t)){let r=t[n];r?.isTexture===!0&&(vn&&console.log("FIND",n,r?.name,r?.userData,r),ss.getOrLoadTexture(e,t,n,r,i).then(o=>{o?.isTexture===!0&&(o.needsUpdate=!0,t[n]=o,t.needsUpdate=!0)}))}}get name(){return dc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return vn&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[dc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{vn&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,ss.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r){let o=n.uuid,s=ss.cache.get(o)||n.userData.deferred;if(s){vn&&console.log(o,s.uri,s.guid);let c=s.uri;if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!s.guid)return console.warn("missing pointer for glb/gltf texture",s),null;let d=s.uri+"_"+s.guid;if(this.resolved[d])return this.resolved[d];let a=new $b;tr(a,e),vn&&console.log("Load "+c,t.name,i);let h=await a.loadAsync(c),u=h.parser,f=-1,E=!1;for(let y of h.parser.json.textures)if(f++,y?.extensions){let g=y?.extensions[dc];if(g?.guid&&g.guid===s.guid){E=!0;break}}if(!E)return null;let b=await u.getDependency("texture",f);return this.resolved[d]=b,vn&&console.log(t.name,i,'change "'+n.name+'" \u2192 "'+b.name+'"',c,f,b,t),b}else{let a=await new Jb().loadAsync(s.uri);return a&&vn?console.log(s,a):console.warn("failed loading",s.uri),a}}else vn&&console.warn("unknown uuid",n.name,n.uuid,n);return null}},ji=ss;z(ji,"cache",new Map),z(ji,"resolved",{});var zu=N("noInstancing"),Gu=!!N("debuglightmaps"),ev=N("debuginstancing"),tv=N("debugprogressiveload"),Hr=class{path=null;asset=null;default};var hc=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,o){if(typeof o=="string"){let s=parseInt(o);if(!isNaN(s))return i(s)}return r[o]},set(r,o,s){return typeof o=="string"&&t(s,Number.parseInt(o)),Reflect.set(r,o,s)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},gc=class extends M{receiveShadows=!1;shadowCastingMode=uc.Off;lightmapIndex=-1;lightmapScaleOffset=new li.Vector4(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 hc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return zu}_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 i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||O.getComponent(n,gc))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.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 i=new Hi(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Gu)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Hi(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Gu),n.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=iv.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return O.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return O.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&&!zu&&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(){er.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,tv?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{ji.assignTextureLOD(this.context,r)},2e3)):ji.assignTextureLOD(this.context,r)),r.envMapIntensity!==void 0){let s=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/s)}if(this._lightmaps)for(let s of this._lightmaps)s.onBeforeRenderThree(r)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[pc]===!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[pc],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&O.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.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==uc.On?e.castShadow=!0:e.castShadow=!1}},Te=gc;k([A()],Te.prototype,"receiveShadows",2),k([A()],Te.prototype,"shadowCastingMode",2),k([A()],Te.prototype,"lightmapIndex",2),k([A(Kb)],Te.prototype,"lightmapScaleOffset",2),k([A()],Te.prototype,"enableInstancing",2),k([A()],Te.prototype,"renderOrder",2),k([A()],Te.prototype,"allowOcclusionWhenDynamic",2);var ir=class extends Te{},jr=class extends ir{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},uc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(uc||{}),pc="NEEDLE_NEED_UPDATE_INSTANCE",he=class{static markDirty(e,t=!0){if(!!e&&(O.isUsingInstancing(e)&&(e[pc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)he.markDirty(i,!0)}},fc=class{objs=[];setup(e,t,i,n,r=0){let o=this.tryCreateOrAddInstance(e,t,n);if(o)return i===null&&(i=[]),i.push(o),i;if(r<=0&&e.type!=="Mesh"){let s=r+1;for(let c of e.children)i=this.setup(c,t,i,n,s)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,o=r.geometry,s=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===o&&d.material===s)return d.addInstance(r);let c=new aa(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},iv=new fc,mc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,O.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)}},bc=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,ev&&(i=new li.MeshBasicMaterial({color:this.randomColor()})),this.inst=new li.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new li.Color(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 mc(-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 i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,bc.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,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}},aa=bc;z(aa,"nullMatrix",new li.Matrix4);var as=N("debugphysics"),nv=N("debugcollisions"),la=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ls=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},vc=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var je=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 ke.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new ke.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(je,"AllLayers",4294967295);var yc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},ca=class{raycaster=new ke.Raycaster;defaultRaycastOptions=new je;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ke.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new ke.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new ke.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new yc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let s=this.context.mainCamera;if(!s)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,s)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ke.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(s=>!o.includes(s.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new sa;objects=[];tempPosition=new ke.Vector3;tempQuaternion=new ke.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),as){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},ju(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 i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(i);let n=new ls(e,i);return n._hasRigidbody=!0,this.objects.push(n),as&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let o=this.tempPosition;e.getWorldScale(o);let s=new _(.5*o.x*n.x,.5*o.y*n.y,.5*o.z*n.z),c=new Jn(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.isAlreadyRegistered(d))return c;let a=new ls(e,d);this.objects.push(a)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new ra(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.isAlreadyRegistered(c))return s;let d=new ls(e,c);this.objects.push(d)}return s}addMeshCollider(e){as&&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,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC,this.world.addBody(r)),r){i.x*=-1;let o=ve(e),s=q(e);s.add(i);let c=new ke.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);o.multiply(c.invert());let d=r.position,a=new _(s.x-d.x,s.y-d.y,s.z-d.z),h=new le(o.x,o.y,o.z,o.w);r.addShape(t,a,h),r.updateMassProperties()}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,as&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new ke.Vector3;tempQuat=new ke.Quaternion;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;i.sleepTick(this.context.time.time),as&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING;let n=t.obj;if(i.type===G.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=ve(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Ch(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Ar(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&he.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new le(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);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 i=new vc(t.contact,t.type),n=0,r=this.objects;function o(){if(!(n>0))for(let s=0;s<r.length;s++){if(n==2)return;let c=r[s];c.body==t.body?(i.obj=c.obj,++n):c.body==t.target&&(i.target=c.obj,++n)}}nv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let s=0;s<e.userData?.components?.length;s++){let c=e.userData.components[s];c.onCollision&&(o(),c.onCollision(i))}}};import{Clock as rv}from"three";var da=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 rv;_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)}};import{WebsocketBuilder as sv}from"websocket-ts";function Vu(l=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(l)===!0}var pt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?pt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=N(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=pt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Vu(e)}};var ci=new Int32Array(2),ha=new Float32Array(ci.buffer),ua=new Float64Array(ci.buffer),Br=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var cs;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(cs||(cs={}));var di=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new di(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 Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ci[0]=this.readInt32(e),ha[0]}readFloat64(e){return ci[Br?0:1]=this.readInt32(e),ci[Br?1:0]=this.readInt32(e+4),ua[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){ha[0]=t,this.writeInt32(e,ci[0])}writeFloat64(e,t){ua[0]=t,this.writeInt32(e,ci[Br?0:1]),this.writeInt32(e+4,ci[Br?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 i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+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 i=this.readInt32(e),n="",r=0;if(e+=4,t===cs.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let o,s=this.readUint8(e+r++);if(s<192)o=s;else{let c=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(c&63)<<6|d&63;else{let a=this.readUint8(e+r++);o=(s&7)<<18|(c&63)<<12|(d&63)<<6|a&63}}}o<65536?n+=String.fromCharCode(o):(o-=65536,n+=String.fromCharCode((o>>10)+55296,(o&(1<<10)-1)+56320))}return n}__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 Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var ft=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=di.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 i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=ft.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}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,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(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 i=t<<1,n=di.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}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 i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(c+d))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let o=4-1;o>=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,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 i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let o=e.charCodeAt(i++);n=(r<<10)+o+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));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 Wu={};function Nr(l,e){Wu[l]=e}function Uu(l){let e=l.getBufferIdentifier(),t=Wu[e];return t(l)}function qu(l){return typeof l.guid=="function"?l.guid():null}var _c=vl(wc(),1);var fa=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 _c.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Tc(t)})}trySetupClient(e){this._client=new _c.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",i=>{console.log("<<",i)})})}},xc=class{_peer;constructor(e){this._peer=e}};var Tc=class extends xc{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(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var Rc="wss://needle-tiny-starter.glitch.me/socket",mt=!!N("debugnet"),ma=!!(mt||N("debugowner"));var En=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||(ma&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return ma&&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?(ma&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(ma&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var ga=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new fa),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mt}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(),mt&&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,i=2){if(t===null&&(t={}),i===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){mt&&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 i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mt&&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 i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,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 i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}connect(){if(this.connected)return;mt&&console.log("connecting");let t=O.findObjectOfType(pt,this.context,!1)?.getWebsocketUrl();t&&(Rc=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 "+Rc);let e=new sv(Rc).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,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{mt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new di(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=Uu(n),c=qu(s);if(c&&typeof c=="string"&&(this._state[c]=s),!o)return;let d=s??n;for(let a of o)a(d)}handleIncomingStringMessage(e){if(mt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let o=e.data;o&&(console.assert(o.id!==void 0&&o.id!==null&&o.id.length>0,"server did not send connection id",o.id),console.log("Your id is: "+o.id,this.context.alias??""),this._connectionId=o.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mt&&console.log(e),e){this._isInRoom=!0;let o=e;this._currentRoomName=o.room,this._currentRoomViewId=o.viewId,this._currentRoomAllowEditing=o.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...o.inRoom),mt&&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 o=e.data;this._currentInRoom.push(o.userId),mt&&console.log(o.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let o=e.data,s=this._currentInRoom.indexOf(o.userId);s>=0&&(console.log(o.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),o.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),mt&&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 n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));mt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import*as Xt from"three";import{OrbitControls as lv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as av}from"three";var Bi=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(av)],Bi.prototype,"sources",2);import*as ds from"three";var gt=class extends M{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 ds.Vector3}onEnable(){this._enableTime=this.context.time.time;let t=O.getComponent(this.gameObject,ne)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new lv(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=O.getComponent(this.gameObject,ne);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new ds.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new je;e.screenPoint=new ds.Vector2(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 i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[e];if(n)return n.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&&O.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A(Bi)],gt.prototype,"lookAtConstraint",2);import{Color as cv}from"three";var we=class extends cv{alpha=1;constructor(e,t,i,n){super(e,t,i),this.alpha=n}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 i=e;return i.alpha&&(this.alpha=Q.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as dv}from"three";var Qu=N("debugcam"),ne=class extends M{get aspect(){return this._cam instanceof dv?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 Xt.PerspectiveCamera&&(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(){Qu&&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 Xt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Xt.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,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 Cc(this)),this._skybox.enable()}};k([A()],ne.prototype,"fieldOfView",1),k([A()],ne.prototype,"nearClipPlane",1),k([A()],ne.prototype,"farClipPlane",1),k([A()],ne.prototype,"clearFlags",1),k([A()],ne.prototype,"orthographic",2),k([A()],ne.prototype,"orthographicSize",2),k([A()],ne.prototype,"ARBackgroundAlpha",2),k([A(we)],ne.prototype,"backgroundColor",1);var Cc=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?(Qu&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Xt.sRGBEncoding,this._skybox.mapping=Xt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Yu(l){let e="created/implictly",t=new Xt.Object3D;l.add(t);let i=O.addNewComponent(t,ne,!1);i.sourceId=e;let n=O.addNewComponent(t,gt,!1);return n.sourceId=e,i}import{EffectComposer as SE}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as PE}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as hv,MathUtils as uv}from"three";var zr=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,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Zu(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??uv.generateUUID(),index:-1,clip:new hv(l,1,[])}}import{AnimationClip as vv,AnimationMixer as yv,AxesHelper as Ev,Euler as ep,LoopOnce as wv,Quaternion as Qt,Vector3 as ps}from"three";import*as xa from"three";var Sc=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},D=new Sc;var hi=N("gizmos"),Ie=N("debugextension");var va=N("debugresolvedependencies"),pv=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Gr(l,e){va&&console.log(l,e);let t=[];Oc(pv,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Oc(l,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let o=Ju(e,r);if(o!==null)typeof o.then=="function"?i.push(o.then(s=>t[n]=s)):t[n]=o;else for(let s of l){let c=Ac(s.prefix,r);if(c>=0){va&&console.log(s,c,s.dependencyName),i.push(e?.getDependency(s.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],c=Ju(e,s);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[o]=d)):r[o]=c;continue}for(let d of l){let a=Ac(d.prefix,s);if(a>=0){va&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(h=>r[o]=h));break}}typeof s=="object"&&Oc(l,e,s,i)}else typeof r=="object"&&Oc(l,e,r,i)}else typeof t=="string"&&fv(l,e,t,i)}var Pc="extensions/";function Ju(l,e){if(l&&l.plugins&&typeof e=="string"&&e.startsWith(Pc)){let t=e.substring(Pc.length),i=t.indexOf("/");i>=0&&(t=t.substring(0,i));let n=l.plugins[t];if(Ie&&console.log(t,n),typeof n?.resolve=="function"){let r=e.substring(Pc.length+t.length+1);return n.resolve(l,r)}}return null}function fv(l,e,t,i){for(let n of l){let r=Ac(n.prefix,t);if(r>=0)return va&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function Ac(l,e){if(typeof e=="string"&&e.startsWith(l)){let t=e.substring(l.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var kc="NEEDLE_persistent_assets";function $u(l){return l?.___persistentAsset===!0}var ya=class{get name(){return kc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[kc];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Gr(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[kc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var nr=N("debugserializer"),Ic=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])}nr&&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){nr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){nr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return nr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){nr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let s=r.prototype??r.constructor;if(s!==e){let c=this.getSerializerForConstructor(s,++t);if(c){nr&&console.log("FOUND "+s.constructor.name,s.name,s,c);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,c):this.register(d,c)}return c}}},wa=new Ic,Fi=class{constructor(e){if(Array.isArray(e))for(let t of e)wa.register(t.name,this);else wa.register(e.name,this)}},Vr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Lc(l,e){let t=l.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=l[n];if(r!=null&&typeof r=="object"){let o=wa.getSerializerForConstructor(r);if(o){i[n]=o.onSerialize(r,e);continue}}i[n]=r}return i.name=l.constructor.name,typeof l.guid=="string"&&(i.guid=l.guid),i}var Ea=[];function Ku(l,e){if(!l)return e;typeof l.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,l.$serializedTypes));let t=Object.getPrototypeOf(l);return Ku(t,e)}function hs(l,e,t){if(!l)return!1;if(t.target=l,l.onBeforeDeserialize!==void 0){let r=l.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=Ku(l);if(e){if(typeof e.guid=="string"&&(l.guid=e.guid),i)for(let r in i){let o=i[r],s=e[r];if(t.path=r,o===null)l[r]=s;else{let c=function(d){let h=d.type;return h?Mc(s,h,t,void 0,l[r]):Mc(s,d,t,void 0,l[r])};var n=c;if(l.onBeforeDeserializeMember!==void 0&&l.onBeforeDeserializeMember(r,s,t)===!0)continue;if(Array.isArray(o))for(let d=0;d<o.length;d++){let a=o[d],h=c(a);if(h!==void 0||d===o.length-1){l[r]=h;break}}else l[r]=c(o);Ea.length=0,l.onAfterDeserializeMember!==void 0&&l.onAfterDeserializeMember(r,s,t)}}mv(l,e)}return l.onAfterDeserialize!==void 0&&l.onAfterDeserialize(e,t),t.path=void 0,!0}function mv(l,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=l[i];if(!r){nr&&console.log(i,"is undefined on",l);continue}for(let o of Object.keys(n))r[o]===void 0&&t(n[o])&&!t(r)&&(r[o]=n[o])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Mc(l,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e?.call(e,n),r=!1,o==null)return}catch(a){console.error("Error in callback",a,l)}if(!r&&n instanceof o)return n;if(n&&typeof n=="object"&&$u(n)){if(n.__concreteInstance)return n.__concreteInstance;let a=n;if(!a.$serializedTypes&&o.prototype.$serializedTypes&&(a.$serializedTypes=o.prototype.$serializedTypes),a.$serializedTypes&&hs(a,l,t),n&&o!==void 0)try{let h=new o;Ie&&console.log("Create concrete instance for persistent asset",n,"instance:",h),us(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,o)}return n}if(i||(i={serializer:wa.getSerializerForConstructor(o)}),Array.isArray(l)){let a=[];for(let h=0;h<l.length;h++){let u=l[h],f=Mc(u,e,t,i,u);a.push(f)}return a}let s=i.serializer;if(s)return s.onDeserialize(l,t);let c;l&&(l.isMaterial||l.isTexture||l.isObject3D)?c=l:c=new o(...gv(l));let d=c;return d.$serializedTypes&&hs(d,l,t),c}function gv(l){if(Ea.length=0,typeof l=="object"&&l!==null&&l!==void 0)for(let e of Object.keys(l))Ea.push(l[e]);return Ea}function us(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=bv(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function bv(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var wn=N("debuganimatorcontroller"),Dc=N("debugrootmotion"),Zt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let o=this.model.layers[t].stateMachine;for(let s of o.states)if(s.name===e||s.hash===e){wn&&console.log("transition to ",s),this.transitionTo(s,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){wn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.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 i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new yv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Qo(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new Zt(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,wn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(wn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){wn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(a=>a.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,wn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new zr(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,a=this._activeState.motion.action.time/d,h=new zr(this._activeState,a,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let o=this._activeState?.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);let s=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(wv,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let a=new zr(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);wn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Hc(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(i=>i.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 i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Zu(r.name)),this.animator&&r.motion.clips){let o=r.motion.clips?.find(s=>s.node.name===this.animator?.gameObject?.name);r.motion.clip=o?.clip}if(!r.motion.clip){let o=new vv;r.motion.clip=o}if(r.motion?.clip){let o=r.motion.clip,s=this.createAction(o);r.motion.action=s}if(r.behaviours&&Array.isArray(r.behaviours))for(let o of r.behaviours){if(!o?.typeName)continue;let s=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,us(c,o.properties),o.instance=c),wn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},_a=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let o=this.originalEvaluate(r);return t(r,o)},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}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new ps;rotationChange=new Qt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new xa.Quaternion),r){let o=r.values;Re.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new Qt),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new Qt),Re.clipOffsetRotation[i.uuid]=new Qt,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new xa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Q.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Dc&&i.add(new Ev),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new ps);let n=new ps,r=new ps,o=0;this.positionWrapper=new _a(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Dc&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(c),o=s,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Dc){let s=t.values,c=new ep().setFromQuaternion(new Qt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Q.toDegrees(c.y));let d=t.values.length-4,a=new Qt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new ep().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Q.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new Qt);let n=0,r=new Qt,o=new Qt;this.rotationWrapper=new _a(t,(s,c)=>(s>n&&(o.set(c[0],c[1],c[2],c[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(c),n=s,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}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(Re.identityQuaternion,1-e)}},Yt=Re;z(Yt,"lastObjPosition",{}),z(Yt,"lastObjRotation",{}),z(Yt,"firstKeyframeRotation",{}),z(Yt,"spaceRotation",{}),z(Yt,"effectiveSpaceRotation",{}),z(Yt,"clipOffsetRotation",{}),z(Yt,"identityQuaternion",new Qt);var Hc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),s=new Yt(this.controller.context,t,i,r,o);this.handler.push(s);let c=e.clipAction(i);return s.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new ps;summedRotation=new Qt;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),Yt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var _v=N("debuganimator"),bt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Zt?this._animatorController=e:this._animatorController=new Zt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}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=Q.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Q.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}_v&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],bt.prototype,"applyRootMotion",2),k([A()],bt.prototype,"hasRootMotion",2),k([A()],bt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],bt.prototype,"runtimeAnimatorController",1);import*as Wr from"three";var Jt=class extends M{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&&he.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let o=this.tryFindHandle(e);if(o)return o.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.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?Wr.LoopRepeat:Wr.LoopOnce),e.play();let r=new jc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.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 Wr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],Jt.prototype,"playAutomatically",2),k([A()],Jt.prototype,"randomStartTime",2);var jc=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}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 wf}from"three/examples/jsm/loaders/GLTFLoader.js";import*as tp from"three";var Ur=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new tp.Vector3}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};var ui=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],ui.prototype,"time",2),k([A()],ui.prototype,"value",2),k([A()],ui.prototype,"inTangent",2),k([A()],ui.prototype,"inWeight",2),k([A()],ui.prototype,"outTangent",2),k([A()],ui.prototype,"outWeight",2),k([A()],ui.prototype,"weightedMode",2);var rr=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 i of this.keys){if(t&&i.time>e&&e>t.time)return Q.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(ui)],rr.prototype,"keys",2);import*as ip from"three";import*as fs from"three";import{PositionalAudioHelper as xv}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Ta=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 at=N("debugaudio");var Be=class extends M{static get userInteractionRegistered(){return Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction()),Be._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Be._userInteractionRegistered){Be._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}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&&(at&&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&&Be._userInteractionRegistered){let e=O.getComponent(this.context.mainCamera,$t)??O.findObjectOfType($t,this.context);e?.listener&&(this.sound=new fs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new fs.AudioLoader,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&&Be._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Be._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Be._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){at&&console.log("audio buffer loaded"),Be.registerWaitForAllowAudio(()=>{at&&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(),at&&console.log(this.name,this.shouldPlay,Be.userInteractionRegistered,this),this.shouldPlay&&Be._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(at&&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?at&&!this.helper&&(this.helper=new xv(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(at&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new fs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){at&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,at&&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,at&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){at&&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(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,at&&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,at&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ue=Be;z(ue,"_didCallBeginWaitForUserInteraction",!1),z(ue,"callbacks",[]),z(ue,"_userInteractionRegistered",!1),k([A()],ue.prototype,"clip",2),k([A()],ue.prototype,"playOnAwake",2),k([A()],ue.prototype,"loop",1),k([A()],ue.prototype,"spatialBlend",1),k([A()],ue.prototype,"minDistance",1),k([A()],ue.prototype,"maxDistance",1),k([A()],ue.prototype,"volume",1),k([A()],ue.prototype,"rollOffMode",2);var $t=class extends M{get listener(){return this._listener==null&&(this._listener=new ip.AudioListener),this._listener}_listener=null;awake(){ue.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=O.getComponentInParent(this.gameObject,ne);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Cv}from"three/examples/jsm/loaders/GLTFLoader";import*as qr from"three";var hp=vl(dp(),1),Ra=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function up(l,e){let t=await l.arrayBuffer(),i=pp(t),n=l.name.split(".").pop(),r=i+"."+n,o=l.name.split(".").shift();console.assert(o!==void 0);let s={alias:o,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new Ra(!0,r,i,l.size);console.log("begin uploading file",o,l.size);let a=new FormData;a.append("file",l);let h={};h.filesize=l.size,o&&(h.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:h})).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===i,"hash sum did not match","received:",f.hash_sum,"expected:",i),f.success&&console.log("successfully uploaded",i,f.id);let E=new Ra(f.success,r,i,l.size);return E.url=e,E}function pp(l){return(0,hp.default)(new Uint8Array(l))}async function Ca(l,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:l});if(r.status!==200)return console.error("download failed",r),null;let o=await r.blob(),s=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);let c=pp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function fp(l,e){let t=await fetch(l),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0,s=[];for(;;){let{done:a,value:h}=await i.read();if(h&&(s.push(h),o+=h.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),a)break}let c=new Uint8Array(o),d=0;for(let a of s)c.set(a,d),d+=a.length;return c}var ms=N("debugavatar"),or=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}assignRandomColors(){Ni.assignRandomPlayerColors(this)}},Ni=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 i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new ye;i=O.instantiate(hn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.assignRandomColors(),n.isValid?(ms&&console.log("[Custom Avatar] valid config",t,ms?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ms?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ms&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let s=await n.blob();s&&(r=await s.arrayBuffer())}return!r&&(r=await Ca(t,t,0,"no url here go away",!0),!r)?null:(await Xr(e,r,null,0))?.scene??null}let i=new Cv;return tr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Sa(e,o,s),n(s.scene)},s=>{ms&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,"head"),r=this.findAvatarPart(i,"left"),o=this.findAvatarPart(i,"right");if(!n){n=t;let c=new qr.Vector3;new qr.Box3().setFromObject(n).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&n.scale.multiplyScalar(1/d*.3)}return new or(t,n,r,o)}findAvatarPart(e,t){for(let i of e.children)if(i.name.toLowerCase().indexOf(t)>-1)return i;return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}static assignRandomPlayerColors(e){let t=new Map;function i(n){if(n.type==="Mesh"){let r=n,o=r.material;if(o&&o.name){if(t.has(o.uuid)){let s=t.get(o.uuid);s&&(r.material=s);return}if(o.name.endsWith("_playercolor")||o.name.endsWith("_player_color2")){let s=o.uuid;r.material=o.clone(),r.material.color=new qr.Color(Math.random(),Math.random(),Math.random()),t.set(s,r.material)}}}}e.head&&e.head.traverse(i),e.leftHand&&e.leftHand.traverse(i),e.rigthHand&&e.rigthHand.traverse(i)}};import{AxesHelper as Sv}from"three";var zi=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!hi)return;this._axes||(this._axes=new Sv(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)}};k([A()],zi.prototype,"length",2),k([A()],zi.prototype,"depthTest",2),k([A()],zi.prototype,"isGizmo",2);import*as gp from"three";var Qr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let o=q(this.hint).clone();o.sub(r);let s=new gp.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),a=Math.sqrt(d*d-c*c),h=s.clone();h.multiplyScalar(a),h.add(r),ie(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Gi from"three";import*as pi from"three";var Pv=new pi.BoxGeometry(1,1,1);function Pa(l=null){let e=new pi.Color(l??14540253),t=new pi.EdgesGeometry(Pv);return new pi.LineSegments(t,new pi.LineBasicMaterial({color:e}))}var Av=N("gizmos"),Oa=class extends M{box=null;testBox=new Gi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Gi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Oa._position),i=Sh(e,Oa._size);this.testBox.setFromCenterAndSize(t,i)}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 Gi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Gi.Vector3(0,0,0),new Gi.Vector3(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(!(!Av&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Pa(e),this.gameObject.add(this._helper)}}},lt=Oa;z(lt,"_position",new Gi.Vector3),z(lt,"_size",new Gi.Vector3(.01,.01,.01));import*as gs from"three";import{FrontSide as bp,DoubleSide as vp}from"three";function Yr(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?vp:bp,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?vp:bp,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Yr(i,e)}function Zr(l,e,t){l[e]===void 0&&console.warn("Field",e,"is undefined on",l);let i=Proxy.revocable(l[e],{set(o,s,c,d){let a=o[s],h=Reflect.set(o,s,c,d);return t(c,a),h}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function yp(l,e,t=3){let i=l.__scheduledActions;i||(i=l.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(l),r[n]=null}let c=l.startCoroutine(s(),t);r[n]=c}var Jr=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.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 gs.Vector3,this._smoothedVelocity=new gs.Vector3,this.lastWorldPosition=q(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=Zr(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 la;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 _(e.x,e.y,e.z),t?new _(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?Jr.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):Jr.tempPosition.set(0,0,0)}setVelocity(e,t,i){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/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 i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){Jr.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(Jr.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=Jr;z(ce,"tempPosition",new gs.Vector3),z(ce,"copyVector3",new gs.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollision",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Aa}from"three";var fi=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],fi.prototype,"attachedRigidbody",2),k([A()],fi.prototype,"isTrigger",2);var _n=class extends fi{radius=.5;center=new Aa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],_n.prototype,"radius",2),k([A(Aa)],_n.prototype,"center",2);var xn=class extends fi{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Aa)],xn.prototype,"size",2),k([A(Aa)],xn.prototype,"center",2);var $r=class{};var kt=class extends M{canGrab=!0;onPointerClick(e){}},It=class extends M{isUsed=!0;usedBy=null};var sr=class extends lt{},Kr=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=O.findObjectsOfType(sr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(O.getComponentInParent(this.gameObject,It)||kr(this.gameObject,this.context.connection))}}};var ar=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||O.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:kv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],ar.prototype,"visibleOn",2);var ka;function kv(){if(ka===!0||ka===!1)return ka;let l=!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)))&&(l=!0)}(navigator.userAgent||navigator.vendor||window.opera),ka=l,l}import*as Vi from"three";var Ce=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,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var eo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,c,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Mt=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 Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__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 eo).__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 Tn=N("debugsync"),to="STRS";Nr(to,Mt.getRootAsSyncedTransformModel);var mi=new ft;function Nc(l,e,t=!0){mi.clear();let i=mi.createString(l);Mt.startSyncedTransformModel(mi),Mt.addGuid(mi,i),Mt.addFast(mi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Mt.addTransform(mi,eo.createTransform(mi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Mt.endSyncedTransformModel(mi);return mi.finish(s,to),mi.asUint8Array()}var Qe=class extends M{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(){Tn&&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(){Tn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Vi.Vector3,this._targetRotation=new Vi.Quaternion,this.lastWorldPos=new Vi.Vector3,this.lastWorldRotation=new Vi.Quaternion,this.rb=O.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new En(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(to,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Lh(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(to,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Vi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Tn&&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){he.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Ph(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){Tn&&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 r=e.distanceTo(this.lastWorldPos),o=t.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(Tn&&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),he.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let o=this._receivedFastUpdate||this.fastMode?.5:.3,s=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,o),this.worldPosition=c,s=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,o),this.worldQuaternion=c,s=!0}s&&he.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&&(Tn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Vi.Vector3(0,0,0))>1e3&&(Tn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){Tn&&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 r=Nc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Ma=class{static createButton(e,t={}){let i=document.createElement("button");function n(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){h.end()}),c.appendChild(d);var a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),a.setAttribute("stroke","#fff"),a.setAttribute("stroke-width",2),d.appendChild(a),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null;async function u(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}function f(){h.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="AR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():o()}).catch(o),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}};var La=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 i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",a),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function a(){c.removeEventListener("end",a),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():o(),La.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),La.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},io=La;z(io,"xrSessionIsGranted",!1);io.registerSessionGrantedListener();import*as Pe from"three";import*as Da from"three";var Ep=vl(wc(),1);import{AudioAnalyser as Mv}from"three";var no="noVoip",ct=N("debugvoip"),Lv=N("voip");var zc=class{id;constructor(e){this.id=e}};var Gc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ct&&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 i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ct&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ct&&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=>{ct&&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(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ct&&console.log("call closed",e)}},Vc=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,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);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,ue.userInteractionRegistered||ct&&console.log("Incoming call, waiting for user interaction before opening audio"),ue.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ct&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Da.AudioListener;this.audio=new Da.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ct&&console.log("call is setup, you should hear something now"),this.analyzer=new Mv(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()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.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 i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.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(N(no)){console.log("VOIP is disabled by url parameter: "+no);return}if(this.requireParam&&!Lv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Ep.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 i=new Gc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ct&&console.log("UserLeftRoom",e,t,n),n&&(n.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){ct&&console.log("Peer connection established and received id"),this.model=new zc(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){ct&&console.log("CONNECTION",t),t.on("data",function(i){ct&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ct&&console.log("received call"),await Ke.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Vc(this,this.gameObject,e),e.on("stream",o=>{ct&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(o)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var ro=N("debugflags");var Wc=class{Mask=17;Has(e){let t=this.Mask&e;return ro&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Se.Apply()}Enable(e){this.Mask|=e,Se.Apply()}Disable(e){this.Mask&=~e,Se.Apply()}Toggle(e){this.Mask^=e,Se.Apply()}EnableAll(){this.Mask=-1,Se.Apply()}DisableAll(){this.Mask=0,Se.Apply()}},vt=Wc;z(vt,"Global",new Wc);var gi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(vt.Global)}awake(){gi.registry.push(this)}onEnable(){gi.firstApply||(gi.firstApply=!0,gi.Apply())}onDestroy(){let e=gi.registry.indexOf(this);e>=0&&gi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),ro&&console.log(i),gi.buffer.Mask=i,e=gi.buffer);let n=e;if(n?(ro&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(ro&&console.log("use global mask"),vt.Global.Has(this.visibleIn)),t!==void 0)if(t)ro&&console.trace("is visible",this.name,this.gameObject.uuid),O.setActive(this.gameObject,!0);else{if(ro&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Se=gi;z(Se,"registry",[]),z(Se,"firstApply"),z(Se,"buffer",new vt);import*as K from"three";import{XRControllerModelFactory as Dv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Hv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as jv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as _p from"three";import*as Kt from"three";var Rn=N("debugavatar"),Wi=class extends M{static onAvatarMarkerCreated(e){return Wi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Wi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Wi.instances.push(this),Rn&&console.log(this);for(let e of Wi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Wi.instances.splice(Wi.instances.indexOf(this),1);for(let e of Wi._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):O.setActive(this.avatar,e))}},fe=Wi;z(fe,"instances",[]),z(fe,"_onNewAvatarMarkerAdded",[]),z(fe,"_onAvatarMarkerDestroyed",[]);var bs=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 Kt.Vector3(1,1,1);handLeftScale=new Kt.Vector3(1,1,1);handRightScale=new Kt.Vector3(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,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 Kt.Object3D;_handLeftTarget=new Kt.Object3D;_handRightTarget=new Kt.Object3D;_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 i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(e.position.x,e.position.y,e.position.z),i.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.headScale),this.handLeft){let n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),n.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),n.quaternion.multiply(bs.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handLeftScale)}if(this.handRight){let n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),n.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),n.quaternion.multiply(bs.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.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(){Rn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&_e.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&O.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Rn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&_e.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;O.setActive(n,!1),e=O.instantiate(n),O.setActive(e,!0)}Rn&&console.log(e);let i=await bs.loader.getOrCreateNewAvatarInstance(this.context,e);if(Rn&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.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=O.addNewComponent(this.root,fe),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&_e.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.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(...O.getComponentsInChildren(this.root,Se)),this.flags.length<=0&&this.head){let n=O.addNewComponent(this.head,Se);n.visibleIn=20,this.flags.push(n),Rn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return Rn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Rn&&console.warn("build avatar failed"),!1}},Lt=bs;z(Lt,"loader",new Ni),z(Lt,"invertRotation",new Kt.Quaternion().setFromAxisAngle(new Kt.Vector3(0,1,0),Math.PI));var _e=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??Z.Current?.time.time;return}}}};z(_e,"Pois",[]),z(_e,"LastChangeTime",0);var Uc=class{guid;position=new _p.Vector3},Ui=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=O.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Uc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=O.getComponentInParent(this.gameObject,fe),this.avatar){let e=O.getComponentInParent(this.gameObject,fe);this._model=new En(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&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(_e.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=_e.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);ie(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=_e.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var lr=class extends M{},Fe=class extends M{static CreateRaycastLine(){let e=new K.Line(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 K.SphereGeometry(.5,22,22),t=new K.MeshBasicMaterial({color:this.raycastColor}),i=new K.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?O.addNewComponent(i,Fe,!1):new Fe;r.webXR=e,r.index=t,r.type=n;let o=e.context;return r.controller=o.renderer.xr.getController(t),r.controllerGrip=o.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=o.renderer.xr.getHand(t),r.hand.add(new Hv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new jv(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(a=>a.layers.set(2)),r.handPointerModel.pointerObject?.traverse(a=>a.layers.set(2));let d=r.hand.joints;if(d)for(let a of Object.keys(d)){let h=d[a];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}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 K.Quaternion),ve(e).multiply(this._wristQuaternion.setFromEuler(new K.Euler(-Math.PI/4,0,0)))):null}movementVector=new K.Vector3;worldRot=new K.Quaternion;joystick=new K.Vector2;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=Fe.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Fe.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 K.Quaternion;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Fe.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(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(ve(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ie(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let o=this.getWristQuaternion();o&&this.rayRotation.copy(o)}Ae(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ae(this.raycastLine,this.rayRotation),ie(this.raycastLine,i);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 i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Fe.MovementSpeedFactor,r=2,o=Q.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=s,c*=o;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,c*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(n*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let f=h>0?-1:1;t.rotateY(Q.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let s=this.handPointerModel.isPinched();s&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),s&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),s||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,o=null;if(t&&this.input&&!this.input.hand)for(let s=0;s<t.length;s++){let c=t[s];if(s===4)if(c.pressed&&!this.didChangeScale){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,Fe.MovementSpeedFactor=1;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance&&(a.far=Fe.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,Fe.MovementSpeedFactor=o*2;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance=a.far,a.far/=o}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let c=s[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return O.getComponentInParent(e,lr)!=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 i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Fe.raycastColor:n.color=Fe.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=Q.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}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 i of e){let n=i.object;if(!this.testIsVisible(n)){console.log("not visible");continue}this.lastSelectStartObject=n;let r={selected:n,grab:n},o=Fe.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=dt.TryTake(this,r.grab,i,t));break}else{let i=Fe.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_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=Fe.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?O.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new K.Ray;return e.origin.copy(q(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=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new je;return e.layerMask=new K.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},se=Fe;z(se,"Factory",new Dv),z(se,"raycastColor",new K.Color(.9,.3,.3)),z(se,"raycastNoHitColor",new K.Color(.6,.6,.6)),z(se,"geometry",new K.BufferGeometry().setFromPoints([new K.Vector3(0,0,0),new K.Vector3(0,0,-1)])),z(se,"handModels",{}),z(se,"eventSubs",{}),z(se,"PreviousCameraFarDistance"),z(se,"MovementSpeedFactor",1);var et=class{static AddEventListener(e,t){return et.Events[e]||(et.Events[e]=[]),et.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!et.Events[e])return;let i=et.Events[e].indexOf(t);i>=0&&et.Events[e].splice(i,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,i,n){let r=O.getComponentInParent(t,kt);if(!r)return console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=O.getComponentInParent(t,Qe);s&&(s.requestOwnership(),o=s.gameObject);for(let d of this.Current)if(d.selected===o)return d.controller===e||(d.free(),d.Take(e,o,t,s,r,i,n)),d;let c=new et;return c.Take(e,o,t,s,r,i,n),c}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,i,n,r,o,s){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=s?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};et.Events.WillTake?.forEach(f=>f(this,c));let d=i;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=s,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=O.addNewComponent(this.selected,It),this.rigidbodies=O.getComponentsInChildren(this.selected,ce),q(this.positionSource,this.lastControllerWorldPos);let a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());let h=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ve(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),_e.Add(e.context,this.selected),et.Register(this),this.sync&&(this.sync.fastMode=!0),et.Events.DidTake?.forEach(f=>f(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};et.Events.WillFree?.forEach(n=>n(this,e)),_e.Remove(this.controller.context,this.selected),et.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}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 n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,et.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new K.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new K.Vector3;localQuaternionToGrab=new K.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new K.Vector3;controllerWorldPos=new K.Vector3;lastControllerWorldPos=new K.Vector3;controllerPosDelta=new K.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new K.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(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 i=q(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}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 K.Vector3),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ae(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});he.markDirty(this.selected,!0)}}},dt=et;z(dt,"Events",{}),z(dt,"Current",[]);import*as Ha from"three";var Dt=class extends M{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,i){if(i&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new Ha.Matrix4().fromArray(i.transform.matrix).invert(),e){if(this.invertForward){let n=new Ha.Matrix4().makeRotationY(Math.PI);this._placementPose.premultiply(n)}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),he.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 Ha.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};k([A()],Dt.prototype,"invertForward",2),k([A()],Dt.prototype,"arScale",1);var Cn=class extends M{awake(){}};import{Object3D as Bv}from"three";var cr=N("debugaddressables"),ja=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}},tt=class{static getOrCreate(e,t,i){let n=Ms(e,t);cr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new tt(n);return r.registerAssetReference(s),s}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,Bh(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&&(cr&&console.log("Unload",this.asset),this.asset.scene?O.destroy(this.asset.scene):O.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,cr&&console.log("Preload",this.uri);let e=await fp(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=Z.Current;this._rawBinary?(this._loading=Xr(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(cr&&console.log("Load async",this.uri),this._loading=dr(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return ki(t),i.scene!==void 0&&(this.asset=i),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,i){let n=Z.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),cr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){cr&&console.log("Add to scene",this.asset);let r=e instanceof ye?e:null;if(r||(r=new ye),typeof e=="object"&&(e instanceof Bv?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Ws(o,r,void 0,i);if(s)return s}else{let o=O.instantiate(this.asset,r);if(o)return o}}else cr&&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}},qc=class extends Fi{constructor(){super([tt])}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?tt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new qc;import*as yt from"three";var bi=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,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Me=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 Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__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 Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new bi).__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 Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new bi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new bi).__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 xp=N("debugxr"),vs=N("debugavatar");var Qc="VRUS";Nr(Qc,Me.getRootAsVrUserStateBuffer);function Xc(){return new Date().getTime()}function Fv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Xe.create(e,t)}var ys=class{guid;time;avatarId;position=new yt.Vector3;rotation=new yt.Vector4;scale=1;posLeftHand=new yt.Vector3;posRightHand=new yt.Vector3;rotLeftHand=new yt.Quaternion;rotRightHand=new yt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Xc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=ys.quat0,s=ys.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,ys.invertRotation),e&&(e.getWorldQuaternion(s),o.multiplyQuaternions(s,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let a=n.LeftController.wrist;a&&(a.getWorldPosition(this.posLeftHand),a.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let a=n.RightController.wrist;a&&(a.getWorldPosition(this.posRightHand),a.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,Fv(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,bi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,bi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,bi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,Qc);let o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());let s=t.posRightHand();s&&this.posRightHand.set(s.x(),s.y(),s.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},Ht=ys;z(Ht,"invertRotation",new yt.Quaternion().setFromAxisAngle(new yt.Vector3(0,1,0),Math.PI)),z(Ht,"quat0",new yt.Quaternion),z(Ht,"quat1",new yt.Quaternion);var qi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent($)),this.webXR||(this.webXR=O.findObjectOfType($,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=O.findObjectOfType($,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=O.findObjectOfType(Ke,this.context)),vs){let e="debug-avatar-"+vs,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof vs=="string"&&vs.length>0)if(await t.setAvatarOverride(vs)){let i=new Ht(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=O.getComponent(this.gameObject,$),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),$.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.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(Qc,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Ht("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return xp&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Lt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Xc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Xc();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.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 Lt(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(){xp&&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 ft(1024);onXRSessionUpdate(e){this.xrState??=new Ht(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new En(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:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let o=r?.transform,s=o.position,c=o.orientation;this.xrState.update(n,s,c,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 N("avatar")}};async function Nv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Yc=!1,Zc=!1;Nv().then(l=>Yc=l);zv().then(l=>Zc=l);var Ne=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Yc||Zc)}static get IsARSupported(){return Yc}static get IsVRSupported(){return Zc}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){Ne.XRSupported||console.warn("WebXR is not supported on this device");let i=io.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={requiredFeatures:["hit-test"]};i&&(n.domOverlay={root:i},n.optionalFeatures=["dom-overlay"]);let r=Ma.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ne.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}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=tt.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!O.findObjectOfType(qi,this.context)){let e=O.addNewComponent(this.gameObject,qi,!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 Sn(this);let e=Ne.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ne.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ne.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ne.resetButtonStyles(i),Ne.resetButtonStyles(t)},1e3)}_transformOrientation=new Pe.Quaternion;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 i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Ne._isInXr===!1&&t&&this.onEnterXR(t,e),Ne.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++)se.Create(this,e,this.gameObject,0);Ne.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ve(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=O.findObjectOfType(Cn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Pe.Group,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Pe.Vector3;_originalCameraRotation=new Pe.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ne._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let s=t.getViewerPose(i)?.transform.orientation;if(s){let c=new Pe.Quaternion(s.x,s.y,s.z,s.w),d=new Pe.Euler().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let o=n.getCamera(this.context.mainCamera);for(let s of o.cameras)s.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(vt.Global.Set(r),r){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"),Ne._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ne.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),ie(this.context.mainCamera,this._originalCameraPosition),Ae(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),vt.Global.Set(17),Ne.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){!N("mirror")||setTimeout(()=>{if(!Ne.IsInWebXR)return;let t=new URL(window.location.href);Or(t.searchParams,no,1),Or(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Ne.IsInWebXR&&e.end()})})},1e3)}},$=Ne;z($,"_isInXr",!1),z($,"events",new Pe.EventDispatcher),k([A(tt)],$.prototype,"defaultAvatar",2);var oo=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 i=0;i<4;i++)se.Create(this.webxr,i,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=O.findObjectOfType(Dt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(i=>{e.requestHitTestSource({space:i}).then(n=>{this.hitTestSource=n})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Pe.Mesh(new Pe.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new Pe.MeshBasicMaterial),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,oo.tempWebXRObject||(oo.tempWebXRObject=new Pe.Object3D),this.context.scene.add(oo.tempWebXRObject),O.addComponent(oo.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),O.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 i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let o=n.getPose(r);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,o),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&o)){let s=o.transform.matrix;this.reticle.matrix.fromArray(s),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)}},Sn=oo;z(Sn,"tempWebXRObject");var Jc=!1;var so=class extends kt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}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)||$.IsInWebXR)return;let t=O.getComponentInParent(e.object,so);!t||t!==this||(so.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||so.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&($.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!$.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 Ba(this.context.mainCamera);else return;if(!e||!e.object)return;let t=O.getComponentInParent(e.object,so);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=O.getComponentInChildren(i,Qe);Jc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=O.addNewComponent(i,It),this._draggingRigidbodies.length=0;let o=O.getComponentsInChildren(i,ce);o&&this._draggingRigidbodies.push(...o);let s=El();O.invokeOnChildren(this._dragHelper.selected,s("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(Jc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=O.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=El();O.invokeOnChildren(t,i("onDragEnd"))}},Et=so;z(Et,"_active",null),z(Et,"lastHovered");var Kc=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line(Kc.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),o=new ee.Mesh(n,r);o.visible=!1,o.layers.set(2),this._groundMarker=o}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&_e.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}_e.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=O.getComponentsInChildren(this._selected,ce),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,i=68,n=83,r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){Jc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&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,h){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&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,i){if(!!this._selected){if(i){let n=q(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(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=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new je;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let o=n[r];if(!o.face||this.contains(this._selected,o.object))continue;let s=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(s,o.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(){he.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 i of e.children)if(this.contains(i,t))return!0}return!1}},Ba=Kc;z(Ba,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Pn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?pt.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 i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let o=await Rp(r,this.context,this.filesBackendUrl);o&&this.addObject(e,o)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let o=new URL(r);if(!o)return;let s=await Cp(o,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new je;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let o of n){r.position.copy(o.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};k([A()],Pn.prototype,"filesBackendUrl",2),k([A()],Pn.prototype,"localhost",2);import{Vector3 as Vv,Quaternion as Wv,Object3D as Sp}from"three";var vi=class extends kt{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 Vv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Wv(0,0,0,1)}let e=O.getComponentInParent(this.gameObject,Et);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),se.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),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 ye;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 i=O.instantiateSynced(this.object,t);return console.assert(i!==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),i}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 i of e.children)if(this.isInChildren(i,t))return!0}return!1}};k([A(Sp)],vi.prototype,"parent",2),k([A(Sp)],vi.prototype,"object",2),k([A()],vi.prototype,"limitCount",2),k([A()],vi.prototype,"limitInterval",2);var yi=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)}}},Uv=l=>/^[A-Z]*$/.test(l),hr=class extends Event{args},Oe=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Uv(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_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 i=new hr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new yi(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 ao=class extends M{};import{FlyControls as qv}from"three/examples/jsm/controls/FlyControls";var lo=class extends M{_controls=null;onEnable(){let e=O.getComponent(this.gameObject,ne)?.cam;this._controls=new qv(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)}};import*as Op from"three";import{Color as Xv}from"three";var Xi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!hi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Op.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Pa(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}};k([A()],Xi.prototype,"objectBounds",2),k([A(Xv)],Xi.prototype,"color",2),k([A()],Xi.prototype,"isGizmo",2);import{GLTFExporter as Jv}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as ed,Matrix4 as Qv,Vector3 as Ap,Quaternion as Yv}from"three";var Es=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let o=new Qv,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new Ap,b=new Yv,y=new Ap;o.decompose(E,b,y),s.push(E.x,E.y,E.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(s),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new ed(a,3)),ROTATION:i.processAccessor(new ed(h,4)),SCALE:i.processAccessor(new ed(u,3))},n[this.name]=!0}};import{Object3D as $v,Vector3 as Kv}from"three";var On=Ie,Fa="$___Export_Components",Zv="NEEDLE_components",td=class{[Wn]},id=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},co=class{get name(){return Zv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Fa]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&On&&console.log("DONE",JSON.stringify(t)),e[Fa]===void 0)return;let i=e[Fa];delete e[Fa],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new id(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){On&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,o=i.nodeIndex,s=n.userData?.components;if(!s||s.length<=0)continue;let c=new td;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=o,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let a of s){this.context.target=a;let h=kp(a,this.context);h!==null&&d.push(h)}d.length>0&&(c[Wn]=d,On&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return On&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];On&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let o=t.json.nodes;for(let s=0;s<o.length;s++){let c=await t.getDependency("node",s);this.nodeToObjectMap[s]=c}for(let s=0;s<o.length;s++){let c=o[s],d=s,a=c.extensions;if(!a)continue;let h=a[this.name];if(!h)continue;On&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Wn];if(i){On&&console.log(e.name,i);for(let n in i){let r=i[n];On&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Gr(this.parser,r),e.userData=e.userData||{},e.userData[Wn]=e.userData[Wn]||[],e.userData[Wn].push(r)}}}};var ho=class extends lt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},jt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?jt.saveArrayBuffer(i,e):jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Jv,this.exporter.register(s=>new Es(s)),this.ext=new co,this.ext.registerExport(this.exporter)),jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:jt.collectAnimations(e)},n=new $v;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(s=>{s&&(n.children.push(s),s.matrixAutoUpdate=!1,s.matrix.copy(s.matrixWorld),O.getComponentsInChildren(s,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Vr(n);return this.ext.context=r,new Promise((s,c)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,O.getComponentsInChildren(s,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.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 i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new Kv;return i.set(0,0,0),e.forEach(n=>{i.add(q(n))}),console.log(i),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};import{Color as Na,GridHelper as ey}from"three";var Qi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!hi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new ey(e,t,this.color0??new Na(.4,.4,.4),this.color1??new Na(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Qi.prototype,"isGizmo",2),k([A(Na)],Qi.prototype,"color0",2),k([A(Na)],Qi.prototype,"color1",2);import{GroundProjectedEnv as ty}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Yi=class extends M{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 Is(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 ty(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))}};k([A()],Yi.prototype,"scale",1),k([A()],Yi.prototype,"radius",1),k([A()],Yi.prototype,"height",1);import*as it from"three";import{Color as iy}from"three";function nd(l){return l*Math.PI/180}var Ip=300,Mp=N("debuglights");var Ye=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new it.Color(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 i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}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 i=t.shadow.camera;i.far=e,i.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 it.Color(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=$.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=$.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){$.removeEventListener("xrStarted",this._webXRStartedListener),$.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Dt)??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 it.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Ip*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Ar(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Mp){let o=new it.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new it.SpotLight(this.color,this.intensity*Math.PI,this.range,nd(this.spotAngle/2),1-nd(this.innerSpotAngle/2)/nd(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new it.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;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=Ip*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 i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Mp&&this.context.scene.add(new it.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};k([A()],Ye.prototype,"type",2),k([A(iy)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var VO=new it.Vector3(0,0,0);import*as za from"three";import{Vector3 as ny}from"three";var uo=N("debugLODs"),ry=N("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};k([A()],Ei.prototype,"screenRelativeTransitionHeight",2),k([A()],Ei.prototype,"distance",2),k([A()],Ei.prototype,"renderers",2);var rd=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):uo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=O.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},An=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!ry&&!this._lodsHandler&&!!this.gameObject&&(uo&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new rd(this,n);this._lods.push(r);for(let o of r.renderers)t.includes(o)||t.push(o)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new za.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new za.Object3D;uo&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,c=0,d=0;uo&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,uo&&console.log("add",h.model.distance,u.name);let f=h.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,u,f)}let a=c+d;uo&&console.log("cull",a),this.onAddLodLevel(o,i,a)}}}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,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};k([A(ny)],An.prototype,"localReferencePoint",2),k([A(Ei)],An.prototype,"lodModels",2);var po=class extends M{onEnable(){this.enabled&&this.context.physics.addMeshCollider(this.gameObject)}};var fo=class extends M{},mo=class extends M{};var od=N("debugnestedgltf"),ur=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;od&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ye;t.idProvider=new We(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;od&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),od&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};k([A(tt)],ur.prototype,"filePath",2);import*as bo from"three";var go=class extends M{from;affectPosition;affectRotation;alignLookDirection;levelLookDirection;positionOffset;rotationOffset;update(){if(!this.from)return;var e=q(this.from),t=ve(this.from);this.affectPosition&&ie(this.gameObject,e.add(this.positionOffset));let i=new bo.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),n=new bo.Quaternion().setFromEuler(i);this.affectRotation&&Ae(this.gameObject,t.multiply(n));let r=new bo.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}};import*as xe from"three";import*as ei from"three";var vo=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 ei.Color(1,1,1);startColor1=new ei.Color(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 ei.Vector2(0,1);cullingMode=0},yo=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Eo=class{shapeType=sd.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ei.Vector3(1,1,1);boxThickness=new ei.Vector3(0,0,0);position=new ei.Vector3(0,0,0);rotation=new ei.Vector3(0,0,0);scale=new ei.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},sd=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(sd||{});var Lp=N("debugparticles"),ad=class{age=0;lifetime=0;position;velocity;color},pr=class extends M{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(){Lp&&console.log(this)}},wo=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new xe.Quaternion;tempVec3=new xe.Vector3;tempQuat=new xe.Quaternion;awake(){this.renderer=O.getComponent(this.gameObject,pr),Lp&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new xe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new xe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new xe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new xe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new xe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new xe.Points(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 i=this.particleStates[t];if(!i)continue;let n=i.velocity.x*e,r=i.velocity.y*e,o=i.velocity.z*e;i.position.x+=n,i.position.y+=r,i.position.z+=o,this.updateOverLifetime(t,i),this.geometry.attributes.position.setXYZ(t,i.position.x,i.position.y,i.position.z),this.geometry.attributes.color.setXYZ(t,i.color.r,i.color.g,i.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new ad;r.lifetime=this.main.startLifetime??1,r.position=new xe.Vector3,r.velocity=new xe.Vector3,r.color=new xe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}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 i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.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 i=new xe.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Q.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)}};import*as Hp from"three";function*Dp(l,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<l;)yield}var ht=class extends M{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 Dp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=O.getComponentInParent(this.gameObject,fe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ht.hashCode(e),i=ht.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t?(n=n.clone(),n._playerMaterial=t,i.material=n):console.log("DONT CLONE",n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new Hp.Color(t/255,i/255,n/255)}};import*as Ga from"three";import{Object3D as ay}from"three";function sy(){return new Promise((l,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),l())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function jp(l){await sy(),l()}var ld=N("debugvideo");var nt=class extends M{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,ld&&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(),jp(()=>{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)}),ld&&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 Ga.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ga.sRGBEncoding,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ld&&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")}};k([A(ay)],nt.prototype,"renderer",2),k([A()],nt.prototype,"playOnAwake",2),k([A()],nt.prototype,"playOnEnable",2),k([A()],nt.prototype,"targetMaterialProperty",2),k([A()],nt.prototype,"time",2),k([A()],nt.prototype,"playbackSpeed",1),k([A()],nt.prototype,"isLooping",1);var _o=class extends M{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=O.getComponentInChildren(this.gameObject,nt);if(t){let i={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(i),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}}};import{ShadowMaterial as ly,AdditiveBlending as cy}from"three";var kn=class extends M{mode=0;shadowColor=new we(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=O.getComponent(this.gameObject,Te);if(e){let t=e.material;t.blending=cy,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
124
124
 
125
125
  // diffuse-only lighting with overdrive to somewhat compensate
126
126
  // for the loss of indirect lighting and to make it more visible.