@needle-tools/engine 2.26.1-pre → 2.28.0-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.
- package/CHANGELOG.md +14 -0
- package/dist/needle-engine.d.ts +5 -1
- package/dist/needle-engine.js +4 -4
- package/dist/needle-engine.js.map +3 -3
- package/dist/needle-engine.min.js +4 -4
- package/dist/needle-engine.min.js.map +3 -3
- package/lib/engine/engine_networking_utils.js +1 -2
- package/lib/engine/engine_networking_utils.js.map +1 -1
- package/lib/engine/engine_serialization_builtin_serializer.js +15 -4
- package/lib/engine/engine_serialization_builtin_serializer.js.map +1 -1
- package/lib/engine/engine_setup.d.ts +5 -1
- package/lib/engine/engine_setup.js +21 -3
- package/lib/engine/engine_setup.js.map +1 -1
- package/lib/engine/extensions/NEEDLE_techniques_webgl.js +2 -2
- package/lib/engine/extensions/NEEDLE_techniques_webgl.js.map +1 -1
- package/lib/engine/extensions/extension_utils.js +6 -6
- package/lib/engine/extensions/extension_utils.js.map +1 -1
- package/lib/engine-components/AvatarLoader.js +1 -1
- package/lib/engine-components/AvatarLoader.js.map +1 -1
- package/lib/engine-components/ui/BaseUIComponent.js +8 -5
- package/lib/engine-components/ui/BaseUIComponent.js.map +1 -1
- package/lib/engine-components/ui/Image.js +4 -0
- package/lib/engine-components/ui/Image.js.map +1 -1
- package/lib/engine-components/ui/InputField.js +2 -2
- package/lib/engine-components/ui/RectTransform.js +1 -1
- package/lib/engine-components/ui/RectTransform.js.map +1 -1
- package/package.json +1 -1
- package/src/engine/engine_networking_utils.ts +1 -2
- package/src/engine/engine_serialization_builtin_serializer.ts +15 -3
- package/src/engine/engine_setup.ts +19 -3
- package/src/engine/extensions/NEEDLE_techniques_webgl.ts +2 -2
- package/src/engine/extensions/extension_utils.ts +6 -6
- package/src/engine-components/AvatarLoader.ts +1 -1
- package/src/engine-components/ui/BaseUIComponent.ts +12 -5
- package/src/engine-components/ui/Image.ts +4 -0
- package/src/engine-components/ui/InputField.ts +2 -2
- package/src/engine-components/ui/RectTransform.ts +1 -1
package/dist/needle-engine.js
CHANGED
|
@@ -6336,7 +6336,7 @@ void main() {
|
|
|
6336
6336
|
// gl_FragColor = vec4(vUv2.xy, 0, 1);
|
|
6337
6337
|
gl_FragColor = lightMapTexel;
|
|
6338
6338
|
}
|
|
6339
|
-
`,defines:{USE_LIGHTMAP:""}})}};var te=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=sO(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=sO(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let n=e.$serializedTypes=e.$serializedTypes||{};n[t]=o}};function sO(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var BM=be("debugstencil");function t5(o,e){return(o&1<<e.layer)!=0}var ph=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(BM&&console.log(t,ph.stencils),!t)return;let n=ph.stencils[t];if(!!n)for(let i=n.length-1;i>=0;i--){let s=n[i];if(t5(s.layer,e)){BM&&console.log(s);let r=e.material?.clone();r&&(e.material=r,e.gameObject.renderOrder=s.event*1e3+s.index*50,r.stencilWrite=!0,r.stencilWriteMask=255,r.stencilFuncMask=255,r.stencilRef=s.value,r.stencilFunc=s.compareFunc,r.stencilZPass=s.passOp,r.stencilFail=s.failOp,r.stencilZFail=s.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[i5];if(n){BM&&console.log(n);let i=n.stencil;if(i&&Array.isArray(i))for(let s of i){let r={...s};r.compareFunc=n5(r.compareFunc),r.passOp=NM(r.passOp),r.failOp=NM(r.failOp),r.zFailOp=NM(r.zFailOp),ph.stencils[this.source]||(ph.stencils[this.source]=[]),ph.stencils[this.source].push(r)}}}return null}},mh=ph;Se(mh,"stencils",{});function NM(o){switch(o){case 0:return id;case 1:return IS;case 2:return LS;case 3:return OS;case 4:return DS;case 6:return kS;case 7:return FS;case 5:return BS}return 0}function n5(o){switch(o){case 1:return NS;case 2:return US;case 3:return HS;case 4:return zS;case 5:return VS;case 6:return GS;case 7:return WS;case 8:return J0}return 0}var i5="NEEDLE_render_objects";import{GLTFLoader as s5}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as UM}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as rO}from"three/examples/jsm/loaders/KTX2Loader.js";var Zm=be("debugdecoders"),Sr,pl;function HM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Zm&&console.log("Setting draco decoder path to",o),Sr.setDecoderPath(o))}function zM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Zm&&console.log("Setting draco decoder type to",o),Sr.setDecoderConfig({type:o}))}function VM(o){o!==void 0&&typeof o=="string"&&(pl||(pl=new rO),Zm&&console.log("Setting ktx2 transcoder path to",o),pl.setTranscoderPath(o))}function gh(o,e){Sr||(Sr=new UM,Sr.setDecoderPath("./include/draco/"),Sr.setDecoderConfig({type:"js"}),Zm&&console.log("Setting draco decoder path to","./include/draco/")),pl||(pl=new rO,pl.setTranscoderPath("./include/ktx2/"),Zm&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&pl.detectSupport(e.renderer)),o.setDRACOLoader(Sr),o.setKTX2Loader(pl)}var GM="NEEDLE_deferred_texture",ml=be("debugdeferredtextures"),Jm=class{static assignTextureLOD(e,t,n=0){if(!!t)for(let i of Object.keys(t)){let s=t[i];s?.isTexture===!0&&(ml&&console.log("FIND",i,s?.name,s?.userData,s),Jm.getOrLoadTexture(e,t,i,s,n).then(r=>{r?.isTexture===!0&&(r.needsUpdate=!0,t[i]=r,t.needsUpdate=!0)}))}}get name(){return GM}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return ml&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[GM];if(i){let s=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),s.then(r=>{ml&&console.log("register texture",r.name,r.uuid,i),r.userData.deferred=i,Jm.cache.set(r.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,s){let r=i.uuid,a=Jm.cache.get(r)||i.userData.deferred;if(a){ml&&console.log(r,a.uri,a.guid);let l=a.uri;if(l.endsWith(".glb")||l.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;let c=a.uri+"_"+a.guid;if(this.resolved[c])return this.resolved[c];let h=new s5;gh(h,e),ml&&console.log("Load "+l,t.name,n);let u=await h.loadAsync(l),d=u.parser,f=-1,g=!1;for(let m of u.parser.json.textures)if(f++,m?.extensions){let y=m?.extensions[GM];if(y?.guid&&y.guid===a.guid){g=!0;break}}if(!g)return null;let p=await d.getDependency("texture",f);return this.resolved[c]=p,ml&&console.log(t.name,n,'change "'+i.name+'" \u2192 "'+p.name+'"',l,f,p,t),p}else{let h=await new Uo().loadAsync(a.uri);return h&&ml?console.log(a,h):console.warn("failed loading",a.uri),h}}else ml&&console.warn("unknown uuid",i.name,i.uuid,i);return null}},Zo=Jm;Se(Zo,"cache",new Map),Se(Zo,"resolved",{});var aO=be("noInstancing"),lO=!!be("debuglightmaps"),r5=be("debuginstancing"),o5=be("debugprogressiveload"),Vd=class{path=null;asset=null;default};var WM=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),n=this.getMaterial.bind(this),i=e.gameObject;if(this._targets=[],i)switch(i.type){case"Group":this._targets=[...i.children];break;case"Mesh":this._targets.push(i);break}return new Proxy(this,{get(s,r){if(typeof r=="string"){let a=parseInt(r);if(!isNaN(a))return n(a)}return s[r]},set(s,r,a){return typeof r=="string"&&t(a,Number.parseInt(r)),Reflect.set(s,r,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let n=this._targets[t];!n||(n.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let n=t[e];return n?n.material:null}},ZM=class extends ce{receiveShadows=!1;shadowCastingMode=jM.Off;lightmapIndex=-1;lightmapScaleOffset=new ot(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new WM(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return aO}_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}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let n=0;n<this.gameObject.children.length;n++){let i=this.gameObject.children[n];if(!(i.type!=="Mesh"||$.getComponent(i,ZM))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}i.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let n=new Yo(this.gameObject,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,lO)}}else if(e==="Group"){for(let n of this.gameObject.children)if(!n.material?.isMeshBasicMaterial){let i=new Yo(n,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,lO),i.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=a5.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return $.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return $.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&&!aO&&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(){mh.applyStencil(this)}onBeforeRenderThree(e,t,n,i,s,r){if(s._didRequestTextureLOD===void 0&&(s._didRequestTextureLOD=0,o5?(console.log("Load material LOD (with delay)",s.name),setTimeout(()=>{Zo.assignTextureLOD(this.context,s)},2e3)):Zo.assignTextureLOD(this.context,s)),s.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;s.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(s)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[XM]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[XM],this.handles)){for(let n=this.handles.length-1;n>=0;n--)this.handles[n].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&$.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let n=this.handles[t];this.prevLayers||(this.prevLayers=[]);let i=n.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(i):this.prevLayers[t]=i,n.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==jM.On?e.castShadow=!0:e.castShadow=!1}},Sn=ZM;ne([te()],Sn.prototype,"receiveShadows",2),ne([te()],Sn.prototype,"shadowCastingMode",2),ne([te()],Sn.prototype,"lightmapIndex",2),ne([te(ot)],Sn.prototype,"lightmapScaleOffset",2),ne([te()],Sn.prototype,"enableInstancing",2),ne([te()],Sn.prototype,"renderOrder",2),ne([te()],Sn.prototype,"allowOcclusionWhenDynamic",2);var vh=class extends Sn{},Gd=class extends vh{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},jM=(i=>(i[i.Off=0]="Off",i[i.On=1]="On",i[i.TwoSided=2]="TwoSided",i[i.ShadowsOnly=3]="ShadowsOnly",i))(jM||{}),XM="NEEDLE_NEED_UPDATE_INSTANCE",Qt=class{static markDirty(e,t=!0){if(!!e&&($.isUsingInstancing(e)&&(e[XM]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let n of e.children)Qt.markDirty(n,!0)}},qM=class{objs=[];setup(e,t,n,i,s=0){let r=this.tryCreateOrAddInstance(e,t,i);if(r)return n===null&&(n=[]),n.push(r),n;if(s<=0&&e.type!=="Mesh"){let a=s+1;for(let l of e.children)n=this.setup(l,t,n,i,a)}return n}tryCreateOrAddInstance(e,t,n){if(e.type==="Mesh"){let i=n.foundMeshes;if(n.foundMeshes+=1,!n.rend.enableInstancing||i>=n.rend.enableInstancing.length||!n.rend.enableInstancing[i])return null;let s=e,r=s.geometry,a=s.material;for(let c of this.objs)if(!c.isFull()&&c.geo===r&&c.material===a)return c.addInstance(s);let l=new Ry(e.name,r,a,200,t);return this.objs.push(l),l.addInstance(s)}return null}},a5=new qM,YM=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,n){this.instanceIndex=e,this.object=t,this.instancer=n,$.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},JM=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,n,i,s){this.name=e,this.geo=t,this.material=n,this.context=s,this.maxCount=i,r5&&(n=new Jt({color:this.randomColor()})),this.inst=new gd(t,n,i),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new q(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new YM(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let n=this.handles.indexOf(e);if(n<0)return;e.instanceIndex=n}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,JM.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let n=this.handles[this.currentCount-1];n&&(n.instanceIndex=e.instanceIndex,n.updateInstanceMatrix(),this.handles[e.instanceIndex]=n,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},Ry=JM;Se(Ry,"nullMatrix",new it);var Qm=be("debugphysics"),l5=be("debugcollisions"),Ay=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},$m=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},QM=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var Zn=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new _e),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Fi);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};Se(Zn,"AllLayers",4294967295);var $M=class{distance;point;object;constructor(e,t,n){this.object=e,this.distance=t,this.point=n}},Py=class{raycaster=new zo;defaultRaycastOptions=new Zn;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Fi;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new gr(e,t),i=this.sphereMask;i.enableAll(),i.disable(2);for(let s of this.context.scene.children){let r=this.onSphereOverlap(s,n,i);r&&this.sphereResults.push(r)}return this.sphereResults.sort((s,r)=>s.distance-r.distance)}tempBoundingBox=new On;onSphereOverlap(e,t,n){if(e.type==="Mesh"){if(!e.layers.test(n))return null;let i=e,s=i.geometry;if(s.boundingBox||s.computeBoundingBox(),!s.boundingBox)return null;i.matrixWorldNeedsUpdate&&i.updateMatrixWorld();let r=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(i.matrixWorld);if(t.intersectsBox(r)){let l=st(e).distanceTo(t.center);return new $M(e,l,t.center.clone())}}else if(e.children)for(let i of e.children){let s=this.onSphereOverlap(i,t,n);if(s)return s}return null}raycastFromRay(e,t=null){let n=t??this.defaultRaycastOptions;return n.ray=e,this.raycast(n)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold?n.params.Line={threshold:e.lineThreshold}:n.params.Line={threshold:0},e.ray)n.ray.copy(e.ray);else{let a=this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];n.setFromCamera(t,a)}let i=e.targets;i||(i=this.targetBuffer,i[0]=this.context.scene);let s=e.results;s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Fi?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),s.length=0,n.intersectObjects(i,e.recursive,s);let r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),s}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new Cy;objects=[];tempPosition=new O;tempQuaternion=new Oe;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),Qm){let t={};t.onInit=(n,i,s)=>{i.layers.set(-1)},iO(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let n=0;n<this.objects.length;n++){let i=this.objects[n];if(i.obj===e){i._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,n=!0){this.world.removeBody(t);for(let i=0;i<this.objects.length;i++){let s=this.objects[i];if(s.obj===e){s._hasRigidbody=!1,n&&this.objects.splice(i,1);break}}}removeShape(e,t){for(let n of this.objects)if(n.obj===e){n.body&&(n.body.removeShape(t),n.body.updateMassProperties());return}}createBody(e,t){let n=this.internalCreateBody(e,null);t.mass&&(n.mass=t.mass),t.kinematic?n.type=qe.KINEMATIC:n.type=qe.DYNAMIC,t.drag&&(n.linearDamping=t.drag),t.angularDrag&&(n.angularDamping=t.angularDrag),t.sleepThreshold&&(n.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(n);let i=new $m(e,n);return i._hasRigidbody=!0,this.objects.push(i),Qm&&console.log("created new body",e.name,n,n.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(i),n}addBoxCollider(e,t,n,i,s){let r=this.tempPosition;e.getWorldScale(r);let a=new H(.5*r.x*i.x,.5*r.y*i.y,.5*r.z*i.z),l=new dh(a);l.collisionResponse=!t,n=n.clone(),n.multiply(r);let c=this.addShape(e,l,n,s);if(c!==null){if(this.isAlreadyRegistered(c))return l;let h=new $m(e,c);this.objects.push(h)}return l}addSphereCollider(e,t,n,i){let s=this.tempPosition;e.getWorldScale(s);let r=Math.max(s.x,s.y,s.z),a=new My(n*r);t=t.clone(),t.multiply(s);let l=this.addShape(e,a,t,i);if(l!==null){if(this.isAlreadyRegistered(l))return a;let c=new $m(e,l);this.objects.push(c)}return a}addMeshCollider(e){Qm&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,n,i){let s=null;if(i?(i.initialize(),console.assert(!!i.body,"rigidbody didn't initialize / produce a physics body",i),s=i.body):(s=this.internalCreateBody(e,null),s.type=qe.KINEMATIC,this.world.addBody(s)),s){n.x*=-1;let r=cn(e),a=st(e);a.add(n);let l=new Oe(s.quaternion.x,s.quaternion.y,s.quaternion.z,s.quaternion.w);r.multiply(l.invert());let c=s.position,h=new H(a.x-c.x,a.y-c.y,a.z-c.z),u=new jt(r.x,r.y,r.z,r.w);s.addShape(t,h,u),s.updateMassProperties()}return s}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,Qm&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new O;tempQuat=new Oe;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],n=t.body;if(!n||!n.world)continue;n.sleepTick(this.context.time.time),Qm&&(!t._didSleepLastStep&&n.sleepState===qe.SLEEPING?console.log("BODY SLEEPING",n):t._didSleepLastStep&&n.sleepState!==qe.SLEEPING&&console.log("BODY WOKE UP",n)),t._didSleepLastStep=n.sleepState===qe.SLEEPING;let i=t.obj;if(n.type===qe.KINEMATIC){let s=st(i,this.temp);n.position.set(s.x,s.y,s.z);let r=cn(i,this.tempQuat);n.quaternion.set(r.x,r.y,r.z,r.w);continue}if(t.parent&&i.parent===t.parent){ZL(i,n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w);let s=n.position;Fd(i,s.x,s.y,s.z),n.velocity.length()>n.sleepSpeedLimit&&Qt.markDirty(i)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let n=new qe;n._owner=e,n._name=e.name,e.getWorldPosition(this.tempPosition);let i=this.tempPosition;n.position=new H(i.x,i.y,i.z);let s=this.tempQuaternion;return e.getWorldQuaternion(s),n.quaternion=new jt(s.x,s.y,s.z,s.w),n.type=qe.KINEMATIC,t&&(n.addShape(t),n.updateMassProperties()),n}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=n=>this.raiseCollisionEvents(e.obj,n);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let n=new QM(t.contact,t.type),i=0,s=this.objects;function r(){if(!(i>0))for(let a=0;a<s.length;a++){if(i==2)return;let l=s[a];l.body==t.body?(n.obj=l.obj,++i):l.body==t.target&&(n.target=l.obj,++i)}}l5&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let a=0;a<e.userData?.components?.length;a++){let l=e.userData.components[a];l.onCollision&&(r(),l.onCollision(n))}}};var Iy=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 Pd;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};var MO=Du(_O(),1);function bO(o=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(o)===!0}var ys=class extends ce{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?ys.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let s=be(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=ys.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return bO(e)}};var Zr=new Int32Array(2),Ny=new Float32Array(Zr.buffer),Uy=new Float64Array(Zr.buffer),jd=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var bi=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?bi.ZERO:new bi(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};bi.ZERO=new bi(0,0);var Km;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Km||(Km={}));var Jr=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Jr(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new bi(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new bi(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Zr[0]=this.readInt32(e),Ny[0]}readFloat64(e){return Zr[jd?0:1]=this.readInt32(e),Zr[jd?1:0]=this.readInt32(e+4),Uy[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){Ny[0]=t,this.writeInt32(e,Zr[0])}writeFloat64(e,t){Uy[0]=t,this.writeInt32(e,Zr[jd?0:1]),this.writeInt32(e+4,Zr[jd?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e),i="",s=0;if(e+=4,t===Km.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;s<n;){let r,a=this.readUint8(e+s++);if(a<192)r=a;else{let l=this.readUint8(e+s++);if(a<224)r=(a&31)<<6|l&63;else{let c=this.readUint8(e+s++);if(a<240)r=(a&15)<<12|(l&63)<<6|c&63;else{let h=this.readUint8(e+s++);r=(a&7)<<18|(l&63)<<12|(c&63)<<6|h&63}}}r<65536?i+=String.fromCharCode(r):(r-=65536,i+=String.fromCharCode((r>>10)+55296,(r&(1<<10)-1)+56320))}return i}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return bi.create(e,t)}createScalarList(e,t){let n=[];for(let i=0;i<t;++i)e(i)!==null&&n.push(e(i));return n}createObjList(e,t){let n=[];for(let i=0;i<t;++i){let s=e(i);s!==null&&n.push(s.unpack())}return n}};var _s=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=Jr.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){let i=this.bb.capacity();this.bb=_s.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let n=t<<1,i=Jr.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let i=2;this.addInt16(e-this.object_start);let s=(n+i)*2;this.addInt16(s);let r=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let l=this.bb.capacity()-this.vtables[t];if(s==this.bb.readInt16(l)){for(let c=2;c<s;c+=2)if(this.bb.readInt16(a+c)!=this.bb.readInt16(l+c))continue e;r=this.vtables[t];break}}return r?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,r-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let i=n?4:0;if(t){let s=t;if(this.prep(this.minalign,4+4+i),s.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let r=4-1;r>=0;r--)this.writeInt8(s.charCodeAt(r))}this.prep(this.minalign,4+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,i=n-this.bb.readInt32(n);if(!(this.bb.readInt16(i+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let i,s=e.charCodeAt(n++);if(s<55296||s>=56320)i=s;else{let r=e.charCodeAt(n++);i=(s<<10)+r+(65536-(55296<<10)-56320)}i<128?t.push(i):(i<2048?t.push(i>>6&31|192):(i<65536?t.push(i>>12&15|224):t.push(i>>18&7|240,i>>12&63|128),t.push(i>>6&63|128)),t.push(i&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,i=this.space,s=this.bb.bytes();n<t.length;n++)s[i++]=t[n];return this.endVector()}createLong(e,t){return bi.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let i=e[n];if(i!==null)t.push(this.createObjectOffset(i));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var xO={};function qd(o,e){xO[o]=e}function wO(o){let e=o.getBufferIdentifier(),t=xO[e];return t(o)}function EO(o){return typeof o.guid=="function"?o.guid():null}var nT=Du(tT(),1);var zy=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new nT.default(e);t.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),t.on("open",n=>{this._host=new sT(t)})}trySetupClient(e){this._client=new nT.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}},iT=class{_peer;constructor(e){this._peer=e}};var sT=class extends iT{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(n=>n.metadata?.id).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let n=this._peer.connections[t];if(!!n)if(Array.isArray(n))for(let i of n)!i||i.send(e);else console.warn(n)}}}};var rT="wss://needle-tiny-starter.glitch.me/socket",bs=!!be("debugnet"),Vy=!!(bs||be("debugowner"));var vl=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Vy&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0,i=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):i()},100)};i()})}requestOwnership(){return Vy&&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?(Vy&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Vy&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var Gy=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new zy),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return bs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),bs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,n=2){if(t===null&&(t={}),n===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){bs&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let n in this._defaultMessagesBuffer){let i=this._defaultMessagesBuffer[n];if(e<=1){this.sendWithWebsocket(i.key,i.value,3);break}let s=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&bs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}connect(){if(this.connected)return;bs&&console.log("connecting");let t=$.findObjectOfType(ys,this.context,!1)?.getWebsocketUrl();t&&(rT=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+rT);let e=new MO.WebsocketBuilder(rT).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,n)=>{console.error(t,n)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}let i=JSON.parse(n);if(Array.isArray(i))for(let s of i)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(i);return}catch{bs&&n==="pong"&&console.log("<<",n)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var n=new Uint8Array(t);let i=new Jr(n),s=i.getBufferIdentifier(),r=this._listenersBinary[s],a=wO(i),l=EO(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;let c=a??i;for(let h of r)h(c)}handleIncomingStringMessage(e){if(bs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.log("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(bs&&console.log(e),e){this._isInRoom=!0;let r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),bs&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let r=e.data;this._currentInRoom.push(r.userId),bs&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(console.log(r.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),bs&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let i of t)i(e.data);let n=e.data;n&&(this._state[n.guid]=n)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=1){if(!this._ws){let s=this._waitingForSocket[n]||[];s.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=s;return}let i=JSON.stringify(this.toMessage(e,t));bs&&console.log(">>",e),this._ws.send(i)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let n of t)n();t.length=0}}};import{OrbitControls as y5}from"three/examples/jsm/controls/OrbitControls";var Qo=class extends ce{constraintActive=!0;locked=!1;sources=[]};ne([te(De)],Qo.prototype,"sources",2);var xs=class extends ce{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;awake(){this._lookTargetPosition=new O}onEnable(){this._enableTime=this.context.time.time;let t=$.getComponent(this.gameObject,Bt)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new y5(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=$.getComponent(this.gameObject,Bt);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new O(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Zn;e.screenPoint=new _e(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&$.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=st(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};ne([te(Qo)],xs.prototype,"lookAtConstraint",2);var gn=class extends q{alpha=1;get isRGBAColor(){return!0}constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let n=e;return n.alpha&&(this.alpha=gt.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};var TO=be("debugcam"),Bt=class extends ce{get aspect(){return this._cam instanceof Wt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof Wt&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(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(){TO&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Wt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new Ka(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.environmentIsTransparent()&&(!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.environmentIsTransparent()&&(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}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode;return t==="additive"||t==="alpha-blend"}enableSkybox(){this._skybox||(this._skybox=new oT(this)),this._skybox.enable()}};ne([te()],Bt.prototype,"fieldOfView",1),ne([te()],Bt.prototype,"nearClipPlane",1),ne([te()],Bt.prototype,"farClipPlane",1),ne([te()],Bt.prototype,"clearFlags",1),ne([te()],Bt.prototype,"orthographic",2),ne([te()],Bt.prototype,"orthographicSize",2),ne([te()],Bt.prototype,"ARBackgroundAlpha",2),ne([te(gn)],Bt.prototype,"backgroundColor",1);var oT=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(TO&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Ct,this._skybox.mapping=Ws,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function CO(o){let e="created/implictly",t=new De;o.add(t);let n=$.addNewComponent(t,Bt,!1);n.sourceId=e;let i=$.addNewComponent(t,xs,!1);return i.sourceId=e,n}import{EffectComposer as VY}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as GY}from"three/examples/jsm/postprocessing/RenderPass";var Yd=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,n,i){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=n,this._speed=i}};function RO(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Um.generateUUID(),index:-1,clip:new br(o,1,[])}}var aT=class{_types={};add(e,t){let n=this._types[e];n===void 0?this._types[e]=t:n!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},pe=new aT;var Qr=be("gizmos"),Nn=be("debugextension");var jy=be("debugresolvedependencies"),_5=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Zd(o,e){jy&&console.log(o,e);let t=[];cT(_5,o,e,t);let n=await Promise.all(t);return typeof e=="string"&&n.length===1?n[0]:n}function cT(o,e,t,n){if(typeof t=="object"&&t!==void 0&&t!==null)for(let i of Object.keys(t)){let s=t[i];if(typeof s=="string"){let r=AO(e,s);if(r!==null)typeof r.then=="function"?n.push(r.then(a=>t[i]=a)):t[i]=r;else for(let a of o){let l=hT(a.prefix,s);if(l>=0){jy&&console.log(a,l,a.dependencyName),n.push(e?.getDependency(a.dependencyName,l).then(c=>(t[i]=c,c)));break}}}else if(Array.isArray(s))for(let r=0;r<s.length;r++){let a=s[r],l=AO(e,a);if(l!==null){typeof l.then=="function"?n.push(l.then(c=>s[r]=c)):s[r]=l;continue}for(let c of o){let h=hT(c.prefix,a);if(h>=0){jy&&console.log(c,h,c.dependencyName),n.push(e?.getDependency(c.dependencyName,h).then(u=>s[r]=u));break}}typeof a=="object"&&cT(o,e,a,n)}else typeof s=="object"&&cT(o,e,s,n)}else typeof t=="string"&&b5(o,e,t,n)}var lT="extensions/";function AO(o,e){if(o&&o.plugins&&typeof e=="string"&&e.startsWith(lT)){let t=e.substring(lT.length),n=t.indexOf("/");n>=0&&(t=t.substring(0,n));let i=o.plugins[t];if(Nn&&console.log(t,i),typeof i?.resolve=="function"){let s=e.substring(lT.length+t.length+1);return i.resolve(o,s)}}return null}function b5(o,e,t,n){for(let i of o){let s=hT(i.prefix,t);if(s>=0)return jy&&console.log(i,s,i.dependencyName),n.push(e?.getDependency(i.dependencyName,s).then(r=>r)),!0}return!1}function hT(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),n=Number.parseInt(t);if(n>=0)return n}return-1}var uT="NEEDLE_persistent_assets";function PO(o){return o?.___persistentAsset===!0}var Xy=class{get name(){return uT}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[uT];if(!t)return;Nn&&console.log(t);let n=new Array;for(let i of t?.assets){let s=Zd(this.parser,i);s&&n.push(s)}await Promise.all(n)}resolve(e,t){let n=Number.parseInt(t);if(n>=0){Nn&&console.log(t);let i=e.json.extensions[uT];if(i){let s=i?.assets[n];if(s&&typeof s=="object"){s.___persistentAsset=!0;let r=s.__type;if(r){let a=pe.get(r)}}return s}}return null}};var _h=be("debugserializer"),dT=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}_h&&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){_h&&console.log("invalid type");return}let n=e.name??e.constructor?.name;if(!n){_h&&console.log("invalid name",n);return}let i=this.getSerializer(n);if(i!==void 0)return _h&&console.log("FOUND "+n,e.name,e.constructor.name,i,this.typeMap),i;let s=Object.getPrototypeOf(e);if(!(s.prototype||s.constructor)){_h&&console.warn("No prototype for "+n,e,e.name,e.prototype,e.constructor.name);return}let a=s.prototype??s.constructor;if(a!==e){let l=this.getSerializerForConstructor(a,++t);if(l){_h&&console.log("FOUND "+a.constructor.name,a.name,a,l);let c=a.name??a.constructor.name;c==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,l):this.register(c,l)}return l}}},Yy=new dT,$o=class{constructor(e){if(Array.isArray(e))for(let t of e)Yy.register(t.name,this);else Yy.register(e.name,this)}},Jd=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function pT(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let n={};for(let i in t){let s=o[i];if(s!=null&&typeof s=="object"){let r=Yy.getSerializerForConstructor(s);if(r){n[i]=r.onSerialize(s,e);continue}}n[i]=s}return n.name=o.constructor.name,typeof o.guid=="string"&&(n.guid=o.guid),n}var qy=[];function IO(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return IO(t,e)}function eg(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let s=o.onBeforeDeserialize(e,t);if(typeof s=="boolean")return s}let n=IO(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),n)for(let s in n){let r=n[s],a=e[s];if(t.path=s,r===null)o[s]=a;else{let l=function(c){let u=c.type;return u?fT(a,u,t,void 0,o[s]):fT(a,c,t,void 0,o[s])};var i=l;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(s,a,t)===!0)continue;if(Array.isArray(r))for(let c=0;c<r.length;c++){let h=r[c],u=l(h);if(u!==void 0||c===r.length-1){o[s]=u;break}}else o[s]=l(r);qy.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(s,a,t)}}x5(o,e)}return o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}function x5(o,e){for(let n of Object.keys(e)){let i=e[n];if(typeof i=="object"&&i!==null&&i!==void 0){let s=o[n];if(!s){_h&&console.log(n,"is undefined on",o);continue}for(let r of Object.keys(i))s[r]===void 0&&t(i[r])&&!t(s)&&(s[r]=i[r])}}function t(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}}function fT(o,e,t,n,i){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,i),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(!s&&i instanceof r)return i;if(i&&typeof i=="object"&&PO(i)){if(i.__concreteInstance)return i.__concreteInstance;let h=i;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&eg(h,o,t),i&&r!==void 0)try{let u=new r;Nn&&console.log("Create concrete instance for persistent asset",i,"instance:",u),tg(u,i),i.__concreteInstance=u,i=u}catch(u){console.error("Error creating instance or creating values on instance",u,i,r)}return i}if(n||(n={serializer:Yy.getSerializerForConstructor(r)}),Array.isArray(o)){let h=[];for(let u=0;u<o.length;u++){let d=o[u],f=fT(d,e,t,n,d);h.push(f)}return h}let a=n.serializer;if(a)return a.onDeserialize(o,t);let l;o&&(o.isMaterial||o.isTexture||o.isObject3D)?l=o:l=new r(...w5(o));let c=l;return c.$serializedTypes&&eg(c,o,t),l}function w5(o){if(qy.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))qy.push(o[e]);return qy}function tg(o,e){if(e==null||o==null)return;let t=!1;for(let n of Object.keys(e)){let i=E5(o,n);t&&i===void 0||(!i||i.writable===!0||i?.set!==void 0)&&(o[n]=e[n])}}function E5(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var yl=be("debuganimatorcontroller"),mT=be("debugrootmotion"),Cr=class{Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let r=this.model.layers[t].stateMachine;for(let a of r.states)if(a.name===e||a.hash===e){yl&&console.log("transition to ",a),this.transitionTo(a,i,n);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??!1}SetFloat(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetInteger(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetTrigger(e){yl&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e)return n;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new Ho(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Hm(this.model,(n,i,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||s?.constructor?.name==="AnimationAction"||s.tracks!==void 0));return console.assert(e!==this.model),new Cr(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,yl&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],n=t.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{let i=n.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(yl&&console.debug("REMOVE",t.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,n=t.motion.action,i=0;for(let r of t.transitions){if(++i,!r.hasExitTime&&r.conditions.length<=0)continue;let a=!0;for(let l of r.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(!!a){yl&&a&&console.log("All conditions are met",r.conditions,n);for(let l of r.conditions){let c=this.model.parameters.find(h=>h.name===l.parameter);c?.type===9&&(c.value=!1)}if(n){let l=t.motion.clip.duration,c=l<=0?1:n.time/l;if(!r.hasExitTime||c>=r.exitTime&&n.time>=n.getClip().duration){n.clampWhenFinished=!0,yl&&(console.log("transition to "+r.destinationState,r),console.log(n.time,r.exitTime)),this.transitionTo(r.destinationState,r.duration,r.offset);return}}else{this.transitionTo(r.destinationState,r.duration,r.offset);return}break}}let s=!1;if(t.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&t&&!e&&n&&this.animator&&t.behaviours){let r=n?.getClip().duration,a=n.time/r,l=new Yd(this._activeState,a,r,this._speed);for(let c of t.behaviours)c.instance&&c.instance.onStateUpdate?.call(c.instance,this.animator,l,0)}}transitionTo(e,t,n){if(!this.animator)return;let i=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[i].stateMachine.defaultState),e=this.model.layers[i].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let s=this._activeState===e;if(s){let c=e.motion;!c.action_loopback&&c.clip&&(this._mixer.uncacheAction(c.clip,this.animator.gameObject),c.action_loopback=this.createAction(c.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let c=this._activeState?.motion.clip.duration,h=this._activeState.motion.action.time/c,u=new Yd(this._activeState,h,c,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateExit?.call(d.instance,this.animator,u,i)}let r=this._activeState?.motion.action;r&&r.fadeOut(t),s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);let a=this._activeState;this._activeState=e;let l=e.motion?.action;if(l){n=Math.max(0,Math.min(1,n)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,l.enabled=!0;let c=e.motion.clip.duration;if(l.time=n*c,l.clampWhenFinished=!0,l.setLoop(Ld,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let h=new Yd(e,n,c,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,h,i)}}else console.warn("No action",e.motion,this);yl&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new gT(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let n=t.stateMachine;for(let i=0;i<n.states.length;i++){let s=n.states[i];if(s.motion||(s.motion=RO(s.name)),this.animator&&s.motion.clips){let r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);s.motion.clip=r?.clip}if(!s.motion.clip){let r=new br;s.motion.clip=r}if(s.motion?.clip){let r=s.motion.clip,a=this.createAction(r);s.motion.action=a}if(s.behaviours&&Array.isArray(s.behaviours))for(let r of s.behaviours){if(!r?.typeName)continue;let a=pe.get(r.typeName),l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,tg(l,r.properties),r.instance=l),yl&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let n=0;n<t.states.length;n++){let i=t.states[n];i?.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}rootMotionHandler},Zy=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let n=e,i=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;let r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},Mn=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new O;rotationChange=new Oe;constructor(e,t,n,i,s){if(this.context=e,this.root=t,this.clip=n,Mn.firstKeyframeRotation[n.uuid]||(Mn.firstKeyframeRotation[n.uuid]=new Oe),s){let r=s.values;Mn.firstKeyframeRotation[n.uuid].set(r[0],r[1],r[2],r[3])}Mn.spaceRotation[n.uuid]||(Mn.spaceRotation[n.uuid]=new Oe),Mn.effectiveSpaceRotation[n.uuid]||(Mn.effectiveSpaceRotation[n.uuid]=new Oe),Mn.clipOffsetRotation[n.uuid]=new Oe,s&&Mn.clipOffsetRotation[n.uuid].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(n,i),this.handleRotation(n,s)}onStart(e){if(e.getClip()!==this.clip)return;let t=Mn.lastObjRotation[this.root.uuid];Mn.spaceRotation[this.clip.uuid].copy(t);{let n=new Lt().setFromQuaternion(t);console.log("START",this.clip.name,gt.toDegrees(n.y))}}getClipRotationOffset(){return Mn.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let n=this.root;mT&&n.add(new xr),Mn.lastObjPosition[n.uuid]||(Mn.lastObjPosition[n.uuid]=new O);let i=new O,s=new O,r=0;this.positionWrapper=new Zy(t,(a,l)=>{let c=this.action.getEffectiveWeight();if(mT&&n.position.length()>8&&n.position.set(0,n.position.y,0),a>r){i.set(l[0],l[1],l[2]),i.sub(s),i.multiplyScalar(c),i.applyQuaternion(this.getClipRotationOffset());let h=this.clip.uuid;i.applyQuaternion(Mn.spaceRotation[h]),this.positionChange.copy(i)}return s.fromArray(l),r=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(mT){let a=t.values,l=new Lt().setFromQuaternion(new Oe(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",gt.toDegrees(l.y));let c=t.values.length-4,h=new Oe().set(a[c],a[c+1],a[c+2],a[c+3]),u=new Lt().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",gt.toDegrees(u.y))}let n=this.root;Mn.lastObjRotation[n.uuid]||(Mn.lastObjRotation[n.uuid]=new Oe);let i=0,s=new Oe,r=new Oe;this.rotationWrapper=new Zy(t,(a,l)=>(a>i&&(r.set(l[0],l[1],l[2],l[3]),s.invert(),r.multiply(s),this.rotationChange.copy(r)),s.fromArray(l),i=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Mn.identityQuaternion,1-e)}},Tr=Mn;Se(Tr,"lastObjPosition",{}),Se(Tr,"lastObjRotation",{}),Se(Tr,"firstKeyframeRotation",{}),Se(Tr,"spaceRotation",{}),Se(Tr,"effectiveSpaceRotation",{}),Se(Tr,"clipOffsetRotation",{}),Se(Tr,"identityQuaternion",new Oe);var gT=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,n){this.root=t;let i="";t&&"name"in t&&(i=t.name);let s=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),a=new Tr(this.controller.context,t,n,s,r);this.handler.push(a);let l=e.clipAction(n);return a.action=l,l}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new O;summedRotation=new Oe;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Tr.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let n=e.tracks;for(let i of n)if(i.name.endsWith(t))return i;return null}};var S5=be("debuganimator"),ws=class extends ce{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Cr?this._animatorController=e:this._animatorController=new Cr(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){this.runtimeAnimatorController?.Play(e,t,n,i)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=gt.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=gt.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}S5&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};ne([te()],ws.prototype,"applyRootMotion",2),ne([te()],ws.prototype,"hasRootMotion",2),ne([te()],ws.prototype,"keepAnimatorControllerStateOnDisable",2),ne([te()],ws.prototype,"runtimeAnimatorController",1);var Rr=class extends ce{playAutomatically=!0;randomStartTime=!0;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&Qt.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let n=e;if(typeof e=="number"){if(e>=this.animations.length)return;n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(s=>s.name===e));if(!n){console.error("Could not find clip",e);return}for(let s of this.actions)if(s.getClip()===n)return this.internalOnPlay(s,t);let i=this.mixer.clipAction(n);return this.actions.push(i),this.internalOnPlay(i,t)}internalOnPlay(e,t){var n=this.currentAction;if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let r=this.tryFindHandle(e);if(r)return r.getPromise()}let i=t?.exclusive??!0;t?.fadeDuration?(i&&n?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):i&&n?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Y0:Ld),e.play();let s=new vT(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Ho(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};ne([te()],Rr.prototype,"playAutomatically",2),ne([te()],Rr.prototype,"randomStartTime",2);var vT=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,n,i){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=i,this._options=n}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as FF}from"three/examples/jsm/loaders/GLTFLoader.js";var _l=class extends ce{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new O}update(){if(!this.from||!this.to)return;let e=st(this.from).clone(),t=st(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),kt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(st(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};ne([te($)],_l.prototype,"from",2),ne([te($)],_l.prototype,"to",2);var $r=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};ne([te()],$r.prototype,"time",2),ne([te()],$r.prototype,"value",2),ne([te()],$r.prototype,"inTangent",2),ne([te()],$r.prototype,"inWeight",2),ne([te()],$r.prototype,"outTangent",2),ne([te()],$r.prototype,"outWeight",2),ne([te()],$r.prototype,"weightedMode",2);var bh=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return gt.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};ne([te($r)],bh.prototype,"keys",2);import{PositionalAudioHelper as M5}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Jy=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var es=be("debugaudio");var Jn=class extends ce{static get userInteractionRegistered(){return Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction()),Jn._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!Jn._userInteractionRegistered){Jn._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(es&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Jn._userInteractionRegistered){let e=$.getComponent(this.context.mainCamera,Ar)??$.findObjectOfType(Ar,this.context);e?.listener&&(this.sound=new Im(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new rl,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Jn._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Jn._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Jn._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){es&&console.log("audio buffer loaded"),Jn.registerWaitForAllowAudio(()=>{es&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),es&&console.log(this.name,this.shouldPlay,Jn.userInteractionRegistered,this),this.shouldPlay&&Jn._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(es&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?es&&!this.helper&&(this.helper=new M5(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(es&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new rl),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){es&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,es&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,es&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,es&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,es&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},$t=Jn;Se($t,"_didCallBeginWaitForUserInteraction",!1),Se($t,"callbacks",[]),Se($t,"_userInteractionRegistered",!1),ne([te()],$t.prototype,"clip",2),ne([te()],$t.prototype,"playOnAwake",2),ne([te()],$t.prototype,"loop",1),ne([te()],$t.prototype,"spatialBlend",1),ne([te()],$t.prototype,"minDistance",1),ne([te()],$t.prototype,"maxDistance",1),ne([te()],$t.prototype,"volume",1),ne([te()],$t.prototype,"rollOffMode",2);var Ar=class extends ce{get listener(){return this._listener==null&&(this._listener=new th),this._listener}_listener=null;awake(){$t.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=$.getComponentInParent(this.gameObject,Bt);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as R5}from"three/examples/jsm/loaders/GLTFLoader";var HO=Du(UO(),1),Qy=class{success;filename;hash;size;url;constructor(e,t,n,i){this.success=e,this.filename=t,this.hash=n,this.size=i}};async function zO(o,e){let t=await o.arrayBuffer(),n=VO(t),i=o.name.split(".").pop(),s=n+"."+i,r=o.name.split(".").shift();console.assert(r!==void 0);let a={alias:r,filename:s},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",n),new Qy(!0,s,n,o.size);console.log("begin uploading file",r,o.size);let h=new FormData;h.append("file",o);let u={};u.filesize=o.size,r&&(u.alias=r);let f=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===n,"hash sum did not match","received:",f.hash_sum,"expected:",n),f.success&&console.log("successfully uploaded",n,f.id);let g=new Qy(f.success,s,n,o.size);return g.url=e,g}function VO(o){return(0,HO.default)(new Uint8Array(o))}async function $y(o,e,t,n,i=!1){try{let s=await fetch(n+"/download/file",{method:"POST",body:o});if(s.status!==200)return console.error("download failed",s),null;let r=await s.blob(),a=await r.arrayBuffer();i||console.assert(r.size===t,"size mismatch","expected:",t,"got:",r.size);let l=VO(a);return i||console.assert(l===e,"hash mismatch, downloaded file is invalid"),r.arrayBuffer()}catch(s){console.error(s)}return null}async function GO(o,e){let t=await fetch(o),n=t.body?.getReader(),i=t.headers.get("Content-Length"),s=i?parseInt(i):0;if(!n)return null;let r=0,a=[];for(;;){let{done:h,value:u}=await n.read();if(u&&(a.push(u),r+=u.length,e.call(null,new ProgressEvent("progress",{loaded:r,total:s}))),h)break}let l=new Uint8Array(r),c=0;for(let h of a)l.set(h,c),c+=h.length;return l}var ng=be("debugavatar"),xh=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(s=>s.layers.set(2))}},bl=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let s=new hn;n=$.instantiate(cl(t,e.scene),s)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.isValid?(ng&&console.log("[Custom Avatar] valid config",t,ng?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,ng?i:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ng&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),s=null;if(i.ok){let a=await i.blob();a&&(s=await a.arrayBuffer())}return!s&&(s=await $y(t,t,0,"no url here go away",!0),!s)?null:(await Qd(e,s,null,0))?.scene??null}let n=new R5;return gh(n,e),new Promise((i,s)=>{let r=this.avatarRegistryUrl+"/"+t;n.load(r,async a=>{await Ky(e,r,a),i(a.scene)},a=>{ng&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,["head"]),s=this.findAvatarPart(n,["left","hand"]),r=this.findAvatarPart(n,["right","hand"]);if(!i){i=t;let l=new O;new On().setFromObject(i).getSize(l);let c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&i.scale.multiplyScalar(1/c*.3)}return new xh(t,i,s,r)}findAvatarPart(e,t){let n=e.name.toLowerCase(),i=!0;for(let s of t){if(!i)break;n.indexOf(s)===-1&&(i=!1)}if(i)return e;if(e.children)for(let s of e.children){let r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};var Ko=class extends ce{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Qr)return;this._axes||(this._axes=new xr(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};ne([te()],Ko.prototype,"length",2),ne([te()],Ko.prototype,"depthTest",2),ne([te()],Ko.prototype,"isGizmo",2);var $d=class extends ce{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=st(this.to).clone(),t=st(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let s=t.clone();s.add(e),s.multiplyScalar(.5);let r=st(this.hint).clone();r.sub(s);let a=new O;a.crossVectors(r,i),a.crossVectors(i,a),a.normalize();let l=n*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),u=a.clone();u.multiplyScalar(h),u.add(s),kt(this.gameObject,u);let d=s.clone();d.sub(a),this.gameObject.lookAt(d)}};var A5=new ri(1,1,1);function e_(o=null){let e=new q(o??14540253),t=new bd(A5);return new Qi(t,new Fn({color:e}))}var I5=be("gizmos"),t_=class extends ce{box=null;testBox=new On;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new On),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=st(e,t_._position),n=JL(e,t_._size);this.testBox.setFromCenterAndSize(t,n)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new On),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new O(0,0,0),new O(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!I5&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=e_(e),this.gameObject.add(this._helper)}}},ts=t_;Se(ts,"_position",new O),Se(ts,"_size",new O(.01,.01,.01));function Kd(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?gi:ps,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?gi:ps,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let n of o.children)Kd(n,e)}function ef(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let n=Proxy.revocable(o[e],{set(r,a,l,c){let h=r[a],u=Reflect.set(r,a,l,c);return t(l,h),u}}),i=n.revoke,s=o[e];return n.revoke=()=>{o[e]=s,i()},o[e]=n.proxy,n}function jO(o,e,t=3){let n=o.__scheduledActions;n||(n=o.__scheduledActions={});let i=e.name;n[t]||(n[t]={});let s=n[t];if(s[i])return;function*a(){e?.call(o),s[i]=null}let l=o.startCoroutine(a(),t);s[i]=l}var tf=class extends ce{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?qe.KINEMATIC:qe.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new O,this._smoothedVelocity=new O,this.lastWorldPosition=st(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=ef(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 Ay;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new H(e.x,e.y,e.z),t?new H(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?tf.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):tf.tempPosition.set(0,0,0)}setVelocity(e,t,n){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=n/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,n){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=n/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let n=this.worldQuaternion;if(this.body.quaternion.set(n.x,n.y,n.z,n.w),e){tf.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(tf.copyVector3,this.context.time.deltaTime/.1);let i=this._smoothedVelocity;this.body.velocity.x=i.x,this.body.velocity.y=i.y,this.body.velocity.z=i.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=st(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},Xt=tf;Se(Xt,"tempPosition",new O),Se(Xt,"copyVector3",new O),ne([te()],Xt.prototype,"mass",2),ne([te()],Xt.prototype,"isKinematic",1),ne([te()],Xt.prototype,"drag",2),ne([te()],Xt.prototype,"angularDrag",2),ne([te()],Xt.prototype,"detectCollision",2),ne([te()],Xt.prototype,"sleepThreshold",2);var Kr=class extends ce{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xt))}onDisable(){this._shape}};ne([te(Xt)],Kr.prototype,"attachedRigidbody",2),ne([te()],Kr.prototype,"isTrigger",2);var xl=class extends Kr{radius=.5;center=new O(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};ne([te()],xl.prototype,"radius",2),ne([te(O)],xl.prototype,"center",2);var wl=class extends Kr{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};ne([te(O)],wl.prototype,"size",2),ne([te(O)],wl.prototype,"center",2);var nf=class{};var qs=class extends ce{canGrab=!0;onPointerClick(e){}},Ys=class extends ce{isUsed=!0;usedBy=null};var wh=class extends ts{},sf=class extends ce{deleteBoxes=[];awake(){this.deleteBoxes=$.findObjectsOfType(wh,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&($.getComponentInParent(this.gameObject,Ys)||Bd(this.gameObject,this.context.connection))}}};var Eh=class extends ce{visibleOn;onEnable(){this.apply()}apply(){this.test()||$.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:L5()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};ne([te()],Eh.prototype,"visibleOn",2);var n_;function L5(){if(n_===!0||n_===!1)return n_;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),n_=o,o}var Tn=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,n,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var rf=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Tn).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Tn).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Tn).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Zs=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new rf).__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 El=be("debugsync"),of="STRS";qd(of,Zs.getRootAsSyncedTransformModel);var eo=new _s;function bT(o,e,t=!0){eo.clear();let n=eo.createString(o);Zs.startSyncedTransformModel(eo),Zs.addGuid(eo,n),Zs.addFast(eo,t);let i=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;Zs.addTransform(eo,rf.createTransform(eo,i.x,i.y,i.z,s.x,s.y,s.z,r.x,r.y,r.z));let a=Zs.endSyncedTransformModel(eo);return eo.finish(a,of),eo.asUint8Array()}var xi=class extends ce{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(){El&&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(){El&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new O,this._targetRotation=new Oe,this.lastWorldPos=new O,this.lastWorldRotation=new Oe,this.rb=$.getComponentInChildren(this.gameObject,Xt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new vl(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(of,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&i2(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(of,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Lt;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){El&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){Qt.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&QL(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){El&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let s=e.distanceTo(this.lastWorldPos),r=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(s>a||r>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(El&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qt.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let r=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){let l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&Qt.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(El&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new O(0,0,0))>1e3&&(El&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){El&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let s=bT(this.guid,this,!!i);this.context.connection.sendBinary(s)}}};var s_=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var l=document.createElement("div");l.style.display="none",document.body.appendChild(l);var c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("width",38),c.setAttribute("height",38),c.style.position="absolute",c.style.right="20px",c.style.top="20px",c.addEventListener("click",function(){u.end()}),l.appendChild(c);var h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),h.setAttribute("stroke","#fff"),h.setAttribute("stroke-width",2),c.appendChild(h),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:l}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function d(g){g.addEventListener("end",f),await e.xr.setSession(g),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=g}function f(){u.removeEventListener("end",f),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(d):u.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="AR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(l){l?i():r()}).catch(r),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}};var r_=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let l=null;async function c(u){u.addEventListener("end",h),await e.xr.setSession(u),n.textContent="EXIT VR",l=u}function h(){l.removeEventListener("end",h),n.textContent="ENTER VR",l=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(l===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(c)}else l.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="VR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?i():r(),r_.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),r_.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},af=r_;Se(af,"xrSessionIsGranted",!1);af.registerSessionGrantedListener();var XO=Du(tT(),1);var lf="noVoip",ns=be("debugvoip"),D5=be("voip");var xT=class{id;constructor(e){this.id=e}};var wT=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){ns&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await Vi.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ns&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ns&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ns&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ns&&console.log("call closed",e)}},ET=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,$t.userInteractionRegistered||ns&&console.log("Incoming call, waiting for user interaction before opening audio"),$t.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ns&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new th;this.audio=new ol(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let s of i)if(s.label==="Speakerphone"){n.sinkId=s.deviceId;break}}}),ns&&console.log("call is setup, you should hear something now"),this.analyzer=new Lm(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Vi=class extends ce{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(be(lf)){console.log("VOIP is disabled by url parameter: "+lf);return}if(this.requireParam&&!D5){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new XO.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new wT(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];ns&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){ns&&console.log("Peer connection established and received id"),this.model=new xT(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ns&&console.log("CONNECTION",t),t.on("data",function(n){ns&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,s=this.currentIncomingCalls[n];if(s&&s.close(),ns&&console.log("received call"),await Vi.HasMicrophonePermissions()){let r=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(r)}else e.answer(null);this.currentIncomingCalls[n]=new ET(this,this.gameObject,e),e.on("stream",r=>{ns&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(r)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var cf=be("debugflags");var ST=class{Mask=17;Has(e){let t=this.Mask&e;return cf&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Cn.Apply()}Enable(e){this.Mask|=e,Cn.Apply()}Disable(e){this.Mask&=~e,Cn.Apply()}Toggle(e){this.Mask^=e,Cn.Apply()}EnableAll(){this.Mask=-1,Cn.Apply()}DisableAll(){this.Mask=0,Cn.Apply()}},Es=ST;Se(Es,"Global",new ST);var to=class extends ce{static Apply(){for(let e of this.registry)e.UpdateVisible(Es.Global)}awake(){to.registry.push(this)}onEnable(){to.firstApply||(to.firstApply=!0,to.Apply())}onDestroy(){let e=to.registry.indexOf(this);e>=0&&to.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),cf&&console.log(n),to.buffer.Mask=n,e=to.buffer);let i=e;if(i?(cf&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(cf&&console.log("use global mask"),Es.Global.Has(this.visibleIn)),t!==void 0)if(t)cf&&console.trace("is visible",this.name,this.gameObject.uuid),$.setActive(this.gameObject,!0);else{if(cf&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Cn=to;Se(Cn,"registry",[]),Se(Cn,"firstApply"),Se(Cn,"buffer",new Es);import{XRControllerModelFactory as k5}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as F5}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as B5}from"three/examples/jsm/webxr/OculusHandPointerModel.js";var Sl=be("debugavatar"),ea=class extends ce{static onAvatarMarkerCreated(e){return ea._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ea._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ea.instances.push(this),Sl&&console.log(this);for(let e of ea._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ea.instances.splice(ea.instances.indexOf(this),1);for(let e of ea._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):$.setActive(this.avatar,e))}},Kt=ea;Se(Kt,"instances",[]),Se(Kt,"_onNewAvatarMarkerAdded",[]),Se(Kt,"_onAvatarMarkerDestroyed",[]);var ig=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new O(1,1,1);handLeftScale=new O(1,1,1);handRightScale=new O(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new De;_handLeftTarget=new De;_handRightTarget=new De;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){this._canInterpolate=!0;let n=this.isLocalAvatar?this.head:this._headTarget;if(n.position.set(e.position.x,e.position.y,e.position.z),n.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.headScale),this.handLeft){let i=this.isLocalAvatar?this.handLeft:this._handLeftTarget;i.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),i.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),i.quaternion.multiply(ig.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handLeftScale)}if(this.handRight){let i=this.isLocalAvatar?this.handRight:this._handRightTarget;i.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),i.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),i.quaternion.multiply(ig.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handRightScale)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){Sl&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&vn.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&$.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Sl&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&vn.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;$.setActive(i,!1),e=$.instantiate(i),$.setActive(e,!0)}Sl&&console.log(e);let n=await ig.loader.getOrCreateNewAvatarInstance(this.context,e);if(Sl&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=$.addNewComponent(this.root,Kt),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&vn.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...$.getComponentsInChildren(this.root,Cn)),this.flags.length<=0&&this.head){let i=$.addNewComponent(this.head,Cn);i.visibleIn=20,this.flags.push(i),Sl&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return Sl&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Sl&&console.warn("build avatar failed"),!1}},Js=ig;Se(Js,"loader",new bl),Se(Js,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI));var vn=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??bt.Current?.time.time;return}}}};Se(vn,"Pois",[]),Se(vn,"LastChangeTime",0);var MT=class{guid;position=new O},ta=class extends ce{set controlledTarget(e){this.target=e;let t=pe.get("MoveRandom");if(t&&this.target){let n=$.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new MT;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=$.getComponentInParent(this.gameObject,Kt),this.avatar){let e=$.getComponentInParent(this.gameObject,Kt);this._model=new vl(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&kt(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(vn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=vn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=st(this._currentTargetObject);kt(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=vn.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};var Sh=class extends ce{},Qn=class extends ce{static CreateRaycastLine(){let e=new Ji(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Ni(.5,22,22),t=new Jt({color:this.raycastColor}),n=new _t(e,t);return n.visible=!1,n.layers.set(1),n}static Create(e,t,n,i){let s=n?$.addNewComponent(n,Qn,!1):new Qn;s.webXR=e,s.index=t,s.type=i;let r=e.context;return s.controller=r.renderer.xr.getController(t),s.controllerGrip=r.renderer.xr.getControllerGrip(t),s.controllerModel=this.Factory.createControllerModel(s.controller),s.controllerGrip.add(s.controllerModel),s.hand=r.renderer.xr.getHand(t),s.hand.add(new F5(s.hand)),s.hand.traverse(a=>a.layers.set(2)),s.handPointerModel=new B5(s.hand,s.controller),s.controller.addEventListener("connected",a=>{s.setControllerLayers(s.controllerModel,2),s.setControllerLayers(s.controllerGrip,2),setTimeout(()=>{s.setControllerLayers(s.controllerGrip,2)},1e3)}),s.hand.addEventListener("connected",a=>{if(a.data.hand){e.Rig&&e.Rig.add(s.hand),s.type=0,s.handPointerModel.traverse(h=>h.layers.set(2)),s.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let c=s.hand.joints;if(c)for(let h of Object.keys(c)){let u=c[h];u.parent||s.hand.add(u)}}}),s}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Oe),cn(e).multiply(this._wristQuaternion.setFromEuler(new Lt(-Math.PI/4,0,0)))):null}movementVector=new O;worldRot=new Oe;joystick=new _e;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Qn.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Qn.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Oe;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Qn.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(cn(this.controller),this.useSmoothing?t:1);let n=st(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,kt(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let r=this.getWristQuaternion();r&&this.rayRotation.copy(r)}Bn(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Bn(this.raycastLine,this.rayRotation),kt(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Qn.MovementSpeedFactor,s=2,r=gt.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,l=Math.pow(this.joystick.x,s);l*=a,l*=r;let c=this.joystick.y>0?1:-1,h=Math.pow(this.joystick.y,s);h*=c,l*=r,t.getWorldQuaternion(this.worldRot),this.movementVector.set(l,0,h),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(i*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,d=Math.abs(u);if(d<.4)this.didRotate=!1;else if(d>.5&&!this.didRotate){let f=u>0?-1:1;t.rotateY(gt.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5,s=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,r=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let l=t[a];if(a===4)if(l.pressed&&!this.didChangeScale){this.didChangeScale=!0;let c=this.webXR.Rig;if(c)if(s){s=!1,c.scale.set(1,1,1),r=1,Qn.MovementSpeedFactor=1;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance&&(h.far=Qn.PreviousCameraFarDistance)}else{s=!0,i=!0,r=.1,Qn.MovementSpeedFactor=r*2;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance=h.far,h.far/=r}}else l.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let l=a[0];if(s||this.isValidTeleportTarget(l.object)){let c=l.point;kt(e,c)}}}}else n<.1&&(this.didTeleport=!1);r!==null&&(e.scale.set(r,r,r),e.updateMatrixWorld())}isValidTeleportTarget(e){return $.getComponentInParent(e,Sh)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Qn.raycastColor:i.color=Qn.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=gt.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),e&&e.length>0)for(let n of e){let i=n.object;if(!this.testIsVisible(i)){console.log("not visible");continue}this.lastSelectStartObject=i;let s={selected:i,grab:i},r=Qn.eventSubs["select-start"];if(r&&r.length>0)for(let a of r)a(this,s);s.grab!==i&&console.log("Grabbed object changed","original",i,"new",s.grab),s.grab&&(this.grabbed=is.TryTake(this,s.grab,n,t));break}else{let n=Qn.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let s of n)s(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Qn.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?$.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new vr;return e.origin.copy(st(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=st(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Zn;return e.layerMask=new Fi,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},Vt=Qn;Se(Vt,"Factory",new k5),Se(Vt,"raycastColor",new q(.9,.3,.3)),Se(Vt,"raycastNoHitColor",new q(.6,.6,.6)),Se(Vt,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,0,-1)])),Se(Vt,"handModels",{}),Se(Vt,"eventSubs",{}),Se(Vt,"PreviousCameraFarDistance"),Se(Vt,"MovementSpeedFactor",1);var Gi=class{static AddEventListener(e,t){return Gi.Events[e]||(Gi.Events[e]=[]),Gi.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Gi.Events[e])return;let n=Gi.Events[e].indexOf(t);n>=0&&Gi.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let s=$.getComponentInParent(t,qs);if(!s)return console.warn("Prevented taking object that is not interactable",t),null;let r=t,a=$.getComponentInParent(t,xi);a&&(a.requestOwnership(),r=a.gameObject);for(let c of this.Current)if(c.selected===r)return c.controller===e||(c.free(),c.Take(e,r,t,a,s,n,i)),c;let l=new Gi;return l.Take(e,r,t,a,s,n,i),l}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,s,r,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let l={controller:e,take:t,hit:n,sync:i,interactable:s};Gi.Events.WillTake?.forEach(f=>f(this,l));let c=n;c?.material&&(this.originalMaterial=c.material,Array.isArray(c.material)||(c.material=c.material.clone(),c.material&&c.material.emissive&&(c.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=c,this.controller=e,this.interactable=s,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=$.addNewComponent(this.selected,Ys),this.rigidbodies=$.getComponentsInChildren(this.selected,Xt),st(this.positionSource,this.lastControllerWorldPos);let h=()=>a?this.lastControllerWorldPos.clone():r.point.clone();this.grabDistance=h().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(h());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();cn(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let d=this.controller.webXR.Rig;return d&&this.rigPositionLastFrame.copy(st(d)),vn.Add(e.context,this.selected),Gi.Register(this),this.sync&&(this.sync.fastMode=!0),Gi.Events.DidTake?.forEach(f=>f(this,l)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Gi.Events.WillFree?.forEach(i=>i(this,e)),vn.Remove(this.controller.context,this.selected),Gi.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Gi.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new O;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new O;localQuaternionToGrab=new Oe(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new O;controllerWorldPos=new O;lastControllerWorldPos=new O;controllerPosDelta=new O;totalChangeAlongDirection=0;rigPositionLastFrame=new O;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),st(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=st(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new O),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Bn(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(st(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),kt(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});Qt.markDirty(this.selected,!0)}}},is=Gi;Se(is,"Events",{}),Se(is,"Current",[]);var Qs=class extends ce{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,n){if(n&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new it().fromArray(n.transform.matrix).invert(),e){if(this.invertForward){let i=new it().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),Qt.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new it().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};ne([te()],Qs.prototype,"invertForward",2),ne([te()],Qs.prototype,"arScale",1);var Ml=class extends ce{awake(){}};var Mh=be("debugaddressables"),o_=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},Wi=class{static getOrCreate(e,t,n){let i=ey(e,t);Mh&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",i);let s=n.addressables,r=s.findAssetReference(i);if(r)return r;let a=new Wi(i);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,a2(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&&(Mh&&console.log("Unload",this.asset),this.asset.scene?$.destroy(this.asset.scene):$.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,Mh&&console.log("Preload",this.uri);let e=await GO(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=bt.Current;this._rawBinary?(this._loading=Qd(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Mh&&console.log("Load async",this.uri),this._loading=Th(t,this.uri,null,!0,i=>{this.raiseProgressEvent(i)}));let n=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(n),this._loading=void 0,n)return Go(t),n.scene!==void 0&&(this.asset=n),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,n){let i=bt.Current;if(e||(e=i.scene),this.mustLoad&&await this.loadAssetAsync(),Mh&&console.log("Instantiate",this.uri,"parent:",e),this.asset){Mh&&console.log("Add to scene",this.asset);let s=e instanceof hn?e:null;if(s||(s=new hn),typeof e=="object"&&(e instanceof De?s.parent=e:Object.assign(s,e)),t){s.context=i;let r=this.asset;r.guid=this.uri;let a=uy(r,s,void 0,n);if(a)return a}else{let r=$.instantiate(this.asset,s);if(r)return r}}else Mh&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},TT=class extends $o{constructor(){super([Wi])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?Wi.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new TT;var no=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,s){return e.prep(4,16),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Un=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var YO=be("debugxr"),sg=be("debugavatar");var RT="VRUS";qd(RT,Un.getRootAsVrUserStateBuffer);function CT(){return new Date().getTime()}function N5(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return bi.create(e,t)}var rg=class{guid;time;avatarId;position=new O;rotation=new ot;scale=1;posLeftHand=new O;posRightHand=new O;rotLeftHand=new Oe;rotRightHand=new Oe;constructor(e){this.guid=e}update(e,t,n,i,s){this.time=CT(),this.avatarId=s,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let r=rg.quat0,a=rg.quat1;r.set(n.x,n.y,n.z,n.w),r=r.multiplyQuaternions(r,rg.invertRotation),e&&(e.getWorldQuaternion(a),r.multiplyQuaternions(a,r)),this.rotation.set(r.x,r.y,r.z,r.w),this.scale=e.scale.x;let l=i.LeftController?.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand));let c=i.RightController?.controllerGrip;if(c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let h=i.LeftController.wrist;h&&(h.getWorldPosition(this.posLeftHand),h.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let h=i.RightController.wrist;h&&(h.getWorldPosition(this.posRightHand),h.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);Un.startVrUserStateBuffer(e),Un.addGuid(e,n),Un.addTime(e,N5(this.time)),Un.addAvatarId(e,i),Un.addPosition(e,Tn.createVec3(e,this.position.x,this.position.y,this.position.z)),Un.addRotation(e,no.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Un.addScale(e,this.scale),Un.addPosLeftHand(e,Tn.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Un.addPosRightHand(e,Tn.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Un.addRotLeftHand(e,no.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Un.addRotRightHand(e,no.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let s=Un.endVrUserStateBuffer(e);e.finish(s,RT);let r=e.asUint8Array();t.sendBinary(r)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let s=t.rotation();s&&this.rotation.set(s.x(),s.y(),s.z(),s.w());let r=t.posLeftHand();r&&this.posLeftHand.set(r.x(),r.y(),r.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());let c=t.rotRightHand();c&&this.rotRightHand.set(c.x(),c.y(),c.z(),c.w()),this.scale=t.scale()}},$s=rg;Se($s,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI)),Se($s,"quat0",new Oe),Se($s,"quat1",new Oe);var na=class extends ce{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent(wt)),this.webXR||(this.webXR=$.findObjectOfType(wt,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=$.findObjectOfType(wt,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=$.findObjectOfType(Vi,this.context)),sg){let e="debug-avatar-"+sg,t=new Js(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof sg=="string"&&sg.length>0)if(await t.setAvatarOverride(sg)){let n=new $s(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=$.getComponent(this.gameObject,wt),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),wt.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),wt.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),wt.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(RT,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new $s("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return YO&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let s=new Js(this.context,e,this.webXR);i=s,this.avatars[e]=s}catch(s){this.avatars[e]=null,console.error(s)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),wt.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),wt.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),wt.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=CT();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=CT();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Js(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){YO&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new _s(1024);onXRSessionUpdate(e){this.xrState??=new $s(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new vl(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,s=t.getViewerPose(n.getReferenceSpace());if(!s)return;let r=s?.transform,a=r.position,l=r.orientation;this.xrState.update(i,a,l,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return be("avatar")}};async function U5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function H5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var AT=!1,PT=!1;U5().then(o=>AT=o);H5().then(o=>PT=o);var $n=class extends ce{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(AT||PT)}static get IsARSupported(){return AT}static get IsVRSupported(){return PT}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){$n.XRSupported||console.warn("WebXR is not supported on this device");let n=af.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={requiredFeatures:["hit-test"]};n&&(i.domOverlay={root:n},i.optionalFeatures=["dom-overlay"]);let s=s_.createButton(e.context.renderer,i);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),$n.resetButtonStyles(s),(t?.registerClick??!0)&&s.addEventListener("click",e.onClickedARButton.bind(e)),s}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Wi.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!$.findObjectOfType(na,this.context)){let e=$.addNewComponent(this.gameObject,na,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new Tl(this);let e=$n.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=$n.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(n=$n.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{$n.resetButtonStyles(n),$n.resetButtonStyles(t)},1e3)}_transformOrientation=new Oe;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let s of this.controllers)s.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}$n._isInXr===!1&&t&&this.onEnterXR(t,e),$n.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)Vt.Create(this,e,this.gameObject,0);$n.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(st(this.context.mainCamera)),this._originalCameraRotation.copy(cn(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=$.findObjectOfType(Ml,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new zr,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new O;_originalCameraRotation=new Oe;onEnterXR(e,t){console.log("[XR] session begin",e),$n._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let l=new Oe(a.x,a.y,a.z,a.w),c=new Lt().setFromQuaternion(l);this.rig.rotateY(c.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let r=i.getCamera(this.context.mainCamera);for(let a of r.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let s=this._requestedAR?2:4;switch(Es.Global.Set(s),s){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),$n._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),$n.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),kt(this.context.mainCamera,this._originalCameraPosition),Bn(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),Es.Global.Set(17),$n.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!be("mirror")||setTimeout(()=>{if(!$n.IsInWebXR)return;let t=new URL(window.location.href);kd(t.searchParams,lf,1),kd(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{$n.IsInWebXR&&e.end()})})},1e3)}},wt=$n;Se(wt,"_isInXr",!1),Se(wt,"events",new ms),ne([te(Wi)],wt.prototype,"defaultAvatar",2);var hf=class{webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this.webxr=e}arDomOverlay=null;arOverlayElement=null;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let n=0;n<4;n++)Vt.Create(this.webxr,n,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=$.findObjectOfType(Qs,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(i=>{this.hitTestSource=i})}),!this.reticle&&this.sessionRoot&&(this.reticle=new _t(new ko(.07,.09,32).rotateX(-Math.PI/2),new Jt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,hf.tempWebXRObject||(hf.tempWebXRObject=new De),this.context.scene.add(hf.tempWebXRObject),$.addComponent(hf.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),$.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],s=this.webxr.context.renderer.xr.getReferenceSpace();if(s){let r=i.getPose(s);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,r),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&r)){let a=r.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Tl=hf;Se(Tl,"tempWebXRObject");var IT=!1;var uf=class extends qs{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new _e}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||wt.IsInWebXR)return;let t=$.getComponentInParent(e.object,uf);!t||t!==this||(uf.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||uf.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(wt.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!wt.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&!this._dragHelper?.hasSelected&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new a_(this.context.mainCamera);else return;if(!e||!e.object)return;let t=$.getComponentInParent(e.object,uf);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let l of this.selectStartEventListener)l(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context);let s=$.getComponentInChildren(n,xi);IT&&console.log("DRAG START",s,n),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=$.addNewComponent(n,Ys),this._draggingRigidbodies.length=0;let r=$.getComponentsInChildren(n,Xt);r&&this._draggingRigidbodies.push(...r);let a=tM();$.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(IT&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let i=$.getComponentInChildren(e.object,xi);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=tM();$.invokeOnChildren(t,n("onDragEnd"))}},Ss=uf;Se(Ss,"_active",null),Se(Ss,"lastHovered");var LT=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new si;_hasGroundPlane=!1;_groundPlane=new si;_groundOffset=new O;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new O;_raycaster=new zo;_cameraPlaneOffset=new O;_intersection=new O;_worldPosition=new O;_inverseMatrix=new it;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Ji(LT.geometry),n=t.material;n.color=new q(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Ni(.5,22,22),s=new Jt({color:n.color}),r=new _t(i,s);r.visible=!1,r.layers.set(2),this._groundMarker=r}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);if(this._selected&&vn.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}vn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=$.getComponentsInChildren(this._selected,Xt),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new O(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,n=68,i=83,s=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),r=this._context.input.getTouchesPressedCount()>=2||s;if(r){let l=this._context.input.getPointerPositionDelta(0);l&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,l.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){IT&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let l=st(this._camera).clone().sub(st(this._selected)).normalize(),c=Math.abs(l.dot(this._groundOffsetVector)),h=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!r&&c>.2&&!h&&this._context.input.getPointerPressedCount()<=1,d=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||d)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,u){this._groundOffsetVector.set(0,1,0);let g=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(g,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);d&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=st(this._selected);i.y=e.y,e=i}if(kt(this._selected,e),kt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=st(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),kt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=st(this._selected),t=new vr(new O(0,.1,0).add(e),new O(0,-1,0)),n=new Zn;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let s=0;s<i.length;s++){let r=i[s];if(!r.face||this.contains(this._selected,r.object))continue;let a=new O(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){Qt.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},a_=LT;Se(a_,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,-1,0)]));var Cl=class extends ce{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?ys.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let s=i.getAsFile();if(!s)continue;console.log("Register file "+s.name+" to",this.filesBackendUrl,s);let r=await JO(s,this.context,this.filesBackendUrl);r&&this.addObject(e,r)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async s=>{console.log("dropped url",s);try{let r=new URL(s);if(!r)return;let a=await QO(r,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",s)}})}}async addObject(e,t){console.log("Dropped",t);let n=new Zn;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),s=t.scene;if(i&&i.length>0)for(let r of i){s.position.copy(r.point);break}this.gameObject.add(s),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};ne([te()],Cl.prototype,"filesBackendUrl",2),ne([te()],Cl.prototype,"localhost",2);var io=class extends qs{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new O(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Oe(0,0,0,1)}let e=$.getComponentInParent(this.gameObject,Ss);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),Vt.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new hn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=$.instantiateSynced(this.object,t);return console.assert(n!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};ne([te(De)],io.prototype,"parent",2),ne([te(De)],io.prototype,"object",2),ne([te()],io.prototype,"limitCount",2),ne([te()],io.prototype,"limitInterval",2);var so=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},V5=o=>/^[A-Z]*$/.test(o),Ch=class extends Event{args},Rn=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let s of this.key)i&&V5(s)&&(n+="-"),i=!0,n+=s.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Ch(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new so(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var df=class extends ce{};import{FlyControls as G5}from"three/examples/jsm/controls/FlyControls";var ff=class extends ce{_controls=null;onEnable(){let e=$.getComponent(this.gameObject,Bt)?.cam;this._controls=new G5(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};var ia=class extends ce{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Qr||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new ih(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=e_(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}};ne([te()],ia.prototype,"objectBounds",2),ne([te(q)],ia.prototype,"color",2),ne([te()],ia.prototype,"isGizmo",2);import{GLTFExporter as j5}from"three/examples/jsm/exporters/GLTFExporter.js";var og=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new it,a=new Array,l=new Array,c=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,r);let g=new O,p=new Oe,m=new O;r.decompose(g,p,m),a.push(g.x,g.y,g.z),l.push(p.x,p.y,p.z,p.w),c.push(m.x,m.y,m.z)}let h=new Float32Array(a),u=new Float32Array(l),d=new Float32Array(c);s.attributes={TRANSLATION:n.processAccessor(new Mt(h,3)),ROTATION:n.processAccessor(new Mt(u,4)),SCALE:n.processAccessor(new Mt(d,3))},i[this.name]=!0}};var Rl=Nn,c_="$___Export_Components",W5="NEEDLE_components",OT=class{[rh]},DT=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},pf=class{get name(){return W5}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let n=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(i,s)=>{try{this.serializeUserData(i,s),n(i,s)}finally{this.afterSerializeUserData(i,s)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;!n||n.length<=0||(delete e.userData.components,e[c_]=n)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Rl&&console.log("DONE",JSON.stringify(t)),e[c_]===void 0)return;let n=e[c_];delete e[c_],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;console.log(e.name,n,e.uuid);let i=new DT(e,n,t);this.exportContext[n]=i,this.objectToNodeMap[e.uuid]=n}afterParse(e){Rl&&console.log("AFTER",e);for(let t in this.exportContext){let n=this.exportContext[t],i=n.node,s=n.nodeDef,r=n.nodeIndex,a=i.userData?.components;if(!a||a.length<=0)continue;let l=new OT;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=i,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;let c=[];for(let h of a){this.context.target=h;let u=KO(h,this.context);u!==null&&c.push(u)}c.length>0&&(l[rh]=c,Rl&&console.log("DID WRITE",i,"nodeIndex",r,c))}}beforeRoot(){return Rl&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,n=t?.extensions;if(!n)return;let i=n[this.name];Rl&&console.log("After root",e,this.parser,n);let s=[];if(i===!0){let r=t.json.nodes;for(let a=0;a<r.length;a++){let l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){let l=r[a],c=a,h=l.extensions;if(!h)continue;let u=h[this.name];if(!u)continue;Rl&&console.log("NODE",l);let d=this.nodeToObjectMap[c];if(!d){console.error("Could not find object for node index: "+c,l,t);continue}s.push(this.createComponents(d,u))}}await Promise.all(s)}async createComponents(e,t){if(!t)return;let n=t[rh];if(n){Rl&&console.log(e.name,n);for(let i in n){let s=n[i];Rl&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&await Zd(this.parser,s),e.userData=e.userData||{},e.userData[rh]=e.userData[rh]||[],e.userData[rh].push(s)}}}};var mf=class extends ts{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Ks=class extends ce{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Ks.calculateCenter(this.objects)},n=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ks.saveArrayBuffer(n,e):Ks.saveJson(n,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new j5,this.exporter.register(a=>new og(a)),this.ext=new pf,this.ext.registerExport(this.exporter)),Ks.filterTopmostParent(e);let n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Ks.collectAnimations(e)},i=new De;t?.pivot&&i.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(i.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),$.getComponentsInChildren(a,Sn).forEach(l=>{$.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))});let s=new Jd(i);return this.ext.context=s,new Promise((a,l)=>{try{this.exporter?.parse(i,c=>{r(),a(c)},c=>{r(),l(c)},n)}catch(c){console.error(c),l(c)}finally{console.log("FINALLY")}});function r(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,$.getComponentsInChildren(a,Sn).forEach(l=>{$.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}static collectAnimations(e,t){t=t||[];for(let n of e)!n||n.traverseVisible(i=>{i.animations&&i.animations.length>0&&t.push(...i.animations)});return t}static calculateCenter(e,t){let n=t||new O;return n.set(0,0,0),e.forEach(i=>{n.add(st(i))}),console.log(n),n.divideScalar(e.length),n}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let n=e[t];if(!n){e.splice(t,1),t--;continue}for(;n.parent;){if(e.includes(n.parent)){e.splice(t,1),t--;break}n=n.parent}}}};var sa=class extends ce{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Qr)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Om(e,t,this.color0??new q(.4,.4,.4),this.color1??new q(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};ne([te()],sa.prototype,"isGizmo",2),ne([te(q)],sa.prototype,"color0",2),ne([te(q)],sa.prototype,"color1",2);import{GroundProjectedEnv as X5}from"three/examples/jsm/objects/GroundProjectedEnv.js";var ra=class extends ce{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 K0(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 X5(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))}};ne([te()],ra.prototype,"scale",1),ne([te()],ra.prototype,"radius",1),ne([te()],ra.prototype,"height",1);function kT(o){return o*Math.PI/180}var eD=300,tD=be("debuglights");var wi=class extends ce{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new q(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let n=this._webARRoot?.arScale;typeof n=="number"&&n>0&&(t/=n)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let n=t.shadow.camera;n.far=e,n.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new q(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=wt.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=wt.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){wt.removeEventListener("xrStarted",this._webXRStartedListener),wt.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Qs)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new Td(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-eD*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Fd(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),tD){let r=new Dm(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:let n=new Sd(this.color,this.intensity*Math.PI,this.range,kT(this.spotAngle/2),1-kT(this.innerSpotAngle/2)/kT(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;let i=n.target;n.add(i),i.position.set(0,0,this.range),i.rotation.set(0,0,0);break;case 2:let s=new Md(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=eD*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let n=this.gameObject.scale.x;t.left*=n,t.right*=n}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let n=this.gameObject.scale.y;t.top*=n,t.bottom*=n}this.light.shadow.needsUpdate=!0,tD&&this.context.scene.add(new km(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)}};ne([te()],wi.prototype,"type",2),ne([te(q)],wi.prototype,"color",2),ne([te()],wi.prototype,"shadowNearPlane",1),ne([te()],wi.prototype,"shadowBias",1),ne([te()],wi.prototype,"shadowNormalBias",1),ne([te()],wi.prototype,"shadows",1),ne([te()],wi.prototype,"lightmapBakeType",2),ne([te()],wi.prototype,"intensity",1),ne([te()],wi.prototype,"shadowDistance",1),ne([te()],wi.prototype,"shadowResolution",1);var pre=new O(0,0,0);var gf=be("debugLODs"),q5=be("noLODs");var ro=class{screenRelativeTransitionHeight;distance;renderers};ne([te()],ro.prototype,"screenRelativeTransitionHeight",2),ne([te()],ro.prototype,"distance",2),ne([te()],ro.prototype,"renderers",2);var FT=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let n of t.renderers){let i=this.findRenderer(n,e.gameObject);i&&i.gameObject?this.renderers.push(i):gf&&console.warn("Renderer not found: "+n,e.gameObject)}}findRenderer(e,t){let n=$.foreachComponent(t,i=>i.guid===e||Object.getPrototypeOf(i)?.guid===e?i:null);if(n)return n;for(let i of t.children){let s=this.findRenderer(e,i);if(s)return s}return null}},Al=class extends ce{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!q5&&!this._lodsHandler&&!!this.gameObject&&(gf&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let i of this.lodModels){e=Math.max(i.distance,e);let s=new FT(this,i);this._lods.push(s);for(let r of s.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let i=0;i<t.length;i++){let s=new pd;this._lodsHandler.push(s),this.gameObject.add(s)}let n=new De;gf&&console.log(t);for(let i=0;i<t.length;i++){let s=t[i],r=this._lodsHandler[i],a=s.gameObject,l=0,c=0;gf&&console.log(i,a.name);for(let u of this._lods){let d=null;u.renderers.includes(s)?d=a:d=n,gf&&console.log("add",u.model.distance,d.name);let f=u.model.distance;c=f-l,l=Math.max(f,l),this.onAddLodLevel(r,d,f)}let h=l+c;gf&&console.log("cull",h),this.onAddLodLevel(r,n,h)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,n){e.addLevel(t,n*this._distanceFactor);let i={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(i)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let n=t.lod.levels[t.levelIndex];n.distance=t.distance*e}}}};ne([te(O)],Al.prototype,"localReferencePoint",2),ne([te(ro)],Al.prototype,"lodModels",2);var vf=class extends ce{},yf=class extends ce{};var BT=be("debugnestedgltf"),Rh=class extends ce{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;BT&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new hn;t.idProvider=new ci(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let n=this.gameObject.matrix;BT&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let i=await this.filePath?.instantiate?.call(this.filePath,t);i&&(i.matrixAutoUpdate=!1,i.matrix.identity(),i.applyMatrix4(n),i.matrixAutoUpdate=!0),this.destroy(),BT&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,i)}}hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}};ne([te(Wi)],Rh.prototype,"filePath",2);var oo=class extends ce{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new O(0,0,0);rotationOffset=new O(0,0,0);offset=new O(0,0,0);update(){if(!this.from)return;var e=st(this.from),t=cn(this.from);this.offset.copy(this.positionOffset);let n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){let a=new si(this.gameObject.up,0),l=st(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);let c=new O(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&kt(this.gameObject,e);let i=new Lt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new Oe().setFromEuler(i);this.affectRotation&&Bn(this.gameObject,t.multiply(s));let r=new O;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}};ne([te($)],oo.prototype,"referenceSpace",2),ne([te($)],oo.prototype,"from",2),ne([te(O)],oo.prototype,"positionOffset",2),ne([te(O)],oo.prototype,"rotationOffset",2);var _f=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new q(1,1,1);startColor1=new q(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new _e(0,1);cullingMode=0},bf=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},xf=class{shapeType=NT.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new O(1,1,1);boxThickness=new O(0,0,0);position=new O(0,0,0);rotation=new O(0,0,0);scale=new O(1,1,1);radius=1;sphericalDirectionAmount=0},NT=(v=>(v[v.Sphere=0]="Sphere",v[v.SphereShell=1]="SphereShell",v[v.Hemisphere=2]="Hemisphere",v[v.HemisphereShell=3]="HemisphereShell",v[v.Cone=4]="Cone",v[v.Box=5]="Box",v[v.Mesh=6]="Mesh",v[v.ConeVolume=7]="ConeVolume",v[v.Circle=10]="Circle",v[v.SingleSidedEdge=11]="SingleSidedEdge",v[v.MeshRenderer=12]="MeshRenderer",v[v.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",v[v.BoxShell=14]="BoxShell",v[v.BoxEdge=15]="BoxEdge",v[v.Donut=16]="Donut",v[v.Rectangle=17]="Rectangle",v[v.Sprite=18]="Sprite",v[v.SpriteRenderer=19]="SpriteRenderer",v))(NT||{});var nD=be("debugparticles"),UT=class{age=0;lifetime=0;position;velocity;color},Ah=class extends ce{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(){nD&&console.log(this)}},wf=class extends ce{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Oe;tempVec3=new O;tempQuat=new Oe;awake(){this.renderer=$.getComponent(this.gameObject,Ah),nD&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Lt(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new ht,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Qe(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let n=0;n<e.length;n++)e[n*3]=1,e[n*3+1]=1,e[n*3+2]=1;let t=new Qe(e,3);this.geometry.setAttribute("color",t),this.material=new Nc({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new vd(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let n=this.particleStates[t];if(!n)continue;let i=n.velocity.x*e,s=n.velocity.y*e,r=n.velocity.z*e;n.position.x+=i,n.position.y+=s,n.position.z+=r,this.updateOverLifetime(t,n),this.geometry.attributes.position.setXYZ(t,n.position.x,n.position.y,n.position.z),this.geometry.attributes.color.setXYZ(t,n.color.r,n.color.g,n.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let n=0;n<t;n+=1){if(n>=this.particleStates.length){let s=new UT;s.lifetime=this.main.startLifetime??1,s.position=new O,s.velocity=new O,s.color=new q(1,0,0),this.particleStates.push(s),this.initializeParticle(n,s),s.age=s.lifetime*Math.random()}let i=this.particleStates[n];if(i.age>i.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(n,i);continue}i.age+=e,this.particleStates[n]=i}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let n=t.position;n.multiply(this.shape.scale),n.applyQuaternion(this.shapeRotation),n.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let n=new O(0,1,0);t.copy(n);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*gt.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};function*iD(o,e=null){let t=e?e.time:bt.Current.time,n=t.time;for(;t.time-n<o;)yield}var ss=class extends ce{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 iD(.2),!this.tryAssignColor()););}tryAssignColor(){let e=$.getComponentInParent(this.gameObject,Kt);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ss.hashCode(e),n=ss.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let i=this.gameObject;this.assignColor(n,e,i)}else if(this.gameObject.children)for(let i of this.gameObject.children){let s=i;s.material&&s.material.color&&this.assignColor(n,e,s)}}assignColor(e,t,n){let i=n.material;!i||(i._playerMaterial!==t?(i=i.clone(),i._playerMaterial=t,n.material=i):console.log("DONT CLONE",i),i.color=e)}static hashCode(e){var t=0,n,i;if(e.length===0)return t;for(n=0;n<e.length;n++)i=e.charCodeAt(n),t=(t<<5)-t+i,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,n=(e&65280)>>8,i=e&255;return new q(t/255,n/255,i/255)}};function Z5(){return new Promise((o,e)=>{let n=()=>{n!=null&&(document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n),o())};document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)})}async function sD(o){await Z5(),o()}var HT=be("debugvideo");var ji=class extends ce{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,HT&&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(),sD(()=>{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)}),HT&&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 gm(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ct,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),HT&&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")}};ne([te(De)],ji.prototype,"renderer",2),ne([te()],ji.prototype,"playOnAwake",2),ne([te()],ji.prototype,"playOnEnable",2),ne([te()],ji.prototype,"targetMaterialProperty",2),ne([te()],ji.prototype,"time",2),ne([te()],ji.prototype,"playbackSpeed",1),ne([te()],ji.prototype,"isLooping",1);var Ef=class extends ce{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=$.getComponentInChildren(this.gameObject,ji);if(t){let n={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(n),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};var Pl=class extends ce{mode=0;shadowColor=new gn(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=$.getComponent(this.gameObject,Sn);if(e){let t=e.material;t.blending=Kp,this.applyMaterialOptions(t),t.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
|
|
6339
|
+
`,defines:{USE_LIGHTMAP:""}})}};var te=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=sO(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=sO(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let n=e.$serializedTypes=e.$serializedTypes||{};n[t]=o}};function sO(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var BM=be("debugstencil");function t5(o,e){return(o&1<<e.layer)!=0}var ph=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(BM&&console.log(t,ph.stencils),!t)return;let n=ph.stencils[t];if(!!n)for(let i=n.length-1;i>=0;i--){let s=n[i];if(t5(s.layer,e)){BM&&console.log(s);let r=e.material?.clone();r&&(e.material=r,e.gameObject.renderOrder=s.event*1e3+s.index*50,r.stencilWrite=!0,r.stencilWriteMask=255,r.stencilFuncMask=255,r.stencilRef=s.value,r.stencilFunc=s.compareFunc,r.stencilZPass=s.passOp,r.stencilFail=s.failOp,r.stencilZFail=s.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[i5];if(n){BM&&console.log(n);let i=n.stencil;if(i&&Array.isArray(i))for(let s of i){let r={...s};r.compareFunc=n5(r.compareFunc),r.passOp=NM(r.passOp),r.failOp=NM(r.failOp),r.zFailOp=NM(r.zFailOp),ph.stencils[this.source]||(ph.stencils[this.source]=[]),ph.stencils[this.source].push(r)}}}return null}},mh=ph;Se(mh,"stencils",{});function NM(o){switch(o){case 0:return id;case 1:return IS;case 2:return LS;case 3:return OS;case 4:return DS;case 6:return kS;case 7:return FS;case 5:return BS}return 0}function n5(o){switch(o){case 1:return NS;case 2:return US;case 3:return HS;case 4:return zS;case 5:return VS;case 6:return GS;case 7:return WS;case 8:return J0}return 0}var i5="NEEDLE_render_objects";import{GLTFLoader as s5}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as UM}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as rO}from"three/examples/jsm/loaders/KTX2Loader.js";var Zm=be("debugdecoders"),Sr,pl;function HM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Zm&&console.log("Setting draco decoder path to",o),Sr.setDecoderPath(o))}function zM(o){o!==void 0&&typeof o=="string"&&(Sr||(Sr=new UM),Zm&&console.log("Setting draco decoder type to",o),Sr.setDecoderConfig({type:o}))}function VM(o){o!==void 0&&typeof o=="string"&&(pl||(pl=new rO),Zm&&console.log("Setting ktx2 transcoder path to",o),pl.setTranscoderPath(o))}function gh(o,e){Sr||(Sr=new UM,Sr.setDecoderPath("./include/draco/"),Sr.setDecoderConfig({type:"js"}),Zm&&console.log("Setting draco decoder path to","./include/draco/")),pl||(pl=new rO,pl.setTranscoderPath("./include/ktx2/"),Zm&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&pl.detectSupport(e.renderer)),o.setDRACOLoader(Sr),o.setKTX2Loader(pl)}var GM="NEEDLE_deferred_texture",ml=be("debugdeferredtextures"),Jm=class{static assignTextureLOD(e,t,n=0){if(!!t)for(let i of Object.keys(t)){let s=t[i];s?.isTexture===!0&&(ml&&console.log("FIND",i,s?.name,s?.userData,s),Jm.getOrLoadTexture(e,t,i,s,n).then(r=>{r?.isTexture===!0&&(r.needsUpdate=!0,t[i]=r,t.needsUpdate=!0)}))}}get name(){return GM}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return ml&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[GM];if(i){let s=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),s.then(r=>{ml&&console.log("register texture",r.name,r.uuid,i),r.userData.deferred=i,Jm.cache.set(r.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,s){let r=i.uuid,a=Jm.cache.get(r)||i.userData.deferred;if(a){ml&&console.log(r,a.uri,a.guid);let l=a.uri;if(l.endsWith(".glb")||l.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;let c=a.uri+"_"+a.guid;if(this.resolved[c])return this.resolved[c];let h=new s5;gh(h,e),ml&&console.log("Load "+l,t.name,n);let u=await h.loadAsync(l),d=u.parser,f=-1,g=!1;for(let m of u.parser.json.textures)if(f++,m?.extensions){let y=m?.extensions[GM];if(y?.guid&&y.guid===a.guid){g=!0;break}}if(!g)return null;let p=await d.getDependency("texture",f);return this.resolved[c]=p,ml&&console.log(t.name,n,'change "'+i.name+'" \u2192 "'+p.name+'"',l,f,p,t),p}else{let h=await new Uo().loadAsync(a.uri);return h&&ml?console.log(a,h):console.warn("failed loading",a.uri),h}}else ml&&console.warn("unknown uuid",i.name,i.uuid,i);return null}},Zo=Jm;Se(Zo,"cache",new Map),Se(Zo,"resolved",{});var aO=be("noInstancing"),lO=!!be("debuglightmaps"),r5=be("debuginstancing"),o5=be("debugprogressiveload"),Vd=class{path=null;asset=null;default};var WM=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),n=this.getMaterial.bind(this),i=e.gameObject;if(this._targets=[],i)switch(i.type){case"Group":this._targets=[...i.children];break;case"Mesh":this._targets.push(i);break}return new Proxy(this,{get(s,r){if(typeof r=="string"){let a=parseInt(r);if(!isNaN(a))return n(a)}return s[r]},set(s,r,a){return typeof r=="string"&&t(a,Number.parseInt(r)),Reflect.set(s,r,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let n=this._targets[t];!n||(n.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let n=t[e];return n?n.material:null}},ZM=class extends ce{receiveShadows=!1;shadowCastingMode=jM.Off;lightmapIndex=-1;lightmapScaleOffset=new ot(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new WM(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return aO}_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}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let n=0;n<this.gameObject.children.length;n++){let i=this.gameObject.children[n];if(!(i.type!=="Mesh"||$.getComponent(i,ZM))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}i.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let n=new Yo(this.gameObject,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,lO)}}else if(e==="Group"){for(let n of this.gameObject.children)if(!n.material?.isMeshBasicMaterial){let i=new Yo(n,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,lO),i.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=a5.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return $.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return $.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&&!aO&&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(){mh.applyStencil(this)}onBeforeRenderThree(e,t,n,i,s,r){if(s._didRequestTextureLOD===void 0&&(s._didRequestTextureLOD=0,o5?(console.log("Load material LOD (with delay)",s.name),setTimeout(()=>{Zo.assignTextureLOD(this.context,s)},2e3)):Zo.assignTextureLOD(this.context,s)),s.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;s.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(s)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[XM]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[XM],this.handles)){for(let n=this.handles.length-1;n>=0;n--)this.handles[n].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&$.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let n=this.handles[t];this.prevLayers||(this.prevLayers=[]);let i=n.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(i):this.prevLayers[t]=i,n.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==jM.On?e.castShadow=!0:e.castShadow=!1}},Sn=ZM;ne([te()],Sn.prototype,"receiveShadows",2),ne([te()],Sn.prototype,"shadowCastingMode",2),ne([te()],Sn.prototype,"lightmapIndex",2),ne([te(ot)],Sn.prototype,"lightmapScaleOffset",2),ne([te()],Sn.prototype,"enableInstancing",2),ne([te()],Sn.prototype,"renderOrder",2),ne([te()],Sn.prototype,"allowOcclusionWhenDynamic",2);var vh=class extends Sn{},Gd=class extends vh{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},jM=(i=>(i[i.Off=0]="Off",i[i.On=1]="On",i[i.TwoSided=2]="TwoSided",i[i.ShadowsOnly=3]="ShadowsOnly",i))(jM||{}),XM="NEEDLE_NEED_UPDATE_INSTANCE",Qt=class{static markDirty(e,t=!0){if(!!e&&($.isUsingInstancing(e)&&(e[XM]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let n of e.children)Qt.markDirty(n,!0)}},qM=class{objs=[];setup(e,t,n,i,s=0){let r=this.tryCreateOrAddInstance(e,t,i);if(r)return n===null&&(n=[]),n.push(r),n;if(s<=0&&e.type!=="Mesh"){let a=s+1;for(let l of e.children)n=this.setup(l,t,n,i,a)}return n}tryCreateOrAddInstance(e,t,n){if(e.type==="Mesh"){let i=n.foundMeshes;if(n.foundMeshes+=1,!n.rend.enableInstancing||i>=n.rend.enableInstancing.length||!n.rend.enableInstancing[i])return null;let s=e,r=s.geometry,a=s.material;for(let c of this.objs)if(!c.isFull()&&c.geo===r&&c.material===a)return c.addInstance(s);let l=new Ry(e.name,r,a,200,t);return this.objs.push(l),l.addInstance(s)}return null}},a5=new qM,YM=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,n){this.instanceIndex=e,this.object=t,this.instancer=n,$.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},JM=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,n,i,s){this.name=e,this.geo=t,this.material=n,this.context=s,this.maxCount=i,r5&&(n=new Jt({color:this.randomColor()})),this.inst=new gd(t,n,i),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new q(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new YM(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let n=this.handles.indexOf(e);if(n<0)return;e.instanceIndex=n}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,JM.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let n=this.handles[this.currentCount-1];n&&(n.instanceIndex=e.instanceIndex,n.updateInstanceMatrix(),this.handles[e.instanceIndex]=n,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},Ry=JM;Se(Ry,"nullMatrix",new it);var Qm=be("debugphysics"),l5=be("debugcollisions"),Ay=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},$m=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},QM=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var Zn=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new _e),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Fi);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};Se(Zn,"AllLayers",4294967295);var $M=class{distance;point;object;constructor(e,t,n){this.object=e,this.distance=t,this.point=n}},Py=class{raycaster=new zo;defaultRaycastOptions=new Zn;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Fi;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new gr(e,t),i=this.sphereMask;i.enableAll(),i.disable(2);for(let s of this.context.scene.children){let r=this.onSphereOverlap(s,n,i);r&&this.sphereResults.push(r)}return this.sphereResults.sort((s,r)=>s.distance-r.distance)}tempBoundingBox=new On;onSphereOverlap(e,t,n){if(e.type==="Mesh"){if(!e.layers.test(n))return null;let i=e,s=i.geometry;if(s.boundingBox||s.computeBoundingBox(),!s.boundingBox)return null;i.matrixWorldNeedsUpdate&&i.updateMatrixWorld();let r=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(i.matrixWorld);if(t.intersectsBox(r)){let l=st(e).distanceTo(t.center);return new $M(e,l,t.center.clone())}}else if(e.children)for(let i of e.children){let s=this.onSphereOverlap(i,t,n);if(s)return s}return null}raycastFromRay(e,t=null){let n=t??this.defaultRaycastOptions;return n.ray=e,this.raycast(n)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold?n.params.Line={threshold:e.lineThreshold}:n.params.Line={threshold:0},e.ray)n.ray.copy(e.ray);else{let a=this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];n.setFromCamera(t,a)}let i=e.targets;i||(i=this.targetBuffer,i[0]=this.context.scene);let s=e.results;s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Fi?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),s.length=0,n.intersectObjects(i,e.recursive,s);let r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),s}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new Cy;objects=[];tempPosition=new O;tempQuaternion=new Oe;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),Qm){let t={};t.onInit=(n,i,s)=>{i.layers.set(-1)},iO(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let n=0;n<this.objects.length;n++){let i=this.objects[n];if(i.obj===e){i._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,n=!0){this.world.removeBody(t);for(let i=0;i<this.objects.length;i++){let s=this.objects[i];if(s.obj===e){s._hasRigidbody=!1,n&&this.objects.splice(i,1);break}}}removeShape(e,t){for(let n of this.objects)if(n.obj===e){n.body&&(n.body.removeShape(t),n.body.updateMassProperties());return}}createBody(e,t){let n=this.internalCreateBody(e,null);t.mass&&(n.mass=t.mass),t.kinematic?n.type=qe.KINEMATIC:n.type=qe.DYNAMIC,t.drag&&(n.linearDamping=t.drag),t.angularDrag&&(n.angularDamping=t.angularDrag),t.sleepThreshold&&(n.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(n);let i=new $m(e,n);return i._hasRigidbody=!0,this.objects.push(i),Qm&&console.log("created new body",e.name,n,n.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(i),n}addBoxCollider(e,t,n,i,s){let r=this.tempPosition;e.getWorldScale(r);let a=new H(.5*r.x*i.x,.5*r.y*i.y,.5*r.z*i.z),l=new dh(a);l.collisionResponse=!t,n=n.clone(),n.multiply(r);let c=this.addShape(e,l,n,s);if(c!==null){if(this.isAlreadyRegistered(c))return l;let h=new $m(e,c);this.objects.push(h)}return l}addSphereCollider(e,t,n,i){let s=this.tempPosition;e.getWorldScale(s);let r=Math.max(s.x,s.y,s.z),a=new My(n*r);t=t.clone(),t.multiply(s);let l=this.addShape(e,a,t,i);if(l!==null){if(this.isAlreadyRegistered(l))return a;let c=new $m(e,l);this.objects.push(c)}return a}addMeshCollider(e){Qm&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,n,i){let s=null;if(i?(i.initialize(),console.assert(!!i.body,"rigidbody didn't initialize / produce a physics body",i),s=i.body):(s=this.internalCreateBody(e,null),s.type=qe.KINEMATIC,this.world.addBody(s)),s){n.x*=-1;let r=cn(e),a=st(e);a.add(n);let l=new Oe(s.quaternion.x,s.quaternion.y,s.quaternion.z,s.quaternion.w);r.multiply(l.invert());let c=s.position,h=new H(a.x-c.x,a.y-c.y,a.z-c.z),u=new jt(r.x,r.y,r.z,r.w);s.addShape(t,h,u),s.updateMassProperties()}return s}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,Qm&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new O;tempQuat=new Oe;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],n=t.body;if(!n||!n.world)continue;n.sleepTick(this.context.time.time),Qm&&(!t._didSleepLastStep&&n.sleepState===qe.SLEEPING?console.log("BODY SLEEPING",n):t._didSleepLastStep&&n.sleepState!==qe.SLEEPING&&console.log("BODY WOKE UP",n)),t._didSleepLastStep=n.sleepState===qe.SLEEPING;let i=t.obj;if(n.type===qe.KINEMATIC){let s=st(i,this.temp);n.position.set(s.x,s.y,s.z);let r=cn(i,this.tempQuat);n.quaternion.set(r.x,r.y,r.z,r.w);continue}if(t.parent&&i.parent===t.parent){ZL(i,n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w);let s=n.position;Fd(i,s.x,s.y,s.z),n.velocity.length()>n.sleepSpeedLimit&&Qt.markDirty(i)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let n=new qe;n._owner=e,n._name=e.name,e.getWorldPosition(this.tempPosition);let i=this.tempPosition;n.position=new H(i.x,i.y,i.z);let s=this.tempQuaternion;return e.getWorldQuaternion(s),n.quaternion=new jt(s.x,s.y,s.z,s.w),n.type=qe.KINEMATIC,t&&(n.addShape(t),n.updateMassProperties()),n}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=n=>this.raiseCollisionEvents(e.obj,n);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let n=new QM(t.contact,t.type),i=0,s=this.objects;function r(){if(!(i>0))for(let a=0;a<s.length;a++){if(i==2)return;let l=s[a];l.body==t.body?(n.obj=l.obj,++i):l.body==t.target&&(n.target=l.obj,++i)}}l5&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let a=0;a<e.userData?.components?.length;a++){let l=e.userData.components[a];l.onCollision&&(r(),l.onCollision(n))}}};var Iy=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 Pd;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};var MO=Du(_O(),1);function bO(o=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(o)===!0}var ys=class extends ce{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?ys.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let s=be(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=ys.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return bO(e)}};var Zr=new Int32Array(2),Ny=new Float32Array(Zr.buffer),Uy=new Float64Array(Zr.buffer),jd=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var bi=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?bi.ZERO:new bi(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};bi.ZERO=new bi(0,0);var Km;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Km||(Km={}));var Jr=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Jr(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new bi(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new bi(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Zr[0]=this.readInt32(e),Ny[0]}readFloat64(e){return Zr[jd?0:1]=this.readInt32(e),Zr[jd?1:0]=this.readInt32(e+4),Uy[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){Ny[0]=t,this.writeInt32(e,Zr[0])}writeFloat64(e,t){Uy[0]=t,this.writeInt32(e,Zr[jd?0:1]),this.writeInt32(e+4,Zr[jd?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e),i="",s=0;if(e+=4,t===Km.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;s<n;){let r,a=this.readUint8(e+s++);if(a<192)r=a;else{let l=this.readUint8(e+s++);if(a<224)r=(a&31)<<6|l&63;else{let c=this.readUint8(e+s++);if(a<240)r=(a&15)<<12|(l&63)<<6|c&63;else{let h=this.readUint8(e+s++);r=(a&7)<<18|(l&63)<<12|(c&63)<<6|h&63}}}r<65536?i+=String.fromCharCode(r):(r-=65536,i+=String.fromCharCode((r>>10)+55296,(r&(1<<10)-1)+56320))}return i}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return bi.create(e,t)}createScalarList(e,t){let n=[];for(let i=0;i<t;++i)e(i)!==null&&n.push(e(i));return n}createObjList(e,t){let n=[];for(let i=0;i<t;++i){let s=e(i);s!==null&&n.push(s.unpack())}return n}};var _s=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=Jr.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){let i=this.bb.capacity();this.bb=_s.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let n=t<<1,i=Jr.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let i=2;this.addInt16(e-this.object_start);let s=(n+i)*2;this.addInt16(s);let r=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let l=this.bb.capacity()-this.vtables[t];if(s==this.bb.readInt16(l)){for(let c=2;c<s;c+=2)if(this.bb.readInt16(a+c)!=this.bb.readInt16(l+c))continue e;r=this.vtables[t];break}}return r?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,r-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let i=n?4:0;if(t){let s=t;if(this.prep(this.minalign,4+4+i),s.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let r=4-1;r>=0;r--)this.writeInt8(s.charCodeAt(r))}this.prep(this.minalign,4+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,i=n-this.bb.readInt32(n);if(!(this.bb.readInt16(i+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let i,s=e.charCodeAt(n++);if(s<55296||s>=56320)i=s;else{let r=e.charCodeAt(n++);i=(s<<10)+r+(65536-(55296<<10)-56320)}i<128?t.push(i):(i<2048?t.push(i>>6&31|192):(i<65536?t.push(i>>12&15|224):t.push(i>>18&7|240,i>>12&63|128),t.push(i>>6&63|128)),t.push(i&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,i=this.space,s=this.bb.bytes();n<t.length;n++)s[i++]=t[n];return this.endVector()}createLong(e,t){return bi.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let i=e[n];if(i!==null)t.push(this.createObjectOffset(i));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var xO={};function qd(o,e){xO[o]=e}function wO(o){let e=o.getBufferIdentifier(),t=xO[e];return t(o)}function EO(o){return typeof o.guid=="function"?o.guid():null}var nT=Du(tT(),1);var zy=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new nT.default(e);t.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),t.on("open",n=>{this._host=new sT(t)})}trySetupClient(e){this._client=new nT.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}},iT=class{_peer;constructor(e){this._peer=e}};var sT=class extends iT{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(n=>n.metadata?.id).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let n=this._peer.connections[t];if(!!n)if(Array.isArray(n))for(let i of n)!i||i.send(e);else console.warn(n)}}}};var rT="wss://needle-tiny-starter.glitch.me/socket",bs=!!be("debugnet"),Vy=!!(bs||be("debugowner"));var vl=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Vy&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0,i=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):i()},100)};i()})}requestOwnership(){return Vy&&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?(Vy&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Vy&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var Gy=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new zy),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return bs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),bs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,n=2){if(t===null&&(t={}),n===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){bs&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let n in this._defaultMessagesBuffer){let i=this._defaultMessagesBuffer[n];if(e<=1){this.sendWithWebsocket(i.key,i.value,3);break}let s=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&bs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}connect(){if(this.connected)return;bs&&console.log("connecting");let t=$.findObjectOfType(ys,this.context,!1)?.getWebsocketUrl();t&&(rT=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+rT);let e=new MO.WebsocketBuilder(rT).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,n)=>{console.error(t,n)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}let i=JSON.parse(n);if(Array.isArray(i))for(let s of i)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(i);return}catch{bs&&n==="pong"&&console.log("<<",n)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var n=new Uint8Array(t);let i=new Jr(n),s=i.getBufferIdentifier(),r=this._listenersBinary[s],a=wO(i),l=EO(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;let c=a??i;for(let h of r)h(c)}handleIncomingStringMessage(e){if(bs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.log("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(bs&&console.log(e),e){this._isInRoom=!0;let r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),bs&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let r=e.data;this._currentInRoom.push(r.userId),bs&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(console.log(r.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),bs&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let i of t)i(e.data);let n=e.data;n&&(this._state[n.guid]=n)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=1){if(!this._ws){let s=this._waitingForSocket[n]||[];s.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=s;return}let i=JSON.stringify(this.toMessage(e,t));bs&&console.log(">>",e),this._ws.send(i)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let n of t)n();t.length=0}}};import{OrbitControls as y5}from"three/examples/jsm/controls/OrbitControls";var Qo=class extends ce{constraintActive=!0;locked=!1;sources=[]};ne([te(De)],Qo.prototype,"sources",2);var xs=class extends ce{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;awake(){this._lookTargetPosition=new O}onEnable(){this._enableTime=this.context.time.time;let t=$.getComponent(this.gameObject,Bt)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new y5(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=$.getComponent(this.gameObject,Bt);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new O(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Zn;e.screenPoint=new _e(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&$.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=st(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};ne([te(Qo)],xs.prototype,"lookAtConstraint",2);var gn=class extends q{alpha=1;get isRGBAColor(){return!0}constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let n=e;return n.alpha&&(this.alpha=gt.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};var TO=be("debugcam"),Bt=class extends ce{get aspect(){return this._cam instanceof Wt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof Wt&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(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(){TO&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Wt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new Ka(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.environmentIsTransparent()&&(!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.environmentIsTransparent()&&(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}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode;return t==="additive"||t==="alpha-blend"}enableSkybox(){this._skybox||(this._skybox=new oT(this)),this._skybox.enable()}};ne([te()],Bt.prototype,"fieldOfView",1),ne([te()],Bt.prototype,"nearClipPlane",1),ne([te()],Bt.prototype,"farClipPlane",1),ne([te()],Bt.prototype,"clearFlags",1),ne([te()],Bt.prototype,"orthographic",2),ne([te()],Bt.prototype,"orthographicSize",2),ne([te()],Bt.prototype,"ARBackgroundAlpha",2),ne([te(gn)],Bt.prototype,"backgroundColor",1);var oT=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(TO&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Ct,this._skybox.mapping=Ws,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function CO(o){let e="created/implictly",t=new De;o.add(t);let n=$.addNewComponent(t,Bt,!1);n.sourceId=e;let i=$.addNewComponent(t,xs,!1);return i.sourceId=e,n}import{EffectComposer as VY}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as GY}from"three/examples/jsm/postprocessing/RenderPass";var Yd=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,n,i){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=n,this._speed=i}};function RO(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Um.generateUUID(),index:-1,clip:new br(o,1,[])}}var aT=class{_types={};add(e,t){let n=this._types[e];n===void 0?this._types[e]=t:n!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},pe=new aT;var Qr=be("gizmos"),Nn=be("debugextension");var jy=be("debugresolvedependencies"),lT="/extensions/",_5=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"}];async function Zd(o,e){jy&&console.log(o,e);let t=[];cT(_5,o,e,t);let n=await Promise.all(t);return typeof e=="string"&&n.length===1?n[0]:n}function cT(o,e,t,n){if(typeof t=="object"&&t!==void 0&&t!==null)for(let i of Object.keys(t)){let s=t[i];if(typeof s=="string"){let r=AO(e,s);if(r!==null)typeof r.then=="function"?n.push(r.then(a=>t[i]=a)):t[i]=r;else for(let a of o){let l=hT(a.prefix,s);if(l>=0){jy&&console.log(a,l,a.dependencyName),n.push(e?.getDependency(a.dependencyName,l).then(c=>(t[i]=c,c)));break}}}else if(Array.isArray(s))for(let r=0;r<s.length;r++){let a=s[r],l=AO(e,a);if(l!==null){typeof l.then=="function"?n.push(l.then(c=>s[r]=c)):s[r]=l;continue}for(let c of o){let h=hT(c.prefix,a);if(h>=0){jy&&console.log(c,h,c.dependencyName),n.push(e?.getDependency(c.dependencyName,h).then(u=>s[r]=u));break}}typeof a=="object"&&cT(o,e,a,n)}else typeof s=="object"&&cT(o,e,s,n)}else typeof t=="string"&&b5(o,e,t,n)}function AO(o,e){if(o&&o.plugins&&typeof e=="string"&&e.startsWith(lT)){let t=e.substring(lT.length),n=t.indexOf("/");n>=0&&(t=t.substring(0,n));let i=o.plugins[t];if(Nn&&console.log(t,i),typeof i?.resolve=="function"){let s=e.substring(lT.length+t.length+1);return i.resolve(o,s)}}return null}function b5(o,e,t,n){for(let i of o){let s=hT(i.prefix,t);if(s>=0)return jy&&console.log(i,s,i.dependencyName),n.push(e?.getDependency(i.dependencyName,s).then(r=>r)),!0}return!1}function hT(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),n=Number.parseInt(t);if(n>=0)return n}return-1}var uT="NEEDLE_persistent_assets";function PO(o){return o?.___persistentAsset===!0}var Xy=class{get name(){return uT}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[uT];if(!t)return;Nn&&console.log(t);let n=new Array;for(let i of t?.assets){let s=Zd(this.parser,i);s&&n.push(s)}await Promise.all(n)}resolve(e,t){let n=Number.parseInt(t);if(n>=0){Nn&&console.log(t);let i=e.json.extensions[uT];if(i){let s=i?.assets[n];if(s&&typeof s=="object"){s.___persistentAsset=!0;let r=s.__type;if(r){let a=pe.get(r)}}return s}}return null}};var _h=be("debugserializer"),dT=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}_h&&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){_h&&console.log("invalid type");return}let n=e.name??e.constructor?.name;if(!n){_h&&console.log("invalid name",n);return}let i=this.getSerializer(n);if(i!==void 0)return _h&&console.log("FOUND "+n,e.name,e.constructor.name,i,this.typeMap),i;let s=Object.getPrototypeOf(e);if(!(s.prototype||s.constructor)){_h&&console.warn("No prototype for "+n,e,e.name,e.prototype,e.constructor.name);return}let a=s.prototype??s.constructor;if(a!==e){let l=this.getSerializerForConstructor(a,++t);if(l){_h&&console.log("FOUND "+a.constructor.name,a.name,a,l);let c=a.name??a.constructor.name;c==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,l):this.register(c,l)}return l}}},Yy=new dT,$o=class{constructor(e){if(Array.isArray(e))for(let t of e)Yy.register(t.name,this);else Yy.register(e.name,this)}},Jd=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function pT(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let n={};for(let i in t){let s=o[i];if(s!=null&&typeof s=="object"){let r=Yy.getSerializerForConstructor(s);if(r){n[i]=r.onSerialize(s,e);continue}}n[i]=s}return n.name=o.constructor.name,typeof o.guid=="string"&&(n.guid=o.guid),n}var qy=[];function IO(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return IO(t,e)}function eg(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let s=o.onBeforeDeserialize(e,t);if(typeof s=="boolean")return s}let n=IO(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),n)for(let s in n){let r=n[s],a=e[s];if(t.path=s,r===null)o[s]=a;else{let l=function(c){let u=c.type;return u?fT(a,u,t,void 0,o[s]):fT(a,c,t,void 0,o[s])};var i=l;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(s,a,t)===!0)continue;if(Array.isArray(r))for(let c=0;c<r.length;c++){let h=r[c],u=l(h);if(u!==void 0||c===r.length-1){o[s]=u;break}}else o[s]=l(r);qy.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(s,a,t)}}x5(o,e)}return o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}function x5(o,e){for(let n of Object.keys(e)){let i=e[n];if(typeof i=="object"&&i!==null&&i!==void 0){let s=o[n];if(!s){_h&&console.log(n,"is undefined on",o);continue}for(let r of Object.keys(i))s[r]===void 0&&t(i[r])&&!t(s)&&(s[r]=i[r])}}function t(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}}function fT(o,e,t,n,i){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,i),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(!s&&i instanceof r)return i;if(i&&typeof i=="object"&&PO(i)){if(i.__concreteInstance)return i.__concreteInstance;let h=i;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&eg(h,o,t),i&&r!==void 0)try{let u=new r;Nn&&console.log("Create concrete instance for persistent asset",i,"instance:",u),tg(u,i),i.__concreteInstance=u,i=u}catch(u){console.error("Error creating instance or creating values on instance",u,i,r)}return i}if(n||(n={serializer:Yy.getSerializerForConstructor(r)}),Array.isArray(o)){let h=[];for(let u=0;u<o.length;u++){let d=o[u],f=fT(d,e,t,n,d);h.push(f)}return h}let a=n.serializer;if(a)return a.onDeserialize(o,t);let l;o&&(o.isMaterial||o.isTexture||o.isObject3D)?l=o:l=new r(...w5(o));let c=l;return c.$serializedTypes&&eg(c,o,t),l}function w5(o){if(qy.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))qy.push(o[e]);return qy}function tg(o,e){if(e==null||o==null)return;let t=!1;for(let n of Object.keys(e)){let i=E5(o,n);t&&i===void 0||(!i||i.writable===!0||i?.set!==void 0)&&(o[n]=e[n])}}function E5(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var yl=be("debuganimatorcontroller"),mT=be("debugrootmotion"),Cr=class{Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let r=this.model.layers[t].stateMachine;for(let a of r.states)if(a.name===e||a.hash===e){yl&&console.log("transition to ",a),this.transitionTo(a,i,n);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??!1}SetFloat(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetInteger(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetTrigger(e){yl&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e)return n;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new Ho(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Hm(this.model,(n,i,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||s?.constructor?.name==="AnimationAction"||s.tracks!==void 0));return console.assert(e!==this.model),new Cr(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,yl&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],n=t.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{let i=n.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(yl&&console.debug("REMOVE",t.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,n=t.motion.action,i=0;for(let r of t.transitions){if(++i,!r.hasExitTime&&r.conditions.length<=0)continue;let a=!0;for(let l of r.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(!!a){yl&&a&&console.log("All conditions are met",r.conditions,n);for(let l of r.conditions){let c=this.model.parameters.find(h=>h.name===l.parameter);c?.type===9&&(c.value=!1)}if(n){let l=t.motion.clip.duration,c=l<=0?1:n.time/l;if(!r.hasExitTime||c>=r.exitTime&&n.time>=n.getClip().duration){n.clampWhenFinished=!0,yl&&(console.log("transition to "+r.destinationState,r),console.log(n.time,r.exitTime)),this.transitionTo(r.destinationState,r.duration,r.offset);return}}else{this.transitionTo(r.destinationState,r.duration,r.offset);return}break}}let s=!1;if(t.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&t&&!e&&n&&this.animator&&t.behaviours){let r=n?.getClip().duration,a=n.time/r,l=new Yd(this._activeState,a,r,this._speed);for(let c of t.behaviours)c.instance&&c.instance.onStateUpdate?.call(c.instance,this.animator,l,0)}}transitionTo(e,t,n){if(!this.animator)return;let i=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[i].stateMachine.defaultState),e=this.model.layers[i].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let s=this._activeState===e;if(s){let c=e.motion;!c.action_loopback&&c.clip&&(this._mixer.uncacheAction(c.clip,this.animator.gameObject),c.action_loopback=this.createAction(c.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let c=this._activeState?.motion.clip.duration,h=this._activeState.motion.action.time/c,u=new Yd(this._activeState,h,c,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateExit?.call(d.instance,this.animator,u,i)}let r=this._activeState?.motion.action;r&&r.fadeOut(t),s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);let a=this._activeState;this._activeState=e;let l=e.motion?.action;if(l){n=Math.max(0,Math.min(1,n)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,l.enabled=!0;let c=e.motion.clip.duration;if(l.time=n*c,l.clampWhenFinished=!0,l.setLoop(Ld,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let h=new Yd(e,n,c,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,h,i)}}else console.warn("No action",e.motion,this);yl&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new gT(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let n=t.stateMachine;for(let i=0;i<n.states.length;i++){let s=n.states[i];if(s.motion||(s.motion=RO(s.name)),this.animator&&s.motion.clips){let r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);s.motion.clip=r?.clip}if(!s.motion.clip){let r=new br;s.motion.clip=r}if(s.motion?.clip){let r=s.motion.clip,a=this.createAction(r);s.motion.action=a}if(s.behaviours&&Array.isArray(s.behaviours))for(let r of s.behaviours){if(!r?.typeName)continue;let a=pe.get(r.typeName),l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,tg(l,r.properties),r.instance=l),yl&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let n=0;n<t.states.length;n++){let i=t.states[n];i?.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}rootMotionHandler},Zy=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let n=e,i=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;let r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},Mn=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new O;rotationChange=new Oe;constructor(e,t,n,i,s){if(this.context=e,this.root=t,this.clip=n,Mn.firstKeyframeRotation[n.uuid]||(Mn.firstKeyframeRotation[n.uuid]=new Oe),s){let r=s.values;Mn.firstKeyframeRotation[n.uuid].set(r[0],r[1],r[2],r[3])}Mn.spaceRotation[n.uuid]||(Mn.spaceRotation[n.uuid]=new Oe),Mn.effectiveSpaceRotation[n.uuid]||(Mn.effectiveSpaceRotation[n.uuid]=new Oe),Mn.clipOffsetRotation[n.uuid]=new Oe,s&&Mn.clipOffsetRotation[n.uuid].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(n,i),this.handleRotation(n,s)}onStart(e){if(e.getClip()!==this.clip)return;let t=Mn.lastObjRotation[this.root.uuid];Mn.spaceRotation[this.clip.uuid].copy(t);{let n=new Lt().setFromQuaternion(t);console.log("START",this.clip.name,gt.toDegrees(n.y))}}getClipRotationOffset(){return Mn.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let n=this.root;mT&&n.add(new xr),Mn.lastObjPosition[n.uuid]||(Mn.lastObjPosition[n.uuid]=new O);let i=new O,s=new O,r=0;this.positionWrapper=new Zy(t,(a,l)=>{let c=this.action.getEffectiveWeight();if(mT&&n.position.length()>8&&n.position.set(0,n.position.y,0),a>r){i.set(l[0],l[1],l[2]),i.sub(s),i.multiplyScalar(c),i.applyQuaternion(this.getClipRotationOffset());let h=this.clip.uuid;i.applyQuaternion(Mn.spaceRotation[h]),this.positionChange.copy(i)}return s.fromArray(l),r=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(mT){let a=t.values,l=new Lt().setFromQuaternion(new Oe(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",gt.toDegrees(l.y));let c=t.values.length-4,h=new Oe().set(a[c],a[c+1],a[c+2],a[c+3]),u=new Lt().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",gt.toDegrees(u.y))}let n=this.root;Mn.lastObjRotation[n.uuid]||(Mn.lastObjRotation[n.uuid]=new Oe);let i=0,s=new Oe,r=new Oe;this.rotationWrapper=new Zy(t,(a,l)=>(a>i&&(r.set(l[0],l[1],l[2],l[3]),s.invert(),r.multiply(s),this.rotationChange.copy(r)),s.fromArray(l),i=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Mn.identityQuaternion,1-e)}},Tr=Mn;Se(Tr,"lastObjPosition",{}),Se(Tr,"lastObjRotation",{}),Se(Tr,"firstKeyframeRotation",{}),Se(Tr,"spaceRotation",{}),Se(Tr,"effectiveSpaceRotation",{}),Se(Tr,"clipOffsetRotation",{}),Se(Tr,"identityQuaternion",new Oe);var gT=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,n){this.root=t;let i="";t&&"name"in t&&(i=t.name);let s=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),a=new Tr(this.controller.context,t,n,s,r);this.handler.push(a);let l=e.clipAction(n);return a.action=l,l}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new O;summedRotation=new Oe;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Tr.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let n=e.tracks;for(let i of n)if(i.name.endsWith(t))return i;return null}};var S5=be("debuganimator"),ws=class extends ce{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Cr?this._animatorController=e:this._animatorController=new Cr(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){this.runtimeAnimatorController?.Play(e,t,n,i)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=gt.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=gt.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}S5&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};ne([te()],ws.prototype,"applyRootMotion",2),ne([te()],ws.prototype,"hasRootMotion",2),ne([te()],ws.prototype,"keepAnimatorControllerStateOnDisable",2),ne([te()],ws.prototype,"runtimeAnimatorController",1);var Rr=class extends ce{playAutomatically=!0;randomStartTime=!0;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&Qt.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let n=e;if(typeof e=="number"){if(e>=this.animations.length)return;n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(s=>s.name===e));if(!n){console.error("Could not find clip",e);return}for(let s of this.actions)if(s.getClip()===n)return this.internalOnPlay(s,t);let i=this.mixer.clipAction(n);return this.actions.push(i),this.internalOnPlay(i,t)}internalOnPlay(e,t){var n=this.currentAction;if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let r=this.tryFindHandle(e);if(r)return r.getPromise()}let i=t?.exclusive??!0;t?.fadeDuration?(i&&n?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):i&&n?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Y0:Ld),e.play();let s=new vT(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Ho(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};ne([te()],Rr.prototype,"playAutomatically",2),ne([te()],Rr.prototype,"randomStartTime",2);var vT=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,n,i){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=i,this._options=n}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as FF}from"three/examples/jsm/loaders/GLTFLoader.js";var _l=class extends ce{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new O}update(){if(!this.from||!this.to)return;let e=st(this.from).clone(),t=st(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),kt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(st(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};ne([te($)],_l.prototype,"from",2),ne([te($)],_l.prototype,"to",2);var $r=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};ne([te()],$r.prototype,"time",2),ne([te()],$r.prototype,"value",2),ne([te()],$r.prototype,"inTangent",2),ne([te()],$r.prototype,"inWeight",2),ne([te()],$r.prototype,"outTangent",2),ne([te()],$r.prototype,"outWeight",2),ne([te()],$r.prototype,"weightedMode",2);var bh=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return gt.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};ne([te($r)],bh.prototype,"keys",2);import{PositionalAudioHelper as M5}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Jy=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var es=be("debugaudio");var Jn=class extends ce{static get userInteractionRegistered(){return Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction()),Jn._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Jn._didCallBeginWaitForUserInteraction||(Jn._didCallBeginWaitForUserInteraction=!0,Jn._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!Jn._userInteractionRegistered){Jn._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(es&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Jn._userInteractionRegistered){let e=$.getComponent(this.context.mainCamera,Ar)??$.findObjectOfType(Ar,this.context);e?.listener&&(this.sound=new Im(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new rl,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Jn._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Jn._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Jn._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){es&&console.log("audio buffer loaded"),Jn.registerWaitForAllowAudio(()=>{es&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),es&&console.log(this.name,this.shouldPlay,Jn.userInteractionRegistered,this),this.shouldPlay&&Jn._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(es&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?es&&!this.helper&&(this.helper=new M5(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(es&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new rl),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){es&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,es&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,es&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){es&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,es&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,es&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},$t=Jn;Se($t,"_didCallBeginWaitForUserInteraction",!1),Se($t,"callbacks",[]),Se($t,"_userInteractionRegistered",!1),ne([te()],$t.prototype,"clip",2),ne([te()],$t.prototype,"playOnAwake",2),ne([te()],$t.prototype,"loop",1),ne([te()],$t.prototype,"spatialBlend",1),ne([te()],$t.prototype,"minDistance",1),ne([te()],$t.prototype,"maxDistance",1),ne([te()],$t.prototype,"volume",1),ne([te()],$t.prototype,"rollOffMode",2);var Ar=class extends ce{get listener(){return this._listener==null&&(this._listener=new th),this._listener}_listener=null;awake(){$t.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=$.getComponentInParent(this.gameObject,Bt);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as R5}from"three/examples/jsm/loaders/GLTFLoader";var HO=Du(UO(),1),Qy=class{success;filename;hash;size;url;constructor(e,t,n,i){this.success=e,this.filename=t,this.hash=n,this.size=i}};async function zO(o,e){let t=await o.arrayBuffer(),n=VO(t),i=o.name.split(".").pop(),s=n+"."+i,r=o.name.split(".").shift();console.assert(r!==void 0);let a={alias:r,filename:s},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",n),new Qy(!0,s,n,o.size);console.log("begin uploading file",r,o.size);let h=new FormData;h.append("file",o);let u={};u.filesize=o.size,r&&(u.alias=r);let f=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===n,"hash sum did not match","received:",f.hash_sum,"expected:",n),f.success&&console.log("successfully uploaded",n,f.id);let g=new Qy(f.success,s,n,o.size);return g.url=e,g}function VO(o){return(0,HO.default)(new Uint8Array(o))}async function $y(o,e,t,n,i=!1){try{let s=await fetch(n+"/download/file",{method:"POST",body:o});if(s.status!==200)return console.error("download failed",s),null;let r=await s.blob(),a=await r.arrayBuffer();i||console.assert(r.size===t,"size mismatch","expected:",t,"got:",r.size);let l=VO(a);return i||console.assert(l===e,"hash mismatch, downloaded file is invalid"),r.arrayBuffer()}catch(s){console.error(s)}return null}async function GO(o,e){let t=await fetch(o),n=t.body?.getReader(),i=t.headers.get("Content-Length"),s=i?parseInt(i):0;if(!n)return null;let r=0,a=[];for(;;){let{done:h,value:u}=await n.read();if(u&&(a.push(u),r+=u.length,e.call(null,new ProgressEvent("progress",{loaded:r,total:s}))),h)break}let l=new Uint8Array(r),c=0;for(let h of a)l.set(h,c),c+=h.length;return l}var ng=be("debugavatar"),xh=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(s=>s.layers.set(2))}},bl=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let s=new hn;n=$.instantiate(cl(t,e.scene),s)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.isValid?(ng&&console.log("[Custom Avatar] valid config",t,ng?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,ng?i:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ng&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),s=null;if(i.ok){let a=await i.blob();a&&(s=await a.arrayBuffer())}return!s&&(s=await $y(t,t,0,"no url here go away",!0),!s)?null:(await Qd(e,s,null,0))?.scene??null}let n=new R5;return gh(n,e),new Promise((i,s)=>{let r=this.avatarRegistryUrl+"/"+t;n.load(r,async a=>{await Ky(e,r,a),i(a.scene)},a=>{ng&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,["head"]),s=this.findAvatarPart(n,["left","hand"]),r=this.findAvatarPart(n,["right","hand"]);if(!i){i=t;let l=new O;new On().setFromObject(i).getSize(l);let c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&i.scale.multiplyScalar(1/c*.3)}return new xh(t,i,s,r)}findAvatarPart(e,t){let n=e.name.toLowerCase(),i=!0;for(let s of t){if(!i)break;n.indexOf(s)===-1&&(i=!1)}if(i)return e;if(e.children)for(let s of e.children){let r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};var Ko=class extends ce{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Qr)return;this._axes||(this._axes=new xr(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};ne([te()],Ko.prototype,"length",2),ne([te()],Ko.prototype,"depthTest",2),ne([te()],Ko.prototype,"isGizmo",2);var $d=class extends ce{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=st(this.to).clone(),t=st(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let s=t.clone();s.add(e),s.multiplyScalar(.5);let r=st(this.hint).clone();r.sub(s);let a=new O;a.crossVectors(r,i),a.crossVectors(i,a),a.normalize();let l=n*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),u=a.clone();u.multiplyScalar(h),u.add(s),kt(this.gameObject,u);let d=s.clone();d.sub(a),this.gameObject.lookAt(d)}};var A5=new ri(1,1,1);function e_(o=null){let e=new q(o??14540253),t=new bd(A5);return new Qi(t,new Fn({color:e}))}var I5=be("gizmos"),t_=class extends ce{box=null;testBox=new On;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new On),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=st(e,t_._position),n=JL(e,t_._size);this.testBox.setFromCenterAndSize(t,n)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new On),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new O(0,0,0),new O(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!I5&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=e_(e),this.gameObject.add(this._helper)}}},ts=t_;Se(ts,"_position",new O),Se(ts,"_size",new O(.01,.01,.01));function Kd(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?gi:ps,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?gi:ps,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let n of o.children)Kd(n,e)}function ef(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let n=Proxy.revocable(o[e],{set(r,a,l,c){let h=r[a],u=Reflect.set(r,a,l,c);return t(l,h),u}}),i=n.revoke,s=o[e];return n.revoke=()=>{o[e]=s,i()},o[e]=n.proxy,n}function jO(o,e,t=3){let n=o.__scheduledActions;n||(n=o.__scheduledActions={});let i=e.name;n[t]||(n[t]={});let s=n[t];if(s[i])return;function*a(){e?.call(o),s[i]=null}let l=o.startCoroutine(a(),t);s[i]=l}var tf=class extends ce{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?qe.KINEMATIC:qe.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new O,this._smoothedVelocity=new O,this.lastWorldPosition=st(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=ef(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 Ay;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new H(e.x,e.y,e.z),t?new H(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?tf.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):tf.tempPosition.set(0,0,0)}setVelocity(e,t,n){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=n/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,n){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=n/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let n=this.worldQuaternion;if(this.body.quaternion.set(n.x,n.y,n.z,n.w),e){tf.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(tf.copyVector3,this.context.time.deltaTime/.1);let i=this._smoothedVelocity;this.body.velocity.x=i.x,this.body.velocity.y=i.y,this.body.velocity.z=i.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=st(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},Xt=tf;Se(Xt,"tempPosition",new O),Se(Xt,"copyVector3",new O),ne([te()],Xt.prototype,"mass",2),ne([te()],Xt.prototype,"isKinematic",1),ne([te()],Xt.prototype,"drag",2),ne([te()],Xt.prototype,"angularDrag",2),ne([te()],Xt.prototype,"detectCollision",2),ne([te()],Xt.prototype,"sleepThreshold",2);var Kr=class extends ce{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xt))}onDisable(){this._shape}};ne([te(Xt)],Kr.prototype,"attachedRigidbody",2),ne([te()],Kr.prototype,"isTrigger",2);var xl=class extends Kr{radius=.5;center=new O(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};ne([te()],xl.prototype,"radius",2),ne([te(O)],xl.prototype,"center",2);var wl=class extends Kr{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};ne([te(O)],wl.prototype,"size",2),ne([te(O)],wl.prototype,"center",2);var nf=class{};var qs=class extends ce{canGrab=!0;onPointerClick(e){}},Ys=class extends ce{isUsed=!0;usedBy=null};var wh=class extends ts{},sf=class extends ce{deleteBoxes=[];awake(){this.deleteBoxes=$.findObjectsOfType(wh,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&($.getComponentInParent(this.gameObject,Ys)||Bd(this.gameObject,this.context.connection))}}};var Eh=class extends ce{visibleOn;onEnable(){this.apply()}apply(){this.test()||$.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:L5()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};ne([te()],Eh.prototype,"visibleOn",2);var n_;function L5(){if(n_===!0||n_===!1)return n_;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),n_=o,o}var Tn=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,n,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var rf=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Tn).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Tn).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Tn).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Zs=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Zs).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new rf).__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 El=be("debugsync"),of="STRS";qd(of,Zs.getRootAsSyncedTransformModel);var eo=new _s;function bT(o,e,t=!0){eo.clear();let n=eo.createString(o);Zs.startSyncedTransformModel(eo),Zs.addGuid(eo,n),Zs.addFast(eo,t);let i=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;Zs.addTransform(eo,rf.createTransform(eo,i.x,i.y,i.z,s.x,s.y,s.z,r.x,r.y,r.z));let a=Zs.endSyncedTransformModel(eo);return eo.finish(a,of),eo.asUint8Array()}var xi=class extends ce{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(){El&&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(){El&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new O,this._targetRotation=new Oe,this.lastWorldPos=new O,this.lastWorldRotation=new Oe,this.rb=$.getComponentInChildren(this.gameObject,Xt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new vl(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(of,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&i2(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(of,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Lt;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){El&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){Qt.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&QL(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){El&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let s=e.distanceTo(this.lastWorldPos),r=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(s>a||r>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(El&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qt.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let r=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){let l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&Qt.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(El&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new O(0,0,0))>1e3&&(El&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){El&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let s=bT(this.guid,this,!!i);this.context.connection.sendBinary(s)}}};var s_=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var l=document.createElement("div");l.style.display="none",document.body.appendChild(l);var c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("width",38),c.setAttribute("height",38),c.style.position="absolute",c.style.right="20px",c.style.top="20px",c.addEventListener("click",function(){u.end()}),l.appendChild(c);var h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),h.setAttribute("stroke","#fff"),h.setAttribute("stroke-width",2),c.appendChild(h),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:l}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function d(g){g.addEventListener("end",f),await e.xr.setSession(g),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=g}function f(){u.removeEventListener("end",f),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(d):u.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="AR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(l){l?i():r()}).catch(r),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}};var r_=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let l=null;async function c(u){u.addEventListener("end",h),await e.xr.setSession(u),n.textContent="EXIT VR",l=u}function h(){l.removeEventListener("end",h),n.textContent="ENTER VR",l=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(l===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(c)}else l.end()}}function s(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(){s(),n.textContent="VR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?i():r(),r_.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),r_.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},af=r_;Se(af,"xrSessionIsGranted",!1);af.registerSessionGrantedListener();var XO=Du(tT(),1);var lf="noVoip",ns=be("debugvoip"),D5=be("voip");var xT=class{id;constructor(e){this.id=e}};var wT=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){ns&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await Vi.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ns&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ns&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ns&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ns&&console.log("call closed",e)}},ET=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,$t.userInteractionRegistered||ns&&console.log("Incoming call, waiting for user interaction before opening audio"),$t.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ns&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new th;this.audio=new ol(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let s of i)if(s.label==="Speakerphone"){n.sinkId=s.deviceId;break}}}),ns&&console.log("call is setup, you should hear something now"),this.analyzer=new Lm(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Vi=class extends ce{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(be(lf)){console.log("VOIP is disabled by url parameter: "+lf);return}if(this.requireParam&&!D5){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new XO.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new wT(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];ns&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){ns&&console.log("Peer connection established and received id"),this.model=new xT(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ns&&console.log("CONNECTION",t),t.on("data",function(n){ns&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,s=this.currentIncomingCalls[n];if(s&&s.close(),ns&&console.log("received call"),await Vi.HasMicrophonePermissions()){let r=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(r)}else e.answer(null);this.currentIncomingCalls[n]=new ET(this,this.gameObject,e),e.on("stream",r=>{ns&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(r)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var cf=be("debugflags");var ST=class{Mask=17;Has(e){let t=this.Mask&e;return cf&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Cn.Apply()}Enable(e){this.Mask|=e,Cn.Apply()}Disable(e){this.Mask&=~e,Cn.Apply()}Toggle(e){this.Mask^=e,Cn.Apply()}EnableAll(){this.Mask=-1,Cn.Apply()}DisableAll(){this.Mask=0,Cn.Apply()}},Es=ST;Se(Es,"Global",new ST);var to=class extends ce{static Apply(){for(let e of this.registry)e.UpdateVisible(Es.Global)}awake(){to.registry.push(this)}onEnable(){to.firstApply||(to.firstApply=!0,to.Apply())}onDestroy(){let e=to.registry.indexOf(this);e>=0&&to.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),cf&&console.log(n),to.buffer.Mask=n,e=to.buffer);let i=e;if(i?(cf&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(cf&&console.log("use global mask"),Es.Global.Has(this.visibleIn)),t!==void 0)if(t)cf&&console.trace("is visible",this.name,this.gameObject.uuid),$.setActive(this.gameObject,!0);else{if(cf&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Cn=to;Se(Cn,"registry",[]),Se(Cn,"firstApply"),Se(Cn,"buffer",new Es);import{XRControllerModelFactory as k5}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as F5}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as B5}from"three/examples/jsm/webxr/OculusHandPointerModel.js";var Sl=be("debugavatar"),ea=class extends ce{static onAvatarMarkerCreated(e){return ea._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ea._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ea.instances.push(this),Sl&&console.log(this);for(let e of ea._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ea.instances.splice(ea.instances.indexOf(this),1);for(let e of ea._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):$.setActive(this.avatar,e))}},Kt=ea;Se(Kt,"instances",[]),Se(Kt,"_onNewAvatarMarkerAdded",[]),Se(Kt,"_onAvatarMarkerDestroyed",[]);var ig=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new O(1,1,1);handLeftScale=new O(1,1,1);handRightScale=new O(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new De;_handLeftTarget=new De;_handRightTarget=new De;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){this._canInterpolate=!0;let n=this.isLocalAvatar?this.head:this._headTarget;if(n.position.set(e.position.x,e.position.y,e.position.z),n.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.headScale),this.handLeft){let i=this.isLocalAvatar?this.handLeft:this._handLeftTarget;i.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),i.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),i.quaternion.multiply(ig.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handLeftScale)}if(this.handRight){let i=this.isLocalAvatar?this.handRight:this._handRightTarget;i.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),i.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),i.quaternion.multiply(ig.invertRotation),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.handRightScale)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){Sl&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&vn.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&$.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Sl&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&vn.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;$.setActive(i,!1),e=$.instantiate(i),$.setActive(e,!0)}Sl&&console.log(e);let n=await ig.loader.getOrCreateNewAvatarInstance(this.context,e);if(Sl&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=$.addNewComponent(this.root,Kt),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&vn.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...$.getComponentsInChildren(this.root,Cn)),this.flags.length<=0&&this.head){let i=$.addNewComponent(this.head,Cn);i.visibleIn=20,this.flags.push(i),Sl&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return Sl&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Sl&&console.warn("build avatar failed"),!1}},Js=ig;Se(Js,"loader",new bl),Se(Js,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI));var vn=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??bt.Current?.time.time;return}}}};Se(vn,"Pois",[]),Se(vn,"LastChangeTime",0);var MT=class{guid;position=new O},ta=class extends ce{set controlledTarget(e){this.target=e;let t=pe.get("MoveRandom");if(t&&this.target){let n=$.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new MT;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=$.getComponentInParent(this.gameObject,Kt),this.avatar){let e=$.getComponentInParent(this.gameObject,Kt);this._model=new vl(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&kt(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(vn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=vn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=st(this._currentTargetObject);kt(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=vn.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};var Sh=class extends ce{},Qn=class extends ce{static CreateRaycastLine(){let e=new Ji(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Ni(.5,22,22),t=new Jt({color:this.raycastColor}),n=new _t(e,t);return n.visible=!1,n.layers.set(1),n}static Create(e,t,n,i){let s=n?$.addNewComponent(n,Qn,!1):new Qn;s.webXR=e,s.index=t,s.type=i;let r=e.context;return s.controller=r.renderer.xr.getController(t),s.controllerGrip=r.renderer.xr.getControllerGrip(t),s.controllerModel=this.Factory.createControllerModel(s.controller),s.controllerGrip.add(s.controllerModel),s.hand=r.renderer.xr.getHand(t),s.hand.add(new F5(s.hand)),s.hand.traverse(a=>a.layers.set(2)),s.handPointerModel=new B5(s.hand,s.controller),s.controller.addEventListener("connected",a=>{s.setControllerLayers(s.controllerModel,2),s.setControllerLayers(s.controllerGrip,2),setTimeout(()=>{s.setControllerLayers(s.controllerGrip,2)},1e3)}),s.hand.addEventListener("connected",a=>{if(a.data.hand){e.Rig&&e.Rig.add(s.hand),s.type=0,s.handPointerModel.traverse(h=>h.layers.set(2)),s.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let c=s.hand.joints;if(c)for(let h of Object.keys(c)){let u=c[h];u.parent||s.hand.add(u)}}}),s}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Oe),cn(e).multiply(this._wristQuaternion.setFromEuler(new Lt(-Math.PI/4,0,0)))):null}movementVector=new O;worldRot=new Oe;joystick=new _e;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Qn.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Qn.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Oe;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Qn.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(cn(this.controller),this.useSmoothing?t:1);let n=st(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,kt(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let r=this.getWristQuaternion();r&&this.rayRotation.copy(r)}Bn(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Bn(this.raycastLine,this.rayRotation),kt(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Qn.MovementSpeedFactor,s=2,r=gt.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,l=Math.pow(this.joystick.x,s);l*=a,l*=r;let c=this.joystick.y>0?1:-1,h=Math.pow(this.joystick.y,s);h*=c,l*=r,t.getWorldQuaternion(this.worldRot),this.movementVector.set(l,0,h),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(i*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,d=Math.abs(u);if(d<.4)this.didRotate=!1;else if(d>.5&&!this.didRotate){let f=u>0?-1:1;t.rotateY(gt.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5,s=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,r=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let l=t[a];if(a===4)if(l.pressed&&!this.didChangeScale){this.didChangeScale=!0;let c=this.webXR.Rig;if(c)if(s){s=!1,c.scale.set(1,1,1),r=1,Qn.MovementSpeedFactor=1;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance&&(h.far=Qn.PreviousCameraFarDistance)}else{s=!0,i=!0,r=.1,Qn.MovementSpeedFactor=r*2;let h=this.context.mainCamera;Qn.PreviousCameraFarDistance=h.far,h.far/=r}}else l.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let l=a[0];if(s||this.isValidTeleportTarget(l.object)){let c=l.point;kt(e,c)}}}}else n<.1&&(this.didTeleport=!1);r!==null&&(e.scale.set(r,r,r),e.updateMatrixWorld())}isValidTeleportTarget(e){return $.getComponentInParent(e,Sh)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Qn.raycastColor:i.color=Qn.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=gt.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),e&&e.length>0)for(let n of e){let i=n.object;if(!this.testIsVisible(i)){console.log("not visible");continue}this.lastSelectStartObject=i;let s={selected:i,grab:i},r=Qn.eventSubs["select-start"];if(r&&r.length>0)for(let a of r)a(this,s);s.grab!==i&&console.log("Grabbed object changed","original",i,"new",s.grab),s.grab&&(this.grabbed=is.TryTake(this,s.grab,n,t));break}else{let n=Qn.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let s of n)s(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Qn.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?$.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new vr;return e.origin.copy(st(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=st(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Zn;return e.layerMask=new Fi,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},Vt=Qn;Se(Vt,"Factory",new k5),Se(Vt,"raycastColor",new q(.9,.3,.3)),Se(Vt,"raycastNoHitColor",new q(.6,.6,.6)),Se(Vt,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,0,-1)])),Se(Vt,"handModels",{}),Se(Vt,"eventSubs",{}),Se(Vt,"PreviousCameraFarDistance"),Se(Vt,"MovementSpeedFactor",1);var Gi=class{static AddEventListener(e,t){return Gi.Events[e]||(Gi.Events[e]=[]),Gi.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Gi.Events[e])return;let n=Gi.Events[e].indexOf(t);n>=0&&Gi.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let s=$.getComponentInParent(t,qs);if(!s)return console.warn("Prevented taking object that is not interactable",t),null;let r=t,a=$.getComponentInParent(t,xi);a&&(a.requestOwnership(),r=a.gameObject);for(let c of this.Current)if(c.selected===r)return c.controller===e||(c.free(),c.Take(e,r,t,a,s,n,i)),c;let l=new Gi;return l.Take(e,r,t,a,s,n,i),l}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,s,r,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let l={controller:e,take:t,hit:n,sync:i,interactable:s};Gi.Events.WillTake?.forEach(f=>f(this,l));let c=n;c?.material&&(this.originalMaterial=c.material,Array.isArray(c.material)||(c.material=c.material.clone(),c.material&&c.material.emissive&&(c.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=c,this.controller=e,this.interactable=s,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=$.addNewComponent(this.selected,Ys),this.rigidbodies=$.getComponentsInChildren(this.selected,Xt),st(this.positionSource,this.lastControllerWorldPos);let h=()=>a?this.lastControllerWorldPos.clone():r.point.clone();this.grabDistance=h().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(h());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();cn(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let d=this.controller.webXR.Rig;return d&&this.rigPositionLastFrame.copy(st(d)),vn.Add(e.context,this.selected),Gi.Register(this),this.sync&&(this.sync.fastMode=!0),Gi.Events.DidTake?.forEach(f=>f(this,l)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Gi.Events.WillFree?.forEach(i=>i(this,e)),vn.Remove(this.controller.context,this.selected),Gi.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Gi.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new O;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new O;localQuaternionToGrab=new Oe(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new O;controllerWorldPos=new O;lastControllerWorldPos=new O;controllerPosDelta=new O;totalChangeAlongDirection=0;rigPositionLastFrame=new O;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),st(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=st(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new O),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Bn(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(st(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),kt(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});Qt.markDirty(this.selected,!0)}}},is=Gi;Se(is,"Events",{}),Se(is,"Current",[]);var Qs=class extends ce{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,n){if(n&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new it().fromArray(n.transform.matrix).invert(),e){if(this.invertForward){let i=new it().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),Qt.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new it().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};ne([te()],Qs.prototype,"invertForward",2),ne([te()],Qs.prototype,"arScale",1);var Ml=class extends ce{awake(){}};var Mh=be("debugaddressables"),o_=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},Wi=class{static getOrCreate(e,t,n){let i=ey(e,t);Mh&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",i);let s=n.addressables,r=s.findAssetReference(i);if(r)return r;let a=new Wi(i);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,a2(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&&(Mh&&console.log("Unload",this.asset),this.asset.scene?$.destroy(this.asset.scene):$.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,Mh&&console.log("Preload",this.uri);let e=await GO(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=bt.Current;this._rawBinary?(this._loading=Qd(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Mh&&console.log("Load async",this.uri),this._loading=Th(t,this.uri,null,!0,i=>{this.raiseProgressEvent(i)}));let n=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(n),this._loading=void 0,n)return Go(t),n.scene!==void 0&&(this.asset=n),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,n){let i=bt.Current;if(e||(e=i.scene),this.mustLoad&&await this.loadAssetAsync(),Mh&&console.log("Instantiate",this.uri,"parent:",e),this.asset){Mh&&console.log("Add to scene",this.asset);let s=e instanceof hn?e:null;if(s||(s=new hn),typeof e=="object"&&(e instanceof De?s.parent=e:Object.assign(s,e)),t){s.context=i;let r=this.asset;r.guid=this.uri;let a=uy(r,s,void 0,n);if(a)return a}else{let r=$.instantiate(this.asset,s);if(r)return r}}else Mh&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},TT=class extends $o{constructor(){super([Wi])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?Wi.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new TT;var no=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,s){return e.prep(4,16),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Un=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Un).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Tn).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new no).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var YO=be("debugxr"),sg=be("debugavatar");var RT="VRUS";qd(RT,Un.getRootAsVrUserStateBuffer);function CT(){return new Date().getTime()}function N5(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return bi.create(e,t)}var rg=class{guid;time;avatarId;position=new O;rotation=new ot;scale=1;posLeftHand=new O;posRightHand=new O;rotLeftHand=new Oe;rotRightHand=new Oe;constructor(e){this.guid=e}update(e,t,n,i,s){this.time=CT(),this.avatarId=s,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let r=rg.quat0,a=rg.quat1;r.set(n.x,n.y,n.z,n.w),r=r.multiplyQuaternions(r,rg.invertRotation),e&&(e.getWorldQuaternion(a),r.multiplyQuaternions(a,r)),this.rotation.set(r.x,r.y,r.z,r.w),this.scale=e.scale.x;let l=i.LeftController?.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand));let c=i.RightController?.controllerGrip;if(c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let h=i.LeftController.wrist;h&&(h.getWorldPosition(this.posLeftHand),h.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let h=i.RightController.wrist;h&&(h.getWorldPosition(this.posRightHand),h.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);Un.startVrUserStateBuffer(e),Un.addGuid(e,n),Un.addTime(e,N5(this.time)),Un.addAvatarId(e,i),Un.addPosition(e,Tn.createVec3(e,this.position.x,this.position.y,this.position.z)),Un.addRotation(e,no.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Un.addScale(e,this.scale),Un.addPosLeftHand(e,Tn.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Un.addPosRightHand(e,Tn.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Un.addRotLeftHand(e,no.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Un.addRotRightHand(e,no.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let s=Un.endVrUserStateBuffer(e);e.finish(s,RT);let r=e.asUint8Array();t.sendBinary(r)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let s=t.rotation();s&&this.rotation.set(s.x(),s.y(),s.z(),s.w());let r=t.posLeftHand();r&&this.posLeftHand.set(r.x(),r.y(),r.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());let c=t.rotRightHand();c&&this.rotRightHand.set(c.x(),c.y(),c.z(),c.w()),this.scale=t.scale()}},$s=rg;Se($s,"invertRotation",new Oe().setFromAxisAngle(new O(0,1,0),Math.PI)),Se($s,"quat0",new Oe),Se($s,"quat1",new Oe);var na=class extends ce{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent(wt)),this.webXR||(this.webXR=$.findObjectOfType(wt,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=$.findObjectOfType(wt,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=$.findObjectOfType(Vi,this.context)),sg){let e="debug-avatar-"+sg,t=new Js(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof sg=="string"&&sg.length>0)if(await t.setAvatarOverride(sg)){let n=new $s(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=$.getComponent(this.gameObject,wt),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),wt.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),wt.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),wt.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(RT,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new $s("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return YO&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let s=new Js(this.context,e,this.webXR);i=s,this.avatars[e]=s}catch(s){this.avatars[e]=null,console.error(s)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),wt.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),wt.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),wt.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=CT();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=CT();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Js(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){YO&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new _s(1024);onXRSessionUpdate(e){this.xrState??=new $s(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new vl(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,s=t.getViewerPose(n.getReferenceSpace());if(!s)return;let r=s?.transform,a=r.position,l=r.orientation;this.xrState.update(i,a,l,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return be("avatar")}};async function U5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function H5(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var AT=!1,PT=!1;U5().then(o=>AT=o);H5().then(o=>PT=o);var $n=class extends ce{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(AT||PT)}static get IsARSupported(){return AT}static get IsVRSupported(){return PT}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){$n.XRSupported||console.warn("WebXR is not supported on this device");let n=af.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={requiredFeatures:["hit-test"]};n&&(i.domOverlay={root:n},i.optionalFeatures=["dom-overlay"]);let s=s_.createButton(e.context.renderer,i);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),$n.resetButtonStyles(s),(t?.registerClick??!0)&&s.addEventListener("click",e.onClickedARButton.bind(e)),s}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Wi.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!$.findObjectOfType(na,this.context)){let e=$.addNewComponent(this.gameObject,na,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new Tl(this);let e=$n.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=$n.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(n=$n.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{$n.resetButtonStyles(n),$n.resetButtonStyles(t)},1e3)}_transformOrientation=new Oe;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let s of this.controllers)s.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}$n._isInXr===!1&&t&&this.onEnterXR(t,e),$n.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)Vt.Create(this,e,this.gameObject,0);$n.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(st(this.context.mainCamera)),this._originalCameraRotation.copy(cn(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=$.findObjectOfType(Ml,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new zr,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new O;_originalCameraRotation=new Oe;onEnterXR(e,t){console.log("[XR] session begin",e),$n._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let l=new Oe(a.x,a.y,a.z,a.w),c=new Lt().setFromQuaternion(l);this.rig.rotateY(c.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let r=i.getCamera(this.context.mainCamera);for(let a of r.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let s=this._requestedAR?2:4;switch(Es.Global.Set(s),s){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),$n._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),$n.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),kt(this.context.mainCamera,this._originalCameraPosition),Bn(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),Es.Global.Set(17),$n.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!be("mirror")||setTimeout(()=>{if(!$n.IsInWebXR)return;let t=new URL(window.location.href);kd(t.searchParams,lf,1),kd(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{$n.IsInWebXR&&e.end()})})},1e3)}},wt=$n;Se(wt,"_isInXr",!1),Se(wt,"events",new ms),ne([te(Wi)],wt.prototype,"defaultAvatar",2);var hf=class{webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this.webxr=e}arDomOverlay=null;arOverlayElement=null;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let n=0;n<4;n++)Vt.Create(this.webxr,n,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=$.findObjectOfType(Qs,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(i=>{this.hitTestSource=i})}),!this.reticle&&this.sessionRoot&&(this.reticle=new _t(new ko(.07,.09,32).rotateX(-Math.PI/2),new Jt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,hf.tempWebXRObject||(hf.tempWebXRObject=new De),this.context.scene.add(hf.tempWebXRObject),$.addComponent(hf.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),$.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],s=this.webxr.context.renderer.xr.getReferenceSpace();if(s){let r=i.getPose(s);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,r),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&r)){let a=r.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Tl=hf;Se(Tl,"tempWebXRObject");var IT=!1;var uf=class extends qs{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new _e}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||wt.IsInWebXR)return;let t=$.getComponentInParent(e.object,uf);!t||t!==this||(uf.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||uf.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||wt.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(wt.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!wt.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&!this._dragHelper?.hasSelected&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new a_(this.context.mainCamera);else return;if(!e||!e.object)return;let t=$.getComponentInParent(e.object,uf);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let l of this.selectStartEventListener)l(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context);let s=$.getComponentInChildren(n,xi);IT&&console.log("DRAG START",s,n),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=$.addNewComponent(n,Ys),this._draggingRigidbodies.length=0;let r=$.getComponentsInChildren(n,Xt);r&&this._draggingRigidbodies.push(...r);let a=tM();$.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(IT&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let i=$.getComponentInChildren(e.object,xi);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=tM();$.invokeOnChildren(t,n("onDragEnd"))}},Ss=uf;Se(Ss,"_active",null),Se(Ss,"lastHovered");var LT=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new si;_hasGroundPlane=!1;_groundPlane=new si;_groundOffset=new O;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new O;_raycaster=new zo;_cameraPlaneOffset=new O;_intersection=new O;_worldPosition=new O;_inverseMatrix=new it;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Ji(LT.geometry),n=t.material;n.color=new q(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Ni(.5,22,22),s=new Jt({color:n.color}),r=new _t(i,s);r.visible=!1,r.layers.set(2),this._groundMarker=r}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);if(this._selected&&vn.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}vn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=$.getComponentsInChildren(this._selected,Xt),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new O(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,n=68,i=83,s=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),r=this._context.input.getTouchesPressedCount()>=2||s;if(r){let l=this._context.input.getPointerPositionDelta(0);l&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,l.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){IT&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let l=st(this._camera).clone().sub(st(this._selected)).normalize(),c=Math.abs(l.dot(this._groundOffsetVector)),h=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!r&&c>.2&&!h&&this._context.input.getPointerPressedCount()<=1,d=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||d)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,u){this._groundOffsetVector.set(0,1,0);let g=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(g,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);d&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=st(this._selected);i.y=e.y,e=i}if(kt(this._selected,e),kt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=st(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),kt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=st(this._selected),t=new vr(new O(0,.1,0).add(e),new O(0,-1,0)),n=new Zn;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let s=0;s<i.length;s++){let r=i[s];if(!r.face||this.contains(this._selected,r.object))continue;let a=new O(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){Qt.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},a_=LT;Se(a_,"geometry",new ht().setFromPoints([new O(0,0,0),new O(0,-1,0)]));var Cl=class extends ce{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?ys.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let s=i.getAsFile();if(!s)continue;console.log("Register file "+s.name+" to",this.filesBackendUrl,s);let r=await JO(s,this.context,this.filesBackendUrl);r&&this.addObject(e,r)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async s=>{console.log("dropped url",s);try{let r=new URL(s);if(!r)return;let a=await QO(r,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",s)}})}}async addObject(e,t){console.log("Dropped",t);let n=new Zn;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),s=t.scene;if(i&&i.length>0)for(let r of i){s.position.copy(r.point);break}this.gameObject.add(s),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};ne([te()],Cl.prototype,"filesBackendUrl",2),ne([te()],Cl.prototype,"localhost",2);var io=class extends qs{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new O(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Oe(0,0,0,1)}let e=$.getComponentInParent(this.gameObject,Ss);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),Vt.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new hn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=$.instantiateSynced(this.object,t);return console.assert(n!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};ne([te(De)],io.prototype,"parent",2),ne([te(De)],io.prototype,"object",2),ne([te()],io.prototype,"limitCount",2),ne([te()],io.prototype,"limitInterval",2);var so=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},V5=o=>/^[A-Z]*$/.test(o),Ch=class extends Event{args},Rn=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let s of this.key)i&&V5(s)&&(n+="-"),i=!0,n+=s.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Ch(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new so(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var df=class extends ce{};import{FlyControls as G5}from"three/examples/jsm/controls/FlyControls";var ff=class extends ce{_controls=null;onEnable(){let e=$.getComponent(this.gameObject,Bt)?.cam;this._controls=new G5(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};var ia=class extends ce{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Qr||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new ih(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=e_(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}};ne([te()],ia.prototype,"objectBounds",2),ne([te(q)],ia.prototype,"color",2),ne([te()],ia.prototype,"isGizmo",2);import{GLTFExporter as j5}from"three/examples/jsm/exporters/GLTFExporter.js";var og=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new it,a=new Array,l=new Array,c=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,r);let g=new O,p=new Oe,m=new O;r.decompose(g,p,m),a.push(g.x,g.y,g.z),l.push(p.x,p.y,p.z,p.w),c.push(m.x,m.y,m.z)}let h=new Float32Array(a),u=new Float32Array(l),d=new Float32Array(c);s.attributes={TRANSLATION:n.processAccessor(new Mt(h,3)),ROTATION:n.processAccessor(new Mt(u,4)),SCALE:n.processAccessor(new Mt(d,3))},i[this.name]=!0}};var Rl=Nn,c_="$___Export_Components",W5="NEEDLE_components",OT=class{[rh]},DT=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},pf=class{get name(){return W5}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let n=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(i,s)=>{try{this.serializeUserData(i,s),n(i,s)}finally{this.afterSerializeUserData(i,s)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;!n||n.length<=0||(delete e.userData.components,e[c_]=n)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Rl&&console.log("DONE",JSON.stringify(t)),e[c_]===void 0)return;let n=e[c_];delete e[c_],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;console.log(e.name,n,e.uuid);let i=new DT(e,n,t);this.exportContext[n]=i,this.objectToNodeMap[e.uuid]=n}afterParse(e){Rl&&console.log("AFTER",e);for(let t in this.exportContext){let n=this.exportContext[t],i=n.node,s=n.nodeDef,r=n.nodeIndex,a=i.userData?.components;if(!a||a.length<=0)continue;let l=new OT;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=i,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;let c=[];for(let h of a){this.context.target=h;let u=KO(h,this.context);u!==null&&c.push(u)}c.length>0&&(l[rh]=c,Rl&&console.log("DID WRITE",i,"nodeIndex",r,c))}}beforeRoot(){return Rl&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,n=t?.extensions;if(!n)return;let i=n[this.name];Rl&&console.log("After root",e,this.parser,n);let s=[];if(i===!0){let r=t.json.nodes;for(let a=0;a<r.length;a++){let l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){let l=r[a],c=a,h=l.extensions;if(!h)continue;let u=h[this.name];if(!u)continue;Rl&&console.log("NODE",l);let d=this.nodeToObjectMap[c];if(!d){console.error("Could not find object for node index: "+c,l,t);continue}s.push(this.createComponents(d,u))}}await Promise.all(s)}async createComponents(e,t){if(!t)return;let n=t[rh];if(n){Rl&&console.log(e.name,n);for(let i in n){let s=n[i];Rl&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&await Zd(this.parser,s),e.userData=e.userData||{},e.userData[rh]=e.userData[rh]||[],e.userData[rh].push(s)}}}};var mf=class extends ts{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Ks=class extends ce{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Ks.calculateCenter(this.objects)},n=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ks.saveArrayBuffer(n,e):Ks.saveJson(n,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new j5,this.exporter.register(a=>new og(a)),this.ext=new pf,this.ext.registerExport(this.exporter)),Ks.filterTopmostParent(e);let n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Ks.collectAnimations(e)},i=new De;t?.pivot&&i.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(i.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),$.getComponentsInChildren(a,Sn).forEach(l=>{$.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))});let s=new Jd(i);return this.ext.context=s,new Promise((a,l)=>{try{this.exporter?.parse(i,c=>{r(),a(c)},c=>{r(),l(c)},n)}catch(c){console.error(c),l(c)}finally{console.log("FINALLY")}});function r(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,$.getComponentsInChildren(a,Sn).forEach(l=>{$.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}static collectAnimations(e,t){t=t||[];for(let n of e)!n||n.traverseVisible(i=>{i.animations&&i.animations.length>0&&t.push(...i.animations)});return t}static calculateCenter(e,t){let n=t||new O;return n.set(0,0,0),e.forEach(i=>{n.add(st(i))}),console.log(n),n.divideScalar(e.length),n}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let n=e[t];if(!n){e.splice(t,1),t--;continue}for(;n.parent;){if(e.includes(n.parent)){e.splice(t,1),t--;break}n=n.parent}}}};var sa=class extends ce{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Qr)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Om(e,t,this.color0??new q(.4,.4,.4),this.color1??new q(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};ne([te()],sa.prototype,"isGizmo",2),ne([te(q)],sa.prototype,"color0",2),ne([te(q)],sa.prototype,"color1",2);import{GroundProjectedEnv as X5}from"three/examples/jsm/objects/GroundProjectedEnv.js";var ra=class extends ce{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 K0(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 X5(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))}};ne([te()],ra.prototype,"scale",1),ne([te()],ra.prototype,"radius",1),ne([te()],ra.prototype,"height",1);function kT(o){return o*Math.PI/180}var eD=300,tD=be("debuglights");var wi=class extends ce{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new q(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let n=this._webARRoot?.arScale;typeof n=="number"&&n>0&&(t/=n)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let n=t.shadow.camera;n.far=e,n.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new q(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=wt.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=wt.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){wt.removeEventListener("xrStarted",this._webXRStartedListener),wt.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Qs)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new Td(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-eD*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Fd(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),tD){let r=new Dm(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:let n=new Sd(this.color,this.intensity*Math.PI,this.range,kT(this.spotAngle/2),1-kT(this.innerSpotAngle/2)/kT(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;let i=n.target;n.add(i),i.position.set(0,0,this.range),i.rotation.set(0,0,0);break;case 2:let s=new Md(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=eD*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let n=this.gameObject.scale.x;t.left*=n,t.right*=n}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let n=this.gameObject.scale.y;t.top*=n,t.bottom*=n}this.light.shadow.needsUpdate=!0,tD&&this.context.scene.add(new km(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)}};ne([te()],wi.prototype,"type",2),ne([te(q)],wi.prototype,"color",2),ne([te()],wi.prototype,"shadowNearPlane",1),ne([te()],wi.prototype,"shadowBias",1),ne([te()],wi.prototype,"shadowNormalBias",1),ne([te()],wi.prototype,"shadows",1),ne([te()],wi.prototype,"lightmapBakeType",2),ne([te()],wi.prototype,"intensity",1),ne([te()],wi.prototype,"shadowDistance",1),ne([te()],wi.prototype,"shadowResolution",1);var pre=new O(0,0,0);var gf=be("debugLODs"),q5=be("noLODs");var ro=class{screenRelativeTransitionHeight;distance;renderers};ne([te()],ro.prototype,"screenRelativeTransitionHeight",2),ne([te()],ro.prototype,"distance",2),ne([te()],ro.prototype,"renderers",2);var FT=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let n of t.renderers){let i=this.findRenderer(n,e.gameObject);i&&i.gameObject?this.renderers.push(i):gf&&console.warn("Renderer not found: "+n,e.gameObject)}}findRenderer(e,t){let n=$.foreachComponent(t,i=>i.guid===e||Object.getPrototypeOf(i)?.guid===e?i:null);if(n)return n;for(let i of t.children){let s=this.findRenderer(e,i);if(s)return s}return null}},Al=class extends ce{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!q5&&!this._lodsHandler&&!!this.gameObject&&(gf&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let i of this.lodModels){e=Math.max(i.distance,e);let s=new FT(this,i);this._lods.push(s);for(let r of s.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let i=0;i<t.length;i++){let s=new pd;this._lodsHandler.push(s),this.gameObject.add(s)}let n=new De;gf&&console.log(t);for(let i=0;i<t.length;i++){let s=t[i],r=this._lodsHandler[i],a=s.gameObject,l=0,c=0;gf&&console.log(i,a.name);for(let u of this._lods){let d=null;u.renderers.includes(s)?d=a:d=n,gf&&console.log("add",u.model.distance,d.name);let f=u.model.distance;c=f-l,l=Math.max(f,l),this.onAddLodLevel(r,d,f)}let h=l+c;gf&&console.log("cull",h),this.onAddLodLevel(r,n,h)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,n){e.addLevel(t,n*this._distanceFactor);let i={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(i)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let n=t.lod.levels[t.levelIndex];n.distance=t.distance*e}}}};ne([te(O)],Al.prototype,"localReferencePoint",2),ne([te(ro)],Al.prototype,"lodModels",2);var vf=class extends ce{},yf=class extends ce{};var BT=be("debugnestedgltf"),Rh=class extends ce{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;BT&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new hn;t.idProvider=new ci(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let n=this.gameObject.matrix;BT&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let i=await this.filePath?.instantiate?.call(this.filePath,t);i&&(i.matrixAutoUpdate=!1,i.matrix.identity(),i.applyMatrix4(n),i.matrixAutoUpdate=!0),this.destroy(),BT&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,i)}}hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}};ne([te(Wi)],Rh.prototype,"filePath",2);var oo=class extends ce{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new O(0,0,0);rotationOffset=new O(0,0,0);offset=new O(0,0,0);update(){if(!this.from)return;var e=st(this.from),t=cn(this.from);this.offset.copy(this.positionOffset);let n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){let a=new si(this.gameObject.up,0),l=st(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);let c=new O(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&kt(this.gameObject,e);let i=new Lt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new Oe().setFromEuler(i);this.affectRotation&&Bn(this.gameObject,t.multiply(s));let r=new O;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}};ne([te($)],oo.prototype,"referenceSpace",2),ne([te($)],oo.prototype,"from",2),ne([te(O)],oo.prototype,"positionOffset",2),ne([te(O)],oo.prototype,"rotationOffset",2);var _f=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new q(1,1,1);startColor1=new q(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new _e(0,1);cullingMode=0},bf=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},xf=class{shapeType=NT.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new O(1,1,1);boxThickness=new O(0,0,0);position=new O(0,0,0);rotation=new O(0,0,0);scale=new O(1,1,1);radius=1;sphericalDirectionAmount=0},NT=(v=>(v[v.Sphere=0]="Sphere",v[v.SphereShell=1]="SphereShell",v[v.Hemisphere=2]="Hemisphere",v[v.HemisphereShell=3]="HemisphereShell",v[v.Cone=4]="Cone",v[v.Box=5]="Box",v[v.Mesh=6]="Mesh",v[v.ConeVolume=7]="ConeVolume",v[v.Circle=10]="Circle",v[v.SingleSidedEdge=11]="SingleSidedEdge",v[v.MeshRenderer=12]="MeshRenderer",v[v.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",v[v.BoxShell=14]="BoxShell",v[v.BoxEdge=15]="BoxEdge",v[v.Donut=16]="Donut",v[v.Rectangle=17]="Rectangle",v[v.Sprite=18]="Sprite",v[v.SpriteRenderer=19]="SpriteRenderer",v))(NT||{});var nD=be("debugparticles"),UT=class{age=0;lifetime=0;position;velocity;color},Ah=class extends ce{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(){nD&&console.log(this)}},wf=class extends ce{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Oe;tempVec3=new O;tempQuat=new Oe;awake(){this.renderer=$.getComponent(this.gameObject,Ah),nD&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Lt(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new ht,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Qe(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let n=0;n<e.length;n++)e[n*3]=1,e[n*3+1]=1,e[n*3+2]=1;let t=new Qe(e,3);this.geometry.setAttribute("color",t),this.material=new Nc({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new vd(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let n=this.particleStates[t];if(!n)continue;let i=n.velocity.x*e,s=n.velocity.y*e,r=n.velocity.z*e;n.position.x+=i,n.position.y+=s,n.position.z+=r,this.updateOverLifetime(t,n),this.geometry.attributes.position.setXYZ(t,n.position.x,n.position.y,n.position.z),this.geometry.attributes.color.setXYZ(t,n.color.r,n.color.g,n.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let n=0;n<t;n+=1){if(n>=this.particleStates.length){let s=new UT;s.lifetime=this.main.startLifetime??1,s.position=new O,s.velocity=new O,s.color=new q(1,0,0),this.particleStates.push(s),this.initializeParticle(n,s),s.age=s.lifetime*Math.random()}let i=this.particleStates[n];if(i.age>i.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(n,i);continue}i.age+=e,this.particleStates[n]=i}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let n=t.position;n.multiply(this.shape.scale),n.applyQuaternion(this.shapeRotation),n.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let n=new O(0,1,0);t.copy(n);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*gt.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};function*iD(o,e=null){let t=e?e.time:bt.Current.time,n=t.time;for(;t.time-n<o;)yield}var ss=class extends ce{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 iD(.2),!this.tryAssignColor()););}tryAssignColor(){let e=$.getComponentInParent(this.gameObject,Kt);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ss.hashCode(e),n=ss.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let i=this.gameObject;this.assignColor(n,e,i)}else if(this.gameObject.children)for(let i of this.gameObject.children){let s=i;s.material&&s.material.color&&this.assignColor(n,e,s)}}assignColor(e,t,n){let i=n.material;!i||(i._playerMaterial!==t?(i=i.clone(),i._playerMaterial=t,n.material=i):console.log("DONT CLONE",i),i.color=e)}static hashCode(e){var t=0,n,i;if(e.length===0)return t;for(n=0;n<e.length;n++)i=e.charCodeAt(n),t=(t<<5)-t+i,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,n=(e&65280)>>8,i=e&255;return new q(t/255,n/255,i/255)}};function Z5(){return new Promise((o,e)=>{let n=()=>{n!=null&&(document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n),o())};document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)})}async function sD(o){await Z5(),o()}var HT=be("debugvideo");var ji=class extends ce{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,HT&&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(),sD(()=>{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)}),HT&&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 gm(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ct,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),HT&&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")}};ne([te(De)],ji.prototype,"renderer",2),ne([te()],ji.prototype,"playOnAwake",2),ne([te()],ji.prototype,"playOnEnable",2),ne([te()],ji.prototype,"targetMaterialProperty",2),ne([te()],ji.prototype,"time",2),ne([te()],ji.prototype,"playbackSpeed",1),ne([te()],ji.prototype,"isLooping",1);var Ef=class extends ce{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=$.getComponentInChildren(this.gameObject,ji);if(t){let n={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(n),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};var Pl=class extends ce{mode=0;shadowColor=new gn(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=$.getComponent(this.gameObject,Sn);if(e){let t=e.material;t.blending=Kp,this.applyMaterialOptions(t),t.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
|
|
6340
6340
|
|
|
6341
6341
|
// diffuse-only lighting with overdrive to somewhat compensate
|
|
6342
6342
|
// for the loss of indirect lighting and to make it more visible.
|
|
@@ -6564,8 +6564,8 @@ void main() {
|
|
|
6564
6564
|
See https://github.com/felixmariotto/three-mesh-ui/wiki/Using-a-custom-text-type`);break}})();return n.renderOrder=1/0,n.onBeforeRender=function(){t.updateClippingPlanes&&t.updateClippingPlanes()},n}getGlyphDimensions(t){switch(t.textType){case"MSDF":return YT.getGlyphDimensions(t);default:console.warn(`'${t.textType}' is not a supported text type.
|
|
6565
6565
|
See https://github.com/felixmariotto/three-mesh-ui/wiki/Using-a-custom-text-type`);break}}getGlyphPairKerning(t,n,i){switch(t){case"MSDF":return YT.getGlyphPairKerning(n,i);default:console.warn(`'${t}' is not a supported text type.
|
|
6566
6566
|
See https://github.com/felixmariotto/three-mesh-ui/wiki/Using-a-custom-text-type`);break}}}}function FD(o){o.children.forEach(e=>{e.children.length>0&&FD(e),o.remove(e),da.disposeOf(e),e.material&&e.material.dispose(),e.geometry&&e.geometry.dispose()}),o.children=[]}var Dj=FD,ug=class extends Df.withBase(Rt.Object3D)(kD,Oj,d1,I_){constructor(e){super(e),this.isText=!0,this.set(e)}parseParams(){this.calculateInlines(this._fitFontSize||this.getFontSize())}updateLayout(){Dj(this),this.inlines&&(this.textContent=this.createText(),this.updateTextMaterial(),this.add(this.textContent)),this.position.z=this.getOffset()}updateInner(){this.position.z=this.getOffset(),this.textContent&&this.updateTextMaterial()}calculateInlines(e){let t=this.content,n=this.getFontFamily(),i=this.getBreakOn(),s=this.getTextType(),r=this.getWhiteSpace();if(!n||typeof n=="string"){hg.getFontOf(this)||console.warn("no font was found");return}if(!this.content){this.inlines=null;return}if(!s){console.error(`You must provide a 'textType' attribute so three-mesh-ui knows how to render your text.
|
|
6567
|
-
See https://github.com/felixmariotto/three-mesh-ui/wiki/Using-a-custom-text-type`);return}let a=ED(t,r),l=Array.from?Array.from(a):String(a).split(""),c=e/n.info.size,h=n.common.lineHeight*c,u=n.common.base*c,d=l.map(f=>{let g=this.getGlyphDimensions({textType:s,glyph:f,font:n,fontSize:e}),p=null;return r!==kf&&(i.includes(f)||f.match(/\s/g))&&(p="possible"),f.match(/\n/g)&&(p=SD(r)),{height:g.height,width:g.width,anchor:g.anchor,xadvance:g.xadvance,xoffset:g.xoffset,lineBreak:p,glyph:f,fontSize:e,lineHeight:h,lineBase:u}});if(this.getFontKerning()!=="none")for(let f=1;f<d.length;f++){let g=d[f],p=d[f-1].glyph+d[f].glyph,m=this.getGlyphPairKerning(s,n,p);g.kerning=m*(e/n.info.size)}this.inlines=d}},dg=class extends Df.withBase(Rt.Object3D)(kD,l1,OD,d1,I_){constructor(e){super(e),this.isInlineBlock=!0,this.size=new Rt.Vector2(1,1),this.frame=new x_(this.getBackgroundMaterial()),this.frame.onBeforeRender=()=>{this.updateClippingPlanes&&this.updateClippingPlanes()},this.add(this.frame),this.set(e)}parseParams(){this.width||console.warn("inlineBlock has no width. Set to 0.3 by default"),this.height||console.warn("inlineBlock has no height. Set to 0.3 by default"),this.inlines=[{height:this.height||.3,width:this.width||.3,anchor:0,lineBreak:"possible"}]}updateLayout(){let e=this.getWidth(),t=this.getHeight();if(this.inlines){let n=this.inlines[0];this.position.set(n.width/2,n.height/2,0),this.position.x+=n.offsetX,this.position.y+=n.offsetY}this.size.set(e,t),this.frame.scale.set(e,t,1),this.frame&&this.updateBackgroundMaterial(),this.frame.renderOrder=this.getParentsNumber(),this.childrenInlines.length&&this.computeInlinesPosition(),this.computeChildrenPosition(),this.position.z=this.getOffset()}updateInner(){this.position.z=this.getOffset(),this.frame&&this.updateBackgroundMaterial()}},Ul={fr:[[[{width:.1,chars:[{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"l",upperCase:"L"}]},{width:.1,chars:[{lowerCase:"m",upperCase:"M"}]}],[{width:.2,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"n",upperCase:"N"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],eng:[[[{width:.1,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"l",upperCase:"L"}]}],[{width:.15,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"n",upperCase:"N"}]},{width:.1,chars:[{lowerCase:"m",upperCase:"M"}]},{width:.15,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],ru:[[[{width:1/12,chars:[{lowerCase:"\u0439",upperCase:"\u0419"},{lowerCase:"q",upperCase:"Q"}]},{width:1/12,chars:[{lowerCase:"\u0446",upperCase:"\u0426"},{lowerCase:"w",upperCase:"W"}]},{width:1/12,chars:[{lowerCase:"\u0443",upperCase:"\u0423"},{lowerCase:"e",upperCase:"E"}]},{width:1/12,chars:[{lowerCase:"\u043A",upperCase:"\u041A"},{lowerCase:"r",upperCase:"R"}]},{width:1/12,chars:[{lowerCase:"\u0435",upperCase:"\u0415"},{lowerCase:"t",upperCase:"T"}]},{width:1/12,chars:[{lowerCase:"\u043D",upperCase:"\u041D"},{lowerCase:"y",upperCase:"Y"}]},{width:1/12,chars:[{lowerCase:"\u0433",upperCase:"\u0413"},{lowerCase:"u",upperCase:"U"}]},{width:1/12,chars:[{lowerCase:"\u0448",upperCase:"\u0428"},{lowerCase:"i",upperCase:"I"}]},{width:1/12,chars:[{lowerCase:"\u0449",upperCase:"\u0429"},{lowerCase:"o",upperCase:"O"}]},{width:1/12,chars:[{lowerCase:"\u0437",upperCase:"\u0417"},{lowerCase:"p",upperCase:"P"}]},{width:1/12,chars:[{lowerCase:"\u0445",upperCase:"\u0425"},{lowerCase:"{",upperCase:"["}]},{width:1/12,chars:[{lowerCase:"\u044A",upperCase:"\u042A"},{lowerCase:"}",upperCase:"]"}]}],[{width:1/12,chars:[{lowerCase:"\u0444",upperCase:"\u0424"},{lowerCase:"a",upperCase:"A"}]},{width:1/12,chars:[{lowerCase:"\u044B",upperCase:"\u042B"},{lowerCase:"s",upperCase:"S"}]},{width:1/12,chars:[{lowerCase:"\u0432",upperCase:"\u0412"},{lowerCase:"d",upperCase:"D"}]},{width:1/12,chars:[{lowerCase:"\u0430",upperCase:"\u0410"},{lowerCase:"f",upperCase:"F"}]},{width:1/12,chars:[{lowerCase:"\u043F",upperCase:"\u041F"},{lowerCase:"g",upperCase:"G"}]},{width:1/12,chars:[{lowerCase:"\u0440",upperCase:"\u0420"},{lowerCase:"h",upperCase:"H"}]},{width:1/12,chars:[{lowerCase:"\u043E",upperCase:"\u041E"},{lowerCase:"j",upperCase:"J"}]},{width:1/12,chars:[{lowerCase:"\u043B",upperCase:"\u041B"},{lowerCase:"k",upperCase:"K"}]},{width:1/12,chars:[{lowerCase:"\u0434",upperCase:"\u0414"},{lowerCase:"l",upperCase:"L"}]},{width:1/12,chars:[{lowerCase:"\u0436",upperCase:"\u0416"},{lowerCase:":",upperCase:";"}]},{width:1/12,chars:[{lowerCase:"\u044D",upperCase:"\u042D"},{lowerCase:'"',upperCase:"'"}]},{width:1/12,chars:[{lowerCase:"\u0451",upperCase:"\u0401"},{lowerCase:"|",upperCase:"\\"}]}],[{width:1.5/12,command:"shift",chars:[{icon:"shift"}]},{width:1/12,chars:[{lowerCase:"\u044F",upperCase:"\u042F"},{lowerCase:"z",upperCase:"Z"}]},{width:1/12,chars:[{lowerCase:"\u0447",upperCase:"\u0427"},{lowerCase:"x",upperCase:"X"}]},{width:1/12,chars:[{lowerCase:"\u0441",upperCase:"\u0421"},{lowerCase:"c",upperCase:"C"}]},{width:1/12,chars:[{lowerCase:"\u043C",upperCase:"\u041C"},{lowerCase:"v",upperCase:"V"}]},{width:1/12,chars:[{lowerCase:"\u0438",upperCase:"\u0418"},{lowerCase:"b",upperCase:"B"}]},{width:1/12,chars:[{lowerCase:"\u0442",upperCase:"\u0422"},{lowerCase:"n",upperCase:"N"}]},{width:1/12,chars:[{lowerCase:"\u044C",upperCase:"\u042C"},{lowerCase:"m",upperCase:"M"}]},{width:1/12,chars:[{lowerCase:"\u0431",upperCase:"\u0411"},{lowerCase:",",upperCase:""}]},{width:1/12,chars:[{lowerCase:"\u044E",upperCase:"\u042E"},{lowerCase:".",upperCase:""}]},{width:1.5/12,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.15,command:"switch-set",chars:[{lowerCase:"eng"}]},{width:.15,command:"switch",chars:[{lowerCase:".?12"}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.3,command:"switch",chars:[{lowerCase:"\u0410\u0411\u0412"}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],de:[[[{width:1/11,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:1/11,chars:[{lowerCase:"w",upperCase:"W"}]},{width:1/11,chars:[{lowerCase:"e",upperCase:"E"}]},{width:1/11,chars:[{lowerCase:"r",upperCase:"R"}]},{width:1/11,chars:[{lowerCase:"t",upperCase:"T"}]},{width:1/11,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:1/11,chars:[{lowerCase:"u",upperCase:"U"}]},{width:1/11,chars:[{lowerCase:"i",upperCase:"I"}]},{width:1/11,chars:[{lowerCase:"o",upperCase:"O"}]},{width:1/11,chars:[{lowerCase:"p",upperCase:"P"}]},{width:1/11,chars:[{lowerCase:"\xFC",upperCase:"\xDC"}]}],[{width:1/11,chars:[{lowerCase:"a",upperCase:"A"}]},{width:1/11,chars:[{lowerCase:"s",upperCase:"S"}]},{width:1/11,chars:[{lowerCase:"d",upperCase:"D"}]},{width:1/11,chars:[{lowerCase:"f",upperCase:"F"}]},{width:1/11,chars:[{lowerCase:"g",upperCase:"G"}]},{width:1/11,chars:[{lowerCase:"h",upperCase:"H"}]},{width:1/11,chars:[{lowerCase:"j",upperCase:"J"}]},{width:1/11,chars:[{lowerCase:"k",upperCase:"K"}]},{width:1/11,chars:[{lowerCase:"l",upperCase:"L"}]},{width:1/11,chars:[{lowerCase:"\xF6",upperCase:"\xD6"}]},{width:1/11,chars:[{lowerCase:"\xE4",upperCase:"\xC4"}]}],[{width:2/11,command:"shift",chars:[{icon:"shift"}]},{width:1/11,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:1/11,chars:[{lowerCase:"x",upperCase:"X"}]},{width:1/11,chars:[{lowerCase:"c",upperCase:"C"}]},{width:1/11,chars:[{lowerCase:"v",upperCase:"V"}]},{width:1/11,chars:[{lowerCase:"b",upperCase:"B"}]},{width:1/11,chars:[{lowerCase:"n",upperCase:"N"}]},{width:1/11,chars:[{lowerCase:"m",upperCase:"M"}]},{width:2/11,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],es:[[[{width:.1,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"l",upperCase:"L"}]},{width:.1,chars:[{lowerCase:"\xF1",upperCase:"\xD1"}]}],[{width:.15,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"n",upperCase:"N"}]},{width:.1,chars:[{lowerCase:"m",upperCase:"M"}]},{width:.15,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],el:[[[{width:.1,chars:[{lowerCase:";",upperCase:":"},{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"\u03C2",upperCase:"\u03C2"},{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"\u03B5",upperCase:"\u0395"},{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"\u03C1",upperCase:"\u03A1"},{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"\u03C4",upperCase:"\u03A4"},{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"\u03C5",upperCase:"\u03A5"},{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"\u03B8",upperCase:"\u0398"},{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"\u03B9",upperCase:"\u0399"},{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"\u03BF",upperCase:"\u039F"},{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"\u03C0",upperCase:"\u03A0"},{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"\u03B1",upperCase:"\u0391"},{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"\u03C3",upperCase:"\u03A3"},{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"\u03B4",upperCase:"\u0394"},{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"\u03C6",upperCase:"\u03A6"},{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"\u03B3",upperCase:"\u0393"},{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"\u03B7",upperCase:"\u0397"},{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"\u03BE",upperCase:"\u039E"},{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"\u03BA",upperCase:"\u039A"},{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"\u03BB",upperCase:"\u039B"},{lowerCase:"l",upperCase:"L"}]}],[{width:.15,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"\u03B6",upperCase:"\u0396"},{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"\u03C7",upperCase:"\u03A7"},{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"\u03C8",upperCase:"\u03A8"},{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"\u03C9",upperCase:"\u03A9"},{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"\u03B2",upperCase:"\u0392"},{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"\u03BD",upperCase:"\u039D"},{lowerCase:"n",upperCase:"N"}]},{width:.1,chars:[{lowerCase:"\u03BC",upperCase:"\u039C"},{lowerCase:"m",upperCase:"M"}]},{width:.15,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.15,command:"switch-set",chars:[{lowerCase:"eng"}]},{width:.15,command:"switch",chars:[{lowerCase:".?12"}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],nord:[[[{width:1/11,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:1/11,chars:[{lowerCase:"w",upperCase:"W"}]},{width:1/11,chars:[{lowerCase:"e",upperCase:"E"}]},{width:1/11,chars:[{lowerCase:"r",upperCase:"R"}]},{width:1/11,chars:[{lowerCase:"t",upperCase:"T"}]},{width:1/11,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:1/11,chars:[{lowerCase:"u",upperCase:"U"}]},{width:1/11,chars:[{lowerCase:"i",upperCase:"I"}]},{width:1/11,chars:[{lowerCase:"o",upperCase:"O"}]},{width:1/11,chars:[{lowerCase:"p",upperCase:"P"}]},{width:1/11,chars:[{lowerCase:"\xE5",upperCase:"\xC5"}]}],[{width:1/11,chars:[{lowerCase:"a",upperCase:"A"}]},{width:1/11,chars:[{lowerCase:"s",upperCase:"S"}]},{width:1/11,chars:[{lowerCase:"d",upperCase:"D"}]},{width:1/11,chars:[{lowerCase:"f",upperCase:"F"}]},{width:1/11,chars:[{lowerCase:"g",upperCase:"G"}]},{width:1/11,chars:[{lowerCase:"h",upperCase:"H"}]},{width:1/11,chars:[{lowerCase:"j",upperCase:"J"}]},{width:1/11,chars:[{lowerCase:"k",upperCase:"K"}]},{width:1/11,chars:[{lowerCase:"l",upperCase:"L"}]},{width:1/11,chars:[{lowerCase:"\xE6",upperCase:"\xC6"}]},{width:1/11,chars:[{lowerCase:"\xF8",upperCase:"\xD8"}]}],[{width:2/11,command:"shift",chars:[{icon:"shift"}]},{width:1/11,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:1/11,chars:[{lowerCase:"x",upperCase:"X"}]},{width:1/11,chars:[{lowerCase:"c",upperCase:"C"}]},{width:1/11,chars:[{lowerCase:"v",upperCase:"V"}]},{width:1/11,chars:[{lowerCase:"b",upperCase:"B"}]},{width:1/11,chars:[{lowerCase:"n",upperCase:"N"}]},{width:1/11,chars:[{lowerCase:"m",upperCase:"M"}]},{width:2/11,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]]},kj=new Rt.TextureLoader,w_=class extends Df.withBase(Rt.Object3D)(l1,I_){constructor(e){e||(e={}),e.width||(e.width=1),e.height||(e.height=.4),e.margin||(e.margin=.003),e.padding||(e.padding=.01),super(e),this.currentPanel=0,this.isLowerCase=!0,this.charsetCount=1;let t;if(e.language||navigator.language)switch(e.language||navigator.language){case"fr":case"fr-CH":case"fr-CA":t=Ul.fr;break;case"ru":this.charsetCount=2,t=Ul.ru;break;case"de":case"de-DE":case"de-AT":case"de-LI":case"de-CH":t=Ul.de;break;case"es":case"es-419":case"es-AR":case"es-CL":case"es-CO":case"es-ES":case"es-CR":case"es-US":case"es-HN":case"es-MX":case"es-PE":case"es-UY":case"es-VE":t=Ul.es;break;case"el":this.charsetCount=2,t=Ul.el;break;case"nord":t=Ul.nord;break;default:t=Ul.eng;break}else t=Ul.eng;this.keys=[],this.panels=t.map(n=>{let i=e.height/n.length-e.margin*2,s=new Fh({width:e.width+e.padding*2,height:e.height+e.padding*2,offset:0,padding:e.padding,fontFamily:e.fontFamily,fontTexture:e.fontTexture,backgroundColor:e.backgroundColor,backgroundOpacity:e.backgroundOpacity});return s.charset=0,s.add(...n.map(r=>{let a=new Fh({width:e.width,height:i,margin:e.margin,contentDirection:"row",justifyContent:"center"});a.frame.visible=!1;let l=[];return r.forEach(c=>{let h=new Fh({width:e.width*c.width-e.margin*2,height:i,margin:e.margin,justifyContent:"center",offset:0}),u=c.chars[s.charset].lowerCase||c.chars[s.charset].icon||"undif";if(u==="enter"&&e.enterTexture||u==="shift"&&e.shiftTexture||u==="backspace"&&e.backspaceTexture){let d=(()=>{switch(u){case"backspace":return e.backspaceTexture;case"enter":return e.enterTexture;case"shift":return e.shiftTexture;default:console.warn("There is no icon image for this key")}})();kj.load(d,f=>{h.add(new dg({width:h.width*.65,height:h.height*.65,backgroundSize:"contain",backgroundTexture:f}))})}else h.add(new ug({content:u,offset:0}));h.type="Key",h.info=c,h.info.input=u,h.panel=s,l.push(h),this.keys.push(h)}),a.add(...l),a})),s}),this.add(this.panels[0]),this.set(e)}setNextPanel(){this.panels.forEach(e=>{this.remove(e)}),this.currentPanel=(this.currentPanel+1)%this.panels.length,this.add(this.panels[this.currentPanel]),this.update(!0,!0,!0)}setNextCharset(){this.panels[this.currentPanel].charset=(this.panels[this.currentPanel].charset+1)%this.charsetCount,this.keys.forEach(e=>{if(!this.panels[this.currentPanel].getObjectById(e.id))return;let n=e.info.chars[e.panel.charset]||e.info.chars[0],i=this.isLowerCase||!n.upperCase?n.lowerCase:n.upperCase;if(!e.childrenTexts.length)return;let s=e.childrenTexts[0];e.info.input=i,s.set({content:i}),s.update(!0,!0,!0)})}toggleCase(){this.isLowerCase=!this.isLowerCase,this.keys.forEach(e=>{let t=e.info.chars[e.panel.charset]||e.info.chars[0],n=this.isLowerCase||!t.upperCase?t.lowerCase:t.upperCase;if(!e.childrenTexts.length)return;let i=e.childrenTexts[0];e.info.input=n,i.set({content:n}),i.update(!0,!0,!0)})}parseParams(){}updateLayout(){}updateInner(){}},BD=()=>da.update(),ND={Block:Fh,Text:ug,InlineBlock:dg,Keyboard:w_,FontLibrary:hg,update:BD,TextAlign:C_,Whitespace:T_,JustifyContent:M_,AlignItems:S_,ContentDirection:E_};typeof global<"u"&&(global.ThreeMeshUI=ND);var Fj=ND,Bj=Rs.g1,pg=Rs.gO,Nj=Rs.km,Uj=Rs.zV,Hj=Rs.ol,zj=Rs.uM,f1=Rs.N1,p1=Rs.xv,Vj=Rs.PH,Gj=Rs.UH,Wj=Rs.ZP,jj=Rs.Vx;var Ir=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};var Xj=be("debugeventsystem"),uo=class extends ce{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,uo.systems.length<=0&&uo.systems.push(...$.findObjectsOfType(uo,e)));for(let n of uo.systems)if(n.context===e)return;let t=new De;$.addNewComponent(t,uo),e.scene.add(t)}static ensureUpdateMeshUI(e,t){Lr.update(e,t)}static markUIDirty(e){Lr.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),uo.systems.push(this)}onDestroy(){uo.systems.splice(uo.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}onEnable(){Vt.addEventListener("select-start",(t,n)=>{if(!n.grab)return;Lr.resetLastSelected();let i=new Ir;i.inputSource=t,i.isDown=t.selectionDown,i.isUp=t.selectionUp,i.isPressed=t.selectionPressed,i.isClicked=!1,n.grab&&!this.handleEvents(n.grab,i)&&(n.grab=null)});let e=new Zn;Vt.addEventListener("select-end",(t,n)=>{if(!n.grab)return;let i=new Ir;i.inputSource=t,i.isDown=t.selectionDown,i.isUp=t.selectionUp,i.isPressed=t.selectionPressed,i.isClicked=t.selectionClick,this.handleEvents(n.grab,i)}),Vt.addEventListener("update",t=>{e.ray=t.getRay();let n=this.performRaycast(e);if(!n)return;let i=new Ir;i.inputSource=t,this.handleIntersections(n,i)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerDown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),wt.IsInWebXR||this.context.input.isKeyPressed(18))return;if(!this._didMove){let s=this.context.input.getPointerPositionRC(0);if(s&&s.x===0&&s.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new Ir(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let n=null,i=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(n=$.getComponent(this.context.mainCameraComponent.gameObject,xs)??null,n&&(i=n.enabled,n.enabled=!1)),this.handleIntersections(e,t),n&&(this.orbitControl=n,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let n=$.getComponentsInParent(t,ce,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let i=0;i<n.length;i++){let s=n[i];if(!s.gameObject||s.destroyed)continue;let r=s;r.onPointerExit&&r.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let n=t.performRaycast(e);n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((t,n)=>t.distance-n.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let n of e){let{object:i}=n;if(this.handleEvents(i,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let n=e[t],i=n.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Xj&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let n=e.parent,i=!1,s=t.isClicked??!1,r=null;if(n&&n.isUI){let a=(t.isPressed||t.isClicked)??!1;if(n.shadowComponentOwner){let l=n.shadowComponentOwner.gameObject;if(l){if(r=this.tryFindCanvasGroup(l),r?.blocksRaycasts===!1)return!1;if(r?.interactable===!1)return!0;let c=this.handleMeshUIIntersection(e,a);e=l,i=!0}}if(!i&&this.handleMeshUiObjectWithoutShadowDom(n,a))return!0}if(this.objectsHoveredThisFrame.push(e),r===null||r.interactable){let a=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let l=$.getComponentsInParent(e,ce,this.handleEventsArray);for(let c=0;c<l.length;c++){if(t.used)return!0;if(l[c].destroyed)continue;let h=l[c];h.interactable!==!1&&(h.onPointerEnter&&(a||h.onPointerEnter(t)),t.isDown&&h.onPointerDown&&!this.raisedPointerDownEvents.includes(h)&&(h.onPointerDown(t),this.raisedPointerDownEvents.push(h)),t.isUp&&h.onPointerUp&&h.onPointerUp(t),t.isClicked&&h.onPointerClick&&h.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let n=Lr.updateState(e,t);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Lr.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];Lr.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?$.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=$.foreachComponent(e,n=>{let i=n;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}},Mi=uo;Se(Mi,"didSearchEventSystem",!1),Se(Mi,"systems",[]);var Lr=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let n of this.lastUpdateFrame)if(n.context===t){if(t.time.frameCount===n.frame)return;n.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let n=null;if(e&&(n=this.findBlockInParent(e),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;t?(this.lastSelected=n,n.states.pressed&&n.setState("pressed")):n.states.hovered&&n.setState("hovered"),this.needsUpdate=!0}return n}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};Se(Lr,"lastSelected",null),Se(Lr,"lastUpdateFrame",[]),Se(Lr,"needsUpdate",!1);var Nf="./include";pg.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var di=class extends ce{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Mi.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=$.getComponentInParent(this.gameObject,fa)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=$.getComponentInParent(n,di),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this;let i=this.raycastTarget;if(e.traverse(s=>{s.shadowComponentOwner===void 0&&(s.shadowComponentOwner=this),i===!1&&s.layers.set(2)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let s=this._parentComponent.shadowComponent;s&&s?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Qr&&e.add(new xr(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,n){if(!!e&&e.shadowComponentOwner===t){n(e);for(let i of e.children)this.traverseOwnedShadowComponents(i,t,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},fa=class extends di{awake(){super.awake()}};var UD=be("debugui"),Uf=class{width;height},Bh=class{x;y;width;height},rs=class extends di{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new O),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new it,this.rectBlock=new De,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new O),ef(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this.applyTransform()}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(UD&&console.log("updating",this.name),this.applyTransform()),Mi.ensureUpdateMeshUI(Bf,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,n=this.pivot.y*2-1;n-=this.anchoredPosition.y*.05;let i=this.sizeDelta.x*t,s=this.sizeDelta.y*n;e.x-=i*.5,e.y-=s*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},UD&&console.log(this.name,e);let t=new pg(e);return this._createdBlocks.push(t),t}};ne([te(Bh)],rs.prototype,"rect",2),ne([te(_e)],rs.prototype,"sizeDelta",2),ne([te(O)],rs.prototype,"anchoredPosition3D",2),ne([te(_e)],rs.prototype,"pivot",2);var As=class extends di{get color(){return this._color||(this._color=new gn(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new gn(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=this.gameObject.getComponent(rs)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),ef(this,"_color",()=>jO(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};ne([te(gn)],As.prototype,"color",1),ne([te()],As.prototype,"raycastTarget",2);var pa=class extends As{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var L_=class{texture;rect};ne([te(Nt)],L_.prototype,"texture",2);var ma=class extends pa{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return!1}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new q(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};ne([te(L_)],ma.prototype,"sprite",2);var Nh=class extends pa{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};ne([te(Nt)],Nh.prototype,"mainTexture",2);var Hf=be("debugbutton");var er=class extends ce{onClick;_isHovered=!1;onPointerEnter(e){Hf&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){Hf&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){Hf&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){Hf&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){Hf&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Hf&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=$.getComponent(this.gameObject,ma),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),n={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(n);let i=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};e.setupState(s);let r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);let l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);let h=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};ne([te(Rn)],er.prototype,"onClick",2),ne([te()],er.prototype,"colors",2),ne([te()],er.prototype,"transition",2),ne([te()],er.prototype,"animationTriggers",2),ne([te(ws)],er.prototype,"animator",2),ne([te()],er.prototype,"interactable",1);var m1=class extends fa{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof m1||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),Kd(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(di))Kd(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let i=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-i;let s=Math.tan(gt.toRadians(e.fieldOfView)*i)*(e.aspect*1.333333),r=s*(this.context.domHeight/this.context.domWidth);t.scale.x=-s,t.scale.y=r;break;case 2:break}}},Ti=m1;ne([te()],Ti.prototype,"renderOnTop",1),ne([te()],Ti.prototype,"depthWrite",1),ne([te()],Ti.prototype,"doubleSided",1),ne([te()],Ti.prototype,"castShadows",1),ne([te()],Ti.prototype,"receiveShadows",1),ne([te()],Ti.prototype,"renderMode",1),ne([te(Ti)],Ti.prototype,"rootCanvas",1);var ga=class extends ce{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of $.getComponentsInChildren(this.gameObject,As,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};ne([te()],ga.prototype,"alpha",1),ne([te()],ga.prototype,"interactable",2),ne([te()],ga.prototype,"blocksRaycasts",2);var qj=be("debugtext");var Hn=class extends As{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){qj&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let n=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(n,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(n,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,n,i=!1){let s={};s.hiddenOverflow=t,s.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(s,i);let r=e.createNewBlock(s);return n&&(Array.isArray(n)?r.add(...n):r.add(n)),r}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((n,i)=>n+i.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e.shadowComponentOwner===void 0&&(e.shadowComponentOwner=this)})}createText(e,t,n){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),n){let i=this.getNextTag(e);if(i)i.startIndex>0&&this.createText(e.substring(0,i.startIndex),t,!1);else return this.createText(e,t,!1);let s=[];for(;i;){let r=this.getNextTag(e,i.endIndex);if(r){let a=this.getText(e,i,r);this.handleTag(i,t,s),this.createText(a,t,!1)}else{let a=e.substring(i.endIndex);this.handleTag(i,t,s),this.createText(a,t,!1)}i=r}}else{let i={...t};i.content=e;let s=new p1(i);this._textMeshUi.push(s),this._textContainer&&this._textContainer.add(s)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,n={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let i=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;i=!0;let r=this._textMeshUi[s];!r.textContent||(Kd(r,n),e[s]=!0)}if(!i)break;yield}}handleTag(e,t,n){if(e.isEndTag){if(n.length>0){let i=n.pop();if(i)for(let s in i.previousValues){let r=i.previousValues[s];t[s]=r}}}else if(e.type.includes("color")){let i=new mg(e,{fontColor:t.fontColor});if(n.push(i),e.type.length>6){let s=e.type.substring(6);t.fontColor=Yj(s)}else t.fontColor=new q(1,1,1)}else if(e.type=="b"){let i=new mg(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});n.push(i),this.setFont(t,1)}else if(e.type=="i"){let i=new mg(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});n.push(i),this.setFont(t,2)}}getText(e,t,n){return e.substring(t.endIndex,n.startIndex)}getNextTag(e,t=0){let n=e.indexOf("<",t),i=e.indexOf(">",n);if(n>=0&&i>=0){let s=e.substring(n+1,i);return{type:s,startIndex:n,endIndex:i+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){let n=this.getFontName(t),i=n;i?.endsWith("-msdf.json")||(i+="-msdf.json"),e.fontFamily=i;let s=n;s?.endsWith(".png")||(s+=".png"),e.fontTexture=s}getFontName(e){return this.font?this.font:null}};ne([te(Ti)],Hn.prototype,"canvas",2),ne([te()],Hn.prototype,"alignment",2),ne([te()],Hn.prototype,"verticalOverflow",2),ne([te()],Hn.prototype,"horizontalOverflow",2),ne([te()],Hn.prototype,"lineSpacing",2),ne([te()],Hn.prototype,"supportRichText",2),ne([te()],Hn.prototype,"font",2),ne([te()],Hn.prototype,"fontStyle",2),ne([te()],Hn.prototype,"text",1),ne([te()],Hn.prototype,"fontSize",1);var mg=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Yj(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let n=e>>16&255,i=e>>8&255,s=e&255;return new q(n/255,i/255,s/255)}switch(o){case"black":return new q(0,0,0);case"white":return new q(1,1,1);case"red":return new q(1,0,0);case"lime":return new q(0,1,0);case"blue":return new q(0,0,1);case"yellow":return new q(1,1,0);case"cyan":return new q(0,1,1);case"magenta":return new q(1,0,1);case"silver":return new q(.75,.75,.75);case"gray":return new q(.5,.5,.5);case"maroon":return new q(.5,0,0);case"olive":return new q(.5,.5,0);case"green":return new q(0,.5,0);case"purple":return new q(.5,0,.5);case"teal":return new q(0,.5,.5);case"navy":return new q(0,0,.5);case"darkred":return new q(.54,0,0);case"brown":return new q(.55,.27,0);case"firebrick":return new q(.69,.13,.13);case"crimson":return new q(.86,.08,.24);case"tomato":return new q(1,.39,.28);case"coral":return new q(1,.49,.31);case"indianred":return new q(.6,.31,.51);case"lightcoral":return new q(.94,.5,.5);case"darkorange":return new q(1,.55,0);case"orange":return new q(1,.65,0);case"gold":return new q(1,.84,0);case"darkgoldenrod":return new q(.72,.53,.04);case"goldenrod":return new q(.85,.65,.13);case"palegoldenrod":return new q(.93,.87,.67);case"darkkhaki":return new q(.74,.7,.42);case"khaki":return new q(.94,.9,.55);case"yellowgreen":return new q(.6,.8,.19);case"darkolivegreen":return new q(.33,.42,.18);case"olivedrab":return new q(.42,.56,.14);case"lawngreen":return new q(.49,.99,0);case"chartreuse":return new q(.5,1,0);case"greenyellow":return new q(.68,1,.18);case"darkgreen":return new q(0,.39,0);case"forestgreen":return new q(.13,.55,.13);case"limegreen":return new q(.19,.8,.19);case"lightgreen":return new q(.56,.93,.56);case"palegreen":return new q(.59,.98,.59);case"darkseagreen":return new q(.56,.74,.56);case"mediumspringgreen":return new q(0,.98,.6);case"springgreen":return new q(0,1,.5);case"seagreen":return new q(.18,.31,.31);case"mediumaquamarine":return new q(.4,.8,.66);case"mediumseagreen":return new q(.24,.7,.44);case"lightseagreen":return new q(.13,.7,.67);case"darkslategray":return new q(.18,.31,.31);case"darkcyan":return new q(0,.55,.55);case"aqua":return new q(0,1,1);case"lightcyan":return new q(.8,1,1);case"darkturquoise":return new q(0,.81,.82);case"turquoise":return new q(0,.82,.82);case"mediumturquoise":return new q(.28,.82,.8);case"paleturquoise":return new q(.68,1,.93);case"aquamarine":return new q(.5,1,.83);case"powderblue":return new q(.69,.88,.9);case"cadetblue":return new q(.37,.62,.63);case"steelblue":return new q(.27,.51,.71);case"cornflowerblue":return new q(.39,.58,.93);case"deepskyblue":return new q(0,.7,1);case"dodgerblue":return new q(.12,.56,1);case"lightblue":return new q(.68,.85,.9);case"skyblue":return new q(.53,.81,.92);case"lightskyblue":return new q(.53,.81,.98);case"midnightblue":return new q(.18,.18,.31);case"darkblue":return new q(0,0,.55);case"mediumblue":return new q(0,0,.82);case"royalblue":return new q(.25,.41,.88);case"blueviolet":return new q(.54,.17,.89);case"indigo":return new q(.29,0,.51);case"darkslateblue":return new q(.28,.24,.55);case"slateblue":return new q(.42,.35,.8);case"mediumslateblue":return new q(.48,.41,.9);case"mediumpurple":return new q(.58,.44,.86);case"darkmagenta":return new q(.55,0,.55);case"darkviolet":return new q(.58,0,.83);case"darkorchid":return new q(.6,.2,.8);case"mediumorchid":return new q(.73,.33,.83);case"thistle":return new q(.84,.75,.85);case"plum":return new q(.87,.63,.87);case"violet":return new q(.93,.51,.93);case"fuchsia":return new q(1,0,1);case"orchid":return new q(.85,.44,.84);case"mediumvioletred":return new q(.78,.08,.52);case"palevioletred":return new q(.86,.44,.58);case"hotpink":return new q(1,.4,.71);case"deeppink":return new q(1,.08,.58);case"lightpink":return new q(1,.71,.76);case"pink":return new q(1,.75,.78);case"antiquewhite":return new q(.98,.92,.84);case"beige":return new q(.96,.96,.86);case"bisque":return new q(1,.89,.77);case"blanchedalmond":return new q(1,.92,.82);case"wheat":return new q(.96,.87,.87);case"cornsilk":return new q(1,.97,.86);case"lemonchiffon":return new q(1,.98,.8);case"lightgoldenrodyellow":return new q(.98,.98,.82);case"lightyellow":return new q(1,1,.8);case"saddlebrown":return new q(.55,.27,.07);case"sienna":return new q(.63,.32,.18);case"chocolate":return new q(.82,.41,.12);case"peru":return new q(.82,.52,.25);case"sandybrown":return new q(.96,.64,.38);case"burlywood":return new q(.87,.72,.53);case"tan":return new q(.82,.71,.55);case"rosybrown":return new q(.74,.56,.56);case"moccasin":return new q(1,.89,.71);case"navajowhite":return new q(1,.87,.68);case"peachpuff":return new q(1,.85,.73);case"mistyrose":return new q(1,.89,.88);case"lavenderblush":return new q(1,.94,.93);case"linen":return new q(.98,.94,.9);case"oldlace":return new q(.99,.96,.9);case"papayawhip":return new q(1,.94,.84);case"seashell":return new q(1,.96,.93);case"mintcream":return new q(.98,1,.98);case"slategray":return new q(.44,.5,.56);case"lightslategray":return new q(.47,.53,.6);case"lightsteelblue":return new q(.69,.77,.87);case"lavender":return new q(.9,.9,.98);case"floralwhite":return new q(1,.98,.98);case"aliceblue":return new q(.94,.97,1);case"ghostwhite":return new q(.97,.97,1);case"honeydew":return new q(.94,1,.94);case"ivory":return new q(1,1,.94);case"azure":return new q(.94,1,1);case"snow":return new q(1,.98,.98);case"dimgray":return new q(.4,.4,.4);case"darkgray":return new q(.66,.66,.66);case"lightgray":return new q(.83,.83,.83);case"gainsboro":return new q(.86,.86,.86);case"whitesmoke":return new q(.96,.96,.96)}return new q(1,1,1)}var Uh=be("debuginputfield"),vt=class extends ce{get text(){return this.textComponent?.text??""}get isFocused(){return vt.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Uh&&console.log(this.name,this)}onEnable(){vt.htmlField||(vt.htmlField=document.createElement("input"),vt.htmlField.classList.add("ar"),document.body.appendChild(vt.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),vt.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&$.setActive(this.placeholder.gameObject,!1)}onDisable(){vt.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Uh&&console.log("CLICK",e,vt.active),vt.activeTime=this.context.time.time,vt.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();vt.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-vt.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(vt.active!==this&&(Uh&&console.log("Select",this.name,this,vt.htmlField,this.context.isInXR,this.context.AROverlayElement,this.textComponent?.text,vt.htmlField?.value),vt.active?.onDeselected(),vt.active=this,this.placeholder&&$.setActive(this.placeholder.gameObject,!1),vt.htmlField)){if(vt.htmlField.value=this.textComponent?.text||"",Uh&&console.log("set input field value",vt.htmlField.value),this.context.isInXR){let e=this.context.AROverlayElement;e&&(vt.htmlField.style.width="0px",vt.htmlField.style.height="0px",e.append(vt.htmlField))}this.selectInputField()}}onDeselected(){vt.active===this&&(vt.active=null,Uh&&console.log("Deselect",this.name,this),vt.htmlField&&(vt.htmlField.blur(),document.body.append(vt.htmlField),vt.htmlField.style.width="",vt.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&$.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(vt.active===this){if(Uh&&console.log(e.code,e,vt.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}vt.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&$.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&vt.htmlField){if(this.textComponent.text!==vt.htmlField.value){Uh&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=vt.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=vt.htmlField.value}}selectInputField(){vt.htmlField&&(vt.htmlField.setSelectionRange(vt.htmlField.value.length,vt.htmlField.value.length),vt.htmlField.focus())}},Ps=vt;Se(Ps,"active",null),Se(Ps,"activeTime",-1),Se(Ps,"htmlField",null),ne([te(Hn)],Ps.prototype,"textComponent",2),ne([te(Hn)],Ps.prototype,"placeholder",2),ne([te(Rn)],Ps.prototype,"onValueChanged",2),ne([te(Rn)],Ps.prototype,"onEndEdit",2);var HD=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(HD||{}),zf=class extends di{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=HD[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",n=this.gameObject.getComponent(rs);if(!n){console.error("Missing rect transform, please add this component inside a canvas");return}let i={...n.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Nf+"/"+t+"-msdf.json",fontTexture:Nf+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new q(this.colors.keyboardBack),backspaceTexture:Nf+"/backspace.png",shiftTexture:Nf+"/shift.png",enterTexture:Nf+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},s=this.gameObject.scale;i.width*=this.gameObject.scale.x,i.height*=this.gameObject.scale.y,i.fontSize*=Math.max(s.x,s.y),this.keyboard=new f1(i),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(r=>{r.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new q(this.colors.button),backgroundOpacity:1}}),r.setState("normal"),r.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new q(this.colors.hovered),backgroundOpacity:1}}),r.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new q(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=r.info.input,l=r.info.command;if(this._lastKeyPressed!==a)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||l=="switch"||l=="shift"||l=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=a,l)switch(l){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
|
|
6568
|
-
`);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else r.info.input!==void 0&&this.tryAppend(r.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var va=class extends ce{reverseArrangement=!1},Vf=class extends va{},Gf=class extends va{},Wf=class extends va{};var Hh=class extends ce{awake(){Mi.createIfNoneExists(this.context)}onEnable(){Mi.instance?.register(this)}onDisable(){Mi.instance?.unregister(this)}performRaycast(e=null){return null}},fo=class extends Hh{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new Zn,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},jf=class extends fo{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import{HTMLMesh as Zj}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as Jj}from"three/examples/jsm/interactive/InteractiveGroup.js";var Xf=class extends ce{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new Jj(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let n=new Zj(e);t.add(n),n.visible=!1,console.log(n);let i=n.material;i.transparent=!0,setTimeout(()=>{n.visible=!0;let s=ay(this.gameObject).clone();ly(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let r=new On;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);let a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){let h=a/l;a>l?n.scale.set(1/a,1/l/h,1):n.scale.set(1/a*h,1/l,1)}else n.scale.set(1/a,1/l,1);let c=this.gameObject.scale;n.scale.multiply(c)},1)}};var O_=class extends ce{toggleKey=80;update(){this.context.input.isKeyDown(80)&&this.context.domElement.classList.toggle("presentation-mode")}};var Ax=Du(EA(),1);var SA=class{id=0;points=[];line=new Ax.MeshLine;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let n=t.options;n&&Object.assign(this.material,n)}this.mesh=new _t(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=SA.wp;t.set(e.x,e.y,e.z);let n=this.mesh?.parent;return n&&(t=n.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new Ax.MeshLineMaterial({color:10066329,lineWidth:.01})},Op=SA;Se(Op,"wp",new O);var Iu=class extends ce{startLine(e,t){let n=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,n,!0,t)}updateLine(e,t){let n=this.inFlight[e.id];if(!n)return;t.point&&(t.point=n.appendPoint(t.point));let i=this.buffer[e.id];i&&(t.point&&i.push(t.point.x,t.point.y,t.point.z),i.length>5&&(this.sendLineUpdate(n,!1,void 0,i),i.length=0))}endLine(e,t=!0){let n=this.inFlight[e.id];if(!n)return;this.finished.push(n),delete this.inFlight[e.id],t&&this.sendLineUpdate(n,!0,0);let i=this.buffer[e.id];if(i){delete this.buffer[e.id];let s=i;s.length=0,this.freeBuffer.push(s)}return n}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let n=$.findByGuid(t,this.context.scene);if(!!n)return this.internalStartLine(n,e,!1),this.inFlight[e]}internalStartLine(e,t,n=!0,i){let s=new Op(e??this.context.scene,i);s.id=t,this.inFlight[t]=s,n&&this.sendLineStart(s);let r;return this.freeBuffer.length<=0?r=new Array:r=this.freeBuffer.pop(),this.buffer[t]=r,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,n,i){if(e){let s={parentGuid:e.mesh.parent.guid,guid:e.id,points:i?[...i]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:n!==void 0?n:e.points.length,finished:t};this.context.connection.send("line-update",s)}}};var SF=Du(EA(),1);var Px=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new O,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},Ix=class extends ce{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=$.getComponent(this.gameObject,Iu),this.lines||(this.lines=$.addNewComponent(this.gameObject,Iu))),this.orbit=$.findObjectOfType(xs,this.context)??void 0,this._states.mouse=new Px;let e={};Vt.addEventListener("select-start",(t,n)=>{e[t.controller.uuid]=!0}),Vt.addEventListener("update",(t,n)=>{if(e[t.controller.uuid]===!0){let i=t.getRay();this.updateLine(t.controller.uuid,i,!0,!1,!1)}}),Vt.addEventListener("select-end",(t,n)=>{e[t.controller.uuid]=!1;let i=t.getRay();this.updateLine(t.controller.uuid,i,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);Ix._raycaster.setFromCamera(t,this.context.mainCamera);let n=Ix._raycaster.ray;this.updateLine("mouse",n,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed(18))}updateLine(e,t,n,i,s=!1){let r=this._states[e];if(r||(this._states[e]=new Px,r=this._states[e]),i)r.isDrawing=!1,r.currentHandle&&(this.lines.endLine(r.currentHandle),r.currentHandle=null);else if(n){if(s)return r;let a=this.getHit(t),l=null,c=r.prevDistance;if(a)r.currentHandle||(r.maxDistance=a.distance),l=a.point,l.add(a.face.normal.multiplyScalar(.01)),r.prevDistance=a.distance;else if(r.maxDistance>0){let h=r.maxDistance;if(!r.currentHandle&&r.lastHit){let u=st(this.context.mainCamera);h=r.lastHit.distanceTo(u)}l=t.origin.add(t.direction.multiplyScalar(r.maxDistance)),r.prevDistance=r.maxDistance}if(l){if(!r.currentHandle){let h=r.lastParent??this.gameObject;this.addToPaintedObject&&a&&(h=a.object),r.lastParent=h,r.currentHandle=this.lines.startLine(h,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(r.prevDistance>r.maxDistance||Math.abs(c-r.prevDistance)>.2)){let h=r.maxDistance;l=t.origin.add(t.direction.multiplyScalar(h)),r.prevDistance=h}if(r.lastHit&&r.lastHit.distanceTo(l)<r.prevDistance*.01)return r;this.lines.updateLine(r.currentHandle,{point:l}),r.lastHit.copy(l)}r.isDrawing=r.currentHandle!==null}return r}_raycastOptions=new Zn;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let n of t)if(!!$.isActiveInHierarchy(n.object))return n}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ss.colorFromHashCode(ss.hashCode(this.context.connection.connectionId)):e=new q("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new SF.MeshLineMaterial({color:e,lineWidth:gt.lerp(.005,.01,Math.random())})}},cv=Ix;Se(cv,"_raycaster",new zo);var hv=class extends ce{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let n=$.getComponent(t,xo);n&&(n.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=xo.all.length-1;t>=0;t--){let n=xo.all[t];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}};ne([te(Wi)],hv.prototype,"asset",2);var lr=class extends ce{static get all(){return lr._all}static get local(){return lr._local}static isLocalPlayer(e){return e instanceof De?$.getComponentInParent(e,lr)?.isLocalPlayer??!1:e instanceof $i?$.getComponentInParent(e.gameObject,lr)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&lr.local.push(this),lr.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){Bd(this.gameObject,this.context.connection)}onDestroy(){if(lr.all.splice(lr.all.indexOf(this),1),this.isLocalPlayer){let e=lr._local.indexOf(this);e>=0&&lr._local.splice(e,1)}}},xo=lr;Se(xo,"_all",[]),Se(xo,"_local",[]),ne([h_(),te()],xo.prototype,"owner",2);pe.add("AlignmentConstraint",_l);pe.add("Animation",Rr);pe.add("AnimationCurve",bh);pe.add("Animator",ws);pe.add("AnimatorController",Cr);pe.add("AudioListener",Ar);pe.add("AudioSource",$t);pe.add("AvatarModel",xh);pe.add("AvatarLoader",bl);pe.add("AxesHelper",Ko);pe.add("BasicIKConstraint",$d);pe.add("BoxHelperComponent",ts);pe.add("Camera",Bt);pe.add("Collider",Kr);pe.add("SphereCollider",xl);pe.add("BoxCollider",wl);pe.add("InstantiateOptions",hn);pe.add("UnityObject",nf);pe.add("DeleteBox",wh);pe.add("Deletable",sf);pe.add("DeviceFlag",Eh);pe.add("DragControls",Ss);pe.add("DropListener",Cl);pe.add("Duplicatable",io);pe.add("CallInfo",so);pe.add("EventListEvent",Ch);pe.add("EventList",Rn);pe.add("EventTrigger",df);pe.add("FlyControls",ff);pe.add("BoxGizmo",ia);pe.add("GltfExportBox",mf);pe.add("GltfExport",Ks);pe.add("GridHelper",sa);pe.add("GroundProjectedEnv",ra);pe.add("Interactable",qs);pe.add("UsageMarker",Ys);pe.add("Light",wi);pe.add("LODModel",ro);pe.add("LODGroup",Al);pe.add("LookAtConstraint",Qo);pe.add("NavMesh",vf);pe.add("NavMeshAgent",yf);pe.add("NestedGltf",Rh);pe.add("Networking",ys);pe.add("OffsetConstraint",oo);pe.add("OrbitControls",xs);pe.add("ParticleSystemRenderer",Ah);pe.add("ParticleSystem",wf);pe.add("MainModule",_f);pe.add("EmissionModule",bf);pe.add("ShapeModule",xf);pe.add("PlayerColor",ss);pe.add("FieldWithDefault",Vd);pe.add("Renderer",Sn);pe.add("MeshRenderer",vh);pe.add("SkinnedMeshRenderer",Gd);pe.add("InstancingUtil",Qt);pe.add("RendererLightmap",Yo);pe.add("Rigidbody",Xt);pe.add("ScreenCapture",Ef);pe.add("ShadowCatcher",Pl);pe.add("RemoteSkybox",Il);pe.add("SmoothFollow",ao);pe.add("SpatialTriggerReceiver",Ms);pe.add("SpatialTrigger",oa);pe.add("SpectatorCamera",Sf);pe.add("SpringJoint",Mf);pe.add("Sprite",Ph);pe.add("SpriteRenderer",aa);pe.add("SyncedCamera",Ll);pe.add("SyncedRoom",Pr);pe.add("SyncedTransform",xi);pe.add("TestRunner",Tf);pe.add("TestSimulateUserData",Cf);pe.add("TransformGizmo",Ih);pe.add("VideoPlayer",ji);pe.add("Voip",Vi);pe.add("VolumeParameter",Rf);pe.add("VolumeComponent",lo);pe.add("ToneMapping",Dl);pe.add("ColorAdjustments",kl);pe.add("VolumeProfile",Ol);pe.add("Volume",Lh);pe.add("WebARSessionRoot",Qs);pe.add("WebXR",wt);pe.add("WebAR",Tl);pe.add("AvatarMarker",Kt);pe.add("WebXRAvatar",Js);pe.add("TeleportTarget",Sh);pe.add("WebXRController",Vt);pe.add("AttachedObject",is);pe.add("XRGrabModel",Oh);pe.add("XRGrabRendering",Af);pe.add("XRRig",Ml);pe.add("VRUserState",$s);pe.add("WebXRSync",na);pe.add("XRState",Es);pe.add("XRFlag",Cn);pe.add("AvatarBlink_Simple",co);pe.add("AvatarEyeLook_Rotation",ho);pe.add("Avatar_POI",vn);pe.add("Avatar_Brain_LookAt",ta);pe.add("Avatar_MouthShapes",Fl);pe.add("Avatar_MustacheShake",Pf);pe.add("LogStats",If);pe.add("RGBAColor",gn);pe.add("PlayableDirector",ua);pe.add("SignalAsset",Dh);pe.add("SignalReceiverEvent",kh);pe.add("SignalReceiver",la);pe.add("AnimationTrackHandler",Bl);pe.add("AudioTrackHandler",Nl);pe.add("SignalTrackHandler",ha);pe.add("ControlTrackHandler",ca);pe.add("BaseUIComponent",di);pe.add("UIRootComponent",fa);pe.add("Button",er);pe.add("Canvas",Ti);pe.add("CanvasGroup",ga);pe.add("EventSystem",Mi);pe.add("Graphic",As);pe.add("MaskableGraphic",pa);pe.add("Image",ma);pe.add("RawImage",Nh);pe.add("InputField",Ps);pe.add("Keyboard",zf);pe.add("LayoutGroup",va);pe.add("VerticalLayoutGroup",Vf);pe.add("HorizontalLayoutGroup",Gf);pe.add("GridLayoutGroup",Wf);pe.add("PointerEventData",Ir);pe.add("Raycaster",Hh);pe.add("ObjectRaycaster",fo);pe.add("GraphicRaycaster",jf);pe.add("Size",Uf);pe.add("Rect",Bh);pe.add("RectTransform",rs);pe.add("SpatialHtml",Xf);pe.add("Text",Hn);pe.add("PresentationMode",O_);pe.add("LinesDrawer",cv);pe.add("LineInstanceHandler",Op);pe.add("LinesManager",Iu);pe.add("PlayerSync",hv);pe.add("PlayerState",xo);var TA=class extends $o{constructor(){super([q,gn])}onDeserialize(e){if(e!=null)return e.a!==void 0?new gn(e.r,e.g,e.b,e.a):e.alpha!==void 0?new gn(e.r,e.g,e.b,e.alpha):new q(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},bpe=new TA,CA=class extends $o{constructor(){super(De)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let n=t.objectToNode[e.uuid];return Nn&&console.log(n,e.name,e.uuid),{node:n}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let n=t.nodeToObject[e.node];return Nn&&console.log("Deserialized object reference?",e,n,t?.nodeToObject),n||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),n}else if(e.guid){if(!t.context){console.error("Missing context");return}let n,i=t.gltf?.scene;return i&&(n=$.findByGuid(e.guid,i)),n||(n=$.findByGuid(e.guid,t.context.scene)),n?Nn&&console.log("Deserialized object reference?",e,n,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),n}}}},CY=new CA,RA=class extends $o{constructor(){super([$i,ce])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Nn&&console.log(e.guid,t.root,t.object,t.target);let n=this.findObjectForGuid(e.guid,t.root);if(n)return n;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){return $.foreachComponent(t,n=>{if(e===n.gameObject.guid)return n.gameObject;if(n.guid===e)return n})}},MA=new RA,AA=class extends $o{constructor(){super([Rn])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Nn&&console.log("DESERIALIZE EVENT",e);let n=new Array;for(let r of e.calls){Nn&&console.log(r);let a=MA.findObjectForGuid(r.target,t.root);!a&&t.context?.scene&&(a=MA.findObjectForGuid(r.target,t.context?.scene));let l=r.method?.length>0;if(a&&l){let d=()=>console.warn(`Could not find method ${r.method} on object ${a.name}`,a,typeof a[r.method]);if(typeof a[r.method]!="function"){let f=!1;r.method.startsWith("set_")&&r.method.length>4&&(r.method=r.method.substring(4),a[r.method]!==void 0&&(f=!0)),f||d()}}let c,h=r.argument;r.argument!==void 0?(typeof h=="object"&&(h=CY.onDeserialize(r.argument,t),h||(h=MA.onDeserialize(r.argument,t))),c=new so(l?(...d)=>u(...d):void 0,r.enabled)):c=new so(l?(...d)=>u(...d):void 0,r.enabled);let u=(...d)=>{let f=a[r.method];typeof f=="function"?h!==void 0?f?.call(a,h):f?.call(a,...d):a[r.method]=h};if(c.method||(c.__debuginfo=t.object?.name),!a||!c.method){let d=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+r.method+'" on',a):console.warn("EventList is missing target - will be ignored",r.target,d,e)}else n.push(c)}let i=new Rn(n);Nn&&console.log(i);let s=t.target;return s!==void 0&&t.path!==void 0&&i.setEventTarget(t.path,s),i}}},xpe=new AA;var MF=Nn;function KO(o,e){let n=pT(o,e);return n!==void 0?n:null}async function Ky(o,e,t,n=null,i){if(!t)return;let s=[],r=n;typeof r=="number"&&(r=new ci(n));let a=new Jd(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=i?.nodeToObjectMap;let l=[];if(t.scenes)for(let c of t.scenes)await IA(a,c,l,s);if(t.children)for(let c of t.children)await IA(a,c,l,s);o.new_scripts_pre_setup_callbacks.push(()=>{for(let c of l)AY(c,a);if(r){PA(t,r);for(let c of t.scenes)PA(c,r)}})}function PA(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)PA(t,e)}}var uv=[];async function IA(o,e,t,n){if(!e)return;let i=e.userData;if(i){let s=i.builtin_components;if(s&&s.length>0)for(let r of s)try{if(r===null)continue;let a=pe.get(r.name);if(a!=null){let l=new a;l.sourceId=o.gltfId,tg(l,r),ty(l,e,!1),t.push({instance:l,compData:r,obj:e})}else MF&&console.debug("unknown component: "+r.name),uv.includes(r.name)||uv.push(r.name)}catch(a){console.error(r.name+" - "+a.message,a)}if(uv.length>0){let r=uv.join(", ");console.warn("unknown components: "+r),uv.length=0}}if(e.children)for(let s of e.children)await IA(o,s,t,n)}function AY(o,e){let{instance:t,compData:n,obj:i}=o;e.object=i,e.target=t;let s=!0;s=eg(t,n,e)===!0,MF&&console.debug("add "+n.name,n,t)}var PY=new oi;async function LA(o){return new Promise((e,t)=>{PY.load(o,e,void 0,t)})}var dv=new Uint8Array(4);dv[0]=255;dv[1]=255;dv[2]=255;dv[3]=255;var RF=new Vs(dv,1,1,vi);function AF(o,e=1){let t="alpha"in o,n=e*e,i=new Uint8Array(4*n),s=Math.floor(o.r*255),r=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let c=0;c<n;c++){let h=c*4;i[h+0]=s,i[h+1]=r,i[h+2]=a,t?i[h+3]=Math.floor(o.alpha*255):i[h+3]=255}let l=new Vs(i,e,e);return l.needsUpdate=!0,l}function PF(o,e,t,n=1,i=3){let a=n*i,l=[o,e,t],c=l.length,h=new Uint8Array(4*c*a),u=new q;for(let f=0;f<i;f++){let g=Math.floor(f/i*c),p=gt.clamp(g+1,0,c-1),m=l[g],y=l[p],v=f/i*c%1;u.lerpColors(m,y,v);let _=Math.floor(u.r*255),b=Math.floor(u.g*255),x=Math.floor(u.b*255);for(let E=0;E<n;E++){let M=(f*n+E)*4;h[M+0]=_,h[M+1]=b,h[M+2]=x,h[M+3]=255}}let d=new Vs(h,n,i);return d.needsUpdate=!0,d}var DA=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},kA=class{loaded=new Map;async loadShader(e){let t=await LA(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((s,r)=>{let a=this.loaded.get(t);a?s(a):r("Shader not found")});let n=await LA(t),i=new DA(e,n);return this.loaded.set(t,i),i}},kpe=new kA;function fv(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let n=0;n<16;n+=4){let i=t[n],s=t[n+1],r=t[n+2],a=t[n+3],l=new ot(i,s,r,a);e.push(l)}return e}var OA=[],TF=[];function BA(o,e){if(OA.length===0)for(let t=0;t<27;t++)OA.push(0);e||(e=OA);for(let t=0;t<27;t++)TF[t]=e[t];e=TF,o.unity_SHAr={value:new ot(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new ot(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new ot(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new ot(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new ot(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new ot(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new ot(e[24],e[25],e[26],1)}}var FA=class{vertexShader;fragmentShader;technique;constructor(e,t,n){this.vertexShader=e,this.fragmentShader=t,this.technique=n}};async function IF(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],n=t.vertexShader,i=t.fragmentShader;if(n!==void 0&&i!==void 0){let s=o.shaders[n],r=o.shaders[i];if(s.uri&&r.uri||s.code&&r.code){if(!s.code&&s.uri&&await CF(s),!r.code&&r.uri&&await CF(r),!s.code||!r.code)return null;let a=o.techniques[e];return new FA(s.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function CF(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let n=await new oi().loadAsync(e);o.code=n.toString()}else o.code=LY(o.uri)}function LY(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var Ba=be("debugshaders"),Dp="NEEDLE_techniques_webgl";var NA=class{objectToWorldMatrix=new it;worldToObjectMatrix=new it;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),fv(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),fv(this.worldToObjectMatrix,this.worldToObject)}};var en=class extends wd{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,Ba&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&bt.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=bt.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&bt.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=bt.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}Ba&&console.log(t);let n=t.array,i=t.texture;this.uniforms.unity_SpecCube0={value:i},BA(this.uniforms,n);let s=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new ot(s,s,s,s)},Ba&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new NA;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&bt.Current.setRequireColor(!0),this.depthTextureUniform&&bt.Current.setRequireDepth(!0)}onBeforeRender(e,t,n,i,s,r){i.attributes.tangent||i.computeTangents(),this.onUpdateUniforms(n,s)}onUpdateUniforms(e,t){let n=bt.Current;e&&(en.viewProjection&&this.uniforms[this._viewProjectionName]&&(en.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),fv(en.viewProjection,en._viewProjectionValues)),en.viewMatrix&&this.uniforms[this._viewMatrixName]&&(en.viewMatrix.copy(e.matrixWorldInverse),fv(en.viewMatrix,en._viewMatrixValues)),this.uniforms[en._worldSpaceCameraPosName]&&en._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=n.rendererData.timeVec4);let i=n?.mainLight;if(i){let a=i.getWorldPosition(en._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},en._mainLightColor.set(i.color.r,i.color.g,i.color.b,0),this.uniforms._MainLightColor={value:en._mainLightColor};let l=i.intensity;en._lightData.z=l,this.uniforms.unity_LightData={value:en._lightData}}if(e&&(en.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=en._viewProjectionValues),en.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=en._viewMatrixValues),this.uniforms[en._worldSpaceCameraPosName]&&(this.uniforms[en._worldSpaceCameraPosName]={value:en._worldSpaceCameraPos}),n.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=n.mainCameraComponent.nearClipPlane,a.z=n.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,l=n.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=n.domWidth,a.y=n.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let s=this.depthTextureUniform;s&&(s.value=n.depthTexture);let r=this.opaqueTextureUniform;if(r&&(r.value=n.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},cr=en;Se(cr,"viewProjection",new it),Se(cr,"_viewProjectionValues",[]),Se(cr,"viewMatrix",new it),Se(cr,"_viewMatrixValues",[]),Se(cr,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),Se(cr,"_worldSpaceCameraPos",new O),Se(cr,"_mainLightColor",new ot),Se(cr,"_mainLightPosition",new O),Se(cr,"_lightData",new ot);var Lx=class{get name(){return Dp}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return Ba&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Dp])return Ba&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let n=t.extensions[Dp].technique;if(n<0)return null;let i=this.parser.json.extensions[Dp];if(!i)return null;Ba&&console.log(i);let s=i.techniques[n];return s?new Promise(async(r,a)=>{let l=await IF(i,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();Ba&&console.log("loadMaterial",t,l);let u={},d=s.uniforms;for(let m in d){let y=m;switch(y){case"_TimeParameters":let v=new ot;u[y]={value:v};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[y]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[y]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[y]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[y]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[y]={value:null};break}}let f=!1;if(t.extensions&&t.extensions[Dp]){let m=t.extensions[Dp];if(m.technique===n){Ba&&console.log(t.name,"Material Properties",m);for(let y in m.values){let v=m.values[y];if(typeof v=="string"){if(v.startsWith("textures/")){let _=v.substring(9),b=Number.parseInt(_);if(b>=0){let x=await this.parser.getDependency("texture",b);x&&(x.encoding=Vr,x.needsUpdate=!0),u[y]={value:x};continue}}switch(y){case"alphaMode":v==="BLEND"&&(f=!0);continue}}if(Array.isArray(v)&&v.length===4){u[y]={value:new ot(v[0],v[1],v[2],v[3])};continue}u[y]={value:v}}}}let g=new cr(this.identifier,{name:t.name??"",uniforms:u,vertexShader:h,fragmentShader:c,lights:!1});switch(u._Cull?.value){case 0:g.side=gi;break;case 1:g.side=ki;break;case 2:g.side=ps;break;default:g.side=ps;break}g.transparent=f,f&&(g.depthWrite=!1),BA(u),g.onUpdateUniforms();for(let m in d){let y=m,v=d[m].type;if(u[y]?.value===void 0)switch(v){case 35678:u[y]={value:RF},console.warn("Missing/unassigned texture, fallback to white: "+y);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+y,d[m]);break}}Ba&&console.log(g.uuid,u),r(g)}):null}};import{EXRLoader as DY}from"three/examples/jsm/loaders/EXRLoader";var UA=be("debugexr"),Ox=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",UA&&console.log(e)}loadTexture(e){let t=this.name,n=this.parser,s=n.json.textures[e];if(UA&&console.log("EXT_texture_exr.loadTexture",e,s),!s.extensions||!s.extensions[t])return null;let r=s.extensions[t],a=new DY(n.options.manager);return UA&&console.log("EXT_texture_exr.loadTexture",r,a),n.loadTextureImage(e,r.source,a)}};var LF="NEEDLE_gameobject_data",Dx=class{get name(){return LF}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let n=0;n<this.parser.json.nodes.length;n++){let i=this.parser.json.nodes[n];if(i&&i.extensions){let s=i.extensions[LF];if(s){let r=this.findAndApplyExtensionData(n,s);t.push(r)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let n=await this.parser.getDependency("node",e);n&&this.applyExtensionData(n,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};var OF="NEEDLE_lightmaps",kY=be("debuglightmapsextension"),pv=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(pv||{}),kx=class{get name(){return OF}parser;registry;source;constructor(e,t,n){this.parser=e,this.registry=t,this.source=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[OF];if(n){let i=n.textures;return i.length?(kY&&console.log(n),new Promise(async(s,r)=>{let a=[];for(let l of i)if(l.pointer){let c=Zd(this.parser,l.pointer).then(h=>{let u=h;u?.isTexture&&(this.registry?(l.type!==0&&(u.encoding=Ct),(u.type==mr||u.type==$a)&&(u.flipY=!0),this.registry.registerTexture(this.source,l.type,u,l.index)):console.log(pv[l.type],l.pointer,u))});a.push(c)}await Promise.all(a),s()})):null}}return null}};import{LightProbeGenerator as FY}from"three/examples/jsm/lights/LightProbeGenerator.js";var HA=be("debugenvlight"),VA=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(VA||{});var Fx=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new ot;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let n=new zA(this.context,t,1);this._lighting[e]=n}getReflection(e){return this._lighting[e]}enableReflection(e){switch(HA&&console.log(this.sceneLightSettings?VA[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let n=this.context.scene,i=t.Source;i.encoding=Ct,i.mapping=Ws,n.environment=i;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,n=PF(t[0],t[1],t[2],64,64);n.encoding=Ct,n.mapping=Ws,this.context.scene.environment=n}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=AF(this.sceneLightSettings.ambientLight,64);t.encoding=Ct,t.mapping=Ws,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return HA&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,n)=>{let i=setInterval(async()=>{let s=this.getReflection(e);s&&(clearInterval(i),t(s.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},zA=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,n=1){this._context=e,this._source=t,this._ambientScale=n,t.mapping=Ws,t.encoding=Ct}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,n=null;if(t){HA&&console.log("GENERATING LIGHT PROBE",t);let i=Math.min(t.image.width,512);n=new ld(i).fromEquirectangularTexture(this._context.renderer,t),this._source=n.texture}if(this._sphericalHarmonicsArray=[],n){let i=FY.fromCubeRenderTarget(this._context.renderer,n);this._lightProbe=i;let s=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=i.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let r=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=r;if(i.sh.scale(s),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:i}}}catch(t){console.error(t)}return null}};var DF="NEEDLE_lighting_settings",mv=be("debugenvlight"),Bx=class{get name(){return DF}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[DF];if(n){mv&&console.log(n);let i=$.addNewComponent(e.scene,GA,!1);i.sourceId=this.sourceId,i.ambientIntensity=n.ambientIntensity,i.ambientLight=new q().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(i.ambientTrilight=n.ambientTrilight.map(s=>new q().fromArray(s))),i.ambientMode=n.ambientMode,i.environmentReflectionSource=n.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(i)}}return null}},GA=class extends ce{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}mv&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(mv&&console.log("enable",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&(this._ambientLightObj=new Cd(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],n=this.ambientTrilight[this.ambientTrilight.length-1],i=new Ed(n,t,this.ambientIntensity);this.gameObject.add(i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{mv&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){mv&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function jA(o){let e=new pf;return o.register(t=>(e.parser=t,e)),e}var WA=class{resolvePath(e){return e.includes("/extensions/builtin_components/")&&(e=e.replace("/extensions/builtin_components/","/userData/components/")),e}};function XA(o,e,t){o.register(i=>new Dx(i)),o.register(i=>new Xy(i)),o.register(i=>new kx(i,e.lightmaps,t)),o.register(i=>new Bx(i,t,e)),o.register(i=>new Lx(i,t)),o.register(i=>new mh(i,t)),o.register(i=>new Zo(i,t,e)),o.register(i=>new Ox(i));let n=o.setAnimationPointerResolver;typeof n=="function"&&n.bind(o)(new WA)}var BY=be("printGltf");var dc=class{context;loader;path;gltf;constructor(e,t,n,i){this.context=e,this.path=t,this.loader=n,this.gltf=i}},kF={};function kp(o,e){if(kF[o])for(let t of kF[o])t(e)}async function BF(o,e,t,n,i){BY&&console.log(t),await o.assets.registerGltf(t),await Ky(o,e,t,n,i)}function Qd(o,e,t,n){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let i=new FF;XA(i,o,t);let r=jA(i);return new Promise((a,l)=>{try{gh(i,o),kp(0,new dc(o,t,i)),i.parse(e,t,async c=>{kp(1,new dc(o,t,i,c)),await BF(o,t,c,n,r),kp(10,new dc(o,t,i,c)),a(c)},c=>{console.error("failed loading "+t,c),a(void 0)})}catch(c){console.error(c),l(c)}})}function Th(o,e,t,n=!1,i){let s=new FF;XA(s,o,e);let a=jA(s);return new Promise((l,c)=>{try{gh(s,o),kp(0,new dc(o,e,s)),s.load(e,async h=>{kp(1,new dc(o,e,s,h)),await BF(o,e,h,t,a),kp(10,new dc(o,e,s,h)),l(h)},h=>{i?.call(s,h)},h=>{console.error("failed loading "+e,h),l(void 0)})}catch(h){console.error(h),c(h)}})}function Nx(o,e,t){let n=$.getComponentInChildren(o,Ss);if(n||(n=$.addNewComponent(o,Ss,!1),n.guid=e.generateUUID()),n&&!$.getComponent(n.gameObject,xi)){let s=$.addNewComponent(n.gameObject,xi,!1);s.guid=e.generateUUID()}if(n&&!$.getComponentInParent(n.gameObject,fo)){let s=$.addNewComponent(n.gameObject,fo,!1);s.guid=e.generateUUID()}if(t&&t.animations?.length>0){let s=t.animations[0],r=$.addNewComponent(o,Rr,!1);r.animations=[s]}let i=!1;o.traverse(s=>{!s||s.isSkinnedMesh===!0&&(i||console.log("Disabling frustum culling for skinned meshes",t),i=!0,s.frustumCulled=!1)})}var qA=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,n,i,s,r,a,l){this.seed=t,this.guid=n,this.file_name=i,this.file_hash=s,this.file_size=r,this.position=a,this.sender=e,this.serverUrl=l}};async function JO(o,e,t){let n=o.name;return n.endsWith(".gltf")||n.endsWith(".glb")?new Promise((i,s)=>{let r=new FileReader;r.readAsDataURL(o),r.onloadend=async a=>{let l=r.result,c=dy(),h=new ci(c),u=await Th(e,l,h,!0);if(u&&u.scene){let d=u.scene;if(!d.guid){let f=new ci(c);d.guid=f.generateUUID()}t&&UY(e.connection,o,c,d,t),Nx(d,h,u),i(u)}}}):(console.warn("Unsupported file type: "+n),console.log(o),null)}async function QO(o,e){return new Promise(async(t,n)=>{let i=dy(),s=new ci(i),r=await Th(e,o.toString(),s,!0);if(r&&r.scene){let a=r.scene;Nx(a,s,r),t(r)}else console.warn("Unsupported file type: "+o.toString())})}function NF(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),HY(e,o);let t=null;try{t=await $y(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{zY(e,o)}if(t){let n=new ci(e.seed),i=await Qd(o,t,null,n);if(i&&i.scene){let s=i.scene;if(Nx(s,n,i),e.parentGuid){let r=$.findByGuid(e.parentGuid,o.scene);"add"in r&&r.add(s)}s.parent||o.scene.add(s),e.position!==null&&s.position.copy(e.position)}}else console.error("download didnt return file")}})}async function UY(o,e,t,n,i){if(!o.connectionId){console.error("Can not upload file - no connection id");return}if(!n.guid){console.error("Can not upload file - no guid",n,n.guid);return}let s=await zO(e,i);if(!s)return;if(!s.filename){console.error("Can not send upload event - no filename",e.name);return}if(!s.hash){console.error("Can not send upload event - no hash",e.name);return}let r=new qA(o.connectionId,t,n.guid,s.filename,s.hash,e.size,n.position,s.url??i);n.parent&&(r.parentGuid=n.parent.guid),o.send("file-spawned",r)}var YA={};function HY(o,e){let t=new ri,n=new _t(t,new Jt({color:65280})),i=new ih(n,5592405);if(YA[o.guid]=i,e.scene.add(i),o.parentGuid){let s=$.findByGuid(o.parentGuid,e.scene);s&&s.add(i)}o.position&&i.position.copy(o.position)}function zY(o,e){let t=o.guid,n=YA[t];n&&(delete YA[t],n.removeFromParent())}var jme=be("debugassets");var Ux=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let n=t[0];n&&n.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
6567
|
+
See https://github.com/felixmariotto/three-mesh-ui/wiki/Using-a-custom-text-type`);return}let a=ED(t,r),l=Array.from?Array.from(a):String(a).split(""),c=e/n.info.size,h=n.common.lineHeight*c,u=n.common.base*c,d=l.map(f=>{let g=this.getGlyphDimensions({textType:s,glyph:f,font:n,fontSize:e}),p=null;return r!==kf&&(i.includes(f)||f.match(/\s/g))&&(p="possible"),f.match(/\n/g)&&(p=SD(r)),{height:g.height,width:g.width,anchor:g.anchor,xadvance:g.xadvance,xoffset:g.xoffset,lineBreak:p,glyph:f,fontSize:e,lineHeight:h,lineBase:u}});if(this.getFontKerning()!=="none")for(let f=1;f<d.length;f++){let g=d[f],p=d[f-1].glyph+d[f].glyph,m=this.getGlyphPairKerning(s,n,p);g.kerning=m*(e/n.info.size)}this.inlines=d}},dg=class extends Df.withBase(Rt.Object3D)(kD,l1,OD,d1,I_){constructor(e){super(e),this.isInlineBlock=!0,this.size=new Rt.Vector2(1,1),this.frame=new x_(this.getBackgroundMaterial()),this.frame.onBeforeRender=()=>{this.updateClippingPlanes&&this.updateClippingPlanes()},this.add(this.frame),this.set(e)}parseParams(){this.width||console.warn("inlineBlock has no width. Set to 0.3 by default"),this.height||console.warn("inlineBlock has no height. Set to 0.3 by default"),this.inlines=[{height:this.height||.3,width:this.width||.3,anchor:0,lineBreak:"possible"}]}updateLayout(){let e=this.getWidth(),t=this.getHeight();if(this.inlines){let n=this.inlines[0];this.position.set(n.width/2,n.height/2,0),this.position.x+=n.offsetX,this.position.y+=n.offsetY}this.size.set(e,t),this.frame.scale.set(e,t,1),this.frame&&this.updateBackgroundMaterial(),this.frame.renderOrder=this.getParentsNumber(),this.childrenInlines.length&&this.computeInlinesPosition(),this.computeChildrenPosition(),this.position.z=this.getOffset()}updateInner(){this.position.z=this.getOffset(),this.frame&&this.updateBackgroundMaterial()}},Ul={fr:[[[{width:.1,chars:[{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"l",upperCase:"L"}]},{width:.1,chars:[{lowerCase:"m",upperCase:"M"}]}],[{width:.2,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"n",upperCase:"N"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],eng:[[[{width:.1,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"l",upperCase:"L"}]}],[{width:.15,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"n",upperCase:"N"}]},{width:.1,chars:[{lowerCase:"m",upperCase:"M"}]},{width:.15,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],ru:[[[{width:1/12,chars:[{lowerCase:"\u0439",upperCase:"\u0419"},{lowerCase:"q",upperCase:"Q"}]},{width:1/12,chars:[{lowerCase:"\u0446",upperCase:"\u0426"},{lowerCase:"w",upperCase:"W"}]},{width:1/12,chars:[{lowerCase:"\u0443",upperCase:"\u0423"},{lowerCase:"e",upperCase:"E"}]},{width:1/12,chars:[{lowerCase:"\u043A",upperCase:"\u041A"},{lowerCase:"r",upperCase:"R"}]},{width:1/12,chars:[{lowerCase:"\u0435",upperCase:"\u0415"},{lowerCase:"t",upperCase:"T"}]},{width:1/12,chars:[{lowerCase:"\u043D",upperCase:"\u041D"},{lowerCase:"y",upperCase:"Y"}]},{width:1/12,chars:[{lowerCase:"\u0433",upperCase:"\u0413"},{lowerCase:"u",upperCase:"U"}]},{width:1/12,chars:[{lowerCase:"\u0448",upperCase:"\u0428"},{lowerCase:"i",upperCase:"I"}]},{width:1/12,chars:[{lowerCase:"\u0449",upperCase:"\u0429"},{lowerCase:"o",upperCase:"O"}]},{width:1/12,chars:[{lowerCase:"\u0437",upperCase:"\u0417"},{lowerCase:"p",upperCase:"P"}]},{width:1/12,chars:[{lowerCase:"\u0445",upperCase:"\u0425"},{lowerCase:"{",upperCase:"["}]},{width:1/12,chars:[{lowerCase:"\u044A",upperCase:"\u042A"},{lowerCase:"}",upperCase:"]"}]}],[{width:1/12,chars:[{lowerCase:"\u0444",upperCase:"\u0424"},{lowerCase:"a",upperCase:"A"}]},{width:1/12,chars:[{lowerCase:"\u044B",upperCase:"\u042B"},{lowerCase:"s",upperCase:"S"}]},{width:1/12,chars:[{lowerCase:"\u0432",upperCase:"\u0412"},{lowerCase:"d",upperCase:"D"}]},{width:1/12,chars:[{lowerCase:"\u0430",upperCase:"\u0410"},{lowerCase:"f",upperCase:"F"}]},{width:1/12,chars:[{lowerCase:"\u043F",upperCase:"\u041F"},{lowerCase:"g",upperCase:"G"}]},{width:1/12,chars:[{lowerCase:"\u0440",upperCase:"\u0420"},{lowerCase:"h",upperCase:"H"}]},{width:1/12,chars:[{lowerCase:"\u043E",upperCase:"\u041E"},{lowerCase:"j",upperCase:"J"}]},{width:1/12,chars:[{lowerCase:"\u043B",upperCase:"\u041B"},{lowerCase:"k",upperCase:"K"}]},{width:1/12,chars:[{lowerCase:"\u0434",upperCase:"\u0414"},{lowerCase:"l",upperCase:"L"}]},{width:1/12,chars:[{lowerCase:"\u0436",upperCase:"\u0416"},{lowerCase:":",upperCase:";"}]},{width:1/12,chars:[{lowerCase:"\u044D",upperCase:"\u042D"},{lowerCase:'"',upperCase:"'"}]},{width:1/12,chars:[{lowerCase:"\u0451",upperCase:"\u0401"},{lowerCase:"|",upperCase:"\\"}]}],[{width:1.5/12,command:"shift",chars:[{icon:"shift"}]},{width:1/12,chars:[{lowerCase:"\u044F",upperCase:"\u042F"},{lowerCase:"z",upperCase:"Z"}]},{width:1/12,chars:[{lowerCase:"\u0447",upperCase:"\u0427"},{lowerCase:"x",upperCase:"X"}]},{width:1/12,chars:[{lowerCase:"\u0441",upperCase:"\u0421"},{lowerCase:"c",upperCase:"C"}]},{width:1/12,chars:[{lowerCase:"\u043C",upperCase:"\u041C"},{lowerCase:"v",upperCase:"V"}]},{width:1/12,chars:[{lowerCase:"\u0438",upperCase:"\u0418"},{lowerCase:"b",upperCase:"B"}]},{width:1/12,chars:[{lowerCase:"\u0442",upperCase:"\u0422"},{lowerCase:"n",upperCase:"N"}]},{width:1/12,chars:[{lowerCase:"\u044C",upperCase:"\u042C"},{lowerCase:"m",upperCase:"M"}]},{width:1/12,chars:[{lowerCase:"\u0431",upperCase:"\u0411"},{lowerCase:",",upperCase:""}]},{width:1/12,chars:[{lowerCase:"\u044E",upperCase:"\u042E"},{lowerCase:".",upperCase:""}]},{width:1.5/12,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.15,command:"switch-set",chars:[{lowerCase:"eng"}]},{width:.15,command:"switch",chars:[{lowerCase:".?12"}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.3,command:"switch",chars:[{lowerCase:"\u0410\u0411\u0412"}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],de:[[[{width:1/11,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:1/11,chars:[{lowerCase:"w",upperCase:"W"}]},{width:1/11,chars:[{lowerCase:"e",upperCase:"E"}]},{width:1/11,chars:[{lowerCase:"r",upperCase:"R"}]},{width:1/11,chars:[{lowerCase:"t",upperCase:"T"}]},{width:1/11,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:1/11,chars:[{lowerCase:"u",upperCase:"U"}]},{width:1/11,chars:[{lowerCase:"i",upperCase:"I"}]},{width:1/11,chars:[{lowerCase:"o",upperCase:"O"}]},{width:1/11,chars:[{lowerCase:"p",upperCase:"P"}]},{width:1/11,chars:[{lowerCase:"\xFC",upperCase:"\xDC"}]}],[{width:1/11,chars:[{lowerCase:"a",upperCase:"A"}]},{width:1/11,chars:[{lowerCase:"s",upperCase:"S"}]},{width:1/11,chars:[{lowerCase:"d",upperCase:"D"}]},{width:1/11,chars:[{lowerCase:"f",upperCase:"F"}]},{width:1/11,chars:[{lowerCase:"g",upperCase:"G"}]},{width:1/11,chars:[{lowerCase:"h",upperCase:"H"}]},{width:1/11,chars:[{lowerCase:"j",upperCase:"J"}]},{width:1/11,chars:[{lowerCase:"k",upperCase:"K"}]},{width:1/11,chars:[{lowerCase:"l",upperCase:"L"}]},{width:1/11,chars:[{lowerCase:"\xF6",upperCase:"\xD6"}]},{width:1/11,chars:[{lowerCase:"\xE4",upperCase:"\xC4"}]}],[{width:2/11,command:"shift",chars:[{icon:"shift"}]},{width:1/11,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:1/11,chars:[{lowerCase:"x",upperCase:"X"}]},{width:1/11,chars:[{lowerCase:"c",upperCase:"C"}]},{width:1/11,chars:[{lowerCase:"v",upperCase:"V"}]},{width:1/11,chars:[{lowerCase:"b",upperCase:"B"}]},{width:1/11,chars:[{lowerCase:"n",upperCase:"N"}]},{width:1/11,chars:[{lowerCase:"m",upperCase:"M"}]},{width:2/11,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],es:[[[{width:.1,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"l",upperCase:"L"}]},{width:.1,chars:[{lowerCase:"\xF1",upperCase:"\xD1"}]}],[{width:.15,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"n",upperCase:"N"}]},{width:.1,chars:[{lowerCase:"m",upperCase:"M"}]},{width:.15,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],el:[[[{width:.1,chars:[{lowerCase:";",upperCase:":"},{lowerCase:"q",upperCase:"Q"}]},{width:.1,chars:[{lowerCase:"\u03C2",upperCase:"\u03C2"},{lowerCase:"w",upperCase:"W"}]},{width:.1,chars:[{lowerCase:"\u03B5",upperCase:"\u0395"},{lowerCase:"e",upperCase:"E"}]},{width:.1,chars:[{lowerCase:"\u03C1",upperCase:"\u03A1"},{lowerCase:"r",upperCase:"R"}]},{width:.1,chars:[{lowerCase:"\u03C4",upperCase:"\u03A4"},{lowerCase:"t",upperCase:"T"}]},{width:.1,chars:[{lowerCase:"\u03C5",upperCase:"\u03A5"},{lowerCase:"y",upperCase:"Y"}]},{width:.1,chars:[{lowerCase:"\u03B8",upperCase:"\u0398"},{lowerCase:"u",upperCase:"U"}]},{width:.1,chars:[{lowerCase:"\u03B9",upperCase:"\u0399"},{lowerCase:"i",upperCase:"I"}]},{width:.1,chars:[{lowerCase:"\u03BF",upperCase:"\u039F"},{lowerCase:"o",upperCase:"O"}]},{width:.1,chars:[{lowerCase:"\u03C0",upperCase:"\u03A0"},{lowerCase:"p",upperCase:"P"}]}],[{width:.1,chars:[{lowerCase:"\u03B1",upperCase:"\u0391"},{lowerCase:"a",upperCase:"A"}]},{width:.1,chars:[{lowerCase:"\u03C3",upperCase:"\u03A3"},{lowerCase:"s",upperCase:"S"}]},{width:.1,chars:[{lowerCase:"\u03B4",upperCase:"\u0394"},{lowerCase:"d",upperCase:"D"}]},{width:.1,chars:[{lowerCase:"\u03C6",upperCase:"\u03A6"},{lowerCase:"f",upperCase:"F"}]},{width:.1,chars:[{lowerCase:"\u03B3",upperCase:"\u0393"},{lowerCase:"g",upperCase:"G"}]},{width:.1,chars:[{lowerCase:"\u03B7",upperCase:"\u0397"},{lowerCase:"h",upperCase:"H"}]},{width:.1,chars:[{lowerCase:"\u03BE",upperCase:"\u039E"},{lowerCase:"j",upperCase:"J"}]},{width:.1,chars:[{lowerCase:"\u03BA",upperCase:"\u039A"},{lowerCase:"k",upperCase:"K"}]},{width:.1,chars:[{lowerCase:"\u03BB",upperCase:"\u039B"},{lowerCase:"l",upperCase:"L"}]}],[{width:.15,command:"shift",chars:[{icon:"shift"}]},{width:.1,chars:[{lowerCase:"\u03B6",upperCase:"\u0396"},{lowerCase:"z",upperCase:"Z"}]},{width:.1,chars:[{lowerCase:"\u03C7",upperCase:"\u03A7"},{lowerCase:"x",upperCase:"X"}]},{width:.1,chars:[{lowerCase:"\u03C8",upperCase:"\u03A8"},{lowerCase:"c",upperCase:"C"}]},{width:.1,chars:[{lowerCase:"\u03C9",upperCase:"\u03A9"},{lowerCase:"v",upperCase:"V"}]},{width:.1,chars:[{lowerCase:"\u03B2",upperCase:"\u0392"},{lowerCase:"b",upperCase:"B"}]},{width:.1,chars:[{lowerCase:"\u03BD",upperCase:"\u039D"},{lowerCase:"n",upperCase:"N"}]},{width:.1,chars:[{lowerCase:"\u03BC",upperCase:"\u039C"},{lowerCase:"m",upperCase:"M"}]},{width:.15,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.15,command:"switch-set",chars:[{lowerCase:"eng"}]},{width:.15,command:"switch",chars:[{lowerCase:".?12"}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]],nord:[[[{width:1/11,chars:[{lowerCase:"q",upperCase:"Q"}]},{width:1/11,chars:[{lowerCase:"w",upperCase:"W"}]},{width:1/11,chars:[{lowerCase:"e",upperCase:"E"}]},{width:1/11,chars:[{lowerCase:"r",upperCase:"R"}]},{width:1/11,chars:[{lowerCase:"t",upperCase:"T"}]},{width:1/11,chars:[{lowerCase:"y",upperCase:"Y"}]},{width:1/11,chars:[{lowerCase:"u",upperCase:"U"}]},{width:1/11,chars:[{lowerCase:"i",upperCase:"I"}]},{width:1/11,chars:[{lowerCase:"o",upperCase:"O"}]},{width:1/11,chars:[{lowerCase:"p",upperCase:"P"}]},{width:1/11,chars:[{lowerCase:"\xE5",upperCase:"\xC5"}]}],[{width:1/11,chars:[{lowerCase:"a",upperCase:"A"}]},{width:1/11,chars:[{lowerCase:"s",upperCase:"S"}]},{width:1/11,chars:[{lowerCase:"d",upperCase:"D"}]},{width:1/11,chars:[{lowerCase:"f",upperCase:"F"}]},{width:1/11,chars:[{lowerCase:"g",upperCase:"G"}]},{width:1/11,chars:[{lowerCase:"h",upperCase:"H"}]},{width:1/11,chars:[{lowerCase:"j",upperCase:"J"}]},{width:1/11,chars:[{lowerCase:"k",upperCase:"K"}]},{width:1/11,chars:[{lowerCase:"l",upperCase:"L"}]},{width:1/11,chars:[{lowerCase:"\xE6",upperCase:"\xC6"}]},{width:1/11,chars:[{lowerCase:"\xF8",upperCase:"\xD8"}]}],[{width:2/11,command:"shift",chars:[{icon:"shift"}]},{width:1/11,chars:[{lowerCase:"z",upperCase:"Z"}]},{width:1/11,chars:[{lowerCase:"x",upperCase:"X"}]},{width:1/11,chars:[{lowerCase:"c",upperCase:"C"}]},{width:1/11,chars:[{lowerCase:"v",upperCase:"V"}]},{width:1/11,chars:[{lowerCase:"b",upperCase:"B"}]},{width:1/11,chars:[{lowerCase:"n",upperCase:"N"}]},{width:1/11,chars:[{lowerCase:"m",upperCase:"M"}]},{width:2/11,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]],[[{width:.1,chars:[{lowerCase:"1"}]},{width:.1,chars:[{lowerCase:"2"}]},{width:.1,chars:[{lowerCase:"3"}]},{width:.1,chars:[{lowerCase:"4"}]},{width:.1,chars:[{lowerCase:"5"}]},{width:.1,chars:[{lowerCase:"6"}]},{width:.1,chars:[{lowerCase:"7"}]},{width:.1,chars:[{lowerCase:"8"}]},{width:.1,chars:[{lowerCase:"9"}]},{width:.1,chars:[{lowerCase:"0"}]}],[{width:.1,chars:[{lowerCase:"@"}]},{width:.1,chars:[{lowerCase:"#"}]},{width:.1,chars:[{lowerCase:"|"}]},{width:.1,chars:[{lowerCase:"_"}]},{width:.1,chars:[{lowerCase:"&"}]},{width:.1,chars:[{lowerCase:"-"}]},{width:.1,chars:[{lowerCase:"+"}]},{width:.1,chars:[{lowerCase:"("}]},{width:.1,chars:[{lowerCase:")"}]},{width:.1,chars:[{lowerCase:"/"}]}],[{width:.1,chars:[{lowerCase:"="}]},{width:.1,chars:[{lowerCase:"*"}]},{width:.1,chars:[{lowerCase:'"'}]},{width:.1,chars:[{lowerCase:"'"}]},{width:.1,chars:[{lowerCase:":"}]},{width:.1,chars:[{lowerCase:";"}]},{width:.1,chars:[{lowerCase:"!"}]},{width:.1,chars:[{lowerCase:"?"}]},{width:.2,command:"backspace",chars:[{icon:"backspace"}]}],[{width:.2,command:"switch",chars:[{lowerCase:".?12"}]},{width:.1,chars:[{lowerCase:","}]},{width:.4,command:"space",chars:[{icon:"space"}]},{width:.1,chars:[{lowerCase:"."}]},{width:.2,command:"enter",chars:[{icon:"enter"}]}]]]},kj=new Rt.TextureLoader,w_=class extends Df.withBase(Rt.Object3D)(l1,I_){constructor(e){e||(e={}),e.width||(e.width=1),e.height||(e.height=.4),e.margin||(e.margin=.003),e.padding||(e.padding=.01),super(e),this.currentPanel=0,this.isLowerCase=!0,this.charsetCount=1;let t;if(e.language||navigator.language)switch(e.language||navigator.language){case"fr":case"fr-CH":case"fr-CA":t=Ul.fr;break;case"ru":this.charsetCount=2,t=Ul.ru;break;case"de":case"de-DE":case"de-AT":case"de-LI":case"de-CH":t=Ul.de;break;case"es":case"es-419":case"es-AR":case"es-CL":case"es-CO":case"es-ES":case"es-CR":case"es-US":case"es-HN":case"es-MX":case"es-PE":case"es-UY":case"es-VE":t=Ul.es;break;case"el":this.charsetCount=2,t=Ul.el;break;case"nord":t=Ul.nord;break;default:t=Ul.eng;break}else t=Ul.eng;this.keys=[],this.panels=t.map(n=>{let i=e.height/n.length-e.margin*2,s=new Fh({width:e.width+e.padding*2,height:e.height+e.padding*2,offset:0,padding:e.padding,fontFamily:e.fontFamily,fontTexture:e.fontTexture,backgroundColor:e.backgroundColor,backgroundOpacity:e.backgroundOpacity});return s.charset=0,s.add(...n.map(r=>{let a=new Fh({width:e.width,height:i,margin:e.margin,contentDirection:"row",justifyContent:"center"});a.frame.visible=!1;let l=[];return r.forEach(c=>{let h=new Fh({width:e.width*c.width-e.margin*2,height:i,margin:e.margin,justifyContent:"center",offset:0}),u=c.chars[s.charset].lowerCase||c.chars[s.charset].icon||"undif";if(u==="enter"&&e.enterTexture||u==="shift"&&e.shiftTexture||u==="backspace"&&e.backspaceTexture){let d=(()=>{switch(u){case"backspace":return e.backspaceTexture;case"enter":return e.enterTexture;case"shift":return e.shiftTexture;default:console.warn("There is no icon image for this key")}})();kj.load(d,f=>{h.add(new dg({width:h.width*.65,height:h.height*.65,backgroundSize:"contain",backgroundTexture:f}))})}else h.add(new ug({content:u,offset:0}));h.type="Key",h.info=c,h.info.input=u,h.panel=s,l.push(h),this.keys.push(h)}),a.add(...l),a})),s}),this.add(this.panels[0]),this.set(e)}setNextPanel(){this.panels.forEach(e=>{this.remove(e)}),this.currentPanel=(this.currentPanel+1)%this.panels.length,this.add(this.panels[this.currentPanel]),this.update(!0,!0,!0)}setNextCharset(){this.panels[this.currentPanel].charset=(this.panels[this.currentPanel].charset+1)%this.charsetCount,this.keys.forEach(e=>{if(!this.panels[this.currentPanel].getObjectById(e.id))return;let n=e.info.chars[e.panel.charset]||e.info.chars[0],i=this.isLowerCase||!n.upperCase?n.lowerCase:n.upperCase;if(!e.childrenTexts.length)return;let s=e.childrenTexts[0];e.info.input=i,s.set({content:i}),s.update(!0,!0,!0)})}toggleCase(){this.isLowerCase=!this.isLowerCase,this.keys.forEach(e=>{let t=e.info.chars[e.panel.charset]||e.info.chars[0],n=this.isLowerCase||!t.upperCase?t.lowerCase:t.upperCase;if(!e.childrenTexts.length)return;let i=e.childrenTexts[0];e.info.input=n,i.set({content:n}),i.update(!0,!0,!0)})}parseParams(){}updateLayout(){}updateInner(){}},BD=()=>da.update(),ND={Block:Fh,Text:ug,InlineBlock:dg,Keyboard:w_,FontLibrary:hg,update:BD,TextAlign:C_,Whitespace:T_,JustifyContent:M_,AlignItems:S_,ContentDirection:E_};typeof global<"u"&&(global.ThreeMeshUI=ND);var Fj=ND,Bj=Rs.g1,pg=Rs.gO,Nj=Rs.km,Uj=Rs.zV,Hj=Rs.ol,zj=Rs.uM,f1=Rs.N1,p1=Rs.xv,Vj=Rs.PH,Gj=Rs.UH,Wj=Rs.ZP,jj=Rs.Vx;var Ir=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};var Xj=be("debugeventsystem"),uo=class extends ce{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,uo.systems.length<=0&&uo.systems.push(...$.findObjectsOfType(uo,e)));for(let n of uo.systems)if(n.context===e)return;let t=new De;$.addNewComponent(t,uo),e.scene.add(t)}static ensureUpdateMeshUI(e,t){Lr.update(e,t)}static markUIDirty(e){Lr.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),uo.systems.push(this)}onDestroy(){uo.systems.splice(uo.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}onEnable(){Vt.addEventListener("select-start",(t,n)=>{if(!n.grab)return;Lr.resetLastSelected();let i=new Ir;i.inputSource=t,i.isDown=t.selectionDown,i.isUp=t.selectionUp,i.isPressed=t.selectionPressed,i.isClicked=!1,n.grab&&!this.handleEvents(n.grab,i)&&(n.grab=null)});let e=new Zn;Vt.addEventListener("select-end",(t,n)=>{if(!n.grab)return;let i=new Ir;i.inputSource=t,i.isDown=t.selectionDown,i.isUp=t.selectionUp,i.isPressed=t.selectionPressed,i.isClicked=t.selectionClick,this.handleEvents(n.grab,i)}),Vt.addEventListener("update",t=>{e.ray=t.getRay();let n=this.performRaycast(e);if(!n)return;let i=new Ir;i.inputSource=t,this.handleIntersections(n,i)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerDown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),wt.IsInWebXR||this.context.input.isKeyPressed(18))return;if(!this._didMove){let s=this.context.input.getPointerPositionRC(0);if(s&&s.x===0&&s.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new Ir(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let n=null,i=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(n=$.getComponent(this.context.mainCameraComponent.gameObject,xs)??null,n&&(i=n.enabled,n.enabled=!1)),this.handleIntersections(e,t),n&&(this.orbitControl=n,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let n=$.getComponentsInParent(t,ce,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let i=0;i<n.length;i++){let s=n[i];if(!s.gameObject||s.destroyed)continue;let r=s;r.onPointerExit&&r.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let n=t.performRaycast(e);n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((t,n)=>t.distance-n.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let n of e){let{object:i}=n;if(this.handleEvents(i,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let n=e[t],i=n.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Xj&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let n=e.parent,i=!1,s=t.isClicked??!1,r=null;if(n&&n.isUI){let a=(t.isPressed||t.isClicked)??!1;if(n.shadowComponentOwner){let l=n.shadowComponentOwner.gameObject;if(l){if(r=this.tryFindCanvasGroup(l),r?.blocksRaycasts===!1)return!1;if(r?.interactable===!1)return!0;let c=this.handleMeshUIIntersection(e,a);e=l,i=!0}}if(!i&&this.handleMeshUiObjectWithoutShadowDom(n,a))return!0}if(this.objectsHoveredThisFrame.push(e),r===null||r.interactable){let a=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let l=$.getComponentsInParent(e,ce,this.handleEventsArray);for(let c=0;c<l.length;c++){if(t.used)return!0;if(l[c].destroyed)continue;let h=l[c];h.interactable!==!1&&(h.onPointerEnter&&(a||h.onPointerEnter(t)),t.isDown&&h.onPointerDown&&!this.raisedPointerDownEvents.includes(h)&&(h.onPointerDown(t),this.raisedPointerDownEvents.push(h)),t.isUp&&h.onPointerUp&&h.onPointerUp(t),t.isClicked&&h.onPointerClick&&h.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let n=Lr.updateState(e,t);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Lr.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];Lr.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?$.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=$.foreachComponent(e,n=>{let i=n;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}},Mi=uo;Se(Mi,"didSearchEventSystem",!1),Se(Mi,"systems",[]);var Lr=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let n of this.lastUpdateFrame)if(n.context===t){if(t.time.frameCount===n.frame)return;n.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let n=null;if(e&&(n=this.findBlockInParent(e),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;t?(this.lastSelected=n,n.states.pressed&&n.setState("pressed")):n.states.hovered&&n.setState("hovered"),this.needsUpdate=!0}return n}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};Se(Lr,"lastSelected",null),Se(Lr,"lastUpdateFrame",[]),Se(Lr,"needsUpdate",!1);var Nf="./include";pg.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var di=class extends ce{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Mi.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=$.getComponentInParent(this.gameObject,fa)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=$.getComponentInParent(n,di),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}if(e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this,e.traverse(i=>{i.shadowComponentOwner===void 0&&(i.shadowComponentOwner=this)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let i=this._parentComponent.shadowComponent;i&&i?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Qr&&e.add(new xr(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,n){if(!!e&&e.shadowComponentOwner===t){n(e);for(let i of e.children)this.traverseOwnedShadowComponents(i,t,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},fa=class extends di{awake(){super.awake()}};var UD=be("debugui"),Uf=class{width;height},Bh=class{x;y;width;height},rs=class extends di{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new O),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new it,this.rectBlock=new De,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new O),ef(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(UD&&console.log("updating",this.name),this.applyTransform()),Mi.ensureUpdateMeshUI(Bf,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,n=this.pivot.y*2-1;n-=this.anchoredPosition.y*.05;let i=this.sizeDelta.x*t,s=this.sizeDelta.y*n;e.x-=i*.5,e.y-=s*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},UD&&console.log(this.name,e);let t=new pg(e);return this._createdBlocks.push(t),t}};ne([te(Bh)],rs.prototype,"rect",2),ne([te(_e)],rs.prototype,"sizeDelta",2),ne([te(O)],rs.prototype,"anchoredPosition3D",2),ne([te(_e)],rs.prototype,"pivot",2);var As=class extends di{get color(){return this._color||(this._color=new gn(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new gn(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=this.gameObject.getComponent(rs)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),ef(this,"_color",()=>jO(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};ne([te(gn)],As.prototype,"color",1),ne([te()],As.prototype,"raycastTarget",2);var pa=class extends As{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var L_=class{texture;rect};ne([te(Nt)],L_.prototype,"texture",2);var ma=class extends pa{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new q(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};ne([te(L_)],ma.prototype,"sprite",2);var Nh=class extends pa{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};ne([te(Nt)],Nh.prototype,"mainTexture",2);var Hf=be("debugbutton");var er=class extends ce{onClick;_isHovered=!1;onPointerEnter(e){Hf&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){Hf&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){Hf&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){Hf&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){Hf&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Hf&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=$.getComponent(this.gameObject,ma),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),n={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(n);let i=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};e.setupState(s);let r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);let l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);let h=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};ne([te(Rn)],er.prototype,"onClick",2),ne([te()],er.prototype,"colors",2),ne([te()],er.prototype,"transition",2),ne([te()],er.prototype,"animationTriggers",2),ne([te(ws)],er.prototype,"animator",2),ne([te()],er.prototype,"interactable",1);var m1=class extends fa{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof m1||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),Kd(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(di))Kd(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let i=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-i;let s=Math.tan(gt.toRadians(e.fieldOfView)*i)*(e.aspect*1.333333),r=s*(this.context.domHeight/this.context.domWidth);t.scale.x=-s,t.scale.y=r;break;case 2:break}}},Ti=m1;ne([te()],Ti.prototype,"renderOnTop",1),ne([te()],Ti.prototype,"depthWrite",1),ne([te()],Ti.prototype,"doubleSided",1),ne([te()],Ti.prototype,"castShadows",1),ne([te()],Ti.prototype,"receiveShadows",1),ne([te()],Ti.prototype,"renderMode",1),ne([te(Ti)],Ti.prototype,"rootCanvas",1);var ga=class extends ce{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of $.getComponentsInChildren(this.gameObject,As,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};ne([te()],ga.prototype,"alpha",1),ne([te()],ga.prototype,"interactable",2),ne([te()],ga.prototype,"blocksRaycasts",2);var qj=be("debugtext");var Hn=class extends As{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){qj&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let n=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(n,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(n,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,n,i=!1){let s={};s.hiddenOverflow=t,s.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(s,i);let r=e.createNewBlock(s);return n&&(Array.isArray(n)?r.add(...n):r.add(n)),r}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((n,i)=>n+i.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e.shadowComponentOwner===void 0&&(e.shadowComponentOwner=this)})}createText(e,t,n){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),n){let i=this.getNextTag(e);if(i)i.startIndex>0&&this.createText(e.substring(0,i.startIndex),t,!1);else return this.createText(e,t,!1);let s=[];for(;i;){let r=this.getNextTag(e,i.endIndex);if(r){let a=this.getText(e,i,r);this.handleTag(i,t,s),this.createText(a,t,!1)}else{let a=e.substring(i.endIndex);this.handleTag(i,t,s),this.createText(a,t,!1)}i=r}}else{let i={...t};i.content=e;let s=new p1(i);this._textMeshUi.push(s),this._textContainer&&this._textContainer.add(s)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,n={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let i=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;i=!0;let r=this._textMeshUi[s];!r.textContent||(Kd(r,n),e[s]=!0)}if(!i)break;yield}}handleTag(e,t,n){if(e.isEndTag){if(n.length>0){let i=n.pop();if(i)for(let s in i.previousValues){let r=i.previousValues[s];t[s]=r}}}else if(e.type.includes("color")){let i=new mg(e,{fontColor:t.fontColor});if(n.push(i),e.type.length>6){let s=e.type.substring(6);t.fontColor=Yj(s)}else t.fontColor=new q(1,1,1)}else if(e.type=="b"){let i=new mg(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});n.push(i),this.setFont(t,1)}else if(e.type=="i"){let i=new mg(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});n.push(i),this.setFont(t,2)}}getText(e,t,n){return e.substring(t.endIndex,n.startIndex)}getNextTag(e,t=0){let n=e.indexOf("<",t),i=e.indexOf(">",n);if(n>=0&&i>=0){let s=e.substring(n+1,i);return{type:s,startIndex:n,endIndex:i+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){let n=this.getFontName(t),i=n;i?.endsWith("-msdf.json")||(i+="-msdf.json"),e.fontFamily=i;let s=n;s?.endsWith(".png")||(s+=".png"),e.fontTexture=s}getFontName(e){return this.font?this.font:null}};ne([te(Ti)],Hn.prototype,"canvas",2),ne([te()],Hn.prototype,"alignment",2),ne([te()],Hn.prototype,"verticalOverflow",2),ne([te()],Hn.prototype,"horizontalOverflow",2),ne([te()],Hn.prototype,"lineSpacing",2),ne([te()],Hn.prototype,"supportRichText",2),ne([te()],Hn.prototype,"font",2),ne([te()],Hn.prototype,"fontStyle",2),ne([te()],Hn.prototype,"text",1),ne([te()],Hn.prototype,"fontSize",1);var mg=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Yj(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let n=e>>16&255,i=e>>8&255,s=e&255;return new q(n/255,i/255,s/255)}switch(o){case"black":return new q(0,0,0);case"white":return new q(1,1,1);case"red":return new q(1,0,0);case"lime":return new q(0,1,0);case"blue":return new q(0,0,1);case"yellow":return new q(1,1,0);case"cyan":return new q(0,1,1);case"magenta":return new q(1,0,1);case"silver":return new q(.75,.75,.75);case"gray":return new q(.5,.5,.5);case"maroon":return new q(.5,0,0);case"olive":return new q(.5,.5,0);case"green":return new q(0,.5,0);case"purple":return new q(.5,0,.5);case"teal":return new q(0,.5,.5);case"navy":return new q(0,0,.5);case"darkred":return new q(.54,0,0);case"brown":return new q(.55,.27,0);case"firebrick":return new q(.69,.13,.13);case"crimson":return new q(.86,.08,.24);case"tomato":return new q(1,.39,.28);case"coral":return new q(1,.49,.31);case"indianred":return new q(.6,.31,.51);case"lightcoral":return new q(.94,.5,.5);case"darkorange":return new q(1,.55,0);case"orange":return new q(1,.65,0);case"gold":return new q(1,.84,0);case"darkgoldenrod":return new q(.72,.53,.04);case"goldenrod":return new q(.85,.65,.13);case"palegoldenrod":return new q(.93,.87,.67);case"darkkhaki":return new q(.74,.7,.42);case"khaki":return new q(.94,.9,.55);case"yellowgreen":return new q(.6,.8,.19);case"darkolivegreen":return new q(.33,.42,.18);case"olivedrab":return new q(.42,.56,.14);case"lawngreen":return new q(.49,.99,0);case"chartreuse":return new q(.5,1,0);case"greenyellow":return new q(.68,1,.18);case"darkgreen":return new q(0,.39,0);case"forestgreen":return new q(.13,.55,.13);case"limegreen":return new q(.19,.8,.19);case"lightgreen":return new q(.56,.93,.56);case"palegreen":return new q(.59,.98,.59);case"darkseagreen":return new q(.56,.74,.56);case"mediumspringgreen":return new q(0,.98,.6);case"springgreen":return new q(0,1,.5);case"seagreen":return new q(.18,.31,.31);case"mediumaquamarine":return new q(.4,.8,.66);case"mediumseagreen":return new q(.24,.7,.44);case"lightseagreen":return new q(.13,.7,.67);case"darkslategray":return new q(.18,.31,.31);case"darkcyan":return new q(0,.55,.55);case"aqua":return new q(0,1,1);case"lightcyan":return new q(.8,1,1);case"darkturquoise":return new q(0,.81,.82);case"turquoise":return new q(0,.82,.82);case"mediumturquoise":return new q(.28,.82,.8);case"paleturquoise":return new q(.68,1,.93);case"aquamarine":return new q(.5,1,.83);case"powderblue":return new q(.69,.88,.9);case"cadetblue":return new q(.37,.62,.63);case"steelblue":return new q(.27,.51,.71);case"cornflowerblue":return new q(.39,.58,.93);case"deepskyblue":return new q(0,.7,1);case"dodgerblue":return new q(.12,.56,1);case"lightblue":return new q(.68,.85,.9);case"skyblue":return new q(.53,.81,.92);case"lightskyblue":return new q(.53,.81,.98);case"midnightblue":return new q(.18,.18,.31);case"darkblue":return new q(0,0,.55);case"mediumblue":return new q(0,0,.82);case"royalblue":return new q(.25,.41,.88);case"blueviolet":return new q(.54,.17,.89);case"indigo":return new q(.29,0,.51);case"darkslateblue":return new q(.28,.24,.55);case"slateblue":return new q(.42,.35,.8);case"mediumslateblue":return new q(.48,.41,.9);case"mediumpurple":return new q(.58,.44,.86);case"darkmagenta":return new q(.55,0,.55);case"darkviolet":return new q(.58,0,.83);case"darkorchid":return new q(.6,.2,.8);case"mediumorchid":return new q(.73,.33,.83);case"thistle":return new q(.84,.75,.85);case"plum":return new q(.87,.63,.87);case"violet":return new q(.93,.51,.93);case"fuchsia":return new q(1,0,1);case"orchid":return new q(.85,.44,.84);case"mediumvioletred":return new q(.78,.08,.52);case"palevioletred":return new q(.86,.44,.58);case"hotpink":return new q(1,.4,.71);case"deeppink":return new q(1,.08,.58);case"lightpink":return new q(1,.71,.76);case"pink":return new q(1,.75,.78);case"antiquewhite":return new q(.98,.92,.84);case"beige":return new q(.96,.96,.86);case"bisque":return new q(1,.89,.77);case"blanchedalmond":return new q(1,.92,.82);case"wheat":return new q(.96,.87,.87);case"cornsilk":return new q(1,.97,.86);case"lemonchiffon":return new q(1,.98,.8);case"lightgoldenrodyellow":return new q(.98,.98,.82);case"lightyellow":return new q(1,1,.8);case"saddlebrown":return new q(.55,.27,.07);case"sienna":return new q(.63,.32,.18);case"chocolate":return new q(.82,.41,.12);case"peru":return new q(.82,.52,.25);case"sandybrown":return new q(.96,.64,.38);case"burlywood":return new q(.87,.72,.53);case"tan":return new q(.82,.71,.55);case"rosybrown":return new q(.74,.56,.56);case"moccasin":return new q(1,.89,.71);case"navajowhite":return new q(1,.87,.68);case"peachpuff":return new q(1,.85,.73);case"mistyrose":return new q(1,.89,.88);case"lavenderblush":return new q(1,.94,.93);case"linen":return new q(.98,.94,.9);case"oldlace":return new q(.99,.96,.9);case"papayawhip":return new q(1,.94,.84);case"seashell":return new q(1,.96,.93);case"mintcream":return new q(.98,1,.98);case"slategray":return new q(.44,.5,.56);case"lightslategray":return new q(.47,.53,.6);case"lightsteelblue":return new q(.69,.77,.87);case"lavender":return new q(.9,.9,.98);case"floralwhite":return new q(1,.98,.98);case"aliceblue":return new q(.94,.97,1);case"ghostwhite":return new q(.97,.97,1);case"honeydew":return new q(.94,1,.94);case"ivory":return new q(1,1,.94);case"azure":return new q(.94,1,1);case"snow":return new q(1,.98,.98);case"dimgray":return new q(.4,.4,.4);case"darkgray":return new q(.66,.66,.66);case"lightgray":return new q(.83,.83,.83);case"gainsboro":return new q(.86,.86,.86);case"whitesmoke":return new q(.96,.96,.96)}return new q(1,1,1)}var Uh=be("debuginputfield"),vt=class extends ce{get text(){return this.textComponent?.text??""}get isFocused(){return vt.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Uh&&console.log(this.name,this)}onEnable(){vt.htmlField||(vt.htmlField=document.createElement("input"),vt.htmlField.classList.add("ar"),document.body.appendChild(vt.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),vt.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&$.setActive(this.placeholder.gameObject,!1)}onDisable(){vt.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Uh&&console.log("CLICK",e,vt.active),vt.activeTime=this.context.time.time,vt.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();vt.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-vt.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(vt.active!==this&&(Uh&&console.log("Select",this.name,this,vt.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,vt.htmlField?.value),vt.active?.onDeselected(),vt.active=this,this.placeholder&&$.setActive(this.placeholder.gameObject,!1),vt.htmlField)){if(vt.htmlField.value=this.textComponent?.text||"",Uh&&console.log("set input field value",vt.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(vt.htmlField.style.width="0px",vt.htmlField.style.height="0px",e.append(vt.htmlField))}this.selectInputField()}}onDeselected(){vt.active===this&&(vt.active=null,Uh&&console.log("Deselect",this.name,this),vt.htmlField&&(vt.htmlField.blur(),document.body.append(vt.htmlField),vt.htmlField.style.width="",vt.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&$.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(vt.active===this){if(Uh&&console.log(e.code,e,vt.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}vt.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&$.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&vt.htmlField){if(this.textComponent.text!==vt.htmlField.value){Uh&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=vt.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=vt.htmlField.value}}selectInputField(){vt.htmlField&&(vt.htmlField.setSelectionRange(vt.htmlField.value.length,vt.htmlField.value.length),vt.htmlField.focus())}},Ps=vt;Se(Ps,"active",null),Se(Ps,"activeTime",-1),Se(Ps,"htmlField",null),ne([te(Hn)],Ps.prototype,"textComponent",2),ne([te(Hn)],Ps.prototype,"placeholder",2),ne([te(Rn)],Ps.prototype,"onValueChanged",2),ne([te(Rn)],Ps.prototype,"onEndEdit",2);var HD=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(HD||{}),zf=class extends di{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=HD[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",n=this.gameObject.getComponent(rs);if(!n){console.error("Missing rect transform, please add this component inside a canvas");return}let i={...n.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Nf+"/"+t+"-msdf.json",fontTexture:Nf+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new q(this.colors.keyboardBack),backspaceTexture:Nf+"/backspace.png",shiftTexture:Nf+"/shift.png",enterTexture:Nf+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},s=this.gameObject.scale;i.width*=this.gameObject.scale.x,i.height*=this.gameObject.scale.y,i.fontSize*=Math.max(s.x,s.y),this.keyboard=new f1(i),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(r=>{r.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new q(this.colors.button),backgroundOpacity:1}}),r.setState("normal"),r.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new q(this.colors.hovered),backgroundOpacity:1}}),r.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new q(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=r.info.input,l=r.info.command;if(this._lastKeyPressed!==a)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||l=="switch"||l=="shift"||l=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=a,l)switch(l){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
|
|
6568
|
+
`);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else r.info.input!==void 0&&this.tryAppend(r.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var va=class extends ce{reverseArrangement=!1},Vf=class extends va{},Gf=class extends va{},Wf=class extends va{};var Hh=class extends ce{awake(){Mi.createIfNoneExists(this.context)}onEnable(){Mi.instance?.register(this)}onDisable(){Mi.instance?.unregister(this)}performRaycast(e=null){return null}},fo=class extends Hh{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new Zn,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},jf=class extends fo{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import{HTMLMesh as Zj}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as Jj}from"three/examples/jsm/interactive/InteractiveGroup.js";var Xf=class extends ce{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new Jj(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let n=new Zj(e);t.add(n),n.visible=!1,console.log(n);let i=n.material;i.transparent=!0,setTimeout(()=>{n.visible=!0;let s=ay(this.gameObject).clone();ly(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let r=new On;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);let a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){let h=a/l;a>l?n.scale.set(1/a,1/l/h,1):n.scale.set(1/a*h,1/l,1)}else n.scale.set(1/a,1/l,1);let c=this.gameObject.scale;n.scale.multiply(c)},1)}};var O_=class extends ce{toggleKey=80;update(){this.context.input.isKeyDown(80)&&this.context.domElement.classList.toggle("presentation-mode")}};var Ax=Du(EA(),1);var SA=class{id=0;points=[];line=new Ax.MeshLine;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let n=t.options;n&&Object.assign(this.material,n)}this.mesh=new _t(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=SA.wp;t.set(e.x,e.y,e.z);let n=this.mesh?.parent;return n&&(t=n.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new Ax.MeshLineMaterial({color:10066329,lineWidth:.01})},Op=SA;Se(Op,"wp",new O);var Iu=class extends ce{startLine(e,t){let n=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,n,!0,t)}updateLine(e,t){let n=this.inFlight[e.id];if(!n)return;t.point&&(t.point=n.appendPoint(t.point));let i=this.buffer[e.id];i&&(t.point&&i.push(t.point.x,t.point.y,t.point.z),i.length>5&&(this.sendLineUpdate(n,!1,void 0,i),i.length=0))}endLine(e,t=!0){let n=this.inFlight[e.id];if(!n)return;this.finished.push(n),delete this.inFlight[e.id],t&&this.sendLineUpdate(n,!0,0);let i=this.buffer[e.id];if(i){delete this.buffer[e.id];let s=i;s.length=0,this.freeBuffer.push(s)}return n}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let n=$.findByGuid(t,this.context.scene);if(!!n)return this.internalStartLine(n,e,!1),this.inFlight[e]}internalStartLine(e,t,n=!0,i){let s=new Op(e??this.context.scene,i);s.id=t,this.inFlight[t]=s,n&&this.sendLineStart(s);let r;return this.freeBuffer.length<=0?r=new Array:r=this.freeBuffer.pop(),this.buffer[t]=r,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,n,i){if(e){let s={parentGuid:e.mesh.parent.guid,guid:e.id,points:i?[...i]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:n!==void 0?n:e.points.length,finished:t};this.context.connection.send("line-update",s)}}};var SF=Du(EA(),1);var Px=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new O,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},Ix=class extends ce{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=$.getComponent(this.gameObject,Iu),this.lines||(this.lines=$.addNewComponent(this.gameObject,Iu))),this.orbit=$.findObjectOfType(xs,this.context)??void 0,this._states.mouse=new Px;let e={};Vt.addEventListener("select-start",(t,n)=>{e[t.controller.uuid]=!0}),Vt.addEventListener("update",(t,n)=>{if(e[t.controller.uuid]===!0){let i=t.getRay();this.updateLine(t.controller.uuid,i,!0,!1,!1)}}),Vt.addEventListener("select-end",(t,n)=>{e[t.controller.uuid]=!1;let i=t.getRay();this.updateLine(t.controller.uuid,i,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);Ix._raycaster.setFromCamera(t,this.context.mainCamera);let n=Ix._raycaster.ray;this.updateLine("mouse",n,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed(18))}updateLine(e,t,n,i,s=!1){let r=this._states[e];if(r||(this._states[e]=new Px,r=this._states[e]),i)r.isDrawing=!1,r.currentHandle&&(this.lines.endLine(r.currentHandle),r.currentHandle=null);else if(n){if(s)return r;let a=this.getHit(t),l=null,c=r.prevDistance;if(a)r.currentHandle||(r.maxDistance=a.distance),l=a.point,l.add(a.face.normal.multiplyScalar(.01)),r.prevDistance=a.distance;else if(r.maxDistance>0){let h=r.maxDistance;if(!r.currentHandle&&r.lastHit){let u=st(this.context.mainCamera);h=r.lastHit.distanceTo(u)}l=t.origin.add(t.direction.multiplyScalar(r.maxDistance)),r.prevDistance=r.maxDistance}if(l){if(!r.currentHandle){let h=r.lastParent??this.gameObject;this.addToPaintedObject&&a&&(h=a.object),r.lastParent=h,r.currentHandle=this.lines.startLine(h,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(r.prevDistance>r.maxDistance||Math.abs(c-r.prevDistance)>.2)){let h=r.maxDistance;l=t.origin.add(t.direction.multiplyScalar(h)),r.prevDistance=h}if(r.lastHit&&r.lastHit.distanceTo(l)<r.prevDistance*.01)return r;this.lines.updateLine(r.currentHandle,{point:l}),r.lastHit.copy(l)}r.isDrawing=r.currentHandle!==null}return r}_raycastOptions=new Zn;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let n of t)if(!!$.isActiveInHierarchy(n.object))return n}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ss.colorFromHashCode(ss.hashCode(this.context.connection.connectionId)):e=new q("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new SF.MeshLineMaterial({color:e,lineWidth:gt.lerp(.005,.01,Math.random())})}},cv=Ix;Se(cv,"_raycaster",new zo);var hv=class extends ce{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let n=$.getComponent(t,xo);n&&(n.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=xo.all.length-1;t>=0;t--){let n=xo.all[t];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}};ne([te(Wi)],hv.prototype,"asset",2);var lr=class extends ce{static get all(){return lr._all}static get local(){return lr._local}static isLocalPlayer(e){return e instanceof De?$.getComponentInParent(e,lr)?.isLocalPlayer??!1:e instanceof $i?$.getComponentInParent(e.gameObject,lr)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&lr.local.push(this),lr.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){Bd(this.gameObject,this.context.connection)}onDestroy(){if(lr.all.splice(lr.all.indexOf(this),1),this.isLocalPlayer){let e=lr._local.indexOf(this);e>=0&&lr._local.splice(e,1)}}},xo=lr;Se(xo,"_all",[]),Se(xo,"_local",[]),ne([h_(),te()],xo.prototype,"owner",2);pe.add("AlignmentConstraint",_l);pe.add("Animation",Rr);pe.add("AnimationCurve",bh);pe.add("Animator",ws);pe.add("AnimatorController",Cr);pe.add("AudioListener",Ar);pe.add("AudioSource",$t);pe.add("AvatarModel",xh);pe.add("AvatarLoader",bl);pe.add("AxesHelper",Ko);pe.add("BasicIKConstraint",$d);pe.add("BoxHelperComponent",ts);pe.add("Camera",Bt);pe.add("Collider",Kr);pe.add("SphereCollider",xl);pe.add("BoxCollider",wl);pe.add("InstantiateOptions",hn);pe.add("UnityObject",nf);pe.add("DeleteBox",wh);pe.add("Deletable",sf);pe.add("DeviceFlag",Eh);pe.add("DragControls",Ss);pe.add("DropListener",Cl);pe.add("Duplicatable",io);pe.add("CallInfo",so);pe.add("EventListEvent",Ch);pe.add("EventList",Rn);pe.add("EventTrigger",df);pe.add("FlyControls",ff);pe.add("BoxGizmo",ia);pe.add("GltfExportBox",mf);pe.add("GltfExport",Ks);pe.add("GridHelper",sa);pe.add("GroundProjectedEnv",ra);pe.add("Interactable",qs);pe.add("UsageMarker",Ys);pe.add("Light",wi);pe.add("LODModel",ro);pe.add("LODGroup",Al);pe.add("LookAtConstraint",Qo);pe.add("NavMesh",vf);pe.add("NavMeshAgent",yf);pe.add("NestedGltf",Rh);pe.add("Networking",ys);pe.add("OffsetConstraint",oo);pe.add("OrbitControls",xs);pe.add("ParticleSystemRenderer",Ah);pe.add("ParticleSystem",wf);pe.add("MainModule",_f);pe.add("EmissionModule",bf);pe.add("ShapeModule",xf);pe.add("PlayerColor",ss);pe.add("FieldWithDefault",Vd);pe.add("Renderer",Sn);pe.add("MeshRenderer",vh);pe.add("SkinnedMeshRenderer",Gd);pe.add("InstancingUtil",Qt);pe.add("RendererLightmap",Yo);pe.add("Rigidbody",Xt);pe.add("ScreenCapture",Ef);pe.add("ShadowCatcher",Pl);pe.add("RemoteSkybox",Il);pe.add("SmoothFollow",ao);pe.add("SpatialTriggerReceiver",Ms);pe.add("SpatialTrigger",oa);pe.add("SpectatorCamera",Sf);pe.add("SpringJoint",Mf);pe.add("Sprite",Ph);pe.add("SpriteRenderer",aa);pe.add("SyncedCamera",Ll);pe.add("SyncedRoom",Pr);pe.add("SyncedTransform",xi);pe.add("TestRunner",Tf);pe.add("TestSimulateUserData",Cf);pe.add("TransformGizmo",Ih);pe.add("VideoPlayer",ji);pe.add("Voip",Vi);pe.add("VolumeParameter",Rf);pe.add("VolumeComponent",lo);pe.add("ToneMapping",Dl);pe.add("ColorAdjustments",kl);pe.add("VolumeProfile",Ol);pe.add("Volume",Lh);pe.add("WebARSessionRoot",Qs);pe.add("WebXR",wt);pe.add("WebAR",Tl);pe.add("AvatarMarker",Kt);pe.add("WebXRAvatar",Js);pe.add("TeleportTarget",Sh);pe.add("WebXRController",Vt);pe.add("AttachedObject",is);pe.add("XRGrabModel",Oh);pe.add("XRGrabRendering",Af);pe.add("XRRig",Ml);pe.add("VRUserState",$s);pe.add("WebXRSync",na);pe.add("XRState",Es);pe.add("XRFlag",Cn);pe.add("AvatarBlink_Simple",co);pe.add("AvatarEyeLook_Rotation",ho);pe.add("Avatar_POI",vn);pe.add("Avatar_Brain_LookAt",ta);pe.add("Avatar_MouthShapes",Fl);pe.add("Avatar_MustacheShake",Pf);pe.add("LogStats",If);pe.add("RGBAColor",gn);pe.add("PlayableDirector",ua);pe.add("SignalAsset",Dh);pe.add("SignalReceiverEvent",kh);pe.add("SignalReceiver",la);pe.add("AnimationTrackHandler",Bl);pe.add("AudioTrackHandler",Nl);pe.add("SignalTrackHandler",ha);pe.add("ControlTrackHandler",ca);pe.add("BaseUIComponent",di);pe.add("UIRootComponent",fa);pe.add("Button",er);pe.add("Canvas",Ti);pe.add("CanvasGroup",ga);pe.add("EventSystem",Mi);pe.add("Graphic",As);pe.add("MaskableGraphic",pa);pe.add("Image",ma);pe.add("RawImage",Nh);pe.add("InputField",Ps);pe.add("Keyboard",zf);pe.add("LayoutGroup",va);pe.add("VerticalLayoutGroup",Vf);pe.add("HorizontalLayoutGroup",Gf);pe.add("GridLayoutGroup",Wf);pe.add("PointerEventData",Ir);pe.add("Raycaster",Hh);pe.add("ObjectRaycaster",fo);pe.add("GraphicRaycaster",jf);pe.add("Size",Uf);pe.add("Rect",Bh);pe.add("RectTransform",rs);pe.add("SpatialHtml",Xf);pe.add("Text",Hn);pe.add("PresentationMode",O_);pe.add("LinesDrawer",cv);pe.add("LineInstanceHandler",Op);pe.add("LinesManager",Iu);pe.add("PlayerSync",hv);pe.add("PlayerState",xo);var TA=class extends $o{constructor(){super([q,gn])}onDeserialize(e){if(e!=null)return e.a!==void 0?new gn(e.r,e.g,e.b,e.a):e.alpha!==void 0?new gn(e.r,e.g,e.b,e.alpha):new q(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},bpe=new TA,CA=class extends $o{constructor(){super(De)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let n=t.objectToNode[e.uuid];return Nn&&console.log(n,e.name,e.uuid),{node:n}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let n=t.nodeToObject[e.node];return Nn&&console.log("Deserialized object reference?",e,n,t?.nodeToObject),n||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),n}else if(e.guid){if(!t.context){console.error("Missing context");return}let n,i=t.gltf?.scene;return i&&(n=$.findByGuid(e.guid,i)),n||(n=$.findByGuid(e.guid,t.context.scene)),n?Nn&&console.log("Deserialized object reference?",e,n,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),n}}}},CY=new CA,RA=class extends $o{constructor(){super([$i,ce])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Nn&&console.log(e.guid,t.root,t.object,t.target);let n=this.findObjectForGuid(e.guid,t.root);if(n)return n;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){if(t.guid===e)return t;let n=$.foreachComponent(t,i=>{if(i.guid===e)return i},!1);if(n!==void 0)return n;for(let i=0;i<t.children.length;i++){let s=t.children[i],r=this.findObjectForGuid(e,s);if(r)return r}}},MA=new RA,AA=class extends $o{constructor(){super([Rn])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Nn&&console.log("DESERIALIZE EVENT",e);let n=new Array;for(let r of e.calls){Nn&&console.log(r);let a=MA.findObjectForGuid(r.target,t.root);!a&&t.context?.scene&&(a=MA.findObjectForGuid(r.target,t.context?.scene));let l=r.method?.length>0;if(a&&l){let d=()=>console.warn(`Could not find method ${r.method} on object ${a.name}`,a,typeof a[r.method]);if(typeof a[r.method]!="function"){let f=!1;r.method.startsWith("set_")&&r.method.length>4&&(r.method=r.method.substring(4),a[r.method]!==void 0&&(f=!0)),f||d()}}let c,h=r.argument;r.argument!==void 0?(typeof h=="object"&&(h=CY.onDeserialize(r.argument,t),h||(h=MA.onDeserialize(r.argument,t))),c=new so(l?(...d)=>u(...d):void 0,r.enabled)):c=new so(l?(...d)=>u(...d):void 0,r.enabled);let u=(...d)=>{let f=a[r.method];typeof f=="function"?h!==void 0?f?.call(a,h):f?.call(a,...d):a[r.method]=h};if(c.method||(c.__debuginfo=t.object?.name),!a||!c.method){let d=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+r.method+'" on',a):console.warn("EventList is missing target - will be ignored",r.target,d,e)}else n.push(c)}let i=new Rn(n);Nn&&console.log(i);let s=t.target;return s!==void 0&&t.path!==void 0&&i.setEventTarget(t.path,s),i}}},xpe=new AA;var MF=Nn;function KO(o,e){let n=pT(o,e);return n!==void 0?n:null}async function Ky(o,e,t,n=null,i){if(!t)return;let s=[],r=n;typeof r=="number"&&(r=new ci(n));let a=new Jd(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=i?.nodeToObjectMap;let l=[];if(t.scenes)for(let c of t.scenes)await IA(a,c,l,s);if(t.children)for(let c of t.children)await IA(a,c,l,s);o.new_scripts_pre_setup_callbacks.push(()=>{for(let c of l)AY(c,a);if(r){PA(t,r);for(let c of t.scenes)PA(c,r)}})}function PA(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)PA(t,e)}}var uv=[];async function IA(o,e,t,n){if(!e)return;let i=e.userData;if(i){let s=i.builtin_components;if(s&&s.length>0)for(let r of s)try{if(r===null)continue;let a=pe.get(r.name);if(a!=null){let l=new a;l.sourceId=o.gltfId,tg(l,r),ty(l,e,!1),t.push({instance:l,compData:r,obj:e})}else MF&&console.debug("unknown component: "+r.name),uv.includes(r.name)||uv.push(r.name)}catch(a){console.error(r.name+" - "+a.message,a)}if(uv.length>0){let r=uv.join(", ");console.warn("unknown components: "+r),uv.length=0}}if(e.children)for(let s of e.children)await IA(o,s,t,n)}function AY(o,e){let{instance:t,compData:n,obj:i}=o;e.object=i,e.target=t;let s=!0;s=eg(t,n,e)===!0,MF&&console.debug("add "+n.name,n,t)}var PY=new oi;async function LA(o){return new Promise((e,t)=>{PY.load(o,e,void 0,t)})}var dv=new Uint8Array(4);dv[0]=255;dv[1]=255;dv[2]=255;dv[3]=255;var RF=new Vs(dv,1,1,vi);function AF(o,e=1){let t="alpha"in o,n=e*e,i=new Uint8Array(4*n),s=Math.floor(o.r*255),r=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let c=0;c<n;c++){let h=c*4;i[h+0]=s,i[h+1]=r,i[h+2]=a,t?i[h+3]=Math.floor(o.alpha*255):i[h+3]=255}let l=new Vs(i,e,e);return l.needsUpdate=!0,l}function PF(o,e,t,n=1,i=3){let a=n*i,l=[o,e,t],c=l.length,h=new Uint8Array(4*c*a),u=new q;for(let f=0;f<i;f++){let g=Math.floor(f/i*c),p=gt.clamp(g+1,0,c-1),m=l[g],y=l[p],v=f/i*c%1;u.lerpColors(m,y,v);let _=Math.floor(u.r*255),b=Math.floor(u.g*255),x=Math.floor(u.b*255);for(let E=0;E<n;E++){let M=(f*n+E)*4;h[M+0]=_,h[M+1]=b,h[M+2]=x,h[M+3]=255}}let d=new Vs(h,n,i);return d.needsUpdate=!0,d}var DA=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},kA=class{loaded=new Map;async loadShader(e){let t=await LA(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((s,r)=>{let a=this.loaded.get(t);a?s(a):r("Shader not found")});let n=await LA(t),i=new DA(e,n);return this.loaded.set(t,i),i}},kpe=new kA;function fv(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let n=0;n<16;n+=4){let i=t[n],s=t[n+1],r=t[n+2],a=t[n+3],l=new ot(i,s,r,a);e.push(l)}return e}var OA=[],TF=[];function BA(o,e){if(OA.length===0)for(let t=0;t<27;t++)OA.push(0);e||(e=OA);for(let t=0;t<27;t++)TF[t]=e[t];e=TF,o.unity_SHAr={value:new ot(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new ot(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new ot(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new ot(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new ot(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new ot(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new ot(e[24],e[25],e[26],1)}}var FA=class{vertexShader;fragmentShader;technique;constructor(e,t,n){this.vertexShader=e,this.fragmentShader=t,this.technique=n}};async function IF(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],n=t.vertexShader,i=t.fragmentShader;if(n!==void 0&&i!==void 0){let s=o.shaders[n],r=o.shaders[i];if(s.uri&&r.uri||s.code&&r.code){if(!s.code&&s.uri&&await CF(s),!r.code&&r.uri&&await CF(r),!s.code||!r.code)return null;let a=o.techniques[e];return new FA(s.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function CF(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let n=await new oi().loadAsync(e);o.code=n.toString()}else o.code=LY(o.uri)}function LY(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var Ba=be("debugshaders"),Dp="NEEDLE_techniques_webgl";var NA=class{objectToWorldMatrix=new it;worldToObjectMatrix=new it;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),fv(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),fv(this.worldToObjectMatrix,this.worldToObject)}};var en=class extends wd{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,Ba&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&bt.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=bt.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&bt.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=bt.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}Ba&&console.log(t);let n=t.array,i=t.texture;this.uniforms.unity_SpecCube0={value:i},BA(this.uniforms,n);let s=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new ot(s,s,s,s)},Ba&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new NA;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&bt.Current.setRequireColor(!0),this.depthTextureUniform&&bt.Current.setRequireDepth(!0)}onBeforeRender(e,t,n,i,s,r){i.attributes.tangent||i.computeTangents(),this.onUpdateUniforms(n,s)}onUpdateUniforms(e,t){let n=bt.Current;e&&(en.viewProjection&&this.uniforms[this._viewProjectionName]&&(en.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),fv(en.viewProjection,en._viewProjectionValues)),en.viewMatrix&&this.uniforms[this._viewMatrixName]&&(en.viewMatrix.copy(e.matrixWorldInverse),fv(en.viewMatrix,en._viewMatrixValues)),this.uniforms[en._worldSpaceCameraPosName]&&en._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=n.rendererData.timeVec4);let i=n?.mainLight;if(i){let a=i.getWorldPosition(en._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},en._mainLightColor.set(i.color.r,i.color.g,i.color.b,0),this.uniforms._MainLightColor={value:en._mainLightColor};let l=i.intensity;en._lightData.z=l,this.uniforms.unity_LightData={value:en._lightData}}if(e&&(en.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=en._viewProjectionValues),en.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=en._viewMatrixValues),this.uniforms[en._worldSpaceCameraPosName]&&(this.uniforms[en._worldSpaceCameraPosName]={value:en._worldSpaceCameraPos}),n.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=n.mainCameraComponent.nearClipPlane,a.z=n.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,l=n.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=n.domWidth,a.y=n.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let s=this.depthTextureUniform;s&&(s.value=n.depthTexture);let r=this.opaqueTextureUniform;if(r&&(r.value=n.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},cr=en;Se(cr,"viewProjection",new it),Se(cr,"_viewProjectionValues",[]),Se(cr,"viewMatrix",new it),Se(cr,"_viewMatrixValues",[]),Se(cr,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),Se(cr,"_worldSpaceCameraPos",new O),Se(cr,"_mainLightColor",new ot),Se(cr,"_mainLightPosition",new O),Se(cr,"_lightData",new ot);var Lx=class{get name(){return Dp}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return Ba&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Dp])return Ba&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let n=t.extensions[Dp].technique;if(n<0)return null;let i=this.parser.json.extensions[Dp];if(!i)return null;Ba&&console.log(i);let s=i.techniques[n];return s?new Promise(async(r,a)=>{let l=await IF(i,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();Ba&&console.log("loadMaterial",t,l);let u={},d=s.uniforms;for(let m in d){let y=m;switch(y){case"_TimeParameters":let v=new ot;u[y]={value:v};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[y]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[y]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[y]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[y]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[y]={value:null};break}}let f=!1;if(t.extensions&&t.extensions[Dp]){let m=t.extensions[Dp];if(m.technique===n){Ba&&console.log(t.name,"Material Properties",m);for(let y in m.values){let v=m.values[y];if(typeof v=="string"){if(v.startsWith("/textures/")){let _=v.substring(10),b=Number.parseInt(_);if(b>=0){let x=await this.parser.getDependency("texture",b);x&&(x.encoding=Vr,x.needsUpdate=!0),u[y]={value:x};continue}}switch(y){case"alphaMode":v==="BLEND"&&(f=!0);continue}}if(Array.isArray(v)&&v.length===4){u[y]={value:new ot(v[0],v[1],v[2],v[3])};continue}u[y]={value:v}}}}let g=new cr(this.identifier,{name:t.name??"",uniforms:u,vertexShader:h,fragmentShader:c,lights:!1});switch(u._Cull?.value){case 0:g.side=gi;break;case 1:g.side=ki;break;case 2:g.side=ps;break;default:g.side=ps;break}g.transparent=f,f&&(g.depthWrite=!1),BA(u),g.onUpdateUniforms();for(let m in d){let y=m,v=d[m].type;if(u[y]?.value===void 0)switch(v){case 35678:u[y]={value:RF},console.warn("Missing/unassigned texture, fallback to white: "+y);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+y,d[m]);break}}Ba&&console.log(g.uuid,u),r(g)}):null}};import{EXRLoader as DY}from"three/examples/jsm/loaders/EXRLoader";var UA=be("debugexr"),Ox=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",UA&&console.log(e)}loadTexture(e){let t=this.name,n=this.parser,s=n.json.textures[e];if(UA&&console.log("EXT_texture_exr.loadTexture",e,s),!s.extensions||!s.extensions[t])return null;let r=s.extensions[t],a=new DY(n.options.manager);return UA&&console.log("EXT_texture_exr.loadTexture",r,a),n.loadTextureImage(e,r.source,a)}};var LF="NEEDLE_gameobject_data",Dx=class{get name(){return LF}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let n=0;n<this.parser.json.nodes.length;n++){let i=this.parser.json.nodes[n];if(i&&i.extensions){let s=i.extensions[LF];if(s){let r=this.findAndApplyExtensionData(n,s);t.push(r)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let n=await this.parser.getDependency("node",e);n&&this.applyExtensionData(n,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};var OF="NEEDLE_lightmaps",kY=be("debuglightmapsextension"),pv=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(pv||{}),kx=class{get name(){return OF}parser;registry;source;constructor(e,t,n){this.parser=e,this.registry=t,this.source=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[OF];if(n){let i=n.textures;return i.length?(kY&&console.log(n),new Promise(async(s,r)=>{let a=[];for(let l of i)if(l.pointer){let c=Zd(this.parser,l.pointer).then(h=>{let u=h;u?.isTexture&&(this.registry?(l.type!==0&&(u.encoding=Ct),(u.type==mr||u.type==$a)&&(u.flipY=!0),this.registry.registerTexture(this.source,l.type,u,l.index)):console.log(pv[l.type],l.pointer,u))});a.push(c)}await Promise.all(a),s()})):null}}return null}};import{LightProbeGenerator as FY}from"three/examples/jsm/lights/LightProbeGenerator.js";var HA=be("debugenvlight"),VA=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(VA||{});var Fx=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new ot;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let n=new zA(this.context,t,1);this._lighting[e]=n}getReflection(e){return this._lighting[e]}enableReflection(e){switch(HA&&console.log(this.sceneLightSettings?VA[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let n=this.context.scene,i=t.Source;i.encoding=Ct,i.mapping=Ws,n.environment=i;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,n=PF(t[0],t[1],t[2],64,64);n.encoding=Ct,n.mapping=Ws,this.context.scene.environment=n}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=AF(this.sceneLightSettings.ambientLight,64);t.encoding=Ct,t.mapping=Ws,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return HA&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,n)=>{let i=setInterval(async()=>{let s=this.getReflection(e);s&&(clearInterval(i),t(s.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},zA=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,n=1){this._context=e,this._source=t,this._ambientScale=n,t.mapping=Ws,t.encoding=Ct}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,n=null;if(t){HA&&console.log("GENERATING LIGHT PROBE",t);let i=Math.min(t.image.width,512);n=new ld(i).fromEquirectangularTexture(this._context.renderer,t),this._source=n.texture}if(this._sphericalHarmonicsArray=[],n){let i=FY.fromCubeRenderTarget(this._context.renderer,n);this._lightProbe=i;let s=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=i.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let r=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=r;if(i.sh.scale(s),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:i}}}catch(t){console.error(t)}return null}};var DF="NEEDLE_lighting_settings",mv=be("debugenvlight"),Bx=class{get name(){return DF}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[DF];if(n){mv&&console.log(n);let i=$.addNewComponent(e.scene,GA,!1);i.sourceId=this.sourceId,i.ambientIntensity=n.ambientIntensity,i.ambientLight=new q().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(i.ambientTrilight=n.ambientTrilight.map(s=>new q().fromArray(s))),i.ambientMode=n.ambientMode,i.environmentReflectionSource=n.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(i)}}return null}},GA=class extends ce{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}mv&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(mv&&console.log("enable",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&(this._ambientLightObj=new Cd(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],n=this.ambientTrilight[this.ambientTrilight.length-1],i=new Ed(n,t,this.ambientIntensity);this.gameObject.add(i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{mv&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){mv&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function jA(o){let e=new pf;return o.register(t=>(e.parser=t,e)),e}var WA=class{resolvePath(e){return e.includes("/extensions/builtin_components/")&&(e=e.replace("/extensions/builtin_components/","/userData/components/")),e}};function XA(o,e,t){o.register(i=>new Dx(i)),o.register(i=>new Xy(i)),o.register(i=>new kx(i,e.lightmaps,t)),o.register(i=>new Bx(i,t,e)),o.register(i=>new Lx(i,t)),o.register(i=>new mh(i,t)),o.register(i=>new Zo(i,t,e)),o.register(i=>new Ox(i));let n=o.setAnimationPointerResolver;typeof n=="function"&&n.bind(o)(new WA)}var BY=be("printGltf");var dc=class{context;loader;path;gltf;constructor(e,t,n,i){this.context=e,this.path=t,this.loader=n,this.gltf=i}},kF={};function kp(o,e){if(kF[o])for(let t of kF[o])t(e)}async function BF(o,e,t,n,i){BY&&console.log(t),await o.assets.registerGltf(t),await Ky(o,e,t,n,i)}function Qd(o,e,t,n){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let i=new FF;XA(i,o,t);let r=jA(i);return new Promise((a,l)=>{try{gh(i,o),kp(0,new dc(o,t,i)),i.parse(e,t,async c=>{kp(1,new dc(o,t,i,c)),await BF(o,t,c,n,r),kp(10,new dc(o,t,i,c)),a(c)},c=>{console.error("failed loading "+t,c),a(void 0)})}catch(c){console.error(c),l(c)}})}function Th(o,e,t,n=!1,i){let s=new FF;XA(s,o,e);let a=jA(s);return new Promise((l,c)=>{try{gh(s,o),kp(0,new dc(o,e,s)),s.load(e,async h=>{kp(1,new dc(o,e,s,h)),await BF(o,e,h,t,a),kp(10,new dc(o,e,s,h)),l(h)},h=>{i?.call(s,h)},h=>{console.error("failed loading "+e,h),l(void 0)})}catch(h){console.error(h),c(h)}})}function Nx(o,e,t){let n=$.getComponentInChildren(o,Ss);if(n||(n=$.addNewComponent(o,Ss,!1),n.guid=e.generateUUID()),n&&!$.getComponent(n.gameObject,xi)){let s=$.addNewComponent(n.gameObject,xi,!1);s.guid=e.generateUUID()}if(n&&!$.getComponentInParent(n.gameObject,fo)){let s=$.addNewComponent(n.gameObject,fo,!1);s.guid=e.generateUUID()}if(t&&t.animations?.length>0){let s=t.animations[0],r=$.addNewComponent(o,Rr,!1);r.animations=[s]}let i=!1;o.traverse(s=>{!s||s.isSkinnedMesh===!0&&(i||console.log("Disabling frustum culling for skinned meshes",t),i=!0,s.frustumCulled=!1)})}var qA=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,n,i,s,r,a,l){this.seed=t,this.guid=n,this.file_name=i,this.file_hash=s,this.file_size=r,this.position=a,this.sender=e,this.serverUrl=l}};async function JO(o,e,t){let n=o.name;return n.endsWith(".gltf")||n.endsWith(".glb")?new Promise((i,s)=>{let r=new FileReader;r.readAsDataURL(o),r.onloadend=async a=>{let l=r.result,c=dy(),h=new ci(c),u=await Th(e,l,h,!0);if(u&&u.scene){let d=u.scene;if(!d.guid){let f=new ci(c);d.guid=f.generateUUID()}t&&UY(e.connection,o,c,d,t),Nx(d,h,u),i(u)}}}):(console.warn("Unsupported file type: "+n),console.log(o),null)}async function QO(o,e){return new Promise(async(t,n)=>{let i=dy(),s=new ci(i),r=await Th(e,o.toString(),s,!0);if(r&&r.scene){let a=r.scene;Nx(a,s,r),t(r)}else console.warn("Unsupported file type: "+o.toString())})}function NF(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),HY(e,o);let t=null;try{t=await $y(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{zY(e,o)}if(t){let n=new ci(e.seed),i=await Qd(o,t,null,n);if(i&&i.scene){let s=i.scene;if(Nx(s,n,i),e.parentGuid){let r=$.findByGuid(e.parentGuid,o.scene);"add"in r&&r.add(s)}s.parent||o.scene.add(s),e.position!==null&&s.position.copy(e.position)}}else console.error("download didnt return file")}})}async function UY(o,e,t,n,i){if(!o.connectionId){console.error("Can not upload file - no connection id");return}if(!n.guid){console.error("Can not upload file - no guid",n,n.guid);return}let s=await zO(e,i);if(!s)return;if(!s.filename){console.error("Can not send upload event - no filename",e.name);return}if(!s.hash){console.error("Can not send upload event - no hash",e.name);return}let r=new qA(o.connectionId,t,n.guid,s.filename,s.hash,e.size,n.position,s.url??i);n.parent&&(r.parentGuid=n.parent.guid),o.send("file-spawned",r)}var YA={};function HY(o,e){let t=new ri,n=new _t(t,new Jt({color:65280})),i=new ih(n,5592405);if(YA[o.guid]=i,e.scene.add(i),o.parentGuid){let s=$.findByGuid(o.parentGuid,e.scene);s&&s.add(i)}o.position&&i.position.copy(o.position)}function zY(o,e){let t=o.guid,n=YA[t];n&&(delete YA[t],n.removeFromParent())}var jme=be("debugassets");var Ux=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let n=t[0];n&&n.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
6569
6569
|
`+n.src),e.preventDefault())}})}texturesLoader=new Uo;textures={};texturesLoading={};async loadTexture(e){if(this.textures[e])return this.textures[e];if(this.texturesLoading[e])return await this.texturesLoading[e];let t=this.texturesLoader.loadAsync(e);this.texturesLoading[e]=t;let n=await t;return delete this.texturesLoading[e],this.textures[e]=n,n}getTexture(e){return this._textures.get(e)||null}findTexture(e){for(let t of this._textures.values())if(t.name===e)return t;return null}findMesh(e){for(let t of this._meshes.values())if(t.name===e)return t;return null}findMaterial(e){for(let t of this._materials.values())if(t.name===e)return t;return null}async registerGltf(e){}registerAsset(e){}_materials=new Map;_meshes=new Map;_textures=new Map};import*as HF from"three/examples/jsm/libs/stats.module";var UF=!!be("debuglightmaps"),Hx=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,n,i){UF&&console.log("Registering lightmap",e,pv[t],n),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let s=this._lightmaps.get(e),r=s?.get(t)??[];r.length<i&&(r.length=i+1),r[i]=n,s?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,n){if(!e)return UF&&console.warn("Missing source id"),null;let i=this._lightmaps.get(e)?.get(t)??null;return!i?.length||i.length<=n?null:i[n]}};mt.lights_fragment_maps=mt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
|
|
6570
6570
|
|
|
6571
6571
|
vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
|
|
@@ -6590,7 +6590,7 @@ See https://github.com/felixmariotto/three-mesh-ui/wiki/Using-a-custom-text-type
|
|
|
6590
6590
|
irradiance += 0.;
|
|
6591
6591
|
#else
|
|
6592
6592
|
irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
6593
|
-
#endif`);We.lightmap.lightmapScaleOffset={value:new ot(1,1,0,0)};var WY=be("debugSetup"),jY=be("stats"),zx={};var Bs=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr?.isPresenting||!1}get xrSession(){return this.renderer.xr?.getSession()}get AROverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;_sizeChanged=!1;_isCreated=!1;_stats=jY?HF.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let n=be("postfx");this.renderer=new Dd({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=zs,this.renderer.setClearColor(new q("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=W0,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Ct,this.renderer.physicallyCorrectLights=!0,this.composer=n?new VY(this.renderer):null}this.scene=new el,this.application=new Jy(this),this.time=new Iy,this.input=new fy(this),this.physics=new Py(this),this.connection=new Gy(this),this.assets=new Ux,this.rendererData=new Fx(this),this.addressables=new o_(this),this.lightmaps=new Hx(this),window.addEventListener("resize",this.updateSize.bind(this)),new ResizeObserver(n=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.domWidth,t=this.domHeight,n=this.mainCamera;this.updateAspect(n),this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),this.composer&&(this.composer.setSize(e,t),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,n=this.domHeight,i=e.aspect;e.aspect=t/n,i!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,$.destroy(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,n){return this.coroutines[n]||(this.coroutines[n]=[]),this.coroutines[n].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let n=this.coroutines[t].findIndex(i=>i.main===e);n>=0&&this.coroutines[t].splice(n,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let n=this.coroutines[t];for(let i=n.length-1;i>=0;i--)n[i].comp===e&&n.splice(i,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let n=e.cam;n.isPerspectiveCamera&&this.updateAspect(n),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let n=(i,s,r,a,l,c)=>{let h=this._onBeforeRenderListeners[e.uuid];if(!!h)for(let u=0;u<h.length;u++){let d=h[u];d(i,s,r,a,l,c)}};e.onBeforeRender=n}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let n=this._onBeforeRenderListeners[e.uuid],i=n.indexOf(t);i>=0&&n.splice(i,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){let n=!0;try{Bs.Current=this,e&&await e(this,t)}catch(s){console.error(s),n=!1}if(!n)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),r2(this),s2(this),NF(this),Bs._current=this;for(let s=0;s<this.new_scripts.length;s++){let r=this.new_scripts[s];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let a=r.gameObject.userData.components;a.includes(r)||a.push(r)}}if(this.post_setup_callbacks)for(let s=0;s<this.post_setup_callbacks.length;s++)Bs._current=this,await this.post_setup_callbacks[s](this);if(!this.mainCamera){Bs._current=this;let s=$.findObjectsOfType(Bt,this),r=s.find(a=>a.tag=="MainCamera")??s.find(a=>!0);if(r)r.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+r.name+'" as mainCamera now.'),this.setCurrentCamera(r);else{console.error("No camera found");let a=CO(this.scene);this.setCurrentCamera(a)}}Bs._current=this,Go(this);let i=this.mainCameraComponent;if(i&&i.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let s=new GY(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(s),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),WY&&Vm(this.scene,!0)}render(e,t){for(this._stats?.begin(),Bs._current=this,this.time.update(),Go(this),UL(),NL(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_callbacks)for(let n in this.pre_update_callbacks)this.pre_update_callbacks[n]();for(let n=0;n<this.scripts_earlyUpdate.length;n++){let i=this.scripts_earlyUpdate[n];!i.activeAndEnabled||i.earlyUpdate!==void 0&&(Bs._current=this,i.earlyUpdate())}this.executeCoroutines(0);for(let n=0;n<this.scripts_update.length;n++){let i=this.scripts_update[n];!i.activeAndEnabled||i.update!==void 0&&(Bs._current=this,i.update())}this.executeCoroutines(1);for(let n=0;n<this.scripts_lateUpdate.length;n++){let i=this.scripts_lateUpdate[n];!i.activeAndEnabled||i.lateUpdate!==void 0&&(Bs._current=this,i.lateUpdate())}this.mainLight=null,this.executeCoroutines(2);try{let i=this.time.deltaTime/2;for(let s=0;s<2;s++)this.physics.step(i),this.executeCoroutines(10)}catch(n){console.error(n)}this.physics.postStep();for(let n=0;n<this.scripts_onBeforeRender.length;n++){let i=this.scripts_onBeforeRender[n];!i.activeAndEnabled||i.onBeforeRender!==void 0&&(Bs._current=this,i.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let n in this.pre_render_callbacks)this.pre_render_callbacks[n]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let n=0;n<this.scripts_onAfterRender.length;n++){let i=this.scripts_onAfterRender[n];!i.activeAndEnabled||i.onAfterRender!==void 0&&(Bs._current=this,i.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let n in this.post_render_callbacks)this.post_render_callbacks[n]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new _i(this.domWidth,this.domHeight),this._requireDepthTexture){let n=new hd(this.domWidth,this.domHeight);this._renderTarget.depthTexture=n}this._requireColorTexture&&(this._renderTarget.texture=new Nt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=tn,this._renderTarget.texture.magFilter=tn,this._renderTarget.texture.format=vi)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){let n=this.coroutines[e];for(let i=0;i<n.length;i++){let s=n[i];if(!s.comp||s.comp.destroyed||!s.main||s.comp.enabled===!1){n.splice(i,1),--i;continue}let a=s.chained;if(a&&a.length>0){let u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(s.chained||(s.chained=[]),s.chained.push(u.value)),!u.done)continue}let l=s.main.next();if(l.done===!0){n.splice(i,1),--i;continue}let c=l.value;if(t(c)){if(c.next().done)continue;s.chained||(s.chained=[]),s.chained.push(c)}}}function t(n){return!!(n&&n.next&&n.return)}}},bt=Bs;Se(bt,"_current");var Lu="ar",XY="quit-ar",Vx=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,n){this.currentSession=n,this.arContainer=t,e.domElement.querySelectorAll(`.${Lu}`).forEach(r=>{!r||r!==this.arContainer&&(this._reparentedObjects.push({el:r,previousParent:r.parentElement}),this.arContainer?.appendChild(r))});let s=t.getElementsByClassName(XY);if(!s||s.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let r=0;r<s.length;r++){let a=s[r];!a||(a.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(a))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let n=t.el;t.previousParent?.appendChild(n)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(Lu))return e;if(e.children){for(let n of e.children)if(!(!n||!n.classList)&&n.classList.contains(Lu))return n}let t=document.createElement("div");return t.classList.add(Lu),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),n.setAttribute("stroke","#eee"),n.setAttribute("stroke-width","2px"),t.appendChild(n),this._createdAROnlyElements.push(n)}};var qY=be("debugloadingbar");function ZA(o){return o.index/o.count+o.progress.loaded/o.progress.total/o.count}var Gx=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let n=this.container.children[t];if(n.classList.contains("loading")){if(!this._allowCustomLoadingElement){this.container.removeChild(n);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let n=0;typeof e=="number"?n=e:("index"in e&&(n=ZA(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;qY&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=gt.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let n=document.createElement("div"),i=20;n.style.display="flex",n.style.width=i+"%",n.style.height="2px",n.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(n),this._loadingBar=document.createElement("div"),n.appendChild(this._loadingBar);let s=function(a){return gt.lerp(i*.5,100-i*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${s(0)}, #0BA398 ${s(.4)}, #99CC33 ${s(.5)}, #D7DB0A ${s(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let r=document.createElement("div");return this._messageContainer=r,r.style.display="flex",r.style.fontSize=".8em",r.style.paddingTop=".5em",r.style.color="rgba(255,255,255,.5)",this._loadingElement.appendChild(r),this._loadingElement}};var Ou=be("debugwebcomponent"),JA=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,n=>{this.onSourceChanged(n,!0)})}async onSourceChanged(e,t=!1,n=!1){this.previouslyAdded&&(t&&e===this.previousSource||$.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,bt.Current=this.context;let i=await Th(this.context,e,this.getHashFromString(e));n||Go(this.context);let s=i?.scene;s&&(this.previouslyAdded=s,this.context.scene.add(s))}getHashFromString(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}},YY="needle-engine",ZY="vr",JY="desktop",QY=[Lu,ZY,JY],QA=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let n=()=>{this.removeEventListener("loadfinished",n),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",n)}})}get Context(){return this._context}gameObject=$;GameObject=$;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new Vx}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let r=this.getAttribute("src");return r?.endsWith(".glb")||r?.endsWith(".gltf")?r:null},n="loadScene",i=t();i&&(n=i);let s=this.getAttribute("alias");if(this._context=new bt({name:n,domElement:this,alias:s}),this._watcher=new JA(this.getAttribute("id")??s??"",this._context),n&&n.length>0){if(!i)for(;Object.keys(zx).length<=0;){if(!this.isConnected)return;await kL(10)}let r=zx[n]??window[n],a=null;if((!r||i)&&(i&&(n=i),r=async l=>{let c=t();c&&this._watcher&&(a=c,await this._watcher.onSourceChanged(c,!0,!0))}),r){this.classList.add("loading"),console.log("Needle Engine: Begin loading",s??"");let l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:s},cancelable:!0}));!this._loadingView&&l&&(this._loadingView=new Gx(this)),l&&this._loadingView?.onLoadingBegin("begin load");let c=(u,d)=>{this._loadingProgress01=ZA(u),l&&this._loadingView?.onLoadingUpdate(u,d),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:u.name,progress:u.progress,index:u.index,count:u.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(r,{progress:c});let h=t();h&&h!==a&&await this._watcher.onSourceChanged(h,!0,!0),this._loadingProgress01=1,l&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",s??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:s??n}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+n+'", it must be either in global scope or added to build_scene_functions',zx)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,n){switch(e){case"src":this._watcher?.onSourceChanged(n);break;case"loadstart":case"progress":case"loadfinished":typeof n=="string"&&n.length>0&&(Ou&&console.log(e+" attribute changed",n),this.registerEventFromAttribute(e,n));break;case"dracoDecoderPath":Ou&&console.log("dracoDecoderPath",n),HM(n);break;case"dracoDecoderType":n==="wasm"||n==="js"?(Ou&&console.log("dracoDecoderType",n),zM(n)):console.error("Invalid dracoDecoderType",n,"expected js or wasm");break;case"ktx2DecoderPath":Ou&&console.log("ktx2DecoderPath",n),VM(n);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let n=(0,eval)(t);typeof n=="function"&&this.addEventListener(e,i=>n?.call(globalThis,this._context,i))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Lu))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,n=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let s of QY)e.classList.contains(s)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let n=this.children[t];n.style&&e(n)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Ou&&console.log("using custom draco decoder path",e),HM(e));let t=this.getAttribute("dracoDecoderType");t&&(Ou&&console.log("using custom draco decoder type",t),zM(t));let n=this.getAttribute("ktx2DecoderPath");n&&(Ou&&console.log("using custom ktx2 decoder path",n),VM(n))}};window.customElements.define(YY,QA);var $A={};gv($A,{AlignmentConstraint:()=>_l,Animation:()=>Rr,AnimationCurve:()=>bh,AnimationTrackHandler:()=>Bl,Animator:()=>ws,AnimatorController:()=>Cr,AttachedObject:()=>is,AudioListener:()=>Ar,AudioSource:()=>$t,AudioTrackHandler:()=>Nl,AvatarBlink_Simple:()=>co,AvatarEyeLook_Rotation:()=>ho,AvatarLoader:()=>bl,AvatarMarker:()=>Kt,AvatarModel:()=>xh,Avatar_Brain_LookAt:()=>ta,Avatar_MouthShapes:()=>Fl,Avatar_MustacheShake:()=>Pf,Avatar_POI:()=>vn,AxesHelper:()=>Ko,BaseUIComponent:()=>di,BasicIKConstraint:()=>$d,BoxCollider:()=>wl,BoxGizmo:()=>ia,BoxHelperComponent:()=>ts,Button:()=>er,CallInfo:()=>so,Camera:()=>Bt,Canvas:()=>Ti,CanvasGroup:()=>ga,Collider:()=>Kr,ColorAdjustments:()=>kl,ControlTrackHandler:()=>ca,Deletable:()=>sf,DeleteBox:()=>wh,DeviceFlag:()=>Eh,DragControls:()=>Ss,DropListener:()=>Cl,Duplicatable:()=>io,EmissionModule:()=>bf,EventList:()=>Rn,EventListEvent:()=>Ch,EventSystem:()=>Mi,EventTrigger:()=>df,FieldWithDefault:()=>Vd,FlyControls:()=>ff,GltfExport:()=>Ks,GltfExportBox:()=>mf,Graphic:()=>As,GraphicRaycaster:()=>jf,GridHelper:()=>sa,GridLayoutGroup:()=>Wf,GroundProjectedEnv:()=>ra,HorizontalLayoutGroup:()=>Gf,Image:()=>ma,InputField:()=>Ps,InstancingUtil:()=>Qt,InstantiateOptions:()=>hn,Interactable:()=>qs,Keyboard:()=>zf,LODGroup:()=>Al,LODModel:()=>ro,LayoutGroup:()=>va,Light:()=>wi,LogStats:()=>If,LookAtConstraint:()=>Qo,MainModule:()=>_f,MaskableGraphic:()=>pa,MeshRenderer:()=>vh,NavMesh:()=>vf,NavMeshAgent:()=>yf,NestedGltf:()=>Rh,Networking:()=>ys,ObjectRaycaster:()=>fo,OffsetConstraint:()=>oo,OrbitControls:()=>xs,ParticleSystem:()=>wf,ParticleSystemRenderer:()=>Ah,PlayableDirector:()=>ua,PlayerColor:()=>ss,PointerEventData:()=>Ir,RGBAColor:()=>gn,RawImage:()=>Nh,Raycaster:()=>Hh,Rect:()=>Bh,RectTransform:()=>rs,RemoteSkybox:()=>Il,Renderer:()=>Sn,RendererLightmap:()=>Yo,Rigidbody:()=>Xt,ScreenCapture:()=>Ef,ShadowCatcher:()=>Pl,ShapeModule:()=>xf,SignalAsset:()=>Dh,SignalReceiver:()=>la,SignalReceiverEvent:()=>kh,SignalTrackHandler:()=>ha,Size:()=>Uf,SkinnedMeshRenderer:()=>Gd,SmoothFollow:()=>ao,SpatialHtml:()=>Xf,SpatialTrigger:()=>oa,SpatialTriggerReceiver:()=>Ms,SpectatorCamera:()=>Sf,SphereCollider:()=>xl,SpringJoint:()=>Mf,Sprite:()=>Ph,SpriteRenderer:()=>aa,SyncedCamera:()=>Ll,SyncedRoom:()=>Pr,SyncedTransform:()=>xi,TeleportTarget:()=>Sh,TestRunner:()=>Tf,TestSimulateUserData:()=>Cf,Text:()=>Hn,ToneMapping:()=>Dl,TransformGizmo:()=>Ih,UIRootComponent:()=>fa,UnityObject:()=>nf,UsageMarker:()=>Ys,VRUserState:()=>$s,VerticalLayoutGroup:()=>Vf,VideoPlayer:()=>ji,Voip:()=>Vi,Volume:()=>Lh,VolumeComponent:()=>lo,VolumeParameter:()=>Rf,VolumeProfile:()=>Ol,WebAR:()=>Tl,WebARSessionRoot:()=>Qs,WebXR:()=>wt,WebXRAvatar:()=>Js,WebXRController:()=>Vt,WebXRSync:()=>na,XRFlag:()=>Cn,XRGrabModel:()=>Oh,XRGrabRendering:()=>Af,XRRig:()=>Ml,XRState:()=>Es});var KA={Context:bt};globalThis.Needle=KA;function zF(o){for(let e in o)KA[e]=o[e]}zF(yM);zF($A);for(let o of Object.getOwnPropertyNames($))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:KA[o]=$[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=lt;export{_l as AlignmentConstraint,Rr as Animation,bh as AnimationCurve,Bl as AnimationTrackHandler,ws as Animator,Cr as AnimatorController,is as AttachedObject,Ar as AudioListener,$t as AudioSource,Nl as AudioTrackHandler,co as AvatarBlink_Simple,ho as AvatarEyeLook_Rotation,bl as AvatarLoader,Kt as AvatarMarker,xh as AvatarModel,ta as Avatar_Brain_LookAt,Fl as Avatar_MouthShapes,Pf as Avatar_MustacheShake,vn as Avatar_POI,Ko as AxesHelper,di as BaseUIComponent,$d as BasicIKConstraint,ce as Behaviour,wl as BoxCollider,ia as BoxGizmo,ts as BoxHelperComponent,er as Button,so as CallInfo,Bt as Camera,Ti as Canvas,ga as CanvasGroup,Kr as Collider,kl as ColorAdjustments,ca as ControlTrackHandler,sf as Deletable,wh as DeleteBox,Eh as DeviceFlag,Ss as DragControls,Cl as DropListener,io as Duplicatable,bf as EmissionModule,Rn as EventList,Ch as EventListEvent,Mi as EventSystem,df as EventTrigger,Vd as FieldWithDefault,ff as FlyControls,$ as GameObject,Ks as GltfExport,mf as GltfExportBox,As as Graphic,jf as GraphicRaycaster,sa as GridHelper,Wf as GridLayoutGroup,ra as GroundProjectedEnv,Gf as HorizontalLayoutGroup,ma as Image,Ps as InputField,Qt as InstancingUtil,hn as InstantiateOptions,qs as Interactable,zf as Keyboard,Al as LODGroup,ro as LODModel,va as LayoutGroup,wi as Light,If as LogStats,Qo as LookAtConstraint,_f as MainModule,pa as MaskableGraphic,vh as MeshRenderer,vf as NavMesh,yf as NavMeshAgent,Rh as NestedGltf,ys as Networking,fo as ObjectRaycaster,oo as OffsetConstraint,xs as OrbitControls,wf as ParticleSystem,Ah as ParticleSystemRenderer,ua as PlayableDirector,ss as PlayerColor,Ir as PointerEventData,gn as RGBAColor,Nh as RawImage,Hh as Raycaster,Bh as Rect,rs as RectTransform,Il as RemoteSkybox,Sn as Renderer,Yo as RendererLightmap,Xt as Rigidbody,Ef as ScreenCapture,Pl as ShadowCatcher,xf as ShapeModule,Dh as SignalAsset,la as SignalReceiver,kh as SignalReceiverEvent,ha as SignalTrackHandler,Uf as Size,Gd as SkinnedMeshRenderer,ao as SmoothFollow,Xf as SpatialHtml,oa as SpatialTrigger,Ms as SpatialTriggerReceiver,Sf as SpectatorCamera,xl as SphereCollider,Mf as SpringJoint,Ph as Sprite,aa as SpriteRenderer,Ll as SyncedCamera,Pr as SyncedRoom,xi as SyncedTransform,Sh as TeleportTarget,Tf as TestRunner,Cf as TestSimulateUserData,Hn as Text,Dl as ToneMapping,Ih as TransformGizmo,fa as UIRootComponent,nf as UnityObject,Ys as UsageMarker,$s as VRUserState,Vf as VerticalLayoutGroup,ji as VideoPlayer,Vi as Voip,Lh as Volume,lo as VolumeComponent,Rf as VolumeParameter,Ol as VolumeProfile,Tl as WebAR,Qs as WebARSessionRoot,wt as WebXR,Js as WebXRAvatar,Vt as WebXRController,na as WebXRSync,Cn as XRFlag,Oh as XRGrabModel,Af as XRGrabRendering,Ml as XRRig,Es as XRState,te as serializeable};
|
|
6593
|
+
#endif`);We.lightmap.lightmapScaleOffset={value:new ot(1,1,0,0)};var WY=be("debugSetup"),jY=be("stats"),zx={};var Bs=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr?.isPresenting||!1}get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;_sizeChanged=!1;_isCreated=!1;_stats=jY?HF.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let n=be("postfx");this.renderer=new Dd({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=zs,this.renderer.setClearColor(new q("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=W0,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Ct,this.renderer.physicallyCorrectLights=!0,this.composer=n?new VY(this.renderer):null}this.scene=new el,this.application=new Jy(this),this.time=new Iy,this.input=new fy(this),this.physics=new Py(this),this.connection=new Gy(this),this.assets=new Ux,this.rendererData=new Fx(this),this.addressables=new o_(this),this.lightmaps=new Hx(this),window.addEventListener("resize",this.updateSize.bind(this)),new ResizeObserver(n=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,n=this.domHeight*e,i=this.mainCamera;this.updateAspect(i),this.renderer.setSize(t,n),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width=this.domWidth+"px",this.renderer.domElement.style.height=this.domHeight+"px",this.composer&&(this.composer.setSize(t,n),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,n=this.domHeight,i=e.aspect;e.aspect=t/n,i!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,$.destroy(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,n){return this.coroutines[n]||(this.coroutines[n]=[]),this.coroutines[n].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let n=this.coroutines[t].findIndex(i=>i.main===e);n>=0&&this.coroutines[t].splice(n,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let n=this.coroutines[t];for(let i=n.length-1;i>=0;i--)n[i].comp===e&&n.splice(i,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let n=e.cam;n.isPerspectiveCamera&&this.updateAspect(n),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let n=(i,s,r,a,l,c)=>{let h=this._onBeforeRenderListeners[e.uuid];if(!!h)for(let u=0;u<h.length;u++){let d=h[u];d(i,s,r,a,l,c)}};e.onBeforeRender=n}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let n=this._onBeforeRenderListeners[e.uuid],i=n.indexOf(t);i>=0&&n.splice(i,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){let n=!0;try{Bs.Current=this,e&&await e(this,t)}catch(s){console.error(s),n=!1}if(!n)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),r2(this),s2(this),NF(this),Bs._current=this;for(let s=0;s<this.new_scripts.length;s++){let r=this.new_scripts[s];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let a=r.gameObject.userData.components;a.includes(r)||a.push(r)}}if(this.post_setup_callbacks)for(let s=0;s<this.post_setup_callbacks.length;s++)Bs._current=this,await this.post_setup_callbacks[s](this);if(!this.mainCamera){Bs._current=this;let s=$.findObjectsOfType(Bt,this),r=s.find(a=>a.tag=="MainCamera")??s.find(a=>!0);if(r)r.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+r.name+'" as mainCamera now.'),this.setCurrentCamera(r);else{console.error("No camera found");let a=CO(this.scene);this.setCurrentCamera(a)}}Bs._current=this,Go(this);let i=this.mainCameraComponent;if(i&&i.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let s=new GY(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(s),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),WY&&Vm(this.scene,!0)}render(e,t){for(this._stats?.begin(),Bs._current=this,this.time.update(),Go(this),UL(),NL(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_callbacks)for(let n in this.pre_update_callbacks)this.pre_update_callbacks[n]();for(let n=0;n<this.scripts_earlyUpdate.length;n++){let i=this.scripts_earlyUpdate[n];!i.activeAndEnabled||i.earlyUpdate!==void 0&&(Bs._current=this,i.earlyUpdate())}this.executeCoroutines(0);for(let n=0;n<this.scripts_update.length;n++){let i=this.scripts_update[n];!i.activeAndEnabled||i.update!==void 0&&(Bs._current=this,i.update())}this.executeCoroutines(1);for(let n=0;n<this.scripts_lateUpdate.length;n++){let i=this.scripts_lateUpdate[n];!i.activeAndEnabled||i.lateUpdate!==void 0&&(Bs._current=this,i.lateUpdate())}this.mainLight=null,this.executeCoroutines(2);try{let i=this.time.deltaTime/2;for(let s=0;s<2;s++)this.physics.step(i),this.executeCoroutines(10)}catch(n){console.error(n)}this.physics.postStep();for(let n=0;n<this.scripts_onBeforeRender.length;n++){let i=this.scripts_onBeforeRender[n];!i.activeAndEnabled||i.onBeforeRender!==void 0&&(Bs._current=this,i.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let n in this.pre_render_callbacks)this.pre_render_callbacks[n]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let n=0;n<this.scripts_onAfterRender.length;n++){let i=this.scripts_onAfterRender[n];!i.activeAndEnabled||i.onAfterRender!==void 0&&(Bs._current=this,i.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let n in this.post_render_callbacks)this.post_render_callbacks[n]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new _i(this.domWidth,this.domHeight),this._requireDepthTexture){let n=new hd(this.domWidth,this.domHeight);this._renderTarget.depthTexture=n}this._requireColorTexture&&(this._renderTarget.texture=new Nt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=tn,this._renderTarget.texture.magFilter=tn,this._renderTarget.texture.format=vi)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){let n=this.coroutines[e];for(let i=0;i<n.length;i++){let s=n[i];if(!s.comp||s.comp.destroyed||!s.main||s.comp.enabled===!1){n.splice(i,1),--i;continue}let a=s.chained;if(a&&a.length>0){let u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(s.chained||(s.chained=[]),s.chained.push(u.value)),!u.done)continue}let l=s.main.next();if(l.done===!0){n.splice(i,1),--i;continue}let c=l.value;if(t(c)){if(c.next().done)continue;s.chained||(s.chained=[]),s.chained.push(c)}}}function t(n){return!!(n&&n.next&&n.return)}}},bt=Bs;Se(bt,"_current");var Lu="ar",XY="quit-ar",Vx=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,n){this.currentSession=n,this.arContainer=t,e.domElement.querySelectorAll(`.${Lu}`).forEach(r=>{!r||r!==this.arContainer&&(this._reparentedObjects.push({el:r,previousParent:r.parentElement}),this.arContainer?.appendChild(r))});let s=t.getElementsByClassName(XY);if(!s||s.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let r=0;r<s.length;r++){let a=s[r];!a||(a.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(a))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let n=t.el;t.previousParent?.appendChild(n)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(Lu))return e;if(e.children){for(let n of e.children)if(!(!n||!n.classList)&&n.classList.contains(Lu))return n}let t=document.createElement("div");return t.classList.add(Lu),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),n.setAttribute("stroke","#eee"),n.setAttribute("stroke-width","2px"),t.appendChild(n),this._createdAROnlyElements.push(n)}};var qY=be("debugloadingbar");function ZA(o){return o.index/o.count+o.progress.loaded/o.progress.total/o.count}var Gx=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let n=this.container.children[t];if(n.classList.contains("loading")){if(!this._allowCustomLoadingElement){this.container.removeChild(n);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let n=0;typeof e=="number"?n=e:("index"in e&&(n=ZA(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;qY&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=gt.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let n=document.createElement("div"),i=20;n.style.display="flex",n.style.width=i+"%",n.style.height="2px",n.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(n),this._loadingBar=document.createElement("div"),n.appendChild(this._loadingBar);let s=function(a){return gt.lerp(i*.5,100-i*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${s(0)}, #0BA398 ${s(.4)}, #99CC33 ${s(.5)}, #D7DB0A ${s(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let r=document.createElement("div");return this._messageContainer=r,r.style.display="flex",r.style.fontSize=".8em",r.style.paddingTop=".5em",r.style.color="rgba(255,255,255,.5)",this._loadingElement.appendChild(r),this._loadingElement}};var Ou=be("debugwebcomponent"),JA=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,n=>{this.onSourceChanged(n,!0)})}async onSourceChanged(e,t=!1,n=!1){this.previouslyAdded&&(t&&e===this.previousSource||$.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,bt.Current=this.context;let i=await Th(this.context,e,this.getHashFromString(e));n||Go(this.context);let s=i?.scene;s&&(this.previouslyAdded=s,this.context.scene.add(s))}getHashFromString(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}},YY="needle-engine",ZY="vr",JY="desktop",QY=[Lu,ZY,JY],QA=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let n=()=>{this.removeEventListener("loadfinished",n),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",n)}})}get Context(){return this._context}gameObject=$;GameObject=$;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new Vx}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let r=this.getAttribute("src");return r?.endsWith(".glb")||r?.endsWith(".gltf")?r:null},n="loadScene",i=t();i&&(n=i);let s=this.getAttribute("alias");if(this._context=new bt({name:n,domElement:this,alias:s}),this._watcher=new JA(this.getAttribute("id")??s??"",this._context),n&&n.length>0){if(!i)for(;Object.keys(zx).length<=0;){if(!this.isConnected)return;await kL(10)}let r=zx[n]??window[n],a=null;if((!r||i)&&(i&&(n=i),r=async l=>{let c=t();c&&this._watcher&&(a=c,await this._watcher.onSourceChanged(c,!0,!0))}),r){this.classList.add("loading"),console.log("Needle Engine: Begin loading",s??"");let l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:s},cancelable:!0}));!this._loadingView&&l&&(this._loadingView=new Gx(this)),l&&this._loadingView?.onLoadingBegin("begin load");let c=(u,d)=>{this._loadingProgress01=ZA(u),l&&this._loadingView?.onLoadingUpdate(u,d),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:u.name,progress:u.progress,index:u.index,count:u.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(r,{progress:c});let h=t();h&&h!==a&&await this._watcher.onSourceChanged(h,!0,!0),this._loadingProgress01=1,l&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",s??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:s??n}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+n+'", it must be either in global scope or added to build_scene_functions',zx)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,n){switch(e){case"src":this._watcher?.onSourceChanged(n);break;case"loadstart":case"progress":case"loadfinished":typeof n=="string"&&n.length>0&&(Ou&&console.log(e+" attribute changed",n),this.registerEventFromAttribute(e,n));break;case"dracoDecoderPath":Ou&&console.log("dracoDecoderPath",n),HM(n);break;case"dracoDecoderType":n==="wasm"||n==="js"?(Ou&&console.log("dracoDecoderType",n),zM(n)):console.error("Invalid dracoDecoderType",n,"expected js or wasm");break;case"ktx2DecoderPath":Ou&&console.log("ktx2DecoderPath",n),VM(n);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let n=(0,eval)(t);typeof n=="function"&&this.addEventListener(e,i=>n?.call(globalThis,this._context,i))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Lu))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,n=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let s of QY)e.classList.contains(s)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let n=this.children[t];n.style&&e(n)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Ou&&console.log("using custom draco decoder path",e),HM(e));let t=this.getAttribute("dracoDecoderType");t&&(Ou&&console.log("using custom draco decoder type",t),zM(t));let n=this.getAttribute("ktx2DecoderPath");n&&(Ou&&console.log("using custom ktx2 decoder path",n),VM(n))}};window.customElements.define(YY,QA);var $A={};gv($A,{AlignmentConstraint:()=>_l,Animation:()=>Rr,AnimationCurve:()=>bh,AnimationTrackHandler:()=>Bl,Animator:()=>ws,AnimatorController:()=>Cr,AttachedObject:()=>is,AudioListener:()=>Ar,AudioSource:()=>$t,AudioTrackHandler:()=>Nl,AvatarBlink_Simple:()=>co,AvatarEyeLook_Rotation:()=>ho,AvatarLoader:()=>bl,AvatarMarker:()=>Kt,AvatarModel:()=>xh,Avatar_Brain_LookAt:()=>ta,Avatar_MouthShapes:()=>Fl,Avatar_MustacheShake:()=>Pf,Avatar_POI:()=>vn,AxesHelper:()=>Ko,BaseUIComponent:()=>di,BasicIKConstraint:()=>$d,BoxCollider:()=>wl,BoxGizmo:()=>ia,BoxHelperComponent:()=>ts,Button:()=>er,CallInfo:()=>so,Camera:()=>Bt,Canvas:()=>Ti,CanvasGroup:()=>ga,Collider:()=>Kr,ColorAdjustments:()=>kl,ControlTrackHandler:()=>ca,Deletable:()=>sf,DeleteBox:()=>wh,DeviceFlag:()=>Eh,DragControls:()=>Ss,DropListener:()=>Cl,Duplicatable:()=>io,EmissionModule:()=>bf,EventList:()=>Rn,EventListEvent:()=>Ch,EventSystem:()=>Mi,EventTrigger:()=>df,FieldWithDefault:()=>Vd,FlyControls:()=>ff,GltfExport:()=>Ks,GltfExportBox:()=>mf,Graphic:()=>As,GraphicRaycaster:()=>jf,GridHelper:()=>sa,GridLayoutGroup:()=>Wf,GroundProjectedEnv:()=>ra,HorizontalLayoutGroup:()=>Gf,Image:()=>ma,InputField:()=>Ps,InstancingUtil:()=>Qt,InstantiateOptions:()=>hn,Interactable:()=>qs,Keyboard:()=>zf,LODGroup:()=>Al,LODModel:()=>ro,LayoutGroup:()=>va,Light:()=>wi,LogStats:()=>If,LookAtConstraint:()=>Qo,MainModule:()=>_f,MaskableGraphic:()=>pa,MeshRenderer:()=>vh,NavMesh:()=>vf,NavMeshAgent:()=>yf,NestedGltf:()=>Rh,Networking:()=>ys,ObjectRaycaster:()=>fo,OffsetConstraint:()=>oo,OrbitControls:()=>xs,ParticleSystem:()=>wf,ParticleSystemRenderer:()=>Ah,PlayableDirector:()=>ua,PlayerColor:()=>ss,PointerEventData:()=>Ir,RGBAColor:()=>gn,RawImage:()=>Nh,Raycaster:()=>Hh,Rect:()=>Bh,RectTransform:()=>rs,RemoteSkybox:()=>Il,Renderer:()=>Sn,RendererLightmap:()=>Yo,Rigidbody:()=>Xt,ScreenCapture:()=>Ef,ShadowCatcher:()=>Pl,ShapeModule:()=>xf,SignalAsset:()=>Dh,SignalReceiver:()=>la,SignalReceiverEvent:()=>kh,SignalTrackHandler:()=>ha,Size:()=>Uf,SkinnedMeshRenderer:()=>Gd,SmoothFollow:()=>ao,SpatialHtml:()=>Xf,SpatialTrigger:()=>oa,SpatialTriggerReceiver:()=>Ms,SpectatorCamera:()=>Sf,SphereCollider:()=>xl,SpringJoint:()=>Mf,Sprite:()=>Ph,SpriteRenderer:()=>aa,SyncedCamera:()=>Ll,SyncedRoom:()=>Pr,SyncedTransform:()=>xi,TeleportTarget:()=>Sh,TestRunner:()=>Tf,TestSimulateUserData:()=>Cf,Text:()=>Hn,ToneMapping:()=>Dl,TransformGizmo:()=>Ih,UIRootComponent:()=>fa,UnityObject:()=>nf,UsageMarker:()=>Ys,VRUserState:()=>$s,VerticalLayoutGroup:()=>Vf,VideoPlayer:()=>ji,Voip:()=>Vi,Volume:()=>Lh,VolumeComponent:()=>lo,VolumeParameter:()=>Rf,VolumeProfile:()=>Ol,WebAR:()=>Tl,WebARSessionRoot:()=>Qs,WebXR:()=>wt,WebXRAvatar:()=>Js,WebXRController:()=>Vt,WebXRSync:()=>na,XRFlag:()=>Cn,XRGrabModel:()=>Oh,XRGrabRendering:()=>Af,XRRig:()=>Ml,XRState:()=>Es});var KA={Context:bt};globalThis.Needle=KA;function zF(o){for(let e in o)KA[e]=o[e]}zF(yM);zF($A);for(let o of Object.getOwnPropertyNames($))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:KA[o]=$[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=lt;export{_l as AlignmentConstraint,Rr as Animation,bh as AnimationCurve,Bl as AnimationTrackHandler,ws as Animator,Cr as AnimatorController,is as AttachedObject,Ar as AudioListener,$t as AudioSource,Nl as AudioTrackHandler,co as AvatarBlink_Simple,ho as AvatarEyeLook_Rotation,bl as AvatarLoader,Kt as AvatarMarker,xh as AvatarModel,ta as Avatar_Brain_LookAt,Fl as Avatar_MouthShapes,Pf as Avatar_MustacheShake,vn as Avatar_POI,Ko as AxesHelper,di as BaseUIComponent,$d as BasicIKConstraint,ce as Behaviour,wl as BoxCollider,ia as BoxGizmo,ts as BoxHelperComponent,er as Button,so as CallInfo,Bt as Camera,Ti as Canvas,ga as CanvasGroup,Kr as Collider,kl as ColorAdjustments,ca as ControlTrackHandler,sf as Deletable,wh as DeleteBox,Eh as DeviceFlag,Ss as DragControls,Cl as DropListener,io as Duplicatable,bf as EmissionModule,Rn as EventList,Ch as EventListEvent,Mi as EventSystem,df as EventTrigger,Vd as FieldWithDefault,ff as FlyControls,$ as GameObject,Ks as GltfExport,mf as GltfExportBox,As as Graphic,jf as GraphicRaycaster,sa as GridHelper,Wf as GridLayoutGroup,ra as GroundProjectedEnv,Gf as HorizontalLayoutGroup,ma as Image,Ps as InputField,Qt as InstancingUtil,hn as InstantiateOptions,qs as Interactable,zf as Keyboard,Al as LODGroup,ro as LODModel,va as LayoutGroup,wi as Light,If as LogStats,Qo as LookAtConstraint,_f as MainModule,pa as MaskableGraphic,vh as MeshRenderer,vf as NavMesh,yf as NavMeshAgent,Rh as NestedGltf,ys as Networking,fo as ObjectRaycaster,oo as OffsetConstraint,xs as OrbitControls,wf as ParticleSystem,Ah as ParticleSystemRenderer,ua as PlayableDirector,ss as PlayerColor,Ir as PointerEventData,gn as RGBAColor,Nh as RawImage,Hh as Raycaster,Bh as Rect,rs as RectTransform,Il as RemoteSkybox,Sn as Renderer,Yo as RendererLightmap,Xt as Rigidbody,Ef as ScreenCapture,Pl as ShadowCatcher,xf as ShapeModule,Dh as SignalAsset,la as SignalReceiver,kh as SignalReceiverEvent,ha as SignalTrackHandler,Uf as Size,Gd as SkinnedMeshRenderer,ao as SmoothFollow,Xf as SpatialHtml,oa as SpatialTrigger,Ms as SpatialTriggerReceiver,Sf as SpectatorCamera,xl as SphereCollider,Mf as SpringJoint,Ph as Sprite,aa as SpriteRenderer,Ll as SyncedCamera,Pr as SyncedRoom,xi as SyncedTransform,Sh as TeleportTarget,Tf as TestRunner,Cf as TestSimulateUserData,Hn as Text,Dl as ToneMapping,Ih as TransformGizmo,fa as UIRootComponent,nf as UnityObject,Ys as UsageMarker,$s as VRUserState,Vf as VerticalLayoutGroup,ji as VideoPlayer,Vi as Voip,Lh as Volume,lo as VolumeComponent,Rf as VolumeParameter,Ol as VolumeProfile,Tl as WebAR,Qs as WebARSessionRoot,wt as WebXR,Js as WebXRAvatar,Vt as WebXRController,na as WebXRSync,Cn as XRFlag,Oh as XRGrabModel,Af as XRGrabRendering,Ml as XRRig,Es as XRState,te as serializeable};
|
|
6594
6594
|
/*!
|
|
6595
6595
|
* Determine if an object is a Buffer
|
|
6596
6596
|
*
|