hytopia 0.14.27 → 0.14.28
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/package.json +1 -1
- package/server.mjs +2 -2
package/package.json
CHANGED
package/server.mjs
CHANGED
|
@@ -236,7 +236,7 @@ globstar while`,A,$,Q,Z,U),this.matchOne(A.slice($),Q.slice(Z),B))return this.de
|
|
|
236
236
|
characterSettings { skinTone hairColor eyeColor hairStyle }
|
|
237
237
|
equippedItems { slot item { slots { flags type modelUrl textureUrl } } }
|
|
238
238
|
}
|
|
239
|
-
}`});try{let Y=(await Q.next()).value?.data?.userById;if(!Y)return n.warning(`PlatformGateway.getPlayerCosmetics(): No cosmetic data returned for user id "${A}".`);let J=Y.equippedItems.map((G)=>({slot:G.slot,item:G.item.slots.find((F)=>F.type===G.slot)})).filter((G)=>!!G.item),C=Number(Y.characterSettings?.hairStyle?.split("_")[1]||1),X=`https://d3qkovarww0lj1.cloudfront.net/?skin_tone=${Y.characterSettings?.skinTone||"SKIN_COLOR_1"}&clothing=${Y.characterSettings?.clothing||"CLOTHING_1"}&hair_style=${Y.characterSettings?.hairStyle||"HAIR_STYLE_1"}&hair_color=${Y.characterSettings?.hairColor||"HAIR_COLOR_1"}&eye_color=${Y.characterSettings?.eyeColor||"00FF00"}`;return{equippedItems:J,hairStyle:C,skinTextureUri:X}}finally{await Q.return?.()}}async getPlayerSession(A){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(A)}async scheduleNotification(A,Q,B){if(!Iw)return n.warning("PlatformGateway.scheduleNotification(): HYTOPIA_NOTIFICATION_SERVICE_URL is not set. Unable to schedule notification.");if(!this.gameId||!this.creatorApiKey)return n.warning("PlatformGateway.scheduleNotification(): HYTOPIA_GAME_ID or HYTOPIA_API_KEY is not set. Unable to schedule notification.");if(B<Date.now()+60000)return n.warning("PlatformGateway.scheduleNotification(): scheduledFor must be at least 60 seconds in the future. Unable to schedule notification.");try{let Y=await fetch(`${Iw}/notifications`,{method:"POST",headers:{"Content-Type":"application/json","X-Game-Id":this.gameId,"X-Creator-Api-Key":this.creatorApiKey},body:JSON.stringify({hytopiaUserId:A,type:Q,scheduledFor:B})});if(!Y.ok)return n.warning(`PlatformGateway.scheduleNotification(): Failed ${Y.status}: ${await Y.text()}`);return(await Y.json()).id}catch(Y){return n.warning(`PlatformGateway.scheduleNotification(): Failed to schedule notification: ${Y}`)}}async setGlobalData(A,Q){if(Q.error)return n.warning("PlatformGateway.setGlobalData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return n.warning("PlatformGateway.setGlobalData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(A,Q):this._writeDevGlobalDataLocally(A,Q)}async unscheduleNotification(A){if(!Iw)return n.warning("PlatformGateway.unscheduleNotification(): HYTOPIA_NOTIFICATION_SERVICE_URL is not set."),!1;if(!this.gameId||!this.creatorApiKey)return n.warning("PlatformGateway.scheduleNotification(): HYTOPIA_GAME_ID or HYTOPIA_API_KEY is not set."),!1;try{let Q=await fetch(`${Iw}/notifications/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json","X-Game-Id":this.gameId,"X-Creator-Api-Key":this.creatorApiKey}});if(!Q.ok)return n.warning(`PlatformGateway.unscheduleNotification(): Failed ${Q.status}: ${await Q.text()}`),!1;return!0}catch(Q){return n.warning(`PlatformGateway.unscheduleNotification(): Failed to unschedule notification: ${Q}`),!1}}_readDevGlobalDataLocally(A){try{if(!EE.existsSync(LD))return{error:{code:"keyNotFound",message:"Local data directory not found."}};let Q=DVA.join(LD,`${A}.json`);return JSON.parse(EE.readFileSync(Q,"utf8"))}catch(Q){return n.warning(`PlatformGateway._readDevGlobalDataLocally(): Failed to read data for key "${A}": ${Q}`),{error:{code:"gatewayError",message:"Failed to read data for key."}}}}_writeDevGlobalDataLocally(A,Q){try{if(!EE.existsSync(LD))EE.mkdirSync(LD,{recursive:!0});let B=DVA.join(LD,`${A}.json`),Y={};if(EE.existsSync(B))Y=JSON.parse(EE.readFileSync(B,"utf8"));let J={...Y,...Q};EE.writeFileSync(B,JSON.stringify(J,null,2),"utf8")}catch(B){n.warning(`PlatformGateway._writeDevGlobalDataLocally(): Failed to write data for key "${A}": ${B}`)}}}class f7{static instance=new f7;_saveStatesClient;constructor(){this._saveStatesClient=new MVA.SaveStatesClient}async getGlobalData(A,Q=3){for(let B=0;B<=Q;B++){let Y=await H8.instance.getGlobalData(A);if(Y&&!Y.error)return Y;if(Y.error.code==="keyNotFound")return{};if(B<Q)n.warning(`PersistenceManager.getGlobalData(): Failed to get global data, retrying. Response: ${JSON.stringify(Y)}`),await new Promise((J)=>setTimeout(J,500))}n.warning(`PersistenceManager.getGlobalData(): Failed to get global data after ${Q} attempts.`);return}async getPlayerData(A){let Q=await this._saveStatesClient.load(this._getPlayerKey(A));if(!Q)return n.warning(`PersistenceManager.getPlayerData(): Failed to get player data for player ${A.id}. Persistence service may be down.`),{};return Q}async setGlobalData(A,Q){let B=await H8.instance.setGlobalData(A,Q);if(!B||B.error){if(B?.error)n.warning(`PersistenceManager.setGlobalData(): ${B.error.message}`)}}async setPlayerData(A,Q){let B=await this.getPlayerData(A);for(let[Y,J]of Object.entries(Q))B[Y]=J}async unloadPlayerData(A){await this._saveStatesClient.unload(this._getPlayerKey(A))}_getPlayerKey(A){return`player-${A.id}`}}var LVA;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})(LVA||={});var Ym;((I)=>{I.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";I.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";I.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";I.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";I.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";I.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";I.SET_FOV="PLAYER_CAMERA.SET_FOV";I.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";I.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";I.SET_MODE="PLAYER_CAMERA.SET_MODE";I.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";I.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";I.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";I.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";I.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(Ym||={});class qD extends YQ{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(A){super();this.player=A}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let A=this._orientation.pitch*0.5,Q=this._orientation.yaw*0.5,B=Math.cos(A),Y=Math.sin(A),J=Math.cos(Q),C=Math.sin(Q);return{x:Y*J,y:B*C,z:-Y*C,w:B*J}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(A){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:A})}lookAtPosition(A){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:A})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(A){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!A.isSpawned)return n.error(`PlayerCamera.setAttachedToEntity(): Entity ${A.id} is not spawned!`);this._attachedToEntity=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:A})}setAttachedToPosition(A){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:A})}setFilmOffset(A){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:A})}setForwardOffset(A){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:A})}setFov(A){if(!this._requirePlayerWorld("setFov"))return;this._fov=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:A})}setModelHiddenNodes(A){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(A){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(A){if(!this._requirePlayerWorld("setMode"))return;this._mode=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:A})}setOffset(A){if(!this._requirePlayerWorld("setOffset"))return;this._offset=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:A})}setOrientationPitch(A){this._orientation.pitch=A}setOrientationYaw(A){this._orientation.yaw=A}setShoulderAngle(A){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:A})}setTrackedEntity(A){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:A})}setTrackedPosition(A){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:A})}setZoom(A){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:A})}serialize(){return VQ.serializePlayerCamera(this)}_requirePlayerWorld(A){if(!this.player.world)n.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${A}()`);return!!this.player.world}}var Hw;((C)=>{C.DATA="PLAYER_UI.DATA";C.FREEZE_POINTER_LOCK="PLAYER_UI.FREEZE_POINTER_LOCK";C.LOAD="PLAYER_UI.LOAD";C.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";C.SEND_DATA="PLAYER_UI.SEND_DATA"})(Hw||={});class zD extends YQ{player;constructor(A){super();this.player=A}freezePointerLock(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.FREEZE_POINTER_LOCK",{playerUI:this,freeze:A})}load(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:A})}lockPointer(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:A})}sendData(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:A})}}var N7B=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0","cp","cy","iro","ird","jd"],RD;((G)=>{G.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";G.INTERACT="PLAYER.INTERACT";G.JOINED_WORLD="PLAYER.JOINED_WORLD";G.LEFT_WORLD="PLAYER.LEFT_WORLD";G.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";G.REQUEST_NOTIFICATION_PERMISSION="PLAYER.REQUEST_NOTIFICATION_PERMISSION";G.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(RD||={});class ZU extends YQ{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;cosmetics;ui;_input={};_interactEnabled=!0;_lastUnreliableInputSequenceNumber=0;_maxInteractDistance=20;_persistedData;_world;_worldSwitched=!1;constructor(A,Q){super();this.id=Q?.user.id??`player-${ZU._devNextPlayerId++}`,this.username=Q?.user.username??this.id,this.profilePictureUrl=Q?.user.profilePictureURL??void 0,this.camera=new qD(this),this.connection=A,this.cosmetics=H8.instance.getPlayerCosmetics(this.id),this.ui=new zD(this),A.onPacket(xA.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),A.onPacket(xA.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),A.onPacket(xA.PacketId.INPUT,this._onInputPacket),A.onPacket(xA.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),A.onPacket(xA.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get interactEnabled(){return this._interactEnabled}get maxInteractDistance(){return this._maxInteractDistance}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){if(!this._persistedData)return;let A=Object.keys(this._persistedData);if(A.length===0||A.length===1&&A[0]==="__version")return;return this._persistedData}joinWorld(A){if(this._world===A)return;if(!this._world)this._world=A,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let Q of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(Q.isSpawned)Q.despawn();this.disconnect(),this._world=A,this._worldSwitched=!0}}async scheduleNotification(A,Q){if(!this._world)return n.warning("Player.scheduleNotification(): Player must be in a world to schedule a notification.");return this.emitWithWorld(this._world,"PLAYER.REQUEST_NOTIFICATION_PERMISSION",{player:this}),H8.instance.scheduleNotification(this.id,A,Q)}async unscheduleNotification(A){if(!A)return!1;return H8.instance.unscheduleNotification(A)}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await f7.instance.getPlayerData(this)}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setInteractEnabled(A){this._interactEnabled=A}setMaxInteractDistance(A){this._maxInteractDistance=A}setPersistedData(A){if(!this._persistedData){n.warning(`Player.setPersistedData(): Persisted data not found for player ${this.id}`);return}for(let[Q,B]of Object.entries(A))this._persistedData[Q]=B}serialize(){return VQ.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(A)=>{if(!this._world)return;let Q=A[1].m;if(this._world.chatManager.handleCommand(this,Q)){this._world.chatManager.sendPlayerMessage(this,`Command Entered: ${Q}`,"CCCCCC");return}if(this.id.startsWith("guest")){this._world.chatManager.sendPlayerMessage(this,"You need to create a HYTOPIA account to send messages in chat.","FFAA00");return}this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:Q})};_onDebugConfigPacket=(A)=>{console.log(A)};_onInputPacket=(A)=>{let Q=A[1];if(Q.sq!==void 0){if(Q.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=Q.sq}if(Object.assign(this._input,Q),Q.cp!==void 0)this.camera.setOrientationPitch(Q.cp);if(Q.cy!==void 0)this.camera.setOrientationYaw(Q.cy);if(this.world&&Q.ird&&Q.iro)this.interact()};interact=()=>{if(!this.world||!this._input.ird||!this._input.iro)return;if(this._interactEnabled){let A={x:this._input.iro[0],y:this._input.iro[1],z:this._input.iro[2]},Q={x:this._input.ird[0],y:this._input.ird[1],z:this._input.ird[2]},B=this.world.entityManager.getPlayerEntitiesByPlayer(this)[0],Y=this.world.simulation.raycast(A,Q,this._maxInteractDistance,{filterExcludeRigidBody:B?.rawRigidBody,filterFlags:WB.QueryFilterFlags.EXCLUDE_SENSORS});if(this.emitWithWorld(this.world,"PLAYER.INTERACT",{player:this,interactOrigin:A,interactDirection:Q,raycastHit:Y}),Y?.hitEntity)Y.hitEntity.interact(this,Y);if(Y?.hitBlock)Y.hitBlock.blockType.interact(this,Y)}};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(A)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:A[1]})}}var Jm;((B)=>{B.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";B.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(Jm||={});class wD extends YQ{_commandCallbacks={};_world;constructor(A){super();this._world=A,this._subscribeToPlayerEvents()}registerCommand(A,Q){this._commandCallbacks[A]=Q}unregisterCommand(A){delete this._commandCallbacks[A]}sendBroadcastMessage(A,Q){this._sendBroadcastMessage(void 0,A,Q)}handleCommand(A,Q){let[B,...Y]=Q.split(" "),J=this._commandCallbacks[B];if(J)return J(A,Y,Q),!0;return!1}sendPlayerMessage(A,Q,B){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:A,message:Q,color:B})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(A)=>{let{player:Q,message:B}=A;this._sendBroadcastMessage(Q,B)})}_sendBroadcastMessage(A,Q,B){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:A,message:Q,color:B})}}var LC=16,Cm=LC-1,M7B=LC**3;class v9{_blocks;_originCoordinate;constructor(A){this._blocks=new Uint8Array(M7B),this._originCoordinate=A}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(A){return{x:A%LC,y:(A/LC|0)%LC,z:A/(LC*LC)|0}}static globalCoordinateToLocalCoordinate(A){return{x:A.x&LC-1,y:A.y&LC-1,z:A.z&LC-1}}static globalCoordinateToOriginCoordinate(A){return{x:A.x&~(LC-1),y:A.y&~(LC-1),z:A.z&~(LC-1)}}getBlockId(A){return this._blocks[this._getIndex(A)]}hasBlock(A){return this._blocks[this._getIndex(A)]!==0}setBlock(A,Q){if(!this._isValidLocalCoordinate(A))return n.error("Chunk.setBlock(): Block local coordinate is out of bounds");let B=this._getIndex(A);this._blocks[B]=Q}serialize(){return VQ.serializeChunk(this)}_getIndex(A){return A.x+(A.y<<4)+(A.z<<8)}_isValidLocalCoordinate(A){return A.x>=0&&A.x<=Cm&&A.y>=0&&A.y<=Cm&&A.z>=0&&A.z<=Cm}}var Xm;((Y)=>{Y.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";Y.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";Y.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(Xm||={});class jD extends YQ{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(A){super();this._world=A}get chunkCount(){return this._chunks.size}clear(){for(let A of this._blockTypeColliders.values())A.removeFromSimulation();this._chunks.forEach((A)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:A})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(A){let Q=this.getChunk(v9.globalCoordinateToOriginCoordinate(A));if(!Q)return 0;return Q.getBlockId(v9.globalCoordinateToLocalCoordinate(A))}getBlockTypeCollider(A){return this._blockTypeColliders.get(A)}getBlockType(A){let Q=this.getBlockId(A);return Q?this._world.blockTypeRegistry.getBlockType(Q):null}getBlockTypeCount(A){return this._blockTypeCounts.get(A)??0}getChunk(A){return this._chunks.get(this._getChunkKey(v9.globalCoordinateToOriginCoordinate(A)))}getOrCreateBlockTypeCollider(A,Q){let B=this._blockTypeColliders.get(A);if(B)return B;let J=this._world.blockTypeRegistry.getBlockType(A).createCollider(Q);return this._blockTypeColliders.set(A,J),J}getOrCreateChunk(A){let Q=v9.globalCoordinateToOriginCoordinate(A),B=this._chunks.get(this._getChunkKey(Q));if(B)return B;return B=new v9(Q),this._chunks.set(this._getChunkKey(Q),B),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:B}),B}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(A){let Q=this.getChunk(v9.globalCoordinateToOriginCoordinate(A));if(!Q)return!1;return Q.hasBlock(v9.globalCoordinateToLocalCoordinate(A))}hasChunk(A){let Q=v9.globalCoordinateToOriginCoordinate(A);return this._chunks.has(this._getChunkKey(Q))}initializeBlocks(A){if(this.clear(),!this._rigidBody)this._rigidBody=new j7({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);for(let Q in A){let B=Number(Q),Y=A[B];if(Y.length===0)continue;let J=this.getOrCreateBlockTypeCollider(B,Y);J.addToSimulation(this._world.simulation,this._rigidBody);let C=this._world.blockTypeRegistry.getBlockType(B);this._world.simulation.colliderMap.setColliderBlockType(J,C),this._blockTypeCounts.set(B,Y.length);for(let X=0;X<Y.length;X++){let G=Y[X],F=v9.globalCoordinateToLocalCoordinate(G),W=this.getOrCreateChunk(G);W.setBlock(F,B),this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:W,globalCoordinate:G,localCoordinate:F,blockTypeId:B})}this._combineVoxelStates(J)}}setBlock(A,Q){let B=v9.globalCoordinateToLocalCoordinate(A),Y=this.getOrCreateChunk(A),J=Y.getBlockId(B);if(J===Q)return;if(Y.setBlock(B,Q),!this._rigidBody)this._rigidBody=new j7({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(J!==0){let C=Math.max(0,(this._blockTypeCounts.get(J)??0)-1),X=this.getBlockTypeCollider(J);if(X)if(C===0)this._world.simulation.colliderMap.removeColliderBlockType(X),X.removeFromSimulation(),this._blockTypeColliders.delete(J);else X.setVoxel(A,!1),this._propagateVoxelChange(X,A);this._blockTypeCounts.set(J,C)}if(Q!==0){let C=(this._blockTypeCounts.get(Q)??0)+1,X=this.getOrCreateBlockTypeCollider(Q,[A]);if(C===1){let G=this._world.blockTypeRegistry.getBlockType(Q);X.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(X,G),this._combineVoxelStates(X)}else X.setVoxel(A,!0),this._propagateVoxelChange(X,A);this._blockTypeCounts.set(Q,C)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:Y,globalCoordinate:A,localCoordinate:B,blockTypeId:Q})}_combineVoxelStates(A){if(A.isSensor)return;for(let Q of this._blockTypeColliders.values()){if(Q===A||Q.isSensor)continue;A.combineVoxelStates(Q)}}_getChunkKey(A){return`${A.x},${A.y},${A.z}`}_propagateVoxelChange(A,Q){if(A.isSensor)return;for(let B of this._blockTypeColliders.values()){if(B===A||B.isSensor)continue;A.propagateVoxelChange(B,Q)}}}class OD{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(A){if(!this._requireSimulatedCollider(A))return;return this._colliderHandleBlockTypeMap.get(A.rawCollider.handle)}getColliderCollisionCallback(A){if(!this._requireSimulatedCollider(A))return;return this._colliderHandleCollisionCallbackMap.get(A.rawCollider.handle)}getColliderEntity(A){if(!this._requireSimulatedCollider(A))return;return this._colliderHandleEntityMap.get(A.rawCollider.handle)}getColliderHandleBlockType(A){return this._colliderHandleBlockTypeMap.get(A)}getColliderHandleCollisionCallback(A){return this._colliderHandleCollisionCallbackMap.get(A)}getColliderHandleEntity(A){return this._colliderHandleEntityMap.get(A)}removeColliderBlockType(A){if(!this._requireSimulatedCollider(A))return;this.removeColliderHandleBlockType(A.rawCollider.handle)}removeColliderCollisionCallback(A){if(!this._requireSimulatedCollider(A))return;this.removeColliderHandleCollisionCallback(A.rawCollider.handle)}removeColliderEntity(A){if(!this._requireSimulatedCollider(A))return;this.removeColliderHandleEntity(A.rawCollider.handle)}removeColliderHandleBlockType(A){this._colliderHandleBlockTypeMap.delete(A)}removeColliderHandleCollisionCallback(A){this._colliderHandleCollisionCallbackMap.delete(A)}removeColliderHandleEntity(A){this._colliderHandleEntityMap.delete(A)}setColliderBlockType(A,Q){if(!this._requireSimulatedCollider(A))return;this.setColliderHandleBlockType(A.rawCollider.handle,Q)}setColliderCollisionCallback(A,Q){if(!this._requireSimulatedCollider(A))return;this.setColliderHandleCollisionCallback(A.rawCollider.handle,Q)}setColliderEntity(A,Q){if(!this._requireSimulatedCollider(A))return;this.setColliderHandleEntity(A.rawCollider.handle,Q)}setColliderHandleBlockType(A,Q){this._colliderHandleBlockTypeMap.set(A,Q),this._cleanupBlockTypeColliderHandles.delete(A),this._pendingCleanupBlockTypeColliderHandles.delete(A)}setColliderHandleCollisionCallback(A,Q){this._colliderHandleCollisionCallbackMap.set(A,Q),this._cleanupCollisionCallbackColliderHandles.delete(A),this._pendingCleanupCollisionCallbackColliderHandles.delete(A)}setColliderHandleEntity(A,Q){this._colliderHandleEntityMap.set(A,Q),this._cleanupEntityColliderHandles.delete(A),this._pendingCleanupEntityColliderHandles.delete(A)}queueColliderHandleForCleanup(A){if(this._colliderHandleBlockTypeMap.has(A))this._pendingCleanupBlockTypeColliderHandles.add(A);if(this._colliderHandleCollisionCallbackMap.has(A))this._pendingCleanupCollisionCallbackColliderHandles.add(A);if(this._colliderHandleEntityMap.has(A))this._pendingCleanupEntityColliderHandles.add(A)}cleanup(){for(let A of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(A);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let A of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(A);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let A of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(A);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let A of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(A);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let A of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(A);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let A of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(A);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(A){if(!A.rawCollider)n.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!A.rawCollider}}var qVA={type:"dynamic",softCcdPrediction:1},zVA=0.015625,RVA=Math.cos(0.026),PD;((q)=>{q.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";q.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";q.DESPAWN="ENTITY.DESPAWN";q.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";q.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";q.INTERACT="ENTITY.INTERACT";q.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";q.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";q.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";q.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";q.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";q.SET_OPACITY="ENTITY.SET_OPACITY";q.SET_PARENT="ENTITY.SET_PARENT";q.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";q.SPAWN="ENTITY.SPAWN";q.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";q.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";q.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";q.TICK="ENTITY.TICK";q.UPDATE_POSITION="ENTITY.UPDATE_POSITION";q.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(PD||={});class CY extends j7{_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale={x:1,y:1,z:1};_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(A){let Q="blockTextureUri"in A,B="modelUri"in A;if(!Q===!B)n.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(Q&&!A.blockHalfExtents)n.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(A.parent&&!A.parent.isSpawned)n.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(A.parent?.modelUri&&A.parentNodeName&&!BJ.instance.modelHasNode(A.parent.modelUri,A.parentNodeName))n.fatalError(`Entity.constructor(): Parent node name ${A.parentNodeName} not found in parent model ${A.parent.modelUri}!`);super(A.rigidBodyOptions??qVA);if(Q)this._blockHalfExtents=A.blockHalfExtents,this._blockTextureUri=A.blockTextureUri;if(B){let Y=this._modelScale=typeof A.modelScale==="number"?{x:A.modelScale,y:A.modelScale,z:A.modelScale}:A.modelScale??{x:1,y:1,z:1};if(this._modelAnimationsPlaybackRate=A.modelAnimationsPlaybackRate??1,this._modelPreferredShape=A.modelPreferredShape,this._modelScale=Y,this._modelTextureUri=A.modelTextureUri,this._modelUri=A.modelUri,!this._modelUri.startsWith("http")&&!BJ.instance.hasModel(this._modelUri))n.error(`Entity.constructor(): Model ${this._modelUri} does not exist!`);A.modelHiddenNodes?.forEach((J)=>this._modelHiddenNodes.add(J.toLowerCase())),A.modelLoopedAnimations?.forEach((J)=>this._modelLoopedAnimations.add(J)),A.modelShownNodes?.forEach((J)=>this._modelShownNodes.add(J.toLowerCase()))}if(this._isEnvironmental=A.isEnvironmental??!1,this._name=A.name??"Nameless",this._opacity=A.opacity??1,this._parent=A.parent,this._parentNodeName=A.parentNodeName,this._tag=A.tag,this._tintColor=A.tintColor,this._positionUpdateThresholdSq=zVA,this._rotationUpdateThreshold=RVA,A.controller)this.setController(A.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?BJ.instance.getDepth(this._modelUri)*this._modelScale.z:this._blockHalfExtents.z*2}get height(){return this.isModelEntity?BJ.instance.getHeight(this._modelUri)*this._modelScale.y:this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?BJ.instance.getWidth(this._modelUri)*this._modelScale.x:this._blockHalfExtents.x*2}get world(){return this._world}spawn(A,Q,B){if(this.isSpawned)return n.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(A.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new IC(IC.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new IC(IC.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach((Y)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))Y.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Y.enableContactForceEvents(!0);if(P5.isDefaultCollisionGroups(Y.collisionGroups)){let J=this.isEnvironmental?[8]:[Y.isSensor?4:2],C=this.isEnvironmental?[65535&~8&~1]:[65535];Y.setCollisionGroups({belongsTo:J,collidesWith:C})}}),this.setPosition(Q),B)this.setRotation(B);if(this._id=A.entityManager.registerEntity(this),this._world=A,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,Q,B);this.colliders.forEach((Y)=>{A.simulation.colliderMap.setColliderEntity(Y,this)}),this.emitWithWorld(A,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((A)=>{A.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}interact(A,Q){if(!this._requireSpawned("interact"))return;this.emitWithWorld(this._world,"ENTITY.INTERACT",{entity:this,player:A,raycastHit:Q})}setController(A){if(this._controller===A)return;if(this._controller)this._controller.detach(this);if(this._controller=A,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(A){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===A)return;this._modelAnimationsPlaybackRate=A,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:A})}setModelHiddenNodes(A){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(A){if(!this._requireSpawned("setModelScale"))return;if(typeof A==="number")A={x:A,y:A,z:A};if(!this.isModelEntity||this._modelScale===A)return;let Q={x:A.x/this._modelScale.x,y:A.y/this._modelScale.y,z:A.z/this._modelScale.z};this._modelScale=A,this.colliders.forEach((B)=>B.setScale(Q)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:A})}setModelShownNodes(A){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(A){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===A)return;this._modelTextureUri=A,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:A})}setOpacity(A){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===A)return;this._opacity=A,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:A})}setParent(A,Q,B,Y){if(!this._requireSpawned("setParent"))return;if(A&&!A.isSpawned)return n.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&A)this._lastParentlessType=this.type;if(this._parent=A,this._parentNodeName=Q,this.colliders.forEach((J)=>J.setEnabled(!A)),this.setType(!A?this._lastParentlessType:"kinematic_velocity"),this.setPosition(B??{x:0,y:0,z:0}),this.setRotation(Y??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:A,parentNodeName:Q})}setTintColor(A){if(!this._requireSpawned("setTintColor"))return;if(!A&&!this._tintColor||A&&this._tintColor&&A.r===this._tintColor.r&&A.g===this._tintColor.g&&A.b===this._tintColor.b)return;this._tintColor=A,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:A})}startModelLoopedAnimations(A){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!A.length)return;if(!A.some((Q)=>!this._modelLoopedAnimations.has(Q)))return;A.forEach((Q)=>{this._modelLoopedAnimations.add(Q)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(A)})}startModelOneshotAnimations(A){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!A.length)return;A.forEach((Q)=>{this._modelOneshotAnimations.add(Q)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(A)})}stopAllModelAnimations(A=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],A)}stopAllModelLoopedAnimations(A=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],A)}stopAllModelOneshotAnimations(A=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],A)}stopModelAnimations(A){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!A.length)return;if(!A.some((Q)=>this._modelLoopedAnimations.has(Q))&&!A.some((Q)=>this._modelOneshotAnimations.has(Q)))return;A.forEach((Q)=>{this._modelLoopedAnimations.delete(Q),this._modelOneshotAnimations.delete(Q)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(A)})}serialize(){return VQ.serializeEntity(this)}tick(A){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:A}),this._controller)this._controller.tick(this,A)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let A=this.position,Q=this.rotation;if(this._rotationExceedsThreshold(Q,this._lastUpdatedRotation))this._lastUpdatedRotation=Q,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:Q});if(this._positionExceedsThreshold(A,this._lastUpdatedPosition))this._lastUpdatedPosition=A,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:A})}_positionExceedsThreshold(A,Q){let B=A.x-Q.x,Y=A.y-Q.y,J=A.z-Q.z;return B*B+Y*Y+J*J>this._positionUpdateThresholdSq}_requireSpawned(A){if(!this.isSpawned)n.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${A}()!`);return this.isSpawned}_rotationExceedsThreshold(A,Q){return Math.abs(A.x*Q.x+A.y*Q.y+A.z*Q.z+A.w*Q.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(A,Q=[]){if(!this.isModelEntity)return;let B=new Set(Q),Y=[];for(let J of A)for(let C of J)if(!B.has(C))Y.push(C);if(Y.length>0)this.stopModelAnimations(Y)}}class J0 extends UW{static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(A={}){super();this.applyDirectionalMovementRotations=A.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=A.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=A.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=A.sticksToPlatforms??this.sticksToPlatforms,this.canJump=A.canJump??this.canJump,this.canRun=A.canRun??this.canRun,this.canSwim=A.canSwim??this.canSwim,this.canWalk=A.canWalk??this.canWalk,this.jumpVelocity=A.jumpVelocity??this.jumpVelocity,this.runVelocity=A.runVelocity??this.runVelocity,this.walkVelocity=A.walkVelocity??this.walkVelocity,this.swimFastVelocity=A.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=A.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=A.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=A.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=A.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=A.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=A.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=A.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=A.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=A.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=A.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=A.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=A.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=A.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(A){super.attach(A),this._internalApplyImpulse=A.applyImpulse.bind(A),A.applyImpulse=(Q)=>{let B=A.mass||1;this._externalVelocity.x+=Q.x/B,this._externalVelocity.y+=Q.y/B,this._externalVelocity.z+=Q.z/B},this._stepAudio=new LV({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:A}),A.setCcdEnabled(!0),A.lockAllRotations(),A.on("ENTITY.BLOCK_COLLISION",({blockType:Q,started:B})=>{if(!Q.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&B){let Y=A.linearVelocity;A.setLinearVelocity({x:Y.x*this.swimGravity,y:Y.y*this.swimGravity,z:Y.z*this.swimGravity})}if(this._liquidContactCount+=B?1:-1,this._liquidContactCount>0)A.setGravityScale(this.swimGravity),A.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+J0.SWIM_UPWARD_COOLDOWN_MS;else A.setGravityScale(1),A.stopModelAnimations(this.swimLoopedAnimations)})}spawn(A){if(!A.isSpawned)return n.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");A.createAndAddChildCollider({shape:"cylinder",radius:J0.GROUND_SENSOR_RADIUS_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),halfHeight:J0.GROUND_SENSOR_HEIGHT_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-A.height/2,z:0},tag:"groundSensor",onCollision:(Q,B)=>{if(!A.isSpawned)return;if(!(Q instanceof HC)||!Q.isLiquid){if(B&&this._groundContactCount===0&&A.linearVelocity.y<-1)if(A.linearVelocity.y<J0.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)A.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else A.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=B?1:-1}if(!this._groundContactCount&&!this.isSwimming)A.startModelOneshotAnimations(this.jumpOneshotAnimations);else A.stopModelAnimations(this.jumpOneshotAnimations);if(!(Q instanceof CY))return;if(B&&this.sticksToPlatforms)this._platform=Q;else if(Q===this._platform&&!B)this._platform=void 0}}),A.createAndAddChildCollider({shape:"capsule",halfHeight:J0.WALL_COLLIDER_HEIGHT_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),radius:J0.WALL_COLLIDER_RADIUS_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(A,Q,B,Y){if(!A.isSpawned||!A.world)return;if(super.tickWithPlayerInput(A,Q,B,Y),A.parent)return;let{w:J,a:C,s:X,d:G,c:F,sp:W,sh:E,ml:$,jd:Z}=Q,{yaw:U}=B,K=A.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0;let I=typeof Z==="number";this._isActivelyMoving=I||!!(J||C||X||G);let V=E,H=!I&&(C&&G&&!J&&!X||J&&X&&!C&&!G),D=V&&this.canRun(this)||!V&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+J0.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!H&&D){let w=V?this.runLoopedAnimations:this.walkLoopedAnimations;A.stopAllModelLoopedAnimations(w),A.startModelLoopedAnimations(w),this._stepAudio?.setPlaybackRate(V?0.75:0.51),this._stepAudio?.play(A.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)A.stopAllModelLoopedAnimations(this.swimLoopedAnimations),A.startModelLoopedAnimations(this.swimLoopedAnimations);else A.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),A.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),A.stopAllModelLoopedAnimations(this.idleLoopedAnimations),A.startModelLoopedAnimations(this.idleLoopedAnimations);let M;if(this.applyDirectionalMovementRotations&&D){if(I)M=Z;else if(J&&C&&!G&&!X)M=J0.MOVEMENT_ROTATIONS.wa;else if(J&&G&&!C&&!X)M=J0.MOVEMENT_ROTATIONS.wd;else if(X&&C&&!J&&!G)M=J0.MOVEMENT_ROTATIONS.sa;else if(X&&G&&!J&&!C)M=J0.MOVEMENT_ROTATIONS.sd;else if(X&&!J&&!C&&!G||C&&X&&G&&!J)M=J0.MOVEMENT_ROTATIONS.s;else if(C&&!J&&!X&&!G)M=J0.MOVEMENT_ROTATIONS.a;else if(G&&!J&&!C&&!X)M=J0.MOVEMENT_ROTATIONS.d}if($)A.startModelOneshotAnimations(this.interactOneshotAnimations),Q.ml=!this.autoCancelMouseLeftClick;if(D){let w=!this.isSwimming?V?this.runVelocity:this.walkVelocity:V?this.swimFastVelocity:this.swimSlowVelocity;if(I){let P=U+Z;this._reusableTargetVelocities.x=-w*Math.sin(P),this._reusableTargetVelocities.z=-w*Math.cos(P)}else{let P=Math.sin(U),_=Math.cos(U);if(J)this._reusableTargetVelocities.x-=w*P,this._reusableTargetVelocities.z-=w*_;if(X)this._reusableTargetVelocities.x+=w*P,this._reusableTargetVelocities.z+=w*_;if(C)this._reusableTargetVelocities.x-=w*_,this._reusableTargetVelocities.z+=w*P;if(G)this._reusableTargetVelocities.x+=w*_,this._reusableTargetVelocities.z-=w*P;let O=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(O>w){let k=w/O;this._reusableTargetVelocities.x*=k,this._reusableTargetVelocities.z*=k}}}if(this.isSwimming){if(K.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=K.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=K.z,A.setLinearVelocity(this._reusableVelocityClamp);if(K.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=K.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=K.z,A.setLinearVelocity(this._reusableVelocityClamp);if(F)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*J0.WATER_ENTRY_SINKING_FACTOR;else if(!W)this._reusableTargetVelocities.y=-K.y*J0.SWIMMING_DRAG_FACTOR}if(W&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&K.y>-0.001&&K.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let z=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let w=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(w>0.01){let _=Math.max(0,w-J0.EXTERNAL_IMPULSE_DECAY_RATE)/w;this._externalVelocity.x*=_,this._magnitudeYTracker*=_,this._externalVelocity.z*=_}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let q=this._reusableTargetVelocities.x+this._externalVelocity.x-K.x+z.x,N=this._reusableTargetVelocities.y+this._externalVelocity.y+z.y,L=this._reusableTargetVelocities.z+this._externalVelocity.z-K.z+z.z;if(this._externalVelocity.y=0,q!==0||N!==0||L!==0){let w=A.mass;this._reusableImpulse.x=q*w,this._reusableImpulse.y=N*w,this._reusableImpulse.z=L*w,this._internalApplyImpulse(this._reusableImpulse)}if(U!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let P=(M!==void 0?U+M:U)*0.5;A.setRotation({x:0,y:Math.sin(P),z:0,w:Math.cos(P)})}}}var Gm;((G)=>{G.LOAD="SCENE_UI.LOAD";G.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";G.SET_OFFSET="SCENE_UI.SET_OFFSET";G.SET_POSITION="SCENE_UI.SET_POSITION";G.SET_STATE="SCENE_UI.SET_STATE";G.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";G.UNLOAD="SCENE_UI.UNLOAD"})(Gm||={});class TD extends YQ{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(A){if(!!A.attachedToEntity===!!A.position)n.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=A.attachedToEntity,this._offset=A.offset,this._position=A.position,this._state=A.state??{},this._templateId=A.templateId,this._viewDistance=A.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(A){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=A.sceneUIManager.registerSceneUI(this),this._world=A,this.emitWithWorld(A,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(A){if(!A.isSpawned)return n.error(`SceneUI.setAttachedToEntity(): Entity ${A.id} is not spawned!`);if(this._attachedToEntity===A)return;if(this._attachedToEntity=A,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:A})}setOffset(A){if(this._offset===A)return;if(this._offset=A,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:A})}setPosition(A){if(this._position===A)return;if(this._attachedToEntity=void 0,this._position=A,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:A})}setState(A){if(this._state={...this._state,...A},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(A){if(this._viewDistance=A,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:A})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return VQ.serializeSceneUI(this)}}var wVA=0.010000000000000002,jVA=Math.cos(0.026);class i1 extends CY{player;nametagSceneUI;constructor(A){super(A);this._positionUpdateThresholdSq=wVA,this._rotationUpdateThreshold=jVA,this.player=A.player,this.nametagSceneUI=new TD({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(A,Q,B){super.spawn(A,Q,B),this.nametagSceneUI.load(A),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:Y})=>{this.nametagSceneUI.setState({chat:Y})})}tick(A){if(!this.isSpawned||!this.world)return;if(!this.controller)return n.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:Q,camera:B}=this.player;this.controller.tickWithPlayerInput(this,Q,B.orientation,A),super.tick(A)}}var OVA="models/players/player.gltf",L7B={BACK:"back-anchor",HEAD:"head-anchor",LEFT_ARM:"arm-left-anchor",LEFT_FOOT:"foot-left-anchor",LEFT_HAND:"hand-left-anchor",LEFT_ITEM:"hand-left-anchor",LEFT_LEG:"leg-left-anchor",RIGHT_ARM:"arm-right-anchor",RIGHT_FOOT:"foot-right-anchor",RIGHT_HAND:"hand-right-anchor",RIGHT_ITEM:"hand-right-anchor",RIGHT_LEG:"leg-right-anchor",TORSO:"torso-anchor"};class Fm extends i1{_cosmeticHiddenSlots;constructor(A){super({modelUri:OVA,modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...A});if(this._cosmeticHiddenSlots=A.cosmeticHiddenSlots??[],!A.controller)this.setController(new J0)}get cosmeticHiddenSlots(){return this._cosmeticHiddenSlots}spawn(A,Q,B){super.spawn(A,Q,B),this.player.cosmetics.then((Y)=>{if(!Y||!this.modelUri)return;let J=this.modelShownNodes.values().toArray().filter((G)=>!G.includes("hair-"));if(!(Y.equippedItems.some((G)=>G.item.flags.includes("HIDES_HAIR"))&&!this._cosmeticHiddenSlots.includes("ALL")&&!this._cosmeticHiddenSlots.includes("HEAD")))J.push(`hair-${String(Y.hairStyle).padStart(4,"0")}`);if(this.setModelShownNodes(J),this.modelUri===OVA)this.setModelTextureUri(Y.skinTextureUri);if(this._cosmeticHiddenSlots.includes("ALL"))return;let X=[];for(let G of Y.equippedItems){let{item:F,slot:W}=G;if(this._cosmeticHiddenSlots.includes(W))continue;let E=L7B[W];if(!E||!BJ.instance.modelHasNode(this.modelUri,E))continue;if(F.flags.includes("REPLACES_LIMB")){let Z=E.split("-").slice(0,-1).join("-");X.push(`${Z}-clothing`,`${Z}-geometry`)}new CY({modelUri:F.modelUrl,modelPreferredShape:"none",parent:this,parentNodeName:E}).spawn(A,{x:0,y:0,z:0})}if(X.length>0)this.setModelHiddenNodes([...this.modelHiddenNodes.values().toArray(),...X])}).catch((Y)=>n.warning(`DefaultPlayerEntity.spawn(): Failed to get player cosmetics: ${Y}`))}}class SD{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(A){this._world=A}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(A){if(A.id!==void 0)n.fatalError(`EntityManager.registerEntity(): Entity ${A.name} is already assigned the id ${A.id}!`);let Q=this._nextEntityId;if(this._entities.set(Q,A),this._nextEntityId++,!A.isEnvironmental)this._activeEntities.add(A);return Q}unregisterEntity(A){if(A.id===void 0)return n.error(`EntityManager.unregisterEntity(): Entity ${A.name} is not assigned an id!`);if(this._entities.delete(A.id),!A.isEnvironmental)this._activeEntities.delete(A)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let A=[];return this._entities.forEach((Q)=>{if(Q instanceof i1)A.push(Q)}),A}getPlayerEntitiesByPlayer(A){let Q=[];return this._entities.forEach((B)=>{if(B instanceof i1&&B.player===A)Q.push(B)}),Q}getEntity(A){return this._entities.get(A)}getEntitiesByTag(A){let Q=[];return this._entities.forEach((B)=>{if(B.tag===A)Q.push(B)}),Q}getEntitiesByTagSubstring(A){let Q=[];return this._entities.forEach((B)=>{if(B.tag?.includes(A))Q.push(B)}),Q}getEntityChildren(A){let Q=[];return this._entities.forEach((B)=>{if(B.parent===A)Q.push(B)}),Q}tickEntities(A){for(let Q of this._activeEntities)Q.tick(A)}checkAndEmitUpdates(){for(let A of this._activeEntities)A.checkAndEmitUpdates()}}import{gzipSync as Pf0}from"zlib";var B9=LA(kIA(),1),UDY=B9.default.v1,KDY=B9.default.v1ToV6,VDY=B9.default.v3,_IA=B9.default.v4,IDY=B9.default.v5,HDY=B9.default.v6,DDY=B9.default.v6ToV1,NDY=B9.default.v7,MDY=B9.default.NIL,LDY=B9.default.MAX,qDY=B9.default.version,zDY=B9.default.validate,RDY=B9.default.stringify,wDY=B9.default.parse;var Im;try{Im=new TextDecoder}catch(A){}var _A,zC,o=0;var Mm=[],$E=Mm,vD=0,tB={},DB,bG,qC=0,D8=0,PY,mG,g9=[],$B,vIA={useRecords:!1,mapsAsObjects:!0};class ww{}var Lm=new ww;Lm.name="MessagePack 0xC1";var b7=!1,uIA=2,Hm,Dm,Nm;try{Function("")}catch(A){uIA=1/0}class uG{constructor(A){if(A){if(A.useRecords===!1&&A.mapsAsObjects===void 0)A.mapsAsObjects=!0;if(A.sequential&&A.trusted!==!1){if(A.trusted=!0,!A.structures&&A.useRecords!=!1){if(A.structures=[],!A.maxSharedStructures)A.maxSharedStructures=0}}if(A.structures)A.structures.sharedLength=A.structures.length;else if(A.getStructures)(A.structures=[]).uninitialized=!0,A.structures.sharedLength=0;if(A.int64AsNumber)A.int64AsType="number"}Object.assign(this,A)}unpack(A,Q){if(_A)return oIA(()=>{return Rw(),this?this.unpack(A,Q):uG.prototype.unpack.call(vIA,A,Q)});if(!A.buffer&&A.constructor===ArrayBuffer)A=typeof Buffer<"u"?Buffer.from(A):new Uint8Array(A);if(typeof Q==="object")zC=Q.end||A.length,o=Q.start||0;else o=0,zC=Q>-1?Q:A.length;vD=0,D8=0,bG=null,$E=Mm,PY=null,_A=A;try{$B=A.dataView||(A.dataView=new DataView(A.buffer,A.byteOffset,A.byteLength))}catch(B){if(_A=null,A instanceof Uint8Array)throw B;throw Error("Source must be a Uint8Array or Buffer but was a "+(A&&typeof A=="object"?A.constructor.name:typeof A))}if(this instanceof uG){if(tB=this,this.structures)return DB=this.structures,qw(Q);else if(!DB||DB.length>0)DB=[]}else if(tB=vIA,!DB||DB.length>0)DB=[];return qw(Q)}unpackMultiple(A,Q){let B,Y=0;try{b7=!0;let J=A.length,C=this?this.unpack(A,J):Ow.unpack(A,J);if(Q){if(Q(C,Y,o)===!1)return;while(o<J)if(Y=o,Q(qw(),Y,o)===!1)return}else{B=[C];while(o<J)Y=o,B.push(qw());return B}}catch(J){throw J.lastPosition=Y,J.values=B,J}finally{b7=!1,Rw()}}_mergeStructures(A,Q){if(Dm)A=Dm.call(this,A);if(A=A||[],Object.isFrozen(A))A=A.map((B)=>B.slice(0));for(let B=0,Y=A.length;B<Y;B++){let J=A[B];if(J){if(J.isShared=!0,B>=32)J.highByte=B-32>>5}}A.sharedLength=A.length;for(let B in Q||[])if(B>=0){let Y=A[B],J=Q[B];if(J){if(Y)(A.restoreStructures||(A.restoreStructures=[]))[B]=Y;A[B]=J}}return this.structures=A}decode(A,Q){return this.unpack(A,Q)}}function qw(A){try{if(!tB.trusted&&!b7){let B=DB.sharedLength||0;if(B<DB.length)DB.length=B}let Q;if(tB.randomAccessStructure&&_A[o]<64&&_A[o]>=32&&Hm){if(Q=Hm(_A,o,zC,tB),_A=null,!(A&&A.lazy)&&Q)Q=Q.toJSON();o=zC}else Q=XY();if(PY)o=PY.postBundlePosition,PY=null;if(b7)DB.restoreStructures=null;if(o==zC){if(DB&&DB.restoreStructures)yIA();if(DB=null,_A=null,mG)mG=null}else if(o>zC)throw Error("Unexpected end of MessagePack data");else if(!b7){let B;try{B=JSON.stringify(Q,(Y,J)=>typeof J==="bigint"?`${J}n`:J).slice(0,100)}catch(Y){B="(JSON view not available "+Y+")"}throw Error("Data read, but end of buffer not reached "+B)}return Q}catch(Q){if(DB&&DB.restoreStructures)yIA();if(Rw(),Q instanceof RangeError||Q.message.startsWith("Unexpected end of buffer")||o>zC)Q.incomplete=!0;throw Q}}function yIA(){for(let A in DB.restoreStructures)DB[A]=DB.restoreStructures[A];DB.restoreStructures=null}function XY(){let A=_A[o++];if(A<160)if(A<128)if(A<64)return A;else{let Q=DB[A&63]||tB.getStructures&&dIA()[A&63];if(Q){if(!Q.read)Q.read=qm(Q,A&63);return Q.read()}else return A}else if(A<144)if(A-=128,tB.mapsAsObjects){let Q={};for(let B=0;B<A;B++){let Y=aIA();if(Y==="__proto__")Y="__proto_";Q[Y]=XY()}return Q}else{let Q=new Map;for(let B=0;B<A;B++)Q.set(XY(),XY());return Q}else{A-=144;let Q=Array(A);for(let B=0;B<A;B++)Q[B]=XY();if(tB.freezeData)return Object.freeze(Q);return Q}else if(A<192){let Q=A-160;if(D8>=o)return bG.slice(o-qC,(o+=Q)-qC);if(D8==0&&zC<140){let B=Q<16?zm(Q):sIA(Q);if(B!=null)return B}return zw(Q)}else{let Q;switch(A){case 192:return null;case 193:if(PY)if(Q=XY(),Q>0)return PY[1].slice(PY.position1,PY.position1+=Q);else return PY[0].slice(PY.position0,PY.position0-=Q);return Lm;case 194:return!1;case 195:return!0;case 196:if(Q=_A[o++],Q===void 0)throw Error("Unexpected end of buffer");return Vm(Q);case 197:return Q=$B.getUint16(o),o+=2,Vm(Q);case 198:return Q=$B.getUint32(o),o+=4,Vm(Q);case 199:return ZE(_A[o++]);case 200:return Q=$B.getUint16(o),o+=2,ZE(Q);case 201:return Q=$B.getUint32(o),o+=4,ZE(Q);case 202:if(Q=$B.getFloat32(o),tB.useFloat32>2){let B=KE[(_A[o]&127)<<1|_A[o+1]>>7];return o+=4,(B*Q+(Q>0?0.5:-0.5)>>0)/B}return o+=4,Q;case 203:return Q=$B.getFloat64(o),o+=8,Q;case 204:return _A[o++];case 205:return Q=$B.getUint16(o),o+=2,Q;case 206:return Q=$B.getUint32(o),o+=4,Q;case 207:if(tB.int64AsType==="number")Q=$B.getUint32(o)*4294967296,Q+=$B.getUint32(o+4);else if(tB.int64AsType==="string")Q=$B.getBigUint64(o).toString();else if(tB.int64AsType==="auto"){if(Q=$B.getBigUint64(o),Q<=BigInt(2)<<BigInt(52))Q=Number(Q)}else Q=$B.getBigUint64(o);return o+=8,Q;case 208:return $B.getInt8(o++);case 209:return Q=$B.getInt16(o),o+=2,Q;case 210:return Q=$B.getInt32(o),o+=4,Q;case 211:if(tB.int64AsType==="number")Q=$B.getInt32(o)*4294967296,Q+=$B.getUint32(o+4);else if(tB.int64AsType==="string")Q=$B.getBigInt64(o).toString();else if(tB.int64AsType==="auto"){if(Q=$B.getBigInt64(o),Q>=BigInt(-2)<<BigInt(52)&&Q<=BigInt(2)<<BigInt(52))Q=Number(Q)}else Q=$B.getBigInt64(o);return o+=8,Q;case 212:if(Q=_A[o++],Q==114)return mIA(_A[o++]&63);else{let B=g9[Q];if(B)if(B.read)return o++,B.read(XY());else if(B.noBuffer)return o++,B();else return B(_A.subarray(o,++o));else throw Error("Unknown extension "+Q)}case 213:if(Q=_A[o],Q==114)return o++,mIA(_A[o++]&63,_A[o++]);else return ZE(2);case 214:return ZE(4);case 215:return ZE(8);case 216:return ZE(16);case 217:if(Q=_A[o++],D8>=o)return bG.slice(o-qC,(o+=Q)-qC);return lIA(Q);case 218:if(Q=$B.getUint16(o),o+=2,D8>=o)return bG.slice(o-qC,(o+=Q)-qC);return cIA(Q);case 219:if(Q=$B.getUint32(o),o+=4,D8>=o)return bG.slice(o-qC,(o+=Q)-qC);return pIA(Q);case 220:return Q=$B.getUint16(o),o+=2,hIA(Q);case 221:return Q=$B.getUint32(o),o+=4,hIA(Q);case 222:return Q=$B.getUint16(o),o+=2,xIA(Q);case 223:return Q=$B.getUint32(o),o+=4,xIA(Q);default:if(A>=224)return A-256;if(A===void 0){let B=Error("Unexpected end of MessagePack data");throw B.incomplete=!0,B}throw Error("Unknown MessagePack token "+A)}}}var rFB=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function qm(A,Q){function B(){if(B.count++>uIA){let J=A.read=Function("r","return function(){return "+(tB.freezeData?"Object.freeze":"")+"({"+A.map((C)=>C==="__proto__"?"__proto_:r()":rFB.test(C)?C+":r()":"["+JSON.stringify(C)+"]:r()").join(",")+"})}")(XY);if(A.highByte===0)A.read=gIA(Q,A.read);return J()}let Y={};for(let J=0,C=A.length;J<C;J++){let X=A[J];if(X==="__proto__")X="__proto_";Y[X]=XY()}if(tB.freezeData)return Object.freeze(Y);return Y}if(B.count=0,A.highByte===0)return gIA(Q,B);return B}var gIA=(A,Q)=>{return function(){let B=_A[o++];if(B===0)return Q();let Y=A<32?-(A+(B<<5)):A+(B<<5),J=DB[Y]||dIA()[Y];if(!J)throw Error("Record id is not defined for "+Y);if(!J.read)J.read=qm(J,A);return J.read()}};function dIA(){let A=oIA(()=>{return _A=null,tB.getStructures()});return DB=tB._mergeStructures(A,DB)}var zw=UE,lIA=UE,cIA=UE,pIA=UE,jw=!1;function iIA(A){jw=!0,zw=Q(1),lIA=Q(2),cIA=Q(3),pIA=Q(5);function Q(B){return function(J){let C=$E[vD++];if(C==null){if(PY)return UE(J);let G=_A.byteOffset,F=A(o-B+G,zC+G,_A.buffer);if(typeof F=="string")C=F,$E=Mm;else if($E=F,vD=1,D8=1,C=$E[0],C===void 0)throw Error("Unexpected end of buffer")}let X=C.length;if(X<=J)return o+=J,C;return bG=C,qC=o,D8=o+X,o+=J,C.slice(0,J)}}}function UE(A){let Q;if(A<16){if(Q=zm(A))return Q}if(A>64&&Im)return Im.decode(_A.subarray(o,o+=A));let B=o+A,Y=[];Q="";while(o<B){let J=_A[o++];if((J&128)===0)Y.push(J);else if((J&224)===192){let C=_A[o++]&63;Y.push((J&31)<<6|C)}else if((J&240)===224){let C=_A[o++]&63,X=_A[o++]&63;Y.push((J&31)<<12|C<<6|X)}else if((J&248)===240){let C=_A[o++]&63,X=_A[o++]&63,G=_A[o++]&63,F=(J&7)<<18|C<<12|X<<6|G;if(F>65535)F-=65536,Y.push(F>>>10&1023|55296),F=56320|F&1023;Y.push(F)}else Y.push(J);if(Y.length>=4096)Q+=mY.apply(String,Y),Y.length=0}if(Y.length>0)Q+=mY.apply(String,Y);return Q}function nIA(A,Q,B){let Y=_A;_A=A,o=Q;try{return UE(B)}finally{_A=Y}}function hIA(A){let Q=Array(A);for(let B=0;B<A;B++)Q[B]=XY();if(tB.freezeData)return Object.freeze(Q);return Q}function xIA(A){if(tB.mapsAsObjects){let Q={};for(let B=0;B<A;B++){let Y=aIA();if(Y==="__proto__")Y="__proto_";Q[Y]=XY()}return Q}else{let Q=new Map;for(let B=0;B<A;B++)Q.set(XY(),XY());return Q}}var mY=String.fromCharCode;function sIA(A){let Q=o,B=Array(A);for(let Y=0;Y<A;Y++){let J=_A[o++];if((J&128)>0){o=Q;return}B[Y]=J}return mY.apply(String,B)}function zm(A){if(A<4)if(A<2)if(A===0)return"";else{let Q=_A[o++];if((Q&128)>1){o-=1;return}return mY(Q)}else{let Q=_A[o++],B=_A[o++];if((Q&128)>0||(B&128)>0){o-=2;return}if(A<3)return mY(Q,B);let Y=_A[o++];if((Y&128)>0){o-=3;return}return mY(Q,B,Y)}else{let Q=_A[o++],B=_A[o++],Y=_A[o++],J=_A[o++];if((Q&128)>0||(B&128)>0||(Y&128)>0||(J&128)>0){o-=4;return}if(A<6)if(A===4)return mY(Q,B,Y,J);else{let C=_A[o++];if((C&128)>0){o-=5;return}return mY(Q,B,Y,J,C)}else if(A<8){let C=_A[o++],X=_A[o++];if((C&128)>0||(X&128)>0){o-=6;return}if(A<7)return mY(Q,B,Y,J,C,X);let G=_A[o++];if((G&128)>0){o-=7;return}return mY(Q,B,Y,J,C,X,G)}else{let C=_A[o++],X=_A[o++],G=_A[o++],F=_A[o++];if((C&128)>0||(X&128)>0||(G&128)>0||(F&128)>0){o-=8;return}if(A<10)if(A===8)return mY(Q,B,Y,J,C,X,G,F);else{let W=_A[o++];if((W&128)>0){o-=9;return}return mY(Q,B,Y,J,C,X,G,F,W)}else if(A<12){let W=_A[o++],E=_A[o++];if((W&128)>0||(E&128)>0){o-=10;return}if(A<11)return mY(Q,B,Y,J,C,X,G,F,W,E);let $=_A[o++];if(($&128)>0){o-=11;return}return mY(Q,B,Y,J,C,X,G,F,W,E,$)}else{let W=_A[o++],E=_A[o++],$=_A[o++],Z=_A[o++];if((W&128)>0||(E&128)>0||($&128)>0||(Z&128)>0){o-=12;return}if(A<14)if(A===12)return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z);else{let U=_A[o++];if((U&128)>0){o-=13;return}return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z,U)}else{let U=_A[o++],K=_A[o++];if((U&128)>0||(K&128)>0){o-=14;return}if(A<15)return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K);let I=_A[o++];if((I&128)>0){o-=15;return}return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K,I)}}}}}function fIA(){let A=_A[o++],Q;if(A<192)Q=A-160;else switch(A){case 217:Q=_A[o++];break;case 218:Q=$B.getUint16(o),o+=2;break;case 219:Q=$B.getUint32(o),o+=4;break;default:throw Error("Expected string")}return UE(Q)}function Vm(A){return tB.copyBuffers?Uint8Array.prototype.slice.call(_A,o,o+=A):_A.subarray(o,o+=A)}function ZE(A){let Q=_A[o++];if(g9[Q]){let B;return g9[Q](_A.subarray(o,B=o+=A),(Y)=>{o=Y;try{return XY()}finally{o=B}})}else throw Error("Unknown extension type "+Q)}var bIA=Array(4096);function aIA(){let A=_A[o++];if(A>=160&&A<192){if(A=A-160,D8>=o)return bG.slice(o-qC,(o+=A)-qC);else if(!(D8==0&&zC<180))return zw(A)}else return o--,rIA(XY());let Q=(A<<5^(A>1?$B.getUint16(o):A>0?_A[o]:0))&4095,B=bIA[Q],Y=o,J=o+A-3,C,X=0;if(B&&B.bytes==A){while(Y<J){if(C=$B.getUint32(Y),C!=B[X++]){Y=1879048192;break}Y+=4}J+=3;while(Y<J)if(C=_A[Y++],C!=B[X++]){Y=1879048192;break}if(Y===J)return o=Y,B.string;J-=3,Y=o}B=[],bIA[Q]=B,B.bytes=A;while(Y<J)C=$B.getUint32(Y),B.push(C),Y+=4;J+=3;while(Y<J)C=_A[Y++],B.push(C);let G=A<16?zm(A):sIA(A);if(G!=null)return B.string=G;return B.string=zw(A)}function rIA(A){if(typeof A==="string")return A;if(typeof A==="number"||typeof A==="boolean"||typeof A==="bigint")return A.toString();if(A==null)return A+"";if(tB.allowArraysInMapKeys&&Array.isArray(A)&&A.flat().every((Q)=>["string","number","boolean","bigint"].includes(typeof Q)))return A.flat().toString();throw Error(`Invalid property type for record: ${typeof A}`)}var mIA=(A,Q)=>{let B=XY().map(rIA),Y=A;if(Q!==void 0)A=A<32?-((Q<<5)+A):(Q<<5)+A,B.highByte=Q;let J=DB[A];if(J&&(J.isShared||b7))(DB.restoreStructures||(DB.restoreStructures=[]))[A]=J;return DB[A]=B,B.read=qm(B,Y),B.read()};g9[0]=()=>{};g9[0].noBuffer=!0;g9[66]=(A)=>{let Q=A.length,B=BigInt(A[0]&128?A[0]-256:A[0]);for(let Y=1;Y<Q;Y++)B<<=BigInt(8),B+=BigInt(A[Y]);return B};var oFB={Error,TypeError,ReferenceError};g9[101]=()=>{let A=XY();return(oFB[A[0]]||Error)(A[1],{cause:A[2]})};g9[105]=(A)=>{if(tB.structuredClone===!1)throw Error("Structured clone extension is disabled");let Q=$B.getUint32(o-4);if(!mG)mG=new Map;let B=_A[o],Y;if(B>=144&&B<160||B==220||B==221)Y=[];else if(B>=128&&B<144||B==222||B==223)Y=new Map;else if((B>=199&&B<=201||B>=212&&B<=216)&&_A[o+1]===115)Y=new Set;else Y={};let J={target:Y};mG.set(Q,J);let C=XY();if(!J.used)return J.target=C;else Object.assign(Y,C);if(Y instanceof Map)for(let[X,G]of C.entries())Y.set(X,G);if(Y instanceof Set)for(let X of Array.from(C))Y.add(X);return Y};g9[112]=(A)=>{if(tB.structuredClone===!1)throw Error("Structured clone extension is disabled");let Q=$B.getUint32(o-4),B=mG.get(Q);return B.used=!0,B.target};g9[115]=()=>new Set(XY());var Rm=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((A)=>A+"Array"),tFB=typeof globalThis==="object"?globalThis:window;g9[116]=(A)=>{let Q=A[0],B=Uint8Array.prototype.slice.call(A,1).buffer,Y=Rm[Q];if(!Y){if(Q===16)return B;if(Q===17)return new DataView(B);throw Error("Could not find typed array for code "+Q)}return new tFB[Y](B)};g9[120]=()=>{let A=XY();return new RegExp(A[0],A[1])};var eFB=[];g9[98]=(A)=>{let Q=(A[0]<<24)+(A[1]<<16)+(A[2]<<8)+A[3],B=o;return o+=Q-A.length,PY=eFB,PY=[fIA(),fIA()],PY.position0=0,PY.position1=0,PY.postBundlePosition=o,o=B,XY()};g9[255]=(A)=>{if(A.length==4)return new Date((A[0]*16777216+(A[1]<<16)+(A[2]<<8)+A[3])*1000);else if(A.length==8)return new Date(((A[0]<<22)+(A[1]<<14)+(A[2]<<6)+(A[3]>>2))/1e6+((A[3]&3)*4294967296+A[4]*16777216+(A[5]<<16)+(A[6]<<8)+A[7])*1000);else if(A.length==12)return new Date(((A[0]<<24)+(A[1]<<16)+(A[2]<<8)+A[3])/1e6+((A[4]&128?-281474976710656:0)+A[6]*1099511627776+A[7]*4294967296+A[8]*16777216+(A[9]<<16)+(A[10]<<8)+A[11])*1000);else return new Date("invalid")};function oIA(A){if(Nm)Nm();let Q=zC,B=o,Y=vD,J=qC,C=D8,X=bG,G=$E,F=mG,W=PY,E=new Uint8Array(_A.slice(0,zC)),$=DB,Z=DB.slice(0,DB.length),U=tB,K=b7,I=A();return zC=Q,o=B,vD=Y,qC=J,D8=C,bG=X,$E=G,mG=F,PY=W,_A=E,b7=K,DB=$,DB.splice(0,DB.length,...Z),tB=U,$B=new DataView(_A.buffer,_A.byteOffset,_A.byteLength),I}function Rw(){_A=null,mG=null,DB=null}var KE=Array(147);for(let A=0;A<256;A++)KE[A]=+("1e"+Math.floor(45.15-A*0.30103));var Ow=new uG({useRecords:!1}),AWB=Ow.unpack,QWB=Ow.unpackMultiple,BWB=Ow.unpack,yD={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},YWB=new Float32Array(1),ODY=new Uint8Array(YWB.buffer,0,4);function tIA(A,Q,B){Hm=A,Dm=Q,Nm=B}var Tw;try{Tw=new TextEncoder}catch(A){}var Om,QHA,hD=typeof Buffer<"u",Pw=hD?function(A){return Buffer.allocUnsafeSlow(A)}:Uint8Array,BHA=hD?Buffer:Uint8Array,eIA=hD?4294967296:2144337920,ZA,gD,C0,BA=0,Y9,_0=null,YHA,JWB=21760,CWB=/[\u0080-\uFFFF]/,n1=Symbol("record-id");class VE extends uG{constructor(A){super(A);this.offset=0;let Q,B,Y,J,C,X=BHA.prototype.utf8Write?function(T,S){return ZA.utf8Write(T,S,ZA.byteLength-S)}:Tw&&Tw.encodeInto?function(T,S){return Tw.encodeInto(T,ZA.subarray(S)).written}:!1,G=this;if(!A)A={};let F=A&&A.sequential,W=A.structures||A.saveStructures,E=A.maxSharedStructures;if(E==null)E=W?32:0;if(E>8160)throw Error("Maximum maxSharedStructure is 8160");if(A.structuredClone&&A.moreTypes==null)this.moreTypes=!0;let $=A.maxOwnStructures;if($==null)$=W?32:64;if(!this.structures&&A.useRecords!=!1)this.structures=[];let Z=E>32||$+E>64,U=E+64,K=E+$+64;if(K>8256)throw Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let I=[],V=0,H=0;this.pack=this.encode=function(T,S){if(!ZA)ZA=new Pw(8192),C0=ZA.dataView||(ZA.dataView=new DataView(ZA.buffer,0,8192)),BA=0;if(Y9=ZA.length-10,Y9-BA<2048)ZA=new Pw(ZA.length),C0=ZA.dataView||(ZA.dataView=new DataView(ZA.buffer,0,ZA.length)),Y9=ZA.length-10,BA=0;else BA=BA+7&2147483640;if(B=BA,S&$WB)BA+=S&255;if(C=G.structuredClone?new Map:null,G.bundleStrings&&typeof T!=="string")_0=[],_0.size=1/0;else _0=null;if(J=G.structures,J){if(J.uninitialized)J=G._mergeStructures(G.getStructures());let v=J.sharedLength||0;if(v>E)throw Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+J.sharedLength);if(!J.transitions){J.transitions=Object.create(null);for(let h=0;h<v;h++){let g=J[h];if(!g)continue;let m,p=J.transitions;for(let c=0,AA=g.length;c<AA;c++){let d=g[c];if(m=p[d],!m)m=p[d]=Object.create(null);p=m}p[n1]=h+64}this.lastNamedStructuresLength=v}if(!F)J.nextId=v+64}if(Y)Y=!1;let y;try{if(G.randomAccessStructure&&T&&T.constructor&&T.constructor===Object)k(T);else z(T);let v=_0;if(_0)AHA(B,z,0);if(C&&C.idsToInsert){let h=C.idsToInsert.sort((c,AA)=>c.offset>AA.offset?1:-1),g=h.length,m=-1;while(v&&g>0){let c=h[--g].offset+B;if(c<v.stringsPosition+B&&m===-1)m=0;if(c>v.position+B){if(m>=0)m+=6}else{if(m>=0)C0.setUint32(v.position+B,C0.getUint32(v.position+B)+m),m=-1;v=v.previous,g++}}if(m>=0&&v)C0.setUint32(v.position+B,C0.getUint32(v.position+B)+m);if(BA+=h.length*6,BA>Y9)P(BA);G.offset=BA;let p=GWB(ZA.subarray(B,BA),h);return C=null,p}if(G.offset=BA,S&EWB)return ZA.start=B,ZA.end=BA,ZA;return ZA.subarray(B,BA)}catch(v){throw y=v,v}finally{if(J){if(D(),Y&&G.saveStructures){let v=J.sharedLength||0,h=ZA.subarray(B,BA),g=JHA(J,G);if(!y){if(G.saveStructures(g,g.isCompatible)===!1)return G.pack(T,S);if(G.lastNamedStructuresLength=v,ZA.length>1073741824)ZA=null;return h}}}if(ZA.length>1073741824)ZA=null;if(S&ZWB)BA=B}};let D=()=>{if(H<10)H++;let T=J.sharedLength||0;if(J.length>T&&!F)J.length=T;if(V>1e4){if(J.transitions=null,H=0,V=0,I.length>0)I=[]}else if(I.length>0&&!F){for(let S=0,y=I.length;S<y;S++)I[S][n1]=0;I=[]}},M=(T)=>{var S=T.length;if(S<16)ZA[BA++]=144|S;else if(S<65536)ZA[BA++]=220,ZA[BA++]=S>>8,ZA[BA++]=S&255;else ZA[BA++]=221,C0.setUint32(BA,S),BA+=4;for(let y=0;y<S;y++)z(T[y])},z=(T)=>{if(BA>Y9)ZA=P(BA);var S=typeof T,y;if(S==="string"){let v=T.length;if(_0&&v>=4&&v<4096){if((_0.size+=v)>JWB){let p,c=(_0[0]?_0[0].length*3+_0[1].length:0)+10;if(BA+c>Y9)ZA=P(BA+c);let AA;if(_0.position)AA=_0,ZA[BA]=200,BA+=3,ZA[BA++]=98,p=BA-B,BA+=4,AHA(B,z,0),C0.setUint16(p+B-3,BA-B-p);else ZA[BA++]=214,ZA[BA++]=98,p=BA-B,BA+=4;_0=["",""],_0.previous=AA,_0.size=0,_0.position=p}let m=CWB.test(T);_0[m?0:1]+=T,ZA[BA++]=193,z(m?-v:v);return}let h;if(v<32)h=1;else if(v<256)h=2;else if(v<65536)h=3;else h=5;let g=v*3;if(BA+g>Y9)ZA=P(BA+g);if(v<64||!X){let m,p,c,AA=BA+h;for(m=0;m<v;m++)if(p=T.charCodeAt(m),p<128)ZA[AA++]=p;else if(p<2048)ZA[AA++]=p>>6|192,ZA[AA++]=p&63|128;else if((p&64512)===55296&&((c=T.charCodeAt(m+1))&64512)===56320)p=65536+((p&1023)<<10)+(c&1023),m++,ZA[AA++]=p>>18|240,ZA[AA++]=p>>12&63|128,ZA[AA++]=p>>6&63|128,ZA[AA++]=p&63|128;else ZA[AA++]=p>>12|224,ZA[AA++]=p>>6&63|128,ZA[AA++]=p&63|128;y=AA-BA-h}else y=X(T,BA+h);if(y<32)ZA[BA++]=160|y;else if(y<256){if(h<2)ZA.copyWithin(BA+2,BA+1,BA+1+y);ZA[BA++]=217,ZA[BA++]=y}else if(y<65536){if(h<3)ZA.copyWithin(BA+3,BA+2,BA+2+y);ZA[BA++]=218,ZA[BA++]=y>>8,ZA[BA++]=y&255}else{if(h<5)ZA.copyWithin(BA+5,BA+3,BA+3+y);ZA[BA++]=219,C0.setUint32(BA,y),BA+=4}BA+=y}else if(S==="number")if(T>>>0===T)if(T<32||T<128&&this.useRecords===!1||T<64&&!this.randomAccessStructure)ZA[BA++]=T;else if(T<256)ZA[BA++]=204,ZA[BA++]=T;else if(T<65536)ZA[BA++]=205,ZA[BA++]=T>>8,ZA[BA++]=T&255;else ZA[BA++]=206,C0.setUint32(BA,T),BA+=4;else if(T>>0===T)if(T>=-32)ZA[BA++]=256+T;else if(T>=-128)ZA[BA++]=208,ZA[BA++]=T+256;else if(T>=-32768)ZA[BA++]=209,C0.setInt16(BA,T),BA+=2;else ZA[BA++]=210,C0.setInt32(BA,T),BA+=4;else{let v;if((v=this.useFloat32)>0&&T<4294967296&&T>=-2147483648){ZA[BA++]=202,C0.setFloat32(BA,T);let h;if(v<4||(h=T*KE[(ZA[BA]&127)<<1|ZA[BA+1]>>7])>>0===h){BA+=4;return}else BA--}ZA[BA++]=203,C0.setFloat64(BA,T),BA+=8}else if(S==="object"||S==="function")if(!T)ZA[BA++]=192;else{if(C){let h=C.get(T);if(h){if(!h.id){let g=C.idsToInsert||(C.idsToInsert=[]);h.id=g.push(h)}ZA[BA++]=214,ZA[BA++]=112,C0.setUint32(BA,h.id),BA+=4;return}else C.set(T,{offset:BA-B})}let v=T.constructor;if(v===Object)w(T);else if(v===Array)M(T);else if(v===Map)if(this.mapAsEmptyObject)ZA[BA++]=128;else{if(y=T.size,y<16)ZA[BA++]=128|y;else if(y<65536)ZA[BA++]=222,ZA[BA++]=y>>8,ZA[BA++]=y&255;else ZA[BA++]=223,C0.setUint32(BA,y),BA+=4;for(let[h,g]of T)z(h),z(g)}else{for(let h=0,g=Om.length;h<g;h++){let m=QHA[h];if(T instanceof m){let p=Om[h];if(p.write){if(p.type)ZA[BA++]=212,ZA[BA++]=p.type,ZA[BA++]=0;let b=p.write.call(this,T);if(b===T)if(Array.isArray(T))M(T);else w(T);else z(b);return}let c=ZA,AA=C0,d=BA;ZA=null;let x;try{x=p.pack.call(this,T,(b)=>{if(ZA=c,c=null,BA+=b,BA>Y9)P(BA);return{target:ZA,targetView:C0,position:BA-b}},z)}finally{if(c)ZA=c,C0=AA,BA=d,Y9=ZA.length-10}if(x){if(x.length+BA>Y9)P(x.length+BA);BA=XWB(x,ZA,BA,p.type)}return}}if(Array.isArray(T))M(T);else{if(T.toJSON){let h=T.toJSON();if(h!==T)return z(h)}if(S==="function")return z(this.writeFunction&&this.writeFunction(T));w(T)}}}else if(S==="boolean")ZA[BA++]=T?195:194;else if(S==="bigint"){if(T<9223372036854776000&&T>=-9223372036854776000)ZA[BA++]=211,C0.setBigInt64(BA,T);else if(T<18446744073709552000&&T>0)ZA[BA++]=207,C0.setBigUint64(BA,T);else if(this.largeBigIntToFloat)ZA[BA++]=203,C0.setFloat64(BA,Number(T));else if(this.largeBigIntToString)return z(T.toString());else if((this.useBigIntExtension||this.moreTypes)&&T<BigInt(2)**BigInt(1023)&&T>-(BigInt(2)**BigInt(1023))){ZA[BA++]=199,BA++,ZA[BA++]=66;let v=[],h;do{let g=T&BigInt(255);h=(g&BigInt(128))===(T<BigInt(0)?BigInt(128):BigInt(0)),v.push(g),T>>=BigInt(8)}while(!((T===BigInt(0)||T===BigInt(-1))&&h));ZA[BA-2]=v.length;for(let g=v.length;g>0;)ZA[BA++]=Number(v[--g]);return}else throw RangeError(T+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");BA+=8}else if(S==="undefined")if(this.encodeUndefinedAsNil)ZA[BA++]=192;else ZA[BA++]=212,ZA[BA++]=0,ZA[BA++]=0;else throw Error("Unknown type: "+S)},q=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(T)=>{let S;if(this.skipValues){S=[];for(let h in T)if((typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(h))&&!this.skipValues.includes(T[h]))S.push(h)}else S=Object.keys(T);let y=S.length;if(y<16)ZA[BA++]=128|y;else if(y<65536)ZA[BA++]=222,ZA[BA++]=y>>8,ZA[BA++]=y&255;else ZA[BA++]=223,C0.setUint32(BA,y),BA+=4;let v;if(this.coercibleKeyAsNumber)for(let h=0;h<y;h++){v=S[h];let g=Number(v);z(isNaN(g)?v:g),z(T[v])}else for(let h=0;h<y;h++)z(v=S[h]),z(T[v])}:(T)=>{ZA[BA++]=222;let S=BA-B;BA+=2;let y=0;for(let v in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(v))z(v),z(T[v]),y++;if(y>65535)throw Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');ZA[S+++B]=y>>8,ZA[S+B]=y&255},N=this.useRecords===!1?q:A.progressiveRecords&&!Z?(T)=>{let S,y=J.transitions||(J.transitions=Object.create(null)),v=BA++-B,h;for(let g in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(g)){if(S=y[g],S)y=S;else{let m=Object.keys(T),p=y;y=J.transitions;let c=0;for(let AA=0,d=m.length;AA<d;AA++){let x=m[AA];if(S=y[x],!S)S=y[x]=Object.create(null),c++;y=S}if(v+B+1==BA)BA--,_(y,m,c);else O(y,m,v,c);h=!0,y=p[g]}z(T[g])}if(!h){let g=y[n1];if(g)ZA[v+B]=g;else O(y,Object.keys(T),v,0)}}:(T)=>{let S,y=J.transitions||(J.transitions=Object.create(null)),v=0;for(let g in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(g)){if(S=y[g],!S)S=y[g]=Object.create(null),v++;y=S}let h=y[n1];if(h)if(h>=96&&Z)ZA[BA++]=((h-=96)&31)+96,ZA[BA++]=h>>5;else ZA[BA++]=h;else _(y,y.__keys__||Object.keys(T),v);for(let g in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(g))z(T[g])},L=typeof this.useRecords=="function"&&this.useRecords,w=L?(T)=>{L(T)?N(T):q(T)}:N,P=(T)=>{let S;if(T>16777216){if(T-B>eIA)throw Error("Packed buffer would be larger than maximum buffer size");S=Math.min(eIA,Math.round(Math.max((T-B)*(T>67108864?1.25:2),4194304)/4096)*4096)}else S=(Math.max(T-B<<2,ZA.length-1)>>12)+1<<12;let y=new Pw(S);if(C0=y.dataView||(y.dataView=new DataView(y.buffer,0,S)),T=Math.min(T,ZA.length),ZA.copy)ZA.copy(y,0,B,T);else y.set(ZA.slice(B,T));return BA-=B,B=0,Y9=y.length-10,ZA=y},_=(T,S,y)=>{let v=J.nextId;if(!v)v=64;if(v<U&&this.shouldShareStructure&&!this.shouldShareStructure(S)){if(v=J.nextOwnId,!(v<K))v=U;J.nextOwnId=v+1}else{if(v>=K)v=U;J.nextId=v+1}let h=S.highByte=v>=96&&Z?v-96>>5:-1;if(T[n1]=v,T.__keys__=S,J[v-64]=S,v<U)if(S.isShared=!0,J.sharedLength=v-63,Y=!0,h>=0)ZA[BA++]=(v&31)+96,ZA[BA++]=h;else ZA[BA++]=v;else{if(h>=0)ZA[BA++]=213,ZA[BA++]=114,ZA[BA++]=(v&31)+96,ZA[BA++]=h;else ZA[BA++]=212,ZA[BA++]=114,ZA[BA++]=v;if(y)V+=H*y;if(I.length>=$)I.shift()[n1]=0;I.push(T),z(S)}},O=(T,S,y,v)=>{let h=ZA,g=BA,m=Y9,p=B;if(ZA=gD,BA=0,B=0,!ZA)gD=ZA=new Pw(8192);Y9=ZA.length-10,_(T,S,v),gD=ZA;let c=BA;if(ZA=h,BA=g,Y9=m,B=p,c>1){let AA=BA+c-1;if(AA>Y9)P(AA);let d=y+B;ZA.copyWithin(d+c,d+1,BA),ZA.set(gD.slice(0,c),d),BA=AA}else ZA[y+B]=gD[0]},k=(T)=>{let S=YHA(T,ZA,B,BA,J,P,(y,v,h)=>{if(h)return Y=!0;BA=v;let g=ZA;if(z(y),D(),g!==ZA)return{position:BA,targetView:C0,target:ZA};return BA},this);if(S===0)return w(T);BA=S}}useBuffer(A){ZA=A,ZA.dataView||(ZA.dataView=new DataView(ZA.buffer,ZA.byteOffset,ZA.byteLength)),BA=0}set position(A){BA=A}get position(){return BA}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}QHA=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ww];Om=[{pack(A,Q,B){let Y=A.getTime()/1000;if((this.useTimestamp32||A.getMilliseconds()===0)&&Y>=0&&Y<4294967296){let{target:J,targetView:C,position:X}=Q(6);J[X++]=214,J[X++]=255,C.setUint32(X,Y)}else if(Y>0&&Y<4294967296){let{target:J,targetView:C,position:X}=Q(10);J[X++]=215,J[X++]=255,C.setUint32(X,A.getMilliseconds()*4000000+(Y/1000/4294967296>>0)),C.setUint32(X+4,Y)}else if(isNaN(Y)){if(this.onInvalidDate)return Q(0),B(this.onInvalidDate());let{target:J,targetView:C,position:X}=Q(3);J[X++]=212,J[X++]=255,J[X++]=255}else{let{target:J,targetView:C,position:X}=Q(15);J[X++]=199,J[X++]=12,J[X++]=255,C.setUint32(X,A.getMilliseconds()*1e6),C.setBigInt64(X+4,BigInt(Math.floor(Y)))}}},{pack(A,Q,B){if(this.setAsEmptyObject)return Q(0),B({});let Y=Array.from(A),{target:J,position:C}=Q(this.moreTypes?3:0);if(this.moreTypes)J[C++]=212,J[C++]=115,J[C++]=0;B(Y)}},{pack(A,Q,B){let{target:Y,position:J}=Q(this.moreTypes?3:0);if(this.moreTypes)Y[J++]=212,Y[J++]=101,Y[J++]=0;B([A.name,A.message,A.cause])}},{pack(A,Q,B){let{target:Y,position:J}=Q(this.moreTypes?3:0);if(this.moreTypes)Y[J++]=212,Y[J++]=120,Y[J++]=0;B([A.source,A.flags])}},{pack(A,Q){if(this.moreTypes)wm(A,16,Q);else jm(hD?Buffer.from(A):new Uint8Array(A),Q)}},{pack(A,Q){let B=A.constructor;if(B!==BHA&&this.moreTypes)wm(A,Rm.indexOf(B.name),Q);else jm(A,Q)}},{pack(A,Q){if(this.moreTypes)wm(A,17,Q);else jm(hD?Buffer.from(A):new Uint8Array(A),Q)}},{pack(A,Q){let{target:B,position:Y}=Q(1);B[Y]=193}}];function wm(A,Q,B,Y){let J=A.byteLength;if(J+1<256){var{target:C,position:X}=B(4+J);C[X++]=199,C[X++]=J+1}else if(J+1<65536){var{target:C,position:X}=B(5+J);C[X++]=200,C[X++]=J+1>>8,C[X++]=J+1&255}else{var{target:C,position:X,targetView:G}=B(7+J);C[X++]=201,G.setUint32(X,J+1),X+=4}if(C[X++]=116,C[X++]=Q,!A.buffer)A=new Uint8Array(A);C.set(new Uint8Array(A.buffer,A.byteOffset,A.byteLength),X)}function jm(A,Q){let B=A.byteLength;var Y,J;if(B<256){var{target:Y,position:J}=Q(B+2);Y[J++]=196,Y[J++]=B}else if(B<65536){var{target:Y,position:J}=Q(B+3);Y[J++]=197,Y[J++]=B>>8,Y[J++]=B&255}else{var{target:Y,position:J,targetView:C}=Q(B+5);Y[J++]=198,C.setUint32(J,B),J+=4}Y.set(A,J)}function XWB(A,Q,B,Y){let J=A.length;switch(J){case 1:Q[B++]=212;break;case 2:Q[B++]=213;break;case 4:Q[B++]=214;break;case 8:Q[B++]=215;break;case 16:Q[B++]=216;break;default:if(J<256)Q[B++]=199,Q[B++]=J;else if(J<65536)Q[B++]=200,Q[B++]=J>>8,Q[B++]=J&255;else Q[B++]=201,Q[B++]=J>>24,Q[B++]=J>>16&255,Q[B++]=J>>8&255,Q[B++]=J&255}return Q[B++]=Y,Q.set(A,B),B+=J,B}function GWB(A,Q){let B,Y=Q.length*6,J=A.length-Y;while(B=Q.pop()){let{offset:C,id:X}=B;A.copyWithin(C+Y,C,J),Y-=6;let G=C+Y;A[G++]=214,A[G++]=105,A[G++]=X>>24,A[G++]=X>>16&255,A[G++]=X>>8&255,A[G++]=X&255,J=C}return A}function AHA(A,Q,B){if(_0.length>0){C0.setUint32(_0.position+A,BA+B-_0.position-A),_0.stringsPosition=BA-A;let Y=_0;_0=null,Q(Y[0]),Q(Y[1])}}function JHA(A,Q){return A.isCompatible=(B)=>{let Y=!B||(Q.lastNamedStructuresLength||0)===B.length;if(!Y)Q._mergeStructures(B);return Y},A}function CHA(A,Q){YHA=A,JHA=Q}var XHA=new VE({useRecords:!1}),FWB=XHA.pack,WWB=XHA.pack;var EWB=512,ZWB=1024,$WB=2048;var Pm=3,UU=0,xD=2,Sw=1,Sm=16,FHA=["num","object","string","ascii"];FHA[Sm]="date";var KWB=[!1,!0,!0,!1,!1,!0,!0,!1],WHA;try{Function(""),WHA=!0}catch(A){}var IE,VWB=typeof Buffer<"u",kw,s1;try{kw=new TextEncoder}catch(A){}var IWB=VWB?function(A,Q,B){return A.utf8Write(Q,B,A.byteLength-B)}:kw&&kw.encodeInto?function(A,Q,B){return kw.encodeInto(Q,A.subarray(B)).written}:!1,hDY=Symbol("type"),xDY=Symbol("parent");CHA(EHA,LWB);function EHA(A,Q,B,Y,J,C,X,G){let F=G.typedStructs||(G.typedStructs=[]),W=Q.dataView,E=(F.lastStringStart||100)+Y,$=Q.length-10,Z=Y;if(Y>$)Q=C(Y),W=Q.dataView,Y-=B,Z-=B,E-=B,B=0,$=Q.length-10;let U,K=E,I=F.transitions||(F.transitions=Object.create(null)),V=F.nextId||F.length,H=V<15?1:V<240?2:V<61440?3:V<15728640?4:0;if(H===0)return 0;Y+=H;let D=[],M,z=0;for(let N in A){let L=A[N],w=I[N];if(!w)I[N]=w={key:N,parent:I,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if(Y>$)Q=C(Y),W=Q.dataView,Y-=B,Z-=B,E-=B,K-=B,B=0,$=Q.length-10;switch(typeof L){case"number":let P=L;if(V<200||!w.num64){if(P>>0===P&&P<536870912&&P>-520093696){if(P<246&&P>=0&&(w.num8&&!(V>200&&w.num32)||P<32&&!w.num32))I=w.num8||h9(w,UU,1),Q[Y++]=P;else I=w.num32||h9(w,UU,4),W.setUint32(Y,P,!0),Y+=4;break}else if(P<4294967296&&P>=-2147483648){if(W.setFloat32(Y,P,!0),KWB[Q[Y+3]>>>5]){let T;if((T=P*KE[(Q[Y+3]&127)<<1|Q[Y+2]>>7])>>0===T){I=w.num32||h9(w,UU,4),Y+=4;break}}}}I=w.num64||h9(w,UU,8),W.setFloat64(Y,P,!0),Y+=8;break;case"string":let _=L.length;if(U=K-E,(_<<2)+K>$)Q=C((_<<2)+K),W=Q.dataView,Y-=B,Z-=B,E-=B,K-=B,B=0,$=Q.length-10;if(_>65280+U>>2){D.push(N,L,Y-Z);break}let O,k=K;if(_<64){let T,S,y;for(T=0;T<_;T++)if(S=L.charCodeAt(T),S<128)Q[K++]=S;else if(S<2048)O=!0,Q[K++]=S>>6|192,Q[K++]=S&63|128;else if((S&64512)===55296&&((y=L.charCodeAt(T+1))&64512)===56320)O=!0,S=65536+((S&1023)<<10)+(y&1023),T++,Q[K++]=S>>18|240,Q[K++]=S>>12&63|128,Q[K++]=S>>6&63|128,Q[K++]=S&63|128;else O=!0,Q[K++]=S>>12|224,Q[K++]=S>>6&63|128,Q[K++]=S&63|128}else K+=IWB(Q,L,K),O=K-k>_;if(U<160||U<246&&(w.ascii8||w.string8)){if(O){if(!(I=w.string8))if(F.length>10&&(I=w.ascii8))I.__type=xD,w.ascii8=null,w.string8=I,X(null,0,!0);else I=h9(w,xD,1)}else if(U===0&&!M){M=!0,I=w.ascii0||h9(w,Pm,0);break}else if(!(I=w.ascii8)&&!(F.length>10&&(I=w.string8)))I=h9(w,Pm,1);Q[Y++]=U}else I=w.string16||h9(w,xD,2),W.setUint16(Y,U,!0),Y+=2;break;case"object":if(L){if(L.constructor===Date)I=w.date64||h9(w,Sm,8),W.setFloat64(Y,L.getTime(),!0),Y+=8;else D.push(N,L,z);break}else if(w=GHA(w,Y,W,-10),w)I=w,Y=IE;else D.push(N,L,z);break;case"boolean":I=w.num8||w.ascii8||h9(w,UU,1),Q[Y++]=L?249:248;break;case"undefined":if(w=GHA(w,Y,W,-9),w)I=w,Y=IE;else D.push(N,L,z);break;default:D.push(N,L,z)}z++}for(let N=0,L=D.length;N<L;){let w=D[N++],P=D[N++],_=D[N++],O=I[w];if(!O)I[w]=O={key:w,parent:I,enumerationOffset:_-z,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let k;if(P){let T;if(U=K-E,U<65280)if(I=O.object16,I)T=2;else if(I=O.object32)T=4;else I=h9(O,Sw,2),T=2;else I=O.object32||h9(O,Sw,4),T=4;if(k=X(P,K),typeof k==="object")K=k.position,W=k.targetView,Q=k.target,E-=B,Y-=B,Z-=B,B=0;else K=k;if(T===2)W.setUint16(Y,U,!0),Y+=2;else W.setUint32(Y,U,!0),Y+=4}else I=O.object16||h9(O,Sw,2),W.setInt16(Y,P===null?-10:-9,!0),Y+=2;z++}let q=I[n1];if(q==null){q=G.typedStructs.length;let N=[],L=I,w,P;while((P=L.__type)!==void 0){let _=L.__size;L=L.__parent,w=L.key;let O=[P,_,w];if(L.enumerationOffset)O.push(L.enumerationOffset);N.push(O),L=L.parent}N.reverse(),I[n1]=q,G.typedStructs[q]=N,X(null,0,!0)}switch(H){case 1:if(q>=16)return 0;Q[Z]=q+32;break;case 2:if(q>=256)return 0;Q[Z]=56,Q[Z+1]=q;break;case 3:if(q>=65536)return 0;Q[Z]=57,W.setUint16(Z+1,q,!0);break;case 4:if(q>=16777216)return 0;W.setUint32(Z,(q<<8)+58,!0);break}if(Y<E){if(E===K)return Y;Q.copyWithin(Y,E,K),K+=Y-E,F.lastStringStart=Y-Z}else if(Y>E){if(E===K)return Y;return F.lastStringStart=Y-Z,EHA(A,Q,B,Z,J,C,X,G)}return K}function GHA(A,Q,B,Y){let J;if(J=A.ascii8||A.num8)return B.setInt8(Q,Y,!0),IE=Q+1,J;if(J=A.string16||A.object16)return B.setInt16(Q,Y,!0),IE=Q+2,J;if(J=A.num32)return B.setUint32(Q,3758096640+Y,!0),IE=Q+4,J;if(J=A.num64)return B.setFloat64(Q,NaN,!0),B.setInt8(Q,Y),IE=Q+8,J;IE=Q;return}function h9(A,Q,B){let Y=FHA[Q]+(B<<3),J=A[Y]||(A[Y]=Object.create(null));return J.__type=Q,J.__size=B,J.__parent=A,J}function HWB(A){if(!(A instanceof Map))return A;let Q=A.get("typed")||[];if(Object.isFrozen(Q))Q=Q.map((J)=>J.slice(0));let B=A.get("named"),Y=Object.create(null);for(let J=0,C=Q.length;J<C;J++){let X=Q[J],G=Y;for(let[F,W,E]of X){let $=G[E];if(!$)G[E]=$={key:E,parent:G,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};G=h9($,F,W)}G[n1]=J}return Q.transitions=Y,this.typedStructs=Q,this.lastTypedStructuresLength=Q.length,B}var Tm=Symbol.for("source");function DWB(A,Q,B,Y){let J=A[Q++]-32;if(J>=24)switch(J){case 24:J=A[Q++];break;case 25:J=A[Q++]+(A[Q++]<<8);break;case 26:J=A[Q++]+(A[Q++]<<8)+(A[Q++]<<16);break;case 27:J=A[Q++]+(A[Q++]<<8)+(A[Q++]<<16)+(A[Q++]<<24);break}let C=Y.typedStructs&&Y.typedStructs[J];if(!C){if(A=Uint8Array.prototype.slice.call(A,Q,B),B-=Q,Q=0,!Y.getStructures)throw Error(`Reference to shared structure ${J} without getStructures method`);if(Y._mergeStructures(Y.getStructures()),!Y.typedStructs)throw Error("Could not find any shared typed structures");if(Y.lastTypedStructuresLength=Y.typedStructs.length,C=Y.typedStructs[J],!C)throw Error("Could not find typed structure "+J)}var{construct:X,fullConstruct:G}=C;if(!X){X=C.construct=function(){},G=C.fullConstruct=function(){},G.prototype=Y.structPrototype??{};var F=X.prototype=Y.structPrototype?Object.create(Y.structPrototype):{};let E=[],$=0,Z;for(let U=0,K=C.length;U<K;U++){let I=C[U],[V,H,D,M]=I;if(D==="__proto__")D="__proto_";let z={key:D,offset:$};if(M)E.splice(U+M,0,z);else E.push(z);let q;switch(H){case 0:q=()=>0;break;case 1:q=(L,w)=>{let P=L.bytes[w+z.offset];return P>=246?$U(P):P};break;case 2:q=(L,w)=>{let P=L.bytes,O=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getUint16(w+z.offset,!0);return O>=65280?$U(O&255):O};break;case 4:q=(L,w)=>{let P=L.bytes,O=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getUint32(w+z.offset,!0);return O>=4294967040?$U(O&255):O};break}z.getRef=q,$+=H;let N;switch(V){case Pm:if(Z&&!Z.next)Z.next=z;Z=z,z.multiGetCount=0,N=function(L){let{bytes:w,position:P}=L,_=$+P,O=q(L,P);if(typeof O!=="number")return O;let k,T=z.next;while(T){if(k=T.getRef(L,P),typeof k==="number")break;else k=null;T=T.next}if(k==null)k=L.bytesEnd-_;if(L.srcString)return L.srcString.slice(O,k);return nIA(w,O+_,k-O)};break;case xD:case Sw:if(Z&&!Z.next)Z.next=z;Z=z,N=function(L){let w=L.position,P=$+w,_=q(L,w);if(typeof _!=="number")return _;let O=L.bytes,k,T=z.next;while(T){if(k=T.getRef(L,w),typeof k==="number")break;else k=null;T=T.next}if(k==null)k=L.bytesEnd-P;if(V===xD)return O.toString("utf8",_+P,k+P);else{s1=L;try{return Y.unpack(O,{start:_+P,end:k+P})}finally{s1=null}}};break;case UU:switch(H){case 4:N=function(L){let w=L.bytes,P=w.dataView||(w.dataView=new DataView(w.buffer,w.byteOffset,w.byteLength)),_=L.position+z.offset,O=P.getInt32(_,!0);if(O<536870912){if(O>-520093696)return O;if(O>-536870912)return $U(O&255)}let k=P.getFloat32(_,!0),T=KE[(w[_+3]&127)<<1|w[_+2]>>7];return(T*k+(k>0?0.5:-0.5)>>0)/T};break;case 8:N=function(L){let w=L.bytes,_=(w.dataView||(w.dataView=new DataView(w.buffer,w.byteOffset,w.byteLength))).getFloat64(L.position+z.offset,!0);if(isNaN(_)){let O=w[L.position+z.offset];if(O>=246)return $U(O)}return _};break;case 1:N=function(L){let P=L.bytes[L.position+z.offset];return P<246?P:$U(P)};break}break;case Sm:N=function(L){let w=L.bytes,P=w.dataView||(w.dataView=new DataView(w.buffer,w.byteOffset,w.byteLength));return new Date(P.getFloat64(L.position+z.offset,!0))};break}z.get=N}if(WHA){let U=[],K=[],I=0,V;for(let D of E){if(Y.alwaysLazyProperty&&Y.alwaysLazyProperty(D.key)){V=!0;continue}Object.defineProperty(F,D.key,{get:NWB(D.get),enumerable:!0});let M="v"+I++;K.push(M),U.push("o["+JSON.stringify(D.key)+"]="+M+"(s)")}if(V)U.push("__proto__:this");let H=Function(...K,"var c=this;return function(s){var o=new c();"+U.join(";")+";return o;}").apply(G,E.map((D)=>D.get));Object.defineProperty(F,"toJSON",{value(D){return H.call(this,this[Tm])}})}else Object.defineProperty(F,"toJSON",{value(U){let K={};for(let I=0,V=E.length;I<V;I++){let H=E[I].key;K[H]=this[H]}return K}})}var W=new X;return W[Tm]={bytes:A,position:Q,srcString:"",bytesEnd:B},W}function $U(A){switch(A){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw Error("Unknown constant")}function NWB(A){return function(){return A(this[Tm])}}function MWB(){if(s1)s1.bytes=Uint8Array.prototype.slice.call(s1.bytes,s1.position,s1.bytesEnd),s1.position=0,s1.bytesEnd=s1.bytes.length}function LWB(A,Q){if(Q.typedStructs){let Y=new Map;Y.set("named",A),Y.set("typed",Q.typedStructs),A=Y}let B=Q.lastTypedStructuresLength||0;return A.isCompatible=(Y)=>{let J=!0;if(Y instanceof Map){if((Y.get("named")||[]).length!==(Q.lastNamedStructuresLength||0))J=!1;if((Y.get("typed")||[]).length!==B)J=!1}else if(Y instanceof Array||Array.isArray(Y)){if(Y.length!==(Q.lastNamedStructuresLength||0))J=!1}if(!J)Q._mergeStructures(Y);return J},Q.lastTypedStructuresLength=Q.typedStructs&&Q.typedStructs.length,A}tIA(DWB,HWB,MWB);var _WB=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!_WB){let A;try{if(A=OHA(),A)iIA(A.extractStrings)}catch(Q){}}var Cs={};h6(Cs,{zodErrorsIntegration:()=>Cd,wrapMcpServerWithSentry:()=>Ed,withScope:()=>OC,withMonitor:()=>o1,withIsolationScope:()=>iG,withActiveSpan:()=>o7,vercelAIIntegration:()=>CT,validateOpenTelemetrySetup:()=>Js,updateSpanName:()=>em,trpcMiddleware:()=>Gd,tediousIntegration:()=>eP,suppressTracing:()=>eD,supabaseIntegration:()=>Jd,startSpanManual:()=>tD,startSpan:()=>R8,startSession:()=>CN,startNewTrace:()=>Nu,startInactiveSpan:()=>Hu,spotlightIntegration:()=>sP,spanToTraceHeader:()=>lD,spanToJSON:()=>AQ,spanToBaggageHeader:()=>Gu,setupKoaErrorHandler:()=>lHQ,setupHapiErrorHandler:()=>HHQ,setupFastifyErrorHandler:()=>S4Q,setupExpressErrorHandler:()=>f$Q,setupConnectErrorHandler:()=>$DQ,setUser:()=>Tu,setTags:()=>Ou,setTag:()=>Pu,setNodeAsyncContextStrategy:()=>fO,setMeasurement:()=>Vu,setHttpStatus:()=>LU,setExtras:()=>wu,setExtra:()=>ju,setCurrentClient:()=>lu,setContext:()=>Ru,rewriteFramesIntegration:()=>Yd,requestDataIntegration:()=>WN,redisIntegration:()=>_P,profiler:()=>Xd,prismaIntegration:()=>fP,preloadOpenTelemetry:()=>qMQ,postgresIntegration:()=>hP,parameterize:()=>Xj,onUnhandledRejectionIntegration:()=>BP,onUncaughtExceptionIntegration:()=>QP,nodeContextIntegration:()=>aO,nativeNodeFetchIntegration:()=>iO,mysqlIntegration:()=>PP,mysql2Integration:()=>SP,mongooseIntegration:()=>jP,mongoIntegration:()=>RP,modulesIntegration:()=>AP,makeNodeTransport:()=>$T,lruMemoizerIntegration:()=>zP,logger:()=>Kd,localVariablesIntegration:()=>eO,linkedErrorsIntegration:()=>FN,lastEventId:()=>Su,koaIntegration:()=>pP,knexIntegration:()=>gDQ,kafkaIntegration:()=>qP,isInitialized:()=>PU,instrumentSupabaseClient:()=>$j,initWithoutDefaultIntegrations:()=>RMQ,initOpenTelemetry:()=>HT,init:()=>DT,inboundFiltersIntegration:()=>GN,httpIntegration:()=>dO,hapiIntegration:()=>dP,graphqlIntegration:()=>LP,getTraceMetaTags:()=>nu,getTraceData:()=>aG,getSpanStatusFromHttpCode:()=>MU,getSpanDescendants:()=>cD,getSentryRelease:()=>VT,getRootSpan:()=>E0,getIsolationScope:()=>wQ,getGlobalScope:()=>pG,getDefaultIntegrationsWithoutPerformance:()=>Bs,getDefaultIntegrations:()=>Ys,getCurrentScope:()=>nQ,getClient:()=>gA,getAutoPerformanceIntegrations:()=>WT,getActiveSpan:()=>c5,genericPoolIntegration:()=>AT,generateInstrumentOnce:()=>UQ,functionToStringIntegration:()=>XN,fsIntegration:()=>fZQ,flush:()=>ku,fastifyIntegration:()=>HP,extraErrorDataIntegration:()=>tu,expressIntegration:()=>FP,expressErrorHandler:()=>wi,eventFiltersIntegration:()=>Fj,endSession:()=>TE,disableAnrDetectionForCallback:()=>Y$Q,defaultStackParser:()=>IT,dedupeIntegration:()=>ou,dataloaderIntegration:()=>jNQ,cron:()=>SMQ,createTransport:()=>TU,createSentryWinstonTransport:()=>oNQ,createGetModuleFromFilename:()=>KT,continueTrace:()=>Du,contextLinesIntegration:()=>rO,consoleLoggingIntegration:()=>$d,consoleIntegration:()=>EN,connectIntegration:()=>nP,close:()=>_u,childProcessIntegration:()=>XT,captureSession:()=>yu,captureMessage:()=>OU,captureFeedback:()=>Zd,captureException:()=>jB,captureEvent:()=>YN,captureConsoleIntegration:()=>ru,captureCheckIn:()=>BN,anrIntegration:()=>B$Q,amqplibIntegration:()=>YT,addIntegration:()=>fu,addEventProcessor:()=>vu,addBreadcrumb:()=>C9,SentryContextManager:()=>FT,Scope:()=>CJ,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>eB,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>z8,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>NQ,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>JQ,SDK_VERSION:()=>b0,NodeClient:()=>vM});var Kd={};h6(Kd,{warn:()=>U$B,trace:()=>E$B,info:()=>$$B,fmt:()=>pu,fatal:()=>V$B,error:()=>K$B,debug:()=>Z$B});import{format as W$B}from"node:util";var OA=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var b0="9.22.0";var QQ=globalThis;function zJ(){return m7(QQ),QQ}function m7(A){let Q=A.__SENTRY__=A.__SENTRY__||{};return Q.version=Q.version||b0,Q[b0]=Q[b0]||{}}function HE(A,Q,B=QQ){let Y=B.__SENTRY__=B.__SENTRY__||{},J=Y[b0]=Y[b0]||{};return J[A]||(J[A]=Q())}var PHA=Object.prototype.toString;function b5(A){switch(PHA.call(A)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return dG(A,Error)}}function yw(A,Q){return PHA.call(A)===`[object ${Q}]`}function THA(A){return yw(A,"ErrorEvent")}function DE(A){return yw(A,"String")}function NE(A){return typeof A==="object"&&A!==null&&"__sentry_template_string__"in A&&"__sentry_template_values__"in A}function fD(A){return A===null||NE(A)||typeof A!=="object"&&typeof A!=="function"}function N8(A){return yw(A,"Object")}function SHA(A){return typeof Event<"u"&&dG(A,Event)}function kHA(A){return typeof Element<"u"&&dG(A,Element)}function _HA(A){return yw(A,"RegExp")}function M8(A){return Boolean(A?.then&&typeof A.then==="function")}function vHA(A){return N8(A)&&"nativeEvent"in A&&"preventDefault"in A&&"stopPropagation"in A}function dG(A,Q){try{return A instanceof Q}catch(B){return!1}}function gw(A){return!!(typeof A==="object"&&A!==null&&(A.__isVue||A._isVue))}var vWB=QQ,yWB=80;function yHA(A,Q={}){if(!A)return"<unknown>";try{let B=A,Y=5,J=[],C=0,X=0,G=" > ",F=G.length,W,E=Array.isArray(Q)?Q:Q.keyAttrs,$=!Array.isArray(Q)&&Q.maxStringLength||yWB;while(B&&C++<Y){if(W=gWB(B,E),W==="html"||C>1&&X+J.length*F+W.length>=$)break;J.push(W),X+=W.length,B=B.parentNode}return J.reverse().join(G)}catch(B){return"<unknown>"}}function gWB(A,Q){let B=A,Y=[];if(!B?.tagName)return"";if(vWB.HTMLElement){if(B instanceof HTMLElement&&B.dataset){if(B.dataset.sentryComponent)return B.dataset.sentryComponent;if(B.dataset.sentryElement)return B.dataset.sentryElement}}Y.push(B.tagName.toLowerCase());let J=Q?.length?Q.filter((X)=>B.getAttribute(X)).map((X)=>[X,B.getAttribute(X)]):null;if(J?.length)J.forEach((X)=>{Y.push(`[${X[0]}="${X[1]}"]`)});else{if(B.id)Y.push(`#${B.id}`);let X=B.className;if(X&&DE(X)){let G=X.split(/\s+/);for(let F of G)Y.push(`.${F}`)}}let C=["aria-label","type","name","title","alt"];for(let X of C){let G=B.getAttribute(X);if(G)Y.push(`[${X}="${G}"]`)}return Y.join("")}var hWB="Sentry Logger ",m5=["debug","info","warn","error","log","assert","trace"],KU={};function v0(A){if(!("console"in QQ))return A();let Q=QQ.console,B={},Y=Object.keys(KU);Y.forEach((J)=>{let C=KU[J];B[J]=Q[J],Q[J]=C});try{return A()}finally{Y.forEach((J)=>{Q[J]=B[J]})}}function xWB(){let A=!1,Q={enable:()=>{A=!0},disable:()=>{A=!1},isEnabled:()=>A};if(OA)m5.forEach((B)=>{Q[B]=(...Y)=>{if(A)v0(()=>{QQ.console[B](`${hWB}[${B}]:`,...Y)})}});else m5.forEach((B)=>{Q[B]=()=>{return}});return Q}var t=HE("logger",xWB);function x9(A,Q=0){if(typeof A!=="string"||Q===0)return A;return A.length<=Q?A:`${A.slice(0,Q)}...`}function fm(A,Q){let B=A,Y=B.length;if(Y<=150)return B;if(Q>Y)Q=Y;let J=Math.max(Q-60,0);if(J<5)J=0;let C=Math.min(J+140,Y);if(C>Y-5)C=Y;if(C===Y)J=Math.max(C-140,0);if(B=B.slice(J,C),J>0)B=`'{snip} ${B}`;if(C<Y)B+=" {snip}";return B}function u7(A,Q){if(!Array.isArray(A))return"";let B=[];for(let Y=0;Y<A.length;Y++){let J=A[Y];try{if(gw(J))B.push("[VueViewModel]");else B.push(String(J))}catch(C){B.push("[value cannot be serialized]")}}return B.join(Q)}function gHA(A,Q,B=!1){if(!DE(A))return!1;if(_HA(Q))return Q.test(A);if(DE(Q))return B?A===Q:A.includes(Q);return!1}function d7(A,Q=[],B=!1){return Q.some((Y)=>gHA(A,Y,B))}function bm(A,Q,B){if(!(Q in A))return;let Y=A[Q];if(typeof Y!=="function")return;let J=B(Y);if(typeof J==="function")fHA(J,Y);try{A[Q]=J}catch{OA&&t.log(`Failed to replace method "${Q}" in object`,A)}}function m0(A,Q,B){try{Object.defineProperty(A,Q,{value:B,writable:!0,configurable:!0})}catch(Y){OA&&t.log(`Failed to add non-enumerable property "${Q}" to object`,A)}}function fHA(A,Q){try{let B=Q.prototype||{};A.prototype=Q.prototype=B,m0(A,"__sentry_original__",Q)}catch(B){}}function mm(A){return A.__sentry_original__}function hw(A){if(b5(A))return{message:A.message,name:A.name,stack:A.stack,...xHA(A)};else if(SHA(A)){let Q={type:A.type,target:hHA(A.target),currentTarget:hHA(A.currentTarget),...xHA(A)};if(typeof CustomEvent<"u"&&dG(A,CustomEvent))Q.detail=A.detail;return Q}else return A}function hHA(A){try{return kHA(A)?yHA(A):Object.prototype.toString.call(A)}catch(Q){return"<unknown>"}}function xHA(A){if(typeof A==="object"&&A!==null){let Q={};for(let B in A)if(Object.prototype.hasOwnProperty.call(A,B))Q[B]=A[B];return Q}else return{}}function um(A,Q=40){let B=Object.keys(hw(A));B.sort();let Y=B[0];if(!Y)return"[object has no keys]";if(Y.length>=Q)return x9(Y,Q);for(let J=B.length;J>0;J--){let C=B.slice(0,J).join(", ");if(C.length>Q)continue;if(J===B.length)return C;return x9(C,Q)}return""}function fWB(){let A=QQ;return A.crypto||A.msCrypto}function GY(A=fWB()){let Q=()=>Math.random()*16;try{if(A?.randomUUID)return A.randomUUID().replace(/-/g,"");if(A?.getRandomValues)Q=()=>{let B=new Uint8Array(1);return A.getRandomValues(B),B[0]}}catch(B){}return([1e7]+1000+4000+8000+100000000000).replace(/[018]/g,(B)=>(B^(Q()&15)>>B/4).toString(16))}function bHA(A){return A.exception?.values?.[0]}function l7(A){let{message:Q,event_id:B}=A;if(Q)return Q;let Y=bHA(A);if(Y){if(Y.type&&Y.value)return`${Y.type}: ${Y.value}`;return Y.type||Y.value||B||"<unknown>"}return B||"<unknown>"}function lm(A,Q,B){let Y=A.exception=A.exception||{},J=Y.values=Y.values||[],C=J[0]=J[0]||{};if(!C.value)C.value=Q||"";if(!C.type)C.type=B||"Error"}function c7(A,Q){let B=bHA(A);if(!B)return;let Y={type:"generic",handled:!0},J=B.mechanism;if(B.mechanism={...Y,...J,...Q},Q&&"data"in Q){let C={...J?.data,...Q.data};B.mechanism.data=C}}var bWB=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function dm(A){return parseInt(A||"",10)}function cm(A){let Q=A.match(bWB)||[],B=dm(Q[1]),Y=dm(Q[2]),J=dm(Q[3]);return{buildmetadata:Q[5],major:isNaN(B)?void 0:B,minor:isNaN(Y)?void 0:Y,patch:isNaN(J)?void 0:J,prerelease:Q[4]}}function xw(A){if(mWB(A))return!0;try{m0(A,"__sentry_captured__",!0)}catch(Q){}return!1}function mWB(A){try{return A.__sentry_captured__}catch{}}var mHA=1000;function lG(){return Date.now()/mHA}function uWB(){let{performance:A}=QQ;if(!A?.now)return lG;let Q=Date.now()-A.now(),B=A.timeOrigin==null?Q:A.timeOrigin;return()=>{return(B+A.now())/mHA}}var RC=uWB();function uHA(A){let Q=RC(),B={sid:GY(),init:!0,timestamp:Q,started:Q,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>dWB(B)};if(A)cG(B,A);return B}function cG(A,Q={}){if(Q.user){if(!A.ipAddress&&Q.user.ip_address)A.ipAddress=Q.user.ip_address;if(!A.did&&!Q.did)A.did=Q.user.id||Q.user.email||Q.user.username}if(A.timestamp=Q.timestamp||RC(),Q.abnormal_mechanism)A.abnormal_mechanism=Q.abnormal_mechanism;if(Q.ignoreDuration)A.ignoreDuration=Q.ignoreDuration;if(Q.sid)A.sid=Q.sid.length===32?Q.sid:GY();if(Q.init!==void 0)A.init=Q.init;if(!A.did&&Q.did)A.did=`${Q.did}`;if(typeof Q.started==="number")A.started=Q.started;if(A.ignoreDuration)A.duration=void 0;else if(typeof Q.duration==="number")A.duration=Q.duration;else{let B=A.timestamp-A.started;A.duration=B>=0?B:0}if(Q.release)A.release=Q.release;if(Q.environment)A.environment=Q.environment;if(!A.ipAddress&&Q.ipAddress)A.ipAddress=Q.ipAddress;if(!A.userAgent&&Q.userAgent)A.userAgent=Q.userAgent;if(typeof Q.errors==="number")A.errors=Q.errors;if(Q.status)A.status=Q.status}function dHA(A,Q){let B={};if(Q)B={status:Q};else if(A.status==="ok")B={status:"exited"};cG(A,B)}function dWB(A){return{sid:`${A.sid}`,init:A.init,started:new Date(A.started*1000).toISOString(),timestamp:new Date(A.timestamp*1000).toISOString(),status:A.status,errors:A.errors,did:typeof A.did==="number"||typeof A.did==="string"?`${A.did}`:void 0,duration:A.duration,abnormal_mechanism:A.abnormal_mechanism,attrs:{release:A.release,environment:A.environment,ip_address:A.ipAddress,user_agent:A.userAgent}}}function p7(A,Q,B=2){if(!Q||typeof Q!=="object"||B<=0)return Q;if(A&&Object.keys(Q).length===0)return A;let Y={...A};for(let J in Q)if(Object.prototype.hasOwnProperty.call(Q,J))Y[J]=p7(Y[J],Q[J],B-1);return Y}var pm="_sentrySpan";function ME(A,Q){if(Q)m0(A,pm,Q);else delete A[pm]}function u5(A){return A[pm]}function wC(){return GY()}function jC(){return GY().substring(16)}var lWB=100;class CJ{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:wC(),sampleRand:Math.random()}}clone(){let A=new CJ;if(A._breadcrumbs=[...this._breadcrumbs],A._tags={...this._tags},A._extra={...this._extra},A._contexts={...this._contexts},this._contexts.flags)A._contexts.flags={values:[...this._contexts.flags.values]};return A._user=this._user,A._level=this._level,A._session=this._session,A._transactionName=this._transactionName,A._fingerprint=this._fingerprint,A._eventProcessors=[...this._eventProcessors],A._attachments=[...this._attachments],A._sdkProcessingMetadata={...this._sdkProcessingMetadata},A._propagationContext={...this._propagationContext},A._client=this._client,A._lastEventId=this._lastEventId,ME(A,u5(this)),A}setClient(A){this._client=A}setLastEventId(A){this._lastEventId=A}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(A){this._scopeListeners.push(A)}addEventProcessor(A){return this._eventProcessors.push(A),this}setUser(A){if(this._user=A||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session)cG(this._session,{user:A});return this._notifyScopeListeners(),this}getUser(){return this._user}setTags(A){return this._tags={...this._tags,...A},this._notifyScopeListeners(),this}setTag(A,Q){return this._tags={...this._tags,[A]:Q},this._notifyScopeListeners(),this}setExtras(A){return this._extra={...this._extra,...A},this._notifyScopeListeners(),this}setExtra(A,Q){return this._extra={...this._extra,[A]:Q},this._notifyScopeListeners(),this}setFingerprint(A){return this._fingerprint=A,this._notifyScopeListeners(),this}setLevel(A){return this._level=A,this._notifyScopeListeners(),this}setTransactionName(A){return this._transactionName=A,this._notifyScopeListeners(),this}setContext(A,Q){if(Q===null)delete this._contexts[A];else this._contexts[A]=Q;return this._notifyScopeListeners(),this}setSession(A){if(!A)delete this._session;else this._session=A;return this._notifyScopeListeners(),this}getSession(){return this._session}update(A){if(!A)return this;let Q=typeof A==="function"?A(this):A,B=Q instanceof CJ?Q.getScopeData():N8(Q)?A:void 0,{tags:Y,extra:J,user:C,contexts:X,level:G,fingerprint:F=[],propagationContext:W}=B||{};if(this._tags={...this._tags,...Y},this._extra={...this._extra,...J},this._contexts={...this._contexts,...X},C&&Object.keys(C).length)this._user=C;if(G)this._level=G;if(F.length)this._fingerprint=F;if(W)this._propagationContext=W;return this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,ME(this,void 0),this._attachments=[],this.setPropagationContext({traceId:wC(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(A,Q){let B=typeof Q==="number"?Q:lWB;if(B<=0)return this;let Y={timestamp:lG(),...A,message:A.message?x9(A.message,2048):A.message};if(this._breadcrumbs.push(Y),this._breadcrumbs.length>B)this._breadcrumbs=this._breadcrumbs.slice(-B),this._client?.recordDroppedEvent("buffer_overflow","log_item");return this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(A){return this._attachments.push(A),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:u5(this)}}setSDKProcessingMetadata(A){return this._sdkProcessingMetadata=p7(this._sdkProcessingMetadata,A,2),this}setPropagationContext(A){return this._propagationContext=A,this}getPropagationContext(){return this._propagationContext}captureException(A,Q){let B=Q?.event_id||GY();if(!this._client)return t.warn("No client configured on scope - will not capture exception!"),B;let Y=Error("Sentry syntheticException");return this._client.captureException(A,{originalException:A,syntheticException:Y,...Q,event_id:B},this),B}captureMessage(A,Q,B){let Y=B?.event_id||GY();if(!this._client)return t.warn("No client configured on scope - will not capture message!"),Y;let J=Error(A);return this._client.captureMessage(A,Q,{originalException:A,syntheticException:J,...B,event_id:Y},this),Y}captureEvent(A,Q){let B=Q?.event_id||GY();if(!this._client)return t.warn("No client configured on scope - will not capture event!"),B;return this._client.captureEvent(A,{...Q,event_id:B},this),B}_notifyScopeListeners(){if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach((A)=>{A(this)}),this._notifyingListeners=!1}}function VU(){return HE("defaultCurrentScope",()=>new CJ)}function L8(){return HE("defaultIsolationScope",()=>new CJ)}class cHA{constructor(A,Q){let B;if(!A)B=new CJ;else B=A;let Y;if(!Q)Y=new CJ;else Y=Q;this._stack=[{scope:B}],this._isolationScope=Y}withScope(A){let Q=this._pushScope(),B;try{B=A(Q)}catch(Y){throw this._popScope(),Y}if(M8(B))return B.then((Y)=>{return this._popScope(),Y},(Y)=>{throw this._popScope(),Y});return this._popScope(),B}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let A=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:A}),A}_popScope(){if(this._stack.length<=1)return!1;return!!this._stack.pop()}}function IU(){let A=zJ(),Q=m7(A);return Q.stack=Q.stack||new cHA(VU(),L8())}function cWB(A){return IU().withScope(A)}function pWB(A,Q){let B=IU();return B.withScope(()=>{return B.getStackTop().scope=A,Q(A)})}function lHA(A){return IU().withScope(()=>{return A(IU().getIsolationScope())})}function pHA(){return{withIsolationScope:lHA,withScope:cWB,withSetScope:pWB,withSetIsolationScope:(A,Q)=>{return lHA(Q)},getCurrentScope:()=>IU().getScope(),getIsolationScope:()=>IU().getIsolationScope()}}function im(A){let Q=zJ(),B=m7(Q);B.acs=A}function q8(A){let Q=m7(A);if(Q.acs)return Q.acs;return pHA()}function nQ(){let A=zJ();return q8(A).getCurrentScope()}function wQ(){let A=zJ();return q8(A).getIsolationScope()}function pG(){return HE("globalScope",()=>new CJ)}function OC(...A){let Q=zJ(),B=q8(Q);if(A.length===2){let[Y,J]=A;if(!Y)return B.withScope(J);return B.withSetScope(Y,J)}return B.withScope(A[0])}function iG(...A){let Q=zJ(),B=q8(Q);if(A.length===2){let[Y,J]=A;if(!Y)return B.withIsolationScope(J);return B.withSetIsolationScope(Y,J)}return B.withIsolationScope(A[0])}function gA(){return nQ().getClient()}function HU(A){let Q=A.getPropagationContext(),{traceId:B,parentSpanId:Y,propagationSpanId:J}=Q,C={trace_id:B,span_id:J||jC()};if(Y)C.parent_span_id=Y;return C}var eB="sentry.source",z8="sentry.sample_rate",nm="sentry.previous_trace_sample_rate",JQ="sentry.op",NQ="sentry.origin";var fw="sentry.measurement_unit",bw="sentry.measurement_value",d5="sentry.custom_span_name",DU="sentry.profile_id",NU="sentry.exclusive_time",sm="cache.hit",am="cache.key",rm="cache.item_size";var om=0,i7=1,f9=2;function MU(A){if(A<400&&A>=100)return{code:1};if(A>=400&&A<500)switch(A){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(A>=500&&A<600)switch(A){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}function LU(A,Q){A.setAttribute("http.response.status_code",Q);let B=MU(Q);if(B.message!=="unknown_error")A.setStatus(B)}var iHA="_sentryScope",nHA="_sentryIsolationScope";function bD(A,Q,B){if(A)m0(A,nHA,B),m0(A,iHA,Q)}function l5(A){return{scope:A[iHA],isolationScope:A[nHA]}}function PC(A){if(typeof A==="boolean")return Number(A);let Q=typeof A==="string"?parseFloat(A):A;if(typeof Q!=="number"||isNaN(Q)||Q<0||Q>1)return;return Q}var mD="sentry-",aHA=/^sentry-/,rHA=8192;function n7(A){let Q=LE(A);if(!Q)return;let B=Object.entries(Q).reduce((Y,[J,C])=>{if(J.match(aHA)){let X=J.slice(mD.length);Y[X]=C}return Y},{});if(Object.keys(B).length>0)return B;else return}function s7(A){if(!A)return;let Q=Object.entries(A).reduce((B,[Y,J])=>{if(J)B[`${mD}${Y}`]=J;return B},{});return mw(Q)}function LE(A){if(!A||!DE(A)&&!Array.isArray(A))return;if(Array.isArray(A))return A.reduce((Q,B)=>{let Y=sHA(B);return Object.entries(Y).forEach(([J,C])=>{Q[J]=C}),Q},{});return sHA(A)}function sHA(A){return A.split(",").map((Q)=>Q.split("=").map((B)=>{try{return decodeURIComponent(B.trim())}catch{return}})).reduce((Q,[B,Y])=>{if(B&&Y)Q[B]=Y;return Q},{})}function mw(A){if(Object.keys(A).length===0)return;return Object.entries(A).reduce((Q,[B,Y],J)=>{let C=`${encodeURIComponent(B)}=${encodeURIComponent(Y)}`,X=J===0?C:`${Q},${C}`;if(X.length>rHA)return OA&&t.warn(`Not adding key: ${B} with val: ${Y} to baggage header due to exceeding baggage size limits.`),Q;else return X},"")}var uD=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function oHA(A){if(!A)return;let Q=A.match(uD);if(!Q)return;let B;if(Q[3]==="1")B=!0;else if(Q[3]==="0")B=!1;return{traceId:Q[1],parentSampled:B,parentSpanId:Q[2]}}function qE(A,Q){let B=oHA(A),Y=n7(Q);if(!B?.traceId)return{traceId:wC(),sampleRand:Math.random()};let J=iWB(B,Y);if(Y)Y.sample_rand=J.toString();let{traceId:C,parentSpanId:X,parentSampled:G}=B;return{traceId:C,parentSpanId:X,sampled:G,dsc:Y||{},sampleRand:J}}function a7(A=wC(),Q=jC(),B){let Y="";if(B!==void 0)Y=B?"-1":"-0";return`${A}-${Q}${Y}`}function iWB(A,Q){let B=PC(Q?.sample_rand);if(B!==void 0)return B;let Y=PC(Q?.sample_rate);if(Y&&A?.parentSampled!==void 0)return A.parentSampled?Math.random()*Y:Y+Math.random()*(1-Y);else return Math.random()}var uw=0,dw=1,tHA=!1;function ADA(A){let{spanId:Q,traceId:B}=A.spanContext(),{data:Y,op:J,parent_span_id:C,status:X,origin:G,links:F}=AQ(A);return{parent_span_id:C,span_id:Q,trace_id:B,data:Y,op:J,status:X,origin:G,links:F}}function r7(A){let{spanId:Q,traceId:B,isRemote:Y}=A.spanContext(),J=Y?Q:AQ(A).parent_span_id,C=l5(A).scope,X=Y?C?.getPropagationContext().propagationSpanId||jC():Q;return{parent_span_id:J,span_id:X,trace_id:B}}function lD(A){let{traceId:Q,spanId:B}=A.spanContext(),Y=r1(A);return a7(Q,B,Y)}function zE(A){if(A&&A.length>0)return A.map(({context:{spanId:Q,traceId:B,traceFlags:Y,...J},attributes:C})=>({span_id:Q,trace_id:B,sampled:Y===dw,attributes:C,...J}));else return}function b9(A){if(typeof A==="number")return eHA(A);if(Array.isArray(A))return A[0]+A[1]/1e9;if(A instanceof Date)return eHA(A.getTime());return RC()}function eHA(A){return A>9999999999?A/1000:A}function AQ(A){if(sWB(A))return A.getSpanJSON();let{spanId:Q,traceId:B}=A.spanContext();if(nWB(A)){let{attributes:Y,startTime:J,name:C,endTime:X,status:G,links:F}=A,W="parentSpanId"in A?A.parentSpanId:("parentSpanContext"in A)?A.parentSpanContext?.spanId:void 0;return{span_id:Q,trace_id:B,data:Y,description:C,parent_span_id:W,start_timestamp:b9(J),timestamp:b9(X)||void 0,status:RE(G),op:Y[JQ],origin:Y[NQ],links:zE(F)}}return{span_id:Q,trace_id:B,start_timestamp:0,data:{}}}function nWB(A){let Q=A;return!!Q.attributes&&!!Q.startTime&&!!Q.name&&!!Q.endTime&&!!Q.status}function sWB(A){return typeof A.getSpanJSON==="function"}function r1(A){let{traceFlags:Q}=A.spanContext();return Q===dw}function RE(A){if(!A||A.code===om)return;if(A.code===i7)return"ok";return A.message||"unknown_error"}var dD="_sentryChildSpans",tm="_sentryRootSpan";function qU(A,Q){let B=A[tm]||A;if(m0(Q,tm,B),A[dD])A[dD].add(Q);else m0(A,dD,new Set([Q]))}function cD(A){let Q=new Set;function B(Y){if(Q.has(Y))return;else if(r1(Y)){Q.add(Y);let J=Y[dD]?Array.from(Y[dD]):[];for(let C of J)B(C)}}return B(A),Array.from(Q)}function E0(A){return A[tm]||A}function c5(){let A=zJ(),Q=q8(A);if(Q.getActiveSpan)return Q.getActiveSpan();return u5(nQ())}function pD(){if(!tHA)v0(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")}),tHA=!0}function em(A,Q){A.updateName(Q),A.setAttributes({[eB]:"custom",[d5]:Q})}var Qu="?",QDA=/\(error: (.*)\)/,BDA=/captureMessage|captureException/;function cw(...A){let Q=A.sort((B,Y)=>B[0]-Y[0]).map((B)=>B[1]);return(B,Y=0,J=0)=>{let C=[],X=B.split(`
|
|
239
|
+
}`});try{let Y=(await Q.next()).value?.data?.userById;if(!Y)return n.warning(`PlatformGateway.getPlayerCosmetics(): No cosmetic data returned for user id "${A}".`);let J=Y.equippedItems.map((G)=>({slot:G.slot,item:G.item.slots.find((F)=>F.type===G.slot)})).filter((G)=>!!G.item),C=Number(Y.characterSettings?.hairStyle?.split("_")[1]||1),X=`https://d3qkovarww0lj1.cloudfront.net/?skin_tone=${Y.characterSettings?.skinTone||"SKIN_COLOR_1"}&clothing=${Y.characterSettings?.clothing||"CLOTHING_1"}&hair_style=${Y.characterSettings?.hairStyle||"HAIR_STYLE_1"}&hair_color=${Y.characterSettings?.hairColor||"HAIR_COLOR_1"}&eye_color=${Y.characterSettings?.eyeColor||"00FF00"}`;return{equippedItems:J,hairStyle:C,skinTextureUri:X}}finally{await Q.return?.()}}async getPlayerSession(A){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(A)}async scheduleNotification(A,Q,B){if(!Iw)return n.warning("PlatformGateway.scheduleNotification(): HYTOPIA_NOTIFICATION_SERVICE_URL is not set. Unable to schedule notification.");if(!this.gameId||!this.creatorApiKey)return n.warning("PlatformGateway.scheduleNotification(): HYTOPIA_GAME_ID or HYTOPIA_API_KEY is not set. Unable to schedule notification.");if(B<Date.now()+55000)return n.warning("PlatformGateway.scheduleNotification(): scheduledFor must be at least 60 seconds in the future. Unable to schedule notification.");try{let Y=await fetch(`${Iw}/notifications`,{method:"POST",headers:{"Content-Type":"application/json","X-Game-Id":this.gameId,"X-Creator-Api-Key":this.creatorApiKey},body:JSON.stringify({hytopiaUserId:A,type:Q,scheduledFor:B})});if(!Y.ok)return n.warning(`PlatformGateway.scheduleNotification(): Failed ${Y.status}: ${await Y.text()}`);return(await Y.json()).id}catch(Y){return n.warning(`PlatformGateway.scheduleNotification(): Failed to schedule notification: ${Y}`)}}async setGlobalData(A,Q){if(Q.error)return n.warning("PlatformGateway.setGlobalData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return n.warning("PlatformGateway.setGlobalData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(A,Q):this._writeDevGlobalDataLocally(A,Q)}async unscheduleNotification(A){if(!Iw)return n.warning("PlatformGateway.unscheduleNotification(): HYTOPIA_NOTIFICATION_SERVICE_URL is not set."),!1;if(!this.gameId||!this.creatorApiKey)return n.warning("PlatformGateway.scheduleNotification(): HYTOPIA_GAME_ID or HYTOPIA_API_KEY is not set."),!1;try{let Q=await fetch(`${Iw}/notifications/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json","X-Game-Id":this.gameId,"X-Creator-Api-Key":this.creatorApiKey}});if(!Q.ok)return n.warning(`PlatformGateway.unscheduleNotification(): Failed ${Q.status}: ${await Q.text()}`),!1;return!0}catch(Q){return n.warning(`PlatformGateway.unscheduleNotification(): Failed to unschedule notification: ${Q}`),!1}}_readDevGlobalDataLocally(A){try{if(!EE.existsSync(LD))return{error:{code:"keyNotFound",message:"Local data directory not found."}};let Q=DVA.join(LD,`${A}.json`);return JSON.parse(EE.readFileSync(Q,"utf8"))}catch(Q){return n.warning(`PlatformGateway._readDevGlobalDataLocally(): Failed to read data for key "${A}": ${Q}`),{error:{code:"gatewayError",message:"Failed to read data for key."}}}}_writeDevGlobalDataLocally(A,Q){try{if(!EE.existsSync(LD))EE.mkdirSync(LD,{recursive:!0});let B=DVA.join(LD,`${A}.json`),Y={};if(EE.existsSync(B))Y=JSON.parse(EE.readFileSync(B,"utf8"));let J={...Y,...Q};EE.writeFileSync(B,JSON.stringify(J,null,2),"utf8")}catch(B){n.warning(`PlatformGateway._writeDevGlobalDataLocally(): Failed to write data for key "${A}": ${B}`)}}}class f7{static instance=new f7;_saveStatesClient;constructor(){this._saveStatesClient=new MVA.SaveStatesClient}async getGlobalData(A,Q=3){for(let B=0;B<=Q;B++){let Y=await H8.instance.getGlobalData(A);if(Y&&!Y.error)return Y;if(Y.error.code==="keyNotFound")return{};if(B<Q)n.warning(`PersistenceManager.getGlobalData(): Failed to get global data, retrying. Response: ${JSON.stringify(Y)}`),await new Promise((J)=>setTimeout(J,500))}n.warning(`PersistenceManager.getGlobalData(): Failed to get global data after ${Q} attempts.`);return}async getPlayerData(A){let Q=await this._saveStatesClient.load(this._getPlayerKey(A));if(!Q)return n.warning(`PersistenceManager.getPlayerData(): Failed to get player data for player ${A.id}. Persistence service may be down.`),{};return Q}async setGlobalData(A,Q){let B=await H8.instance.setGlobalData(A,Q);if(!B||B.error){if(B?.error)n.warning(`PersistenceManager.setGlobalData(): ${B.error.message}`)}}async setPlayerData(A,Q){let B=await this.getPlayerData(A);for(let[Y,J]of Object.entries(Q))B[Y]=J}async unloadPlayerData(A){await this._saveStatesClient.unload(this._getPlayerKey(A))}_getPlayerKey(A){return`player-${A.id}`}}var LVA;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})(LVA||={});var Ym;((I)=>{I.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";I.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";I.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";I.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";I.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";I.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";I.SET_FOV="PLAYER_CAMERA.SET_FOV";I.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";I.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";I.SET_MODE="PLAYER_CAMERA.SET_MODE";I.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";I.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";I.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";I.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";I.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(Ym||={});class qD extends YQ{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(A){super();this.player=A}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let A=this._orientation.pitch*0.5,Q=this._orientation.yaw*0.5,B=Math.cos(A),Y=Math.sin(A),J=Math.cos(Q),C=Math.sin(Q);return{x:Y*J,y:B*C,z:-Y*C,w:B*J}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(A){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:A})}lookAtPosition(A){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:A})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(A){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!A.isSpawned)return n.error(`PlayerCamera.setAttachedToEntity(): Entity ${A.id} is not spawned!`);this._attachedToEntity=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:A})}setAttachedToPosition(A){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:A})}setFilmOffset(A){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:A})}setForwardOffset(A){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:A})}setFov(A){if(!this._requirePlayerWorld("setFov"))return;this._fov=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:A})}setModelHiddenNodes(A){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(A){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(A){if(!this._requirePlayerWorld("setMode"))return;this._mode=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:A})}setOffset(A){if(!this._requirePlayerWorld("setOffset"))return;this._offset=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:A})}setOrientationPitch(A){this._orientation.pitch=A}setOrientationYaw(A){this._orientation.yaw=A}setShoulderAngle(A){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:A})}setTrackedEntity(A){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:A})}setTrackedPosition(A){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:A})}setZoom(A){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=A,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:A})}serialize(){return VQ.serializePlayerCamera(this)}_requirePlayerWorld(A){if(!this.player.world)n.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${A}()`);return!!this.player.world}}var Hw;((C)=>{C.DATA="PLAYER_UI.DATA";C.FREEZE_POINTER_LOCK="PLAYER_UI.FREEZE_POINTER_LOCK";C.LOAD="PLAYER_UI.LOAD";C.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";C.SEND_DATA="PLAYER_UI.SEND_DATA"})(Hw||={});class zD extends YQ{player;constructor(A){super();this.player=A}freezePointerLock(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.FREEZE_POINTER_LOCK",{playerUI:this,freeze:A})}load(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:A})}lockPointer(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:A})}sendData(A){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:A})}}var N7B=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0","cp","cy","iro","ird","jd"],RD;((G)=>{G.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";G.INTERACT="PLAYER.INTERACT";G.JOINED_WORLD="PLAYER.JOINED_WORLD";G.LEFT_WORLD="PLAYER.LEFT_WORLD";G.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";G.REQUEST_NOTIFICATION_PERMISSION="PLAYER.REQUEST_NOTIFICATION_PERMISSION";G.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(RD||={});class ZU extends YQ{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;cosmetics;ui;_input={};_interactEnabled=!0;_lastUnreliableInputSequenceNumber=0;_maxInteractDistance=20;_persistedData;_world;_worldSwitched=!1;constructor(A,Q){super();this.id=Q?.user.id??`player-${ZU._devNextPlayerId++}`,this.username=Q?.user.username??this.id,this.profilePictureUrl=Q?.user.profilePictureURL??void 0,this.camera=new qD(this),this.connection=A,this.cosmetics=H8.instance.getPlayerCosmetics(this.id),this.ui=new zD(this),A.onPacket(xA.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),A.onPacket(xA.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),A.onPacket(xA.PacketId.INPUT,this._onInputPacket),A.onPacket(xA.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),A.onPacket(xA.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get interactEnabled(){return this._interactEnabled}get maxInteractDistance(){return this._maxInteractDistance}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){if(!this._persistedData)return;let A=Object.keys(this._persistedData);if(A.length===0||A.length===1&&A[0]==="__version")return;return this._persistedData}joinWorld(A){if(this._world===A)return;if(!this._world)this._world=A,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let Q of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(Q.isSpawned)Q.despawn();this.disconnect(),this._world=A,this._worldSwitched=!0}}async scheduleNotification(A,Q){if(!this._world)return n.warning("Player.scheduleNotification(): Player must be in a world to schedule a notification.");return this.emitWithWorld(this._world,"PLAYER.REQUEST_NOTIFICATION_PERMISSION",{player:this}),H8.instance.scheduleNotification(this.id,A,Q)}async unscheduleNotification(A){if(!A)return!1;return H8.instance.unscheduleNotification(A)}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await f7.instance.getPlayerData(this)}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setInteractEnabled(A){this._interactEnabled=A}setMaxInteractDistance(A){this._maxInteractDistance=A}setPersistedData(A){if(!this._persistedData){n.warning(`Player.setPersistedData(): Persisted data not found for player ${this.id}`);return}for(let[Q,B]of Object.entries(A))this._persistedData[Q]=B}serialize(){return VQ.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(A)=>{if(!this._world)return;let Q=A[1].m;if(this._world.chatManager.handleCommand(this,Q)){this._world.chatManager.sendPlayerMessage(this,`Command Entered: ${Q}`,"CCCCCC");return}if(this.id.startsWith("guest")){this._world.chatManager.sendPlayerMessage(this,"You need to create a HYTOPIA account to send messages in chat.","FFAA00");return}this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:Q})};_onDebugConfigPacket=(A)=>{console.log(A)};_onInputPacket=(A)=>{let Q=A[1];if(Q.sq!==void 0){if(Q.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=Q.sq}if(Object.assign(this._input,Q),Q.cp!==void 0)this.camera.setOrientationPitch(Q.cp);if(Q.cy!==void 0)this.camera.setOrientationYaw(Q.cy);if(this.world&&Q.ird&&Q.iro)this.interact()};interact=()=>{if(!this.world||!this._input.ird||!this._input.iro)return;if(this._interactEnabled){let A={x:this._input.iro[0],y:this._input.iro[1],z:this._input.iro[2]},Q={x:this._input.ird[0],y:this._input.ird[1],z:this._input.ird[2]},B=this.world.entityManager.getPlayerEntitiesByPlayer(this)[0],Y=this.world.simulation.raycast(A,Q,this._maxInteractDistance,{filterExcludeRigidBody:B?.rawRigidBody,filterFlags:WB.QueryFilterFlags.EXCLUDE_SENSORS});if(this.emitWithWorld(this.world,"PLAYER.INTERACT",{player:this,interactOrigin:A,interactDirection:Q,raycastHit:Y}),Y?.hitEntity)Y.hitEntity.interact(this,Y);if(Y?.hitBlock)Y.hitBlock.blockType.interact(this,Y)}};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(A)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:A[1]})}}var Jm;((B)=>{B.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";B.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(Jm||={});class wD extends YQ{_commandCallbacks={};_world;constructor(A){super();this._world=A,this._subscribeToPlayerEvents()}registerCommand(A,Q){this._commandCallbacks[A]=Q}unregisterCommand(A){delete this._commandCallbacks[A]}sendBroadcastMessage(A,Q){this._sendBroadcastMessage(void 0,A,Q)}handleCommand(A,Q){let[B,...Y]=Q.split(" "),J=this._commandCallbacks[B];if(J)return J(A,Y,Q),!0;return!1}sendPlayerMessage(A,Q,B){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:A,message:Q,color:B})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(A)=>{let{player:Q,message:B}=A;this._sendBroadcastMessage(Q,B)})}_sendBroadcastMessage(A,Q,B){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:A,message:Q,color:B})}}var LC=16,Cm=LC-1,M7B=LC**3;class v9{_blocks;_originCoordinate;constructor(A){this._blocks=new Uint8Array(M7B),this._originCoordinate=A}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(A){return{x:A%LC,y:(A/LC|0)%LC,z:A/(LC*LC)|0}}static globalCoordinateToLocalCoordinate(A){return{x:A.x&LC-1,y:A.y&LC-1,z:A.z&LC-1}}static globalCoordinateToOriginCoordinate(A){return{x:A.x&~(LC-1),y:A.y&~(LC-1),z:A.z&~(LC-1)}}getBlockId(A){return this._blocks[this._getIndex(A)]}hasBlock(A){return this._blocks[this._getIndex(A)]!==0}setBlock(A,Q){if(!this._isValidLocalCoordinate(A))return n.error("Chunk.setBlock(): Block local coordinate is out of bounds");let B=this._getIndex(A);this._blocks[B]=Q}serialize(){return VQ.serializeChunk(this)}_getIndex(A){return A.x+(A.y<<4)+(A.z<<8)}_isValidLocalCoordinate(A){return A.x>=0&&A.x<=Cm&&A.y>=0&&A.y<=Cm&&A.z>=0&&A.z<=Cm}}var Xm;((Y)=>{Y.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";Y.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";Y.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(Xm||={});class jD extends YQ{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(A){super();this._world=A}get chunkCount(){return this._chunks.size}clear(){for(let A of this._blockTypeColliders.values())A.removeFromSimulation();this._chunks.forEach((A)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:A})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(A){let Q=this.getChunk(v9.globalCoordinateToOriginCoordinate(A));if(!Q)return 0;return Q.getBlockId(v9.globalCoordinateToLocalCoordinate(A))}getBlockTypeCollider(A){return this._blockTypeColliders.get(A)}getBlockType(A){let Q=this.getBlockId(A);return Q?this._world.blockTypeRegistry.getBlockType(Q):null}getBlockTypeCount(A){return this._blockTypeCounts.get(A)??0}getChunk(A){return this._chunks.get(this._getChunkKey(v9.globalCoordinateToOriginCoordinate(A)))}getOrCreateBlockTypeCollider(A,Q){let B=this._blockTypeColliders.get(A);if(B)return B;let J=this._world.blockTypeRegistry.getBlockType(A).createCollider(Q);return this._blockTypeColliders.set(A,J),J}getOrCreateChunk(A){let Q=v9.globalCoordinateToOriginCoordinate(A),B=this._chunks.get(this._getChunkKey(Q));if(B)return B;return B=new v9(Q),this._chunks.set(this._getChunkKey(Q),B),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:B}),B}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(A){let Q=this.getChunk(v9.globalCoordinateToOriginCoordinate(A));if(!Q)return!1;return Q.hasBlock(v9.globalCoordinateToLocalCoordinate(A))}hasChunk(A){let Q=v9.globalCoordinateToOriginCoordinate(A);return this._chunks.has(this._getChunkKey(Q))}initializeBlocks(A){if(this.clear(),!this._rigidBody)this._rigidBody=new j7({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);for(let Q in A){let B=Number(Q),Y=A[B];if(Y.length===0)continue;let J=this.getOrCreateBlockTypeCollider(B,Y);J.addToSimulation(this._world.simulation,this._rigidBody);let C=this._world.blockTypeRegistry.getBlockType(B);this._world.simulation.colliderMap.setColliderBlockType(J,C),this._blockTypeCounts.set(B,Y.length);for(let X=0;X<Y.length;X++){let G=Y[X],F=v9.globalCoordinateToLocalCoordinate(G),W=this.getOrCreateChunk(G);W.setBlock(F,B),this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:W,globalCoordinate:G,localCoordinate:F,blockTypeId:B})}this._combineVoxelStates(J)}}setBlock(A,Q){let B=v9.globalCoordinateToLocalCoordinate(A),Y=this.getOrCreateChunk(A),J=Y.getBlockId(B);if(J===Q)return;if(Y.setBlock(B,Q),!this._rigidBody)this._rigidBody=new j7({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(J!==0){let C=Math.max(0,(this._blockTypeCounts.get(J)??0)-1),X=this.getBlockTypeCollider(J);if(X)if(C===0)this._world.simulation.colliderMap.removeColliderBlockType(X),X.removeFromSimulation(),this._blockTypeColliders.delete(J);else X.setVoxel(A,!1),this._propagateVoxelChange(X,A);this._blockTypeCounts.set(J,C)}if(Q!==0){let C=(this._blockTypeCounts.get(Q)??0)+1,X=this.getOrCreateBlockTypeCollider(Q,[A]);if(C===1){let G=this._world.blockTypeRegistry.getBlockType(Q);X.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(X,G),this._combineVoxelStates(X)}else X.setVoxel(A,!0),this._propagateVoxelChange(X,A);this._blockTypeCounts.set(Q,C)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:Y,globalCoordinate:A,localCoordinate:B,blockTypeId:Q})}_combineVoxelStates(A){if(A.isSensor)return;for(let Q of this._blockTypeColliders.values()){if(Q===A||Q.isSensor)continue;A.combineVoxelStates(Q)}}_getChunkKey(A){return`${A.x},${A.y},${A.z}`}_propagateVoxelChange(A,Q){if(A.isSensor)return;for(let B of this._blockTypeColliders.values()){if(B===A||B.isSensor)continue;A.propagateVoxelChange(B,Q)}}}class OD{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(A){if(!this._requireSimulatedCollider(A))return;return this._colliderHandleBlockTypeMap.get(A.rawCollider.handle)}getColliderCollisionCallback(A){if(!this._requireSimulatedCollider(A))return;return this._colliderHandleCollisionCallbackMap.get(A.rawCollider.handle)}getColliderEntity(A){if(!this._requireSimulatedCollider(A))return;return this._colliderHandleEntityMap.get(A.rawCollider.handle)}getColliderHandleBlockType(A){return this._colliderHandleBlockTypeMap.get(A)}getColliderHandleCollisionCallback(A){return this._colliderHandleCollisionCallbackMap.get(A)}getColliderHandleEntity(A){return this._colliderHandleEntityMap.get(A)}removeColliderBlockType(A){if(!this._requireSimulatedCollider(A))return;this.removeColliderHandleBlockType(A.rawCollider.handle)}removeColliderCollisionCallback(A){if(!this._requireSimulatedCollider(A))return;this.removeColliderHandleCollisionCallback(A.rawCollider.handle)}removeColliderEntity(A){if(!this._requireSimulatedCollider(A))return;this.removeColliderHandleEntity(A.rawCollider.handle)}removeColliderHandleBlockType(A){this._colliderHandleBlockTypeMap.delete(A)}removeColliderHandleCollisionCallback(A){this._colliderHandleCollisionCallbackMap.delete(A)}removeColliderHandleEntity(A){this._colliderHandleEntityMap.delete(A)}setColliderBlockType(A,Q){if(!this._requireSimulatedCollider(A))return;this.setColliderHandleBlockType(A.rawCollider.handle,Q)}setColliderCollisionCallback(A,Q){if(!this._requireSimulatedCollider(A))return;this.setColliderHandleCollisionCallback(A.rawCollider.handle,Q)}setColliderEntity(A,Q){if(!this._requireSimulatedCollider(A))return;this.setColliderHandleEntity(A.rawCollider.handle,Q)}setColliderHandleBlockType(A,Q){this._colliderHandleBlockTypeMap.set(A,Q),this._cleanupBlockTypeColliderHandles.delete(A),this._pendingCleanupBlockTypeColliderHandles.delete(A)}setColliderHandleCollisionCallback(A,Q){this._colliderHandleCollisionCallbackMap.set(A,Q),this._cleanupCollisionCallbackColliderHandles.delete(A),this._pendingCleanupCollisionCallbackColliderHandles.delete(A)}setColliderHandleEntity(A,Q){this._colliderHandleEntityMap.set(A,Q),this._cleanupEntityColliderHandles.delete(A),this._pendingCleanupEntityColliderHandles.delete(A)}queueColliderHandleForCleanup(A){if(this._colliderHandleBlockTypeMap.has(A))this._pendingCleanupBlockTypeColliderHandles.add(A);if(this._colliderHandleCollisionCallbackMap.has(A))this._pendingCleanupCollisionCallbackColliderHandles.add(A);if(this._colliderHandleEntityMap.has(A))this._pendingCleanupEntityColliderHandles.add(A)}cleanup(){for(let A of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(A);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let A of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(A);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let A of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(A);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let A of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(A);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let A of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(A);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let A of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(A);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(A){if(!A.rawCollider)n.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!A.rawCollider}}var qVA={type:"dynamic",softCcdPrediction:1},zVA=0.015625,RVA=Math.cos(0.026),PD;((q)=>{q.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";q.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";q.DESPAWN="ENTITY.DESPAWN";q.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";q.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";q.INTERACT="ENTITY.INTERACT";q.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";q.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";q.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";q.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";q.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";q.SET_OPACITY="ENTITY.SET_OPACITY";q.SET_PARENT="ENTITY.SET_PARENT";q.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";q.SPAWN="ENTITY.SPAWN";q.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";q.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";q.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";q.TICK="ENTITY.TICK";q.UPDATE_POSITION="ENTITY.UPDATE_POSITION";q.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(PD||={});class CY extends j7{_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale={x:1,y:1,z:1};_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(A){let Q="blockTextureUri"in A,B="modelUri"in A;if(!Q===!B)n.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(Q&&!A.blockHalfExtents)n.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(A.parent&&!A.parent.isSpawned)n.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(A.parent?.modelUri&&A.parentNodeName&&!BJ.instance.modelHasNode(A.parent.modelUri,A.parentNodeName))n.fatalError(`Entity.constructor(): Parent node name ${A.parentNodeName} not found in parent model ${A.parent.modelUri}!`);super(A.rigidBodyOptions??qVA);if(Q)this._blockHalfExtents=A.blockHalfExtents,this._blockTextureUri=A.blockTextureUri;if(B){let Y=this._modelScale=typeof A.modelScale==="number"?{x:A.modelScale,y:A.modelScale,z:A.modelScale}:A.modelScale??{x:1,y:1,z:1};if(this._modelAnimationsPlaybackRate=A.modelAnimationsPlaybackRate??1,this._modelPreferredShape=A.modelPreferredShape,this._modelScale=Y,this._modelTextureUri=A.modelTextureUri,this._modelUri=A.modelUri,!this._modelUri.startsWith("http")&&!BJ.instance.hasModel(this._modelUri))n.error(`Entity.constructor(): Model ${this._modelUri} does not exist!`);A.modelHiddenNodes?.forEach((J)=>this._modelHiddenNodes.add(J.toLowerCase())),A.modelLoopedAnimations?.forEach((J)=>this._modelLoopedAnimations.add(J)),A.modelShownNodes?.forEach((J)=>this._modelShownNodes.add(J.toLowerCase()))}if(this._isEnvironmental=A.isEnvironmental??!1,this._name=A.name??"Nameless",this._opacity=A.opacity??1,this._parent=A.parent,this._parentNodeName=A.parentNodeName,this._tag=A.tag,this._tintColor=A.tintColor,this._positionUpdateThresholdSq=zVA,this._rotationUpdateThreshold=RVA,A.controller)this.setController(A.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?BJ.instance.getDepth(this._modelUri)*this._modelScale.z:this._blockHalfExtents.z*2}get height(){return this.isModelEntity?BJ.instance.getHeight(this._modelUri)*this._modelScale.y:this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?BJ.instance.getWidth(this._modelUri)*this._modelScale.x:this._blockHalfExtents.x*2}get world(){return this._world}spawn(A,Q,B){if(this.isSpawned)return n.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(A.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new IC(IC.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new IC(IC.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach((Y)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))Y.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Y.enableContactForceEvents(!0);if(P5.isDefaultCollisionGroups(Y.collisionGroups)){let J=this.isEnvironmental?[8]:[Y.isSensor?4:2],C=this.isEnvironmental?[65535&~8&~1]:[65535];Y.setCollisionGroups({belongsTo:J,collidesWith:C})}}),this.setPosition(Q),B)this.setRotation(B);if(this._id=A.entityManager.registerEntity(this),this._world=A,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,Q,B);this.colliders.forEach((Y)=>{A.simulation.colliderMap.setColliderEntity(Y,this)}),this.emitWithWorld(A,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((A)=>{A.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}interact(A,Q){if(!this._requireSpawned("interact"))return;this.emitWithWorld(this._world,"ENTITY.INTERACT",{entity:this,player:A,raycastHit:Q})}setController(A){if(this._controller===A)return;if(this._controller)this._controller.detach(this);if(this._controller=A,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(A){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===A)return;this._modelAnimationsPlaybackRate=A,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:A})}setModelHiddenNodes(A){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(A){if(!this._requireSpawned("setModelScale"))return;if(typeof A==="number")A={x:A,y:A,z:A};if(!this.isModelEntity||this._modelScale===A)return;let Q={x:A.x/this._modelScale.x,y:A.y/this._modelScale.y,z:A.z/this._modelScale.z};this._modelScale=A,this.colliders.forEach((B)=>B.setScale(Q)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:A})}setModelShownNodes(A){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(A.map((Q)=>Q.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(A){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===A)return;this._modelTextureUri=A,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:A})}setOpacity(A){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===A)return;this._opacity=A,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:A})}setParent(A,Q,B,Y){if(!this._requireSpawned("setParent"))return;if(A&&!A.isSpawned)return n.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&A)this._lastParentlessType=this.type;if(this._parent=A,this._parentNodeName=Q,this.colliders.forEach((J)=>J.setEnabled(!A)),this.setType(!A?this._lastParentlessType:"kinematic_velocity"),this.setPosition(B??{x:0,y:0,z:0}),this.setRotation(Y??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:A,parentNodeName:Q})}setTintColor(A){if(!this._requireSpawned("setTintColor"))return;if(!A&&!this._tintColor||A&&this._tintColor&&A.r===this._tintColor.r&&A.g===this._tintColor.g&&A.b===this._tintColor.b)return;this._tintColor=A,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:A})}startModelLoopedAnimations(A){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!A.length)return;if(!A.some((Q)=>!this._modelLoopedAnimations.has(Q)))return;A.forEach((Q)=>{this._modelLoopedAnimations.add(Q)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(A)})}startModelOneshotAnimations(A){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!A.length)return;A.forEach((Q)=>{this._modelOneshotAnimations.add(Q)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(A)})}stopAllModelAnimations(A=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],A)}stopAllModelLoopedAnimations(A=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],A)}stopAllModelOneshotAnimations(A=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],A)}stopModelAnimations(A){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!A.length)return;if(!A.some((Q)=>this._modelLoopedAnimations.has(Q))&&!A.some((Q)=>this._modelOneshotAnimations.has(Q)))return;A.forEach((Q)=>{this._modelLoopedAnimations.delete(Q),this._modelOneshotAnimations.delete(Q)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(A)})}serialize(){return VQ.serializeEntity(this)}tick(A){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:A}),this._controller)this._controller.tick(this,A)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let A=this.position,Q=this.rotation;if(this._rotationExceedsThreshold(Q,this._lastUpdatedRotation))this._lastUpdatedRotation=Q,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:Q});if(this._positionExceedsThreshold(A,this._lastUpdatedPosition))this._lastUpdatedPosition=A,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:A})}_positionExceedsThreshold(A,Q){let B=A.x-Q.x,Y=A.y-Q.y,J=A.z-Q.z;return B*B+Y*Y+J*J>this._positionUpdateThresholdSq}_requireSpawned(A){if(!this.isSpawned)n.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${A}()!`);return this.isSpawned}_rotationExceedsThreshold(A,Q){return Math.abs(A.x*Q.x+A.y*Q.y+A.z*Q.z+A.w*Q.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(A,Q=[]){if(!this.isModelEntity)return;let B=new Set(Q),Y=[];for(let J of A)for(let C of J)if(!B.has(C))Y.push(C);if(Y.length>0)this.stopModelAnimations(Y)}}class J0 extends UW{static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(A={}){super();this.applyDirectionalMovementRotations=A.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=A.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=A.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=A.sticksToPlatforms??this.sticksToPlatforms,this.canJump=A.canJump??this.canJump,this.canRun=A.canRun??this.canRun,this.canSwim=A.canSwim??this.canSwim,this.canWalk=A.canWalk??this.canWalk,this.jumpVelocity=A.jumpVelocity??this.jumpVelocity,this.runVelocity=A.runVelocity??this.runVelocity,this.walkVelocity=A.walkVelocity??this.walkVelocity,this.swimFastVelocity=A.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=A.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=A.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=A.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=A.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=A.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=A.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=A.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=A.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=A.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=A.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=A.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=A.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=A.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(A){super.attach(A),this._internalApplyImpulse=A.applyImpulse.bind(A),A.applyImpulse=(Q)=>{let B=A.mass||1;this._externalVelocity.x+=Q.x/B,this._externalVelocity.y+=Q.y/B,this._externalVelocity.z+=Q.z/B},this._stepAudio=new LV({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:A}),A.setCcdEnabled(!0),A.lockAllRotations(),A.on("ENTITY.BLOCK_COLLISION",({blockType:Q,started:B})=>{if(!Q.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&B){let Y=A.linearVelocity;A.setLinearVelocity({x:Y.x*this.swimGravity,y:Y.y*this.swimGravity,z:Y.z*this.swimGravity})}if(this._liquidContactCount+=B?1:-1,this._liquidContactCount>0)A.setGravityScale(this.swimGravity),A.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+J0.SWIM_UPWARD_COOLDOWN_MS;else A.setGravityScale(1),A.stopModelAnimations(this.swimLoopedAnimations)})}spawn(A){if(!A.isSpawned)return n.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");A.createAndAddChildCollider({shape:"cylinder",radius:J0.GROUND_SENSOR_RADIUS_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),halfHeight:J0.GROUND_SENSOR_HEIGHT_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-A.height/2,z:0},tag:"groundSensor",onCollision:(Q,B)=>{if(!A.isSpawned)return;if(!(Q instanceof HC)||!Q.isLiquid){if(B&&this._groundContactCount===0&&A.linearVelocity.y<-1)if(A.linearVelocity.y<J0.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)A.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else A.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=B?1:-1}if(!this._groundContactCount&&!this.isSwimming)A.startModelOneshotAnimations(this.jumpOneshotAnimations);else A.stopModelAnimations(this.jumpOneshotAnimations);if(!(Q instanceof CY))return;if(B&&this.sticksToPlatforms)this._platform=Q;else if(Q===this._platform&&!B)this._platform=void 0}}),A.createAndAddChildCollider({shape:"capsule",halfHeight:J0.WALL_COLLIDER_HEIGHT_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),radius:J0.WALL_COLLIDER_RADIUS_SCALE*(A.height/J0.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(A,Q,B,Y){if(!A.isSpawned||!A.world)return;if(super.tickWithPlayerInput(A,Q,B,Y),A.parent)return;let{w:J,a:C,s:X,d:G,c:F,sp:W,sh:E,ml:$,jd:Z}=Q,{yaw:U}=B,K=A.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0;let I=typeof Z==="number";this._isActivelyMoving=I||!!(J||C||X||G);let V=E,H=!I&&(C&&G&&!J&&!X||J&&X&&!C&&!G),D=V&&this.canRun(this)||!V&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+J0.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!H&&D){let w=V?this.runLoopedAnimations:this.walkLoopedAnimations;A.stopAllModelLoopedAnimations(w),A.startModelLoopedAnimations(w),this._stepAudio?.setPlaybackRate(V?0.75:0.51),this._stepAudio?.play(A.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)A.stopAllModelLoopedAnimations(this.swimLoopedAnimations),A.startModelLoopedAnimations(this.swimLoopedAnimations);else A.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),A.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),A.stopAllModelLoopedAnimations(this.idleLoopedAnimations),A.startModelLoopedAnimations(this.idleLoopedAnimations);let M;if(this.applyDirectionalMovementRotations&&D){if(I)M=Z;else if(J&&C&&!G&&!X)M=J0.MOVEMENT_ROTATIONS.wa;else if(J&&G&&!C&&!X)M=J0.MOVEMENT_ROTATIONS.wd;else if(X&&C&&!J&&!G)M=J0.MOVEMENT_ROTATIONS.sa;else if(X&&G&&!J&&!C)M=J0.MOVEMENT_ROTATIONS.sd;else if(X&&!J&&!C&&!G||C&&X&&G&&!J)M=J0.MOVEMENT_ROTATIONS.s;else if(C&&!J&&!X&&!G)M=J0.MOVEMENT_ROTATIONS.a;else if(G&&!J&&!C&&!X)M=J0.MOVEMENT_ROTATIONS.d}if($)A.startModelOneshotAnimations(this.interactOneshotAnimations),Q.ml=!this.autoCancelMouseLeftClick;if(D){let w=!this.isSwimming?V?this.runVelocity:this.walkVelocity:V?this.swimFastVelocity:this.swimSlowVelocity;if(I){let P=U+Z;this._reusableTargetVelocities.x=-w*Math.sin(P),this._reusableTargetVelocities.z=-w*Math.cos(P)}else{let P=Math.sin(U),_=Math.cos(U);if(J)this._reusableTargetVelocities.x-=w*P,this._reusableTargetVelocities.z-=w*_;if(X)this._reusableTargetVelocities.x+=w*P,this._reusableTargetVelocities.z+=w*_;if(C)this._reusableTargetVelocities.x-=w*_,this._reusableTargetVelocities.z+=w*P;if(G)this._reusableTargetVelocities.x+=w*_,this._reusableTargetVelocities.z-=w*P;let O=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(O>w){let k=w/O;this._reusableTargetVelocities.x*=k,this._reusableTargetVelocities.z*=k}}}if(this.isSwimming){if(K.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=K.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=K.z,A.setLinearVelocity(this._reusableVelocityClamp);if(K.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=K.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=K.z,A.setLinearVelocity(this._reusableVelocityClamp);if(F)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*J0.WATER_ENTRY_SINKING_FACTOR;else if(!W)this._reusableTargetVelocities.y=-K.y*J0.SWIMMING_DRAG_FACTOR}if(W&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&K.y>-0.001&&K.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let z=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let w=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(w>0.01){let _=Math.max(0,w-J0.EXTERNAL_IMPULSE_DECAY_RATE)/w;this._externalVelocity.x*=_,this._magnitudeYTracker*=_,this._externalVelocity.z*=_}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let q=this._reusableTargetVelocities.x+this._externalVelocity.x-K.x+z.x,N=this._reusableTargetVelocities.y+this._externalVelocity.y+z.y,L=this._reusableTargetVelocities.z+this._externalVelocity.z-K.z+z.z;if(this._externalVelocity.y=0,q!==0||N!==0||L!==0){let w=A.mass;this._reusableImpulse.x=q*w,this._reusableImpulse.y=N*w,this._reusableImpulse.z=L*w,this._internalApplyImpulse(this._reusableImpulse)}if(U!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let P=(M!==void 0?U+M:U)*0.5;A.setRotation({x:0,y:Math.sin(P),z:0,w:Math.cos(P)})}}}var Gm;((G)=>{G.LOAD="SCENE_UI.LOAD";G.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";G.SET_OFFSET="SCENE_UI.SET_OFFSET";G.SET_POSITION="SCENE_UI.SET_POSITION";G.SET_STATE="SCENE_UI.SET_STATE";G.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";G.UNLOAD="SCENE_UI.UNLOAD"})(Gm||={});class TD extends YQ{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(A){if(!!A.attachedToEntity===!!A.position)n.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=A.attachedToEntity,this._offset=A.offset,this._position=A.position,this._state=A.state??{},this._templateId=A.templateId,this._viewDistance=A.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(A){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=A.sceneUIManager.registerSceneUI(this),this._world=A,this.emitWithWorld(A,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(A){if(!A.isSpawned)return n.error(`SceneUI.setAttachedToEntity(): Entity ${A.id} is not spawned!`);if(this._attachedToEntity===A)return;if(this._attachedToEntity=A,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:A})}setOffset(A){if(this._offset===A)return;if(this._offset=A,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:A})}setPosition(A){if(this._position===A)return;if(this._attachedToEntity=void 0,this._position=A,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:A})}setState(A){if(this._state={...this._state,...A},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(A){if(this._viewDistance=A,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:A})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return VQ.serializeSceneUI(this)}}var wVA=0.010000000000000002,jVA=Math.cos(0.026);class i1 extends CY{player;nametagSceneUI;constructor(A){super(A);this._positionUpdateThresholdSq=wVA,this._rotationUpdateThreshold=jVA,this.player=A.player,this.nametagSceneUI=new TD({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(A,Q,B){super.spawn(A,Q,B),this.nametagSceneUI.load(A),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:Y})=>{this.nametagSceneUI.setState({chat:Y})})}tick(A){if(!this.isSpawned||!this.world)return;if(!this.controller)return n.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:Q,camera:B}=this.player;this.controller.tickWithPlayerInput(this,Q,B.orientation,A),super.tick(A)}}var OVA="models/players/player.gltf",L7B={BACK:"back-anchor",HEAD:"head-anchor",LEFT_ARM:"arm-left-anchor",LEFT_FOOT:"foot-left-anchor",LEFT_HAND:"hand-left-anchor",LEFT_ITEM:"hand-left-anchor",LEFT_LEG:"leg-left-anchor",RIGHT_ARM:"arm-right-anchor",RIGHT_FOOT:"foot-right-anchor",RIGHT_HAND:"hand-right-anchor",RIGHT_ITEM:"hand-right-anchor",RIGHT_LEG:"leg-right-anchor",TORSO:"torso-anchor"};class Fm extends i1{_cosmeticHiddenSlots;constructor(A){super({modelUri:OVA,modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...A});if(this._cosmeticHiddenSlots=A.cosmeticHiddenSlots??[],!A.controller)this.setController(new J0)}get cosmeticHiddenSlots(){return this._cosmeticHiddenSlots}spawn(A,Q,B){super.spawn(A,Q,B),this.player.cosmetics.then((Y)=>{if(!Y||!this.modelUri)return;let J=this.modelShownNodes.values().toArray().filter((G)=>!G.includes("hair-"));if(!(Y.equippedItems.some((G)=>G.item.flags.includes("HIDES_HAIR"))&&!this._cosmeticHiddenSlots.includes("ALL")&&!this._cosmeticHiddenSlots.includes("HEAD")))J.push(`hair-${String(Y.hairStyle).padStart(4,"0")}`);if(this.setModelShownNodes(J),this.modelUri===OVA)this.setModelTextureUri(Y.skinTextureUri);if(this._cosmeticHiddenSlots.includes("ALL"))return;let X=[];for(let G of Y.equippedItems){let{item:F,slot:W}=G;if(this._cosmeticHiddenSlots.includes(W))continue;let E=L7B[W];if(!E||!BJ.instance.modelHasNode(this.modelUri,E))continue;if(F.flags.includes("REPLACES_LIMB")){let Z=E.split("-").slice(0,-1).join("-");X.push(`${Z}-clothing`,`${Z}-geometry`)}new CY({modelUri:F.modelUrl,modelPreferredShape:"none",parent:this,parentNodeName:E}).spawn(A,{x:0,y:0,z:0})}if(X.length>0)this.setModelHiddenNodes([...this.modelHiddenNodes.values().toArray(),...X])}).catch((Y)=>n.warning(`DefaultPlayerEntity.spawn(): Failed to get player cosmetics: ${Y}`))}}class SD{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(A){this._world=A}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(A){if(A.id!==void 0)n.fatalError(`EntityManager.registerEntity(): Entity ${A.name} is already assigned the id ${A.id}!`);let Q=this._nextEntityId;if(this._entities.set(Q,A),this._nextEntityId++,!A.isEnvironmental)this._activeEntities.add(A);return Q}unregisterEntity(A){if(A.id===void 0)return n.error(`EntityManager.unregisterEntity(): Entity ${A.name} is not assigned an id!`);if(this._entities.delete(A.id),!A.isEnvironmental)this._activeEntities.delete(A)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let A=[];return this._entities.forEach((Q)=>{if(Q instanceof i1)A.push(Q)}),A}getPlayerEntitiesByPlayer(A){let Q=[];return this._entities.forEach((B)=>{if(B instanceof i1&&B.player===A)Q.push(B)}),Q}getEntity(A){return this._entities.get(A)}getEntitiesByTag(A){let Q=[];return this._entities.forEach((B)=>{if(B.tag===A)Q.push(B)}),Q}getEntitiesByTagSubstring(A){let Q=[];return this._entities.forEach((B)=>{if(B.tag?.includes(A))Q.push(B)}),Q}getEntityChildren(A){let Q=[];return this._entities.forEach((B)=>{if(B.parent===A)Q.push(B)}),Q}tickEntities(A){for(let Q of this._activeEntities)Q.tick(A)}checkAndEmitUpdates(){for(let A of this._activeEntities)A.checkAndEmitUpdates()}}import{gzipSync as Pf0}from"zlib";var B9=LA(kIA(),1),UDY=B9.default.v1,KDY=B9.default.v1ToV6,VDY=B9.default.v3,_IA=B9.default.v4,IDY=B9.default.v5,HDY=B9.default.v6,DDY=B9.default.v6ToV1,NDY=B9.default.v7,MDY=B9.default.NIL,LDY=B9.default.MAX,qDY=B9.default.version,zDY=B9.default.validate,RDY=B9.default.stringify,wDY=B9.default.parse;var Im;try{Im=new TextDecoder}catch(A){}var _A,zC,o=0;var Mm=[],$E=Mm,vD=0,tB={},DB,bG,qC=0,D8=0,PY,mG,g9=[],$B,vIA={useRecords:!1,mapsAsObjects:!0};class ww{}var Lm=new ww;Lm.name="MessagePack 0xC1";var b7=!1,uIA=2,Hm,Dm,Nm;try{Function("")}catch(A){uIA=1/0}class uG{constructor(A){if(A){if(A.useRecords===!1&&A.mapsAsObjects===void 0)A.mapsAsObjects=!0;if(A.sequential&&A.trusted!==!1){if(A.trusted=!0,!A.structures&&A.useRecords!=!1){if(A.structures=[],!A.maxSharedStructures)A.maxSharedStructures=0}}if(A.structures)A.structures.sharedLength=A.structures.length;else if(A.getStructures)(A.structures=[]).uninitialized=!0,A.structures.sharedLength=0;if(A.int64AsNumber)A.int64AsType="number"}Object.assign(this,A)}unpack(A,Q){if(_A)return oIA(()=>{return Rw(),this?this.unpack(A,Q):uG.prototype.unpack.call(vIA,A,Q)});if(!A.buffer&&A.constructor===ArrayBuffer)A=typeof Buffer<"u"?Buffer.from(A):new Uint8Array(A);if(typeof Q==="object")zC=Q.end||A.length,o=Q.start||0;else o=0,zC=Q>-1?Q:A.length;vD=0,D8=0,bG=null,$E=Mm,PY=null,_A=A;try{$B=A.dataView||(A.dataView=new DataView(A.buffer,A.byteOffset,A.byteLength))}catch(B){if(_A=null,A instanceof Uint8Array)throw B;throw Error("Source must be a Uint8Array or Buffer but was a "+(A&&typeof A=="object"?A.constructor.name:typeof A))}if(this instanceof uG){if(tB=this,this.structures)return DB=this.structures,qw(Q);else if(!DB||DB.length>0)DB=[]}else if(tB=vIA,!DB||DB.length>0)DB=[];return qw(Q)}unpackMultiple(A,Q){let B,Y=0;try{b7=!0;let J=A.length,C=this?this.unpack(A,J):Ow.unpack(A,J);if(Q){if(Q(C,Y,o)===!1)return;while(o<J)if(Y=o,Q(qw(),Y,o)===!1)return}else{B=[C];while(o<J)Y=o,B.push(qw());return B}}catch(J){throw J.lastPosition=Y,J.values=B,J}finally{b7=!1,Rw()}}_mergeStructures(A,Q){if(Dm)A=Dm.call(this,A);if(A=A||[],Object.isFrozen(A))A=A.map((B)=>B.slice(0));for(let B=0,Y=A.length;B<Y;B++){let J=A[B];if(J){if(J.isShared=!0,B>=32)J.highByte=B-32>>5}}A.sharedLength=A.length;for(let B in Q||[])if(B>=0){let Y=A[B],J=Q[B];if(J){if(Y)(A.restoreStructures||(A.restoreStructures=[]))[B]=Y;A[B]=J}}return this.structures=A}decode(A,Q){return this.unpack(A,Q)}}function qw(A){try{if(!tB.trusted&&!b7){let B=DB.sharedLength||0;if(B<DB.length)DB.length=B}let Q;if(tB.randomAccessStructure&&_A[o]<64&&_A[o]>=32&&Hm){if(Q=Hm(_A,o,zC,tB),_A=null,!(A&&A.lazy)&&Q)Q=Q.toJSON();o=zC}else Q=XY();if(PY)o=PY.postBundlePosition,PY=null;if(b7)DB.restoreStructures=null;if(o==zC){if(DB&&DB.restoreStructures)yIA();if(DB=null,_A=null,mG)mG=null}else if(o>zC)throw Error("Unexpected end of MessagePack data");else if(!b7){let B;try{B=JSON.stringify(Q,(Y,J)=>typeof J==="bigint"?`${J}n`:J).slice(0,100)}catch(Y){B="(JSON view not available "+Y+")"}throw Error("Data read, but end of buffer not reached "+B)}return Q}catch(Q){if(DB&&DB.restoreStructures)yIA();if(Rw(),Q instanceof RangeError||Q.message.startsWith("Unexpected end of buffer")||o>zC)Q.incomplete=!0;throw Q}}function yIA(){for(let A in DB.restoreStructures)DB[A]=DB.restoreStructures[A];DB.restoreStructures=null}function XY(){let A=_A[o++];if(A<160)if(A<128)if(A<64)return A;else{let Q=DB[A&63]||tB.getStructures&&dIA()[A&63];if(Q){if(!Q.read)Q.read=qm(Q,A&63);return Q.read()}else return A}else if(A<144)if(A-=128,tB.mapsAsObjects){let Q={};for(let B=0;B<A;B++){let Y=aIA();if(Y==="__proto__")Y="__proto_";Q[Y]=XY()}return Q}else{let Q=new Map;for(let B=0;B<A;B++)Q.set(XY(),XY());return Q}else{A-=144;let Q=Array(A);for(let B=0;B<A;B++)Q[B]=XY();if(tB.freezeData)return Object.freeze(Q);return Q}else if(A<192){let Q=A-160;if(D8>=o)return bG.slice(o-qC,(o+=Q)-qC);if(D8==0&&zC<140){let B=Q<16?zm(Q):sIA(Q);if(B!=null)return B}return zw(Q)}else{let Q;switch(A){case 192:return null;case 193:if(PY)if(Q=XY(),Q>0)return PY[1].slice(PY.position1,PY.position1+=Q);else return PY[0].slice(PY.position0,PY.position0-=Q);return Lm;case 194:return!1;case 195:return!0;case 196:if(Q=_A[o++],Q===void 0)throw Error("Unexpected end of buffer");return Vm(Q);case 197:return Q=$B.getUint16(o),o+=2,Vm(Q);case 198:return Q=$B.getUint32(o),o+=4,Vm(Q);case 199:return ZE(_A[o++]);case 200:return Q=$B.getUint16(o),o+=2,ZE(Q);case 201:return Q=$B.getUint32(o),o+=4,ZE(Q);case 202:if(Q=$B.getFloat32(o),tB.useFloat32>2){let B=KE[(_A[o]&127)<<1|_A[o+1]>>7];return o+=4,(B*Q+(Q>0?0.5:-0.5)>>0)/B}return o+=4,Q;case 203:return Q=$B.getFloat64(o),o+=8,Q;case 204:return _A[o++];case 205:return Q=$B.getUint16(o),o+=2,Q;case 206:return Q=$B.getUint32(o),o+=4,Q;case 207:if(tB.int64AsType==="number")Q=$B.getUint32(o)*4294967296,Q+=$B.getUint32(o+4);else if(tB.int64AsType==="string")Q=$B.getBigUint64(o).toString();else if(tB.int64AsType==="auto"){if(Q=$B.getBigUint64(o),Q<=BigInt(2)<<BigInt(52))Q=Number(Q)}else Q=$B.getBigUint64(o);return o+=8,Q;case 208:return $B.getInt8(o++);case 209:return Q=$B.getInt16(o),o+=2,Q;case 210:return Q=$B.getInt32(o),o+=4,Q;case 211:if(tB.int64AsType==="number")Q=$B.getInt32(o)*4294967296,Q+=$B.getUint32(o+4);else if(tB.int64AsType==="string")Q=$B.getBigInt64(o).toString();else if(tB.int64AsType==="auto"){if(Q=$B.getBigInt64(o),Q>=BigInt(-2)<<BigInt(52)&&Q<=BigInt(2)<<BigInt(52))Q=Number(Q)}else Q=$B.getBigInt64(o);return o+=8,Q;case 212:if(Q=_A[o++],Q==114)return mIA(_A[o++]&63);else{let B=g9[Q];if(B)if(B.read)return o++,B.read(XY());else if(B.noBuffer)return o++,B();else return B(_A.subarray(o,++o));else throw Error("Unknown extension "+Q)}case 213:if(Q=_A[o],Q==114)return o++,mIA(_A[o++]&63,_A[o++]);else return ZE(2);case 214:return ZE(4);case 215:return ZE(8);case 216:return ZE(16);case 217:if(Q=_A[o++],D8>=o)return bG.slice(o-qC,(o+=Q)-qC);return lIA(Q);case 218:if(Q=$B.getUint16(o),o+=2,D8>=o)return bG.slice(o-qC,(o+=Q)-qC);return cIA(Q);case 219:if(Q=$B.getUint32(o),o+=4,D8>=o)return bG.slice(o-qC,(o+=Q)-qC);return pIA(Q);case 220:return Q=$B.getUint16(o),o+=2,hIA(Q);case 221:return Q=$B.getUint32(o),o+=4,hIA(Q);case 222:return Q=$B.getUint16(o),o+=2,xIA(Q);case 223:return Q=$B.getUint32(o),o+=4,xIA(Q);default:if(A>=224)return A-256;if(A===void 0){let B=Error("Unexpected end of MessagePack data");throw B.incomplete=!0,B}throw Error("Unknown MessagePack token "+A)}}}var rFB=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function qm(A,Q){function B(){if(B.count++>uIA){let J=A.read=Function("r","return function(){return "+(tB.freezeData?"Object.freeze":"")+"({"+A.map((C)=>C==="__proto__"?"__proto_:r()":rFB.test(C)?C+":r()":"["+JSON.stringify(C)+"]:r()").join(",")+"})}")(XY);if(A.highByte===0)A.read=gIA(Q,A.read);return J()}let Y={};for(let J=0,C=A.length;J<C;J++){let X=A[J];if(X==="__proto__")X="__proto_";Y[X]=XY()}if(tB.freezeData)return Object.freeze(Y);return Y}if(B.count=0,A.highByte===0)return gIA(Q,B);return B}var gIA=(A,Q)=>{return function(){let B=_A[o++];if(B===0)return Q();let Y=A<32?-(A+(B<<5)):A+(B<<5),J=DB[Y]||dIA()[Y];if(!J)throw Error("Record id is not defined for "+Y);if(!J.read)J.read=qm(J,A);return J.read()}};function dIA(){let A=oIA(()=>{return _A=null,tB.getStructures()});return DB=tB._mergeStructures(A,DB)}var zw=UE,lIA=UE,cIA=UE,pIA=UE,jw=!1;function iIA(A){jw=!0,zw=Q(1),lIA=Q(2),cIA=Q(3),pIA=Q(5);function Q(B){return function(J){let C=$E[vD++];if(C==null){if(PY)return UE(J);let G=_A.byteOffset,F=A(o-B+G,zC+G,_A.buffer);if(typeof F=="string")C=F,$E=Mm;else if($E=F,vD=1,D8=1,C=$E[0],C===void 0)throw Error("Unexpected end of buffer")}let X=C.length;if(X<=J)return o+=J,C;return bG=C,qC=o,D8=o+X,o+=J,C.slice(0,J)}}}function UE(A){let Q;if(A<16){if(Q=zm(A))return Q}if(A>64&&Im)return Im.decode(_A.subarray(o,o+=A));let B=o+A,Y=[];Q="";while(o<B){let J=_A[o++];if((J&128)===0)Y.push(J);else if((J&224)===192){let C=_A[o++]&63;Y.push((J&31)<<6|C)}else if((J&240)===224){let C=_A[o++]&63,X=_A[o++]&63;Y.push((J&31)<<12|C<<6|X)}else if((J&248)===240){let C=_A[o++]&63,X=_A[o++]&63,G=_A[o++]&63,F=(J&7)<<18|C<<12|X<<6|G;if(F>65535)F-=65536,Y.push(F>>>10&1023|55296),F=56320|F&1023;Y.push(F)}else Y.push(J);if(Y.length>=4096)Q+=mY.apply(String,Y),Y.length=0}if(Y.length>0)Q+=mY.apply(String,Y);return Q}function nIA(A,Q,B){let Y=_A;_A=A,o=Q;try{return UE(B)}finally{_A=Y}}function hIA(A){let Q=Array(A);for(let B=0;B<A;B++)Q[B]=XY();if(tB.freezeData)return Object.freeze(Q);return Q}function xIA(A){if(tB.mapsAsObjects){let Q={};for(let B=0;B<A;B++){let Y=aIA();if(Y==="__proto__")Y="__proto_";Q[Y]=XY()}return Q}else{let Q=new Map;for(let B=0;B<A;B++)Q.set(XY(),XY());return Q}}var mY=String.fromCharCode;function sIA(A){let Q=o,B=Array(A);for(let Y=0;Y<A;Y++){let J=_A[o++];if((J&128)>0){o=Q;return}B[Y]=J}return mY.apply(String,B)}function zm(A){if(A<4)if(A<2)if(A===0)return"";else{let Q=_A[o++];if((Q&128)>1){o-=1;return}return mY(Q)}else{let Q=_A[o++],B=_A[o++];if((Q&128)>0||(B&128)>0){o-=2;return}if(A<3)return mY(Q,B);let Y=_A[o++];if((Y&128)>0){o-=3;return}return mY(Q,B,Y)}else{let Q=_A[o++],B=_A[o++],Y=_A[o++],J=_A[o++];if((Q&128)>0||(B&128)>0||(Y&128)>0||(J&128)>0){o-=4;return}if(A<6)if(A===4)return mY(Q,B,Y,J);else{let C=_A[o++];if((C&128)>0){o-=5;return}return mY(Q,B,Y,J,C)}else if(A<8){let C=_A[o++],X=_A[o++];if((C&128)>0||(X&128)>0){o-=6;return}if(A<7)return mY(Q,B,Y,J,C,X);let G=_A[o++];if((G&128)>0){o-=7;return}return mY(Q,B,Y,J,C,X,G)}else{let C=_A[o++],X=_A[o++],G=_A[o++],F=_A[o++];if((C&128)>0||(X&128)>0||(G&128)>0||(F&128)>0){o-=8;return}if(A<10)if(A===8)return mY(Q,B,Y,J,C,X,G,F);else{let W=_A[o++];if((W&128)>0){o-=9;return}return mY(Q,B,Y,J,C,X,G,F,W)}else if(A<12){let W=_A[o++],E=_A[o++];if((W&128)>0||(E&128)>0){o-=10;return}if(A<11)return mY(Q,B,Y,J,C,X,G,F,W,E);let $=_A[o++];if(($&128)>0){o-=11;return}return mY(Q,B,Y,J,C,X,G,F,W,E,$)}else{let W=_A[o++],E=_A[o++],$=_A[o++],Z=_A[o++];if((W&128)>0||(E&128)>0||($&128)>0||(Z&128)>0){o-=12;return}if(A<14)if(A===12)return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z);else{let U=_A[o++];if((U&128)>0){o-=13;return}return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z,U)}else{let U=_A[o++],K=_A[o++];if((U&128)>0||(K&128)>0){o-=14;return}if(A<15)return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K);let I=_A[o++];if((I&128)>0){o-=15;return}return mY(Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K,I)}}}}}function fIA(){let A=_A[o++],Q;if(A<192)Q=A-160;else switch(A){case 217:Q=_A[o++];break;case 218:Q=$B.getUint16(o),o+=2;break;case 219:Q=$B.getUint32(o),o+=4;break;default:throw Error("Expected string")}return UE(Q)}function Vm(A){return tB.copyBuffers?Uint8Array.prototype.slice.call(_A,o,o+=A):_A.subarray(o,o+=A)}function ZE(A){let Q=_A[o++];if(g9[Q]){let B;return g9[Q](_A.subarray(o,B=o+=A),(Y)=>{o=Y;try{return XY()}finally{o=B}})}else throw Error("Unknown extension type "+Q)}var bIA=Array(4096);function aIA(){let A=_A[o++];if(A>=160&&A<192){if(A=A-160,D8>=o)return bG.slice(o-qC,(o+=A)-qC);else if(!(D8==0&&zC<180))return zw(A)}else return o--,rIA(XY());let Q=(A<<5^(A>1?$B.getUint16(o):A>0?_A[o]:0))&4095,B=bIA[Q],Y=o,J=o+A-3,C,X=0;if(B&&B.bytes==A){while(Y<J){if(C=$B.getUint32(Y),C!=B[X++]){Y=1879048192;break}Y+=4}J+=3;while(Y<J)if(C=_A[Y++],C!=B[X++]){Y=1879048192;break}if(Y===J)return o=Y,B.string;J-=3,Y=o}B=[],bIA[Q]=B,B.bytes=A;while(Y<J)C=$B.getUint32(Y),B.push(C),Y+=4;J+=3;while(Y<J)C=_A[Y++],B.push(C);let G=A<16?zm(A):sIA(A);if(G!=null)return B.string=G;return B.string=zw(A)}function rIA(A){if(typeof A==="string")return A;if(typeof A==="number"||typeof A==="boolean"||typeof A==="bigint")return A.toString();if(A==null)return A+"";if(tB.allowArraysInMapKeys&&Array.isArray(A)&&A.flat().every((Q)=>["string","number","boolean","bigint"].includes(typeof Q)))return A.flat().toString();throw Error(`Invalid property type for record: ${typeof A}`)}var mIA=(A,Q)=>{let B=XY().map(rIA),Y=A;if(Q!==void 0)A=A<32?-((Q<<5)+A):(Q<<5)+A,B.highByte=Q;let J=DB[A];if(J&&(J.isShared||b7))(DB.restoreStructures||(DB.restoreStructures=[]))[A]=J;return DB[A]=B,B.read=qm(B,Y),B.read()};g9[0]=()=>{};g9[0].noBuffer=!0;g9[66]=(A)=>{let Q=A.length,B=BigInt(A[0]&128?A[0]-256:A[0]);for(let Y=1;Y<Q;Y++)B<<=BigInt(8),B+=BigInt(A[Y]);return B};var oFB={Error,TypeError,ReferenceError};g9[101]=()=>{let A=XY();return(oFB[A[0]]||Error)(A[1],{cause:A[2]})};g9[105]=(A)=>{if(tB.structuredClone===!1)throw Error("Structured clone extension is disabled");let Q=$B.getUint32(o-4);if(!mG)mG=new Map;let B=_A[o],Y;if(B>=144&&B<160||B==220||B==221)Y=[];else if(B>=128&&B<144||B==222||B==223)Y=new Map;else if((B>=199&&B<=201||B>=212&&B<=216)&&_A[o+1]===115)Y=new Set;else Y={};let J={target:Y};mG.set(Q,J);let C=XY();if(!J.used)return J.target=C;else Object.assign(Y,C);if(Y instanceof Map)for(let[X,G]of C.entries())Y.set(X,G);if(Y instanceof Set)for(let X of Array.from(C))Y.add(X);return Y};g9[112]=(A)=>{if(tB.structuredClone===!1)throw Error("Structured clone extension is disabled");let Q=$B.getUint32(o-4),B=mG.get(Q);return B.used=!0,B.target};g9[115]=()=>new Set(XY());var Rm=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((A)=>A+"Array"),tFB=typeof globalThis==="object"?globalThis:window;g9[116]=(A)=>{let Q=A[0],B=Uint8Array.prototype.slice.call(A,1).buffer,Y=Rm[Q];if(!Y){if(Q===16)return B;if(Q===17)return new DataView(B);throw Error("Could not find typed array for code "+Q)}return new tFB[Y](B)};g9[120]=()=>{let A=XY();return new RegExp(A[0],A[1])};var eFB=[];g9[98]=(A)=>{let Q=(A[0]<<24)+(A[1]<<16)+(A[2]<<8)+A[3],B=o;return o+=Q-A.length,PY=eFB,PY=[fIA(),fIA()],PY.position0=0,PY.position1=0,PY.postBundlePosition=o,o=B,XY()};g9[255]=(A)=>{if(A.length==4)return new Date((A[0]*16777216+(A[1]<<16)+(A[2]<<8)+A[3])*1000);else if(A.length==8)return new Date(((A[0]<<22)+(A[1]<<14)+(A[2]<<6)+(A[3]>>2))/1e6+((A[3]&3)*4294967296+A[4]*16777216+(A[5]<<16)+(A[6]<<8)+A[7])*1000);else if(A.length==12)return new Date(((A[0]<<24)+(A[1]<<16)+(A[2]<<8)+A[3])/1e6+((A[4]&128?-281474976710656:0)+A[6]*1099511627776+A[7]*4294967296+A[8]*16777216+(A[9]<<16)+(A[10]<<8)+A[11])*1000);else return new Date("invalid")};function oIA(A){if(Nm)Nm();let Q=zC,B=o,Y=vD,J=qC,C=D8,X=bG,G=$E,F=mG,W=PY,E=new Uint8Array(_A.slice(0,zC)),$=DB,Z=DB.slice(0,DB.length),U=tB,K=b7,I=A();return zC=Q,o=B,vD=Y,qC=J,D8=C,bG=X,$E=G,mG=F,PY=W,_A=E,b7=K,DB=$,DB.splice(0,DB.length,...Z),tB=U,$B=new DataView(_A.buffer,_A.byteOffset,_A.byteLength),I}function Rw(){_A=null,mG=null,DB=null}var KE=Array(147);for(let A=0;A<256;A++)KE[A]=+("1e"+Math.floor(45.15-A*0.30103));var Ow=new uG({useRecords:!1}),AWB=Ow.unpack,QWB=Ow.unpackMultiple,BWB=Ow.unpack,yD={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},YWB=new Float32Array(1),ODY=new Uint8Array(YWB.buffer,0,4);function tIA(A,Q,B){Hm=A,Dm=Q,Nm=B}var Tw;try{Tw=new TextEncoder}catch(A){}var Om,QHA,hD=typeof Buffer<"u",Pw=hD?function(A){return Buffer.allocUnsafeSlow(A)}:Uint8Array,BHA=hD?Buffer:Uint8Array,eIA=hD?4294967296:2144337920,ZA,gD,C0,BA=0,Y9,_0=null,YHA,JWB=21760,CWB=/[\u0080-\uFFFF]/,n1=Symbol("record-id");class VE extends uG{constructor(A){super(A);this.offset=0;let Q,B,Y,J,C,X=BHA.prototype.utf8Write?function(T,S){return ZA.utf8Write(T,S,ZA.byteLength-S)}:Tw&&Tw.encodeInto?function(T,S){return Tw.encodeInto(T,ZA.subarray(S)).written}:!1,G=this;if(!A)A={};let F=A&&A.sequential,W=A.structures||A.saveStructures,E=A.maxSharedStructures;if(E==null)E=W?32:0;if(E>8160)throw Error("Maximum maxSharedStructure is 8160");if(A.structuredClone&&A.moreTypes==null)this.moreTypes=!0;let $=A.maxOwnStructures;if($==null)$=W?32:64;if(!this.structures&&A.useRecords!=!1)this.structures=[];let Z=E>32||$+E>64,U=E+64,K=E+$+64;if(K>8256)throw Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let I=[],V=0,H=0;this.pack=this.encode=function(T,S){if(!ZA)ZA=new Pw(8192),C0=ZA.dataView||(ZA.dataView=new DataView(ZA.buffer,0,8192)),BA=0;if(Y9=ZA.length-10,Y9-BA<2048)ZA=new Pw(ZA.length),C0=ZA.dataView||(ZA.dataView=new DataView(ZA.buffer,0,ZA.length)),Y9=ZA.length-10,BA=0;else BA=BA+7&2147483640;if(B=BA,S&$WB)BA+=S&255;if(C=G.structuredClone?new Map:null,G.bundleStrings&&typeof T!=="string")_0=[],_0.size=1/0;else _0=null;if(J=G.structures,J){if(J.uninitialized)J=G._mergeStructures(G.getStructures());let v=J.sharedLength||0;if(v>E)throw Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+J.sharedLength);if(!J.transitions){J.transitions=Object.create(null);for(let h=0;h<v;h++){let g=J[h];if(!g)continue;let m,p=J.transitions;for(let c=0,AA=g.length;c<AA;c++){let d=g[c];if(m=p[d],!m)m=p[d]=Object.create(null);p=m}p[n1]=h+64}this.lastNamedStructuresLength=v}if(!F)J.nextId=v+64}if(Y)Y=!1;let y;try{if(G.randomAccessStructure&&T&&T.constructor&&T.constructor===Object)k(T);else z(T);let v=_0;if(_0)AHA(B,z,0);if(C&&C.idsToInsert){let h=C.idsToInsert.sort((c,AA)=>c.offset>AA.offset?1:-1),g=h.length,m=-1;while(v&&g>0){let c=h[--g].offset+B;if(c<v.stringsPosition+B&&m===-1)m=0;if(c>v.position+B){if(m>=0)m+=6}else{if(m>=0)C0.setUint32(v.position+B,C0.getUint32(v.position+B)+m),m=-1;v=v.previous,g++}}if(m>=0&&v)C0.setUint32(v.position+B,C0.getUint32(v.position+B)+m);if(BA+=h.length*6,BA>Y9)P(BA);G.offset=BA;let p=GWB(ZA.subarray(B,BA),h);return C=null,p}if(G.offset=BA,S&EWB)return ZA.start=B,ZA.end=BA,ZA;return ZA.subarray(B,BA)}catch(v){throw y=v,v}finally{if(J){if(D(),Y&&G.saveStructures){let v=J.sharedLength||0,h=ZA.subarray(B,BA),g=JHA(J,G);if(!y){if(G.saveStructures(g,g.isCompatible)===!1)return G.pack(T,S);if(G.lastNamedStructuresLength=v,ZA.length>1073741824)ZA=null;return h}}}if(ZA.length>1073741824)ZA=null;if(S&ZWB)BA=B}};let D=()=>{if(H<10)H++;let T=J.sharedLength||0;if(J.length>T&&!F)J.length=T;if(V>1e4){if(J.transitions=null,H=0,V=0,I.length>0)I=[]}else if(I.length>0&&!F){for(let S=0,y=I.length;S<y;S++)I[S][n1]=0;I=[]}},M=(T)=>{var S=T.length;if(S<16)ZA[BA++]=144|S;else if(S<65536)ZA[BA++]=220,ZA[BA++]=S>>8,ZA[BA++]=S&255;else ZA[BA++]=221,C0.setUint32(BA,S),BA+=4;for(let y=0;y<S;y++)z(T[y])},z=(T)=>{if(BA>Y9)ZA=P(BA);var S=typeof T,y;if(S==="string"){let v=T.length;if(_0&&v>=4&&v<4096){if((_0.size+=v)>JWB){let p,c=(_0[0]?_0[0].length*3+_0[1].length:0)+10;if(BA+c>Y9)ZA=P(BA+c);let AA;if(_0.position)AA=_0,ZA[BA]=200,BA+=3,ZA[BA++]=98,p=BA-B,BA+=4,AHA(B,z,0),C0.setUint16(p+B-3,BA-B-p);else ZA[BA++]=214,ZA[BA++]=98,p=BA-B,BA+=4;_0=["",""],_0.previous=AA,_0.size=0,_0.position=p}let m=CWB.test(T);_0[m?0:1]+=T,ZA[BA++]=193,z(m?-v:v);return}let h;if(v<32)h=1;else if(v<256)h=2;else if(v<65536)h=3;else h=5;let g=v*3;if(BA+g>Y9)ZA=P(BA+g);if(v<64||!X){let m,p,c,AA=BA+h;for(m=0;m<v;m++)if(p=T.charCodeAt(m),p<128)ZA[AA++]=p;else if(p<2048)ZA[AA++]=p>>6|192,ZA[AA++]=p&63|128;else if((p&64512)===55296&&((c=T.charCodeAt(m+1))&64512)===56320)p=65536+((p&1023)<<10)+(c&1023),m++,ZA[AA++]=p>>18|240,ZA[AA++]=p>>12&63|128,ZA[AA++]=p>>6&63|128,ZA[AA++]=p&63|128;else ZA[AA++]=p>>12|224,ZA[AA++]=p>>6&63|128,ZA[AA++]=p&63|128;y=AA-BA-h}else y=X(T,BA+h);if(y<32)ZA[BA++]=160|y;else if(y<256){if(h<2)ZA.copyWithin(BA+2,BA+1,BA+1+y);ZA[BA++]=217,ZA[BA++]=y}else if(y<65536){if(h<3)ZA.copyWithin(BA+3,BA+2,BA+2+y);ZA[BA++]=218,ZA[BA++]=y>>8,ZA[BA++]=y&255}else{if(h<5)ZA.copyWithin(BA+5,BA+3,BA+3+y);ZA[BA++]=219,C0.setUint32(BA,y),BA+=4}BA+=y}else if(S==="number")if(T>>>0===T)if(T<32||T<128&&this.useRecords===!1||T<64&&!this.randomAccessStructure)ZA[BA++]=T;else if(T<256)ZA[BA++]=204,ZA[BA++]=T;else if(T<65536)ZA[BA++]=205,ZA[BA++]=T>>8,ZA[BA++]=T&255;else ZA[BA++]=206,C0.setUint32(BA,T),BA+=4;else if(T>>0===T)if(T>=-32)ZA[BA++]=256+T;else if(T>=-128)ZA[BA++]=208,ZA[BA++]=T+256;else if(T>=-32768)ZA[BA++]=209,C0.setInt16(BA,T),BA+=2;else ZA[BA++]=210,C0.setInt32(BA,T),BA+=4;else{let v;if((v=this.useFloat32)>0&&T<4294967296&&T>=-2147483648){ZA[BA++]=202,C0.setFloat32(BA,T);let h;if(v<4||(h=T*KE[(ZA[BA]&127)<<1|ZA[BA+1]>>7])>>0===h){BA+=4;return}else BA--}ZA[BA++]=203,C0.setFloat64(BA,T),BA+=8}else if(S==="object"||S==="function")if(!T)ZA[BA++]=192;else{if(C){let h=C.get(T);if(h){if(!h.id){let g=C.idsToInsert||(C.idsToInsert=[]);h.id=g.push(h)}ZA[BA++]=214,ZA[BA++]=112,C0.setUint32(BA,h.id),BA+=4;return}else C.set(T,{offset:BA-B})}let v=T.constructor;if(v===Object)w(T);else if(v===Array)M(T);else if(v===Map)if(this.mapAsEmptyObject)ZA[BA++]=128;else{if(y=T.size,y<16)ZA[BA++]=128|y;else if(y<65536)ZA[BA++]=222,ZA[BA++]=y>>8,ZA[BA++]=y&255;else ZA[BA++]=223,C0.setUint32(BA,y),BA+=4;for(let[h,g]of T)z(h),z(g)}else{for(let h=0,g=Om.length;h<g;h++){let m=QHA[h];if(T instanceof m){let p=Om[h];if(p.write){if(p.type)ZA[BA++]=212,ZA[BA++]=p.type,ZA[BA++]=0;let b=p.write.call(this,T);if(b===T)if(Array.isArray(T))M(T);else w(T);else z(b);return}let c=ZA,AA=C0,d=BA;ZA=null;let x;try{x=p.pack.call(this,T,(b)=>{if(ZA=c,c=null,BA+=b,BA>Y9)P(BA);return{target:ZA,targetView:C0,position:BA-b}},z)}finally{if(c)ZA=c,C0=AA,BA=d,Y9=ZA.length-10}if(x){if(x.length+BA>Y9)P(x.length+BA);BA=XWB(x,ZA,BA,p.type)}return}}if(Array.isArray(T))M(T);else{if(T.toJSON){let h=T.toJSON();if(h!==T)return z(h)}if(S==="function")return z(this.writeFunction&&this.writeFunction(T));w(T)}}}else if(S==="boolean")ZA[BA++]=T?195:194;else if(S==="bigint"){if(T<9223372036854776000&&T>=-9223372036854776000)ZA[BA++]=211,C0.setBigInt64(BA,T);else if(T<18446744073709552000&&T>0)ZA[BA++]=207,C0.setBigUint64(BA,T);else if(this.largeBigIntToFloat)ZA[BA++]=203,C0.setFloat64(BA,Number(T));else if(this.largeBigIntToString)return z(T.toString());else if((this.useBigIntExtension||this.moreTypes)&&T<BigInt(2)**BigInt(1023)&&T>-(BigInt(2)**BigInt(1023))){ZA[BA++]=199,BA++,ZA[BA++]=66;let v=[],h;do{let g=T&BigInt(255);h=(g&BigInt(128))===(T<BigInt(0)?BigInt(128):BigInt(0)),v.push(g),T>>=BigInt(8)}while(!((T===BigInt(0)||T===BigInt(-1))&&h));ZA[BA-2]=v.length;for(let g=v.length;g>0;)ZA[BA++]=Number(v[--g]);return}else throw RangeError(T+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");BA+=8}else if(S==="undefined")if(this.encodeUndefinedAsNil)ZA[BA++]=192;else ZA[BA++]=212,ZA[BA++]=0,ZA[BA++]=0;else throw Error("Unknown type: "+S)},q=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(T)=>{let S;if(this.skipValues){S=[];for(let h in T)if((typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(h))&&!this.skipValues.includes(T[h]))S.push(h)}else S=Object.keys(T);let y=S.length;if(y<16)ZA[BA++]=128|y;else if(y<65536)ZA[BA++]=222,ZA[BA++]=y>>8,ZA[BA++]=y&255;else ZA[BA++]=223,C0.setUint32(BA,y),BA+=4;let v;if(this.coercibleKeyAsNumber)for(let h=0;h<y;h++){v=S[h];let g=Number(v);z(isNaN(g)?v:g),z(T[v])}else for(let h=0;h<y;h++)z(v=S[h]),z(T[v])}:(T)=>{ZA[BA++]=222;let S=BA-B;BA+=2;let y=0;for(let v in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(v))z(v),z(T[v]),y++;if(y>65535)throw Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');ZA[S+++B]=y>>8,ZA[S+B]=y&255},N=this.useRecords===!1?q:A.progressiveRecords&&!Z?(T)=>{let S,y=J.transitions||(J.transitions=Object.create(null)),v=BA++-B,h;for(let g in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(g)){if(S=y[g],S)y=S;else{let m=Object.keys(T),p=y;y=J.transitions;let c=0;for(let AA=0,d=m.length;AA<d;AA++){let x=m[AA];if(S=y[x],!S)S=y[x]=Object.create(null),c++;y=S}if(v+B+1==BA)BA--,_(y,m,c);else O(y,m,v,c);h=!0,y=p[g]}z(T[g])}if(!h){let g=y[n1];if(g)ZA[v+B]=g;else O(y,Object.keys(T),v,0)}}:(T)=>{let S,y=J.transitions||(J.transitions=Object.create(null)),v=0;for(let g in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(g)){if(S=y[g],!S)S=y[g]=Object.create(null),v++;y=S}let h=y[n1];if(h)if(h>=96&&Z)ZA[BA++]=((h-=96)&31)+96,ZA[BA++]=h>>5;else ZA[BA++]=h;else _(y,y.__keys__||Object.keys(T),v);for(let g in T)if(typeof T.hasOwnProperty!=="function"||T.hasOwnProperty(g))z(T[g])},L=typeof this.useRecords=="function"&&this.useRecords,w=L?(T)=>{L(T)?N(T):q(T)}:N,P=(T)=>{let S;if(T>16777216){if(T-B>eIA)throw Error("Packed buffer would be larger than maximum buffer size");S=Math.min(eIA,Math.round(Math.max((T-B)*(T>67108864?1.25:2),4194304)/4096)*4096)}else S=(Math.max(T-B<<2,ZA.length-1)>>12)+1<<12;let y=new Pw(S);if(C0=y.dataView||(y.dataView=new DataView(y.buffer,0,S)),T=Math.min(T,ZA.length),ZA.copy)ZA.copy(y,0,B,T);else y.set(ZA.slice(B,T));return BA-=B,B=0,Y9=y.length-10,ZA=y},_=(T,S,y)=>{let v=J.nextId;if(!v)v=64;if(v<U&&this.shouldShareStructure&&!this.shouldShareStructure(S)){if(v=J.nextOwnId,!(v<K))v=U;J.nextOwnId=v+1}else{if(v>=K)v=U;J.nextId=v+1}let h=S.highByte=v>=96&&Z?v-96>>5:-1;if(T[n1]=v,T.__keys__=S,J[v-64]=S,v<U)if(S.isShared=!0,J.sharedLength=v-63,Y=!0,h>=0)ZA[BA++]=(v&31)+96,ZA[BA++]=h;else ZA[BA++]=v;else{if(h>=0)ZA[BA++]=213,ZA[BA++]=114,ZA[BA++]=(v&31)+96,ZA[BA++]=h;else ZA[BA++]=212,ZA[BA++]=114,ZA[BA++]=v;if(y)V+=H*y;if(I.length>=$)I.shift()[n1]=0;I.push(T),z(S)}},O=(T,S,y,v)=>{let h=ZA,g=BA,m=Y9,p=B;if(ZA=gD,BA=0,B=0,!ZA)gD=ZA=new Pw(8192);Y9=ZA.length-10,_(T,S,v),gD=ZA;let c=BA;if(ZA=h,BA=g,Y9=m,B=p,c>1){let AA=BA+c-1;if(AA>Y9)P(AA);let d=y+B;ZA.copyWithin(d+c,d+1,BA),ZA.set(gD.slice(0,c),d),BA=AA}else ZA[y+B]=gD[0]},k=(T)=>{let S=YHA(T,ZA,B,BA,J,P,(y,v,h)=>{if(h)return Y=!0;BA=v;let g=ZA;if(z(y),D(),g!==ZA)return{position:BA,targetView:C0,target:ZA};return BA},this);if(S===0)return w(T);BA=S}}useBuffer(A){ZA=A,ZA.dataView||(ZA.dataView=new DataView(ZA.buffer,ZA.byteOffset,ZA.byteLength)),BA=0}set position(A){BA=A}get position(){return BA}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}QHA=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ww];Om=[{pack(A,Q,B){let Y=A.getTime()/1000;if((this.useTimestamp32||A.getMilliseconds()===0)&&Y>=0&&Y<4294967296){let{target:J,targetView:C,position:X}=Q(6);J[X++]=214,J[X++]=255,C.setUint32(X,Y)}else if(Y>0&&Y<4294967296){let{target:J,targetView:C,position:X}=Q(10);J[X++]=215,J[X++]=255,C.setUint32(X,A.getMilliseconds()*4000000+(Y/1000/4294967296>>0)),C.setUint32(X+4,Y)}else if(isNaN(Y)){if(this.onInvalidDate)return Q(0),B(this.onInvalidDate());let{target:J,targetView:C,position:X}=Q(3);J[X++]=212,J[X++]=255,J[X++]=255}else{let{target:J,targetView:C,position:X}=Q(15);J[X++]=199,J[X++]=12,J[X++]=255,C.setUint32(X,A.getMilliseconds()*1e6),C.setBigInt64(X+4,BigInt(Math.floor(Y)))}}},{pack(A,Q,B){if(this.setAsEmptyObject)return Q(0),B({});let Y=Array.from(A),{target:J,position:C}=Q(this.moreTypes?3:0);if(this.moreTypes)J[C++]=212,J[C++]=115,J[C++]=0;B(Y)}},{pack(A,Q,B){let{target:Y,position:J}=Q(this.moreTypes?3:0);if(this.moreTypes)Y[J++]=212,Y[J++]=101,Y[J++]=0;B([A.name,A.message,A.cause])}},{pack(A,Q,B){let{target:Y,position:J}=Q(this.moreTypes?3:0);if(this.moreTypes)Y[J++]=212,Y[J++]=120,Y[J++]=0;B([A.source,A.flags])}},{pack(A,Q){if(this.moreTypes)wm(A,16,Q);else jm(hD?Buffer.from(A):new Uint8Array(A),Q)}},{pack(A,Q){let B=A.constructor;if(B!==BHA&&this.moreTypes)wm(A,Rm.indexOf(B.name),Q);else jm(A,Q)}},{pack(A,Q){if(this.moreTypes)wm(A,17,Q);else jm(hD?Buffer.from(A):new Uint8Array(A),Q)}},{pack(A,Q){let{target:B,position:Y}=Q(1);B[Y]=193}}];function wm(A,Q,B,Y){let J=A.byteLength;if(J+1<256){var{target:C,position:X}=B(4+J);C[X++]=199,C[X++]=J+1}else if(J+1<65536){var{target:C,position:X}=B(5+J);C[X++]=200,C[X++]=J+1>>8,C[X++]=J+1&255}else{var{target:C,position:X,targetView:G}=B(7+J);C[X++]=201,G.setUint32(X,J+1),X+=4}if(C[X++]=116,C[X++]=Q,!A.buffer)A=new Uint8Array(A);C.set(new Uint8Array(A.buffer,A.byteOffset,A.byteLength),X)}function jm(A,Q){let B=A.byteLength;var Y,J;if(B<256){var{target:Y,position:J}=Q(B+2);Y[J++]=196,Y[J++]=B}else if(B<65536){var{target:Y,position:J}=Q(B+3);Y[J++]=197,Y[J++]=B>>8,Y[J++]=B&255}else{var{target:Y,position:J,targetView:C}=Q(B+5);Y[J++]=198,C.setUint32(J,B),J+=4}Y.set(A,J)}function XWB(A,Q,B,Y){let J=A.length;switch(J){case 1:Q[B++]=212;break;case 2:Q[B++]=213;break;case 4:Q[B++]=214;break;case 8:Q[B++]=215;break;case 16:Q[B++]=216;break;default:if(J<256)Q[B++]=199,Q[B++]=J;else if(J<65536)Q[B++]=200,Q[B++]=J>>8,Q[B++]=J&255;else Q[B++]=201,Q[B++]=J>>24,Q[B++]=J>>16&255,Q[B++]=J>>8&255,Q[B++]=J&255}return Q[B++]=Y,Q.set(A,B),B+=J,B}function GWB(A,Q){let B,Y=Q.length*6,J=A.length-Y;while(B=Q.pop()){let{offset:C,id:X}=B;A.copyWithin(C+Y,C,J),Y-=6;let G=C+Y;A[G++]=214,A[G++]=105,A[G++]=X>>24,A[G++]=X>>16&255,A[G++]=X>>8&255,A[G++]=X&255,J=C}return A}function AHA(A,Q,B){if(_0.length>0){C0.setUint32(_0.position+A,BA+B-_0.position-A),_0.stringsPosition=BA-A;let Y=_0;_0=null,Q(Y[0]),Q(Y[1])}}function JHA(A,Q){return A.isCompatible=(B)=>{let Y=!B||(Q.lastNamedStructuresLength||0)===B.length;if(!Y)Q._mergeStructures(B);return Y},A}function CHA(A,Q){YHA=A,JHA=Q}var XHA=new VE({useRecords:!1}),FWB=XHA.pack,WWB=XHA.pack;var EWB=512,ZWB=1024,$WB=2048;var Pm=3,UU=0,xD=2,Sw=1,Sm=16,FHA=["num","object","string","ascii"];FHA[Sm]="date";var KWB=[!1,!0,!0,!1,!1,!0,!0,!1],WHA;try{Function(""),WHA=!0}catch(A){}var IE,VWB=typeof Buffer<"u",kw,s1;try{kw=new TextEncoder}catch(A){}var IWB=VWB?function(A,Q,B){return A.utf8Write(Q,B,A.byteLength-B)}:kw&&kw.encodeInto?function(A,Q,B){return kw.encodeInto(Q,A.subarray(B)).written}:!1,hDY=Symbol("type"),xDY=Symbol("parent");CHA(EHA,LWB);function EHA(A,Q,B,Y,J,C,X,G){let F=G.typedStructs||(G.typedStructs=[]),W=Q.dataView,E=(F.lastStringStart||100)+Y,$=Q.length-10,Z=Y;if(Y>$)Q=C(Y),W=Q.dataView,Y-=B,Z-=B,E-=B,B=0,$=Q.length-10;let U,K=E,I=F.transitions||(F.transitions=Object.create(null)),V=F.nextId||F.length,H=V<15?1:V<240?2:V<61440?3:V<15728640?4:0;if(H===0)return 0;Y+=H;let D=[],M,z=0;for(let N in A){let L=A[N],w=I[N];if(!w)I[N]=w={key:N,parent:I,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if(Y>$)Q=C(Y),W=Q.dataView,Y-=B,Z-=B,E-=B,K-=B,B=0,$=Q.length-10;switch(typeof L){case"number":let P=L;if(V<200||!w.num64){if(P>>0===P&&P<536870912&&P>-520093696){if(P<246&&P>=0&&(w.num8&&!(V>200&&w.num32)||P<32&&!w.num32))I=w.num8||h9(w,UU,1),Q[Y++]=P;else I=w.num32||h9(w,UU,4),W.setUint32(Y,P,!0),Y+=4;break}else if(P<4294967296&&P>=-2147483648){if(W.setFloat32(Y,P,!0),KWB[Q[Y+3]>>>5]){let T;if((T=P*KE[(Q[Y+3]&127)<<1|Q[Y+2]>>7])>>0===T){I=w.num32||h9(w,UU,4),Y+=4;break}}}}I=w.num64||h9(w,UU,8),W.setFloat64(Y,P,!0),Y+=8;break;case"string":let _=L.length;if(U=K-E,(_<<2)+K>$)Q=C((_<<2)+K),W=Q.dataView,Y-=B,Z-=B,E-=B,K-=B,B=0,$=Q.length-10;if(_>65280+U>>2){D.push(N,L,Y-Z);break}let O,k=K;if(_<64){let T,S,y;for(T=0;T<_;T++)if(S=L.charCodeAt(T),S<128)Q[K++]=S;else if(S<2048)O=!0,Q[K++]=S>>6|192,Q[K++]=S&63|128;else if((S&64512)===55296&&((y=L.charCodeAt(T+1))&64512)===56320)O=!0,S=65536+((S&1023)<<10)+(y&1023),T++,Q[K++]=S>>18|240,Q[K++]=S>>12&63|128,Q[K++]=S>>6&63|128,Q[K++]=S&63|128;else O=!0,Q[K++]=S>>12|224,Q[K++]=S>>6&63|128,Q[K++]=S&63|128}else K+=IWB(Q,L,K),O=K-k>_;if(U<160||U<246&&(w.ascii8||w.string8)){if(O){if(!(I=w.string8))if(F.length>10&&(I=w.ascii8))I.__type=xD,w.ascii8=null,w.string8=I,X(null,0,!0);else I=h9(w,xD,1)}else if(U===0&&!M){M=!0,I=w.ascii0||h9(w,Pm,0);break}else if(!(I=w.ascii8)&&!(F.length>10&&(I=w.string8)))I=h9(w,Pm,1);Q[Y++]=U}else I=w.string16||h9(w,xD,2),W.setUint16(Y,U,!0),Y+=2;break;case"object":if(L){if(L.constructor===Date)I=w.date64||h9(w,Sm,8),W.setFloat64(Y,L.getTime(),!0),Y+=8;else D.push(N,L,z);break}else if(w=GHA(w,Y,W,-10),w)I=w,Y=IE;else D.push(N,L,z);break;case"boolean":I=w.num8||w.ascii8||h9(w,UU,1),Q[Y++]=L?249:248;break;case"undefined":if(w=GHA(w,Y,W,-9),w)I=w,Y=IE;else D.push(N,L,z);break;default:D.push(N,L,z)}z++}for(let N=0,L=D.length;N<L;){let w=D[N++],P=D[N++],_=D[N++],O=I[w];if(!O)I[w]=O={key:w,parent:I,enumerationOffset:_-z,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let k;if(P){let T;if(U=K-E,U<65280)if(I=O.object16,I)T=2;else if(I=O.object32)T=4;else I=h9(O,Sw,2),T=2;else I=O.object32||h9(O,Sw,4),T=4;if(k=X(P,K),typeof k==="object")K=k.position,W=k.targetView,Q=k.target,E-=B,Y-=B,Z-=B,B=0;else K=k;if(T===2)W.setUint16(Y,U,!0),Y+=2;else W.setUint32(Y,U,!0),Y+=4}else I=O.object16||h9(O,Sw,2),W.setInt16(Y,P===null?-10:-9,!0),Y+=2;z++}let q=I[n1];if(q==null){q=G.typedStructs.length;let N=[],L=I,w,P;while((P=L.__type)!==void 0){let _=L.__size;L=L.__parent,w=L.key;let O=[P,_,w];if(L.enumerationOffset)O.push(L.enumerationOffset);N.push(O),L=L.parent}N.reverse(),I[n1]=q,G.typedStructs[q]=N,X(null,0,!0)}switch(H){case 1:if(q>=16)return 0;Q[Z]=q+32;break;case 2:if(q>=256)return 0;Q[Z]=56,Q[Z+1]=q;break;case 3:if(q>=65536)return 0;Q[Z]=57,W.setUint16(Z+1,q,!0);break;case 4:if(q>=16777216)return 0;W.setUint32(Z,(q<<8)+58,!0);break}if(Y<E){if(E===K)return Y;Q.copyWithin(Y,E,K),K+=Y-E,F.lastStringStart=Y-Z}else if(Y>E){if(E===K)return Y;return F.lastStringStart=Y-Z,EHA(A,Q,B,Z,J,C,X,G)}return K}function GHA(A,Q,B,Y){let J;if(J=A.ascii8||A.num8)return B.setInt8(Q,Y,!0),IE=Q+1,J;if(J=A.string16||A.object16)return B.setInt16(Q,Y,!0),IE=Q+2,J;if(J=A.num32)return B.setUint32(Q,3758096640+Y,!0),IE=Q+4,J;if(J=A.num64)return B.setFloat64(Q,NaN,!0),B.setInt8(Q,Y),IE=Q+8,J;IE=Q;return}function h9(A,Q,B){let Y=FHA[Q]+(B<<3),J=A[Y]||(A[Y]=Object.create(null));return J.__type=Q,J.__size=B,J.__parent=A,J}function HWB(A){if(!(A instanceof Map))return A;let Q=A.get("typed")||[];if(Object.isFrozen(Q))Q=Q.map((J)=>J.slice(0));let B=A.get("named"),Y=Object.create(null);for(let J=0,C=Q.length;J<C;J++){let X=Q[J],G=Y;for(let[F,W,E]of X){let $=G[E];if(!$)G[E]=$={key:E,parent:G,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};G=h9($,F,W)}G[n1]=J}return Q.transitions=Y,this.typedStructs=Q,this.lastTypedStructuresLength=Q.length,B}var Tm=Symbol.for("source");function DWB(A,Q,B,Y){let J=A[Q++]-32;if(J>=24)switch(J){case 24:J=A[Q++];break;case 25:J=A[Q++]+(A[Q++]<<8);break;case 26:J=A[Q++]+(A[Q++]<<8)+(A[Q++]<<16);break;case 27:J=A[Q++]+(A[Q++]<<8)+(A[Q++]<<16)+(A[Q++]<<24);break}let C=Y.typedStructs&&Y.typedStructs[J];if(!C){if(A=Uint8Array.prototype.slice.call(A,Q,B),B-=Q,Q=0,!Y.getStructures)throw Error(`Reference to shared structure ${J} without getStructures method`);if(Y._mergeStructures(Y.getStructures()),!Y.typedStructs)throw Error("Could not find any shared typed structures");if(Y.lastTypedStructuresLength=Y.typedStructs.length,C=Y.typedStructs[J],!C)throw Error("Could not find typed structure "+J)}var{construct:X,fullConstruct:G}=C;if(!X){X=C.construct=function(){},G=C.fullConstruct=function(){},G.prototype=Y.structPrototype??{};var F=X.prototype=Y.structPrototype?Object.create(Y.structPrototype):{};let E=[],$=0,Z;for(let U=0,K=C.length;U<K;U++){let I=C[U],[V,H,D,M]=I;if(D==="__proto__")D="__proto_";let z={key:D,offset:$};if(M)E.splice(U+M,0,z);else E.push(z);let q;switch(H){case 0:q=()=>0;break;case 1:q=(L,w)=>{let P=L.bytes[w+z.offset];return P>=246?$U(P):P};break;case 2:q=(L,w)=>{let P=L.bytes,O=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getUint16(w+z.offset,!0);return O>=65280?$U(O&255):O};break;case 4:q=(L,w)=>{let P=L.bytes,O=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getUint32(w+z.offset,!0);return O>=4294967040?$U(O&255):O};break}z.getRef=q,$+=H;let N;switch(V){case Pm:if(Z&&!Z.next)Z.next=z;Z=z,z.multiGetCount=0,N=function(L){let{bytes:w,position:P}=L,_=$+P,O=q(L,P);if(typeof O!=="number")return O;let k,T=z.next;while(T){if(k=T.getRef(L,P),typeof k==="number")break;else k=null;T=T.next}if(k==null)k=L.bytesEnd-_;if(L.srcString)return L.srcString.slice(O,k);return nIA(w,O+_,k-O)};break;case xD:case Sw:if(Z&&!Z.next)Z.next=z;Z=z,N=function(L){let w=L.position,P=$+w,_=q(L,w);if(typeof _!=="number")return _;let O=L.bytes,k,T=z.next;while(T){if(k=T.getRef(L,w),typeof k==="number")break;else k=null;T=T.next}if(k==null)k=L.bytesEnd-P;if(V===xD)return O.toString("utf8",_+P,k+P);else{s1=L;try{return Y.unpack(O,{start:_+P,end:k+P})}finally{s1=null}}};break;case UU:switch(H){case 4:N=function(L){let w=L.bytes,P=w.dataView||(w.dataView=new DataView(w.buffer,w.byteOffset,w.byteLength)),_=L.position+z.offset,O=P.getInt32(_,!0);if(O<536870912){if(O>-520093696)return O;if(O>-536870912)return $U(O&255)}let k=P.getFloat32(_,!0),T=KE[(w[_+3]&127)<<1|w[_+2]>>7];return(T*k+(k>0?0.5:-0.5)>>0)/T};break;case 8:N=function(L){let w=L.bytes,_=(w.dataView||(w.dataView=new DataView(w.buffer,w.byteOffset,w.byteLength))).getFloat64(L.position+z.offset,!0);if(isNaN(_)){let O=w[L.position+z.offset];if(O>=246)return $U(O)}return _};break;case 1:N=function(L){let P=L.bytes[L.position+z.offset];return P<246?P:$U(P)};break}break;case Sm:N=function(L){let w=L.bytes,P=w.dataView||(w.dataView=new DataView(w.buffer,w.byteOffset,w.byteLength));return new Date(P.getFloat64(L.position+z.offset,!0))};break}z.get=N}if(WHA){let U=[],K=[],I=0,V;for(let D of E){if(Y.alwaysLazyProperty&&Y.alwaysLazyProperty(D.key)){V=!0;continue}Object.defineProperty(F,D.key,{get:NWB(D.get),enumerable:!0});let M="v"+I++;K.push(M),U.push("o["+JSON.stringify(D.key)+"]="+M+"(s)")}if(V)U.push("__proto__:this");let H=Function(...K,"var c=this;return function(s){var o=new c();"+U.join(";")+";return o;}").apply(G,E.map((D)=>D.get));Object.defineProperty(F,"toJSON",{value(D){return H.call(this,this[Tm])}})}else Object.defineProperty(F,"toJSON",{value(U){let K={};for(let I=0,V=E.length;I<V;I++){let H=E[I].key;K[H]=this[H]}return K}})}var W=new X;return W[Tm]={bytes:A,position:Q,srcString:"",bytesEnd:B},W}function $U(A){switch(A){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw Error("Unknown constant")}function NWB(A){return function(){return A(this[Tm])}}function MWB(){if(s1)s1.bytes=Uint8Array.prototype.slice.call(s1.bytes,s1.position,s1.bytesEnd),s1.position=0,s1.bytesEnd=s1.bytes.length}function LWB(A,Q){if(Q.typedStructs){let Y=new Map;Y.set("named",A),Y.set("typed",Q.typedStructs),A=Y}let B=Q.lastTypedStructuresLength||0;return A.isCompatible=(Y)=>{let J=!0;if(Y instanceof Map){if((Y.get("named")||[]).length!==(Q.lastNamedStructuresLength||0))J=!1;if((Y.get("typed")||[]).length!==B)J=!1}else if(Y instanceof Array||Array.isArray(Y)){if(Y.length!==(Q.lastNamedStructuresLength||0))J=!1}if(!J)Q._mergeStructures(Y);return J},Q.lastTypedStructuresLength=Q.typedStructs&&Q.typedStructs.length,A}tIA(DWB,HWB,MWB);var _WB=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!_WB){let A;try{if(A=OHA(),A)iIA(A.extractStrings)}catch(Q){}}var Cs={};h6(Cs,{zodErrorsIntegration:()=>Cd,wrapMcpServerWithSentry:()=>Ed,withScope:()=>OC,withMonitor:()=>o1,withIsolationScope:()=>iG,withActiveSpan:()=>o7,vercelAIIntegration:()=>CT,validateOpenTelemetrySetup:()=>Js,updateSpanName:()=>em,trpcMiddleware:()=>Gd,tediousIntegration:()=>eP,suppressTracing:()=>eD,supabaseIntegration:()=>Jd,startSpanManual:()=>tD,startSpan:()=>R8,startSession:()=>CN,startNewTrace:()=>Nu,startInactiveSpan:()=>Hu,spotlightIntegration:()=>sP,spanToTraceHeader:()=>lD,spanToJSON:()=>AQ,spanToBaggageHeader:()=>Gu,setupKoaErrorHandler:()=>lHQ,setupHapiErrorHandler:()=>HHQ,setupFastifyErrorHandler:()=>S4Q,setupExpressErrorHandler:()=>f$Q,setupConnectErrorHandler:()=>$DQ,setUser:()=>Tu,setTags:()=>Ou,setTag:()=>Pu,setNodeAsyncContextStrategy:()=>fO,setMeasurement:()=>Vu,setHttpStatus:()=>LU,setExtras:()=>wu,setExtra:()=>ju,setCurrentClient:()=>lu,setContext:()=>Ru,rewriteFramesIntegration:()=>Yd,requestDataIntegration:()=>WN,redisIntegration:()=>_P,profiler:()=>Xd,prismaIntegration:()=>fP,preloadOpenTelemetry:()=>qMQ,postgresIntegration:()=>hP,parameterize:()=>Xj,onUnhandledRejectionIntegration:()=>BP,onUncaughtExceptionIntegration:()=>QP,nodeContextIntegration:()=>aO,nativeNodeFetchIntegration:()=>iO,mysqlIntegration:()=>PP,mysql2Integration:()=>SP,mongooseIntegration:()=>jP,mongoIntegration:()=>RP,modulesIntegration:()=>AP,makeNodeTransport:()=>$T,lruMemoizerIntegration:()=>zP,logger:()=>Kd,localVariablesIntegration:()=>eO,linkedErrorsIntegration:()=>FN,lastEventId:()=>Su,koaIntegration:()=>pP,knexIntegration:()=>gDQ,kafkaIntegration:()=>qP,isInitialized:()=>PU,instrumentSupabaseClient:()=>$j,initWithoutDefaultIntegrations:()=>RMQ,initOpenTelemetry:()=>HT,init:()=>DT,inboundFiltersIntegration:()=>GN,httpIntegration:()=>dO,hapiIntegration:()=>dP,graphqlIntegration:()=>LP,getTraceMetaTags:()=>nu,getTraceData:()=>aG,getSpanStatusFromHttpCode:()=>MU,getSpanDescendants:()=>cD,getSentryRelease:()=>VT,getRootSpan:()=>E0,getIsolationScope:()=>wQ,getGlobalScope:()=>pG,getDefaultIntegrationsWithoutPerformance:()=>Bs,getDefaultIntegrations:()=>Ys,getCurrentScope:()=>nQ,getClient:()=>gA,getAutoPerformanceIntegrations:()=>WT,getActiveSpan:()=>c5,genericPoolIntegration:()=>AT,generateInstrumentOnce:()=>UQ,functionToStringIntegration:()=>XN,fsIntegration:()=>fZQ,flush:()=>ku,fastifyIntegration:()=>HP,extraErrorDataIntegration:()=>tu,expressIntegration:()=>FP,expressErrorHandler:()=>wi,eventFiltersIntegration:()=>Fj,endSession:()=>TE,disableAnrDetectionForCallback:()=>Y$Q,defaultStackParser:()=>IT,dedupeIntegration:()=>ou,dataloaderIntegration:()=>jNQ,cron:()=>SMQ,createTransport:()=>TU,createSentryWinstonTransport:()=>oNQ,createGetModuleFromFilename:()=>KT,continueTrace:()=>Du,contextLinesIntegration:()=>rO,consoleLoggingIntegration:()=>$d,consoleIntegration:()=>EN,connectIntegration:()=>nP,close:()=>_u,childProcessIntegration:()=>XT,captureSession:()=>yu,captureMessage:()=>OU,captureFeedback:()=>Zd,captureException:()=>jB,captureEvent:()=>YN,captureConsoleIntegration:()=>ru,captureCheckIn:()=>BN,anrIntegration:()=>B$Q,amqplibIntegration:()=>YT,addIntegration:()=>fu,addEventProcessor:()=>vu,addBreadcrumb:()=>C9,SentryContextManager:()=>FT,Scope:()=>CJ,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>eB,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>z8,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>NQ,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>JQ,SDK_VERSION:()=>b0,NodeClient:()=>vM});var Kd={};h6(Kd,{warn:()=>U$B,trace:()=>E$B,info:()=>$$B,fmt:()=>pu,fatal:()=>V$B,error:()=>K$B,debug:()=>Z$B});import{format as W$B}from"node:util";var OA=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var b0="9.22.0";var QQ=globalThis;function zJ(){return m7(QQ),QQ}function m7(A){let Q=A.__SENTRY__=A.__SENTRY__||{};return Q.version=Q.version||b0,Q[b0]=Q[b0]||{}}function HE(A,Q,B=QQ){let Y=B.__SENTRY__=B.__SENTRY__||{},J=Y[b0]=Y[b0]||{};return J[A]||(J[A]=Q())}var PHA=Object.prototype.toString;function b5(A){switch(PHA.call(A)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return dG(A,Error)}}function yw(A,Q){return PHA.call(A)===`[object ${Q}]`}function THA(A){return yw(A,"ErrorEvent")}function DE(A){return yw(A,"String")}function NE(A){return typeof A==="object"&&A!==null&&"__sentry_template_string__"in A&&"__sentry_template_values__"in A}function fD(A){return A===null||NE(A)||typeof A!=="object"&&typeof A!=="function"}function N8(A){return yw(A,"Object")}function SHA(A){return typeof Event<"u"&&dG(A,Event)}function kHA(A){return typeof Element<"u"&&dG(A,Element)}function _HA(A){return yw(A,"RegExp")}function M8(A){return Boolean(A?.then&&typeof A.then==="function")}function vHA(A){return N8(A)&&"nativeEvent"in A&&"preventDefault"in A&&"stopPropagation"in A}function dG(A,Q){try{return A instanceof Q}catch(B){return!1}}function gw(A){return!!(typeof A==="object"&&A!==null&&(A.__isVue||A._isVue))}var vWB=QQ,yWB=80;function yHA(A,Q={}){if(!A)return"<unknown>";try{let B=A,Y=5,J=[],C=0,X=0,G=" > ",F=G.length,W,E=Array.isArray(Q)?Q:Q.keyAttrs,$=!Array.isArray(Q)&&Q.maxStringLength||yWB;while(B&&C++<Y){if(W=gWB(B,E),W==="html"||C>1&&X+J.length*F+W.length>=$)break;J.push(W),X+=W.length,B=B.parentNode}return J.reverse().join(G)}catch(B){return"<unknown>"}}function gWB(A,Q){let B=A,Y=[];if(!B?.tagName)return"";if(vWB.HTMLElement){if(B instanceof HTMLElement&&B.dataset){if(B.dataset.sentryComponent)return B.dataset.sentryComponent;if(B.dataset.sentryElement)return B.dataset.sentryElement}}Y.push(B.tagName.toLowerCase());let J=Q?.length?Q.filter((X)=>B.getAttribute(X)).map((X)=>[X,B.getAttribute(X)]):null;if(J?.length)J.forEach((X)=>{Y.push(`[${X[0]}="${X[1]}"]`)});else{if(B.id)Y.push(`#${B.id}`);let X=B.className;if(X&&DE(X)){let G=X.split(/\s+/);for(let F of G)Y.push(`.${F}`)}}let C=["aria-label","type","name","title","alt"];for(let X of C){let G=B.getAttribute(X);if(G)Y.push(`[${X}="${G}"]`)}return Y.join("")}var hWB="Sentry Logger ",m5=["debug","info","warn","error","log","assert","trace"],KU={};function v0(A){if(!("console"in QQ))return A();let Q=QQ.console,B={},Y=Object.keys(KU);Y.forEach((J)=>{let C=KU[J];B[J]=Q[J],Q[J]=C});try{return A()}finally{Y.forEach((J)=>{Q[J]=B[J]})}}function xWB(){let A=!1,Q={enable:()=>{A=!0},disable:()=>{A=!1},isEnabled:()=>A};if(OA)m5.forEach((B)=>{Q[B]=(...Y)=>{if(A)v0(()=>{QQ.console[B](`${hWB}[${B}]:`,...Y)})}});else m5.forEach((B)=>{Q[B]=()=>{return}});return Q}var t=HE("logger",xWB);function x9(A,Q=0){if(typeof A!=="string"||Q===0)return A;return A.length<=Q?A:`${A.slice(0,Q)}...`}function fm(A,Q){let B=A,Y=B.length;if(Y<=150)return B;if(Q>Y)Q=Y;let J=Math.max(Q-60,0);if(J<5)J=0;let C=Math.min(J+140,Y);if(C>Y-5)C=Y;if(C===Y)J=Math.max(C-140,0);if(B=B.slice(J,C),J>0)B=`'{snip} ${B}`;if(C<Y)B+=" {snip}";return B}function u7(A,Q){if(!Array.isArray(A))return"";let B=[];for(let Y=0;Y<A.length;Y++){let J=A[Y];try{if(gw(J))B.push("[VueViewModel]");else B.push(String(J))}catch(C){B.push("[value cannot be serialized]")}}return B.join(Q)}function gHA(A,Q,B=!1){if(!DE(A))return!1;if(_HA(Q))return Q.test(A);if(DE(Q))return B?A===Q:A.includes(Q);return!1}function d7(A,Q=[],B=!1){return Q.some((Y)=>gHA(A,Y,B))}function bm(A,Q,B){if(!(Q in A))return;let Y=A[Q];if(typeof Y!=="function")return;let J=B(Y);if(typeof J==="function")fHA(J,Y);try{A[Q]=J}catch{OA&&t.log(`Failed to replace method "${Q}" in object`,A)}}function m0(A,Q,B){try{Object.defineProperty(A,Q,{value:B,writable:!0,configurable:!0})}catch(Y){OA&&t.log(`Failed to add non-enumerable property "${Q}" to object`,A)}}function fHA(A,Q){try{let B=Q.prototype||{};A.prototype=Q.prototype=B,m0(A,"__sentry_original__",Q)}catch(B){}}function mm(A){return A.__sentry_original__}function hw(A){if(b5(A))return{message:A.message,name:A.name,stack:A.stack,...xHA(A)};else if(SHA(A)){let Q={type:A.type,target:hHA(A.target),currentTarget:hHA(A.currentTarget),...xHA(A)};if(typeof CustomEvent<"u"&&dG(A,CustomEvent))Q.detail=A.detail;return Q}else return A}function hHA(A){try{return kHA(A)?yHA(A):Object.prototype.toString.call(A)}catch(Q){return"<unknown>"}}function xHA(A){if(typeof A==="object"&&A!==null){let Q={};for(let B in A)if(Object.prototype.hasOwnProperty.call(A,B))Q[B]=A[B];return Q}else return{}}function um(A,Q=40){let B=Object.keys(hw(A));B.sort();let Y=B[0];if(!Y)return"[object has no keys]";if(Y.length>=Q)return x9(Y,Q);for(let J=B.length;J>0;J--){let C=B.slice(0,J).join(", ");if(C.length>Q)continue;if(J===B.length)return C;return x9(C,Q)}return""}function fWB(){let A=QQ;return A.crypto||A.msCrypto}function GY(A=fWB()){let Q=()=>Math.random()*16;try{if(A?.randomUUID)return A.randomUUID().replace(/-/g,"");if(A?.getRandomValues)Q=()=>{let B=new Uint8Array(1);return A.getRandomValues(B),B[0]}}catch(B){}return([1e7]+1000+4000+8000+100000000000).replace(/[018]/g,(B)=>(B^(Q()&15)>>B/4).toString(16))}function bHA(A){return A.exception?.values?.[0]}function l7(A){let{message:Q,event_id:B}=A;if(Q)return Q;let Y=bHA(A);if(Y){if(Y.type&&Y.value)return`${Y.type}: ${Y.value}`;return Y.type||Y.value||B||"<unknown>"}return B||"<unknown>"}function lm(A,Q,B){let Y=A.exception=A.exception||{},J=Y.values=Y.values||[],C=J[0]=J[0]||{};if(!C.value)C.value=Q||"";if(!C.type)C.type=B||"Error"}function c7(A,Q){let B=bHA(A);if(!B)return;let Y={type:"generic",handled:!0},J=B.mechanism;if(B.mechanism={...Y,...J,...Q},Q&&"data"in Q){let C={...J?.data,...Q.data};B.mechanism.data=C}}var bWB=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function dm(A){return parseInt(A||"",10)}function cm(A){let Q=A.match(bWB)||[],B=dm(Q[1]),Y=dm(Q[2]),J=dm(Q[3]);return{buildmetadata:Q[5],major:isNaN(B)?void 0:B,minor:isNaN(Y)?void 0:Y,patch:isNaN(J)?void 0:J,prerelease:Q[4]}}function xw(A){if(mWB(A))return!0;try{m0(A,"__sentry_captured__",!0)}catch(Q){}return!1}function mWB(A){try{return A.__sentry_captured__}catch{}}var mHA=1000;function lG(){return Date.now()/mHA}function uWB(){let{performance:A}=QQ;if(!A?.now)return lG;let Q=Date.now()-A.now(),B=A.timeOrigin==null?Q:A.timeOrigin;return()=>{return(B+A.now())/mHA}}var RC=uWB();function uHA(A){let Q=RC(),B={sid:GY(),init:!0,timestamp:Q,started:Q,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>dWB(B)};if(A)cG(B,A);return B}function cG(A,Q={}){if(Q.user){if(!A.ipAddress&&Q.user.ip_address)A.ipAddress=Q.user.ip_address;if(!A.did&&!Q.did)A.did=Q.user.id||Q.user.email||Q.user.username}if(A.timestamp=Q.timestamp||RC(),Q.abnormal_mechanism)A.abnormal_mechanism=Q.abnormal_mechanism;if(Q.ignoreDuration)A.ignoreDuration=Q.ignoreDuration;if(Q.sid)A.sid=Q.sid.length===32?Q.sid:GY();if(Q.init!==void 0)A.init=Q.init;if(!A.did&&Q.did)A.did=`${Q.did}`;if(typeof Q.started==="number")A.started=Q.started;if(A.ignoreDuration)A.duration=void 0;else if(typeof Q.duration==="number")A.duration=Q.duration;else{let B=A.timestamp-A.started;A.duration=B>=0?B:0}if(Q.release)A.release=Q.release;if(Q.environment)A.environment=Q.environment;if(!A.ipAddress&&Q.ipAddress)A.ipAddress=Q.ipAddress;if(!A.userAgent&&Q.userAgent)A.userAgent=Q.userAgent;if(typeof Q.errors==="number")A.errors=Q.errors;if(Q.status)A.status=Q.status}function dHA(A,Q){let B={};if(Q)B={status:Q};else if(A.status==="ok")B={status:"exited"};cG(A,B)}function dWB(A){return{sid:`${A.sid}`,init:A.init,started:new Date(A.started*1000).toISOString(),timestamp:new Date(A.timestamp*1000).toISOString(),status:A.status,errors:A.errors,did:typeof A.did==="number"||typeof A.did==="string"?`${A.did}`:void 0,duration:A.duration,abnormal_mechanism:A.abnormal_mechanism,attrs:{release:A.release,environment:A.environment,ip_address:A.ipAddress,user_agent:A.userAgent}}}function p7(A,Q,B=2){if(!Q||typeof Q!=="object"||B<=0)return Q;if(A&&Object.keys(Q).length===0)return A;let Y={...A};for(let J in Q)if(Object.prototype.hasOwnProperty.call(Q,J))Y[J]=p7(Y[J],Q[J],B-1);return Y}var pm="_sentrySpan";function ME(A,Q){if(Q)m0(A,pm,Q);else delete A[pm]}function u5(A){return A[pm]}function wC(){return GY()}function jC(){return GY().substring(16)}var lWB=100;class CJ{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:wC(),sampleRand:Math.random()}}clone(){let A=new CJ;if(A._breadcrumbs=[...this._breadcrumbs],A._tags={...this._tags},A._extra={...this._extra},A._contexts={...this._contexts},this._contexts.flags)A._contexts.flags={values:[...this._contexts.flags.values]};return A._user=this._user,A._level=this._level,A._session=this._session,A._transactionName=this._transactionName,A._fingerprint=this._fingerprint,A._eventProcessors=[...this._eventProcessors],A._attachments=[...this._attachments],A._sdkProcessingMetadata={...this._sdkProcessingMetadata},A._propagationContext={...this._propagationContext},A._client=this._client,A._lastEventId=this._lastEventId,ME(A,u5(this)),A}setClient(A){this._client=A}setLastEventId(A){this._lastEventId=A}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(A){this._scopeListeners.push(A)}addEventProcessor(A){return this._eventProcessors.push(A),this}setUser(A){if(this._user=A||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session)cG(this._session,{user:A});return this._notifyScopeListeners(),this}getUser(){return this._user}setTags(A){return this._tags={...this._tags,...A},this._notifyScopeListeners(),this}setTag(A,Q){return this._tags={...this._tags,[A]:Q},this._notifyScopeListeners(),this}setExtras(A){return this._extra={...this._extra,...A},this._notifyScopeListeners(),this}setExtra(A,Q){return this._extra={...this._extra,[A]:Q},this._notifyScopeListeners(),this}setFingerprint(A){return this._fingerprint=A,this._notifyScopeListeners(),this}setLevel(A){return this._level=A,this._notifyScopeListeners(),this}setTransactionName(A){return this._transactionName=A,this._notifyScopeListeners(),this}setContext(A,Q){if(Q===null)delete this._contexts[A];else this._contexts[A]=Q;return this._notifyScopeListeners(),this}setSession(A){if(!A)delete this._session;else this._session=A;return this._notifyScopeListeners(),this}getSession(){return this._session}update(A){if(!A)return this;let Q=typeof A==="function"?A(this):A,B=Q instanceof CJ?Q.getScopeData():N8(Q)?A:void 0,{tags:Y,extra:J,user:C,contexts:X,level:G,fingerprint:F=[],propagationContext:W}=B||{};if(this._tags={...this._tags,...Y},this._extra={...this._extra,...J},this._contexts={...this._contexts,...X},C&&Object.keys(C).length)this._user=C;if(G)this._level=G;if(F.length)this._fingerprint=F;if(W)this._propagationContext=W;return this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,ME(this,void 0),this._attachments=[],this.setPropagationContext({traceId:wC(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(A,Q){let B=typeof Q==="number"?Q:lWB;if(B<=0)return this;let Y={timestamp:lG(),...A,message:A.message?x9(A.message,2048):A.message};if(this._breadcrumbs.push(Y),this._breadcrumbs.length>B)this._breadcrumbs=this._breadcrumbs.slice(-B),this._client?.recordDroppedEvent("buffer_overflow","log_item");return this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(A){return this._attachments.push(A),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:u5(this)}}setSDKProcessingMetadata(A){return this._sdkProcessingMetadata=p7(this._sdkProcessingMetadata,A,2),this}setPropagationContext(A){return this._propagationContext=A,this}getPropagationContext(){return this._propagationContext}captureException(A,Q){let B=Q?.event_id||GY();if(!this._client)return t.warn("No client configured on scope - will not capture exception!"),B;let Y=Error("Sentry syntheticException");return this._client.captureException(A,{originalException:A,syntheticException:Y,...Q,event_id:B},this),B}captureMessage(A,Q,B){let Y=B?.event_id||GY();if(!this._client)return t.warn("No client configured on scope - will not capture message!"),Y;let J=Error(A);return this._client.captureMessage(A,Q,{originalException:A,syntheticException:J,...B,event_id:Y},this),Y}captureEvent(A,Q){let B=Q?.event_id||GY();if(!this._client)return t.warn("No client configured on scope - will not capture event!"),B;return this._client.captureEvent(A,{...Q,event_id:B},this),B}_notifyScopeListeners(){if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach((A)=>{A(this)}),this._notifyingListeners=!1}}function VU(){return HE("defaultCurrentScope",()=>new CJ)}function L8(){return HE("defaultIsolationScope",()=>new CJ)}class cHA{constructor(A,Q){let B;if(!A)B=new CJ;else B=A;let Y;if(!Q)Y=new CJ;else Y=Q;this._stack=[{scope:B}],this._isolationScope=Y}withScope(A){let Q=this._pushScope(),B;try{B=A(Q)}catch(Y){throw this._popScope(),Y}if(M8(B))return B.then((Y)=>{return this._popScope(),Y},(Y)=>{throw this._popScope(),Y});return this._popScope(),B}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let A=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:A}),A}_popScope(){if(this._stack.length<=1)return!1;return!!this._stack.pop()}}function IU(){let A=zJ(),Q=m7(A);return Q.stack=Q.stack||new cHA(VU(),L8())}function cWB(A){return IU().withScope(A)}function pWB(A,Q){let B=IU();return B.withScope(()=>{return B.getStackTop().scope=A,Q(A)})}function lHA(A){return IU().withScope(()=>{return A(IU().getIsolationScope())})}function pHA(){return{withIsolationScope:lHA,withScope:cWB,withSetScope:pWB,withSetIsolationScope:(A,Q)=>{return lHA(Q)},getCurrentScope:()=>IU().getScope(),getIsolationScope:()=>IU().getIsolationScope()}}function im(A){let Q=zJ(),B=m7(Q);B.acs=A}function q8(A){let Q=m7(A);if(Q.acs)return Q.acs;return pHA()}function nQ(){let A=zJ();return q8(A).getCurrentScope()}function wQ(){let A=zJ();return q8(A).getIsolationScope()}function pG(){return HE("globalScope",()=>new CJ)}function OC(...A){let Q=zJ(),B=q8(Q);if(A.length===2){let[Y,J]=A;if(!Y)return B.withScope(J);return B.withSetScope(Y,J)}return B.withScope(A[0])}function iG(...A){let Q=zJ(),B=q8(Q);if(A.length===2){let[Y,J]=A;if(!Y)return B.withIsolationScope(J);return B.withSetIsolationScope(Y,J)}return B.withIsolationScope(A[0])}function gA(){return nQ().getClient()}function HU(A){let Q=A.getPropagationContext(),{traceId:B,parentSpanId:Y,propagationSpanId:J}=Q,C={trace_id:B,span_id:J||jC()};if(Y)C.parent_span_id=Y;return C}var eB="sentry.source",z8="sentry.sample_rate",nm="sentry.previous_trace_sample_rate",JQ="sentry.op",NQ="sentry.origin";var fw="sentry.measurement_unit",bw="sentry.measurement_value",d5="sentry.custom_span_name",DU="sentry.profile_id",NU="sentry.exclusive_time",sm="cache.hit",am="cache.key",rm="cache.item_size";var om=0,i7=1,f9=2;function MU(A){if(A<400&&A>=100)return{code:1};if(A>=400&&A<500)switch(A){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(A>=500&&A<600)switch(A){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}function LU(A,Q){A.setAttribute("http.response.status_code",Q);let B=MU(Q);if(B.message!=="unknown_error")A.setStatus(B)}var iHA="_sentryScope",nHA="_sentryIsolationScope";function bD(A,Q,B){if(A)m0(A,nHA,B),m0(A,iHA,Q)}function l5(A){return{scope:A[iHA],isolationScope:A[nHA]}}function PC(A){if(typeof A==="boolean")return Number(A);let Q=typeof A==="string"?parseFloat(A):A;if(typeof Q!=="number"||isNaN(Q)||Q<0||Q>1)return;return Q}var mD="sentry-",aHA=/^sentry-/,rHA=8192;function n7(A){let Q=LE(A);if(!Q)return;let B=Object.entries(Q).reduce((Y,[J,C])=>{if(J.match(aHA)){let X=J.slice(mD.length);Y[X]=C}return Y},{});if(Object.keys(B).length>0)return B;else return}function s7(A){if(!A)return;let Q=Object.entries(A).reduce((B,[Y,J])=>{if(J)B[`${mD}${Y}`]=J;return B},{});return mw(Q)}function LE(A){if(!A||!DE(A)&&!Array.isArray(A))return;if(Array.isArray(A))return A.reduce((Q,B)=>{let Y=sHA(B);return Object.entries(Y).forEach(([J,C])=>{Q[J]=C}),Q},{});return sHA(A)}function sHA(A){return A.split(",").map((Q)=>Q.split("=").map((B)=>{try{return decodeURIComponent(B.trim())}catch{return}})).reduce((Q,[B,Y])=>{if(B&&Y)Q[B]=Y;return Q},{})}function mw(A){if(Object.keys(A).length===0)return;return Object.entries(A).reduce((Q,[B,Y],J)=>{let C=`${encodeURIComponent(B)}=${encodeURIComponent(Y)}`,X=J===0?C:`${Q},${C}`;if(X.length>rHA)return OA&&t.warn(`Not adding key: ${B} with val: ${Y} to baggage header due to exceeding baggage size limits.`),Q;else return X},"")}var uD=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function oHA(A){if(!A)return;let Q=A.match(uD);if(!Q)return;let B;if(Q[3]==="1")B=!0;else if(Q[3]==="0")B=!1;return{traceId:Q[1],parentSampled:B,parentSpanId:Q[2]}}function qE(A,Q){let B=oHA(A),Y=n7(Q);if(!B?.traceId)return{traceId:wC(),sampleRand:Math.random()};let J=iWB(B,Y);if(Y)Y.sample_rand=J.toString();let{traceId:C,parentSpanId:X,parentSampled:G}=B;return{traceId:C,parentSpanId:X,sampled:G,dsc:Y||{},sampleRand:J}}function a7(A=wC(),Q=jC(),B){let Y="";if(B!==void 0)Y=B?"-1":"-0";return`${A}-${Q}${Y}`}function iWB(A,Q){let B=PC(Q?.sample_rand);if(B!==void 0)return B;let Y=PC(Q?.sample_rate);if(Y&&A?.parentSampled!==void 0)return A.parentSampled?Math.random()*Y:Y+Math.random()*(1-Y);else return Math.random()}var uw=0,dw=1,tHA=!1;function ADA(A){let{spanId:Q,traceId:B}=A.spanContext(),{data:Y,op:J,parent_span_id:C,status:X,origin:G,links:F}=AQ(A);return{parent_span_id:C,span_id:Q,trace_id:B,data:Y,op:J,status:X,origin:G,links:F}}function r7(A){let{spanId:Q,traceId:B,isRemote:Y}=A.spanContext(),J=Y?Q:AQ(A).parent_span_id,C=l5(A).scope,X=Y?C?.getPropagationContext().propagationSpanId||jC():Q;return{parent_span_id:J,span_id:X,trace_id:B}}function lD(A){let{traceId:Q,spanId:B}=A.spanContext(),Y=r1(A);return a7(Q,B,Y)}function zE(A){if(A&&A.length>0)return A.map(({context:{spanId:Q,traceId:B,traceFlags:Y,...J},attributes:C})=>({span_id:Q,trace_id:B,sampled:Y===dw,attributes:C,...J}));else return}function b9(A){if(typeof A==="number")return eHA(A);if(Array.isArray(A))return A[0]+A[1]/1e9;if(A instanceof Date)return eHA(A.getTime());return RC()}function eHA(A){return A>9999999999?A/1000:A}function AQ(A){if(sWB(A))return A.getSpanJSON();let{spanId:Q,traceId:B}=A.spanContext();if(nWB(A)){let{attributes:Y,startTime:J,name:C,endTime:X,status:G,links:F}=A,W="parentSpanId"in A?A.parentSpanId:("parentSpanContext"in A)?A.parentSpanContext?.spanId:void 0;return{span_id:Q,trace_id:B,data:Y,description:C,parent_span_id:W,start_timestamp:b9(J),timestamp:b9(X)||void 0,status:RE(G),op:Y[JQ],origin:Y[NQ],links:zE(F)}}return{span_id:Q,trace_id:B,start_timestamp:0,data:{}}}function nWB(A){let Q=A;return!!Q.attributes&&!!Q.startTime&&!!Q.name&&!!Q.endTime&&!!Q.status}function sWB(A){return typeof A.getSpanJSON==="function"}function r1(A){let{traceFlags:Q}=A.spanContext();return Q===dw}function RE(A){if(!A||A.code===om)return;if(A.code===i7)return"ok";return A.message||"unknown_error"}var dD="_sentryChildSpans",tm="_sentryRootSpan";function qU(A,Q){let B=A[tm]||A;if(m0(Q,tm,B),A[dD])A[dD].add(Q);else m0(A,dD,new Set([Q]))}function cD(A){let Q=new Set;function B(Y){if(Q.has(Y))return;else if(r1(Y)){Q.add(Y);let J=Y[dD]?Array.from(Y[dD]):[];for(let C of J)B(C)}}return B(A),Array.from(Q)}function E0(A){return A[tm]||A}function c5(){let A=zJ(),Q=q8(A);if(Q.getActiveSpan)return Q.getActiveSpan();return u5(nQ())}function pD(){if(!tHA)v0(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")}),tHA=!0}function em(A,Q){A.updateName(Q),A.setAttributes({[eB]:"custom",[d5]:Q})}var Qu="?",QDA=/\(error: (.*)\)/,BDA=/captureMessage|captureException/;function cw(...A){let Q=A.sort((B,Y)=>B[0]-Y[0]).map((B)=>B[1]);return(B,Y=0,J=0)=>{let C=[],X=B.split(`
|
|
240
240
|
`);for(let G=Y;G<X.length;G++){let F=X[G];if(F.length>1024)continue;let W=QDA.test(F)?F.replace(QDA,"$1"):F;if(W.match(/\S*Error: /))continue;for(let E of Q){let $=E(W);if($){C.push($);break}}if(C.length>=50+J)break}return YDA(C.slice(J))}}function Bu(A){if(Array.isArray(A))return cw(...A);return A}function YDA(A){if(!A.length)return[];let Q=Array.from(A);if(/sentryWrapped/.test(lw(Q).function||""))Q.pop();if(Q.reverse(),BDA.test(lw(Q).function||"")){if(Q.pop(),BDA.test(lw(Q).function||""))Q.pop()}return Q.slice(0,50).map((B)=>({...B,filename:B.filename||lw(Q).filename,function:B.function||"?"}))}function lw(A){return A[A.length-1]||{}}var Au="<anonymous>";function iD(A){try{if(!A||typeof A!=="function")return Au;return A.name||Au}catch(Q){return Au}}function pw(A){let Q=A.exception;if(Q){let B=[];try{return Q.values.forEach((Y)=>{if(Y.stacktrace.frames)B.push(...Y.stacktrace.frames)}),B}catch(Y){return}}return}var iw={},JDA={};function zU(A,Q){iw[A]=iw[A]||[],iw[A].push(Q)}function RU(A,Q){if(!JDA[A]){JDA[A]=!0;try{Q()}catch(B){OA&&t.error(`Error while instrumenting ${A}`,B)}}}function wU(A,Q){let B=A&&iw[A];if(!B)return;for(let Y of B)try{Y(Q)}catch(J){OA&&t.error(`Error while triggering instrumentation handler.
|
|
241
241
|
Type: ${A}
|
|
242
242
|
Name: ${iD(Y)}
|
|
@@ -378,4 +378,4 @@ wzUfQXDpZndkqxHilERgvPXLEsTTCMF/W+C8gsO9AoGAZWt+CU6zQhqMBB5MMGZf
|
|
|
378
378
|
UE5WUS/oOd4jHBqwVxBTLOAPlmnQSp1uiTu2K0NrnnvZ6Zi/+tIsjbtxhomeOmnH
|
|
379
379
|
+wsk9n+Bif4P7VTvwqc9FY4Ya79PEJK+J/xx/mldUEz3R63RiRXZAaDddO7yCQFX
|
|
380
380
|
W8eeuIMLKU6dSq0yu22+nyU=
|
|
381
|
-
-----END PRIVATE KEY-----`;or(new rr({connections:50,pipelining:1,keepAliveTimeout:30000,keepAliveMaxTimeout:60000,connect:{timeout:1e4},headersTimeout:15000,bodyTimeout:30000}));var Yk=process.env.PORT??8080,er="0.14.27",Ao;((J)=>{J.READY="WEBSERVER.READY";J.STOPPED="WEBSERVER.STOPPED";J.ERROR="WEBSERVER.ERROR";J.UPGRADE="WEBSERVER.UPGRADE"})(Ao||={});var hL={"access-control-allow-origin":"*"},jf0=JSON.stringify({status:"OK",version:er,runtime:"node"}),Of0={".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".gltf":"model/gltf+json",".glb":"model/gltf-binary",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".ktx2":"image/ktx2",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".bin":"application/octet-stream",".wasm":"application/wasm"};class UV extends YQ{static instance=new UV;_server;_assetCache=new Map;_assetDirs=[];constructor(){super();this._assetDirs.push(tr.resolve("assets"));let A=qY.assetsLibraryPath;if(A)this._assetDirs.push(A)}start(){if(this._server)return n.warning("WebServer.start(): already started");this._server=wf0.createSecureServer({key:Bk,cert:Qk,allowHTTP1:!0}),this._server.on("stream",this._onStream),this._server.on("upgrade",this._onUpgrade),this._server.on("error",this._onError),this._server.on("close",this._onStopped),this._server.listen(Yk,this._onStarted),console.info(`WebServer.start(): Server running on port ${Yk}`)}stop(){if(!this._server)return n.warning("WebServer.stop(): not started"),Promise.resolve(!1);return new Promise((A,Q)=>{this._server.close((B)=>B?Q(B):A(!0))})}_onStarted=()=>this.emitWithGlobal("WEBSERVER.READY",{});_onStopped=()=>this.emitWithGlobal("WEBSERVER.STOPPED",{});_onError=(A)=>{n.error(`WebServer._onError(): ${A.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:A})};_onStream=(A,Q)=>{A.on("error",()=>{});let B=Q[":path"]||"/",J=(Q[":method"]||"GET")==="HEAD";if(B==="/"){A.respond({":status":200,"content-type":"application/json",...hL}),A.end(!J?jf0:void 0);return}let C=decodeURIComponent(B.split("?")[0]);if(C.includes("..")){A.respond({":status":400,...hL}),A.end();return}for(let X of this._assetDirs){let G=tr.join(X,C);if(!G.startsWith(X))continue;let F=qY.assetsLibraryPath;if(F&&G.startsWith(F))qY.instance.syncAsset(G);let W=this._assetCache.get(G);if(!W)try{let U=iPQ.statSync(G);if(!U.isFile())continue;W={size:U.size,etag:`"${U.mtimeMs.toString(36)}-${U.size.toString(36)}"`},this._assetCache.set(G,W)}catch{continue}if(Q["if-none-match"]===W.etag){A.respond({":status":304,...hL}),A.end();return}let $={":status":200,"content-type":Of0[tr.extname(G).toLowerCase()]||"application/octet-stream","content-length":W.size,etag:W.etag,"cache-control":"public, max-age=0, must-revalidate",...hL};if(J){A.respond($),A.end();return}A.respond($);let Z=iPQ.createReadStream(G);A.on("close",()=>Z.destroy()),Z.on("error",()=>A.close()),Z.pipe(A);return}A.respond({":status":404,...hL}),A.end()};_onUpgrade=(A,Q,B)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:A,socket:Q,head:B})}}var tZ;((I)=>{I.BUILD_PACKETS="build_packets";I.ENTITIES_EMIT_UPDATES="entities_emit_updates";I.ENTITIES_TICK="entities_tick";I.NETWORK_SYNCHRONIZE="network_synchronize";I.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";I.PHYSICS_CLEANUP="physics_cleanup";I.PHYSICS_STEP="physics_step";I.SEND_ALL_PACKETS="send_all_packets";I.SEND_PACKETS="send_packets";I.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";I.SERIALIZE_PACKETS="serialize_packets";I.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";I.SIMULATION_STEP="simulation_step";I.TICKER_TICK="ticker_tick";I.WORLD_TICK="world_tick"})(tZ||={});class a0{static getProcessStats(A=!1){let Q=process.memoryUsage(),B={jsHeapSizeMb:{value:Q.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:Q.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:Q.heapUsed/Q.heapTotal,unit:"percent"},processHeapSizeMb:{value:Q.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:Q.rss/1024/1024,unit:"megabyte"}};if(A)return B;return Object.fromEntries(Object.entries(B).map(([Y,J])=>[Y,J.value]))}static initializeSentry(A,Q=50){if(PU())return;DT({dsn:A,release:er,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(B)=>{return B.extra=a0.getProcessStats(),B},beforeSendTransaction:(B)=>{if(B.contexts?.trace?.op==="ticker_tick"){let J=B?.start_timestamp,C=B?.timestamp;if(!J||!C)return null;if((C-J)*1000>Q)return B.measurements=a0.getProcessStats(!0),B}return null}})}static startSpan(A,Q){if(PU())return R8({attributes:A.attributes,name:A.operation,op:A.operation},Q);else return Q()}static sentry(){return Cs}}if(!jw)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var nPQ=new VE({useFloat32:yD.ALWAYS}),Tf0=30000;class E1 extends YQ{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_isDuplicate=!1;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(A,Q,B){super();this.id=_IA(),this.onPacket(xA.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{YQ.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:B})};if(A)this.bindWs(A),Y();else if(Q)this.bindWt(Q).then(Y).catch((J)=>{this._onClose(),n.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${J}`)})}get isDuplicate(){return this._isDuplicate}static clearCachedPacketsSerializedBuffers(){if(E1._cachedPacketsSerializedBuffer.size>0)E1._cachedPacketsSerializedBuffer.clear()}static serializePackets(A){for(let B of A)if(!xA.isValidPacket(B))return n.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(B)}`);let Q=E1._cachedPacketsSerializedBuffer.get(A);if(Q)return Q;return a0.startSpan({operation:"serialize_packets",attributes:{packets:A.length,packetIds:A.map((B)=>B[0]).join(",")}},(B)=>{let Y=nPQ.pack(A);if(Y.byteLength>65536)Y=Pf0(Y,{level:1});return B?.setAttribute("serializedBytes",Y.byteLength),E1._cachedPacketsSerializedBuffer.set(A,Y),Y})}bindWs(A){this._wsBinding=!0;let Q=this._handleReconnect();if(this._cleanupConnections(),this._ws=A,this._ws.binaryType="nodebuffer",this._ws.onmessage=(B)=>this._onMessage(B.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),Q)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(A){this._wtBinding=!0;let Q=this._handleReconnect();this._cleanupConnections(),A.userData.onclose=this._onClose,A.closed.catch(()=>{}).finally(()=>A.userData.onclose?.()),this._wt=A;try{await A.ready;let B=A.incomingBidirectionalStreams.getReader();try{let{value:Y}=await B.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{B.releaseLock()}this._wtUnreliableReader=A.datagrams.readable,this._wtUnreliableWriter=A.datagrams.createWritable().getWriter()}catch{this._wtBinding=!1;return}if(this._wtBinding=!1,this._wt!==A)return;if((async()=>{if(!this._wtReliableReader)throw Error("Connection.bindWt(): Reliable reader not found.");let B=xA.createPacketBufferUnframer((Y)=>{this._onMessage(Y)});for await(let Y of this._wtReliableReader){if(A!==this._wt)return;B(Y)}})().catch(()=>{try{A?.close()}catch{}}),(async()=>{if(!this._wtUnreliableReader)throw Error("Connection.bindWt(): Unreliable reader not found.");for await(let B of this._wtUnreliableReader){if(A!==this._wt)return;this._onMessage(B)}})().catch(()=>{try{A?.close()}catch{}}),this._signalConnectionId(),Q)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(A){n.error(`Connection.disconnect(): Connection disconnect failed. Error: ${A}`)}}killDuplicateConnection(){this._isDuplicate=!0,this._cleanupConnections(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._finalizeClose()}onPacket(A,Q){this.on("CONNECTION.PACKET_RECEIVED",({packet:B})=>{if(B[0]===A)Q(B)})}send(A,Q=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let B=this._ws&&this._ws.readyState===WU.default.OPEN,Y=this._wt&&this._wt.state==="connected";if(!B&&!Y)return;a0.startSpan({operation:"send_packets"},()=>{try{let J=E1.serializePackets(A);if(!J)return;if(Y)if(Q||J.byteLength>1200)this._wtReliableWriter?.write(xA.framePacketBuffer(J)).catch(()=>{n.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(J).catch(()=>{n.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(J);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:A})}catch(J){n.error(`Connection.send(): Packet send failed. Error: ${J}`)}})}_onHeartbeatPacket=()=>{this.send([xA.createPacket(xA.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(A)=>{try{let Q=this._deserialize(A);if(!Q)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:Q})}catch(Q){n.error(`Connection._ws.onmessage(): Error: ${Q}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>this._finalizeClose(),Tf0)};_onError=(A)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:A})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill();try{this._ws?.close()}catch{}let A=this._wt;if(A)setTimeout(()=>{try{A.close()}catch{}},50);this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(A){let Q=nPQ.unpack(A);if(!Q||typeof Q!=="object"||typeof Q[0]!=="number")return n.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(Q)}`);if(!xA.isValidPacket(Q))return n.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(Q)}`);return Q}_finalizeClose(){this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()}_handleReconnect(){let A=!!this._ws||!!this._wt;if(A&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return A}_signalConnectionId(){this.send([xA.createPacket(xA.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([xA.createPacket(xA.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class xL{_lights=new Map;_nextLightId=1;_world;constructor(A){this._world=A}get world(){return this._world}despawnEntityAttachedLights(A){this.getAllEntityAttachedLights(A).forEach((Q)=>{Q.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(A){return this.getAllLights().filter((Q)=>Q.attachedToEntity===A)}registerLight(A){if(A.id!==void 0)return A.id;let Q=this._nextLightId;return this._lights.set(Q,A),this._nextLightId++,Q}unregisterLight(A){if(A.id===void 0)return;this._lights.delete(A.id)}}class pY{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(A){return this._map.get(A)}set(A,Q){let B=this._map.has(A);if(this._map.set(A,Q),!B)this._values.push(Q);else this._isDirty=!0;return this}has(A){return this._map.has(A)}delete(A){let Q=this._map.delete(A);if(Q)this._isDirty=!0;return Q}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(A,Q){this._map.forEach((B,Y)=>{A.call(Q,B,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let A of this._map.values())this._values.push(A);this._isDirty=!1}}var Sf0={x:0,y:-32,z:0},fL=60,Qo;((J)=>{J.STEP_START="SIMULATION.STEP_START";J.STEP_END="SIMULATION.STEP_END";J.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";J.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Qo||={});class bL extends YQ{_colliderMap=new OD;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(A,Q=fL,B=Sf0){super();this._rapierEventQueue=new WB.EventQueue(!0),this._rapierSimulation=new WB.World(B),this._rapierSimulation.timestep=Math.fround(1/Q),this._world=A}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(A,Q){return this._rapierSimulation.createCollider(A,Q)}createRawRigidBody(A){return this._rapierSimulation.createRigidBody(A)}enableDebugRaycasting(A){this._debugRaycastingEnabled=A}enableDebugRendering(A,Q=WB.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=A,this._debugRenderingFilterFlags=Q}getContactManifolds(A,Q){let B=[];return this._rapierSimulation.narrowPhase.contactPair(A,Q,(Y,J)=>{if(Y.numContacts()===0)return;let C=Y.normal(),X=[];for(let G=0;G<Y.numSolverContacts();G++)X.push(Y.solverContactPoint(G));B.push({contactPoints:X,localNormalA:!J?Y.localNormal1():Y.localNormal2(),localNormalB:!J?Y.localNormal2():Y.localNormal1(),normal:!J?C:{x:-C.x,y:-C.y,z:-C.z}})}),B}intersectionsWithRawShape(A,Q,B,Y={}){let J=new Set,C=[];return this._rapierSimulation.intersectionsWithShape(Q,B,A,(X)=>{let G=this._colliderMap.getColliderHandleBlockType(X.handle);if(G&&!J.has(G))return J.add(G),C.push({intersectedBlockType:G}),!0;let F=this._colliderMap.getColliderHandleEntity(X.handle);if(F&&!J.has(F))return J.add(F),C.push({intersectedEntity:F}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),C}raycast(A,Q,B,Y={}){let J=new WB.Ray(A,Q),C=this._rapierSimulation.castRay(J,B,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:A,direction:Q,length:B,hit:!!C});if(!C)return null;let X=J.pointAt(C.timeOfImpact),G=C.timeOfImpact,F=C.collider,W=this._colliderMap.getColliderHandleBlockType(F.handle);if(W)return{hitBlock:J$.fromGlobalCoordinate({x:Math.floor(X.x-(J.dir.x<0?0.0001:-0.0001)),y:Math.floor(X.y-(J.dir.y<0?0.0001:-0.0001)),z:Math.floor(X.z-(J.dir.z<0?0.0001:-0.0001))},W),hitPoint:X,hitDistance:G,origin:A,originDirection:Q};let E=this._colliderMap.getColliderHandleEntity(F.handle);if(E)return{hitEntity:E,hitPoint:X,hitDistance:G,origin:A,originDirection:Q};return null}removeRawCollider(A){this._colliderMap.queueColliderHandleForCleanup(A.handle),this._rapierSimulation.removeCollider(A,!1)}removeRawRigidBody(A){this._rapierSimulation.removeRigidBody(A)}setGravity(A){this._rapierSimulation.gravity=A}step=(A)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:A});let Q=performance.now();if(a0.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),a0.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-Q}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(A,Q,B)=>{let[Y,J]=this._getCollisionObjects(A,Q);if(!Y||!J)return;let C=(X,G)=>{if(X instanceof HC&&G instanceof CY&&X.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))X.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:X,entity:G,started:B,colliderHandleA:A,colliderHandleB:Q});else if(X instanceof CY&&G instanceof HC&&X.hasListeners("ENTITY.BLOCK_COLLISION"))X.emit("ENTITY.BLOCK_COLLISION",{entity:X,blockType:G,started:B,colliderHandleA:A,colliderHandleB:Q});else if(X instanceof CY&&G instanceof CY&&X.hasListeners("ENTITY.ENTITY_COLLISION"))X.emit("ENTITY.ENTITY_COLLISION",{entity:X,otherEntity:G,started:B,colliderHandleA:A,colliderHandleB:Q});else if(typeof X==="function"&&(G instanceof CY||G instanceof HC))X(G,B,A,Q)};C(Y,J),C(J,Y)};_onContactForceEvent=(A)=>{let[Q,B]=this._getCollisionObjects(A.collider1(),A.collider2());if(!Q||typeof Q==="function"||!B||typeof B==="function")return;let Y={totalForce:A.totalForce(),totalForceMagnitude:A.totalForceMagnitude(),maxForceDirection:A.maxForceDirection(),maxForceMagnitude:A.maxForceMagnitude()},J=(C,X)=>{if(C instanceof HC&&X instanceof CY&&C.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))C.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:C,entity:X,contactForceData:Y});else if(C instanceof CY&&X instanceof HC&&C.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))C.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:C,blockType:X,contactForceData:Y});else if(C instanceof CY&&X instanceof CY&&C.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))C.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:C,otherEntity:X,contactForceData:Y})};J(Q,B),J(B,Q)};_getCollisionObjects(A,Q){let B=this._colliderMap.getColliderHandleBlockType(A)??this._colliderMap.getColliderHandleCollisionCallback(A)??this._colliderMap.getColliderHandleEntity(A),Y=this._colliderMap.getColliderHandleBlockType(Q)??this._colliderMap.getColliderHandleCollisionCallback(Q)??this._colliderMap.getColliderHandleEntity(Q);return[B,Y]}}var sPQ;((B)=>{B[B.POINTLIGHT=0]="POINTLIGHT";B[B.SPOTLIGHT=1]="SPOTLIGHT"})(sPQ||={});var Bo;((Z)=>{Z.DESPAWN="LIGHT.DESPAWN";Z.SET_ANGLE="LIGHT.SET_ANGLE";Z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";Z.SET_COLOR="LIGHT.SET_COLOR";Z.SET_DISTANCE="LIGHT.SET_DISTANCE";Z.SET_INTENSITY="LIGHT.SET_INTENSITY";Z.SET_OFFSET="LIGHT.SET_OFFSET";Z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";Z.SET_POSITION="LIGHT.SET_POSITION";Z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";Z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";Z.SPAWN="LIGHT.SPAWN"})(Bo||={});class Yo extends YQ{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(A){if(!!A.attachedToEntity===!!A.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");super();n.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=A.angle,this._attachedToEntity=A.attachedToEntity,this._color=A.color??{r:255,g:255,b:255},this._distance=A.distance,this._intensity=A.intensity??1,this._offset=A.offset,this._penumbra=A.penumbra,this._position=A.position,this._trackedEntity=A.trackedEntity,this._trackedPosition=A.trackedPosition,this._type=A.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(A){if(this._angle===A)return;if(this._angle=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:A})}setAttachedToEntity(A){if(!A.isSpawned)return n.error(`Light.setAttachedToEntity(): Entity ${A.id} is not spawned!`);if(this._attachedToEntity===A)return;if(this._attachedToEntity=A,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:A})}setColor(A){if(this._color.r===A.r&&this._color.g===A.g&&this._color.b===A.b)return;if(this._color=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:A})}setDistance(A){if(this._distance===A)return;if(this._distance=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:A})}setIntensity(A){if(this._intensity===A)return;if(this._intensity=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:A})}setOffset(A){if(this._offset&&this._offset.x===A.x&&this._offset.y===A.y&&this._offset.z===A.z)return;if(this._offset=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:A})}setPenumbra(A){if(this._penumbra===A)return;if(this._penumbra=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:A})}setPosition(A){if(this._position&&this._position.x===A.x&&this._position.y===A.y&&this._position.z===A.z)return;if(this._position=A,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:A})}setTrackedEntity(A){if(!A.isSpawned)return n.error(`Light.setTrackedEntity(): Entity ${A.id} is not spawned!`);if(this._trackedEntity===A)return;if(this._trackedEntity=A,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:A})}setTrackedPosition(A){if(this._trackedPosition===A)return;if(this._trackedPosition=A,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:A})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(A){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=A.lightManager.registerLight(this),this._world=A,this.emitWithWorld(A,"LIGHT.SPAWN",{light:this})}serialize(){return VQ.serializeLight(this)}}var Jo;((v)=>{v.BURST="PARTICLE_EMITTER.BURST";v.DESPAWN="PARTICLE_EMITTER.DESPAWN";v.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";v.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";v.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";v.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";v.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";v.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";v.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";v.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";v.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";v.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";v.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";v.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";v.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";v.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";v.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";v.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";v.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";v.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";v.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";v.SET_RATE="PARTICLE_EMITTER.SET_RATE";v.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";v.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";v.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";v.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";v.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";v.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";v.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";v.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";v.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";v.SPAWN="PARTICLE_EMITTER.SPAWN"})(Jo||={});class Co extends YQ{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(A){if(!!A.attachedToEntity===!!A.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");if(!A.textureUri)n.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=A.alphaTest??0.05,this._attachedToEntity=A.attachedToEntity,this._attachedToEntityNodeName=A.attachedToEntityNodeName,this._colorEnd=A.colorEnd,this._colorEndVariance=A.colorEndVariance,this._colorStart=A.colorStart,this._colorStartVariance=A.colorStartVariance,this._gravity=A.gravity,this._lifetime=A.lifetime,this._lifetimeVariance=A.lifetimeVariance,this._maxParticles=A.maxParticles,this._offset=A.offset,this._opacityEnd=A.opacityEnd,this._opacityEndVariance=A.opacityEndVariance,this._opacityStart=A.opacityStart,this._opacityStartVariance=A.opacityStartVariance,this._paused=!1,this._position=A.position,this._positionVariance=A.positionVariance,this._rate=A.rate,this._rateVariance=A.rateVariance,this._sizeEnd=A.sizeEnd,this._sizeEndVariance=A.sizeEndVariance,this._sizeStart=A.sizeStart,this._sizeStartVariance=A.sizeStartVariance,this._textureUri=A.textureUri,this._transparent=A.transparent,this._velocity=A.velocity,this._velocityVariance=A.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(A){if(this._alphaTest===A)return;if(this._alphaTest=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:A})}setAttachedToEntity(A){if(!A.isSpawned)return n.error(`ParticleEmitter.setAttachedToEntity(): Entity ${A.id} is not spawned!`);if(this._attachedToEntity===A)return;if(this._attachedToEntity=A,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:A})}setAttachedToEntityNodeName(A){if(this._attachedToEntityNodeName===A)return;if(this._attachedToEntityNodeName=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:A})}setColorEnd(A){if(this._colorEnd&&this._colorEnd.r===A.r&&this._colorEnd.g===A.g&&this._colorEnd.b===A.b)return;if(this._colorEnd=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:A})}setColorEndVariance(A){if(this._colorEndVariance&&this._colorEndVariance.r===A.r&&this._colorEndVariance.g===A.g&&this._colorEndVariance.b===A.b)return;if(this._colorEndVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:A})}setColorStart(A){if(this._colorStart&&this._colorStart.r===A.r&&this._colorStart.g===A.g&&this._colorStart.b===A.b)return;if(this._colorStart=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:A})}setColorStartVariance(A){if(this._colorStartVariance&&this._colorStartVariance.r===A.r&&this._colorStartVariance.g===A.g&&this._colorStartVariance.b===A.b)return;if(this._colorStartVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:A})}setGravity(A){if(this._gravity&&this._gravity.x===A.x&&this._gravity.y===A.y&&this._gravity.z===A.z)return;if(this._gravity=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:A})}setLifetime(A){if(this._lifetime===A)return;if(this._lifetime=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:A})}setLifetimeVariance(A){if(this._lifetimeVariance===A)return;if(this._lifetimeVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:A})}setMaxParticles(A){if(this._maxParticles===A)return;if(this._maxParticles=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:A})}setOffset(A){if(this._offset&&this._offset.x===A.x&&this._offset.y===A.y&&this._offset.z===A.z)return;if(this._offset=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:A})}setOpacityEnd(A){if(this._opacityEnd===A)return;if(this._opacityEnd=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:A})}setOpacityEndVariance(A){if(this._opacityEndVariance===A)return;if(this._opacityEndVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:A})}setOpacityStart(A){if(this._opacityStart===A)return;if(this._opacityStart=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:A})}setOpacityStartVariance(A){if(this._opacityStartVariance===A)return;if(this._opacityStartVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:A})}setPosition(A){if(this._position&&this._position.x===A.x&&this._position.y===A.y&&this._position.z===A.z)return;if(this._position=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:A})}setPositionVariance(A){if(this._positionVariance&&this._positionVariance.x===A.x&&this._positionVariance.y===A.y&&this._positionVariance.z===A.z)return;if(this._positionVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:A})}setRate(A){if(this._rate===A)return;if(this._rate=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:A})}setRateVariance(A){if(this._rateVariance===A)return;if(this._rateVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:A})}setSizeEnd(A){if(this._sizeEnd===A)return;if(this._sizeEnd=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:A})}setSizeEndVariance(A){if(this._sizeEndVariance===A)return;if(this._sizeEndVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:A})}setSizeStart(A){if(this._sizeStart===A)return;if(this._sizeStart=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:A})}setSizeStartVariance(A){if(this._sizeStartVariance===A)return;if(this._sizeStartVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:A})}setTextureUri(A){if(this._textureUri===A)return;if(this._textureUri=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:A})}setTransparent(A){if(this._transparent===A)return;if(this._transparent=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:A})}setVelocity(A){if(this._velocity&&this._velocity.x===A.x&&this._velocity.y===A.y&&this._velocity.z===A.z)return;if(this._velocity=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:A})}setVelocityVariance(A){if(this._velocityVariance&&this._velocityVariance.x===A.x&&this._velocityVariance.y===A.y&&this._velocityVariance.z===A.z)return;if(this._velocityVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:A})}burst(A){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:A})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(A){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=A.particleEmitterManager.registerParticleEmitter(this),this._world=A,this.emitWithWorld(A,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return VQ.serializeParticleEmitter(this)}}var kf0=30,_f0=Math.round(fL/kf0);class Jk{_synchronizedPlayerReliablePackets=new pY;_queuedBroadcasts=[];_queuedAudioSynchronizations=new pY;_queuedBlockSynchronizations=new pY;_queuedBlockTypeSynchronizations=new pY;_queuedChunkSynchronizations=new pY;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new pY;_queuedLightSynchronizations=new pY;_queuedParticleEmitterSynchronizations=new pY;_queuedPerPlayerSynchronizations=new pY;_queuedPerPlayerCameraSynchronizations=new pY;_queuedPerPlayerUISynchronizations=new pY;_queuedPerPlayerUIDatasSynchronizations=new pY;_queuedPlayerSynchronizations=new pY;_queuedSceneUISynchronizations=new pY;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(A){this._world=A,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}shouldSynchronize(){return this._world.loop.currentTick%_f0===0}synchronize(){let A=[],Q=[],B=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(...J);if(this._queuedEntitySynchronizations.size>0){let Y=[],J=[];for(let C of this._queuedEntitySynchronizations.valuesArray){let X=!1;for(let G in C)if(G!=="i"&&G!=="p"&&G!=="r"){X=!0;break}if(X)Y.push(C);else J.push(C)}if(J.length>0){let C=xA.createPacket(xA.outboundPackets.entitiesPacketDefinition,J,B);Q.push(C)}if(Y.length>0){let C=xA.createPacket(xA.outboundPackets.entitiesPacketDefinition,Y,B);A.push(C);for(let X of this._synchronizedPlayerReliablePackets.valuesArray)X.push(C)}}if(this._queuedAudioSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerUISynchronizations){let C=xA.createPacket(xA.outboundPackets.uiPacketDefinition,J,B);this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(C)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerUIDatasSynchronizations){let C=xA.createPacket(xA.outboundPackets.uiDatasPacketDefinition,J,B);this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(C)}if(this._queuedSceneUISynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedWorldSynchronization){let Y=xA.createPacket(xA.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerCameraSynchronizations){let C=xA.createPacket(xA.outboundPackets.cameraPacketDefinition,J,B);this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(C)}if(this._queuedPlayerSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=xA.createPacket(xA.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}a0.startSpan({operation:"send_all_packets"},()=>{for(let Y of Z1.instance.getConnectedPlayersByWorld(this._world)){let J=this._synchronizedPlayerReliablePackets.get(Y)??A;if(J.length>0)Y.connection.send(J);if(Q.length>0)Y.connection.send(Q,!1)}}),a0.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();E1.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.FREEZE_POINTER_LOCK",this._onPlayerUIFreezePointerLock),this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.pa=!0,delete Q.pl,delete Q.r};_onAudioPlay=(A)=>{let Q=A.audio.serialize();Q.pl=!0,delete Q.pa,delete Q.r,this._queuedAudioSynchronizations.set(Q.i,Q)};_onAudioPlayRestart=(A)=>{let Q=A.audio.serialize();Q.r=!0,delete Q.pa,delete Q.pl,this._queuedAudioSynchronizations.set(Q.i,Q)};_onAudioSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onAudioSetCutoffDistance=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.cd=A.cutoffDistance};_onAudioSetDetune=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.de=A.detune};_onAudioSetDistortion=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.di=A.distortion};_onAudioSetPosition=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.e=A.position?void 0:Q.e,Q.p=A.position?VQ.serializeVector(A.position):void 0};_onAudioSetPlaybackRate=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.pr=A.playbackRate};_onAudioSetReferenceDistance=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.rd=A.referenceDistance};_onAudioSetVolume=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.v=A.volume};_onBlockTypeRegistryRegisterBlockType=(A)=>{let Q=A.blockType.serialize();this._queuedBlockTypeSynchronizations.set(A.blockType.id,Q)};_onChatSendBroadcastMessage=(A)=>{let{player:Q,message:B,color:Y}=A;this._queuedBroadcasts.push(xA.createPacket(xA.outboundPackets.chatMessagesPacketDefinition,[{m:B,c:Y,p:Q?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(A)=>{let{player:Q,message:B,color:Y}=A,J=this._queuedPerPlayerSynchronizations.get(Q)??[];J.push(xA.createPacket(xA.outboundPackets.chatMessagesPacketDefinition,[{m:B,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(Q,J)};_onChunkLatticeAddChunk=(A)=>{let Q=this._createOrGetQueuedChunkSync(A.chunk);Q.b=Array.from(A.chunk.blocks),Q.rm=void 0,this._spawnedChunks.add(Q.c.join(","))};_onChunkLatticeRemoveChunk=(A)=>{let Q=this._createOrGetQueuedChunkSync(A.chunk),B=Q.c.join(",");if(this._spawnedChunks.has(B))this._queuedChunkSynchronizations.delete(B),this._spawnedChunks.delete(B);else Q.rm=!0};_onChunkLatticeSetBlock=(A)=>{let Q=this._createOrGetQueuedBlockSync(A.globalCoordinate);Q.i=A.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.ap=A.playbackRate};_onEntitySpawn=(A)=>{let Q=A.entity.serialize();this._queuedEntitySynchronizations.set(Q.i,Q),this._spawnedEntities.add(Q.i)};_onEntityDespawn=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(this._spawnedEntities.has(Q.i))this._queuedEntitySynchronizations.delete(Q.i),this._spawnedEntities.delete(Q.i);else Q.rm=!0};_onEntitySetModelHiddenNodes=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.h=Array.from(A.modelHiddenNodes)};_onEntitySetModelScale=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.sv=A.modelScale?VQ.serializeVector(A.modelScale):void 0};_onEntitySetModelShownNodes=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.sn=Array.from(A.modelShownNodes)};_onEntitySetModelTextureUri=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.mt=A.modelTextureUri};_onEntitySetOpacity=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.o=A.opacity};_onEntitySetParent=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.pe=A.parent?A.parent.id:void 0,Q.pn=A.parentNodeName};_onEntitySetTintColor=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.t=A.tintColor?VQ.serializeRgbColor(A.tintColor):void 0};_onEntityStartModelLoopedAnimations=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(Q.al=Array.from(new Set([...Q.al??[],...A.animations])),Q.as)Q.as=Q.as.filter((B)=>!A.animations.has(B)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(Q.ao=Array.from(new Set([...Q.ao??[],...A.animations])),Q.as)Q.as=Q.as.filter((B)=>!A.animations.has(B)).filter(Boolean)};_onEntityStopModelAnimations=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(Q.al)Q.al=Q.al.filter((B)=>!A.animations.has(B)).filter(Boolean);if(Q.ao)Q.ao=Q.ao.filter((B)=>!A.animations.has(B)).filter(Boolean);Q.as=Array.from(new Set([...Q.as??[],...A.animations]))};_onEntityUpdateRotation=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.r=[A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w]};_onEntityUpdatePosition=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.p=[A.position.x,A.position.y,A.position.z]};_onLightDespawn=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.rm=!0};_onLightSetAngle=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.a=A.angle};_onLightSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onLightSetColor=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.c=VQ.serializeRgbColor(A.color)};_onLightSetDistance=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.d=A.distance};_onLightSetIntensity=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.n=A.intensity};_onLightSetOffset=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onLightSetPenumbra=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.pe=A.penumbra};_onLightSetPosition=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.p=A.position?VQ.serializeVector(A.position):void 0,Q.e=A.position?void 0:Q.e};_onLightSetTrackedEntity=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.te=A.entity?A.entity.id:void 0,Q.tp=A.entity?void 0:Q.tp};_onLightSetTrackedPosition=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.tp=A.position?VQ.serializeVector(A.position):void 0,Q.te=A.position?void 0:Q.te};_onLightSpawn=(A)=>{let Q=A.light.serialize();this._queuedLightSynchronizations.set(Q.i,Q)};_onParticleEmitterBurst=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.b=A.count};_onParticleEmitterDespawn=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.rm=!0};_onParticleEmitterSetAlphaTest=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.at=A.alphaTest};_onParticleEmitterSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onParticleEmitterSetAttachedToEntityNodeName=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.en=A.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.ce=A.colorEnd?VQ.serializeRgbColor(A.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.cev=A.colorEndVariance?VQ.serializeRgbColor(A.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.cs=A.colorStart?VQ.serializeRgbColor(A.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.csv=A.colorStartVariance?VQ.serializeRgbColor(A.colorStartVariance):void 0};_onParticleEmitterSetGravity=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.g=A.gravity?VQ.serializeVector(A.gravity):void 0};_onParticleEmitterSetLifetime=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.l=A.lifetime};_onParticleEmitterSetLifetimeVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.lv=A.lifetimeVariance};_onParticleEmitterSetMaxParticles=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.mp=A.maxParticles};_onParticleEmitterSetOffset=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onParticleEmitterSetOpacityEnd=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.oe=A.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.oev=A.opacityEndVariance};_onParticleEmitterSetOpacityStart=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.os=A.opacityStart};_onParticleEmitterSetOpacityStartVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.osv=A.opacityStartVariance};_onParticleEmitterSetPaused=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.pa=A.paused};_onParticleEmitterSetPosition=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.p=A.position?VQ.serializeVector(A.position):void 0,Q.e=A.position?void 0:Q.e,Q.en=A.position?void 0:Q.en};_onParticleEmitterSetPositionVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.pv=A.positionVariance?VQ.serializeVector(A.positionVariance):void 0};_onParticleEmitterSetRate=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.r=A.rate};_onParticleEmitterSetRateVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.rv=A.rateVariance};_onParticleEmitterSetSizeEnd=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.se=A.sizeEnd};_onParticleEmitterSetSizeEndVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.sev=A.sizeEndVariance};_onParticleEmitterSetSizeStart=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.ss=A.sizeStart};_onParticleEmitterSetSizeStartVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.ssv=A.sizeStartVariance};_onParticleEmitterSetTextureUri=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.tu=A.textureUri};_onParticleEmitterSetTransparent=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.t=A.transparent};_onParticleEmitterSetVelocity=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.v=A.velocity?VQ.serializeVector(A.velocity):void 0};_onParticleEmitterSetVelocityVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.vv=A.velocityVariance?VQ.serializeVector(A.velocityVariance):void 0};_onParticleEmitterSpawn=(A)=>{let Q=A.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(Q.i,Q)};_onPlayerCameraLookAtEntity=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.pl=VQ.serializeVector(A.entity.position),delete Q.et,delete Q.pt};_onPlayerCameraLookAtPosition=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.pl=A.position?VQ.serializeVector(A.position):void 0,delete Q.et,delete Q.pt};_onPlayerCameraSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.e=A.entity.id,delete Q.p};_onPlayerCameraSetAttachedToPosition=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.p=A.position?VQ.serializeVector(A.position):void 0,delete Q.e};_onPlayerCameraSetFilmOffset=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.fo=A.filmOffset};_onPlayerCameraSetForwardOffset=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.ffo=A.forwardOffset};_onPlayerCameraSetFov=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.fv=A.fov};_onPlayerCameraSetModelHiddenNodes=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.h=Array.from(A.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.s=Array.from(A.modelShownNodes)};_onPlayerCameraSetMode=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.m=A.mode};_onPlayerCameraSetOffset=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onPlayerCameraSetShoulderAngle=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.sa=A.shoulderAngle};_onPlayerCameraSetTrackedEntity=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.et=A.entity?A.entity.id:void 0,delete Q.pl,delete Q.pt};_onPlayerCameraSetTrackedPosition=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.pt=A.position?VQ.serializeVector(A.position):void 0,delete Q.et,delete Q.pl};_onPlayerCameraSetZoom=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.z=A.zoom};_onPlayerJoinedWorld=(A)=>{let{player:Q}=A,B=this._queuedPerPlayerSynchronizations.get(Q)??[];B.push(xA.createPacket(xA.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((J)=>{if(Q.camera.attachedToEntity===void 0&&J instanceof i1&&J.player===Q)Q.camera.setAttachedToEntity(J);return J.serialize()}),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.playersPacketDefinition,Z1.instance.getConnectedPlayers().map((J)=>J.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(Q.camera);this._queuedPerPlayerCameraSynchronizations.set(Q,{...Q.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(Q,B),this._queuedPlayerSynchronizations.set(Q.id,Q.serialize())};_onPlayerLeftWorld=(A)=>{let Q=this._createOrGetQueuedPlayerSync(A.player);Q.rm=!0};_onPlayerReconnectedWorld=(A)=>{this._onPlayerJoinedWorld(A)};_onPlayerRequestNotificationPermission=(A)=>{let{player:Q}=A,B=this._queuedPerPlayerSynchronizations.get(Q)??[];B.push(xA.createPacket(xA.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(Q,B)};_onPlayerRequestSync=(A)=>{A.player.connection.send([xA.createPacket(xA.outboundPackets.syncResponsePacketDefinition,{r:A.receivedAt,s:Date.now(),p:performance.now()-A.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUIFreezePointerLock=(A)=>{let Q=this._createOrGetQueuedPlayerUISync(A.playerUI);Q.pf=A.freeze};_onPlayerUILoad=(A)=>{let Q=this._createOrGetQueuedPlayerUISync(A.playerUI);Q.u=A.htmlUri};_onPlayerUILockPointer=(A)=>{let Q=this._createOrGetQueuedPlayerUISync(A.playerUI);Q.p=A.lock};_onPlayerUISendData=(A)=>{this._createOrGetQueuedPlayerUIDatasSync(A.playerUI).push(A.data)};_onSceneUILoad=(A)=>{let Q=A.sceneUI.serialize();this._queuedSceneUISynchronizations.set(Q.i,Q),this._loadedSceneUIs.add(Q.i)};_onSceneUISetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onSceneUISetOffset=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onSceneUISetPosition=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.p=A.position?VQ.serializeVector(A.position):void 0,Q.e=A.position?void 0:Q.e};_onSceneUISetState=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.s=A.state};_onSceneUISetViewDistance=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.v=A.viewDistance};_onSceneUIUnload=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);if(this._loadedSceneUIs.has(Q.i))this._queuedSceneUISynchronizations.delete(Q.i),this._loadedSceneUIs.delete(Q.i);else Q.rm=!0};_onSimulationDebugRaycast=(A)=>{this._queuedDebugRaycastSynchronizations.push(VQ.serializePhysicsDebugRaycast(A))};_onSimulationDebugRender=(A)=>{this._queuedBroadcasts.push(xA.createPacket(xA.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(A.vertices),c:Array.from(A.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.ac=VQ.serializeRgbColor(A.color)};_onWorldSetAmbientLightIntensity=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.ai=A.intensity};_onWorldSetDirectionalLightColor=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.dc=VQ.serializeRgbColor(A.color)};_onWorldSetDirectionalLightIntensity=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.di=A.intensity};_onWorldSetDirectionalLightPosition=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.dp=VQ.serializeVector(A.position)};_onWorldSetFogColor=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.fc=VQ.serializeRgbColor(A.color)};_onWorldSetFogFar=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.ff=A.far};_onWorldSetFogNear=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.fn=A.near};_onWorldSetSkyboxIntensity=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.si=A.intensity};_onWorldSetSkyboxUri=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.s=A.uri};_createOrGetQueuedAudioSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let Q=this._queuedAudioSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedAudioSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedBlockSync(A){let{x:Q,y:B,z:Y}=A,J=`${Q},${B},${Y}`,C=this._queuedBlockSynchronizations.get(J);if(!C)C={i:0,c:[Q,B,Y]},this._queuedBlockSynchronizations.set(J,C);return C}_createOrGetQueuedChunkSync(A){if(!A.originCoordinate)n.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:Q,y:B,z:Y}=A.originCoordinate,J=`${Q},${B},${Y}`,C=this._queuedChunkSynchronizations.get(J);if(!C)C={c:[Q,B,Y]},this._queuedChunkSynchronizations.set(J,C);return C}_createOrGetQueuedEntitySync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let Q=this._queuedEntitySynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedEntitySynchronizations.set(A.id,Q);return Q}_createOrGetQueuedLightSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let Q=this._queuedLightSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedLightSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedParticleEmitterSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let Q=this._queuedParticleEmitterSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedParticleEmitterSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedPlayerSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let Q=this._queuedPlayerSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedPlayerSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedPlayerCameraSync(A){let Q=this._queuedPerPlayerCameraSynchronizations.get(A.player);if(!Q)Q={},this._queuedPerPlayerCameraSynchronizations.set(A.player,Q);return Q}_createOrGetQueuedPlayerUISync(A){let Q=this._queuedPerPlayerUISynchronizations.get(A.player);if(!Q)Q={},this._queuedPerPlayerUISynchronizations.set(A.player,Q);return Q}_createOrGetQueuedPlayerUIDatasSync(A){let Q=this._queuedPerPlayerUIDatasSynchronizations.get(A.player);if(!Q)Q=[],this._queuedPerPlayerUIDatasSynchronizations.set(A.player,Q);return Q}_createOrGetQueuedSceneUISync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let Q=this._queuedSceneUISynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedSceneUISynchronizations.set(A.id,Q);return Q}_createOrGetQueuedWorldSync(A){if(A.id!==this._world.id)n.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:A.id}}_createOrGetSynchronizedPlayerReliablePackets(A,Q){let B=this._synchronizedPlayerReliablePackets.get(A);if(!B)B=[...Q],this._synchronizedPlayerReliablePackets.set(A,B);return B}}class mL{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(A){this._world=A}get world(){return this._world}despawnEntityAttachedParticleEmitters(A){this.getAllEntityAttachedParticleEmitters(A).forEach((Q)=>{Q.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(A){return this.getAllParticleEmitters().filter((Q)=>Q.attachedToEntity===A)}registerParticleEmitter(A){if(A.id!==void 0)return A.id;let Q=this._nextParticleEmitterId;return this._particleEmitters.set(Q,A),this._nextParticleEmitterId++,Q}unregisterParticleEmitter(A){if(A.id===void 0)return;this._particleEmitters.delete(A.id)}}class uL{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(A){this._world=A}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(A){return this.getAllSceneUIs().filter((Q)=>Q.attachedToEntity===A)}getSceneUIById(A){return this._sceneUIs.get(A)}registerSceneUI(A){if(A.id!==void 0)return A.id;let Q=this._nextSceneUIId;return this._sceneUIs.set(Q,A),this._nextSceneUIId++,Q}unloadEntityAttachedSceneUIs(A){this.getAllEntityAttachedSceneUIs(A).forEach((Q)=>{Q.unload()})}unregisterSceneUI(A){if(A.id===void 0)return;this._sceneUIs.delete(A.id)}}var vf0=2,yf0=3;class dL{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(A,Q,B){this._targetTicksPerSecond=A,this._fixedTimestepS=Math.fround(1/A),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*yf0,this._tickFunction=Q,this._tickErrorCallback=B}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let A=()=>{let Q=performance.now(),B=Q-this._lastLoopTimeMs;if(this._lastLoopTimeMs=Q,this._accumulatorMs+=B,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)a0.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<vf0)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(A,this._nextTickMs)};A()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(A){try{this._tickFunction(A)}catch(Q){if(Q instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(Q);else n.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${Q}`)}}}var aPQ;((C)=>{C.START="WORLD_LOOP.START";C.STOP="WORLD_LOOP.STOP";C.TICK_START="WORLD_LOOP.TICK_START";C.TICK_END="WORLD_LOOP.TICK_END";C.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(aPQ||={});class lL extends YQ{_currentTick=0;_ticker;_world;constructor(A,Q=fL){super();this._ticker=new dL(Q,this._tick,this._onTickError),this._world=A}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(A)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:A});let Q=performance.now();a0.startSpan({operation:"world_tick",attributes:{serverPlayerCount:Z1.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{if(a0.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(A)),a0.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(A)),a0.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),this._world.networkSynchronizer.shouldSynchronize())a0.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-Q})};_onTickError=(A)=>{n.error(`WorldLoop._onTickError(): Error: ${A}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:A})}}var Xo;((Z)=>{Z.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";Z.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";Z.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";Z.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";Z.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";Z.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";Z.SET_FOG_FAR="WORLD.SET_FOG_FAR";Z.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";Z.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";Z.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";Z.START="WORLD.START";Z.STOP="WORLD.STOP"})(Xo||={});class cL extends YQ{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(A){super();if(this._id=A.id,this._ambientLightColor=A.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=A.ambientLightIntensity??1,this._directionalLightColor=A.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=A.directionalLightIntensity??3,this._directionalLightPosition=A.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=A.fogColor,this._fogFar=A.fogFar??550,this._fogNear=A.fogNear??500,this._name=A.name,this._skyboxIntensity=A.skyboxIntensity??1,this._skyboxUri=A.skyboxUri,this._tag=A.tag,this._audioManager=new qV(this),this._blockTypeRegistry=new mH(this),this._chatManager=new wD(this),this._chunkLattice=new jD(this),this._entityManager=new SD(this),this._lightManager=new xL(this),this._loop=new lL(this,A.tickRate),this._networkSynchronizer=new Jk(this),this._particleEmitterManager=new mL(this),this._sceneUIManager=new uL(this),this._simulation=new bL(this,A.tickRate,A.gravity),A.map)this.loadMap(A.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(A){if(this.chunkLattice.clear(),A.blockTypes)for(let Q of A.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:Q.id,isLiquid:Q.isLiquid,lightLevel:Q.lightLevel,name:Q.name,textureUri:Q.textureUri});if(A.blocks){let Q={};for(let B in A.blocks){let Y=A.blocks[B],J=B.indexOf(","),C=B.indexOf(",",J+1),X=Number(B.slice(0,J)),G=Number(B.slice(J+1,C)),F=Number(B.slice(C+1));if(!Q[Y])Q[Y]=[];Q[Y].push({x:X,y:G,z:F})}this.chunkLattice.initializeBlocks(Q)}if(A.entities)for(let Q in A.entities){let B=A.entities[Q],Y=Q.indexOf(","),J=Q.indexOf(",",Y+1),C=Number(Q.slice(0,Y)),X=Number(Q.slice(Y+1,J)),G=Number(Q.slice(J+1));new CY({isEnvironmental:!0,...B}).spawn(this,{x:C,y:X,z:G})}}setAmbientLightColor(A){this._ambientLightColor=A,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:A})}setAmbientLightIntensity(A){this._ambientLightIntensity=A,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:A})}setDirectionalLightColor(A){this._directionalLightColor=A,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:A})}setDirectionalLightIntensity(A){this._directionalLightIntensity=A,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:A})}setDirectionalLightPosition(A){this._directionalLightPosition=A,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:A})}setFogColor(A){this._fogColor=A,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:A})}setFogFar(A){this._fogFar=A,this.emit("WORLD.SET_FOG_FAR",{world:this,far:A})}setFogNear(A){this._fogNear=A,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:A})}setSkyboxIntensity(A){this._skyboxIntensity=A,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:A})}setSkyboxUri(A){this._skyboxUri=A,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:A})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return VQ.serializeWorld(this)}}var rPQ;((Q)=>Q.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(rPQ||={});class XW{static instance=new XW;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(A){let Q=new cL({...A,id:this._nextWorldId++});return Q.start(),this._worlds.set(Q.id,Q),YQ.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:Q}),Q}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(A){let Q=[];return this._worlds.forEach((B)=>{if(B.tag===A)Q.push(B)}),Q}getWorld(A){return this._worlds.get(A)}setDefaultWorld(A){this._defaultWorld=A}}var oPQ;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(oPQ||={});class Z1{static instance=new Z1;worldSelectionHandler;_connectionPlayers=new Map;constructor(){YQ.globalInstance.on("CONNECTION.OPENED",({connection:A,session:Q})=>{this._onConnectionOpened(A,Q)}),YQ.globalInstance.on("CONNECTION.DISCONNECTED",({connection:A})=>{this._onConnectionDisconnected(A)}),YQ.globalInstance.on("CONNECTION.RECONNECTED",({connection:A})=>{this._onConnectionReconnected(A)}),YQ.globalInstance.on("CONNECTION.CLOSED",({connection:A})=>{this._onConnectionClosed(A)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(A){return this.getConnectedPlayers().filter((Q)=>Q.world===A)}getConnectedPlayerByUsername(A){return Array.from(this._connectionPlayers.values()).find((Q)=>{return Q.username.toLowerCase()===A.toLowerCase()})}async _onConnectionOpened(A,Q){let B=new ZU(A,Q);await B.loadInitialPersistedData(),YQ.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:B});let Y=await this.worldSelectionHandler?.(B);B.joinWorld(Y??XW.instance.getDefaultWorld()),this._connectionPlayers.set(A,B)}_onConnectionDisconnected(A){let Q=this._connectionPlayers.get(A);if(Q)Q.resetInputs(),Q.camera.reset()}_onConnectionReconnected(A){let Q=this._connectionPlayers.get(A);if(Q)Q.reconnected(),YQ.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:Q});else n.warning(`PlayerManager._onConnectionReconnected(): Connection ${A.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(A){let Q=this._connectionPlayers.get(A);if(Q){if(Q.disconnect(),this._connectionPlayers.delete(A),!A.isDuplicate)f7.instance.unloadPlayerData(Q).catch((B)=>{n.warning(`PlayerManager._onConnectionClosed(): Failed to unload player data for player ${Q.id}. Error: ${B}`)});YQ.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:Q})}else n.warning(`PlayerManager._onConnectionClosed(): Connection ${A.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as hf0}from"crypto";import{Http3Server as xf0}from"@fails-components/webtransport";class pL extends YQ{static instance=new pL;_connectionIdConnections=new Map;_userIdConnections=new Map;_wss;_wts;constructor(){super();this._wss=new tb.default({noServer:!0}),this._wss.on("connection",(A,Q)=>this._onConnection(A,void 0,Q.connectionId,Q.session)),this._wts=new xf0({port:Yk,host:"0.0.0.0",secret:hf0(32).toString("hex"),cert:Qk,privKey:Bk,defaultDatagramsReadableMode:"bytes",initialStreamFlowControlWindow:1048576,streamShouldAutoTuneReceiveWindow:!0,streamFlowControlWindowSizeLimit:6291456,initialSessionFlowControlWindow:2097152,sessionShouldAutoTuneReceiveWindow:!0,sessionFlowControlWindowSizeLimit:15728640}),this._wts.setRequestCallback(this._onWebTransportRequest),this._startWebTransport().catch((A)=>{n.error(`Socket: WebTransport server failed to start or crashed while listening for sessions. Error: ${A}`)}),YQ.globalInstance.on("WEBSERVER.UPGRADE",async({req:A,socket:Q,head:B})=>{Q.on("error",()=>{}),await this._authorizeAndConnectWebsocket(A,Q,B)})}async _authorizeAndConnectWebsocket(A,Q,B){let Y=await this._authorizeConnection(A.url??"");if(Y.error){Q.end();return}A.connectionId=Y.connectionId,A.session=Y.session,Q.setNoDelay(!0),this._wss.handleUpgrade(A,Q,B,(J)=>{if(J.readyState!==WU.default.OPEN)J.once("open",()=>this._wss.emit("connection",J,A));else this._wss.emit("connection",J,A)})}async _authorizeConnection(A){let Q=A.includes("?")?A.slice(A.indexOf("?")):"",B=new URLSearchParams(Q),Y=B.get("connectionId")??void 0,J=B.get("sessionToken")??"";if(Y&&this._isValidConnectionId(Y))return{connectionId:Y};else{let C=await H8.instance.getPlayerSession(J);if(C?.error)return{error:C.error};else if(C)return{session:C}}return{}}_isValidConnectionId(A){return this._connectionIdConnections.has(A)}_onConnection=(A,Q,B,Y)=>{let J=Y?.user.id,C=B&&this._connectionIdConnections.get(B),X=J&&this._userIdConnections.get(J);if(!C&&X)X.killDuplicateConnection();if(C){if(A)C.bindWs(A);if(Q)C.bindWt(Q).catch((G)=>{n.error(`Socket._onConnection(): WebTransport binding failed. Error: ${G}`)})}else{let G=new E1(A,Q,Y);if(G.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(G.id),J&&this._userIdConnections.get(J)===G)this._userIdConnections.delete(J)}),this._connectionIdConnections.set(G.id,G),J)this._userIdConnections.set(J,G)}};_onWebTransportRequest=async({header:A})=>{let{connectionId:Q,session:B,error:Y}=await this._authorizeConnection(A[":path"]??"");return{status:Y?401:200,path:"/",userData:{connectionId:Q,session:B}}};async _startWebTransport(){this._wts.startServer();for await(let A of this._wts.sessionStream("/"))try{let{connectionId:Q,session:B}=A.userData;this._onConnection(void 0,A,Q,B)}catch(Q){n.error(`Socket._startWebTransport(): WebTransport connection failed. Error: ${Q}`)}}}Buffer.poolSize=134217728;var tPQ;((B)=>{B.START="GAMESERVER.START";B.STOP="GAMESERVER.STOP"})(tPQ||={});function ff0(A){WB.init().then(()=>{return GW.instance.blockTextureRegistry.preloadAtlas()}).then(()=>{return GW.instance.modelRegistry.preloadModels()}).then(()=>{if(A.length>0)A(GW.instance.worldManager.getDefaultWorld());else A();GW.instance.start()}).catch((Q)=>{n.fatalError(`Failed to initialize the game engine, exiting. Error: ${Q}`)})}class GW{static _instance;_blockTextureRegistry=Z7.instance;_modelRegistry=BJ.instance;_playerManager=Z1.instance;_socket=pL.instance;_worldManager=XW.instance;_webServer=UV.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new GW;return this._instance}get blockTextureRegistry(){return this._blockTextureRegistry}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){if(YQ.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start(),process.env.NODE_ENV!=="production")console.log("---"),console.log("\uD83D\uDFE2 Server Running: You can test & play it at: https://hytopia.com/play");n.enableCrashProtection()}}var iY=LA(Q$(),1);class B$ extends Float32Array{constructor(A,Q,B,Y){super([A,Q,B,Y])}get determinant(){return iY.mat2.determinant(this)}get frobeniusNorm(){return iY.mat2.frob(this)}static create(){let A=new B$(0,0,0,0);return iY.mat2.identity(A),A}static fromRotation(A){let Q=B$.create();return iY.mat2.fromRotation(Q,A),Q}static fromScaling(A){let Q=B$.create();return iY.mat2.fromScaling(Q,A),Q}add(A){return iY.mat2.add(this,this,A),this}adjoint(){return iY.mat2.adjoint(this,this),this}clone(){return new B$(this[0],this[1],this[2],this[3])}copy(A){return iY.mat2.copy(this,A),this}equals(A){return iY.mat2.equals(this,A)}exactEquals(A){return iY.mat2.exactEquals(this,A)}identity(){return iY.mat2.identity(this),this}invert(){return iY.mat2.invert(this,this),this}multiply(A){return iY.mat2.mul(this,this,A),this}multiplyScalar(A){return iY.mat2.multiplyScalar(this,this,A),this}rotate(A){return iY.mat2.rotate(this,this,A),this}subtract(A){return iY.mat2.sub(this,this,A),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return iY.mat2.transpose(this,this),this}}var r0=LA(Q$(),1);class SX extends Float32Array{constructor(A,Q,B,Y,J,C,X,G,F){super([A,Q,B,Y,J,C,X,G,F])}get determinant(){return r0.mat3.determinant(this)}get frobeniusNorm(){return r0.mat3.frob(this)}static create(){let A=new SX(0,0,0,0,0,0,0,0,0);return r0.mat3.identity(A),A}static fromMatrix4(A){let Q=SX.create();return r0.mat3.fromMat4(Q,A),Q}static fromQuaternion(A){let Q=SX.create();return r0.mat3.fromQuat(Q,A),Q}static fromRotation(A){let Q=SX.create();return r0.mat3.fromRotation(Q,A),Q}static fromScaling(A){let Q=SX.create();return r0.mat3.fromScaling(Q,A),Q}static fromTranslation(A){let Q=SX.create();return r0.mat3.fromTranslation(Q,A),Q}add(A){return r0.mat3.add(this,this,A),this}adjoint(){return r0.mat3.adjoint(this,this),this}clone(){return new SX(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(A){return r0.mat3.copy(this,A),this}equals(A){return r0.mat3.equals(this,A)}exactEquals(A){return r0.mat3.exactEquals(this,A)}identity(){return r0.mat3.identity(this),this}invert(){return r0.mat3.invert(this,this),this}multiply(A){return r0.mat3.mul(this,this,A),this}multiplyScalar(A){return r0.mat3.multiplyScalar(this,this,A),this}transformVector(A){return A.transformMatrix3(this)}projection(A,Q){return r0.mat3.projection(this,A,Q),this}rotate(A){return r0.mat3.rotate(this,this,A),this}subtract(A){return r0.mat3.sub(this,this,A),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return r0.mat3.transpose(this,this),this}}var UB=LA(Q$(),1);class N9 extends Float32Array{constructor(A,Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K,I){super([A,Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K,I])}get determinant(){return UB.mat4.determinant(this)}get frobeniusNorm(){return UB.mat4.frob(this)}static create(){let A=new N9(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return UB.mat4.identity(A),A}static fromQuaternion(A){let Q=N9.create();return UB.mat4.fromQuat(Q,A),Q}static fromRotation(A,Q){let B=N9.create();return UB.mat4.fromRotation(B,A,Q),B}static fromRotationTranslation(A,Q){let B=N9.create();return UB.mat4.fromRotationTranslation(B,A,Q),B}static fromRotationTranslationScale(A,Q,B){let Y=N9.create();return UB.mat4.fromRotationTranslationScale(Y,A,Q,B),Y}static fromRotationTranslationScaleOrigin(A,Q,B,Y){let J=N9.create();return UB.mat4.fromRotationTranslationScaleOrigin(J,A,Q,B,Y),J}static fromScaling(A){let Q=N9.create();return UB.mat4.fromScaling(Q,A),Q}static fromTranslation(A){let Q=N9.create();return UB.mat4.fromTranslation(Q,A),Q}static fromXRotation(A){let Q=N9.create();return UB.mat4.fromXRotation(Q,A),Q}static fromYRotation(A){let Q=N9.create();return UB.mat4.fromYRotation(Q,A),Q}static fromZRotation(A){let Q=N9.create();return UB.mat4.fromZRotation(Q,A),Q}add(A){return UB.mat4.add(this,this,A),this}adjoint(){return UB.mat4.adjoint(this,this),this}clone(){return new N9(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(A){return UB.mat4.copy(this,A),this}equals(A){return UB.mat4.equals(this,A)}exactEquals(A){return UB.mat4.exactEquals(this,A)}frustrum(A,Q,B,Y,J,C){return UB.mat4.frustum(this,A,Q,B,Y,J,C),this}identity(){return UB.mat4.identity(this),this}invert(){return UB.mat4.invert(this,this),this}lookAt(A,Q,B){return UB.mat4.lookAt(this,A,Q,B),this}multiply(A){return UB.mat4.mul(this,this,A),this}multiplyScalar(A){return UB.mat4.multiplyScalar(this,this,A),this}orthographic(A,Q,B,Y,J,C){return UB.mat4.ortho(this,A,Q,B,Y,J,C),this}perspective(A,Q,B,Y){return UB.mat4.perspective(this,A,Q,B,Y),this}rotate(A,Q){return UB.mat4.rotate(this,this,A,Q),this}rotateX(A){return UB.mat4.rotateX(this,this,A),this}rotateY(A){return UB.mat4.rotateY(this,this,A),this}rotateZ(A){return UB.mat4.rotateZ(this,this,A),this}scale(A){return UB.mat4.scale(this,this,A),this}subtract(A){return UB.mat4.sub(this,this,A),this}targetTo(A,Q,B){return UB.mat4.targetTo(this,A,Q,B),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(A){return UB.mat4.translate(this,this,A),this}transpose(){return UB.mat4.transpose(this,this),this}}var B0=LA(Q$(),1);class KV extends Float32Array{constructor(A,Q,B,Y){super([A,Q,B,Y])}get length(){return B0.quat.length(this)}get squaredLength(){return B0.quat.squaredLength(this)}get magnitude(){return B0.quat.length(this)}get squaredMagnitude(){return B0.quat.squaredLength(this)}get x(){return this[0]}set x(A){this[0]=A}get y(){return this[1]}set y(A){this[1]=A}get z(){return this[2]}set z(A){this[2]=A}get w(){return this[3]}set w(A){this[3]=A}static fromEuler(A,Q,B){let Y=B0.quat.fromEuler(new Float32Array(4),A,Q,B);return new KV(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(A){return new KV(A.x,A.y,A.z,A.w)}clone(){return new KV(this.x,this.y,this.z,this.w)}conjugate(){return B0.quat.conjugate(this,this),this}copy(A){return B0.quat.copy(this,A),this}dot(A){return B0.quat.dot(this,A)}exponential(){return B0.quat.exp(this,this),this}equals(A){return B0.quat.equals(this,A)}exactEquals(A){return B0.quat.exactEquals(this,A)}getAngle(A){return B0.quat.getAngle(this,A)}identity(){return B0.quat.identity(this),this}invert(){return B0.quat.invert(this,this),this}lerp(A,Q){return B0.quat.lerp(this,this,A,Q),this}logarithm(){return B0.quat.ln(this,this),this}multiply(A){return B0.quat.multiply(this,this,A),this}transformVector(A){return A.transformQuaternion(this)}normalize(){return B0.quat.normalize(this,this),this}power(A){return B0.quat.pow(this,this,A),this}randomize(){return B0.quat.random(this),this}rotateX(A){return B0.quat.rotateX(this,this,A),this}rotateY(A){return B0.quat.rotateY(this,this,A),this}rotateZ(A){return B0.quat.rotateZ(this,this,A),this}scale(A){return B0.quat.scale(this,this,A),this}setAxisAngle(A,Q){return B0.quat.setAxisAngle(this,A,Q),this}slerp(A,Q){return B0.quat.slerp(this,this,A,Q),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var vB=LA(Q$(),1);class iL extends Float32Array{constructor(A,Q){super([A,Q])}get length(){return vB.vec2.length(this)}get squaredLength(){return vB.vec2.squaredLength(this)}get magnitude(){return vB.vec2.length(this)}get squaredMagnitude(){return vB.vec2.squaredLength(this)}get x(){return this[0]}set x(A){this[0]=A}get y(){return this[1]}set y(A){this[1]=A}static create(){return new iL(0,0)}add(A){return vB.vec2.add(this,this,A),this}angle(A){return vB.vec2.angle(this,A)}ceil(){return vB.vec2.ceil(this,this),this}clone(){return new iL(this.x,this.y)}copy(A){return vB.vec2.copy(this,A),this}distance(A){return vB.vec2.distance(this,A)}divide(A){return vB.vec2.divide(this,this,A),this}dot(A){return vB.vec2.dot(this,A)}equals(A){return vB.vec2.equals(this,A)}exactEquals(A){return vB.vec2.exactEquals(this,A)}floor(){return vB.vec2.floor(this,this),this}invert(){return vB.vec2.inverse(this,this),this}lerp(A,Q){return vB.vec2.lerp(this,this,A,Q),this}max(A){return vB.vec2.max(this,this,A),this}min(A){return vB.vec2.min(this,this,A),this}multiply(A){return vB.vec2.mul(this,this,A),this}negate(){return vB.vec2.negate(this,this),this}normalize(){return vB.vec2.normalize(this,this),this}randomize(A){return vB.vec2.random(this,A),this}rotate(A,Q){return vB.vec2.rotate(this,this,A,Q),this}round(){return vB.vec2.round(this,this),this}scale(A){return vB.vec2.scale(this,this,A),this}scaleAndAdd(A,Q){return vB.vec2.scaleAndAdd(this,this,A,Q),this}subtract(A){return vB.vec2.sub(this,this,A),this}toString(){return`${this.x},${this.y}`}transformMatrix2(A){return vB.vec2.transformMat2(this,this,A),this}transformMatrix3(A){return vB.vec2.transformMat3(this,this,A),this}transformMatrix4(A){return vB.vec2.transformMat4(this,this,A),this}zero(){return vB.vec2.zero(this),this}}var RB=LA(Q$(),1);class VV extends Float32Array{constructor(A,Q,B){super([A,Q,B])}get length(){return RB.vec3.length(this)}get squaredLength(){return RB.vec3.squaredLength(this)}get magnitude(){return RB.vec3.length(this)}get squaredMagnitude(){return RB.vec3.squaredLength(this)}get x(){return this[0]}set x(A){this[0]=A}get y(){return this[1]}set y(A){this[1]=A}get z(){return this[2]}set z(A){this[2]=A}static create(){return new VV(0,0,0)}static fromVector3Like(A){return new VV(A.x,A.y,A.z)}add(A){return RB.vec3.add(this,this,A),this}ceil(){return RB.vec3.ceil(this,this),this}clone(){return new VV(this.x,this.y,this.z)}copy(A){return RB.vec3.copy(this,A),this}cross(A){return RB.vec3.cross(this,this,A),this}distance(A){return RB.vec3.distance(this,A)}divide(A){return RB.vec3.div(this,this,A),this}dot(A){return RB.vec3.dot(this,A)}equals(A){return RB.vec3.equals(this,A)}exactEquals(A){return RB.vec3.exactEquals(this,A)}floor(){return RB.vec3.floor(this,this),this}invert(){return RB.vec3.inverse(this,this),this}lerp(A,Q){return RB.vec3.lerp(this,this,A,Q),this}max(A){return RB.vec3.max(this,this,A),this}min(A){return RB.vec3.min(this,this,A),this}multiply(A){return RB.vec3.mul(this,this,A),this}negate(){return RB.vec3.negate(this,this),this}normalize(){return RB.vec3.normalize(this,this),this}randomize(A){return RB.vec3.random(this,A),this}rotateX(A,Q){return RB.vec3.rotateX(this,this,A,Q),this}rotateY(A,Q){return RB.vec3.rotateY(this,this,A,Q),this}rotateZ(A,Q){return RB.vec3.rotateZ(this,this,A,Q),this}round(){return RB.vec3.round(this,this),this}scale(A){return RB.vec3.scale(this,this,A),this}scaleAndAdd(A,Q){return RB.vec3.scaleAndAdd(this,this,A,Q),this}subtract(A){return RB.vec3.sub(this,this,A),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(A){return RB.vec3.transformMat3(this,this,A),this}transformMatrix4(A){return RB.vec3.transformMat4(this,this,A),this}transformQuaternion(A){return RB.vec3.transformQuat(this,this,A),this}zero(){return RB.vec3.zero(this),this}}var mSQ=LA(fSQ(),1);var bSQ=0.099856;class nL extends UW{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=bSQ;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(A={}){super();this.idleLoopedAnimations=A.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=A.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=A.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=A.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=A.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(A){super.spawn(A),this._startIdleAnimations(A)}face(A,Q,B){this._faceTarget=A,this.faceSpeed=Q,this._onFace=B?.faceCallback,this._onFaceComplete=B?.faceCompleteCallback}jump(A){this._jumpHeight=A}move(A,Q,B){this.moveSpeed=Q,this._moveCompletesWhenStuck=B?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=B?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=B?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=B?.moveStoppingDistance?B.moveStoppingDistance**2:bSQ,this._moveTarget=A,this._onMove=B?.moveCallback,this._onMoveComplete=B?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(A,Q){if(super.tick(A,Q),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(A),this._moveStartMoveAnimations=!1;let B=Q/1000,Y=A.position;if(A.isDynamic&&this._jumpHeight>0){let J=Math.abs(A.world.simulation.gravity.y),C=Math.sqrt(2*J*this._jumpHeight);A.applyImpulse({x:0,y:C*A.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(A)}if(this._moveTarget){let J={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},C=J.x*J.x+J.y*J.y+J.z*J.z,X=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=Q,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let G=Y.x-this._moveStuckLastPosition.x,F=Y.y-this._moveStuckLastPosition.y,W=Y.z-this._moveStuckLastPosition.z;X=Math.sqrt(G*G+F*F+W*W)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(C>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!X){let G=Math.sqrt(C),F=this.moveSpeed*B,E=Math.min(G,F)/G,$={x:Y.x+J.x*E,y:Y.y+J.y*E,z:Y.z+J.z*E};if(A.setPosition($),this._onMove)this._onMove($,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(A);if(this._onMoveComplete){let G=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,G(Y)}}}if(this._faceTarget){let J={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},C=Math.atan2(-J.x,-J.z),X=A.rotation,G=Math.atan2(2*(X.w*X.y),1-2*(X.y*X.y)),F=C-G;while(F>Math.PI)F-=2*Math.PI;while(F<-Math.PI)F+=2*Math.PI;if(Math.abs(F)>0.01&&!this._stopFaceRequested){let W=this.faceSpeed*B,E=Math.abs(F)<W?F:Math.sign(F)*W,Z=(G+E)/2,U={x:0,y:Math.fround(Math.sin(Z)),z:0,w:Math.fround(Math.cos(Z))};if(A.setRotation(U),this._onFace)this._onFace(X,U)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let W=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,W(A.rotation)}}}_startIdleAnimations(A){if(this.idleLoopedAnimationsSpeed)A.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);A.stopModelAnimations(this.moveLoopedAnimations),A.stopModelAnimations(this.jumpOneshotAnimations),A.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(A){A.stopModelAnimations(this.moveLoopedAnimations),A.stopModelAnimations(this.idleLoopedAnimations),A.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(A){if(this.moveLoopedAnimationsSpeed)A.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);A.stopModelAnimations(this.jumpOneshotAnimations),A.stopModelAnimations(this.idleLoopedAnimations),A.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Vo extends nL{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(A={}){super(A)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(A,Q,B){if(this._target=A,this._speed=Q,this._debug=B?.debug??!1,this._maxFall=B?.maxFall?-Math.abs(B.maxFall):0,this._maxJump=B?.maxJump?Math.abs(B.maxJump):0,this._maxOpenSetIterations=B?.maxOpenSetIterations??200,this._onPathfindAbort=B?.pathfindAbortCallback,this._onPathfindComplete=B?.pathfindCompleteCallback,this._onWaypointMoveComplete=B?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=B?.waypointMoveSkippedCallback,this._verticalPenalty=B?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=B?.waypointStoppingDistance,this._waypointTimeoutMs=B?.waypointTimeoutMs??2000/Q,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(A){super.attach(A),this._entity=A}detach(A){super.detach(A),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return n.error("PathfindingEntityController._calculatePath: No target or world"),!1;let A=this._entity.height,Q=this._findGroundedStart();if(!Q){if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let B={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(B.x-Q.x),J=Math.abs(B.y-Q.y),C=Math.abs(B.z-Q.z);if(Y<=2&&J<=2&&C<=2&&!this._isNeighborCoordinateBlocked(Q,B,this._entity.height))return this._waypoints=[{x:Q.x+0.5,y:Q.y+A/2,z:Q.z+0.5},{x:B.x+0.5,y:B.y+A/2,z:B.z+0.5}],!0;if(Q.x===B.x&&Q.y===B.y&&Q.z===B.z)return this._waypoints=[{x:Q.x+0.5,y:Q.y+A/2,z:Q.z+0.5}],!0;let G=this._coordinateToKey(Q),F=new Map,W=new Map([[G,0]]),E=new Map([[G,this._pathfindingHeuristic(Q,B)]]),$=new Set,Z=new mSQ.Heap((M,z)=>{let q=E.get(M[0])??1/0,N=E.get(z[0])??1/0;return q-N});Z.push([G,Q]);let U=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],K=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let z=Math.abs(Q.y+M-B.y);K.push({y:M,distanceToTargetY:z})}K.sort((M,z)=>M.distanceToTargetY-z.distanceToTargetY);let I=[...U,...K.flatMap(({y:M})=>U.map((z)=>({...z,y:M})))],V=0,H=Math.abs(B.x-Q.x)+Math.abs(B.y-Q.y)+Math.abs(B.z-Q.z),D=Math.min(this._maxOpenSetIterations,H*20);while(!Z.isEmpty()&&V<D){V++;let[M,z]=Z.pop();if(z.x===B.x&&z.y===B.y&&z.z===B.z){let L=this._reconstructPath(F,z);if(this._waypoints=L.map((w)=>({x:w.x+0.5,y:w.y+A/2,z:w.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${V} open set iterations. Start: ${this._coordinateToKey(Q)}, Target: ${this._coordinateToKey(this._target)}`);return!0}$.add(M);let q=W.get(M),N=new Map;for(let L of I){let w=`${L.x},${L.z}`,P=L.y<0;if(P&&N.has(w))continue;let _={x:z.x+L.x,y:z.y+L.y,z:z.z+L.z};if(Math.abs(B.x-_.x)+Math.abs(B.y-_.y)+Math.abs(B.z-_.z)>H*1.5)continue;let k=this._coordinateToKey(_);if($.has(k))continue;let T=this._isNeighborCoordinateBlocked(z,_,this._entity.height);if(P&&T){N.set(w,!0);continue}if(T)continue;let S=Math.abs(L.x),y=Math.abs(L.y),v=Math.abs(L.z),h=y===0?0:this._verticalPenalty,g=(Math.max(S,y,v)===1&&S+y+v>1?1.4:1)+h,m=q+g,p=W.get(k)??1/0;if(m>=p)continue;F.set(k,z),W.set(k,m);let c=m+this._pathfindingHeuristic(_,B);E.set(k,c),Z.push([k,_])}}if(V>=D){if(this._onPathfindAbort?.(),this._debug)n.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${D}), path search aborted. Start: ${this._coordinateToKey(Q)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(Q)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(A,Q){let B=[Q],Y=Q;while(A.has(this._coordinateToKey(Y)))Y=A.get(this._coordinateToKey(Y)),B.unshift(Y);return B}_coordinateToKey(A){return`${A.x},${A.y},${A.z}`}_moveToNextWaypoint(){let A=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,Q=this._waypoints[this._waypointNextIndex];if(!Q||!this._entity)return;let B=0;if(this._entity.isDynamic&&A&&Q.y>A.y){let Y=Q.y-A.y,J=Math.min(Y,this._maxJump)+0.75;this.jump(J);let C=Math.abs(this._entity.world.simulation.gravity.y),X=Math.sqrt(2*C*J),G=A.x+0.5,F=A.z+0.5,W=Q.x+0.5,E=Q.z+0.5,$=W-G,Z=E-F,U=Math.sqrt($*$+Z*Z),K=X/C,I=U/this._speed;B=Math.min(K*0.8,I)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(Q,this._speed),this.move(Q,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(Q,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(Q,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},B)}_pathfindingHeuristic(A,Q){return Math.abs(A.x-Q.x)+Math.abs(A.y-Q.y)+Math.abs(A.z-Q.z)}_isNeighborCoordinateBlocked(A,Q,B){if(!this._entity?.world)return!1;let Y=this._entity.world,J=Math.floor(Q.x),C=Math.floor(Q.y),X=Math.floor(Q.z),G=Math.floor(A.x),F=Math.floor(A.z);if(!Y.chunkLattice.hasBlock({x:J,y:C-1,z:X}))return!0;for(let W=0;W<B;W++)if(Y.chunkLattice.hasBlock({x:J,y:C+W,z:X}))return!0;if(J!==G&&X!==F)for(let W=0;W<B;W++){let E=Y.chunkLattice.hasBlock({x:J,y:C+W,z:F}),$=Y.chunkLattice.hasBlock({x:G,y:C+W,z:X});if(E||$)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:A,y:Q,z:B}=this._entity.position,Y={x:Math.floor(A),y:Math.floor(Q),z:Math.floor(B)};for(let J=0;J<=Math.abs(this._maxFall);J++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-J-1}))return{...Y,y:Y.y-J};return}}export{ff0 as startServer,rPQ as WorldManagerEvent,XW as WorldManager,aPQ as WorldLoopEvent,lL as WorldLoop,Xo as WorldEvent,cL as World,Ao as WebServerEvent,UV as WebServer,VV as Vector3,iL as Vector2,dL as Ticker,tZ as TelemetrySpanOperation,a0 as Telemetry,Qo as SimulationEvent,bL as Simulation,nL as SimpleEntityController,uL as SceneUIManager,Gm as SceneUIEvent,TD as SceneUI,N7B as SUPPORTED_INPUTS,bH as RigidBodyType,j7 as RigidBody,KV as Quaternion,Hw as PlayerUIEvent,zD as PlayerUI,oPQ as PlayerManagerEvent,Z1 as PlayerManager,RD as PlayerEvent,i1 as PlayerEntity,LVA as PlayerCameraMode,Ym as PlayerCameraEvent,qD as PlayerCamera,ZU as Player,f7 as PersistenceManager,Vo as PathfindingEntityController,mL as ParticleEmitterManager,Jo as ParticleEmitterEvent,Co as ParticleEmitter,jVA as PLAYER_ROTATION_UPDATE_THRESHOLD,wVA as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,BJ as ModelRegistry,N9 as Matrix4,SX as Matrix3,B$ as Matrix2,sPQ as LightType,xL as LightManager,Bo as LightEvent,Yo as Light,pY as IterationMap,tPQ as GameServerEvent,GW as GameServer,YQ as EventRouter,n as ErrorHandler,SD as EntityManager,PD as EntityEvent,CY as Entity,RVA as ENTITY_ROTATION_UPDATE_THRESHOLD,zVA as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,J0 as DefaultPlayerEntityController,Fm as DefaultPlayerEntity,qVA as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,P5 as CollisionGroupsBuilder,lW as CollisionGroup,c4 as ColliderShape,OD as ColliderMap,IC as Collider,ox as CoefficientCombineRule,Xm as ChunkLatticeEvent,jD as ChunkLattice,v9 as Chunk,wD as ChatManager,Jm as ChatEvent,ex as BlockTypeRegistryEvent,mH as BlockTypeRegistry,tx as BlockTypeEvent,HC as BlockType,Z7 as BlockTextureRegistry,J$ as Block,jo as BaseEntityControllerEvent,UW as BaseEntityController,qV as AudioManager,qk as AudioEvent,LV as Audio,qY as AssetsLibrary};
|
|
381
|
+
-----END PRIVATE KEY-----`;or(new rr({connections:50,pipelining:1,keepAliveTimeout:30000,keepAliveMaxTimeout:60000,connect:{timeout:1e4},headersTimeout:15000,bodyTimeout:30000}));var Yk=process.env.PORT??8080,er="0.14.28",Ao;((J)=>{J.READY="WEBSERVER.READY";J.STOPPED="WEBSERVER.STOPPED";J.ERROR="WEBSERVER.ERROR";J.UPGRADE="WEBSERVER.UPGRADE"})(Ao||={});var hL={"access-control-allow-origin":"*"},jf0=JSON.stringify({status:"OK",version:er,runtime:"node"}),Of0={".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".gltf":"model/gltf+json",".glb":"model/gltf-binary",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".ktx2":"image/ktx2",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".bin":"application/octet-stream",".wasm":"application/wasm"};class UV extends YQ{static instance=new UV;_server;_assetCache=new Map;_assetDirs=[];constructor(){super();this._assetDirs.push(tr.resolve("assets"));let A=qY.assetsLibraryPath;if(A)this._assetDirs.push(A)}start(){if(this._server)return n.warning("WebServer.start(): already started");this._server=wf0.createSecureServer({key:Bk,cert:Qk,allowHTTP1:!0}),this._server.on("stream",this._onStream),this._server.on("upgrade",this._onUpgrade),this._server.on("error",this._onError),this._server.on("close",this._onStopped),this._server.listen(Yk,this._onStarted),console.info(`WebServer.start(): Server running on port ${Yk}`)}stop(){if(!this._server)return n.warning("WebServer.stop(): not started"),Promise.resolve(!1);return new Promise((A,Q)=>{this._server.close((B)=>B?Q(B):A(!0))})}_onStarted=()=>this.emitWithGlobal("WEBSERVER.READY",{});_onStopped=()=>this.emitWithGlobal("WEBSERVER.STOPPED",{});_onError=(A)=>{n.error(`WebServer._onError(): ${A.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:A})};_onStream=(A,Q)=>{A.on("error",()=>{});let B=Q[":path"]||"/",J=(Q[":method"]||"GET")==="HEAD";if(B==="/"){A.respond({":status":200,"content-type":"application/json",...hL}),A.end(!J?jf0:void 0);return}let C=decodeURIComponent(B.split("?")[0]);if(C.includes("..")){A.respond({":status":400,...hL}),A.end();return}for(let X of this._assetDirs){let G=tr.join(X,C);if(!G.startsWith(X))continue;let F=qY.assetsLibraryPath;if(F&&G.startsWith(F))qY.instance.syncAsset(G);let W=this._assetCache.get(G);if(!W)try{let U=iPQ.statSync(G);if(!U.isFile())continue;W={size:U.size,etag:`"${U.mtimeMs.toString(36)}-${U.size.toString(36)}"`},this._assetCache.set(G,W)}catch{continue}if(Q["if-none-match"]===W.etag){A.respond({":status":304,...hL}),A.end();return}let $={":status":200,"content-type":Of0[tr.extname(G).toLowerCase()]||"application/octet-stream","content-length":W.size,etag:W.etag,"cache-control":"public, max-age=0, must-revalidate",...hL};if(J){A.respond($),A.end();return}A.respond($);let Z=iPQ.createReadStream(G);A.on("close",()=>Z.destroy()),Z.on("error",()=>A.close()),Z.pipe(A);return}A.respond({":status":404,...hL}),A.end()};_onUpgrade=(A,Q,B)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:A,socket:Q,head:B})}}var tZ;((I)=>{I.BUILD_PACKETS="build_packets";I.ENTITIES_EMIT_UPDATES="entities_emit_updates";I.ENTITIES_TICK="entities_tick";I.NETWORK_SYNCHRONIZE="network_synchronize";I.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";I.PHYSICS_CLEANUP="physics_cleanup";I.PHYSICS_STEP="physics_step";I.SEND_ALL_PACKETS="send_all_packets";I.SEND_PACKETS="send_packets";I.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";I.SERIALIZE_PACKETS="serialize_packets";I.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";I.SIMULATION_STEP="simulation_step";I.TICKER_TICK="ticker_tick";I.WORLD_TICK="world_tick"})(tZ||={});class a0{static getProcessStats(A=!1){let Q=process.memoryUsage(),B={jsHeapSizeMb:{value:Q.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:Q.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:Q.heapUsed/Q.heapTotal,unit:"percent"},processHeapSizeMb:{value:Q.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:Q.rss/1024/1024,unit:"megabyte"}};if(A)return B;return Object.fromEntries(Object.entries(B).map(([Y,J])=>[Y,J.value]))}static initializeSentry(A,Q=50){if(PU())return;DT({dsn:A,release:er,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(B)=>{return B.extra=a0.getProcessStats(),B},beforeSendTransaction:(B)=>{if(B.contexts?.trace?.op==="ticker_tick"){let J=B?.start_timestamp,C=B?.timestamp;if(!J||!C)return null;if((C-J)*1000>Q)return B.measurements=a0.getProcessStats(!0),B}return null}})}static startSpan(A,Q){if(PU())return R8({attributes:A.attributes,name:A.operation,op:A.operation},Q);else return Q()}static sentry(){return Cs}}if(!jw)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var nPQ=new VE({useFloat32:yD.ALWAYS}),Tf0=30000;class E1 extends YQ{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_isDuplicate=!1;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(A,Q,B){super();this.id=_IA(),this.onPacket(xA.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{YQ.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:B})};if(A)this.bindWs(A),Y();else if(Q)this.bindWt(Q).then(Y).catch((J)=>{this._onClose(),n.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${J}`)})}get isDuplicate(){return this._isDuplicate}static clearCachedPacketsSerializedBuffers(){if(E1._cachedPacketsSerializedBuffer.size>0)E1._cachedPacketsSerializedBuffer.clear()}static serializePackets(A){for(let B of A)if(!xA.isValidPacket(B))return n.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(B)}`);let Q=E1._cachedPacketsSerializedBuffer.get(A);if(Q)return Q;return a0.startSpan({operation:"serialize_packets",attributes:{packets:A.length,packetIds:A.map((B)=>B[0]).join(",")}},(B)=>{let Y=nPQ.pack(A);if(Y.byteLength>65536)Y=Pf0(Y,{level:1});return B?.setAttribute("serializedBytes",Y.byteLength),E1._cachedPacketsSerializedBuffer.set(A,Y),Y})}bindWs(A){this._wsBinding=!0;let Q=this._handleReconnect();if(this._cleanupConnections(),this._ws=A,this._ws.binaryType="nodebuffer",this._ws.onmessage=(B)=>this._onMessage(B.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),Q)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(A){this._wtBinding=!0;let Q=this._handleReconnect();this._cleanupConnections(),A.userData.onclose=this._onClose,A.closed.catch(()=>{}).finally(()=>A.userData.onclose?.()),this._wt=A;try{await A.ready;let B=A.incomingBidirectionalStreams.getReader();try{let{value:Y}=await B.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{B.releaseLock()}this._wtUnreliableReader=A.datagrams.readable,this._wtUnreliableWriter=A.datagrams.createWritable().getWriter()}catch{this._wtBinding=!1;return}if(this._wtBinding=!1,this._wt!==A)return;if((async()=>{if(!this._wtReliableReader)throw Error("Connection.bindWt(): Reliable reader not found.");let B=xA.createPacketBufferUnframer((Y)=>{this._onMessage(Y)});for await(let Y of this._wtReliableReader){if(A!==this._wt)return;B(Y)}})().catch(()=>{try{A?.close()}catch{}}),(async()=>{if(!this._wtUnreliableReader)throw Error("Connection.bindWt(): Unreliable reader not found.");for await(let B of this._wtUnreliableReader){if(A!==this._wt)return;this._onMessage(B)}})().catch(()=>{try{A?.close()}catch{}}),this._signalConnectionId(),Q)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(A){n.error(`Connection.disconnect(): Connection disconnect failed. Error: ${A}`)}}killDuplicateConnection(){this._isDuplicate=!0,this._cleanupConnections(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._finalizeClose()}onPacket(A,Q){this.on("CONNECTION.PACKET_RECEIVED",({packet:B})=>{if(B[0]===A)Q(B)})}send(A,Q=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let B=this._ws&&this._ws.readyState===WU.default.OPEN,Y=this._wt&&this._wt.state==="connected";if(!B&&!Y)return;a0.startSpan({operation:"send_packets"},()=>{try{let J=E1.serializePackets(A);if(!J)return;if(Y)if(Q||J.byteLength>1200)this._wtReliableWriter?.write(xA.framePacketBuffer(J)).catch(()=>{n.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(J).catch(()=>{n.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(J);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:A})}catch(J){n.error(`Connection.send(): Packet send failed. Error: ${J}`)}})}_onHeartbeatPacket=()=>{this.send([xA.createPacket(xA.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(A)=>{try{let Q=this._deserialize(A);if(!Q)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:Q})}catch(Q){n.error(`Connection._ws.onmessage(): Error: ${Q}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>this._finalizeClose(),Tf0)};_onError=(A)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:A})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill();try{this._ws?.close()}catch{}let A=this._wt;if(A)setTimeout(()=>{try{A.close()}catch{}},50);this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(A){let Q=nPQ.unpack(A);if(!Q||typeof Q!=="object"||typeof Q[0]!=="number")return n.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(Q)}`);if(!xA.isValidPacket(Q))return n.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(Q)}`);return Q}_finalizeClose(){this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()}_handleReconnect(){let A=!!this._ws||!!this._wt;if(A&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return A}_signalConnectionId(){this.send([xA.createPacket(xA.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([xA.createPacket(xA.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class xL{_lights=new Map;_nextLightId=1;_world;constructor(A){this._world=A}get world(){return this._world}despawnEntityAttachedLights(A){this.getAllEntityAttachedLights(A).forEach((Q)=>{Q.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(A){return this.getAllLights().filter((Q)=>Q.attachedToEntity===A)}registerLight(A){if(A.id!==void 0)return A.id;let Q=this._nextLightId;return this._lights.set(Q,A),this._nextLightId++,Q}unregisterLight(A){if(A.id===void 0)return;this._lights.delete(A.id)}}class pY{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(A){return this._map.get(A)}set(A,Q){let B=this._map.has(A);if(this._map.set(A,Q),!B)this._values.push(Q);else this._isDirty=!0;return this}has(A){return this._map.has(A)}delete(A){let Q=this._map.delete(A);if(Q)this._isDirty=!0;return Q}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(A,Q){this._map.forEach((B,Y)=>{A.call(Q,B,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let A of this._map.values())this._values.push(A);this._isDirty=!1}}var Sf0={x:0,y:-32,z:0},fL=60,Qo;((J)=>{J.STEP_START="SIMULATION.STEP_START";J.STEP_END="SIMULATION.STEP_END";J.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";J.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Qo||={});class bL extends YQ{_colliderMap=new OD;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(A,Q=fL,B=Sf0){super();this._rapierEventQueue=new WB.EventQueue(!0),this._rapierSimulation=new WB.World(B),this._rapierSimulation.timestep=Math.fround(1/Q),this._world=A}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(A,Q){return this._rapierSimulation.createCollider(A,Q)}createRawRigidBody(A){return this._rapierSimulation.createRigidBody(A)}enableDebugRaycasting(A){this._debugRaycastingEnabled=A}enableDebugRendering(A,Q=WB.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=A,this._debugRenderingFilterFlags=Q}getContactManifolds(A,Q){let B=[];return this._rapierSimulation.narrowPhase.contactPair(A,Q,(Y,J)=>{if(Y.numContacts()===0)return;let C=Y.normal(),X=[];for(let G=0;G<Y.numSolverContacts();G++)X.push(Y.solverContactPoint(G));B.push({contactPoints:X,localNormalA:!J?Y.localNormal1():Y.localNormal2(),localNormalB:!J?Y.localNormal2():Y.localNormal1(),normal:!J?C:{x:-C.x,y:-C.y,z:-C.z}})}),B}intersectionsWithRawShape(A,Q,B,Y={}){let J=new Set,C=[];return this._rapierSimulation.intersectionsWithShape(Q,B,A,(X)=>{let G=this._colliderMap.getColliderHandleBlockType(X.handle);if(G&&!J.has(G))return J.add(G),C.push({intersectedBlockType:G}),!0;let F=this._colliderMap.getColliderHandleEntity(X.handle);if(F&&!J.has(F))return J.add(F),C.push({intersectedEntity:F}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),C}raycast(A,Q,B,Y={}){let J=new WB.Ray(A,Q),C=this._rapierSimulation.castRay(J,B,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:A,direction:Q,length:B,hit:!!C});if(!C)return null;let X=J.pointAt(C.timeOfImpact),G=C.timeOfImpact,F=C.collider,W=this._colliderMap.getColliderHandleBlockType(F.handle);if(W)return{hitBlock:J$.fromGlobalCoordinate({x:Math.floor(X.x-(J.dir.x<0?0.0001:-0.0001)),y:Math.floor(X.y-(J.dir.y<0?0.0001:-0.0001)),z:Math.floor(X.z-(J.dir.z<0?0.0001:-0.0001))},W),hitPoint:X,hitDistance:G,origin:A,originDirection:Q};let E=this._colliderMap.getColliderHandleEntity(F.handle);if(E)return{hitEntity:E,hitPoint:X,hitDistance:G,origin:A,originDirection:Q};return null}removeRawCollider(A){this._colliderMap.queueColliderHandleForCleanup(A.handle),this._rapierSimulation.removeCollider(A,!1)}removeRawRigidBody(A){this._rapierSimulation.removeRigidBody(A)}setGravity(A){this._rapierSimulation.gravity=A}step=(A)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:A});let Q=performance.now();if(a0.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),a0.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-Q}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(A,Q,B)=>{let[Y,J]=this._getCollisionObjects(A,Q);if(!Y||!J)return;let C=(X,G)=>{if(X instanceof HC&&G instanceof CY&&X.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))X.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:X,entity:G,started:B,colliderHandleA:A,colliderHandleB:Q});else if(X instanceof CY&&G instanceof HC&&X.hasListeners("ENTITY.BLOCK_COLLISION"))X.emit("ENTITY.BLOCK_COLLISION",{entity:X,blockType:G,started:B,colliderHandleA:A,colliderHandleB:Q});else if(X instanceof CY&&G instanceof CY&&X.hasListeners("ENTITY.ENTITY_COLLISION"))X.emit("ENTITY.ENTITY_COLLISION",{entity:X,otherEntity:G,started:B,colliderHandleA:A,colliderHandleB:Q});else if(typeof X==="function"&&(G instanceof CY||G instanceof HC))X(G,B,A,Q)};C(Y,J),C(J,Y)};_onContactForceEvent=(A)=>{let[Q,B]=this._getCollisionObjects(A.collider1(),A.collider2());if(!Q||typeof Q==="function"||!B||typeof B==="function")return;let Y={totalForce:A.totalForce(),totalForceMagnitude:A.totalForceMagnitude(),maxForceDirection:A.maxForceDirection(),maxForceMagnitude:A.maxForceMagnitude()},J=(C,X)=>{if(C instanceof HC&&X instanceof CY&&C.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))C.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:C,entity:X,contactForceData:Y});else if(C instanceof CY&&X instanceof HC&&C.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))C.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:C,blockType:X,contactForceData:Y});else if(C instanceof CY&&X instanceof CY&&C.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))C.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:C,otherEntity:X,contactForceData:Y})};J(Q,B),J(B,Q)};_getCollisionObjects(A,Q){let B=this._colliderMap.getColliderHandleBlockType(A)??this._colliderMap.getColliderHandleCollisionCallback(A)??this._colliderMap.getColliderHandleEntity(A),Y=this._colliderMap.getColliderHandleBlockType(Q)??this._colliderMap.getColliderHandleCollisionCallback(Q)??this._colliderMap.getColliderHandleEntity(Q);return[B,Y]}}var sPQ;((B)=>{B[B.POINTLIGHT=0]="POINTLIGHT";B[B.SPOTLIGHT=1]="SPOTLIGHT"})(sPQ||={});var Bo;((Z)=>{Z.DESPAWN="LIGHT.DESPAWN";Z.SET_ANGLE="LIGHT.SET_ANGLE";Z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";Z.SET_COLOR="LIGHT.SET_COLOR";Z.SET_DISTANCE="LIGHT.SET_DISTANCE";Z.SET_INTENSITY="LIGHT.SET_INTENSITY";Z.SET_OFFSET="LIGHT.SET_OFFSET";Z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";Z.SET_POSITION="LIGHT.SET_POSITION";Z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";Z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";Z.SPAWN="LIGHT.SPAWN"})(Bo||={});class Yo extends YQ{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(A){if(!!A.attachedToEntity===!!A.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");super();n.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=A.angle,this._attachedToEntity=A.attachedToEntity,this._color=A.color??{r:255,g:255,b:255},this._distance=A.distance,this._intensity=A.intensity??1,this._offset=A.offset,this._penumbra=A.penumbra,this._position=A.position,this._trackedEntity=A.trackedEntity,this._trackedPosition=A.trackedPosition,this._type=A.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(A){if(this._angle===A)return;if(this._angle=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:A})}setAttachedToEntity(A){if(!A.isSpawned)return n.error(`Light.setAttachedToEntity(): Entity ${A.id} is not spawned!`);if(this._attachedToEntity===A)return;if(this._attachedToEntity=A,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:A})}setColor(A){if(this._color.r===A.r&&this._color.g===A.g&&this._color.b===A.b)return;if(this._color=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:A})}setDistance(A){if(this._distance===A)return;if(this._distance=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:A})}setIntensity(A){if(this._intensity===A)return;if(this._intensity=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:A})}setOffset(A){if(this._offset&&this._offset.x===A.x&&this._offset.y===A.y&&this._offset.z===A.z)return;if(this._offset=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:A})}setPenumbra(A){if(this._penumbra===A)return;if(this._penumbra=A,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:A})}setPosition(A){if(this._position&&this._position.x===A.x&&this._position.y===A.y&&this._position.z===A.z)return;if(this._position=A,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:A})}setTrackedEntity(A){if(!A.isSpawned)return n.error(`Light.setTrackedEntity(): Entity ${A.id} is not spawned!`);if(this._trackedEntity===A)return;if(this._trackedEntity=A,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:A})}setTrackedPosition(A){if(this._trackedPosition===A)return;if(this._trackedPosition=A,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:A})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(A){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=A.lightManager.registerLight(this),this._world=A,this.emitWithWorld(A,"LIGHT.SPAWN",{light:this})}serialize(){return VQ.serializeLight(this)}}var Jo;((v)=>{v.BURST="PARTICLE_EMITTER.BURST";v.DESPAWN="PARTICLE_EMITTER.DESPAWN";v.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";v.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";v.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";v.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";v.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";v.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";v.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";v.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";v.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";v.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";v.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";v.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";v.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";v.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";v.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";v.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";v.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";v.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";v.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";v.SET_RATE="PARTICLE_EMITTER.SET_RATE";v.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";v.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";v.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";v.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";v.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";v.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";v.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";v.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";v.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";v.SPAWN="PARTICLE_EMITTER.SPAWN"})(Jo||={});class Co extends YQ{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(A){if(!!A.attachedToEntity===!!A.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");if(!A.textureUri)n.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=A.alphaTest??0.05,this._attachedToEntity=A.attachedToEntity,this._attachedToEntityNodeName=A.attachedToEntityNodeName,this._colorEnd=A.colorEnd,this._colorEndVariance=A.colorEndVariance,this._colorStart=A.colorStart,this._colorStartVariance=A.colorStartVariance,this._gravity=A.gravity,this._lifetime=A.lifetime,this._lifetimeVariance=A.lifetimeVariance,this._maxParticles=A.maxParticles,this._offset=A.offset,this._opacityEnd=A.opacityEnd,this._opacityEndVariance=A.opacityEndVariance,this._opacityStart=A.opacityStart,this._opacityStartVariance=A.opacityStartVariance,this._paused=!1,this._position=A.position,this._positionVariance=A.positionVariance,this._rate=A.rate,this._rateVariance=A.rateVariance,this._sizeEnd=A.sizeEnd,this._sizeEndVariance=A.sizeEndVariance,this._sizeStart=A.sizeStart,this._sizeStartVariance=A.sizeStartVariance,this._textureUri=A.textureUri,this._transparent=A.transparent,this._velocity=A.velocity,this._velocityVariance=A.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(A){if(this._alphaTest===A)return;if(this._alphaTest=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:A})}setAttachedToEntity(A){if(!A.isSpawned)return n.error(`ParticleEmitter.setAttachedToEntity(): Entity ${A.id} is not spawned!`);if(this._attachedToEntity===A)return;if(this._attachedToEntity=A,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:A})}setAttachedToEntityNodeName(A){if(this._attachedToEntityNodeName===A)return;if(this._attachedToEntityNodeName=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:A})}setColorEnd(A){if(this._colorEnd&&this._colorEnd.r===A.r&&this._colorEnd.g===A.g&&this._colorEnd.b===A.b)return;if(this._colorEnd=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:A})}setColorEndVariance(A){if(this._colorEndVariance&&this._colorEndVariance.r===A.r&&this._colorEndVariance.g===A.g&&this._colorEndVariance.b===A.b)return;if(this._colorEndVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:A})}setColorStart(A){if(this._colorStart&&this._colorStart.r===A.r&&this._colorStart.g===A.g&&this._colorStart.b===A.b)return;if(this._colorStart=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:A})}setColorStartVariance(A){if(this._colorStartVariance&&this._colorStartVariance.r===A.r&&this._colorStartVariance.g===A.g&&this._colorStartVariance.b===A.b)return;if(this._colorStartVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:A})}setGravity(A){if(this._gravity&&this._gravity.x===A.x&&this._gravity.y===A.y&&this._gravity.z===A.z)return;if(this._gravity=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:A})}setLifetime(A){if(this._lifetime===A)return;if(this._lifetime=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:A})}setLifetimeVariance(A){if(this._lifetimeVariance===A)return;if(this._lifetimeVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:A})}setMaxParticles(A){if(this._maxParticles===A)return;if(this._maxParticles=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:A})}setOffset(A){if(this._offset&&this._offset.x===A.x&&this._offset.y===A.y&&this._offset.z===A.z)return;if(this._offset=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:A})}setOpacityEnd(A){if(this._opacityEnd===A)return;if(this._opacityEnd=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:A})}setOpacityEndVariance(A){if(this._opacityEndVariance===A)return;if(this._opacityEndVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:A})}setOpacityStart(A){if(this._opacityStart===A)return;if(this._opacityStart=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:A})}setOpacityStartVariance(A){if(this._opacityStartVariance===A)return;if(this._opacityStartVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:A})}setPosition(A){if(this._position&&this._position.x===A.x&&this._position.y===A.y&&this._position.z===A.z)return;if(this._position=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:A})}setPositionVariance(A){if(this._positionVariance&&this._positionVariance.x===A.x&&this._positionVariance.y===A.y&&this._positionVariance.z===A.z)return;if(this._positionVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:A})}setRate(A){if(this._rate===A)return;if(this._rate=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:A})}setRateVariance(A){if(this._rateVariance===A)return;if(this._rateVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:A})}setSizeEnd(A){if(this._sizeEnd===A)return;if(this._sizeEnd=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:A})}setSizeEndVariance(A){if(this._sizeEndVariance===A)return;if(this._sizeEndVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:A})}setSizeStart(A){if(this._sizeStart===A)return;if(this._sizeStart=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:A})}setSizeStartVariance(A){if(this._sizeStartVariance===A)return;if(this._sizeStartVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:A})}setTextureUri(A){if(this._textureUri===A)return;if(this._textureUri=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:A})}setTransparent(A){if(this._transparent===A)return;if(this._transparent=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:A})}setVelocity(A){if(this._velocity&&this._velocity.x===A.x&&this._velocity.y===A.y&&this._velocity.z===A.z)return;if(this._velocity=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:A})}setVelocityVariance(A){if(this._velocityVariance&&this._velocityVariance.x===A.x&&this._velocityVariance.y===A.y&&this._velocityVariance.z===A.z)return;if(this._velocityVariance=A,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:A})}burst(A){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:A})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(A){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=A.particleEmitterManager.registerParticleEmitter(this),this._world=A,this.emitWithWorld(A,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return VQ.serializeParticleEmitter(this)}}var kf0=30,_f0=Math.round(fL/kf0);class Jk{_synchronizedPlayerReliablePackets=new pY;_queuedBroadcasts=[];_queuedAudioSynchronizations=new pY;_queuedBlockSynchronizations=new pY;_queuedBlockTypeSynchronizations=new pY;_queuedChunkSynchronizations=new pY;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new pY;_queuedLightSynchronizations=new pY;_queuedParticleEmitterSynchronizations=new pY;_queuedPerPlayerSynchronizations=new pY;_queuedPerPlayerCameraSynchronizations=new pY;_queuedPerPlayerUISynchronizations=new pY;_queuedPerPlayerUIDatasSynchronizations=new pY;_queuedPlayerSynchronizations=new pY;_queuedSceneUISynchronizations=new pY;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(A){this._world=A,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}shouldSynchronize(){return this._world.loop.currentTick%_f0===0}synchronize(){let A=[],Q=[],B=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(...J);if(this._queuedEntitySynchronizations.size>0){let Y=[],J=[];for(let C of this._queuedEntitySynchronizations.valuesArray){let X=!1;for(let G in C)if(G!=="i"&&G!=="p"&&G!=="r"){X=!0;break}if(X)Y.push(C);else J.push(C)}if(J.length>0){let C=xA.createPacket(xA.outboundPackets.entitiesPacketDefinition,J,B);Q.push(C)}if(Y.length>0){let C=xA.createPacket(xA.outboundPackets.entitiesPacketDefinition,Y,B);A.push(C);for(let X of this._synchronizedPlayerReliablePackets.valuesArray)X.push(C)}}if(this._queuedAudioSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerUISynchronizations){let C=xA.createPacket(xA.outboundPackets.uiPacketDefinition,J,B);this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(C)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerUIDatasSynchronizations){let C=xA.createPacket(xA.outboundPackets.uiDatasPacketDefinition,J,B);this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(C)}if(this._queuedSceneUISynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedWorldSynchronization){let Y=xA.createPacket(xA.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,J]of this._queuedPerPlayerCameraSynchronizations){let C=xA.createPacket(xA.outboundPackets.cameraPacketDefinition,J,B);this._createOrGetSynchronizedPlayerReliablePackets(Y,A).push(C)}if(this._queuedPlayerSynchronizations.size>0){let Y=xA.createPacket(xA.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=xA.createPacket(xA.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,B);A.push(Y);for(let J of this._synchronizedPlayerReliablePackets.valuesArray)J.push(Y)}a0.startSpan({operation:"send_all_packets"},()=>{for(let Y of Z1.instance.getConnectedPlayersByWorld(this._world)){let J=this._synchronizedPlayerReliablePackets.get(Y)??A;if(J.length>0)Y.connection.send(J);if(Q.length>0)Y.connection.send(Q,!1)}}),a0.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();E1.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.FREEZE_POINTER_LOCK",this._onPlayerUIFreezePointerLock),this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.pa=!0,delete Q.pl,delete Q.r};_onAudioPlay=(A)=>{let Q=A.audio.serialize();Q.pl=!0,delete Q.pa,delete Q.r,this._queuedAudioSynchronizations.set(Q.i,Q)};_onAudioPlayRestart=(A)=>{let Q=A.audio.serialize();Q.r=!0,delete Q.pa,delete Q.pl,this._queuedAudioSynchronizations.set(Q.i,Q)};_onAudioSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onAudioSetCutoffDistance=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.cd=A.cutoffDistance};_onAudioSetDetune=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.de=A.detune};_onAudioSetDistortion=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.di=A.distortion};_onAudioSetPosition=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.e=A.position?void 0:Q.e,Q.p=A.position?VQ.serializeVector(A.position):void 0};_onAudioSetPlaybackRate=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.pr=A.playbackRate};_onAudioSetReferenceDistance=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.rd=A.referenceDistance};_onAudioSetVolume=(A)=>{let Q=this._createOrGetQueuedAudioSync(A.audio);Q.v=A.volume};_onBlockTypeRegistryRegisterBlockType=(A)=>{let Q=A.blockType.serialize();this._queuedBlockTypeSynchronizations.set(A.blockType.id,Q)};_onChatSendBroadcastMessage=(A)=>{let{player:Q,message:B,color:Y}=A;this._queuedBroadcasts.push(xA.createPacket(xA.outboundPackets.chatMessagesPacketDefinition,[{m:B,c:Y,p:Q?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(A)=>{let{player:Q,message:B,color:Y}=A,J=this._queuedPerPlayerSynchronizations.get(Q)??[];J.push(xA.createPacket(xA.outboundPackets.chatMessagesPacketDefinition,[{m:B,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(Q,J)};_onChunkLatticeAddChunk=(A)=>{let Q=this._createOrGetQueuedChunkSync(A.chunk);Q.b=Array.from(A.chunk.blocks),Q.rm=void 0,this._spawnedChunks.add(Q.c.join(","))};_onChunkLatticeRemoveChunk=(A)=>{let Q=this._createOrGetQueuedChunkSync(A.chunk),B=Q.c.join(",");if(this._spawnedChunks.has(B))this._queuedChunkSynchronizations.delete(B),this._spawnedChunks.delete(B);else Q.rm=!0};_onChunkLatticeSetBlock=(A)=>{let Q=this._createOrGetQueuedBlockSync(A.globalCoordinate);Q.i=A.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.ap=A.playbackRate};_onEntitySpawn=(A)=>{let Q=A.entity.serialize();this._queuedEntitySynchronizations.set(Q.i,Q),this._spawnedEntities.add(Q.i)};_onEntityDespawn=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(this._spawnedEntities.has(Q.i))this._queuedEntitySynchronizations.delete(Q.i),this._spawnedEntities.delete(Q.i);else Q.rm=!0};_onEntitySetModelHiddenNodes=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.h=Array.from(A.modelHiddenNodes)};_onEntitySetModelScale=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.sv=A.modelScale?VQ.serializeVector(A.modelScale):void 0};_onEntitySetModelShownNodes=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.sn=Array.from(A.modelShownNodes)};_onEntitySetModelTextureUri=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.mt=A.modelTextureUri};_onEntitySetOpacity=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.o=A.opacity};_onEntitySetParent=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.pe=A.parent?A.parent.id:void 0,Q.pn=A.parentNodeName};_onEntitySetTintColor=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.t=A.tintColor?VQ.serializeRgbColor(A.tintColor):void 0};_onEntityStartModelLoopedAnimations=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(Q.al=Array.from(new Set([...Q.al??[],...A.animations])),Q.as)Q.as=Q.as.filter((B)=>!A.animations.has(B)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(Q.ao=Array.from(new Set([...Q.ao??[],...A.animations])),Q.as)Q.as=Q.as.filter((B)=>!A.animations.has(B)).filter(Boolean)};_onEntityStopModelAnimations=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);if(Q.al)Q.al=Q.al.filter((B)=>!A.animations.has(B)).filter(Boolean);if(Q.ao)Q.ao=Q.ao.filter((B)=>!A.animations.has(B)).filter(Boolean);Q.as=Array.from(new Set([...Q.as??[],...A.animations]))};_onEntityUpdateRotation=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.r=[A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w]};_onEntityUpdatePosition=(A)=>{let Q=this._createOrGetQueuedEntitySync(A.entity);Q.p=[A.position.x,A.position.y,A.position.z]};_onLightDespawn=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.rm=!0};_onLightSetAngle=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.a=A.angle};_onLightSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onLightSetColor=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.c=VQ.serializeRgbColor(A.color)};_onLightSetDistance=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.d=A.distance};_onLightSetIntensity=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.n=A.intensity};_onLightSetOffset=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onLightSetPenumbra=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.pe=A.penumbra};_onLightSetPosition=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.p=A.position?VQ.serializeVector(A.position):void 0,Q.e=A.position?void 0:Q.e};_onLightSetTrackedEntity=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.te=A.entity?A.entity.id:void 0,Q.tp=A.entity?void 0:Q.tp};_onLightSetTrackedPosition=(A)=>{let Q=this._createOrGetQueuedLightSync(A.light);Q.tp=A.position?VQ.serializeVector(A.position):void 0,Q.te=A.position?void 0:Q.te};_onLightSpawn=(A)=>{let Q=A.light.serialize();this._queuedLightSynchronizations.set(Q.i,Q)};_onParticleEmitterBurst=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.b=A.count};_onParticleEmitterDespawn=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.rm=!0};_onParticleEmitterSetAlphaTest=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.at=A.alphaTest};_onParticleEmitterSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onParticleEmitterSetAttachedToEntityNodeName=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.en=A.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.ce=A.colorEnd?VQ.serializeRgbColor(A.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.cev=A.colorEndVariance?VQ.serializeRgbColor(A.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.cs=A.colorStart?VQ.serializeRgbColor(A.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.csv=A.colorStartVariance?VQ.serializeRgbColor(A.colorStartVariance):void 0};_onParticleEmitterSetGravity=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.g=A.gravity?VQ.serializeVector(A.gravity):void 0};_onParticleEmitterSetLifetime=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.l=A.lifetime};_onParticleEmitterSetLifetimeVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.lv=A.lifetimeVariance};_onParticleEmitterSetMaxParticles=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.mp=A.maxParticles};_onParticleEmitterSetOffset=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onParticleEmitterSetOpacityEnd=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.oe=A.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.oev=A.opacityEndVariance};_onParticleEmitterSetOpacityStart=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.os=A.opacityStart};_onParticleEmitterSetOpacityStartVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.osv=A.opacityStartVariance};_onParticleEmitterSetPaused=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.pa=A.paused};_onParticleEmitterSetPosition=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.p=A.position?VQ.serializeVector(A.position):void 0,Q.e=A.position?void 0:Q.e,Q.en=A.position?void 0:Q.en};_onParticleEmitterSetPositionVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.pv=A.positionVariance?VQ.serializeVector(A.positionVariance):void 0};_onParticleEmitterSetRate=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.r=A.rate};_onParticleEmitterSetRateVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.rv=A.rateVariance};_onParticleEmitterSetSizeEnd=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.se=A.sizeEnd};_onParticleEmitterSetSizeEndVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.sev=A.sizeEndVariance};_onParticleEmitterSetSizeStart=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.ss=A.sizeStart};_onParticleEmitterSetSizeStartVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.ssv=A.sizeStartVariance};_onParticleEmitterSetTextureUri=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.tu=A.textureUri};_onParticleEmitterSetTransparent=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.t=A.transparent};_onParticleEmitterSetVelocity=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.v=A.velocity?VQ.serializeVector(A.velocity):void 0};_onParticleEmitterSetVelocityVariance=(A)=>{let Q=this._createOrGetQueuedParticleEmitterSync(A.particleEmitter);Q.vv=A.velocityVariance?VQ.serializeVector(A.velocityVariance):void 0};_onParticleEmitterSpawn=(A)=>{let Q=A.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(Q.i,Q)};_onPlayerCameraLookAtEntity=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.pl=VQ.serializeVector(A.entity.position),delete Q.et,delete Q.pt};_onPlayerCameraLookAtPosition=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.pl=A.position?VQ.serializeVector(A.position):void 0,delete Q.et,delete Q.pt};_onPlayerCameraSetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.e=A.entity.id,delete Q.p};_onPlayerCameraSetAttachedToPosition=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.p=A.position?VQ.serializeVector(A.position):void 0,delete Q.e};_onPlayerCameraSetFilmOffset=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.fo=A.filmOffset};_onPlayerCameraSetForwardOffset=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.ffo=A.forwardOffset};_onPlayerCameraSetFov=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.fv=A.fov};_onPlayerCameraSetModelHiddenNodes=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.h=Array.from(A.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.s=Array.from(A.modelShownNodes)};_onPlayerCameraSetMode=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.m=A.mode};_onPlayerCameraSetOffset=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onPlayerCameraSetShoulderAngle=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.sa=A.shoulderAngle};_onPlayerCameraSetTrackedEntity=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.et=A.entity?A.entity.id:void 0,delete Q.pl,delete Q.pt};_onPlayerCameraSetTrackedPosition=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.pt=A.position?VQ.serializeVector(A.position):void 0,delete Q.et,delete Q.pl};_onPlayerCameraSetZoom=(A)=>{let Q=this._createOrGetQueuedPlayerCameraSync(A.playerCamera);Q.z=A.zoom};_onPlayerJoinedWorld=(A)=>{let{player:Q}=A,B=this._queuedPerPlayerSynchronizations.get(Q)??[];B.push(xA.createPacket(xA.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((J)=>{if(Q.camera.attachedToEntity===void 0&&J instanceof i1&&J.player===Q)Q.camera.setAttachedToEntity(J);return J.serialize()}),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((J)=>J.serialize()),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),B.push(xA.createPacket(xA.outboundPackets.playersPacketDefinition,Z1.instance.getConnectedPlayers().map((J)=>J.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(Q.camera);this._queuedPerPlayerCameraSynchronizations.set(Q,{...Q.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(Q,B),this._queuedPlayerSynchronizations.set(Q.id,Q.serialize())};_onPlayerLeftWorld=(A)=>{let Q=this._createOrGetQueuedPlayerSync(A.player);Q.rm=!0};_onPlayerReconnectedWorld=(A)=>{this._onPlayerJoinedWorld(A)};_onPlayerRequestNotificationPermission=(A)=>{let{player:Q}=A,B=this._queuedPerPlayerSynchronizations.get(Q)??[];B.push(xA.createPacket(xA.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(Q,B)};_onPlayerRequestSync=(A)=>{A.player.connection.send([xA.createPacket(xA.outboundPackets.syncResponsePacketDefinition,{r:A.receivedAt,s:Date.now(),p:performance.now()-A.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUIFreezePointerLock=(A)=>{let Q=this._createOrGetQueuedPlayerUISync(A.playerUI);Q.pf=A.freeze};_onPlayerUILoad=(A)=>{let Q=this._createOrGetQueuedPlayerUISync(A.playerUI);Q.u=A.htmlUri};_onPlayerUILockPointer=(A)=>{let Q=this._createOrGetQueuedPlayerUISync(A.playerUI);Q.p=A.lock};_onPlayerUISendData=(A)=>{this._createOrGetQueuedPlayerUIDatasSync(A.playerUI).push(A.data)};_onSceneUILoad=(A)=>{let Q=A.sceneUI.serialize();this._queuedSceneUISynchronizations.set(Q.i,Q),this._loadedSceneUIs.add(Q.i)};_onSceneUISetAttachedToEntity=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.e=A.entity?A.entity.id:void 0,Q.p=A.entity?void 0:Q.p};_onSceneUISetOffset=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.o=A.offset?VQ.serializeVector(A.offset):void 0};_onSceneUISetPosition=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.p=A.position?VQ.serializeVector(A.position):void 0,Q.e=A.position?void 0:Q.e};_onSceneUISetState=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.s=A.state};_onSceneUISetViewDistance=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);Q.v=A.viewDistance};_onSceneUIUnload=(A)=>{let Q=this._createOrGetQueuedSceneUISync(A.sceneUI);if(this._loadedSceneUIs.has(Q.i))this._queuedSceneUISynchronizations.delete(Q.i),this._loadedSceneUIs.delete(Q.i);else Q.rm=!0};_onSimulationDebugRaycast=(A)=>{this._queuedDebugRaycastSynchronizations.push(VQ.serializePhysicsDebugRaycast(A))};_onSimulationDebugRender=(A)=>{this._queuedBroadcasts.push(xA.createPacket(xA.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(A.vertices),c:Array.from(A.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.ac=VQ.serializeRgbColor(A.color)};_onWorldSetAmbientLightIntensity=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.ai=A.intensity};_onWorldSetDirectionalLightColor=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.dc=VQ.serializeRgbColor(A.color)};_onWorldSetDirectionalLightIntensity=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.di=A.intensity};_onWorldSetDirectionalLightPosition=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.dp=VQ.serializeVector(A.position)};_onWorldSetFogColor=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.fc=VQ.serializeRgbColor(A.color)};_onWorldSetFogFar=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.ff=A.far};_onWorldSetFogNear=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.fn=A.near};_onWorldSetSkyboxIntensity=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.si=A.intensity};_onWorldSetSkyboxUri=(A)=>{let Q=this._createOrGetQueuedWorldSync(A.world);Q.s=A.uri};_createOrGetQueuedAudioSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let Q=this._queuedAudioSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedAudioSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedBlockSync(A){let{x:Q,y:B,z:Y}=A,J=`${Q},${B},${Y}`,C=this._queuedBlockSynchronizations.get(J);if(!C)C={i:0,c:[Q,B,Y]},this._queuedBlockSynchronizations.set(J,C);return C}_createOrGetQueuedChunkSync(A){if(!A.originCoordinate)n.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:Q,y:B,z:Y}=A.originCoordinate,J=`${Q},${B},${Y}`,C=this._queuedChunkSynchronizations.get(J);if(!C)C={c:[Q,B,Y]},this._queuedChunkSynchronizations.set(J,C);return C}_createOrGetQueuedEntitySync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let Q=this._queuedEntitySynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedEntitySynchronizations.set(A.id,Q);return Q}_createOrGetQueuedLightSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let Q=this._queuedLightSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedLightSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedParticleEmitterSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let Q=this._queuedParticleEmitterSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedParticleEmitterSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedPlayerSync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let Q=this._queuedPlayerSynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedPlayerSynchronizations.set(A.id,Q);return Q}_createOrGetQueuedPlayerCameraSync(A){let Q=this._queuedPerPlayerCameraSynchronizations.get(A.player);if(!Q)Q={},this._queuedPerPlayerCameraSynchronizations.set(A.player,Q);return Q}_createOrGetQueuedPlayerUISync(A){let Q=this._queuedPerPlayerUISynchronizations.get(A.player);if(!Q)Q={},this._queuedPerPlayerUISynchronizations.set(A.player,Q);return Q}_createOrGetQueuedPlayerUIDatasSync(A){let Q=this._queuedPerPlayerUIDatasSynchronizations.get(A.player);if(!Q)Q=[],this._queuedPerPlayerUIDatasSynchronizations.set(A.player,Q);return Q}_createOrGetQueuedSceneUISync(A){if(A.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let Q=this._queuedSceneUISynchronizations.get(A.id);if(!Q)Q={i:A.id},this._queuedSceneUISynchronizations.set(A.id,Q);return Q}_createOrGetQueuedWorldSync(A){if(A.id!==this._world.id)n.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:A.id}}_createOrGetSynchronizedPlayerReliablePackets(A,Q){let B=this._synchronizedPlayerReliablePackets.get(A);if(!B)B=[...Q],this._synchronizedPlayerReliablePackets.set(A,B);return B}}class mL{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(A){this._world=A}get world(){return this._world}despawnEntityAttachedParticleEmitters(A){this.getAllEntityAttachedParticleEmitters(A).forEach((Q)=>{Q.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(A){return this.getAllParticleEmitters().filter((Q)=>Q.attachedToEntity===A)}registerParticleEmitter(A){if(A.id!==void 0)return A.id;let Q=this._nextParticleEmitterId;return this._particleEmitters.set(Q,A),this._nextParticleEmitterId++,Q}unregisterParticleEmitter(A){if(A.id===void 0)return;this._particleEmitters.delete(A.id)}}class uL{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(A){this._world=A}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(A){return this.getAllSceneUIs().filter((Q)=>Q.attachedToEntity===A)}getSceneUIById(A){return this._sceneUIs.get(A)}registerSceneUI(A){if(A.id!==void 0)return A.id;let Q=this._nextSceneUIId;return this._sceneUIs.set(Q,A),this._nextSceneUIId++,Q}unloadEntityAttachedSceneUIs(A){this.getAllEntityAttachedSceneUIs(A).forEach((Q)=>{Q.unload()})}unregisterSceneUI(A){if(A.id===void 0)return;this._sceneUIs.delete(A.id)}}var vf0=2,yf0=3;class dL{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(A,Q,B){this._targetTicksPerSecond=A,this._fixedTimestepS=Math.fround(1/A),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*yf0,this._tickFunction=Q,this._tickErrorCallback=B}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let A=()=>{let Q=performance.now(),B=Q-this._lastLoopTimeMs;if(this._lastLoopTimeMs=Q,this._accumulatorMs+=B,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)a0.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<vf0)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(A,this._nextTickMs)};A()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(A){try{this._tickFunction(A)}catch(Q){if(Q instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(Q);else n.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${Q}`)}}}var aPQ;((C)=>{C.START="WORLD_LOOP.START";C.STOP="WORLD_LOOP.STOP";C.TICK_START="WORLD_LOOP.TICK_START";C.TICK_END="WORLD_LOOP.TICK_END";C.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(aPQ||={});class lL extends YQ{_currentTick=0;_ticker;_world;constructor(A,Q=fL){super();this._ticker=new dL(Q,this._tick,this._onTickError),this._world=A}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(A)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:A});let Q=performance.now();a0.startSpan({operation:"world_tick",attributes:{serverPlayerCount:Z1.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{if(a0.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(A)),a0.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(A)),a0.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),this._world.networkSynchronizer.shouldSynchronize())a0.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-Q})};_onTickError=(A)=>{n.error(`WorldLoop._onTickError(): Error: ${A}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:A})}}var Xo;((Z)=>{Z.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";Z.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";Z.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";Z.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";Z.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";Z.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";Z.SET_FOG_FAR="WORLD.SET_FOG_FAR";Z.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";Z.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";Z.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";Z.START="WORLD.START";Z.STOP="WORLD.STOP"})(Xo||={});class cL extends YQ{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(A){super();if(this._id=A.id,this._ambientLightColor=A.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=A.ambientLightIntensity??1,this._directionalLightColor=A.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=A.directionalLightIntensity??3,this._directionalLightPosition=A.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=A.fogColor,this._fogFar=A.fogFar??550,this._fogNear=A.fogNear??500,this._name=A.name,this._skyboxIntensity=A.skyboxIntensity??1,this._skyboxUri=A.skyboxUri,this._tag=A.tag,this._audioManager=new qV(this),this._blockTypeRegistry=new mH(this),this._chatManager=new wD(this),this._chunkLattice=new jD(this),this._entityManager=new SD(this),this._lightManager=new xL(this),this._loop=new lL(this,A.tickRate),this._networkSynchronizer=new Jk(this),this._particleEmitterManager=new mL(this),this._sceneUIManager=new uL(this),this._simulation=new bL(this,A.tickRate,A.gravity),A.map)this.loadMap(A.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(A){if(this.chunkLattice.clear(),A.blockTypes)for(let Q of A.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:Q.id,isLiquid:Q.isLiquid,lightLevel:Q.lightLevel,name:Q.name,textureUri:Q.textureUri});if(A.blocks){let Q={};for(let B in A.blocks){let Y=A.blocks[B],J=B.indexOf(","),C=B.indexOf(",",J+1),X=Number(B.slice(0,J)),G=Number(B.slice(J+1,C)),F=Number(B.slice(C+1));if(!Q[Y])Q[Y]=[];Q[Y].push({x:X,y:G,z:F})}this.chunkLattice.initializeBlocks(Q)}if(A.entities)for(let Q in A.entities){let B=A.entities[Q],Y=Q.indexOf(","),J=Q.indexOf(",",Y+1),C=Number(Q.slice(0,Y)),X=Number(Q.slice(Y+1,J)),G=Number(Q.slice(J+1));new CY({isEnvironmental:!0,...B}).spawn(this,{x:C,y:X,z:G})}}setAmbientLightColor(A){this._ambientLightColor=A,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:A})}setAmbientLightIntensity(A){this._ambientLightIntensity=A,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:A})}setDirectionalLightColor(A){this._directionalLightColor=A,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:A})}setDirectionalLightIntensity(A){this._directionalLightIntensity=A,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:A})}setDirectionalLightPosition(A){this._directionalLightPosition=A,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:A})}setFogColor(A){this._fogColor=A,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:A})}setFogFar(A){this._fogFar=A,this.emit("WORLD.SET_FOG_FAR",{world:this,far:A})}setFogNear(A){this._fogNear=A,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:A})}setSkyboxIntensity(A){this._skyboxIntensity=A,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:A})}setSkyboxUri(A){this._skyboxUri=A,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:A})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return VQ.serializeWorld(this)}}var rPQ;((Q)=>Q.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(rPQ||={});class XW{static instance=new XW;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(A){let Q=new cL({...A,id:this._nextWorldId++});return Q.start(),this._worlds.set(Q.id,Q),YQ.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:Q}),Q}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(A){let Q=[];return this._worlds.forEach((B)=>{if(B.tag===A)Q.push(B)}),Q}getWorld(A){return this._worlds.get(A)}setDefaultWorld(A){this._defaultWorld=A}}var oPQ;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(oPQ||={});class Z1{static instance=new Z1;worldSelectionHandler;_connectionPlayers=new Map;constructor(){YQ.globalInstance.on("CONNECTION.OPENED",({connection:A,session:Q})=>{this._onConnectionOpened(A,Q)}),YQ.globalInstance.on("CONNECTION.DISCONNECTED",({connection:A})=>{this._onConnectionDisconnected(A)}),YQ.globalInstance.on("CONNECTION.RECONNECTED",({connection:A})=>{this._onConnectionReconnected(A)}),YQ.globalInstance.on("CONNECTION.CLOSED",({connection:A})=>{this._onConnectionClosed(A)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(A){return this.getConnectedPlayers().filter((Q)=>Q.world===A)}getConnectedPlayerByUsername(A){return Array.from(this._connectionPlayers.values()).find((Q)=>{return Q.username.toLowerCase()===A.toLowerCase()})}async _onConnectionOpened(A,Q){let B=new ZU(A,Q);await B.loadInitialPersistedData(),YQ.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:B});let Y=await this.worldSelectionHandler?.(B);B.joinWorld(Y??XW.instance.getDefaultWorld()),this._connectionPlayers.set(A,B)}_onConnectionDisconnected(A){let Q=this._connectionPlayers.get(A);if(Q)Q.resetInputs(),Q.camera.reset()}_onConnectionReconnected(A){let Q=this._connectionPlayers.get(A);if(Q)Q.reconnected(),YQ.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:Q});else n.warning(`PlayerManager._onConnectionReconnected(): Connection ${A.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(A){let Q=this._connectionPlayers.get(A);if(Q){if(Q.disconnect(),this._connectionPlayers.delete(A),!A.isDuplicate)f7.instance.unloadPlayerData(Q).catch((B)=>{n.warning(`PlayerManager._onConnectionClosed(): Failed to unload player data for player ${Q.id}. Error: ${B}`)});YQ.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:Q})}else n.warning(`PlayerManager._onConnectionClosed(): Connection ${A.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as hf0}from"crypto";import{Http3Server as xf0}from"@fails-components/webtransport";class pL extends YQ{static instance=new pL;_connectionIdConnections=new Map;_userIdConnections=new Map;_wss;_wts;constructor(){super();this._wss=new tb.default({noServer:!0}),this._wss.on("connection",(A,Q)=>this._onConnection(A,void 0,Q.connectionId,Q.session)),this._wts=new xf0({port:Yk,host:"0.0.0.0",secret:hf0(32).toString("hex"),cert:Qk,privKey:Bk,defaultDatagramsReadableMode:"bytes",initialStreamFlowControlWindow:1048576,streamShouldAutoTuneReceiveWindow:!0,streamFlowControlWindowSizeLimit:6291456,initialSessionFlowControlWindow:2097152,sessionShouldAutoTuneReceiveWindow:!0,sessionFlowControlWindowSizeLimit:15728640}),this._wts.setRequestCallback(this._onWebTransportRequest),this._startWebTransport().catch((A)=>{n.error(`Socket: WebTransport server failed to start or crashed while listening for sessions. Error: ${A}`)}),YQ.globalInstance.on("WEBSERVER.UPGRADE",async({req:A,socket:Q,head:B})=>{Q.on("error",()=>{}),await this._authorizeAndConnectWebsocket(A,Q,B)})}async _authorizeAndConnectWebsocket(A,Q,B){let Y=await this._authorizeConnection(A.url??"");if(Y.error){Q.end();return}A.connectionId=Y.connectionId,A.session=Y.session,Q.setNoDelay(!0),this._wss.handleUpgrade(A,Q,B,(J)=>{if(J.readyState!==WU.default.OPEN)J.once("open",()=>this._wss.emit("connection",J,A));else this._wss.emit("connection",J,A)})}async _authorizeConnection(A){let Q=A.includes("?")?A.slice(A.indexOf("?")):"",B=new URLSearchParams(Q),Y=B.get("connectionId")??void 0,J=B.get("sessionToken")??"";if(Y&&this._isValidConnectionId(Y))return{connectionId:Y};else{let C=await H8.instance.getPlayerSession(J);if(C?.error)return{error:C.error};else if(C)return{session:C}}return{}}_isValidConnectionId(A){return this._connectionIdConnections.has(A)}_onConnection=(A,Q,B,Y)=>{let J=Y?.user.id,C=B&&this._connectionIdConnections.get(B),X=J&&this._userIdConnections.get(J);if(!C&&X)X.killDuplicateConnection();if(C){if(A)C.bindWs(A);if(Q)C.bindWt(Q).catch((G)=>{n.error(`Socket._onConnection(): WebTransport binding failed. Error: ${G}`)})}else{let G=new E1(A,Q,Y);if(G.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(G.id),J&&this._userIdConnections.get(J)===G)this._userIdConnections.delete(J)}),this._connectionIdConnections.set(G.id,G),J)this._userIdConnections.set(J,G)}};_onWebTransportRequest=async({header:A})=>{let{connectionId:Q,session:B,error:Y}=await this._authorizeConnection(A[":path"]??"");return{status:Y?401:200,path:"/",userData:{connectionId:Q,session:B}}};async _startWebTransport(){this._wts.startServer();for await(let A of this._wts.sessionStream("/"))try{let{connectionId:Q,session:B}=A.userData;this._onConnection(void 0,A,Q,B)}catch(Q){n.error(`Socket._startWebTransport(): WebTransport connection failed. Error: ${Q}`)}}}Buffer.poolSize=134217728;var tPQ;((B)=>{B.START="GAMESERVER.START";B.STOP="GAMESERVER.STOP"})(tPQ||={});function ff0(A){WB.init().then(()=>{return GW.instance.blockTextureRegistry.preloadAtlas()}).then(()=>{return GW.instance.modelRegistry.preloadModels()}).then(()=>{if(A.length>0)A(GW.instance.worldManager.getDefaultWorld());else A();GW.instance.start()}).catch((Q)=>{n.fatalError(`Failed to initialize the game engine, exiting. Error: ${Q}`)})}class GW{static _instance;_blockTextureRegistry=Z7.instance;_modelRegistry=BJ.instance;_playerManager=Z1.instance;_socket=pL.instance;_worldManager=XW.instance;_webServer=UV.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new GW;return this._instance}get blockTextureRegistry(){return this._blockTextureRegistry}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){if(YQ.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start(),process.env.NODE_ENV!=="production")console.log("---"),console.log("\uD83D\uDFE2 Server Running: You can test & play it at: https://hytopia.com/play");n.enableCrashProtection()}}var iY=LA(Q$(),1);class B$ extends Float32Array{constructor(A,Q,B,Y){super([A,Q,B,Y])}get determinant(){return iY.mat2.determinant(this)}get frobeniusNorm(){return iY.mat2.frob(this)}static create(){let A=new B$(0,0,0,0);return iY.mat2.identity(A),A}static fromRotation(A){let Q=B$.create();return iY.mat2.fromRotation(Q,A),Q}static fromScaling(A){let Q=B$.create();return iY.mat2.fromScaling(Q,A),Q}add(A){return iY.mat2.add(this,this,A),this}adjoint(){return iY.mat2.adjoint(this,this),this}clone(){return new B$(this[0],this[1],this[2],this[3])}copy(A){return iY.mat2.copy(this,A),this}equals(A){return iY.mat2.equals(this,A)}exactEquals(A){return iY.mat2.exactEquals(this,A)}identity(){return iY.mat2.identity(this),this}invert(){return iY.mat2.invert(this,this),this}multiply(A){return iY.mat2.mul(this,this,A),this}multiplyScalar(A){return iY.mat2.multiplyScalar(this,this,A),this}rotate(A){return iY.mat2.rotate(this,this,A),this}subtract(A){return iY.mat2.sub(this,this,A),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return iY.mat2.transpose(this,this),this}}var r0=LA(Q$(),1);class SX extends Float32Array{constructor(A,Q,B,Y,J,C,X,G,F){super([A,Q,B,Y,J,C,X,G,F])}get determinant(){return r0.mat3.determinant(this)}get frobeniusNorm(){return r0.mat3.frob(this)}static create(){let A=new SX(0,0,0,0,0,0,0,0,0);return r0.mat3.identity(A),A}static fromMatrix4(A){let Q=SX.create();return r0.mat3.fromMat4(Q,A),Q}static fromQuaternion(A){let Q=SX.create();return r0.mat3.fromQuat(Q,A),Q}static fromRotation(A){let Q=SX.create();return r0.mat3.fromRotation(Q,A),Q}static fromScaling(A){let Q=SX.create();return r0.mat3.fromScaling(Q,A),Q}static fromTranslation(A){let Q=SX.create();return r0.mat3.fromTranslation(Q,A),Q}add(A){return r0.mat3.add(this,this,A),this}adjoint(){return r0.mat3.adjoint(this,this),this}clone(){return new SX(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(A){return r0.mat3.copy(this,A),this}equals(A){return r0.mat3.equals(this,A)}exactEquals(A){return r0.mat3.exactEquals(this,A)}identity(){return r0.mat3.identity(this),this}invert(){return r0.mat3.invert(this,this),this}multiply(A){return r0.mat3.mul(this,this,A),this}multiplyScalar(A){return r0.mat3.multiplyScalar(this,this,A),this}transformVector(A){return A.transformMatrix3(this)}projection(A,Q){return r0.mat3.projection(this,A,Q),this}rotate(A){return r0.mat3.rotate(this,this,A),this}subtract(A){return r0.mat3.sub(this,this,A),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return r0.mat3.transpose(this,this),this}}var UB=LA(Q$(),1);class N9 extends Float32Array{constructor(A,Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K,I){super([A,Q,B,Y,J,C,X,G,F,W,E,$,Z,U,K,I])}get determinant(){return UB.mat4.determinant(this)}get frobeniusNorm(){return UB.mat4.frob(this)}static create(){let A=new N9(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return UB.mat4.identity(A),A}static fromQuaternion(A){let Q=N9.create();return UB.mat4.fromQuat(Q,A),Q}static fromRotation(A,Q){let B=N9.create();return UB.mat4.fromRotation(B,A,Q),B}static fromRotationTranslation(A,Q){let B=N9.create();return UB.mat4.fromRotationTranslation(B,A,Q),B}static fromRotationTranslationScale(A,Q,B){let Y=N9.create();return UB.mat4.fromRotationTranslationScale(Y,A,Q,B),Y}static fromRotationTranslationScaleOrigin(A,Q,B,Y){let J=N9.create();return UB.mat4.fromRotationTranslationScaleOrigin(J,A,Q,B,Y),J}static fromScaling(A){let Q=N9.create();return UB.mat4.fromScaling(Q,A),Q}static fromTranslation(A){let Q=N9.create();return UB.mat4.fromTranslation(Q,A),Q}static fromXRotation(A){let Q=N9.create();return UB.mat4.fromXRotation(Q,A),Q}static fromYRotation(A){let Q=N9.create();return UB.mat4.fromYRotation(Q,A),Q}static fromZRotation(A){let Q=N9.create();return UB.mat4.fromZRotation(Q,A),Q}add(A){return UB.mat4.add(this,this,A),this}adjoint(){return UB.mat4.adjoint(this,this),this}clone(){return new N9(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(A){return UB.mat4.copy(this,A),this}equals(A){return UB.mat4.equals(this,A)}exactEquals(A){return UB.mat4.exactEquals(this,A)}frustrum(A,Q,B,Y,J,C){return UB.mat4.frustum(this,A,Q,B,Y,J,C),this}identity(){return UB.mat4.identity(this),this}invert(){return UB.mat4.invert(this,this),this}lookAt(A,Q,B){return UB.mat4.lookAt(this,A,Q,B),this}multiply(A){return UB.mat4.mul(this,this,A),this}multiplyScalar(A){return UB.mat4.multiplyScalar(this,this,A),this}orthographic(A,Q,B,Y,J,C){return UB.mat4.ortho(this,A,Q,B,Y,J,C),this}perspective(A,Q,B,Y){return UB.mat4.perspective(this,A,Q,B,Y),this}rotate(A,Q){return UB.mat4.rotate(this,this,A,Q),this}rotateX(A){return UB.mat4.rotateX(this,this,A),this}rotateY(A){return UB.mat4.rotateY(this,this,A),this}rotateZ(A){return UB.mat4.rotateZ(this,this,A),this}scale(A){return UB.mat4.scale(this,this,A),this}subtract(A){return UB.mat4.sub(this,this,A),this}targetTo(A,Q,B){return UB.mat4.targetTo(this,A,Q,B),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(A){return UB.mat4.translate(this,this,A),this}transpose(){return UB.mat4.transpose(this,this),this}}var B0=LA(Q$(),1);class KV extends Float32Array{constructor(A,Q,B,Y){super([A,Q,B,Y])}get length(){return B0.quat.length(this)}get squaredLength(){return B0.quat.squaredLength(this)}get magnitude(){return B0.quat.length(this)}get squaredMagnitude(){return B0.quat.squaredLength(this)}get x(){return this[0]}set x(A){this[0]=A}get y(){return this[1]}set y(A){this[1]=A}get z(){return this[2]}set z(A){this[2]=A}get w(){return this[3]}set w(A){this[3]=A}static fromEuler(A,Q,B){let Y=B0.quat.fromEuler(new Float32Array(4),A,Q,B);return new KV(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(A){return new KV(A.x,A.y,A.z,A.w)}clone(){return new KV(this.x,this.y,this.z,this.w)}conjugate(){return B0.quat.conjugate(this,this),this}copy(A){return B0.quat.copy(this,A),this}dot(A){return B0.quat.dot(this,A)}exponential(){return B0.quat.exp(this,this),this}equals(A){return B0.quat.equals(this,A)}exactEquals(A){return B0.quat.exactEquals(this,A)}getAngle(A){return B0.quat.getAngle(this,A)}identity(){return B0.quat.identity(this),this}invert(){return B0.quat.invert(this,this),this}lerp(A,Q){return B0.quat.lerp(this,this,A,Q),this}logarithm(){return B0.quat.ln(this,this),this}multiply(A){return B0.quat.multiply(this,this,A),this}transformVector(A){return A.transformQuaternion(this)}normalize(){return B0.quat.normalize(this,this),this}power(A){return B0.quat.pow(this,this,A),this}randomize(){return B0.quat.random(this),this}rotateX(A){return B0.quat.rotateX(this,this,A),this}rotateY(A){return B0.quat.rotateY(this,this,A),this}rotateZ(A){return B0.quat.rotateZ(this,this,A),this}scale(A){return B0.quat.scale(this,this,A),this}setAxisAngle(A,Q){return B0.quat.setAxisAngle(this,A,Q),this}slerp(A,Q){return B0.quat.slerp(this,this,A,Q),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var vB=LA(Q$(),1);class iL extends Float32Array{constructor(A,Q){super([A,Q])}get length(){return vB.vec2.length(this)}get squaredLength(){return vB.vec2.squaredLength(this)}get magnitude(){return vB.vec2.length(this)}get squaredMagnitude(){return vB.vec2.squaredLength(this)}get x(){return this[0]}set x(A){this[0]=A}get y(){return this[1]}set y(A){this[1]=A}static create(){return new iL(0,0)}add(A){return vB.vec2.add(this,this,A),this}angle(A){return vB.vec2.angle(this,A)}ceil(){return vB.vec2.ceil(this,this),this}clone(){return new iL(this.x,this.y)}copy(A){return vB.vec2.copy(this,A),this}distance(A){return vB.vec2.distance(this,A)}divide(A){return vB.vec2.divide(this,this,A),this}dot(A){return vB.vec2.dot(this,A)}equals(A){return vB.vec2.equals(this,A)}exactEquals(A){return vB.vec2.exactEquals(this,A)}floor(){return vB.vec2.floor(this,this),this}invert(){return vB.vec2.inverse(this,this),this}lerp(A,Q){return vB.vec2.lerp(this,this,A,Q),this}max(A){return vB.vec2.max(this,this,A),this}min(A){return vB.vec2.min(this,this,A),this}multiply(A){return vB.vec2.mul(this,this,A),this}negate(){return vB.vec2.negate(this,this),this}normalize(){return vB.vec2.normalize(this,this),this}randomize(A){return vB.vec2.random(this,A),this}rotate(A,Q){return vB.vec2.rotate(this,this,A,Q),this}round(){return vB.vec2.round(this,this),this}scale(A){return vB.vec2.scale(this,this,A),this}scaleAndAdd(A,Q){return vB.vec2.scaleAndAdd(this,this,A,Q),this}subtract(A){return vB.vec2.sub(this,this,A),this}toString(){return`${this.x},${this.y}`}transformMatrix2(A){return vB.vec2.transformMat2(this,this,A),this}transformMatrix3(A){return vB.vec2.transformMat3(this,this,A),this}transformMatrix4(A){return vB.vec2.transformMat4(this,this,A),this}zero(){return vB.vec2.zero(this),this}}var RB=LA(Q$(),1);class VV extends Float32Array{constructor(A,Q,B){super([A,Q,B])}get length(){return RB.vec3.length(this)}get squaredLength(){return RB.vec3.squaredLength(this)}get magnitude(){return RB.vec3.length(this)}get squaredMagnitude(){return RB.vec3.squaredLength(this)}get x(){return this[0]}set x(A){this[0]=A}get y(){return this[1]}set y(A){this[1]=A}get z(){return this[2]}set z(A){this[2]=A}static create(){return new VV(0,0,0)}static fromVector3Like(A){return new VV(A.x,A.y,A.z)}add(A){return RB.vec3.add(this,this,A),this}ceil(){return RB.vec3.ceil(this,this),this}clone(){return new VV(this.x,this.y,this.z)}copy(A){return RB.vec3.copy(this,A),this}cross(A){return RB.vec3.cross(this,this,A),this}distance(A){return RB.vec3.distance(this,A)}divide(A){return RB.vec3.div(this,this,A),this}dot(A){return RB.vec3.dot(this,A)}equals(A){return RB.vec3.equals(this,A)}exactEquals(A){return RB.vec3.exactEquals(this,A)}floor(){return RB.vec3.floor(this,this),this}invert(){return RB.vec3.inverse(this,this),this}lerp(A,Q){return RB.vec3.lerp(this,this,A,Q),this}max(A){return RB.vec3.max(this,this,A),this}min(A){return RB.vec3.min(this,this,A),this}multiply(A){return RB.vec3.mul(this,this,A),this}negate(){return RB.vec3.negate(this,this),this}normalize(){return RB.vec3.normalize(this,this),this}randomize(A){return RB.vec3.random(this,A),this}rotateX(A,Q){return RB.vec3.rotateX(this,this,A,Q),this}rotateY(A,Q){return RB.vec3.rotateY(this,this,A,Q),this}rotateZ(A,Q){return RB.vec3.rotateZ(this,this,A,Q),this}round(){return RB.vec3.round(this,this),this}scale(A){return RB.vec3.scale(this,this,A),this}scaleAndAdd(A,Q){return RB.vec3.scaleAndAdd(this,this,A,Q),this}subtract(A){return RB.vec3.sub(this,this,A),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(A){return RB.vec3.transformMat3(this,this,A),this}transformMatrix4(A){return RB.vec3.transformMat4(this,this,A),this}transformQuaternion(A){return RB.vec3.transformQuat(this,this,A),this}zero(){return RB.vec3.zero(this),this}}var mSQ=LA(fSQ(),1);var bSQ=0.099856;class nL extends UW{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=bSQ;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(A={}){super();this.idleLoopedAnimations=A.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=A.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=A.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=A.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=A.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(A){super.spawn(A),this._startIdleAnimations(A)}face(A,Q,B){this._faceTarget=A,this.faceSpeed=Q,this._onFace=B?.faceCallback,this._onFaceComplete=B?.faceCompleteCallback}jump(A){this._jumpHeight=A}move(A,Q,B){this.moveSpeed=Q,this._moveCompletesWhenStuck=B?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=B?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=B?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=B?.moveStoppingDistance?B.moveStoppingDistance**2:bSQ,this._moveTarget=A,this._onMove=B?.moveCallback,this._onMoveComplete=B?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(A,Q){if(super.tick(A,Q),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(A),this._moveStartMoveAnimations=!1;let B=Q/1000,Y=A.position;if(A.isDynamic&&this._jumpHeight>0){let J=Math.abs(A.world.simulation.gravity.y),C=Math.sqrt(2*J*this._jumpHeight);A.applyImpulse({x:0,y:C*A.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(A)}if(this._moveTarget){let J={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},C=J.x*J.x+J.y*J.y+J.z*J.z,X=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=Q,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let G=Y.x-this._moveStuckLastPosition.x,F=Y.y-this._moveStuckLastPosition.y,W=Y.z-this._moveStuckLastPosition.z;X=Math.sqrt(G*G+F*F+W*W)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(C>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!X){let G=Math.sqrt(C),F=this.moveSpeed*B,E=Math.min(G,F)/G,$={x:Y.x+J.x*E,y:Y.y+J.y*E,z:Y.z+J.z*E};if(A.setPosition($),this._onMove)this._onMove($,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(A);if(this._onMoveComplete){let G=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,G(Y)}}}if(this._faceTarget){let J={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},C=Math.atan2(-J.x,-J.z),X=A.rotation,G=Math.atan2(2*(X.w*X.y),1-2*(X.y*X.y)),F=C-G;while(F>Math.PI)F-=2*Math.PI;while(F<-Math.PI)F+=2*Math.PI;if(Math.abs(F)>0.01&&!this._stopFaceRequested){let W=this.faceSpeed*B,E=Math.abs(F)<W?F:Math.sign(F)*W,Z=(G+E)/2,U={x:0,y:Math.fround(Math.sin(Z)),z:0,w:Math.fround(Math.cos(Z))};if(A.setRotation(U),this._onFace)this._onFace(X,U)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let W=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,W(A.rotation)}}}_startIdleAnimations(A){if(this.idleLoopedAnimationsSpeed)A.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);A.stopModelAnimations(this.moveLoopedAnimations),A.stopModelAnimations(this.jumpOneshotAnimations),A.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(A){A.stopModelAnimations(this.moveLoopedAnimations),A.stopModelAnimations(this.idleLoopedAnimations),A.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(A){if(this.moveLoopedAnimationsSpeed)A.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);A.stopModelAnimations(this.jumpOneshotAnimations),A.stopModelAnimations(this.idleLoopedAnimations),A.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Vo extends nL{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(A={}){super(A)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(A,Q,B){if(this._target=A,this._speed=Q,this._debug=B?.debug??!1,this._maxFall=B?.maxFall?-Math.abs(B.maxFall):0,this._maxJump=B?.maxJump?Math.abs(B.maxJump):0,this._maxOpenSetIterations=B?.maxOpenSetIterations??200,this._onPathfindAbort=B?.pathfindAbortCallback,this._onPathfindComplete=B?.pathfindCompleteCallback,this._onWaypointMoveComplete=B?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=B?.waypointMoveSkippedCallback,this._verticalPenalty=B?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=B?.waypointStoppingDistance,this._waypointTimeoutMs=B?.waypointTimeoutMs??2000/Q,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(A){super.attach(A),this._entity=A}detach(A){super.detach(A),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return n.error("PathfindingEntityController._calculatePath: No target or world"),!1;let A=this._entity.height,Q=this._findGroundedStart();if(!Q){if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let B={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(B.x-Q.x),J=Math.abs(B.y-Q.y),C=Math.abs(B.z-Q.z);if(Y<=2&&J<=2&&C<=2&&!this._isNeighborCoordinateBlocked(Q,B,this._entity.height))return this._waypoints=[{x:Q.x+0.5,y:Q.y+A/2,z:Q.z+0.5},{x:B.x+0.5,y:B.y+A/2,z:B.z+0.5}],!0;if(Q.x===B.x&&Q.y===B.y&&Q.z===B.z)return this._waypoints=[{x:Q.x+0.5,y:Q.y+A/2,z:Q.z+0.5}],!0;let G=this._coordinateToKey(Q),F=new Map,W=new Map([[G,0]]),E=new Map([[G,this._pathfindingHeuristic(Q,B)]]),$=new Set,Z=new mSQ.Heap((M,z)=>{let q=E.get(M[0])??1/0,N=E.get(z[0])??1/0;return q-N});Z.push([G,Q]);let U=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],K=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let z=Math.abs(Q.y+M-B.y);K.push({y:M,distanceToTargetY:z})}K.sort((M,z)=>M.distanceToTargetY-z.distanceToTargetY);let I=[...U,...K.flatMap(({y:M})=>U.map((z)=>({...z,y:M})))],V=0,H=Math.abs(B.x-Q.x)+Math.abs(B.y-Q.y)+Math.abs(B.z-Q.z),D=Math.min(this._maxOpenSetIterations,H*20);while(!Z.isEmpty()&&V<D){V++;let[M,z]=Z.pop();if(z.x===B.x&&z.y===B.y&&z.z===B.z){let L=this._reconstructPath(F,z);if(this._waypoints=L.map((w)=>({x:w.x+0.5,y:w.y+A/2,z:w.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${V} open set iterations. Start: ${this._coordinateToKey(Q)}, Target: ${this._coordinateToKey(this._target)}`);return!0}$.add(M);let q=W.get(M),N=new Map;for(let L of I){let w=`${L.x},${L.z}`,P=L.y<0;if(P&&N.has(w))continue;let _={x:z.x+L.x,y:z.y+L.y,z:z.z+L.z};if(Math.abs(B.x-_.x)+Math.abs(B.y-_.y)+Math.abs(B.z-_.z)>H*1.5)continue;let k=this._coordinateToKey(_);if($.has(k))continue;let T=this._isNeighborCoordinateBlocked(z,_,this._entity.height);if(P&&T){N.set(w,!0);continue}if(T)continue;let S=Math.abs(L.x),y=Math.abs(L.y),v=Math.abs(L.z),h=y===0?0:this._verticalPenalty,g=(Math.max(S,y,v)===1&&S+y+v>1?1.4:1)+h,m=q+g,p=W.get(k)??1/0;if(m>=p)continue;F.set(k,z),W.set(k,m);let c=m+this._pathfindingHeuristic(_,B);E.set(k,c),Z.push([k,_])}}if(V>=D){if(this._onPathfindAbort?.(),this._debug)n.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${D}), path search aborted. Start: ${this._coordinateToKey(Q)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(Q)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(A,Q){let B=[Q],Y=Q;while(A.has(this._coordinateToKey(Y)))Y=A.get(this._coordinateToKey(Y)),B.unshift(Y);return B}_coordinateToKey(A){return`${A.x},${A.y},${A.z}`}_moveToNextWaypoint(){let A=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,Q=this._waypoints[this._waypointNextIndex];if(!Q||!this._entity)return;let B=0;if(this._entity.isDynamic&&A&&Q.y>A.y){let Y=Q.y-A.y,J=Math.min(Y,this._maxJump)+0.75;this.jump(J);let C=Math.abs(this._entity.world.simulation.gravity.y),X=Math.sqrt(2*C*J),G=A.x+0.5,F=A.z+0.5,W=Q.x+0.5,E=Q.z+0.5,$=W-G,Z=E-F,U=Math.sqrt($*$+Z*Z),K=X/C,I=U/this._speed;B=Math.min(K*0.8,I)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(Q,this._speed),this.move(Q,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(Q,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(Q,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},B)}_pathfindingHeuristic(A,Q){return Math.abs(A.x-Q.x)+Math.abs(A.y-Q.y)+Math.abs(A.z-Q.z)}_isNeighborCoordinateBlocked(A,Q,B){if(!this._entity?.world)return!1;let Y=this._entity.world,J=Math.floor(Q.x),C=Math.floor(Q.y),X=Math.floor(Q.z),G=Math.floor(A.x),F=Math.floor(A.z);if(!Y.chunkLattice.hasBlock({x:J,y:C-1,z:X}))return!0;for(let W=0;W<B;W++)if(Y.chunkLattice.hasBlock({x:J,y:C+W,z:X}))return!0;if(J!==G&&X!==F)for(let W=0;W<B;W++){let E=Y.chunkLattice.hasBlock({x:J,y:C+W,z:F}),$=Y.chunkLattice.hasBlock({x:G,y:C+W,z:X});if(E||$)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:A,y:Q,z:B}=this._entity.position,Y={x:Math.floor(A),y:Math.floor(Q),z:Math.floor(B)};for(let J=0;J<=Math.abs(this._maxFall);J++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-J-1}))return{...Y,y:Y.y-J};return}}export{ff0 as startServer,rPQ as WorldManagerEvent,XW as WorldManager,aPQ as WorldLoopEvent,lL as WorldLoop,Xo as WorldEvent,cL as World,Ao as WebServerEvent,UV as WebServer,VV as Vector3,iL as Vector2,dL as Ticker,tZ as TelemetrySpanOperation,a0 as Telemetry,Qo as SimulationEvent,bL as Simulation,nL as SimpleEntityController,uL as SceneUIManager,Gm as SceneUIEvent,TD as SceneUI,N7B as SUPPORTED_INPUTS,bH as RigidBodyType,j7 as RigidBody,KV as Quaternion,Hw as PlayerUIEvent,zD as PlayerUI,oPQ as PlayerManagerEvent,Z1 as PlayerManager,RD as PlayerEvent,i1 as PlayerEntity,LVA as PlayerCameraMode,Ym as PlayerCameraEvent,qD as PlayerCamera,ZU as Player,f7 as PersistenceManager,Vo as PathfindingEntityController,mL as ParticleEmitterManager,Jo as ParticleEmitterEvent,Co as ParticleEmitter,jVA as PLAYER_ROTATION_UPDATE_THRESHOLD,wVA as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,BJ as ModelRegistry,N9 as Matrix4,SX as Matrix3,B$ as Matrix2,sPQ as LightType,xL as LightManager,Bo as LightEvent,Yo as Light,pY as IterationMap,tPQ as GameServerEvent,GW as GameServer,YQ as EventRouter,n as ErrorHandler,SD as EntityManager,PD as EntityEvent,CY as Entity,RVA as ENTITY_ROTATION_UPDATE_THRESHOLD,zVA as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,J0 as DefaultPlayerEntityController,Fm as DefaultPlayerEntity,qVA as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,P5 as CollisionGroupsBuilder,lW as CollisionGroup,c4 as ColliderShape,OD as ColliderMap,IC as Collider,ox as CoefficientCombineRule,Xm as ChunkLatticeEvent,jD as ChunkLattice,v9 as Chunk,wD as ChatManager,Jm as ChatEvent,ex as BlockTypeRegistryEvent,mH as BlockTypeRegistry,tx as BlockTypeEvent,HC as BlockType,Z7 as BlockTextureRegistry,J$ as Block,jo as BaseEntityControllerEvent,UW as BaseEntityController,qV as AudioManager,qk as AudioEvent,LV as Audio,qY as AssetsLibrary};
|