hytopia 0.6.13 → 0.6.15

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/node-server.mjs CHANGED
@@ -367,7 +367,7 @@ ${G}${I8.bold}==========[ RUNTIME ${W?"WARNING":"ERROR"} #${V} | ${K} ]=========
367
367
  `);else console.log("The server encountered a recoverable error and did not crash."),console.log(`You should fix this to prevent undefined-like return values and unexpected behavior.
368
368
  `);let F=Q?"FATAL ERROR":W?"WARNING":"ERROR";if(H(`${G}${I8.bold}⚠️ ${F}:${I8.reset} ${I8.bold}${J}${I8.reset}`),Y)H(`${I8.cyan}ℹ️ CONTEXT:${I8.reset} ${Y}`);let z=X.stack?.split(`
369
369
  `)??[];if(z.length>1)H(`${I8.cyan}\uD83D\uDD0D STACK TRACE:${I8.reset}`),z.slice(1).forEach((q)=>{let L=q.trim().replace(/at\s+([^\s]+)/,`at ${I8.green}$1${I8.reset}`).replace(/\(([^:]+):(\d+):(\d+)\)/,`(${I8.cyan}$1${I8.reset}:${I8.yellow}$2:$3${I8.reset})`);H(` ${L}`)});console.log(`${G}${I8.bold}=================================================${I8.reset}
370
- `)}}var sy=r(ay(),1);var oy=sy.default;class j0{static globalInstance=new j0;_emitter=new oy;_finalListeners={};emit(Z,J){let X=!1;try{if(X=this._emitter.emit(Z,J),Z in this._finalListeners)this._finalListeners[Z](J),X=!0}catch(Y){console.error(`EventRouter.emit(): Error emitting event "${Z}":`,Y)}return X}emitWithGlobal(Z,J){this.emit(Z,J),j0.globalInstance.emit(Z,J)}emitWithWorld(Z,J,X){this.emit(J,X),Z.emit(J,X)}final(Z,J){if(this._finalListeners[Z]&&J!==this._finalListeners[Z])return u.error(`EventRouter.final(): Listener for event type "${Z}" already exists. It must be removed explicitly with .off() before a different final listener can be set.`);this._finalListeners[Z]=J}hasListeners(Z){return this._emitter.listenerCount(Z)>0}listeners(Z){return[...this._emitter.listeners(Z),...this._finalListeners[Z]?[this._finalListeners[Z]]:[]]}listenerCount(Z){return this._emitter.listenerCount(Z)+(this._finalListeners[Z]?1:0)}off(Z,J){if(this._emitter.removeListener(Z,J),this._finalListeners[Z]===J)delete this._finalListeners[Z]}offAll(Z){if(this._emitter.removeAllListeners(Z),Z)delete this._finalListeners[Z];else this._finalListeners={}}on(Z,J){this._emitter.addListener(Z,J)}once(Z,J){this._emitter.once(Z,J)}}class p0{static serializeAudio(Z){if(Z.id===void 0)u.fatalError(`Serializer.serializeAudio(): Audio ${Z.uri} is not playing!`);if(Z.attachedToEntity&&!Z.attachedToEntity.isSpawned)u.warning(`Serializer.serializeAudio(): Audio ${Z.uri} is attached to an entity that is not spawned or was recently despawned, reverting to unattached!`);return{i:Z.id,a:Z.uri,cd:Z.cutoffDistance,d:Z.duration,de:Z.detune,di:Z.distortion,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,l:Z.loop,o:Z.offset,p:Z.position?this.serializeVector(Z.position):void 0,pa:!Z.isPlaying,pl:Z.isPlaying,pr:Z.playbackRate,rd:Z.referenceDistance,s:Z.startTick,v:Z.volume}}static serializeBlockType(Z){return{i:Z.id,l:Z.isLiquid,n:Z.name,t:Z.textureUri}}static serializeBlockTypeRegistry(Z){return Z.getAllBlockTypes().map((J)=>this.serializeBlockType(J))}static serializeChunk(Z){if(!Z.world||!Z.originCoordinate)u.fatalError("Serializer.serializeChunk(): Chunk is not in a world");return{c:this.serializeVector(Z.originCoordinate),b:Array.from(Z.blocks)}}static serializeEntity(Z){if(!Z.world||Z.id===void 0)u.fatalError("Serializer.serializeEntity(): Entity is not in a world");return{i:Z.id,al:Array.from(Z.modelLoopedAnimations),ap:Z.modelAnimationsPlaybackRate,bt:Z.blockTextureUri,bh:Z.blockHalfExtents?this.serializeVector(Z.blockHalfExtents):void 0,h:Array.from(Z.modelHiddenNodes),m:Z.modelUri,mt:Z.modelTextureUri,n:Z.name,o:Z.opacity,p:this.serializeVector(Z.position),pe:Z.parent?Z.parent.id:void 0,pn:Z.parentNodeName,r:this.serializeQuaternion(Z.rotation),s:Z.modelScale,sn:Array.from(Z.modelShownNodes),t:Z.tintColor?this.serializeRgbColor(Z.tintColor):void 0}}static serializeLight(Z){if(!Z.world||Z.id===void 0)u.fatalError("Serializer.serializeLight(): Light is not in a world");return{i:Z.id,a:Z.angle,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,c:this.serializeRgbColor(Z.color),d:Z.distance,n:Z.intensity,o:Z.offset?this.serializeVector(Z.offset):void 0,p:Z.position?this.serializeVector(Z.position):void 0,pe:Z.penumbra,t:Z.type,te:Z.trackedEntity?.isSpawned?Z.trackedEntity.id:void 0,tp:Z.trackedPosition?this.serializeVector(Z.trackedPosition):void 0}}static serializePhysicsDebugRaycast(Z){return{o:this.serializeVector(Z.origin),d:this.serializeVector(Z.direction),l:Z.length,h:Z.hit}}static serializePlayer(Z){return{i:Z.id,u:Z.username,p:Z.profilePictureUrl}}static serializePlayerCamera(Z){return{m:Z.mode,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,et:Z.trackedEntity?.isSpawned?Z.trackedEntity.id:void 0,fo:Z.filmOffset,ffo:Z.forwardOffset,fv:Z.fov,h:Array.from(Z.modelHiddenNodes),o:Z.offset?this.serializeVector(Z.offset):void 0,p:Z.attachedToPosition?this.serializeVector(Z.attachedToPosition):void 0,pt:Z.trackedPosition?this.serializeVector(Z.trackedPosition):void 0,s:Array.from(Z.modelShownNodes),sa:Z.shoulderAngle,z:Z.zoom}}static serializeQuaternion(Z){return[Z.x,Z.y,Z.z,Z.w]}static serializeRgbColor(Z){return[Z.r,Z.g,Z.b]}static serializeSceneUI(Z){if(Z.id===void 0)u.fatalError("Serializer.serializeSceneUI(): SceneUI is not loaded!");return{i:Z.id,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,o:Z.offset?this.serializeVector(Z.offset):void 0,p:Z.position?this.serializeVector(Z.position):void 0,s:Z.state,t:Z.templateId,v:Z.viewDistance}}static serializeVector(Z){return[Z.x,Z.y,Z.z]}static serializeVectorBoolean(Z){return[Z.x,Z.y,Z.z]}static serializeWorld(Z){return{i:Z.id,ac:this.serializeRgbColor(Z.ambientLightColor),ai:Z.ambientLightIntensity,dc:this.serializeRgbColor(Z.directionalLightColor),di:Z.directionalLightIntensity,dp:this.serializeVector(Z.directionalLightPosition),n:Z.name,s:Z.skyboxUri,si:Z.skyboxIntensity,t:Z.loop.timestepS}}}var ry=5,sR;((F)=>{F.PAUSE="AUDIO.PAUSE";F.PLAY="AUDIO.PLAY";F.PLAY_RESTART="AUDIO.PLAY_RESTART";F.SET_ATTACHED_TO_ENTITY="AUDIO.SET_ATTACHED_TO_ENTITY";F.SET_CUTOFF_DISTANCE="AUDIO.SET_CUTOFF_DISTANCE";F.SET_DETUNE="AUDIO.SET_DETUNE";F.SET_DISTORTION="AUDIO.SET_DISTORTION";F.SET_POSITION="AUDIO.SET_POSITION";F.SET_PLAYBACK_RATE="AUDIO.SET_PLAYBACK_RATE";F.SET_REFERENCE_DISTANCE="AUDIO.SET_REFERENCE_DISTANCE";F.SET_VOLUME="AUDIO.SET_VOLUME"})(sR||={});class mG extends j0{_id;_attachedToEntity;_cutoffDistance;_duration;_detune;_distortion;_loop;_offset;_position;_playbackRate;_playing;_referenceDistance;_startTick;_uri;_volume;_world;constructor(Z){super();this._attachedToEntity=Z.attachedToEntity,this._cutoffDistance=Z.cutoffDistance??(this.isPositional?(Z.referenceDistance??ry)+10:0),this._duration=Z.duration,this._detune=Z.detune??0,this._distortion=Z.distortion??0,this._loop=Z.loop??!1,this._offset=Z.offset??0,this._position=Z.position,this._playing=!1,this._playbackRate=Z.playbackRate??1,this._referenceDistance=Z.referenceDistance??(this.isPositional?ry:0),this._uri=Z.uri,this._volume=Z.volume??0.5}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get cutoffDistance(){return this._cutoffDistance}get duration(){return this._duration}get detune(){return this._detune}get distortion(){return this._distortion}get loop(){return this._loop}get offset(){return this._offset}get isLoaded(){return this._id!==void 0}get isPlaying(){return this._playing}get isPositional(){return this._attachedToEntity!==void 0||this._position!==void 0}get position(){return this._position}get playbackRate(){return this._playbackRate}get referenceDistance(){return this._referenceDistance}get startTick(){return this._startTick}get uri(){return this._uri}get volume(){return this._volume}get world(){return this._world}play(Z,J=!1){if(this.isPlaying&&!J)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`Audio.play(): Attached entity ${this._attachedToEntity.id} is not spawned!`);let X=J&&this._id!==void 0?"AUDIO.PLAY_RESTART":"AUDIO.PLAY";this._id??=Z.audioManager.registerAudio(this),this._playing=!0,this._startTick=Z.loop.currentTick,this._world=this._world??Z,this.emitWithWorld(Z,X,{audio:this})}pause(){if(!this.isPlaying||!this._world)return;this._playing=!1,this.emitWithWorld(this._world,"AUDIO.PAUSE",{audio:this})}setAttachedToEntity(Z){if(!this._requirePositional())return;if(!Z.isSpawned)return u.error(`Audio.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_ATTACHED_TO_ENTITY",{audio:this,entity:Z})}setCutoffDistance(Z){if(!this._requirePositional())return;if(Z<=0||Z<this._referenceDistance)return u.error("Audio.setCutoffDistance(): Cutoff distance cannot be less than or equal to 0 or less than reference distance!");if(this._cutoffDistance===Z)return;if(this._cutoffDistance=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_CUTOFF_DISTANCE",{audio:this,cutoffDistance:Z})}setDetune(Z){if(this._detune===Z)return;if(this._detune=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_DETUNE",{audio:this,detune:Z})}setDistortion(Z){if(Z<0)return u.error("Distortion cannot be less than 0");if(this._distortion===Z)return;if(this._distortion=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_DISTORTION",{audio:this,distortion:Z})}setPosition(Z){if(!this._requirePositional())return;if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_POSITION",{audio:this,position:Z})}setPlaybackRate(Z){if(Z<=0)return u.error("Playback rate cannot be less than or equal to 0");if(this._playbackRate===Z)return;if(this._playbackRate=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_PLAYBACK_RATE",{audio:this,playbackRate:Z})}setReferenceDistance(Z){if(!this._requirePositional())return;if(Z<=0)return u.error("Reference distance cannot be less than or equal to 0");if(this._referenceDistance===Z)return;if(this._referenceDistance=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_REFERENCE_DISTANCE",{audio:this,referenceDistance:Z})}setVolume(Z){if(Z<0||Z>1)return u.error("Volume must be between 0 and 1");if(this._volume===Z)return;if(this._volume=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_VOLUME",{audio:this,volume:Z})}serialize(){return p0.serializeAudio(this)}_requirePositional(){if(!this.isPositional)u.error("Audio._requirePositional(): Audio is not positional. and therefor does not support the invoked method.");return this.isPositional}}class uG{_audios=new Map;_nextAudioId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllAudios(){return Array.from(this._audios.values())}getAllEntityAttachedAudios(Z){return this.getAllAudios().filter((J)=>J.attachedToEntity===Z)}getAllLoopedAudios(){return this.getAllAudios().filter((Z)=>Z.loop)}getAllOneshotAudios(){return this.getAllAudios().filter((Z)=>!Z.loop)}registerAudio(Z){if(Z.id!==void 0)u.fatalError(`AudioManager.registerAudio(): Provided audio instance with uri ${Z.uri} is already assigned the id ${Z.id}!`);let J=this._nextAudioId;return this._audios.set(J,Z),this._nextAudioId++,J}unregisterAudio(Z){if(Z.id===void 0)return u.error(`AudioManager.unregisterAudio(): Provided audio instance with uri ${Z.uri} is not assigned an id!`);Z.pause(),this._audios.delete(Z.id)}unregisterEntityAttachedAudios(Z){this.getAllEntityAttachedAudios(Z).forEach((J)=>{this.unregisterAudio(J)})}}var ty;((K)=>{K.ATTACH="BASE_ENTITY_CONTROLLER.ATTACH";K.DESPAWN="BASE_ENTITY_CONTROLLER.DESPAWN";K.DETACH="BASE_ENTITY_CONTROLLER.DETACH";K.SPAWN="BASE_ENTITY_CONTROLLER.SPAWN";K.TICK="BASE_ENTITY_CONTROLLER.TICK";K.TICK_WITH_PLAYER_INPUT="BASE_ENTITY_CONTROLLER.TICK_WITH_PLAYER_INPUT"})(ty||={});class JY extends j0{attach(Z){this.emit("BASE_ENTITY_CONTROLLER.ATTACH",{entity:Z})}despawn(Z){this.emit("BASE_ENTITY_CONTROLLER.DESPAWN",{entity:Z})}detach(Z){this.emit("BASE_ENTITY_CONTROLLER.DETACH",{entity:Z})}spawn(Z){this.emit("BASE_ENTITY_CONTROLLER.SPAWN",{entity:Z})}tickWithPlayerInput(Z,J,X,Y){this.emit("BASE_ENTITY_CONTROLLER.TICK_WITH_PLAYER_INPUT",{entity:Z,input:J,cameraOrientation:X,deltaTimeMs:Y})}tick(Z,J){this.emit("BASE_ENTITY_CONTROLLER.TICK",{entity:Z,deltaTimeMs:J})}}class EQ{globalCoordinate;blockType;constructor(Z,J){this.globalCoordinate=Z,this.blockType=J}static fromGlobalCoordinate(Z,J){return new EQ(Z,J)}getNeighborGlobalCoordinateFromHitPoint(Z){let J={x:Z.x-(this.globalCoordinate.x+0.5),y:Z.y-(this.globalCoordinate.y+0.5),z:Z.z-(this.globalCoordinate.z+0.5)},X="x",Y=Math.abs(J.x);for(let[$,Q]of Object.entries(J))if(Math.abs(Q)>Y)X=$,Y=Math.abs(Q);return{x:this.globalCoordinate.x+(X==="x"?Math.sign(J.x):0),y:this.globalCoordinate.y+(X==="y"?Math.sign(J.y):0),z:this.globalCoordinate.z+(X==="z"?Math.sign(J.z):0)}}}var os=r(gQ(),1);var e8=r(gQ(),1);var OJ;((w)=>{w[w.BLOCK=1]="BLOCK";w[w.ENTITY=2]="ENTITY";w[w.ENTITY_SENSOR=4]="ENTITY_SENSOR";w[w.ENVIRONMENT_ENTITY=8]="ENVIRONMENT_ENTITY";w[w.PLAYER=16]="PLAYER";w[w.GROUP_1=32]="GROUP_1";w[w.GROUP_2=64]="GROUP_2";w[w.GROUP_3=128]="GROUP_3";w[w.GROUP_4=256]="GROUP_4";w[w.GROUP_5=512]="GROUP_5";w[w.GROUP_6=1024]="GROUP_6";w[w.GROUP_7=2048]="GROUP_7";w[w.GROUP_8=4096]="GROUP_8";w[w.GROUP_9=8192]="GROUP_9";w[w.GROUP_10=16384]="GROUP_10";w[w.GROUP_11=32768]="GROUP_11";w[w.ALL=65535]="ALL"})(OJ||={});class H4{static BELONGS_TO_SHIFT=16;static COLLIDES_WITH_MASK=65535;static buildRawCollisionGroups(Z){return this.combineGroups(Z.belongsTo)<<this.BELONGS_TO_SHIFT|this.combineGroups(Z.collidesWith)}static decodeRawCollisionGroups(Z){return{belongsTo:this.bitsToGroups(Z>>>this.BELONGS_TO_SHIFT),collidesWith:this.bitsToGroups(Z&this.COLLIDES_WITH_MASK)}}static decodeCollisionGroups(Z){return{belongsTo:Z.belongsTo.map((J)=>this.groupToName(J)),collidesWith:Z.collidesWith.map((J)=>this.groupToName(J))}}static isDefaultCollisionGroups(Z){return Z.belongsTo.includes(65535)&&Z.collidesWith.includes(65535)}static combineGroups(Z){return Z.reduce((J,X)=>J|X,0)}static bitsToGroups(Z){if(Z===65535)return[65535];return Object.values(OJ).filter((J)=>typeof J==="number"&&J!==65535&&(Z&J)!==0)}static groupToName(Z){let J=Object.entries(OJ).find(([X,Y])=>Y===Z);if(!J)u.fatalError(`CollisionGroupsBuilder.groupToName(): Unknown collision group: ${Z}`);return J[0]}}import IP1 from"crypto";import uJ from"fs";import o5 from"path";function B8(Z){if(typeof Z!=="object"||Z===null)return!1;let J=Object.getPrototypeOf(Z);return(J===null||J===Object.prototype||Object.getPrototypeOf(J)===null)&&!(Symbol.toStringTag in Z)&&!(Symbol.iterator in Z)}import{fileURLToPath as GG1}from"node:url";var mQ=(Z,J)=>{let X=EM(VG1(Z));if(typeof X!=="string")throw new TypeError(`${J} must be a string or a file URL: ${X}.`);return X},VG1=(Z)=>TM(Z)?Z.toString():Z,TM=(Z)=>typeof Z!=="string"&&Z&&Object.getPrototypeOf(Z)===String.prototype,EM=(Z)=>Z instanceof URL?GG1(Z):Z;var jU=(Z,J=[],X={})=>{let Y=mQ(Z,"First argument"),[$,Q]=B8(J)?[[],J]:[J,X];if(!Array.isArray($))throw new TypeError(`Second argument must be either an array of arguments or an options object: ${$}`);if($.some((G)=>typeof G==="object"&&G!==null))throw new TypeError(`Second argument must be an array of strings: ${$}`);let K=$.map(String),W=K.find((G)=>G.includes("\x00"));if(W!==void 0)throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${W}`);if(!B8(Q))throw new TypeError(`Last argument must be an options object: ${Q}`);return[Y,K,Q]};import{ChildProcess as BG1}from"node:child_process";import{StringDecoder as HG1}from"node:string_decoder";var{toString:ub}=Object.prototype,db=(Z)=>ub.call(Z)==="[object ArrayBuffer]",b8=(Z)=>ub.call(Z)==="[object Uint8Array]",WZ=(Z)=>new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),zG1=new TextEncoder,cb=(Z)=>zG1.encode(Z),FG1=new TextDecoder,OU=(Z)=>FG1.decode(Z),lb=(Z,J)=>{return qG1(Z,J).join("")},qG1=(Z,J)=>{if(J==="utf8"&&Z.every((Q)=>typeof Q==="string"))return Z;let X=new HG1(J),Y=Z.map((Q)=>typeof Q==="string"?cb(Q):Q).map((Q)=>X.write(Q)),$=X.end();return $===""?Y:[...Y,$]},P3=(Z)=>{if(Z.length===1&&b8(Z[0]))return Z[0];return kM(UG1(Z))},UG1=(Z)=>Z.map((J)=>typeof J==="string"?cb(J):J),kM=(Z)=>{let J=new Uint8Array(LG1(Z)),X=0;for(let Y of Z)J.set(Y,X),X+=Y.length;return J},LG1=(Z)=>{let J=0;for(let X of Z)J+=X.length;return J};var ab=(Z)=>Array.isArray(Z)&&Array.isArray(Z.raw),sb=(Z,J)=>{let X=[];for(let[Q,K]of Z.entries())X=wG1({templates:Z,expressions:J,tokens:X,index:Q,template:K});if(X.length===0)throw new TypeError("Template script must not be empty");let[Y,...$]=X;return[Y,$,{}]},wG1=({templates:Z,expressions:J,tokens:X,index:Y,template:$})=>{if($===void 0)throw new TypeError(`Invalid backslash sequence: ${Z.raw[Y]}`);let{nextTokens:Q,leadingWhitespaces:K,trailingWhitespaces:W}=jG1($,Z.raw[Y]),G=ib(X,Q,K);if(Y===J.length)return G;let V=J[Y],H=Array.isArray(V)?V.map((F)=>nb(F)):[nb(V)];return ib(G,H,W)},jG1=(Z,J)=>{if(J.length===0)return{nextTokens:[],leadingWhitespaces:!1,trailingWhitespaces:!1};let X=[],Y=0,$=pb.has(J[0]);for(let K=0,W=0;K<Z.length;K+=1,W+=1){let G=J[W];if(pb.has(G)){if(Y!==K)X.push(Z.slice(Y,K));Y=K+1}else if(G==="\\"){let V=J[W+1];if(V===`
370
+ `)}}var sy=r(ay(),1);var oy=sy.default;class j0{static globalInstance=new j0;_emitter=new oy;_finalListeners={};emit(Z,J){if(this.listenerCount(Z)===0)return!1;try{this._emitter.emit(Z,J),this._finalListeners[Z]?.(J)}catch(X){console.error(`EventRouter.emit(): Error emitting event "${Z}":`,X)}return!0}emitWithGlobal(Z,J){this.emit(Z,J),j0.globalInstance.emit(Z,J)}emitWithWorld(Z,J,X){this.emit(J,X),Z.emit(J,X)}final(Z,J){if(this._finalListeners[Z]&&J!==this._finalListeners[Z])return u.error(`EventRouter.final(): Listener for event type "${Z}" already exists. It must be removed explicitly with .off() before a different final listener can be set.`);this._finalListeners[Z]=J}hasListeners(Z){return this._emitter.listenerCount(Z)>0||Z in this._finalListeners}listeners(Z){return[...this._emitter.listeners(Z),...this._finalListeners[Z]?[this._finalListeners[Z]]:[]]}listenerCount(Z){return this._emitter.listenerCount(Z)+(this._finalListeners[Z]?1:0)}off(Z,J){if(this._emitter.removeListener(Z,J),this._finalListeners[Z]===J)delete this._finalListeners[Z]}offAll(Z){if(this._emitter.removeAllListeners(Z),Z)delete this._finalListeners[Z];else this._finalListeners={}}on(Z,J){this._emitter.addListener(Z,J)}once(Z,J){this._emitter.once(Z,J)}}class p0{static serializeAudio(Z){if(Z.id===void 0)u.fatalError(`Serializer.serializeAudio(): Audio ${Z.uri} is not playing!`);if(Z.attachedToEntity&&!Z.attachedToEntity.isSpawned)u.warning(`Serializer.serializeAudio(): Audio ${Z.uri} is attached to an entity that is not spawned or was recently despawned, reverting to unattached!`);return{i:Z.id,a:Z.uri,cd:Z.cutoffDistance,d:Z.duration,de:Z.detune,di:Z.distortion,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,l:Z.loop,o:Z.offset,p:Z.position?this.serializeVector(Z.position):void 0,pa:!Z.isPlaying,pl:Z.isPlaying,pr:Z.playbackRate,rd:Z.referenceDistance,s:Z.startTick,v:Z.volume}}static serializeBlockType(Z){return{i:Z.id,l:Z.isLiquid,n:Z.name,t:Z.textureUri}}static serializeBlockTypeRegistry(Z){return Z.getAllBlockTypes().map((J)=>this.serializeBlockType(J))}static serializeChunk(Z){if(!Z.world||!Z.originCoordinate)u.fatalError("Serializer.serializeChunk(): Chunk is not in a world");return{c:this.serializeVector(Z.originCoordinate),b:Array.from(Z.blocks)}}static serializeEntity(Z){if(!Z.world||Z.id===void 0)u.fatalError("Serializer.serializeEntity(): Entity is not in a world");return{i:Z.id,al:Array.from(Z.modelLoopedAnimations),ap:Z.modelAnimationsPlaybackRate,bt:Z.blockTextureUri,bh:Z.blockHalfExtents?this.serializeVector(Z.blockHalfExtents):void 0,h:Array.from(Z.modelHiddenNodes),m:Z.modelUri,mt:Z.modelTextureUri,n:Z.name,o:Z.opacity,p:this.serializeVector(Z.position),pe:Z.parent?Z.parent.id:void 0,pn:Z.parentNodeName,r:this.serializeQuaternion(Z.rotation),s:Z.modelScale,sn:Array.from(Z.modelShownNodes),t:Z.tintColor?this.serializeRgbColor(Z.tintColor):void 0}}static serializeLight(Z){if(!Z.world||Z.id===void 0)u.fatalError("Serializer.serializeLight(): Light is not in a world");return{i:Z.id,a:Z.angle,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,c:this.serializeRgbColor(Z.color),d:Z.distance,n:Z.intensity,o:Z.offset?this.serializeVector(Z.offset):void 0,p:Z.position?this.serializeVector(Z.position):void 0,pe:Z.penumbra,t:Z.type,te:Z.trackedEntity?.isSpawned?Z.trackedEntity.id:void 0,tp:Z.trackedPosition?this.serializeVector(Z.trackedPosition):void 0}}static serializePhysicsDebugRaycast(Z){return{o:this.serializeVector(Z.origin),d:this.serializeVector(Z.direction),l:Z.length,h:Z.hit}}static serializePlayer(Z){return{i:Z.id,u:Z.username,p:Z.profilePictureUrl}}static serializePlayerCamera(Z){return{m:Z.mode,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,et:Z.trackedEntity?.isSpawned?Z.trackedEntity.id:void 0,fo:Z.filmOffset,ffo:Z.forwardOffset,fv:Z.fov,h:Array.from(Z.modelHiddenNodes),o:Z.offset?this.serializeVector(Z.offset):void 0,p:Z.attachedToPosition?this.serializeVector(Z.attachedToPosition):void 0,pt:Z.trackedPosition?this.serializeVector(Z.trackedPosition):void 0,s:Array.from(Z.modelShownNodes),sa:Z.shoulderAngle,z:Z.zoom}}static serializeQuaternion(Z){return[Z.x,Z.y,Z.z,Z.w]}static serializeRgbColor(Z){return[Z.r,Z.g,Z.b]}static serializeSceneUI(Z){if(Z.id===void 0)u.fatalError("Serializer.serializeSceneUI(): SceneUI is not loaded!");return{i:Z.id,e:Z.attachedToEntity?.isSpawned?Z.attachedToEntity.id:void 0,o:Z.offset?this.serializeVector(Z.offset):void 0,p:Z.position?this.serializeVector(Z.position):void 0,s:Z.state,t:Z.templateId,v:Z.viewDistance}}static serializeVector(Z){return[Z.x,Z.y,Z.z]}static serializeVectorBoolean(Z){return[Z.x,Z.y,Z.z]}static serializeWorld(Z){return{i:Z.id,ac:this.serializeRgbColor(Z.ambientLightColor),ai:Z.ambientLightIntensity,dc:this.serializeRgbColor(Z.directionalLightColor),di:Z.directionalLightIntensity,dp:this.serializeVector(Z.directionalLightPosition),n:Z.name,s:Z.skyboxUri,si:Z.skyboxIntensity,t:Z.loop.timestepS}}}var ry=5,sR;((F)=>{F.PAUSE="AUDIO.PAUSE";F.PLAY="AUDIO.PLAY";F.PLAY_RESTART="AUDIO.PLAY_RESTART";F.SET_ATTACHED_TO_ENTITY="AUDIO.SET_ATTACHED_TO_ENTITY";F.SET_CUTOFF_DISTANCE="AUDIO.SET_CUTOFF_DISTANCE";F.SET_DETUNE="AUDIO.SET_DETUNE";F.SET_DISTORTION="AUDIO.SET_DISTORTION";F.SET_POSITION="AUDIO.SET_POSITION";F.SET_PLAYBACK_RATE="AUDIO.SET_PLAYBACK_RATE";F.SET_REFERENCE_DISTANCE="AUDIO.SET_REFERENCE_DISTANCE";F.SET_VOLUME="AUDIO.SET_VOLUME"})(sR||={});class mG extends j0{_id;_attachedToEntity;_cutoffDistance;_duration;_detune;_distortion;_loop;_offset;_position;_playbackRate;_playing;_referenceDistance;_startTick;_uri;_volume;_world;constructor(Z){super();this._attachedToEntity=Z.attachedToEntity,this._cutoffDistance=Z.cutoffDistance??(this.isPositional?(Z.referenceDistance??ry)+10:0),this._duration=Z.duration,this._detune=Z.detune??0,this._distortion=Z.distortion??0,this._loop=Z.loop??!1,this._offset=Z.offset??0,this._position=Z.position,this._playing=!1,this._playbackRate=Z.playbackRate??1,this._referenceDistance=Z.referenceDistance??(this.isPositional?ry:0),this._uri=Z.uri,this._volume=Z.volume??0.5}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get cutoffDistance(){return this._cutoffDistance}get duration(){return this._duration}get detune(){return this._detune}get distortion(){return this._distortion}get loop(){return this._loop}get offset(){return this._offset}get isLoaded(){return this._id!==void 0}get isPlaying(){return this._playing}get isPositional(){return this._attachedToEntity!==void 0||this._position!==void 0}get position(){return this._position}get playbackRate(){return this._playbackRate}get referenceDistance(){return this._referenceDistance}get startTick(){return this._startTick}get uri(){return this._uri}get volume(){return this._volume}get world(){return this._world}play(Z,J=!1){if(this.isPlaying&&!J)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`Audio.play(): Attached entity ${this._attachedToEntity.id} is not spawned!`);let X=J&&this._id!==void 0?"AUDIO.PLAY_RESTART":"AUDIO.PLAY";this._id??=Z.audioManager.registerAudio(this),this._playing=!0,this._startTick=Z.loop.currentTick,this._world=this._world??Z,this.emitWithWorld(Z,X,{audio:this})}pause(){if(!this.isPlaying||!this._world)return;this._playing=!1,this.emitWithWorld(this._world,"AUDIO.PAUSE",{audio:this})}setAttachedToEntity(Z){if(!this._requirePositional())return;if(!Z.isSpawned)return u.error(`Audio.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_ATTACHED_TO_ENTITY",{audio:this,entity:Z})}setCutoffDistance(Z){if(!this._requirePositional())return;if(Z<=0||Z<this._referenceDistance)return u.error("Audio.setCutoffDistance(): Cutoff distance cannot be less than or equal to 0 or less than reference distance!");if(this._cutoffDistance===Z)return;if(this._cutoffDistance=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_CUTOFF_DISTANCE",{audio:this,cutoffDistance:Z})}setDetune(Z){if(this._detune===Z)return;if(this._detune=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_DETUNE",{audio:this,detune:Z})}setDistortion(Z){if(Z<0)return u.error("Distortion cannot be less than 0");if(this._distortion===Z)return;if(this._distortion=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_DISTORTION",{audio:this,distortion:Z})}setPosition(Z){if(!this._requirePositional())return;if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_POSITION",{audio:this,position:Z})}setPlaybackRate(Z){if(Z<=0)return u.error("Playback rate cannot be less than or equal to 0");if(this._playbackRate===Z)return;if(this._playbackRate=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_PLAYBACK_RATE",{audio:this,playbackRate:Z})}setReferenceDistance(Z){if(!this._requirePositional())return;if(Z<=0)return u.error("Reference distance cannot be less than or equal to 0");if(this._referenceDistance===Z)return;if(this._referenceDistance=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_REFERENCE_DISTANCE",{audio:this,referenceDistance:Z})}setVolume(Z){if(Z<0||Z>1)return u.error("Volume must be between 0 and 1");if(this._volume===Z)return;if(this._volume=Z,this.isLoaded&&this._world)this.emitWithWorld(this._world,"AUDIO.SET_VOLUME",{audio:this,volume:Z})}serialize(){return p0.serializeAudio(this)}_requirePositional(){if(!this.isPositional)u.error("Audio._requirePositional(): Audio is not positional. and therefor does not support the invoked method.");return this.isPositional}}class uG{_audios=new Map;_nextAudioId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllAudios(){return Array.from(this._audios.values())}getAllEntityAttachedAudios(Z){return this.getAllAudios().filter((J)=>J.attachedToEntity===Z)}getAllLoopedAudios(){return this.getAllAudios().filter((Z)=>Z.loop)}getAllOneshotAudios(){return this.getAllAudios().filter((Z)=>!Z.loop)}registerAudio(Z){if(Z.id!==void 0)u.fatalError(`AudioManager.registerAudio(): Provided audio instance with uri ${Z.uri} is already assigned the id ${Z.id}!`);let J=this._nextAudioId;return this._audios.set(J,Z),this._nextAudioId++,J}unregisterAudio(Z){if(Z.id===void 0)return u.error(`AudioManager.unregisterAudio(): Provided audio instance with uri ${Z.uri} is not assigned an id!`);Z.pause(),this._audios.delete(Z.id)}unregisterEntityAttachedAudios(Z){this.getAllEntityAttachedAudios(Z).forEach((J)=>{this.unregisterAudio(J)})}}var ty;((K)=>{K.ATTACH="BASE_ENTITY_CONTROLLER.ATTACH";K.DESPAWN="BASE_ENTITY_CONTROLLER.DESPAWN";K.DETACH="BASE_ENTITY_CONTROLLER.DETACH";K.SPAWN="BASE_ENTITY_CONTROLLER.SPAWN";K.TICK="BASE_ENTITY_CONTROLLER.TICK";K.TICK_WITH_PLAYER_INPUT="BASE_ENTITY_CONTROLLER.TICK_WITH_PLAYER_INPUT"})(ty||={});class JY extends j0{attach(Z){this.emit("BASE_ENTITY_CONTROLLER.ATTACH",{entity:Z})}despawn(Z){this.emit("BASE_ENTITY_CONTROLLER.DESPAWN",{entity:Z})}detach(Z){this.emit("BASE_ENTITY_CONTROLLER.DETACH",{entity:Z})}spawn(Z){this.emit("BASE_ENTITY_CONTROLLER.SPAWN",{entity:Z})}tickWithPlayerInput(Z,J,X,Y){this.emit("BASE_ENTITY_CONTROLLER.TICK_WITH_PLAYER_INPUT",{entity:Z,input:J,cameraOrientation:X,deltaTimeMs:Y})}tick(Z,J){this.emit("BASE_ENTITY_CONTROLLER.TICK",{entity:Z,deltaTimeMs:J})}}class EQ{globalCoordinate;blockType;constructor(Z,J){this.globalCoordinate=Z,this.blockType=J}static fromGlobalCoordinate(Z,J){return new EQ(Z,J)}getNeighborGlobalCoordinateFromHitPoint(Z){let J={x:Z.x-(this.globalCoordinate.x+0.5),y:Z.y-(this.globalCoordinate.y+0.5),z:Z.z-(this.globalCoordinate.z+0.5)},X="x",Y=Math.abs(J.x);for(let[$,Q]of Object.entries(J))if(Math.abs(Q)>Y)X=$,Y=Math.abs(Q);return{x:this.globalCoordinate.x+(X==="x"?Math.sign(J.x):0),y:this.globalCoordinate.y+(X==="y"?Math.sign(J.y):0),z:this.globalCoordinate.z+(X==="z"?Math.sign(J.z):0)}}}var os=r(gQ(),1);var e8=r(gQ(),1);var OJ;((w)=>{w[w.BLOCK=1]="BLOCK";w[w.ENTITY=2]="ENTITY";w[w.ENTITY_SENSOR=4]="ENTITY_SENSOR";w[w.ENVIRONMENT_ENTITY=8]="ENVIRONMENT_ENTITY";w[w.PLAYER=16]="PLAYER";w[w.GROUP_1=32]="GROUP_1";w[w.GROUP_2=64]="GROUP_2";w[w.GROUP_3=128]="GROUP_3";w[w.GROUP_4=256]="GROUP_4";w[w.GROUP_5=512]="GROUP_5";w[w.GROUP_6=1024]="GROUP_6";w[w.GROUP_7=2048]="GROUP_7";w[w.GROUP_8=4096]="GROUP_8";w[w.GROUP_9=8192]="GROUP_9";w[w.GROUP_10=16384]="GROUP_10";w[w.GROUP_11=32768]="GROUP_11";w[w.ALL=65535]="ALL"})(OJ||={});class H4{static BELONGS_TO_SHIFT=16;static COLLIDES_WITH_MASK=65535;static buildRawCollisionGroups(Z){return this.combineGroups(Z.belongsTo)<<this.BELONGS_TO_SHIFT|this.combineGroups(Z.collidesWith)}static decodeRawCollisionGroups(Z){return{belongsTo:this.bitsToGroups(Z>>>this.BELONGS_TO_SHIFT),collidesWith:this.bitsToGroups(Z&this.COLLIDES_WITH_MASK)}}static decodeCollisionGroups(Z){return{belongsTo:Z.belongsTo.map((J)=>this.groupToName(J)),collidesWith:Z.collidesWith.map((J)=>this.groupToName(J))}}static isDefaultCollisionGroups(Z){return Z.belongsTo.includes(65535)&&Z.collidesWith.includes(65535)}static combineGroups(Z){return Z.reduce((J,X)=>J|X,0)}static bitsToGroups(Z){if(Z===65535)return[65535];return Object.values(OJ).filter((J)=>typeof J==="number"&&J!==65535&&(Z&J)!==0)}static groupToName(Z){let J=Object.entries(OJ).find(([X,Y])=>Y===Z);if(!J)u.fatalError(`CollisionGroupsBuilder.groupToName(): Unknown collision group: ${Z}`);return J[0]}}import IP1 from"crypto";import uJ from"fs";import o5 from"path";function B8(Z){if(typeof Z!=="object"||Z===null)return!1;let J=Object.getPrototypeOf(Z);return(J===null||J===Object.prototype||Object.getPrototypeOf(J)===null)&&!(Symbol.toStringTag in Z)&&!(Symbol.iterator in Z)}import{fileURLToPath as GG1}from"node:url";var mQ=(Z,J)=>{let X=EM(VG1(Z));if(typeof X!=="string")throw new TypeError(`${J} must be a string or a file URL: ${X}.`);return X},VG1=(Z)=>TM(Z)?Z.toString():Z,TM=(Z)=>typeof Z!=="string"&&Z&&Object.getPrototypeOf(Z)===String.prototype,EM=(Z)=>Z instanceof URL?GG1(Z):Z;var jU=(Z,J=[],X={})=>{let Y=mQ(Z,"First argument"),[$,Q]=B8(J)?[[],J]:[J,X];if(!Array.isArray($))throw new TypeError(`Second argument must be either an array of arguments or an options object: ${$}`);if($.some((G)=>typeof G==="object"&&G!==null))throw new TypeError(`Second argument must be an array of strings: ${$}`);let K=$.map(String),W=K.find((G)=>G.includes("\x00"));if(W!==void 0)throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${W}`);if(!B8(Q))throw new TypeError(`Last argument must be an options object: ${Q}`);return[Y,K,Q]};import{ChildProcess as BG1}from"node:child_process";import{StringDecoder as HG1}from"node:string_decoder";var{toString:ub}=Object.prototype,db=(Z)=>ub.call(Z)==="[object ArrayBuffer]",b8=(Z)=>ub.call(Z)==="[object Uint8Array]",WZ=(Z)=>new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),zG1=new TextEncoder,cb=(Z)=>zG1.encode(Z),FG1=new TextDecoder,OU=(Z)=>FG1.decode(Z),lb=(Z,J)=>{return qG1(Z,J).join("")},qG1=(Z,J)=>{if(J==="utf8"&&Z.every((Q)=>typeof Q==="string"))return Z;let X=new HG1(J),Y=Z.map((Q)=>typeof Q==="string"?cb(Q):Q).map((Q)=>X.write(Q)),$=X.end();return $===""?Y:[...Y,$]},P3=(Z)=>{if(Z.length===1&&b8(Z[0]))return Z[0];return kM(UG1(Z))},UG1=(Z)=>Z.map((J)=>typeof J==="string"?cb(J):J),kM=(Z)=>{let J=new Uint8Array(LG1(Z)),X=0;for(let Y of Z)J.set(Y,X),X+=Y.length;return J},LG1=(Z)=>{let J=0;for(let X of Z)J+=X.length;return J};var ab=(Z)=>Array.isArray(Z)&&Array.isArray(Z.raw),sb=(Z,J)=>{let X=[];for(let[Q,K]of Z.entries())X=wG1({templates:Z,expressions:J,tokens:X,index:Q,template:K});if(X.length===0)throw new TypeError("Template script must not be empty");let[Y,...$]=X;return[Y,$,{}]},wG1=({templates:Z,expressions:J,tokens:X,index:Y,template:$})=>{if($===void 0)throw new TypeError(`Invalid backslash sequence: ${Z.raw[Y]}`);let{nextTokens:Q,leadingWhitespaces:K,trailingWhitespaces:W}=jG1($,Z.raw[Y]),G=ib(X,Q,K);if(Y===J.length)return G;let V=J[Y],H=Array.isArray(V)?V.map((F)=>nb(F)):[nb(V)];return ib(G,H,W)},jG1=(Z,J)=>{if(J.length===0)return{nextTokens:[],leadingWhitespaces:!1,trailingWhitespaces:!1};let X=[],Y=0,$=pb.has(J[0]);for(let K=0,W=0;K<Z.length;K+=1,W+=1){let G=J[W];if(pb.has(G)){if(Y!==K)X.push(Z.slice(Y,K));Y=K+1}else if(G==="\\"){let V=J[W+1];if(V===`
371
371
  `)K-=1,W+=1;else if(V==="u"&&J[W+2]==="{")W=J.indexOf("}",W+3);else W+=OG1[V]??1}}let Q=Y===Z.length;if(!Q)X.push(Z.slice(Y));return{nextTokens:X,leadingWhitespaces:$,trailingWhitespaces:Q}},pb=new Set([" ","\t","\r",`
372
372
  `]),OG1={x:3,u:5},ib=(Z,J,X)=>X||Z.length===0||J.length===0?[...Z,...J]:[...Z.slice(0,-1),`${Z.at(-1)}${J[0]}`,...J.slice(1)],nb=(Z)=>{let J=typeof Z;if(J==="string")return Z;if(J==="number")return String(Z);if(B8(Z)&&(("stdout"in Z)||("isMaxBuffer"in Z)))return NG1(Z);if(Z instanceof BG1||Object.prototype.toString.call(Z)==="[object Promise]")throw new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.");throw new TypeError(`Unexpected "${J}" in template expression`)},NG1=({stdout:Z})=>{if(typeof Z==="string")return Z;if(b8(Z))return OU(Z);if(Z===void 0)throw new TypeError(`Missing result.stdout in template expression. This is probably due to the previous subprocess' "stdout" option.`);throw new TypeError(`Unexpected "${typeof Z}" stdout in template expression`)};import{spawnSync as EF1}from"node:child_process";import{debuglog as RG1}from"node:util";import IM from"node:process";var z4=(Z)=>NU.includes(Z),NU=[IM.stdin,IM.stdout,IM.stderr],O9=["stdin","stdout","stderr"],RU=(Z)=>O9[Z]??`stdio[${Z}]`;var rb=(Z)=>{let J={...Z};for(let X of SM)J[X]=_M(Z,X);return J},_M=(Z,J)=>{let X=Array.from({length:MG1(Z)+1}),Y=PG1(Z[J],X,J);return kG1(Y,J)},MG1=({stdio:Z})=>Array.isArray(Z)?Math.max(Z.length,O9.length):O9.length,PG1=(Z,J,X)=>B8(Z)?DG1(Z,J,X):J.fill(Z),DG1=(Z,J,X)=>{for(let Y of Object.keys(Z).sort(CG1))for(let $ of TG1(Y,X,J))J[$]=Z[Y];return J},CG1=(Z,J)=>ob(Z)<ob(J)?1:-1,ob=(Z)=>{if(Z==="stdout"||Z==="stderr")return 0;return Z==="all"?2:1},TG1=(Z,J,X)=>{if(Z==="ipc")return[X.length-1];let Y=vM(Z);if(Y===void 0||Y===0)throw new TypeError(`"${J}.${Z}" is invalid.
373
373
  It must be "${J}.stdout", "${J}.stderr", "${J}.all", "${J}.ipc", or "${J}.fd3", "${J}.fd4" (and so on).`);if(Y>=X.length)throw new TypeError(`"${J}.${Z}" is invalid: that file descriptor does not exist.
@@ -457,7 +457,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
457
457
  xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
458
458
  6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
459
459
  0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
460
- -----END RSA PRIVATE KEY-----`;var Uv=process.env.PORT??8080,Lv="0.6.13",Bv;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(Bv||={});class IW extends j0{static instance=new IW;_webserver=Cj.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:Lv,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(Cj.default.static("assets"));try{this._webserver.use(Cj.default.static(Cn1.dirname(g.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?Pn1.createServer(this._webserver):Dn1.createServer({key:Dj.existsSync("assets/certs/localhost.key")?Dj.readFileSync("assets/certs/localhost.key"):uY0,cert:Dj.existsSync("assets/certs/localhost.crt")?Dj.readFileSync("assets/certs/localhost.crt"):mY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else u.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(Uv,this._onStarted),console.info(`WebServer.start(): Server running on port ${Uv}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return u.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Tn1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&S7.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await N7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
460
+ -----END RSA PRIVATE KEY-----`;var Uv=process.env.PORT??8080,Lv="0.6.15",Bv;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(Bv||={});class IW extends j0{static instance=new IW;_webserver=Cj.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:Lv,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(Cj.default.static("assets"));try{this._webserver.use(Cj.default.static(Cn1.dirname(g.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?Pn1.createServer(this._webserver):Dn1.createServer({key:Dj.existsSync("assets/certs/localhost.key")?Dj.readFileSync("assets/certs/localhost.key"):uY0,cert:Dj.existsSync("assets/certs/localhost.crt")?Dj.readFileSync("assets/certs/localhost.crt"):mY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else u.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(Uv,this._onStarted),console.info(`WebServer.start(): Server running on port ${Uv}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return u.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Tn1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&S7.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await N7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
461
461
  Content-Type: text/plain\r
462
462
  Content-Length: ${W.length}\r
463
463
  Connection: close\r
@@ -488,4 +488,4 @@ Event: ${HX(Z)}`),!0}return!1}function Xs1(Z,J){if(!J?.length)return!1;return JO
488
488
  `),U=q.shift();if(!U)return Z.destroy(),X(new Error("No header received from proxy CONNECT response"));let L=U.split(" "),B=+(L[1]||0),w=L.slice(2).join(" "),O={};for(let N of q){if(!N)continue;let R=N.indexOf(":");if(R===-1)return Z.destroy(),X(new Error(`Invalid header from proxy CONNECT response: "${N}"`));let D=N.slice(0,R).toLowerCase(),M=N.slice(R+1).trimStart(),C=O[D];if(typeof C==="string")O[D]=[C,M];else if(Array.isArray(C))C.push(M);else O[D]=M}kR("got proxy server response: %o %o",U,O),K(),J({connect:{statusCode:B,statusText:w,headers:O},buffered:F})}Z.on("error",G),Z.on("end",W),Q()})}function zq(...Z){l.log("[https-proxy-agent]",...Z)}class IR extends Ey{static __initStatic(){this.protocols=["http","https"]}constructor(Z,J){super(J);this.options={},this.proxy=typeof Z==="string"?new URL(Z):Z,this.proxyHeaders=J?.headers??{},zq("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let X=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),Y=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...J?bQ1(J,"headers"):null,host:X,port:Y}}async connect(Z,J){let{proxy:X}=this;if(!J.host)throw new TypeError('No "host" provided');let Y;if(X.protocol==="https:"){zq("Creating `tls.Socket`: %o",this.connectOpts);let F=this.connectOpts.servername||this.connectOpts.host;Y=ky.connect({...this.connectOpts,servername:F&&VJ.isIP(F)?void 0:F})}else zq("Creating `net.Socket`: %o",this.connectOpts),Y=VJ.connect(this.connectOpts);let $=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},Q=VJ.isIPv6(J.host)?`[${J.host}]`:J.host,K=`CONNECT ${Q}:${J.port} HTTP/1.1\r
489
489
  `;if(X.username||X.password){let F=`${decodeURIComponent(X.username)}:${decodeURIComponent(X.password)}`;$["Proxy-Authorization"]=`Basic ${Buffer.from(F).toString("base64")}`}if($.Host=`${Q}:${J.port}`,!$["Proxy-Connection"])$["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let F of Object.keys($))K+=`${F}: ${$[F]}\r
490
490
  `;let W=yQ1(Y);Y.write(`${K}\r
491
- `);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",AZ6),J.secureEndpoint){zq("Upgrading socket connection to TLS");let F=J.servername||J.host;return ky.connect({...bQ1(J,"host","path","port"),socket:Y,servername:VJ.isIP(F)?void 0:F})}return Y}Y.destroy();let H=new VJ.Socket({writable:!1});return H.readable=!0,Z.once("socket",(F)=>{zq("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),H}}IR.__initStatic();function AZ6(Z){Z.resume()}function bQ1(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var bZ6=32768;function gZ6(Z){return new fZ6({read(){this.push(Z),this.push(null)}})}function gQ1(Z){let J;try{J=new URL(Z.url)}catch(G){return D8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),pz(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=mZ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?hZ6:xZ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new IR(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=uZ6(Z,Z.httpModule??$,K);return pz(Z,W)}function mZ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function uZ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((H,F)=>{ij(()=>{let z=gZ6(V.body),q={...Z.headers};if(V.body.length>bZ6)q["content-encoding"]="gzip",z=z.pipe(yZ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,port:Q,protocol:K,ca:Z.caCerts},(L)=>{L.on("data",()=>{}),L.on("end",()=>{}),L.setEncoding("utf8");let B=L.headers["retry-after"]??null,w=L.headers["x-sentry-rate-limits"]??null;H({statusCode:L.statusCode,headers:{"retry-after":B,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),z.pipe(U)})})}}var dZ6=new Set(["false","f","n","no","off","0"]),cZ6=new Set(["true","t","y","yes","on","1"]);function _R(Z,J){let X=String(Z).toLowerCase();if(dZ6.has(X))return!1;if(cZ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as lZ6,sep as pZ6}from"node:path";function mQ1(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function uQ1(Z=process.argv[1]?FS(process.argv[1]):process.cwd(),J=pZ6==="\\"){let X=J?mQ1(Z):Z;return(Y)=>{if(!Y)return;let $=J?mQ1(Y):Y,{dir:Q,base:K,ext:W}=lZ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${G}`:G}return G}}function dQ1(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(I0.SENTRY_RELEASE?.id)return I0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var cQ1=gj(qS(uQ1()));var pQ1=r(Z0(),1),iQ1=r(V1(),1);import*as lQ1 from"node:os";import{threadId as iZ6,isMainThread as nZ6}from"worker_threads";var aZ6=60000;class Iy extends YO{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||lQ1.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)iQ1.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});GS(X,"node"),l.log(`Initializing Sentry: process: ${process.pid}, thread: ${nZ6?"main":`worker-${iZ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{S$(this)},J)this.on("beforeCaptureLog",(Y)=>{Y.attributes={...Y.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=x8,X=pQ1.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{m0&&l.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??aZ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return I61(this,Z)}}var s4=r(Z0(),1),nQ1=r(Sh(),1),aQ1=r(hh(),1),fG=r(v1(),1);var sQ1=r(lx(),1);import sZ6 from"module";var _y=1e6;function oQ1(Z,J={}){if(Z.getOptions().debug)tZ6();let X=oZ6(Z,J);Z.traceProvider=X}function rQ1(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!I0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=sQ1.createAddHookMessageChannel();sZ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){l.warn("Failed to register ESM hook",X)}}else D8(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function oZ6(Z,J={}){let X=new aQ1.BasicTracerProvider({sampler:new Jf(Z),resource:new nQ1.Resource({[fG.ATTR_SERVICE_NAME]:"node",[fG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[fG.ATTR_SERVICE_VERSION]:x8}),forceFlushTimeoutMillis:500,spanProcessors:[new Zf({timeout:rZ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return s4.trace.setGlobalTracerProvider(X),s4.propagation.setGlobalPropagator(new sh),s4.context.setGlobalContextManager(new xQ1),X}function rZ6(Z){if(Z==null)return;if(Z>_y)return m0&&l.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${_y}`),_y;else if(Z<=0||Number.isNaN(Z)){m0&&l.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function tZ6(){let Z=new Proxy(l,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});s4.diag.disable(),s4.diag.setLogger(Z,s4.DiagLogLevel.DEBUG)}function eZ6(){return DG()?[_51()]:[]}function tQ1(){return[WO(),QO(),GO(),VO(),HO(),d61(),H51(),v51(),S51(),O51(),E51(),q51(),NQ1(),hQ1(),...eZ6()]}function eQ1(Z){return[...tQ1(),...K9(Z)?fQ1():[]]}function vy(Z={}){return ZJ6(Z,eQ1)}function ZJ6(Z={},J){let X=JJ6(Z,J);if(X.debug===!0)if(m0)l.enable();else D8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!DG()&&X.registerEsmLoaderHooks!==!1)rQ1();if(v61(),O1().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===Oy))X.integrations.push(F$1({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new Iy(X);if(O1().setClient($),$.init(),l.log(`Running in ${DG()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),$J6(),!X.skipOpenTelemetrySetup)oQ1($,{spanProcessors:X.openTelemetrySpanProcessors}),ZK1();return N61($),_61($),$}function ZK1(){if(!m0)return;let Z=D61(),J=["SentryContextManager","SentryPropagator"];if(K9())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))l.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))l.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function JJ6(Z,J){let X=XJ6(Z.release),Y=Z.spotlight??_R(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=YJ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??gQ1,stackParser:yv(Z.stackParser||cQ1),release:X,tracesSampleRate:$,spotlight:Y,debug:_R(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:ZS({defaultIntegrations:W,integrations:K})}}function XJ6(Z){if(Z!==void 0)return Z;let J=dQ1();if(J!==void 0)return J;return}function YJ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function $J6(){if(_R(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=xz(Z,J);O1().setPropagationContext(X)}}if(process.env.NODE_ENV==="production"&&process.env.SENTRY_DSN)vy({dsn:process.env.SENTRY_DSN,release:Lv,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:(Z)=>{return Z.extra=X8.getProcessStats(),Z},beforeSendTransaction:(Z)=>{if(Z.contexts?.trace?.op==="ticker_tick"){let X=Z?.start_timestamp,Y=Z?.timestamp;if(!X||!Y)return null;if((Y-X)*1000>30)return Z.measurements=X8.getProcessStats(!0),Z}return null}}),console.log("Telemetry: Sentry.io initialized!");class X8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static startSpan(Z,J){if(ej())return pj({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}}var JK1=new K$,KJ6=5000;class _4 extends j0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=C60(),this.onPacket(X0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(X0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),j0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(_4._cachedPacketsSerializedBuffer.size>0)_4._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!X0.isValidPacket(X))return u.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=_4._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return X8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=X8.startSpan({operation:"serialize_packets_encode"},()=>JK1.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),_4._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=this._closeTimeout!==null;if(J)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(S7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){u.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==hk.default.OPEN)return;X8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=_4.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){u.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([X0.createPacket(X0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){u.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},KJ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await S7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=JK1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return u.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!X0.isValidPacket(J))return u.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class Fq{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class M6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,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 Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var XK1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(XK1||={});var Sy;((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"})(Sy||={});class Ay extends j0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both");super();u.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=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.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(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position===Z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return u.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}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(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return p0.serializeLight(this)}}var qq=r(gQ(),1);var WJ6={x:0,y:-32,z:0},xy=60,hy;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(hy||={});class Uq extends j0{_colliderMap=new FH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=xy,X=WJ6){super();this._rapierEventQueue=new qq.default.EventQueue(!0),this._rapierSimulation=new qq.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}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(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=qq.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(Q)=>{let K=this._colliderMap.getColliderHandleBlockType(Q.handle);if(K)return $.push({intersectedBlockType:K}),!0;let W=this._colliderMap.getColliderHandleEntity(Q.handle);if(W)return $.push({intersectedEntity:W}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),$}raycast(Z,J,X,Y={}){let $=new qq.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,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:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:EQ.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(X8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),X8.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()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,W)=>{if(K instanceof t5&&W instanceof u8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof u8&&W instanceof t5&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof u8&&W instanceof u8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof u8||W instanceof t5))K(W,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof t5&&K instanceof u8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof u8&&K instanceof t5&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof u8&&K instanceof u8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class SR{_synchronizedPlayerReliablePackets=new M6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new M6;_queuedBlockSynchronizations=new M6;_queuedBlockTypeSynchronizations=new M6;_queuedChunkSynchronizations=new M6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new M6;_queuedLightSynchronizations=new M6;_queuedPerPlayerSynchronizations=new M6;_queuedPerPlayerCameraSynchronizations=new M6;_queuedPerPlayerUISynchronizations=new M6;_queuedPerPlayerUIDatasSynchronizations=new M6;_queuedPlayerSynchronizations=new M6;_queuedSceneUISynchronizations=new M6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(...$);if(this._queuedEntitySynchronizations.size>0){let Y=[],$=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)Y.push(Q);else $.push(Q)}if($.length>0){let Q=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,$,X);J.push(Q)}if(Y.length>0){let Q=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,Y,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUISynchronizations){let Q=X0.createPacket(X0.outboundPackets.uiPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUIDatasSynchronizations){let Q=X0.createPacket(X0.outboundPackets.uiDatasPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedWorldSynchronization){let Y=X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerCameraSynchronizations){let Q=X0.createPacket(X0.outboundPackets.cameraPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=X0.createPacket(X0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}X8.startSpan({operation:"send_all_packets"},()=>{for(let Y of Y9.instance.getConnectedPlayersByWorld(this._world)){let $=this._synchronizedPlayerReliablePackets.get(Y)??Z;if($.length>0)Y.connection.send($);if(J.length>0)Y.connection.send(J,!1)}}),X8.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._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();_4.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)}_subscribeToChunkEvents(){this._world.final("CHUNK.SPAWN",this._onChunkSpawn),this._world.final("CHUNK.DESPAWN",this._onChunkDespawn),this._world.final("CHUNK.SET_BLOCK",this._onChunkSetBlock)}_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_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)}_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_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.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_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?p0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:Y}=Z;this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_onChunkSpawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkDespawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?p0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=p0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?p0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?p0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?p0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=p0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?p0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?p0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?p0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?p0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof R7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.playersPacketDefinition,Y9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([X0.createPacket(X0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?p0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?p0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(p0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=p0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=p0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=p0.serializeVector(Z.position)};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q={i:0,c:[J,X,Y]},this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)u.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q={c:[J,X,Y]},this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)u.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class Lq{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var GJ6=2,VJ6=3;class Bq{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*VJ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return u.warning("Ticker.start(): ticker already running.");this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)X8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<GJ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++;this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs)});this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return u.warning("Ticker.stop(): ticker not running.");clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else u.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var YK1;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(YK1||={});class wq extends j0{_currentTick=0;_ticker;_world;constructor(Z,J=xy){super();this._ticker=new Bq(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}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=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();X8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:Y9.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}},()=>{X8.startSpan({operation:"chunks_update"},()=>this._world.chunkLattice.updateChunks()),X8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),X8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),X8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),X8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{u.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var fy;((G)=>{G.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";G.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";G.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";G.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";G.START="WORLD.START";G.STOP="WORLD.STOP"})(fy||={});class jq extends j0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_sceneUIManager;_simulation;_tag;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new uG(this),this._blockTypeRegistry=new xV(this),this._chatManager=new HH(this),this._chunkLattice=new zH(this),this._entityManager=new LH(this),this._lightManager=new Fq(this),this._loop=new wq(this,Z.tickRate),this._networkSynchronizer=new SR(this),this._sceneUIManager=new Lq(this),this._simulation=new Uq(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number),K=new u8({isEnvironmental:!0,...X});K.spawn(this,{x:Y,y:$,z:Q}),K.setCollisionGroupsForSolidColliders({belongsTo:[2,8],collidesWith:[65535]})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return p0.serializeWorld(this)}}var $K1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")($K1||={});class tX{static instance=new tX;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new jq({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),j0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var QK1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(QK1||={});class Y9{static instance=new Y9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){j0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),j0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),j0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),j0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}_onConnectionOpened(Z,J){let X=new uK(Z,J);this._connectionPlayers.set(Z,X),j0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X}),(this.worldSelectionHandler?.(X)??Promise.resolve(void 0)).then((Y)=>{X.joinWorld(Y??tX.instance.getDefaultWorld())})}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),j0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),j0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var WK1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(WK1||={});function HJ6(Z){KK1.default.init().then(()=>{return NQ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(NQ.instance.worldManager.getDefaultWorld());else Z();NQ.instance.start()}).catch((J)=>{u.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class NQ{static _instance;_modelRegistry=_9.instance;_playerManager=Y9.instance;_socket=S7.instance;_worldManager=tX.instance;_webServer=IW.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new NQ;return this._instance}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(){j0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var H6=r(PQ(),1);class DQ extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return H6.mat2.determinant(this)}get frobeniusNorm(){return H6.mat2.frob(this)}static create(){let Z=new DQ(0,0,0,0);return H6.mat2.identity(Z),Z}static fromRotation(Z){let J=DQ.create();return H6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=DQ.create();return H6.mat2.fromScaling(J,Z),J}add(Z){return H6.mat2.add(this,this,Z),this}adjoint(){return H6.mat2.adjoint(this,this),this}clone(){return new DQ(this[0],this[1],this[2],this[3])}copy(Z){return H6.mat2.copy(this,Z),this}equals(Z){return H6.mat2.equals(this,Z)}exactEquals(Z){return H6.mat2.exactEquals(this,Z)}identity(){return H6.mat2.identity(this),this}invert(){return H6.mat2.invert(this,this),this}multiply(Z){return H6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return H6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return H6.mat2.rotate(this,this,Z),this}subtract(Z){return H6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return H6.mat2.transpose(this,this),this}}var U8=r(PQ(),1);class JZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return U8.mat3.determinant(this)}get frobeniusNorm(){return U8.mat3.frob(this)}static create(){let Z=new JZ(0,0,0,0,0,0,0,0,0);return U8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=JZ.create();return U8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=JZ.create();return U8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=JZ.create();return U8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=JZ.create();return U8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=JZ.create();return U8.mat3.fromTranslation(J,Z),J}add(Z){return U8.mat3.add(this,this,Z),this}adjoint(){return U8.mat3.adjoint(this,this),this}clone(){return new JZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return U8.mat3.copy(this,Z),this}equals(Z){return U8.mat3.equals(this,Z)}exactEquals(Z){return U8.mat3.exactEquals(this,Z)}identity(){return U8.mat3.identity(this),this}invert(){return U8.mat3.invert(this,this),this}multiply(Z){return U8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return U8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return U8.mat3.projection(this,Z,J),this}rotate(Z){return U8.mat3.rotate(this,this,Z),this}subtract(Z){return U8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return U8.mat3.transpose(this,this),this}}var e0=r(PQ(),1);class j5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,L){super([Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,L])}get determinant(){return e0.mat4.determinant(this)}get frobeniusNorm(){return e0.mat4.frob(this)}static create(){let Z=new j5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e0.mat4.identity(Z),Z}static fromQuaternion(Z){let J=j5.create();return e0.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=j5.create();return e0.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=j5.create();return e0.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=j5.create();return e0.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=j5.create();return e0.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=j5.create();return e0.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=j5.create();return e0.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=j5.create();return e0.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=j5.create();return e0.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=j5.create();return e0.mat4.fromZRotation(J,Z),J}add(Z){return e0.mat4.add(this,this,Z),this}adjoint(){return e0.mat4.adjoint(this,this),this}clone(){return new j5(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(Z){return e0.mat4.copy(this,Z),this}equals(Z){return e0.mat4.equals(this,Z)}exactEquals(Z){return e0.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return e0.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return e0.mat4.identity(this),this}invert(){return e0.mat4.invert(this,this),this}lookAt(Z,J,X){return e0.mat4.lookAt(this,Z,J,X),this}multiply(Z){return e0.mat4.mul(this,this,Z),this}multiplyScalar(Z){return e0.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return e0.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return e0.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return e0.mat4.rotate(this,this,Z,J),this}rotateX(Z){return e0.mat4.rotateX(this,this,Z),this}rotateY(Z){return e0.mat4.rotateY(this,this,Z),this}rotateZ(Z){return e0.mat4.rotateZ(this,this,Z),this}scale(Z){return e0.mat4.scale(this,this,Z),this}subtract(Z){return e0.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return e0.mat4.targetTo(this,Z,J,X),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(Z){return e0.mat4.translate(this,this,Z),this}transpose(){return e0.mat4.transpose(this,this),this}}var A1=r(PQ(),1);class yG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return A1.quat.length(this)}get squaredLength(){return A1.quat.squaredLength(this)}get magnitude(){return A1.quat.length(this)}get squaredMagnitude(){return A1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=A1.quat.fromEuler(new Float32Array(4),Z,J,X);return new yG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new yG(Z.x,Z.y,Z.z,Z.w)}clone(){return new yG(this.x,this.y,this.z,this.w)}conjugate(){return A1.quat.conjugate(this,this),this}copy(Z){return A1.quat.copy(this,Z),this}dot(Z){return A1.quat.dot(this,Z)}exponential(){return A1.quat.exp(this,this),this}equals(Z){return A1.quat.equals(this,Z)}exactEquals(Z){return A1.quat.exactEquals(this,Z)}getAngle(Z){return A1.quat.getAngle(this,Z)}identity(){return A1.quat.identity(this),this}invert(){return A1.quat.invert(this,this),this}lerp(Z,J){return A1.quat.lerp(this,this,Z,J),this}logarithm(){return A1.quat.ln(this,this),this}multiply(Z){return A1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return A1.quat.normalize(this,this),this}power(Z){return A1.quat.pow(this,this,Z),this}randomize(){return A1.quat.random(this),this}rotateX(Z){return A1.quat.rotateX(this,this,Z),this}rotateY(Z){return A1.quat.rotateY(this,this,Z),this}rotateZ(Z){return A1.quat.rotateZ(this,this,Z),this}scale(Z){return A1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return A1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return A1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var H1=r(PQ(),1);class Oq extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return H1.vec2.length(this)}get squaredLength(){return H1.vec2.squaredLength(this)}get magnitude(){return H1.vec2.length(this)}get squaredMagnitude(){return H1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new Oq(0,0)}add(Z){return H1.vec2.add(this,this,Z),this}angle(Z){return H1.vec2.angle(this,Z)}ceil(){return H1.vec2.ceil(this,this),this}clone(){return new Oq(this.x,this.y)}copy(Z){return H1.vec2.copy(this,Z),this}distance(Z){return H1.vec2.distance(this,Z)}divide(Z){return H1.vec2.divide(this,this,Z),this}dot(Z){return H1.vec2.dot(this,Z)}equals(Z){return H1.vec2.equals(this,Z)}exactEquals(Z){return H1.vec2.exactEquals(this,Z)}floor(){return H1.vec2.floor(this,this),this}invert(){return H1.vec2.inverse(this,this),this}lerp(Z,J){return H1.vec2.lerp(this,this,Z,J),this}max(Z){return H1.vec2.max(this,this,Z),this}min(Z){return H1.vec2.min(this,this,Z),this}multiply(Z){return H1.vec2.mul(this,this,Z),this}negate(){return H1.vec2.negate(this,this),this}normalize(){return H1.vec2.normalize(this,this),this}randomize(Z){return H1.vec2.random(this,Z),this}rotate(Z,J){return H1.vec2.rotate(this,this,Z,J),this}round(){return H1.vec2.round(this,this),this}scale(Z){return H1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return H1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return H1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec2.transformMat4(this,this,Z),this}zero(){return H1.vec2.zero(this),this}}var $1=r(PQ(),1);class bG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return $1.vec3.length(this)}get squaredLength(){return $1.vec3.squaredLength(this)}get magnitude(){return $1.vec3.length(this)}get squaredMagnitude(){return $1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new bG(0,0,0)}static fromVector3Like(Z){return new bG(Z.x,Z.y,Z.z)}add(Z){return $1.vec3.add(this,this,Z),this}ceil(){return $1.vec3.ceil(this,this),this}clone(){return new bG(this.x,this.y,this.z)}copy(Z){return $1.vec3.copy(this,Z),this}cross(Z){return $1.vec3.cross(this,this,Z),this}distance(Z){return $1.vec3.distance(this,Z)}divide(Z){return $1.vec3.div(this,this,Z),this}dot(Z){return $1.vec3.dot(this,Z)}equals(Z){return $1.vec3.equals(this,Z)}exactEquals(Z){return $1.vec3.exactEquals(this,Z)}floor(){return $1.vec3.floor(this,this),this}invert(){return $1.vec3.inverse(this,this),this}lerp(Z,J){return $1.vec3.lerp(this,this,Z,J),this}max(Z){return $1.vec3.max(this,this,Z),this}min(Z){return $1.vec3.min(this,this,Z),this}multiply(Z){return $1.vec3.mul(this,this,Z),this}negate(){return $1.vec3.negate(this,this),this}normalize(){return $1.vec3.normalize(this,this),this}randomize(Z){return $1.vec3.random(this,Z),this}rotateX(Z,J){return $1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return $1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return $1.vec3.rotateZ(this,this,Z,J),this}round(){return $1.vec3.round(this,this),this}scale(Z){return $1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return $1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return $1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return $1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return $1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return $1.vec3.transformQuat(this,this,Z),this}zero(){return $1.vec3.zero(this),this}}var sW1=r(nW1(),1);var aW1=0.099856;class Nq extends JY{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=aW1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:aW1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={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},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,H=Math.min(W,G)/W,F={x:Y.x+$.x*H,y:Y.y+$.y*H,z:Y.z+$.z*H};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(W+H)/2,q={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class py extends Nq{_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(Z={}){super(Z)}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(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return u.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)u.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 X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),H=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new sW1.Heap((N,R)=>{let D=H.get(N[0])??1/0,M=H.get(R[0])??1/0;return D-M});z.push([W,J]);let q=[{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}],U=[];for(let N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let L=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],B=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),O=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&B<O){B++;let[N,R]=z.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,R);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${B} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(N);let D=V.get(N),M=new Map;for(let C of L){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&M.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(E&&I){M.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),y=Math.abs(C.y),p=Math.abs(C.z),n=y===0?0:this._verticalPenalty,o=(Math.max(_,y,p)===1&&_+y+p>1?1.4:1)+n,J0=D+o,Q0=V.get(x)??1/0;if(J0>=Q0)continue;G.set(x,R),V.set(x,J0);let C0=J0+this._pathfindingHeuristic(A,X);H.set(x,C0),z.push([x,A])}}if(B>=O){if(this._onPathfindAbort?.(),this._debug)u.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${O}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)u.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,F=V-W,z=H-G,q=Math.sqrt(F*F+z*z),U=K/Q,L=q/this._speed;X=Math.min(U*0.8,L)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{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?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(H||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{HJ6 as startServer,$K1 as WorldManagerEvent,tX as WorldManager,YK1 as WorldLoopEvent,wq as WorldLoop,fy as WorldEvent,jq as World,Bv as WebServerEvent,IW as WebServer,bG as Vector3,Oq as Vector2,Bq as Ticker,hy as SimulationEvent,Uq as Simulation,Nq as SimpleEntityController,Lq as SceneUIManager,Ok as SceneUIEvent,UH as SceneUI,B10 as SUPPORTED_INPUT_KEYS,SV as RigidBodyType,cY as RigidBody,yG as Quaternion,n2 as PlayerUIEvent,GH as PlayerUI,QK1 as PlayerManagerEvent,Y9 as PlayerManager,VH as PlayerEvent,R7 as PlayerEntity,L10 as PlayerCameraMode,Bk as PlayerCameraEvent,WH as PlayerCamera,uK as Player,rY as PersistenceManager,py as PathfindingEntityController,Uv as PORT,_9 as ModelRegistry,j5 as Matrix4,JZ as Matrix3,DQ as Matrix2,XK1 as LightType,Fq as LightManager,Sy as LightEvent,Ay as Light,M6 as IterationMap,WK1 as GameServerEvent,NQ as GameServer,j0 as EventRouter,u as ErrorHandler,LH as EntityManager,qH as EntityEvent,u8 as Entity,h1 as DefaultPlayerEntityController,Nk as DefaultPlayerEntity,j10 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,H4 as CollisionGroupsBuilder,OJ as CollisionGroup,AV as ColliderShape,FH as ColliderMap,r5 as Collider,yT as CoefficientCombineRule,zH as ChunkLattice,jk as ChunkEvent,A6 as Chunk,HH as ChatManager,wk as ChatEvent,gT as BlockTypeRegistryEvent,xV as BlockTypeRegistry,bT as BlockTypeEvent,t5 as BlockType,EQ as Block,ty as BaseEntityControllerEvent,JY as BaseEntityController,uG as AudioManager,sR as AudioEvent,mG as Audio};
491
+ `);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",AZ6),J.secureEndpoint){zq("Upgrading socket connection to TLS");let F=J.servername||J.host;return ky.connect({...bQ1(J,"host","path","port"),socket:Y,servername:VJ.isIP(F)?void 0:F})}return Y}Y.destroy();let H=new VJ.Socket({writable:!1});return H.readable=!0,Z.once("socket",(F)=>{zq("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),H}}IR.__initStatic();function AZ6(Z){Z.resume()}function bQ1(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var bZ6=32768;function gZ6(Z){return new fZ6({read(){this.push(Z),this.push(null)}})}function gQ1(Z){let J;try{J=new URL(Z.url)}catch(G){return D8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),pz(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=mZ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?hZ6:xZ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new IR(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=uZ6(Z,Z.httpModule??$,K);return pz(Z,W)}function mZ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function uZ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((H,F)=>{ij(()=>{let z=gZ6(V.body),q={...Z.headers};if(V.body.length>bZ6)q["content-encoding"]="gzip",z=z.pipe(yZ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,port:Q,protocol:K,ca:Z.caCerts},(L)=>{L.on("data",()=>{}),L.on("end",()=>{}),L.setEncoding("utf8");let B=L.headers["retry-after"]??null,w=L.headers["x-sentry-rate-limits"]??null;H({statusCode:L.statusCode,headers:{"retry-after":B,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),z.pipe(U)})})}}var dZ6=new Set(["false","f","n","no","off","0"]),cZ6=new Set(["true","t","y","yes","on","1"]);function _R(Z,J){let X=String(Z).toLowerCase();if(dZ6.has(X))return!1;if(cZ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as lZ6,sep as pZ6}from"node:path";function mQ1(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function uQ1(Z=process.argv[1]?FS(process.argv[1]):process.cwd(),J=pZ6==="\\"){let X=J?mQ1(Z):Z;return(Y)=>{if(!Y)return;let $=J?mQ1(Y):Y,{dir:Q,base:K,ext:W}=lZ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${G}`:G}return G}}function dQ1(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(I0.SENTRY_RELEASE?.id)return I0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var cQ1=gj(qS(uQ1()));var pQ1=r(Z0(),1),iQ1=r(V1(),1);import*as lQ1 from"node:os";import{threadId as iZ6,isMainThread as nZ6}from"worker_threads";var aZ6=60000;class Iy extends YO{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||lQ1.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)iQ1.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});GS(X,"node"),l.log(`Initializing Sentry: process: ${process.pid}, thread: ${nZ6?"main":`worker-${iZ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{S$(this)},J)this.on("beforeCaptureLog",(Y)=>{Y.attributes={...Y.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=x8,X=pQ1.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{m0&&l.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??aZ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return I61(this,Z)}}var s4=r(Z0(),1),nQ1=r(Sh(),1),aQ1=r(hh(),1),fG=r(v1(),1);var sQ1=r(lx(),1);import sZ6 from"module";var _y=1e6;function oQ1(Z,J={}){if(Z.getOptions().debug)tZ6();let X=oZ6(Z,J);Z.traceProvider=X}function rQ1(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!I0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=sQ1.createAddHookMessageChannel();sZ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){l.warn("Failed to register ESM hook",X)}}else D8(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function oZ6(Z,J={}){let X=new aQ1.BasicTracerProvider({sampler:new Jf(Z),resource:new nQ1.Resource({[fG.ATTR_SERVICE_NAME]:"node",[fG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[fG.ATTR_SERVICE_VERSION]:x8}),forceFlushTimeoutMillis:500,spanProcessors:[new Zf({timeout:rZ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return s4.trace.setGlobalTracerProvider(X),s4.propagation.setGlobalPropagator(new sh),s4.context.setGlobalContextManager(new xQ1),X}function rZ6(Z){if(Z==null)return;if(Z>_y)return m0&&l.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${_y}`),_y;else if(Z<=0||Number.isNaN(Z)){m0&&l.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function tZ6(){let Z=new Proxy(l,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});s4.diag.disable(),s4.diag.setLogger(Z,s4.DiagLogLevel.DEBUG)}function eZ6(){return DG()?[_51()]:[]}function tQ1(){return[WO(),QO(),GO(),VO(),HO(),d61(),H51(),v51(),S51(),O51(),E51(),q51(),NQ1(),hQ1(),...eZ6()]}function eQ1(Z){return[...tQ1(),...K9(Z)?fQ1():[]]}function vy(Z={}){return ZJ6(Z,eQ1)}function ZJ6(Z={},J){let X=JJ6(Z,J);if(X.debug===!0)if(m0)l.enable();else D8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!DG()&&X.registerEsmLoaderHooks!==!1)rQ1();if(v61(),O1().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===Oy))X.integrations.push(F$1({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new Iy(X);if(O1().setClient($),$.init(),l.log(`Running in ${DG()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),$J6(),!X.skipOpenTelemetrySetup)oQ1($,{spanProcessors:X.openTelemetrySpanProcessors}),ZK1();return N61($),_61($),$}function ZK1(){if(!m0)return;let Z=D61(),J=["SentryContextManager","SentryPropagator"];if(K9())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))l.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))l.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function JJ6(Z,J){let X=XJ6(Z.release),Y=Z.spotlight??_R(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=YJ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??gQ1,stackParser:yv(Z.stackParser||cQ1),release:X,tracesSampleRate:$,spotlight:Y,debug:_R(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:ZS({defaultIntegrations:W,integrations:K})}}function XJ6(Z){if(Z!==void 0)return Z;let J=dQ1();if(J!==void 0)return J;return}function YJ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function $J6(){if(_R(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=xz(Z,J);O1().setPropagationContext(X)}}if(process.env.NODE_ENV==="production"&&process.env.SENTRY_DSN)vy({dsn:process.env.SENTRY_DSN,release:Lv,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:(Z)=>{return Z.extra=X8.getProcessStats(),Z},beforeSendTransaction:(Z)=>{if(Z.contexts?.trace?.op==="ticker_tick"){let X=Z?.start_timestamp,Y=Z?.timestamp;if(!X||!Y)return null;if((Y-X)*1000>30)return Z.measurements=X8.getProcessStats(!0),Z}return null}}),console.log("Telemetry: Sentry.io initialized!");class X8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static startSpan(Z,J){if(ej())return pj({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}}var JK1=new K$,KJ6=5000;class _4 extends j0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=C60(),this.onPacket(X0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(X0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),j0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(_4._cachedPacketsSerializedBuffer.size>0)_4._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!X0.isValidPacket(X))return u.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=_4._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return X8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=X8.startSpan({operation:"serialize_packets_encode"},()=>JK1.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),_4._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=this._closeTimeout!==null;if(J)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(S7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){u.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==hk.default.OPEN)return;X8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=_4.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){u.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([X0.createPacket(X0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){u.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},KJ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await S7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=JK1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return u.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!X0.isValidPacket(J))return u.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class Fq{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class M6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,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 Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var XK1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(XK1||={});var Sy;((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"})(Sy||={});class Ay extends j0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both");super();u.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=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.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(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return u.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position===Z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return u.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}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(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return u.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return p0.serializeLight(this)}}var qq=r(gQ(),1);var WJ6={x:0,y:-32,z:0},xy=60,hy;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(hy||={});class Uq extends j0{_colliderMap=new FH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=xy,X=WJ6){super();this._rapierEventQueue=new qq.default.EventQueue(!0),this._rapierSimulation=new qq.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}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(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=qq.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(Q)=>{let K=this._colliderMap.getColliderHandleBlockType(Q.handle);if(K)return $.push({intersectedBlockType:K}),!0;let W=this._colliderMap.getColliderHandleEntity(Q.handle);if(W)return $.push({intersectedEntity:W}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),$}raycast(Z,J,X,Y={}){let $=new qq.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,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:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:EQ.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(X8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),X8.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()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,W)=>{if(K instanceof t5&&W instanceof u8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof u8&&W instanceof t5&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof u8&&W instanceof u8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof u8||W instanceof t5))K(W,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof t5&&K instanceof u8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof u8&&K instanceof t5&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof u8&&K instanceof u8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class SR{_synchronizedPlayerReliablePackets=new M6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new M6;_queuedBlockSynchronizations=new M6;_queuedBlockTypeSynchronizations=new M6;_queuedChunkSynchronizations=new M6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new M6;_queuedLightSynchronizations=new M6;_queuedPerPlayerSynchronizations=new M6;_queuedPerPlayerCameraSynchronizations=new M6;_queuedPerPlayerUISynchronizations=new M6;_queuedPerPlayerUIDatasSynchronizations=new M6;_queuedPlayerSynchronizations=new M6;_queuedSceneUISynchronizations=new M6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(...$);if(this._queuedEntitySynchronizations.size>0){let Y=[],$=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)Y.push(Q);else $.push(Q)}if($.length>0){let Q=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,$,X);J.push(Q)}if(Y.length>0){let Q=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,Y,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUISynchronizations){let Q=X0.createPacket(X0.outboundPackets.uiPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerUIDatasSynchronizations){let Q=X0.createPacket(X0.outboundPackets.uiDatasPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedWorldSynchronization){let Y=X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,$]of this._queuedPerPlayerCameraSynchronizations){let Q=X0.createPacket(X0.outboundPackets.cameraPacketDefinition,$,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let Y=X0.createPacket(X0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=X0.createPacket(X0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push(Y);for(let $ of this._synchronizedPlayerReliablePackets.valuesArray)$.push(Y)}X8.startSpan({operation:"send_all_packets"},()=>{for(let Y of Y9.instance.getConnectedPlayersByWorld(this._world)){let $=this._synchronizedPlayerReliablePackets.get(Y)??Z;if($.length>0)Y.connection.send($);if(J.length>0)Y.connection.send(J,!1)}}),X8.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._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();_4.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)}_subscribeToChunkEvents(){this._world.final("CHUNK.SPAWN",this._onChunkSpawn),this._world.final("CHUNK.DESPAWN",this._onChunkDespawn),this._world.final("CHUNK.SET_BLOCK",this._onChunkSetBlock)}_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_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)}_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_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.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_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?p0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:Y}=Z;this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_onChunkSpawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkDespawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?p0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=p0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?p0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?p0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?p0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=p0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?p0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?p0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?p0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?p0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof R7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.playersPacketDefinition,Y9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([X0.createPacket(X0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?p0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?p0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(p0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=p0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=p0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=p0.serializeVector(Z.position)};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q={i:0,c:[J,X,Y]},this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)u.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q={c:[J,X,Y]},this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)u.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class Lq{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var GJ6=2,VJ6=3;class Bq{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*VJ6,this._tickFunction=J,this._tickErrorCallback=X}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 Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)X8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<GJ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++;this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs)});this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else u.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var YK1;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(YK1||={});class wq extends j0{_currentTick=0;_ticker;_world;constructor(Z,J=xy){super();this._ticker=new Bq(J,this._tick,this._onTickError),this._world=Z}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=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();X8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:Y9.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}},()=>{X8.startSpan({operation:"chunks_update"},()=>this._world.chunkLattice.updateChunks()),X8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),X8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),X8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),X8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{u.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var fy;((G)=>{G.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";G.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";G.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";G.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";G.START="WORLD.START";G.STOP="WORLD.STOP"})(fy||={});class jq extends j0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_sceneUIManager;_simulation;_tag;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new uG(this),this._blockTypeRegistry=new xV(this),this._chatManager=new HH(this),this._chunkLattice=new zH(this),this._entityManager=new LH(this),this._lightManager=new Fq(this),this._loop=new wq(this,Z.tickRate),this._networkSynchronizer=new SR(this),this._sceneUIManager=new Lq(this),this._simulation=new Uq(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number),K=new u8({isEnvironmental:!0,...X});K.spawn(this,{x:Y,y:$,z:Q}),K.setCollisionGroupsForSolidColliders({belongsTo:[2,8],collidesWith:[65535]})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}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 p0.serializeWorld(this)}}var $K1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")($K1||={});class tX{static instance=new tX;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new jq({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),j0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var QK1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(QK1||={});class Y9{static instance=new Y9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){j0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),j0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),j0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),j0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}_onConnectionOpened(Z,J){let X=new uK(Z,J);this._connectionPlayers.set(Z,X),j0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X}),(this.worldSelectionHandler?.(X)??Promise.resolve(void 0)).then((Y)=>{X.joinWorld(Y??tX.instance.getDefaultWorld())})}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),j0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),j0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var WK1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(WK1||={});function HJ6(Z){KK1.default.init().then(()=>{return NQ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(NQ.instance.worldManager.getDefaultWorld());else Z();NQ.instance.start()}).catch((J)=>{u.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class NQ{static _instance;_modelRegistry=_9.instance;_playerManager=Y9.instance;_socket=S7.instance;_worldManager=tX.instance;_webServer=IW.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new NQ;return this._instance}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(){j0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var H6=r(PQ(),1);class DQ extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return H6.mat2.determinant(this)}get frobeniusNorm(){return H6.mat2.frob(this)}static create(){let Z=new DQ(0,0,0,0);return H6.mat2.identity(Z),Z}static fromRotation(Z){let J=DQ.create();return H6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=DQ.create();return H6.mat2.fromScaling(J,Z),J}add(Z){return H6.mat2.add(this,this,Z),this}adjoint(){return H6.mat2.adjoint(this,this),this}clone(){return new DQ(this[0],this[1],this[2],this[3])}copy(Z){return H6.mat2.copy(this,Z),this}equals(Z){return H6.mat2.equals(this,Z)}exactEquals(Z){return H6.mat2.exactEquals(this,Z)}identity(){return H6.mat2.identity(this),this}invert(){return H6.mat2.invert(this,this),this}multiply(Z){return H6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return H6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return H6.mat2.rotate(this,this,Z),this}subtract(Z){return H6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return H6.mat2.transpose(this,this),this}}var U8=r(PQ(),1);class JZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return U8.mat3.determinant(this)}get frobeniusNorm(){return U8.mat3.frob(this)}static create(){let Z=new JZ(0,0,0,0,0,0,0,0,0);return U8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=JZ.create();return U8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=JZ.create();return U8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=JZ.create();return U8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=JZ.create();return U8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=JZ.create();return U8.mat3.fromTranslation(J,Z),J}add(Z){return U8.mat3.add(this,this,Z),this}adjoint(){return U8.mat3.adjoint(this,this),this}clone(){return new JZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return U8.mat3.copy(this,Z),this}equals(Z){return U8.mat3.equals(this,Z)}exactEquals(Z){return U8.mat3.exactEquals(this,Z)}identity(){return U8.mat3.identity(this),this}invert(){return U8.mat3.invert(this,this),this}multiply(Z){return U8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return U8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return U8.mat3.projection(this,Z,J),this}rotate(Z){return U8.mat3.rotate(this,this,Z),this}subtract(Z){return U8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return U8.mat3.transpose(this,this),this}}var e0=r(PQ(),1);class j5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,L){super([Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,L])}get determinant(){return e0.mat4.determinant(this)}get frobeniusNorm(){return e0.mat4.frob(this)}static create(){let Z=new j5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e0.mat4.identity(Z),Z}static fromQuaternion(Z){let J=j5.create();return e0.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=j5.create();return e0.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=j5.create();return e0.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=j5.create();return e0.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=j5.create();return e0.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=j5.create();return e0.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=j5.create();return e0.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=j5.create();return e0.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=j5.create();return e0.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=j5.create();return e0.mat4.fromZRotation(J,Z),J}add(Z){return e0.mat4.add(this,this,Z),this}adjoint(){return e0.mat4.adjoint(this,this),this}clone(){return new j5(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(Z){return e0.mat4.copy(this,Z),this}equals(Z){return e0.mat4.equals(this,Z)}exactEquals(Z){return e0.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return e0.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return e0.mat4.identity(this),this}invert(){return e0.mat4.invert(this,this),this}lookAt(Z,J,X){return e0.mat4.lookAt(this,Z,J,X),this}multiply(Z){return e0.mat4.mul(this,this,Z),this}multiplyScalar(Z){return e0.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return e0.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return e0.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return e0.mat4.rotate(this,this,Z,J),this}rotateX(Z){return e0.mat4.rotateX(this,this,Z),this}rotateY(Z){return e0.mat4.rotateY(this,this,Z),this}rotateZ(Z){return e0.mat4.rotateZ(this,this,Z),this}scale(Z){return e0.mat4.scale(this,this,Z),this}subtract(Z){return e0.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return e0.mat4.targetTo(this,Z,J,X),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(Z){return e0.mat4.translate(this,this,Z),this}transpose(){return e0.mat4.transpose(this,this),this}}var A1=r(PQ(),1);class yG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return A1.quat.length(this)}get squaredLength(){return A1.quat.squaredLength(this)}get magnitude(){return A1.quat.length(this)}get squaredMagnitude(){return A1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=A1.quat.fromEuler(new Float32Array(4),Z,J,X);return new yG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new yG(Z.x,Z.y,Z.z,Z.w)}clone(){return new yG(this.x,this.y,this.z,this.w)}conjugate(){return A1.quat.conjugate(this,this),this}copy(Z){return A1.quat.copy(this,Z),this}dot(Z){return A1.quat.dot(this,Z)}exponential(){return A1.quat.exp(this,this),this}equals(Z){return A1.quat.equals(this,Z)}exactEquals(Z){return A1.quat.exactEquals(this,Z)}getAngle(Z){return A1.quat.getAngle(this,Z)}identity(){return A1.quat.identity(this),this}invert(){return A1.quat.invert(this,this),this}lerp(Z,J){return A1.quat.lerp(this,this,Z,J),this}logarithm(){return A1.quat.ln(this,this),this}multiply(Z){return A1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return A1.quat.normalize(this,this),this}power(Z){return A1.quat.pow(this,this,Z),this}randomize(){return A1.quat.random(this),this}rotateX(Z){return A1.quat.rotateX(this,this,Z),this}rotateY(Z){return A1.quat.rotateY(this,this,Z),this}rotateZ(Z){return A1.quat.rotateZ(this,this,Z),this}scale(Z){return A1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return A1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return A1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var H1=r(PQ(),1);class Oq extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return H1.vec2.length(this)}get squaredLength(){return H1.vec2.squaredLength(this)}get magnitude(){return H1.vec2.length(this)}get squaredMagnitude(){return H1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new Oq(0,0)}add(Z){return H1.vec2.add(this,this,Z),this}angle(Z){return H1.vec2.angle(this,Z)}ceil(){return H1.vec2.ceil(this,this),this}clone(){return new Oq(this.x,this.y)}copy(Z){return H1.vec2.copy(this,Z),this}distance(Z){return H1.vec2.distance(this,Z)}divide(Z){return H1.vec2.divide(this,this,Z),this}dot(Z){return H1.vec2.dot(this,Z)}equals(Z){return H1.vec2.equals(this,Z)}exactEquals(Z){return H1.vec2.exactEquals(this,Z)}floor(){return H1.vec2.floor(this,this),this}invert(){return H1.vec2.inverse(this,this),this}lerp(Z,J){return H1.vec2.lerp(this,this,Z,J),this}max(Z){return H1.vec2.max(this,this,Z),this}min(Z){return H1.vec2.min(this,this,Z),this}multiply(Z){return H1.vec2.mul(this,this,Z),this}negate(){return H1.vec2.negate(this,this),this}normalize(){return H1.vec2.normalize(this,this),this}randomize(Z){return H1.vec2.random(this,Z),this}rotate(Z,J){return H1.vec2.rotate(this,this,Z,J),this}round(){return H1.vec2.round(this,this),this}scale(Z){return H1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return H1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return H1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec2.transformMat4(this,this,Z),this}zero(){return H1.vec2.zero(this),this}}var $1=r(PQ(),1);class bG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return $1.vec3.length(this)}get squaredLength(){return $1.vec3.squaredLength(this)}get magnitude(){return $1.vec3.length(this)}get squaredMagnitude(){return $1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new bG(0,0,0)}static fromVector3Like(Z){return new bG(Z.x,Z.y,Z.z)}add(Z){return $1.vec3.add(this,this,Z),this}ceil(){return $1.vec3.ceil(this,this),this}clone(){return new bG(this.x,this.y,this.z)}copy(Z){return $1.vec3.copy(this,Z),this}cross(Z){return $1.vec3.cross(this,this,Z),this}distance(Z){return $1.vec3.distance(this,Z)}divide(Z){return $1.vec3.div(this,this,Z),this}dot(Z){return $1.vec3.dot(this,Z)}equals(Z){return $1.vec3.equals(this,Z)}exactEquals(Z){return $1.vec3.exactEquals(this,Z)}floor(){return $1.vec3.floor(this,this),this}invert(){return $1.vec3.inverse(this,this),this}lerp(Z,J){return $1.vec3.lerp(this,this,Z,J),this}max(Z){return $1.vec3.max(this,this,Z),this}min(Z){return $1.vec3.min(this,this,Z),this}multiply(Z){return $1.vec3.mul(this,this,Z),this}negate(){return $1.vec3.negate(this,this),this}normalize(){return $1.vec3.normalize(this,this),this}randomize(Z){return $1.vec3.random(this,Z),this}rotateX(Z,J){return $1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return $1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return $1.vec3.rotateZ(this,this,Z,J),this}round(){return $1.vec3.round(this,this),this}scale(Z){return $1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return $1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return $1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return $1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return $1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return $1.vec3.transformQuat(this,this,Z),this}zero(){return $1.vec3.zero(this),this}}var sW1=r(nW1(),1);var aW1=0.099856;class Nq extends JY{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=aW1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:aW1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={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},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,H=Math.min(W,G)/W,F={x:Y.x+$.x*H,y:Y.y+$.y*H,z:Y.z+$.z*H};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(W+H)/2,q={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class py extends Nq{_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(Z={}){super(Z)}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(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return u.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)u.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 X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),H=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new sW1.Heap((N,R)=>{let D=H.get(N[0])??1/0,M=H.get(R[0])??1/0;return D-M});z.push([W,J]);let q=[{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}],U=[];for(let N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let L=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],B=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),O=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&B<O){B++;let[N,R]=z.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,R);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${B} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(N);let D=V.get(N),M=new Map;for(let C of L){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&M.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(E&&I){M.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),y=Math.abs(C.y),p=Math.abs(C.z),n=y===0?0:this._verticalPenalty,o=(Math.max(_,y,p)===1&&_+y+p>1?1.4:1)+n,J0=D+o,Q0=V.get(x)??1/0;if(J0>=Q0)continue;G.set(x,R),V.set(x,J0);let C0=J0+this._pathfindingHeuristic(A,X);H.set(x,C0),z.push([x,A])}}if(B>=O){if(this._onPathfindAbort?.(),this._debug)u.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${O}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)u.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,F=V-W,z=H-G,q=Math.sqrt(F*F+z*z),U=K/Q,L=q/this._speed;X=Math.min(U*0.8,L)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{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?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(H||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{HJ6 as startServer,$K1 as WorldManagerEvent,tX as WorldManager,YK1 as WorldLoopEvent,wq as WorldLoop,fy as WorldEvent,jq as World,Bv as WebServerEvent,IW as WebServer,bG as Vector3,Oq as Vector2,Bq as Ticker,hy as SimulationEvent,Uq as Simulation,Nq as SimpleEntityController,Lq as SceneUIManager,Ok as SceneUIEvent,UH as SceneUI,B10 as SUPPORTED_INPUT_KEYS,SV as RigidBodyType,cY as RigidBody,yG as Quaternion,n2 as PlayerUIEvent,GH as PlayerUI,QK1 as PlayerManagerEvent,Y9 as PlayerManager,VH as PlayerEvent,R7 as PlayerEntity,L10 as PlayerCameraMode,Bk as PlayerCameraEvent,WH as PlayerCamera,uK as Player,rY as PersistenceManager,py as PathfindingEntityController,Uv as PORT,_9 as ModelRegistry,j5 as Matrix4,JZ as Matrix3,DQ as Matrix2,XK1 as LightType,Fq as LightManager,Sy as LightEvent,Ay as Light,M6 as IterationMap,WK1 as GameServerEvent,NQ as GameServer,j0 as EventRouter,u as ErrorHandler,LH as EntityManager,qH as EntityEvent,u8 as Entity,h1 as DefaultPlayerEntityController,Nk as DefaultPlayerEntity,j10 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,H4 as CollisionGroupsBuilder,OJ as CollisionGroup,AV as ColliderShape,FH as ColliderMap,r5 as Collider,yT as CoefficientCombineRule,zH as ChunkLattice,jk as ChunkEvent,A6 as Chunk,HH as ChatManager,wk as ChatEvent,gT as BlockTypeRegistryEvent,xV as BlockTypeRegistry,bT as BlockTypeEvent,t5 as BlockType,EQ as Block,ty as BaseEntityControllerEvent,JY as BaseEntityController,uG as AudioManager,sR as AudioEvent,mG as Audio};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hytopia",
3
- "version": "0.6.13",
3
+ "version": "0.6.15",
4
4
  "description": "The HYTOPIA SDK makes it easy for developers to create massively multiplayer games using JavaScript or TypeScript.",
5
5
  "type": "module",
6
6
  "main": "./node-server.mjs",