hytopia 0.14.16 → 0.14.17

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/bin/scripts.js CHANGED
@@ -158,6 +158,12 @@ function init() {
158
158
  function installProjectDependencies() {
159
159
  // init project
160
160
  execSync('npm init -y --silent --loglevel silent', { stdio: ['ignore', 'ignore', 'inherit'] });
161
+
162
+ // Add various common scripts to the package.json
163
+ execSync('npm pkg set scripts.build="hytopia build"', { stdio: 'ignore' });
164
+ execSync('npm pkg set scripts.package="hytopia package"', { stdio: 'ignore' });
165
+ execSync('npm pkg set scripts.upgrade-assets-library="hytopia upgrade-assets-library"', { stdio: 'ignore' });
166
+ execSync('npm pkg set scripts.upgrade-project="hytopia upgrade-project"', { stdio: 'ignore' });
161
167
 
162
168
  // create tsconfig.json, used by build
163
169
  fs.writeFileSync('tsconfig.json', JSON.stringify({
@@ -0,0 +1,95 @@
1
+ <!-- Do not edit this file. It is automatically generated by API Documenter. -->
2
+
3
+ [Home](./index.md) &gt; [client](./client.md) &gt; [HytopiaUI](./client.hytopiaui.md) &gt; [connectArrow](./client.hytopiaui.connectarrow.md)
4
+
5
+ ## HytopiaUI.connectArrow() method
6
+
7
+ Creates an arrow between two points or entities.
8
+
9
+ **Signature:**
10
+
11
+ ```typescript
12
+ connectArrow(source: number | THREE.Vector3Like, target: number | THREE.Vector3Like, options?: {
13
+ color?: {
14
+ r: number;
15
+ g: number;
16
+ b: number;
17
+ };
18
+ textureUri?: string;
19
+ }): number;
20
+ ```
21
+
22
+ ## Parameters
23
+
24
+ <table><thead><tr><th>
25
+
26
+ Parameter
27
+
28
+
29
+ </th><th>
30
+
31
+ Type
32
+
33
+
34
+ </th><th>
35
+
36
+ Description
37
+
38
+
39
+ </th></tr></thead>
40
+ <tbody><tr><td>
41
+
42
+ source
43
+
44
+
45
+ </td><td>
46
+
47
+ number \| THREE.Vector3Like
48
+
49
+
50
+ </td><td>
51
+
52
+ Source entity ID (number) or position (Vector3Like)
53
+
54
+
55
+ </td></tr>
56
+ <tr><td>
57
+
58
+ target
59
+
60
+
61
+ </td><td>
62
+
63
+ number \| THREE.Vector3Like
64
+
65
+
66
+ </td><td>
67
+
68
+ Target entity ID (number) or position (Vector3Like)
69
+
70
+
71
+ </td></tr>
72
+ <tr><td>
73
+
74
+ options
75
+
76
+
77
+ </td><td>
78
+
79
+ { color?: { r: number; g: number; b: number; }; textureUri?: string; }
80
+
81
+
82
+ </td><td>
83
+
84
+ _(Optional)_ Optional arrow properties (color, textureUrl)
85
+
86
+
87
+ </td></tr>
88
+ </tbody></table>
89
+
90
+ **Returns:**
91
+
92
+ number
93
+
94
+ The arrow ID
95
+
@@ -0,0 +1,58 @@
1
+ <!-- Do not edit this file. It is automatically generated by API Documenter. -->
2
+
3
+ [Home](./index.md) &gt; [client](./client.md) &gt; [HytopiaUI](./client.hytopiaui.md) &gt; [disconnectArrow](./client.hytopiaui.disconnectarrow.md)
4
+
5
+ ## HytopiaUI.disconnectArrow() method
6
+
7
+ Removes an arrow by its ID.
8
+
9
+ **Signature:**
10
+
11
+ ```typescript
12
+ disconnectArrow(arrowId: number): void;
13
+ ```
14
+
15
+ ## Parameters
16
+
17
+ <table><thead><tr><th>
18
+
19
+ Parameter
20
+
21
+
22
+ </th><th>
23
+
24
+ Type
25
+
26
+
27
+ </th><th>
28
+
29
+ Description
30
+
31
+
32
+ </th></tr></thead>
33
+ <tbody><tr><td>
34
+
35
+ arrowId
36
+
37
+
38
+ </td><td>
39
+
40
+ number
41
+
42
+
43
+ </td><td>
44
+
45
+ The arrow ID to remove
46
+
47
+
48
+ </td></tr>
49
+ </tbody></table>
50
+
51
+ **Returns:**
52
+
53
+ void
54
+
55
+ ## Exceptions
56
+
57
+ Error if the arrow ID does not exist
58
+
@@ -0,0 +1,56 @@
1
+ <!-- Do not edit this file. It is automatically generated by API Documenter. -->
2
+
3
+ [Home](./index.md) &gt; [client](./client.md) &gt; [HytopiaUI](./client.hytopiaui.md) &gt; [getEntityIdByName](./client.hytopiaui.getentityidbyname.md)
4
+
5
+ ## HytopiaUI.getEntityIdByName() method
6
+
7
+ Finds an entity by its name property and returns its ID. If multiple entities have the same name, returns the first one found.
8
+
9
+ **Signature:**
10
+
11
+ ```typescript
12
+ getEntityIdByName(name: string): number | undefined;
13
+ ```
14
+
15
+ ## Parameters
16
+
17
+ <table><thead><tr><th>
18
+
19
+ Parameter
20
+
21
+
22
+ </th><th>
23
+
24
+ Type
25
+
26
+
27
+ </th><th>
28
+
29
+ Description
30
+
31
+
32
+ </th></tr></thead>
33
+ <tbody><tr><td>
34
+
35
+ name
36
+
37
+
38
+ </td><td>
39
+
40
+ string
41
+
42
+
43
+ </td><td>
44
+
45
+ The exact name to search for (case-sensitive)
46
+
47
+
48
+ </td></tr>
49
+ </tbody></table>
50
+
51
+ **Returns:**
52
+
53
+ number \| undefined
54
+
55
+ The entity ID if found, undefined otherwise
56
+
@@ -0,0 +1,19 @@
1
+ <!-- Do not edit this file. It is automatically generated by API Documenter. -->
2
+
3
+ [Home](./index.md) &gt; [client](./client.md) &gt; [HytopiaUI](./client.hytopiaui.md) &gt; [getPlayerEntityId](./client.hytopiaui.getplayerentityid.md)
4
+
5
+ ## HytopiaUI.getPlayerEntityId() method
6
+
7
+ Gets the entity ID of the current player's entity. Returns undefined if the player entity is not yet initialized.
8
+
9
+ **Signature:**
10
+
11
+ ```typescript
12
+ getPlayerEntityId(): number | undefined;
13
+ ```
14
+ **Returns:**
15
+
16
+ number \| undefined
17
+
18
+ The player's entity ID, or undefined if not available
19
+
@@ -162,6 +162,34 @@ Description
162
162
  </th></tr></thead>
163
163
  <tbody><tr><td>
164
164
 
165
+ [connectArrow(source, target, options)](./client.hytopiaui.connectarrow.md)
166
+
167
+
168
+ </td><td>
169
+
170
+
171
+ </td><td>
172
+
173
+ Creates an arrow between two points or entities.
174
+
175
+
176
+ </td></tr>
177
+ <tr><td>
178
+
179
+ [disconnectArrow(arrowId)](./client.hytopiaui.disconnectarrow.md)
180
+
181
+
182
+ </td><td>
183
+
184
+
185
+ </td><td>
186
+
187
+ Removes an arrow by its ID.
188
+
189
+
190
+ </td></tr>
191
+ <tr><td>
192
+
165
193
  [filterProfanity(text)](./client.hytopiaui.filterprofanity.md)
166
194
 
167
195
 
@@ -173,6 +201,34 @@ Description
173
201
  Filters inappropriate language from text by replacing profanity with asterisks. Use this to sanitize user-generated content displayed in your UI (e.g., chat messages, usernames).
174
202
 
175
203
 
204
+ </td></tr>
205
+ <tr><td>
206
+
207
+ [getEntityIdByName(name)](./client.hytopiaui.getentityidbyname.md)
208
+
209
+
210
+ </td><td>
211
+
212
+
213
+ </td><td>
214
+
215
+ Finds an entity by its name property and returns its ID. If multiple entities have the same name, returns the first one found.
216
+
217
+
218
+ </td></tr>
219
+ <tr><td>
220
+
221
+ [getPlayerEntityId()](./client.hytopiaui.getplayerentityid.md)
222
+
223
+
224
+ </td><td>
225
+
226
+
227
+ </td><td>
228
+
229
+ Gets the entity ID of the current player's entity. Returns undefined if the player entity is not yet initialized.
230
+
231
+
176
232
  </td></tr>
177
233
  <tr><td>
178
234
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hytopia",
3
- "version": "0.14.16",
3
+ "version": "0.14.17",
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": "./server.mjs",
package/server.mjs CHANGED
@@ -249,4 +249,4 @@ wzUfQXDpZndkqxHilERgvPXLEsTTCMF/W+C8gsO9AoGAZWt+CU6zQhqMBB5MMGZf
249
249
  UE5WUS/oOd4jHBqwVxBTLOAPlmnQSp1uiTu2K0NrnnvZ6Zi/+tIsjbtxhomeOmnH
250
250
  +wsk9n+Bif4P7VTvwqc9FY4Ya79PEJK+J/xx/mldUEz3R63RiRXZAaDddO7yCQFX
251
251
  W8eeuIMLKU6dSq0yu22+nyU=
252
- -----END PRIVATE KEY-----`;var pP=process.env.PORT??8080,su="0.14.16",ru;((Q)=>{Q.READY="WEBSERVER.READY";Q.STOPPED="WEBSERVER.STOPPED";Q.ERROR="WEBSERVER.ERROR";Q.UPGRADE="WEBSERVER.UPGRADE"})(ru||={});var gq={"access-control-allow-origin":"*"},AK6=JSON.stringify({status:"OK",version:su,runtime:"node"}),_K6={".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".gltf":"model/gltf+json",".glb":"model/gltf-binary",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".ktx2":"image/ktx2",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".bin":"application/octet-stream",".wasm":"application/wasm"};class mq extends $8{static instance=new mq;_server;_assetCache=new Map;_assetDirs=[];constructor(){super();this._assetDirs.push(iu.resolve("assets"));let J=p6.assetsLibraryPath;if(J)this._assetDirs.push(J)}start(){if(this._server)return n.warning("WebServer.start(): already started");this._server=IK6.createSecureServer({key:cP,cert:lP,allowHTTP1:!0}),this._server.on("stream",this._onStream),this._server.on("upgrade",this._onUpgrade),this._server.on("error",this._onError),this._server.on("close",this._onStopped),this._server.listen(pP,this._onStarted),console.info(`WebServer.start(): Server running on port ${pP}`)}stop(){if(!this._server)return n.warning("WebServer.stop(): not started"),Promise.resolve(!1);return new Promise((J,$)=>{this._server.close((X)=>X?$(X):J(!0))})}_onStarted=()=>this.emitWithGlobal("WEBSERVER.READY",{});_onStopped=()=>this.emitWithGlobal("WEBSERVER.STOPPED",{});_onError=(J)=>{n.error(`WebServer._onError(): ${J.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:J})};_onStream=(J,$)=>{let X=$[":path"]||"/",Q=($[":method"]||"GET")==="HEAD";if(X==="/"){J.respond({":status":200,"content-type":"application/json",...gq}),J.end(!Q?AK6:void 0);return}let W=decodeURIComponent(X.split("?")[0]);if(W.includes("..")){J.respond({":status":400,...gq}),J.end();return}for(let K of this._assetDirs){let Z=iu.join(K,W);if(!Z.startsWith(K))continue;let G=p6.assetsLibraryPath;if(G&&Z.startsWith(G))p6.instance.syncAsset(Z);let V=this._assetCache.get(Z);if(!V)try{let q=kK6.statSync(Z);if(!q.isFile())continue;V={size:q.size,etag:`"${q.mtimeMs.toString(36)}-${q.size.toString(36)}"`},this._assetCache.set(Z,V)}catch{continue}if($["if-none-match"]===V.etag){J.respond({":status":304,...gq}),J.end();return}let z={":status":200,"content-type":_K6[iu.extname(Z).toLowerCase()]||"application/octet-stream","content-length":V.size,etag:V.etag,"cache-control":"public, max-age=0, must-revalidate",...gq};if(Q){J.respond(z),J.end();return}J.respondWithFile(Z,z,{onError:(q)=>{if(!J.destroyed)J.respond({":status":500,...gq}),J.end();n.error(`WebServer: ${q.message}`)}});return}J.respond({":status":404,...gq}),J.end()};_onUpgrade=(J,$,X)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:J,socket:$,head:X})}}var FG;((B)=>{B.BUILD_PACKETS="build_packets";B.ENTITIES_EMIT_UPDATES="entities_emit_updates";B.ENTITIES_TICK="entities_tick";B.NETWORK_SYNCHRONIZE="network_synchronize";B.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";B.PHYSICS_CLEANUP="physics_cleanup";B.PHYSICS_STEP="physics_step";B.SEND_ALL_PACKETS="send_all_packets";B.SEND_PACKETS="send_packets";B.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";B.SERIALIZE_PACKETS="serialize_packets";B.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";B.SIMULATION_STEP="simulation_step";B.TICKER_TICK="ticker_tick";B.WORLD_TICK="world_tick"})(FG||={});class w6{static getProcessStats(J=!1){let $=process.memoryUsage(),X={jsHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:$.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:$.heapUsed/$.heapTotal,unit:"percent"},processHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:$.rss/1024/1024,unit:"megabyte"}};if(J)return X;return Object.fromEntries(Object.entries(X).map(([Y,Q])=>[Y,Q.value]))}static initializeSentry(J,$=50){dP({dsn:J,release:su,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=w6.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Q=X?.start_timestamp,W=X?.timestamp;if(!Q||!W)return null;if((W-Q)*1000>$)return X.measurements=w6.getProcessStats(!0),X}return null}})}static startSpan(J,$){if(A3())return w1({attributes:J.attributes,name:J.operation,op:J.operation},$);else return $()}static sentry(){return nu}}if(!aO)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var Sq8=new ZZ({useFloat32:Z3.ALWAYS}),yK6=30000;class i$ extends $8{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(J,$,X){super();this.id=kZ0(),this.onPacket(h0.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{$8.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:X})};if(J)this.bindWs(J),Y();else if($)this.bindWt($).then(Y).catch((Q)=>{this._onClose(),n.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${Q}`)})}static clearCachedPacketsSerializedBuffers(){if(i$._cachedPacketsSerializedBuffer.size>0)i$._cachedPacketsSerializedBuffer.clear()}static serializePackets(J){for(let X of J)if(!h0.isValidPacket(X))return n.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let $=i$._cachedPacketsSerializedBuffer.get(J);if($)return $;return w6.startSpan({operation:"serialize_packets",attributes:{packets:J.length,packetIds:J.map((X)=>X[0]).join(",")}},(X)=>{let Y=Sq8.pack(J);if(Y.byteLength>65536)Y=vK6(Y,{level:1});return X?.setAttribute("serializedBytes",Y.byteLength),i$._cachedPacketsSerializedBuffer.set(J,Y),Y})}bindWs(J){this._wsBinding=!0;let $=this._handleReconnect();if(this._cleanupConnections(),this._ws=J,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(J){this._wtBinding=!0;let $=this._handleReconnect();this._cleanupConnections(),J.userData.onclose=this._onClose,J.closed.catch(()=>{}).finally(()=>J.userData.onclose?.()),this._wt=J,await this._wt.ready;let X=this._wt.incomingBidirectionalStreams.getReader();try{let{value:Y}=await X.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{X.releaseLock()}if(this._wtUnreliableReader=this._wt.datagrams.readable,this._wtUnreliableWriter=this._wt.datagrams.createWritable().getWriter(),(async()=>{if(!this._wtReliableReader)return;let Y=this._wt,Q=h0.createPacketBufferUnframer((W)=>{this._onMessage(W)});for await(let W of this._wtReliableReader){if(Y!==this._wt)return;Q(W)}})().catch(()=>this._wt?.close()),(async()=>{if(!this._wtUnreliableReader)return;let Y=this._wt;for await(let Q of this._wtUnreliableReader){if(Y!==this._wt)return;this._onMessage(Q)}})().catch(()=>this._wt?.close()),this._wtBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(J){n.error(`Connection.disconnect(): Connection disconnect failed. Error: ${J}`)}}onPacket(J,$){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===J)$(X)})}send(J,$=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let X=this._ws&&this._ws.readyState===PH.default.OPEN,Y=this._wt&&(this._wt.state==="connected"||this._wt.state==="draining");if(!X&&!Y)return;w6.startSpan({operation:"send_packets"},()=>{try{let Q=i$.serializePackets(J);if(!Q)return;if(Y)if($||Q.byteLength>1200)this._wtReliableWriter?.write(h0.framePacketBuffer(Q)).catch(()=>{n.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(Q).catch(()=>{n.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(Q);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:J})}catch(Q){n.error(`Connection.send(): Packet send failed. Error: ${Q}`)}})}_onHeartbeatPacket=()=>{this.send([h0.createPacket(h0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(J)=>{try{let $=this._deserialize(J);if(!$)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:$})}catch($){n.error(`Connection._ws.onmessage(): Error: ${$}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},yK6)};_onError=(J)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:J})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill(),this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(J){let $=Sq8.unpack(J);if(!$||typeof $!=="object"||typeof $[0]!=="number")return n.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify($)}`);if(!h0.isValidPacket($))return n.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify($)}`);return $}_handleReconnect(){let J=!!this._ws||!!this._wt;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return J}_signalConnectionId(){this.send([h0.createPacket(h0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([h0.createPacket(h0.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class GL{_lights=new Map;_nextLightId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedLights(J){this.getAllEntityAttachedLights(J).forEach(($)=>{$.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(J){return this.getAllLights().filter(($)=>$.attachedToEntity===J)}registerLight(J){if(J.id!==void 0)return J.id;let $=this._nextLightId;return this._lights.set($,J),this._nextLightId++,$}unregisterLight(J){if(J.id===void 0)return;this._lights.delete(J.id)}}class H9{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(J){return this._map.get(J)}set(J,$){let X=this._map.has(J);if(this._map.set(J,$),!X)this._values.push($);else this._isDirty=!0;return this}has(J){return this._map.has(J)}delete(J){let $=this._map.delete(J);if($)this._isDirty=!0;return $}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(J,$){this._map.forEach((X,Y)=>{J.call($,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 J of this._map.values())this._values.push(J);this._isDirty=!1}}var kq8;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(kq8||={});var au;((q)=>{q.DESPAWN="LIGHT.DESPAWN";q.SET_ANGLE="LIGHT.SET_ANGLE";q.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";q.SET_COLOR="LIGHT.SET_COLOR";q.SET_DISTANCE="LIGHT.SET_DISTANCE";q.SET_INTENSITY="LIGHT.SET_INTENSITY";q.SET_OFFSET="LIGHT.SET_OFFSET";q.SET_PENUMBRA="LIGHT.SET_PENUMBRA";q.SET_POSITION="LIGHT.SET_POSITION";q.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";q.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";q.SPAWN="LIGHT.SPAWN"})(au||={});class ou extends $8{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");super();n.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=J.angle,this._attachedToEntity=J.attachedToEntity,this._color=J.color??{r:255,g:255,b:255},this._distance=J.distance,this._intensity=J.intensity??1,this._offset=J.offset,this._penumbra=J.penumbra,this._position=J.position,this._trackedEntity=J.trackedEntity,this._trackedPosition=J.trackedPosition,this._type=J.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(J){if(this._angle===J)return;if(this._angle=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`Light.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:J})}setColor(J){if(this._color.r===J.r&&this._color.g===J.g&&this._color.b===J.b)return;if(this._color=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:J})}setDistance(J){if(this._distance===J)return;if(this._distance=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:J})}setIntensity(J){if(this._intensity===J)return;if(this._intensity=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:J})}setPenumbra(J){if(this._penumbra===J)return;if(this._penumbra=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:J})}setTrackedEntity(J){if(!J.isSpawned)return n.error(`Light.setTrackedEntity(): Entity ${J.id} is not spawned!`);if(this._trackedEntity===J)return;if(this._trackedEntity=J,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:J})}setTrackedPosition(J){if(this._trackedPosition===J)return;if(this._trackedPosition=J,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:J})}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(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=J.lightManager.registerLight(this),this._world=J,this.emitWithWorld(J,"LIGHT.SPAWN",{light:this})}serialize(){return V8.serializeLight(this)}}var tu;((v)=>{v.BURST="PARTICLE_EMITTER.BURST";v.DESPAWN="PARTICLE_EMITTER.DESPAWN";v.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";v.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";v.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";v.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";v.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";v.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";v.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";v.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";v.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";v.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";v.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";v.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";v.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";v.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";v.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";v.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";v.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";v.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";v.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";v.SET_RATE="PARTICLE_EMITTER.SET_RATE";v.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";v.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";v.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";v.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";v.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";v.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";v.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";v.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";v.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";v.SPAWN="PARTICLE_EMITTER.SPAWN"})(tu||={});class eu extends $8{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");if(!J.textureUri)n.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=J.alphaTest??0.05,this._attachedToEntity=J.attachedToEntity,this._attachedToEntityNodeName=J.attachedToEntityNodeName,this._colorEnd=J.colorEnd,this._colorEndVariance=J.colorEndVariance,this._colorStart=J.colorStart,this._colorStartVariance=J.colorStartVariance,this._gravity=J.gravity,this._lifetime=J.lifetime,this._lifetimeVariance=J.lifetimeVariance,this._maxParticles=J.maxParticles,this._offset=J.offset,this._opacityEnd=J.opacityEnd,this._opacityEndVariance=J.opacityEndVariance,this._opacityStart=J.opacityStart,this._opacityStartVariance=J.opacityStartVariance,this._paused=!1,this._position=J.position,this._positionVariance=J.positionVariance,this._rate=J.rate,this._rateVariance=J.rateVariance,this._sizeEnd=J.sizeEnd,this._sizeEndVariance=J.sizeEndVariance,this._sizeStart=J.sizeStart,this._sizeStartVariance=J.sizeStartVariance,this._textureUri=J.textureUri,this._transparent=J.transparent,this._velocity=J.velocity,this._velocityVariance=J.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(J){if(this._alphaTest===J)return;if(this._alphaTest=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`ParticleEmitter.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:J})}setAttachedToEntityNodeName(J){if(this._attachedToEntityNodeName===J)return;if(this._attachedToEntityNodeName=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:J})}setColorEnd(J){if(this._colorEnd&&this._colorEnd.r===J.r&&this._colorEnd.g===J.g&&this._colorEnd.b===J.b)return;if(this._colorEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:J})}setColorEndVariance(J){if(this._colorEndVariance&&this._colorEndVariance.r===J.r&&this._colorEndVariance.g===J.g&&this._colorEndVariance.b===J.b)return;if(this._colorEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:J})}setColorStart(J){if(this._colorStart&&this._colorStart.r===J.r&&this._colorStart.g===J.g&&this._colorStart.b===J.b)return;if(this._colorStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:J})}setColorStartVariance(J){if(this._colorStartVariance&&this._colorStartVariance.r===J.r&&this._colorStartVariance.g===J.g&&this._colorStartVariance.b===J.b)return;if(this._colorStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:J})}setGravity(J){if(this._gravity&&this._gravity.x===J.x&&this._gravity.y===J.y&&this._gravity.z===J.z)return;if(this._gravity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:J})}setLifetime(J){if(this._lifetime===J)return;if(this._lifetime=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:J})}setLifetimeVariance(J){if(this._lifetimeVariance===J)return;if(this._lifetimeVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:J})}setMaxParticles(J){if(this._maxParticles===J)return;if(this._maxParticles=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:J})}setOpacityEnd(J){if(this._opacityEnd===J)return;if(this._opacityEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:J})}setOpacityEndVariance(J){if(this._opacityEndVariance===J)return;if(this._opacityEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:J})}setOpacityStart(J){if(this._opacityStart===J)return;if(this._opacityStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:J})}setOpacityStartVariance(J){if(this._opacityStartVariance===J)return;if(this._opacityStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:J})}setPositionVariance(J){if(this._positionVariance&&this._positionVariance.x===J.x&&this._positionVariance.y===J.y&&this._positionVariance.z===J.z)return;if(this._positionVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:J})}setRate(J){if(this._rate===J)return;if(this._rate=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:J})}setRateVariance(J){if(this._rateVariance===J)return;if(this._rateVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:J})}setSizeEnd(J){if(this._sizeEnd===J)return;if(this._sizeEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:J})}setSizeEndVariance(J){if(this._sizeEndVariance===J)return;if(this._sizeEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:J})}setSizeStart(J){if(this._sizeStart===J)return;if(this._sizeStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:J})}setSizeStartVariance(J){if(this._sizeStartVariance===J)return;if(this._sizeStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:J})}setTextureUri(J){if(this._textureUri===J)return;if(this._textureUri=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:J})}setTransparent(J){if(this._transparent===J)return;if(this._transparent=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:J})}setVelocity(J){if(this._velocity&&this._velocity.x===J.x&&this._velocity.y===J.y&&this._velocity.z===J.z)return;if(this._velocity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:J})}setVelocityVariance(J){if(this._velocityVariance&&this._velocityVariance.x===J.x&&this._velocityVariance.y===J.y&&this._velocityVariance.z===J.z)return;if(this._velocityVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:J})}burst(J){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=J.particleEmitterManager.registerParticleEmitter(this),this._world=J,this.emitWithWorld(J,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return V8.serializeParticleEmitter(this)}}var hK6={x:0,y:-32,z:0},Jd=60,$d;((Q)=>{Q.STEP_START="SIMULATION.STEP_START";Q.STEP_END="SIMULATION.STEP_END";Q.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Q.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})($d||={});class VL extends $8{_colliderMap=new J3;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(J,$=Jd,X=hK6){super();this._rapierEventQueue=new Y5.EventQueue(!0),this._rapierSimulation=new Y5.World(X),this._rapierSimulation.timestep=Math.fround(1/$),this._world=J}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(J,$){return this._rapierSimulation.createCollider(J,$)}createRawRigidBody(J){return this._rapierSimulation.createRigidBody(J)}enableDebugRaycasting(J){this._debugRaycastingEnabled=J}enableDebugRendering(J,$=Y5.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=J,this._debugRenderingFilterFlags=$}getContactManifolds(J,$){let X=[];return this._rapierSimulation.narrowPhase.contactPair(J,$,(Y,Q)=>{if(Y.numContacts()===0)return;let W=Y.normal(),K=[];for(let Z=0;Z<Y.numSolverContacts();Z++)K.push(Y.solverContactPoint(Z));X.push({contactPoints:K,localNormalA:!Q?Y.localNormal1():Y.localNormal2(),localNormalB:!Q?Y.localNormal2():Y.localNormal1(),normal:!Q?W:{x:-W.x,y:-W.y,z:-W.z}})}),X}intersectionsWithRawShape(J,$,X,Y={}){let Q=new Set,W=[];return this._rapierSimulation.intersectionsWithShape($,X,J,(K)=>{let Z=this._colliderMap.getColliderHandleBlockType(K.handle);if(Z&&!Q.has(Z))return Q.add(Z),W.push({intersectedBlockType:Z}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!Q.has(G))return Q.add(G),W.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),W}raycast(J,$,X,Y={}){let Q=new Y5.Ray(J,$),W=this._rapierSimulation.castRay(Q,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:J,direction:$,length:X,hit:!!W});if(!W)return null;let K=Q.pointAt(W.timeOfImpact),Z=W.timeOfImpact,G=W.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:NG.fromGlobalCoordinate({x:Math.floor(K.x-(Q.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-(Q.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-(Q.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:Z};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:Z};return null}removeRawCollider(J){this._colliderMap.queueColliderHandleForCleanup(J.handle),this._rapierSimulation.removeCollider(J,!1)}removeRawRigidBody(J){this._rapierSimulation.removeRigidBody(J)}setGravity(J){this._rapierSimulation.gravity=J}step=(J)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:J});let $=performance.now();if(w6.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),w6.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()-$}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(J,$,X)=>{let[Y,Q]=this._getCollisionObjects(J,$);if(!Y||!Q)return;let W=(K,Z)=>{if(K instanceof wJ&&Z instanceof v6&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof v6&&Z instanceof wJ&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof v6&&Z instanceof v6&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(typeof K==="function"&&(Z instanceof v6||Z instanceof wJ))K(Z,X,J,$)};W(Y,Q),W(Q,Y)};_onContactForceEvent=(J)=>{let[$,X]=this._getCollisionObjects(J.collider1(),J.collider2());if(!$||typeof $==="function"||!X||typeof X==="function")return;let Y={totalForce:J.totalForce(),totalForceMagnitude:J.totalForceMagnitude(),maxForceDirection:J.maxForceDirection(),maxForceMagnitude:J.maxForceMagnitude()},Q=(W,K)=>{if(W instanceof wJ&&K instanceof v6&&W.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))W.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:W,entity:K,contactForceData:Y});else if(W instanceof v6&&K instanceof wJ&&W.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))W.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:W,blockType:K,contactForceData:Y});else if(W instanceof v6&&K instanceof v6&&W.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))W.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:W,otherEntity:K,contactForceData:Y})};Q($,X),Q(X,$)};_getCollisionObjects(J,$){let X=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J),Y=this._colliderMap.getColliderHandleBlockType($)??this._colliderMap.getColliderHandleCollisionCallback($)??this._colliderMap.getColliderHandleEntity($);return[X,Y]}}class nP{_synchronizedPlayerReliablePackets=new H9;_queuedBroadcasts=[];_queuedAudioSynchronizations=new H9;_queuedBlockSynchronizations=new H9;_queuedBlockTypeSynchronizations=new H9;_queuedChunkSynchronizations=new H9;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new H9;_queuedLightSynchronizations=new H9;_queuedParticleEmitterSynchronizations=new H9;_queuedPerPlayerSynchronizations=new H9;_queuedPerPlayerCameraSynchronizations=new H9;_queuedPerPlayerUISynchronizations=new H9;_queuedPerPlayerUIDatasSynchronizations=new H9;_queuedPlayerSynchronizations=new H9;_queuedSceneUISynchronizations=new H9;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(J){this._world=J,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let J=[],$=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let Y=[],Q=[];for(let W of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let Z in W)if(Z!=="i"&&Z!=="p"&&Z!=="r"){K=!0;break}if(K)Y.push(W);else Q.push(W)}if(Q.length>0){let W=h0.createPacket(h0.outboundPackets.entitiesPacketDefinition,Q,X);$.push(W)}if(Y.length>0){let W=h0.createPacket(h0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(W);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(W)}}if(this._queuedAudioSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUISynchronizations){let W=h0.createPacket(h0.outboundPackets.uiPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUIDatasSynchronizations){let W=h0.createPacket(h0.outboundPackets.uiDatasPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedSceneUISynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedWorldSynchronization){let Y=h0.createPacket(h0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerCameraSynchronizations){let W=h0.createPacket(h0.outboundPackets.cameraPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPlayerSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=h0.createPacket(h0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}w6.startSpan({operation:"send_all_packets"},()=>{for(let Y of s$.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get(Y)??J;if(Q.length>0)Y.connection.send(Q);if($.length>0)Y.connection.send($,!1)}}),w6.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();i$.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pa=!0,delete $.pl,delete $.r};_onAudioPlay=(J)=>{let $=J.audio.serialize();$.pl=!0,delete $.pa,delete $.r,this._queuedAudioSynchronizations.set($.i,$)};_onAudioPlayRestart=(J)=>{let $=J.audio.serialize();$.r=!0,delete $.pa,delete $.pl,this._queuedAudioSynchronizations.set($.i,$)};_onAudioSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onAudioSetCutoffDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.cd=J.cutoffDistance};_onAudioSetDetune=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.de=J.detune};_onAudioSetDistortion=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.di=J.distortion};_onAudioSetPosition=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.position?void 0:$.e,$.p=J.position?V8.serializeVector(J.position):void 0};_onAudioSetPlaybackRate=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pr=J.playbackRate};_onAudioSetReferenceDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.rd=J.referenceDistance};_onAudioSetVolume=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.v=J.volume};_onBlockTypeRegistryRegisterBlockType=(J)=>{let $=J.blockType.serialize();this._queuedBlockTypeSynchronizations.set(J.blockType.id,$)};_onChatSendBroadcastMessage=(J)=>{let{player:$,message:X,color:Y}=J;this._queuedBroadcasts.push(h0.createPacket(h0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:$?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(J)=>{let{player:$,message:X,color:Y}=J,Q=this._queuedPerPlayerSynchronizations.get($)??[];Q.push(h0.createPacket(h0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,Q)};_onChunkLatticeAddChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk);$.b=Array.from(J.chunk.blocks),$.rm=void 0,this._spawnedChunks.add($.c.join(","))};_onChunkLatticeRemoveChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk),X=$.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else $.rm=!0};_onChunkLatticeSetBlock=(J)=>{let $=this._createOrGetQueuedBlockSync(J.globalCoordinate);$.i=J.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.ap=J.playbackRate};_onEntitySpawn=(J)=>{let $=J.entity.serialize();this._queuedEntitySynchronizations.set($.i,$),this._spawnedEntities.add($.i)};_onEntityDespawn=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if(this._spawnedEntities.has($.i))this._queuedEntitySynchronizations.delete($.i),this._spawnedEntities.delete($.i);else $.rm=!0};_onEntitySetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.h=Array.from(J.modelHiddenNodes)};_onEntitySetModelScale=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sv=J.modelScale?V8.serializeVector(J.modelScale):void 0};_onEntitySetModelShownNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sn=Array.from(J.modelShownNodes)};_onEntitySetModelTextureUri=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.mt=J.modelTextureUri};_onEntitySetOpacity=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.o=J.opacity};_onEntitySetParent=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.pe=J.parent?J.parent.id:void 0,$.pn=J.parentNodeName};_onEntitySetTintColor=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.t=J.tintColor?V8.serializeRgbColor(J.tintColor):void 0};_onEntityStartModelLoopedAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al=Array.from(new Set([...$.al??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.ao=Array.from(new Set([...$.ao??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al)$.al=$.al.filter((X)=>!J.animations.has(X)).filter(Boolean);if($.ao)$.ao=$.ao.filter((X)=>!J.animations.has(X)).filter(Boolean);$.as=Array.from(new Set([...$.as??[],...J.animations]))};_onEntityUpdateRotation=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.r=[J.rotation.x,J.rotation.y,J.rotation.z,J.rotation.w]};_onEntityUpdatePosition=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.p=[J.position.x,J.position.y,J.position.z]};_onLightDespawn=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.rm=!0};_onLightSetAngle=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.a=J.angle};_onLightSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onLightSetColor=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.c=V8.serializeRgbColor(J.color)};_onLightSetDistance=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.d=J.distance};_onLightSetIntensity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.n=J.intensity};_onLightSetOffset=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onLightSetPenumbra=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.pe=J.penumbra};_onLightSetPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.p=J.position?V8.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onLightSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.te=J.entity?J.entity.id:void 0,$.tp=J.entity?void 0:$.tp};_onLightSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.tp=J.position?V8.serializeVector(J.position):void 0,$.te=J.position?void 0:$.te};_onLightSpawn=(J)=>{let $=J.light.serialize();this._queuedLightSynchronizations.set($.i,$)};_onParticleEmitterBurst=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.b=J.count};_onParticleEmitterDespawn=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rm=!0};_onParticleEmitterSetAlphaTest=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.at=J.alphaTest};_onParticleEmitterSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onParticleEmitterSetAttachedToEntityNodeName=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.en=J.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ce=J.colorEnd?V8.serializeRgbColor(J.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cev=J.colorEndVariance?V8.serializeRgbColor(J.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cs=J.colorStart?V8.serializeRgbColor(J.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.csv=J.colorStartVariance?V8.serializeRgbColor(J.colorStartVariance):void 0};_onParticleEmitterSetGravity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.g=J.gravity?V8.serializeVector(J.gravity):void 0};_onParticleEmitterSetLifetime=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.l=J.lifetime};_onParticleEmitterSetLifetimeVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.lv=J.lifetimeVariance};_onParticleEmitterSetMaxParticles=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.mp=J.maxParticles};_onParticleEmitterSetOffset=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onParticleEmitterSetOpacityEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oe=J.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oev=J.opacityEndVariance};_onParticleEmitterSetOpacityStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.os=J.opacityStart};_onParticleEmitterSetOpacityStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.osv=J.opacityStartVariance};_onParticleEmitterSetPaused=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pa=J.paused};_onParticleEmitterSetPosition=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.p=J.position?V8.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e,$.en=J.position?void 0:$.en};_onParticleEmitterSetPositionVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pv=J.positionVariance?V8.serializeVector(J.positionVariance):void 0};_onParticleEmitterSetRate=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.r=J.rate};_onParticleEmitterSetRateVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rv=J.rateVariance};_onParticleEmitterSetSizeEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.se=J.sizeEnd};_onParticleEmitterSetSizeEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.sev=J.sizeEndVariance};_onParticleEmitterSetSizeStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ss=J.sizeStart};_onParticleEmitterSetSizeStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ssv=J.sizeStartVariance};_onParticleEmitterSetTextureUri=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.tu=J.textureUri};_onParticleEmitterSetTransparent=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.t=J.transparent};_onParticleEmitterSetVelocity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.v=J.velocity?V8.serializeVector(J.velocity):void 0};_onParticleEmitterSetVelocityVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.vv=J.velocityVariance?V8.serializeVector(J.velocityVariance):void 0};_onParticleEmitterSpawn=(J)=>{let $=J.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set($.i,$)};_onPlayerCameraLookAtEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=V8.serializeVector(J.entity.position),delete $.et,delete $.pt};_onPlayerCameraLookAtPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=J.position?V8.serializeVector(J.position):void 0,delete $.et,delete $.pt};_onPlayerCameraSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.e=J.entity.id,delete $.p};_onPlayerCameraSetAttachedToPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.p=J.position?V8.serializeVector(J.position):void 0,delete $.e};_onPlayerCameraSetFilmOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fo=J.filmOffset};_onPlayerCameraSetForwardOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.ffo=J.forwardOffset};_onPlayerCameraSetFov=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fv=J.fov};_onPlayerCameraSetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.h=Array.from(J.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.s=Array.from(J.modelShownNodes)};_onPlayerCameraSetMode=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.m=J.mode};_onPlayerCameraSetOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onPlayerCameraSetShoulderAngle=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.sa=J.shoulderAngle};_onPlayerCameraSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.et=J.entity?J.entity.id:void 0,delete $.pl,delete $.pt};_onPlayerCameraSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pt=J.position?V8.serializeVector(J.position):void 0,delete $.et,delete $.pl};_onPlayerCameraSetZoom=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.z=J.zoom};_onPlayerJoinedWorld=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(h0.createPacket(h0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Q)=>{if($.camera.attachedToEntity===void 0&&Q instanceof kX&&Q.player===$)$.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.playersPacketDefinition,s$.instance.getConnectedPlayers().map((Q)=>Q.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync($.camera);this._queuedPerPlayerCameraSynchronizations.set($,{...$.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set($,X),this._queuedPlayerSynchronizations.set($.id,$.serialize())};_onPlayerLeftWorld=(J)=>{let $=this._createOrGetQueuedPlayerSync(J.player);$.rm=!0};_onPlayerReconnectedWorld=(J)=>{this._onPlayerJoinedWorld(J)};_onPlayerRequestNotificationPermission=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(h0.createPacket(h0.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,X)};_onPlayerRequestSync=(J)=>{J.player.connection.send([h0.createPacket(h0.outboundPackets.syncResponsePacketDefinition,{r:J.receivedAt,s:Date.now(),p:performance.now()-J.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.u=J.htmlUri};_onPlayerUILockPointer=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.p=J.lock};_onPlayerUISendData=(J)=>{this._createOrGetQueuedPlayerUIDatasSync(J.playerUI).push(J.data)};_onSceneUILoad=(J)=>{let $=J.sceneUI.serialize();this._queuedSceneUISynchronizations.set($.i,$),this._loadedSceneUIs.add($.i)};_onSceneUISetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onSceneUISetOffset=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onSceneUISetPosition=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.p=J.position?V8.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onSceneUISetState=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.s=J.state};_onSceneUISetViewDistance=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.v=J.viewDistance};_onSceneUIUnload=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);if(this._loadedSceneUIs.has($.i))this._queuedSceneUISynchronizations.delete($.i),this._loadedSceneUIs.delete($.i);else $.rm=!0};_onSimulationDebugRaycast=(J)=>{this._queuedDebugRaycastSynchronizations.push(V8.serializePhysicsDebugRaycast(J))};_onSimulationDebugRender=(J)=>{this._queuedBroadcasts.push(h0.createPacket(h0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(J.vertices),c:Array.from(J.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ac=V8.serializeRgbColor(J.color)};_onWorldSetAmbientLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ai=J.intensity};_onWorldSetDirectionalLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dc=V8.serializeRgbColor(J.color)};_onWorldSetDirectionalLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.di=J.intensity};_onWorldSetDirectionalLightPosition=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dp=V8.serializeVector(J.position)};_onWorldSetFogColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fc=V8.serializeRgbColor(J.color)};_onWorldSetFogFar=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ff=J.far};_onWorldSetFogNear=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fn=J.near};_onWorldSetSkyboxIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.si=J.intensity};_onWorldSetSkyboxUri=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.s=J.uri};_createOrGetQueuedAudioSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let $=this._queuedAudioSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedAudioSynchronizations.set(J.id,$);return $}_createOrGetQueuedBlockSync(J){let{x:$,y:X,z:Y}=J,Q=`${$},${X},${Y}`,W=this._queuedBlockSynchronizations.get(Q);if(!W)W={i:0,c:[$,X,Y]},this._queuedBlockSynchronizations.set(Q,W);return W}_createOrGetQueuedChunkSync(J){if(!J.originCoordinate)n.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:$,y:X,z:Y}=J.originCoordinate,Q=`${$},${X},${Y}`,W=this._queuedChunkSynchronizations.get(Q);if(!W)W={c:[$,X,Y]},this._queuedChunkSynchronizations.set(Q,W);return W}_createOrGetQueuedEntitySync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let $=this._queuedEntitySynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedEntitySynchronizations.set(J.id,$);return $}_createOrGetQueuedLightSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let $=this._queuedLightSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedLightSynchronizations.set(J.id,$);return $}_createOrGetQueuedParticleEmitterSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let $=this._queuedParticleEmitterSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedParticleEmitterSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let $=this._queuedPlayerSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedPlayerSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerCameraSync(J){let $=this._queuedPerPlayerCameraSynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerCameraSynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUISync(J){let $=this._queuedPerPlayerUISynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerUISynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUIDatasSync(J){let $=this._queuedPerPlayerUIDatasSynchronizations.get(J.player);if(!$)$=[],this._queuedPerPlayerUIDatasSynchronizations.set(J.player,$);return $}_createOrGetQueuedSceneUISync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let $=this._queuedSceneUISynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedSceneUISynchronizations.set(J.id,$);return $}_createOrGetQueuedWorldSync(J){if(J.id!==this._world.id)n.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:J.id}}_createOrGetSynchronizedPlayerReliablePackets(J,$){let X=this._synchronizedPlayerReliablePackets.get(J);if(!X)X=[...$],this._synchronizedPlayerReliablePackets.set(J,X);return X}}class HL{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedParticleEmitters(J){this.getAllEntityAttachedParticleEmitters(J).forEach(($)=>{$.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(J){return this.getAllParticleEmitters().filter(($)=>$.attachedToEntity===J)}registerParticleEmitter(J){if(J.id!==void 0)return J.id;let $=this._nextParticleEmitterId;return this._particleEmitters.set($,J),this._nextParticleEmitterId++,$}unregisterParticleEmitter(J){if(J.id===void 0)return;this._particleEmitters.delete(J.id)}}class qL{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(J){this._world=J}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(J){return this.getAllSceneUIs().filter(($)=>$.attachedToEntity===J)}getSceneUIById(J){return this._sceneUIs.get(J)}registerSceneUI(J){if(J.id!==void 0)return J.id;let $=this._nextSceneUIId;return this._sceneUIs.set($,J),this._nextSceneUIId++,$}unloadEntityAttachedSceneUIs(J){this.getAllEntityAttachedSceneUIs(J).forEach(($)=>{$.unload()})}unregisterSceneUI(J){if(J.id===void 0)return;this._sceneUIs.delete(J.id)}}var xK6=2,fK6=3;class zL{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(J,$,X){this._targetTicksPerSecond=J,this._fixedTimestepS=Math.fround(1/J),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*fK6,this._tickFunction=$,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 J=()=>{let $=performance.now(),X=$-this._lastLoopTimeMs;if(this._lastLoopTimeMs=$,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)w6.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<xK6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(J,this._nextTickMs)};J()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(J){try{this._tickFunction(J)}catch($){if($ instanceof Error&&this._tickErrorCallback)this._tickErrorCallback($);else n.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${$}`)}}}var Iq8;((W)=>{W.START="WORLD_LOOP.START";W.STOP="WORLD_LOOP.STOP";W.TICK_START="WORLD_LOOP.TICK_START";W.TICK_END="WORLD_LOOP.TICK_END";W.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(Iq8||={});class FL extends $8{_currentTick=0;_ticker;_world;constructor(J,$=Jd){super();this._ticker=new zL($,this._tick,this._onTickError),this._world=J}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=(J)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:J});let $=performance.now();w6.startSpan({operation:"world_tick",attributes:{serverPlayerCount:s$.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}},()=>{w6.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(J)),w6.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(J)),w6.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),w6.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-$})};_onTickError=(J)=>{n.error(`WorldLoop._onTickError(): Error: ${J}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:J})}}var Xd;((q)=>{q.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";q.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";q.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";q.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";q.SET_FOG_FAR="WORLD.SET_FOG_FAR";q.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";q.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";q.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";q.START="WORLD.START";q.STOP="WORLD.STOP"})(Xd||={});class UL extends $8{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(J){super();if(this._id=J.id,this._ambientLightColor=J.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=J.ambientLightIntensity??1,this._directionalLightColor=J.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=J.directionalLightIntensity??3,this._directionalLightPosition=J.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=J.fogColor,this._fogFar=J.fogFar??550,this._fogNear=J.fogNear??500,this._name=J.name,this._skyboxIntensity=J.skyboxIntensity??1,this._skyboxUri=J.skyboxUri,this._tag=J.tag,this._audioManager=new rq(this),this._blockTypeRegistry=new FU(this),this._chatManager=new tU(this),this._chunkLattice=new eU(this),this._entityManager=new Y3(this),this._lightManager=new GL(this),this._loop=new FL(this,J.tickRate),this._networkSynchronizer=new nP(this),this._particleEmitterManager=new HL(this),this._sceneUIManager=new qL(this),this._simulation=new VL(this,J.tickRate,J.gravity),J.map)this.loadMap(J.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(J){if(this.chunkLattice.clear(),J.blockTypes)for(let $ of J.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:$.id,isLiquid:$.isLiquid,lightLevel:$.lightLevel,name:$.name,textureUri:$.textureUri});if(J.blocks){let $={};for(let X in J.blocks){let Y=J.blocks[X],Q=X.indexOf(","),W=X.indexOf(",",Q+1),K=Number(X.slice(0,Q)),Z=Number(X.slice(Q+1,W)),G=Number(X.slice(W+1));if(!$[Y])$[Y]=[];$[Y].push({x:K,y:Z,z:G})}this.chunkLattice.initializeBlocks($)}if(J.entities)for(let $ in J.entities){let X=J.entities[$],Y=$.indexOf(","),Q=$.indexOf(",",Y+1),W=Number($.slice(0,Y)),K=Number($.slice(Y+1,Q)),Z=Number($.slice(Q+1));new v6({isEnvironmental:!0,...X}).spawn(this,{x:W,y:K,z:Z})}}setAmbientLightColor(J){this._ambientLightColor=J,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:J})}setAmbientLightIntensity(J){this._ambientLightIntensity=J,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightColor(J){this._directionalLightColor=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:J})}setDirectionalLightIntensity(J){this._directionalLightIntensity=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightPosition(J){this._directionalLightPosition=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:J})}setFogColor(J){this._fogColor=J,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:J})}setFogFar(J){this._fogFar=J,this.emit("WORLD.SET_FOG_FAR",{world:this,far:J})}setFogNear(J){this._fogNear=J,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:J})}setSkyboxIntensity(J){this._skyboxIntensity=J,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:J})}setSkyboxUri(J){this._skyboxUri=J,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:J})}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 V8.serializeWorld(this)}}var Aq8;(($)=>$.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(Aq8||={});class tW{static instance=new tW;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(J){let $=new UL({...J,id:this._nextWorldId++});return $.start(),this._worlds.set($.id,$),$8.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:$}),$}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(J){let $=[];return this._worlds.forEach((X)=>{if(X.tag===J)$.push(X)}),$}getWorld(J){return this._worlds.get(J)}setDefaultWorld(J){this._defaultWorld=J}}var _q8;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(_q8||={});class s${static instance=new s$;worldSelectionHandler;_connectionPlayers=new Map;constructor(){$8.globalInstance.on("CONNECTION.OPENED",({connection:J,session:$})=>{this._onConnectionOpened(J,$)}),$8.globalInstance.on("CONNECTION.DISCONNECTED",({connection:J})=>{this._onConnectionDisconnected(J)}),$8.globalInstance.on("CONNECTION.RECONNECTED",({connection:J})=>{this._onConnectionReconnected(J)}),$8.globalInstance.on("CONNECTION.CLOSED",({connection:J})=>{this._onConnectionClosed(J)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(J){return this.getConnectedPlayers().filter(($)=>$.world===J)}getConnectedPlayerByUsername(J){return Array.from(this._connectionPlayers.values()).find(($)=>{return $.username.toLowerCase()===J.toLowerCase()})}async _onConnectionOpened(J,$){let X=new TH(J,$);await X.loadInitialPersistedData(),$8.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??tW.instance.getDefaultWorld()),this._connectionPlayers.set(J,X)}_onConnectionDisconnected(J){let $=this._connectionPlayers.get(J);if($)$.resetInputs(),$.camera.reset()}_onConnectionReconnected(J){let $=this._connectionPlayers.get(J);if($)$.reconnected(),$8.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionReconnected(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(J){let $=this._connectionPlayers.get(J);if($)$.disconnect(),this._connectionPlayers.delete(J),sQ.instance.unloadPlayerData($).catch((X)=>{n.warning(`PlayerManager._onConnectionClosed(): Failed to unload player data for player ${$.id}. Error: ${X}`)}),$8.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionClosed(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as gK6}from"crypto";import{Http3Server as mK6}from"@fails-components/webtransport";class BL extends $8{static instance=new BL;_connectionIdConnections=new Map;_userIdConnections=new Map;_wss;_wts;constructor(){super();this._wss=new gv.default({noServer:!0}),this._wss.on("connection",(J,$)=>this._onConnection(J,void 0,$.connectionId,$.session)),this._wts=new mK6({port:pP,host:"0.0.0.0",secret:gK6(32).toString("hex"),cert:lP,privKey:cP,defaultDatagramsReadableMode:"bytes",initialStreamFlowControlWindow:1048576,streamShouldAutoTuneReceiveWindow:!0,streamFlowControlWindowSizeLimit:6291456,initialSessionFlowControlWindow:2097152,sessionShouldAutoTuneReceiveWindow:!0,sessionFlowControlWindowSizeLimit:15728640}),this._wts.setRequestCallback(this._onWebTransportRequest),this._startWebTransport().catch((J)=>{n.error(`Socket: WebTransport server failed to start or crashed while listening for sessions. Error: ${J}`)}),$8.globalInstance.on("WEBSERVER.UPGRADE",async({req:J,socket:$,head:X})=>{$.on("error",()=>{}),await this._authorizeAndConnectWebsocket(J,$,X)})}async _authorizeAndConnectWebsocket(J,$,X){let Y=await this._authorizeConnection(J.url??"");if(Y.error){$.end();return}J.connectionId=Y.connectionId,J.session=Y.session,$.setNoDelay(!0),this._wss.handleUpgrade(J,$,X,(Q)=>{if(Q.readyState!==PH.default.OPEN)Q.once("open",()=>this._wss.emit("connection",Q,J));else this._wss.emit("connection",Q,J)})}async _authorizeConnection(J){let $=J.includes("?")?J.slice(J.indexOf("?")):"",X=new URLSearchParams($),Y=X.get("connectionId")??void 0,Q=X.get("sessionToken")??"";if(Y&&this._isValidConnectionId(Y))return{connectionId:Y};else{let W=await L1.instance.getPlayerSession(Q);if(W?.error)return{error:W.error};else if(W)return{session:W}}return{}}_isValidConnectionId(J){return this._connectionIdConnections.has(J)}_onConnection=(J,$,X,Y)=>{let Q=Y?.user.id,W=(X&&this._connectionIdConnections.get(X))??(Q&&this._userIdConnections.get(Q));if(W){if(J)W.bindWs(J);if($)W.bindWt($).catch((K)=>{n.error(`Socket._onConnection(): WebTransport binding failed. Error: ${K}`)})}else{let K=new i$(J,$,Y);if(K.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(K.id),Q)this._userIdConnections.delete(Q)}),this._connectionIdConnections.set(K.id,K),Q)this._userIdConnections.set(Q,K)}};_onWebTransportRequest=async({header:J})=>{let{connectionId:$,session:X,error:Y}=await this._authorizeConnection(J[":path"]??"");return{status:Y?401:200,path:"/",userData:{connectionId:$,session:X}}};async _startWebTransport(){this._wts.startServer();for await(let J of this._wts.sessionStream("/"))try{let{connectionId:$,session:X}=J.userData;this._onConnection(void 0,J,$,X)}catch($){n.error(`Socket._startWebTransport(): WebTransport connection failed. Error: ${$}`)}}}Buffer.poolSize=134217728;var vq8;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(vq8||={});function uK6(J){Y5.init().then(()=>{return eW.instance.blockTextureRegistry.preloadAtlas()}).then(()=>{return eW.instance.modelRegistry.preloadModels()}).then(()=>{if(J.length>0)J(eW.instance.worldManager.getDefaultWorld());else J();eW.instance.start()}).catch(($)=>{n.fatalError(`Failed to initialize the game engine, exiting. Error: ${$}`)})}class eW{static _instance;_blockTextureRegistry=RQ.instance;_modelRegistry=R9.instance;_playerManager=s$.instance;_socket=BL.instance;_worldManager=tW.instance;_webServer=mq.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new eW;return this._instance}get blockTextureRegistry(){return this._blockTextureRegistry}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){if($8.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start(),process.env.NODE_ENV!=="production")console.log("---"),console.log("\uD83D\uDFE2 Server Running: You can test & play it at: https://hytopia.com/play");n.enableCrashProtection()}}var q9=O0(LG(),1);class jG extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get determinant(){return q9.mat2.determinant(this)}get frobeniusNorm(){return q9.mat2.frob(this)}static create(){let J=new jG(0,0,0,0);return q9.mat2.identity(J),J}static fromRotation(J){let $=jG.create();return q9.mat2.fromRotation($,J),$}static fromScaling(J){let $=jG.create();return q9.mat2.fromScaling($,J),$}add(J){return q9.mat2.add(this,this,J),this}adjoint(){return q9.mat2.adjoint(this,this),this}clone(){return new jG(this[0],this[1],this[2],this[3])}copy(J){return q9.mat2.copy(this,J),this}equals(J){return q9.mat2.equals(this,J)}exactEquals(J){return q9.mat2.exactEquals(this,J)}identity(){return q9.mat2.identity(this),this}invert(){return q9.mat2.invert(this,this),this}multiply(J){return q9.mat2.mul(this,this,J),this}multiplyScalar(J){return q9.mat2.multiplyScalar(this,this,J),this}rotate(J){return q9.mat2.rotate(this,this,J),this}subtract(J){return q9.mat2.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return q9.mat2.transpose(this,this),this}}var P6=O0(LG(),1);class tX extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G){super([J,$,X,Y,Q,W,K,Z,G])}get determinant(){return P6.mat3.determinant(this)}get frobeniusNorm(){return P6.mat3.frob(this)}static create(){let J=new tX(0,0,0,0,0,0,0,0,0);return P6.mat3.identity(J),J}static fromMatrix4(J){let $=tX.create();return P6.mat3.fromMat4($,J),$}static fromQuaternion(J){let $=tX.create();return P6.mat3.fromQuat($,J),$}static fromRotation(J){let $=tX.create();return P6.mat3.fromRotation($,J),$}static fromScaling(J){let $=tX.create();return P6.mat3.fromScaling($,J),$}static fromTranslation(J){let $=tX.create();return P6.mat3.fromTranslation($,J),$}add(J){return P6.mat3.add(this,this,J),this}adjoint(){return P6.mat3.adjoint(this,this),this}clone(){return new tX(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(J){return P6.mat3.copy(this,J),this}equals(J){return P6.mat3.equals(this,J)}exactEquals(J){return P6.mat3.exactEquals(this,J)}identity(){return P6.mat3.identity(this),this}invert(){return P6.mat3.invert(this,this),this}multiply(J){return P6.mat3.mul(this,this,J),this}multiplyScalar(J){return P6.mat3.multiplyScalar(this,this,J),this}transformVector(J){return J.transformMatrix3(this)}projection(J,$){return P6.mat3.projection(this,J,$),this}rotate(J){return P6.mat3.rotate(this,this,J),this}subtract(J){return P6.mat3.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return P6.mat3.transpose(this,this),this}}var e8=O0(LG(),1);class I7 extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G,V,H,z,q,F,U,B){super([J,$,X,Y,Q,W,K,Z,G,V,H,z,q,F,U,B])}get determinant(){return e8.mat4.determinant(this)}get frobeniusNorm(){return e8.mat4.frob(this)}static create(){let J=new I7(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e8.mat4.identity(J),J}static fromQuaternion(J){let $=I7.create();return e8.mat4.fromQuat($,J),$}static fromRotation(J,$){let X=I7.create();return e8.mat4.fromRotation(X,J,$),X}static fromRotationTranslation(J,$){let X=I7.create();return e8.mat4.fromRotationTranslation(X,J,$),X}static fromRotationTranslationScale(J,$,X){let Y=I7.create();return e8.mat4.fromRotationTranslationScale(Y,J,$,X),Y}static fromRotationTranslationScaleOrigin(J,$,X,Y){let Q=I7.create();return e8.mat4.fromRotationTranslationScaleOrigin(Q,J,$,X,Y),Q}static fromScaling(J){let $=I7.create();return e8.mat4.fromScaling($,J),$}static fromTranslation(J){let $=I7.create();return e8.mat4.fromTranslation($,J),$}static fromXRotation(J){let $=I7.create();return e8.mat4.fromXRotation($,J),$}static fromYRotation(J){let $=I7.create();return e8.mat4.fromYRotation($,J),$}static fromZRotation(J){let $=I7.create();return e8.mat4.fromZRotation($,J),$}add(J){return e8.mat4.add(this,this,J),this}adjoint(){return e8.mat4.adjoint(this,this),this}clone(){return new I7(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(J){return e8.mat4.copy(this,J),this}equals(J){return e8.mat4.equals(this,J)}exactEquals(J){return e8.mat4.exactEquals(this,J)}frustrum(J,$,X,Y,Q,W){return e8.mat4.frustum(this,J,$,X,Y,Q,W),this}identity(){return e8.mat4.identity(this),this}invert(){return e8.mat4.invert(this,this),this}lookAt(J,$,X){return e8.mat4.lookAt(this,J,$,X),this}multiply(J){return e8.mat4.mul(this,this,J),this}multiplyScalar(J){return e8.mat4.multiplyScalar(this,this,J),this}orthographic(J,$,X,Y,Q,W){return e8.mat4.ortho(this,J,$,X,Y,Q,W),this}perspective(J,$,X,Y){return e8.mat4.perspective(this,J,$,X,Y),this}rotate(J,$){return e8.mat4.rotate(this,this,J,$),this}rotateX(J){return e8.mat4.rotateX(this,this,J),this}rotateY(J){return e8.mat4.rotateY(this,this,J),this}rotateZ(J){return e8.mat4.rotateZ(this,this,J),this}scale(J){return e8.mat4.scale(this,this,J),this}subtract(J){return e8.mat4.sub(this,this,J),this}targetTo(J,$,X){return e8.mat4.targetTo(this,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(J){return e8.mat4.translate(this,this,J),this}transpose(){return e8.mat4.transpose(this,this),this}}var h5=O0(LG(),1);class uq extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get length(){return h5.quat.length(this)}get squaredLength(){return h5.quat.squaredLength(this)}get magnitude(){return h5.quat.length(this)}get squaredMagnitude(){return h5.quat.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}get w(){return this[3]}set w(J){this[3]=J}static fromEuler(J,$,X){let Y=h5.quat.fromEuler(new Float32Array(4),J,$,X);return new uq(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(J){return new uq(J.x,J.y,J.z,J.w)}clone(){return new uq(this.x,this.y,this.z,this.w)}conjugate(){return h5.quat.conjugate(this,this),this}copy(J){return h5.quat.copy(this,J),this}dot(J){return h5.quat.dot(this,J)}exponential(){return h5.quat.exp(this,this),this}equals(J){return h5.quat.equals(this,J)}exactEquals(J){return h5.quat.exactEquals(this,J)}getAngle(J){return h5.quat.getAngle(this,J)}identity(){return h5.quat.identity(this),this}invert(){return h5.quat.invert(this,this),this}lerp(J,$){return h5.quat.lerp(this,this,J,$),this}logarithm(){return h5.quat.ln(this,this),this}multiply(J){return h5.quat.multiply(this,this,J),this}transformVector(J){return J.transformQuaternion(this)}normalize(){return h5.quat.normalize(this,this),this}power(J){return h5.quat.pow(this,this,J),this}randomize(){return h5.quat.random(this),this}rotateX(J){return h5.quat.rotateX(this,this,J),this}rotateY(J){return h5.quat.rotateY(this,this,J),this}rotateZ(J){return h5.quat.rotateZ(this,this,J),this}scale(J){return h5.quat.scale(this,this,J),this}setAxisAngle(J,$){return h5.quat.setAxisAngle(this,J,$),this}slerp(J,$){return h5.quat.slerp(this,this,J,$),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var L5=O0(LG(),1);class LL extends Float32Array{constructor(J,$){super([J,$])}get length(){return L5.vec2.length(this)}get squaredLength(){return L5.vec2.squaredLength(this)}get magnitude(){return L5.vec2.length(this)}get squaredMagnitude(){return L5.vec2.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}static create(){return new LL(0,0)}add(J){return L5.vec2.add(this,this,J),this}angle(J){return L5.vec2.angle(this,J)}ceil(){return L5.vec2.ceil(this,this),this}clone(){return new LL(this.x,this.y)}copy(J){return L5.vec2.copy(this,J),this}distance(J){return L5.vec2.distance(this,J)}divide(J){return L5.vec2.divide(this,this,J),this}dot(J){return L5.vec2.dot(this,J)}equals(J){return L5.vec2.equals(this,J)}exactEquals(J){return L5.vec2.exactEquals(this,J)}floor(){return L5.vec2.floor(this,this),this}invert(){return L5.vec2.inverse(this,this),this}lerp(J,$){return L5.vec2.lerp(this,this,J,$),this}max(J){return L5.vec2.max(this,this,J),this}min(J){return L5.vec2.min(this,this,J),this}multiply(J){return L5.vec2.mul(this,this,J),this}negate(){return L5.vec2.negate(this,this),this}normalize(){return L5.vec2.normalize(this,this),this}randomize(J){return L5.vec2.random(this,J),this}rotate(J,$){return L5.vec2.rotate(this,this,J,$),this}round(){return L5.vec2.round(this,this),this}scale(J){return L5.vec2.scale(this,this,J),this}scaleAndAdd(J,$){return L5.vec2.scaleAndAdd(this,this,J,$),this}subtract(J){return L5.vec2.sub(this,this,J),this}toString(){return`${this.x},${this.y}`}transformMatrix2(J){return L5.vec2.transformMat2(this,this,J),this}transformMatrix3(J){return L5.vec2.transformMat3(this,this,J),this}transformMatrix4(J){return L5.vec2.transformMat4(this,this,J),this}zero(){return L5.vec2.zero(this),this}}var H5=O0(LG(),1);class dq extends Float32Array{constructor(J,$,X){super([J,$,X])}get length(){return H5.vec3.length(this)}get squaredLength(){return H5.vec3.squaredLength(this)}get magnitude(){return H5.vec3.length(this)}get squaredMagnitude(){return H5.vec3.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}static create(){return new dq(0,0,0)}static fromVector3Like(J){return new dq(J.x,J.y,J.z)}add(J){return H5.vec3.add(this,this,J),this}ceil(){return H5.vec3.ceil(this,this),this}clone(){return new dq(this.x,this.y,this.z)}copy(J){return H5.vec3.copy(this,J),this}cross(J){return H5.vec3.cross(this,this,J),this}distance(J){return H5.vec3.distance(this,J)}divide(J){return H5.vec3.div(this,this,J),this}dot(J){return H5.vec3.dot(this,J)}equals(J){return H5.vec3.equals(this,J)}exactEquals(J){return H5.vec3.exactEquals(this,J)}floor(){return H5.vec3.floor(this,this),this}invert(){return H5.vec3.inverse(this,this),this}lerp(J,$){return H5.vec3.lerp(this,this,J,$),this}max(J){return H5.vec3.max(this,this,J),this}min(J){return H5.vec3.min(this,this,J),this}multiply(J){return H5.vec3.mul(this,this,J),this}negate(){return H5.vec3.negate(this,this),this}normalize(){return H5.vec3.normalize(this,this),this}randomize(J){return H5.vec3.random(this,J),this}rotateX(J,$){return H5.vec3.rotateX(this,this,J,$),this}rotateY(J,$){return H5.vec3.rotateY(this,this,J,$),this}rotateZ(J,$){return H5.vec3.rotateZ(this,this,J,$),this}round(){return H5.vec3.round(this,this),this}scale(J){return H5.vec3.scale(this,this,J),this}scaleAndAdd(J,$){return H5.vec3.scaleAndAdd(this,this,J,$),this}subtract(J){return H5.vec3.sub(this,this,J),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(J){return H5.vec3.transformMat3(this,this,J),this}transformMatrix4(J){return H5.vec3.transformMat4(this,this,J),this}transformQuaternion(J){return H5.vec3.transformQuat(this,this,J),this}zero(){return H5.vec3.zero(this),this}}var RF8=O0(NF8(),1);var OF8=0.099856;class jL extends WK{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=OF8;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(J={}){super();this.idleLoopedAnimations=J.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=J.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=J.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=J.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=J.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(J){super.spawn(J),this._startIdleAnimations(J)}face(J,$,X){this._faceTarget=J,this.faceSpeed=$,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(J){this._jumpHeight=J}move(J,$,X){this.moveSpeed=$,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:OF8,this._moveTarget=J,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(J,$){if(super.tick(J,$),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(J),this._moveStartMoveAnimations=!1;let X=$/1000,Y=J.position;if(J.isDynamic&&this._jumpHeight>0){let Q=Math.abs(J.world.simulation.gravity.y),W=Math.sqrt(2*Q*this._jumpHeight);J.applyImpulse({x:0,y:W*J.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(J)}if(this._moveTarget){let Q={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},W=Q.x*Q.x+Q.y*Q.y+Q.z*Q.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=$,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let Z=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(Z*Z+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(W>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let Z=Math.sqrt(W),G=this.moveSpeed*X,H=Math.min(Z,G)/Z,z={x:Y.x+Q.x*H,y:Y.y+Q.y*H,z:Y.z+Q.z*H};if(J.setPosition(z),this._onMove)this._onMove(z,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(J);if(this._onMoveComplete){let Z=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,Z(Y)}}}if(this._faceTarget){let Q={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},W=Math.atan2(-Q.x,-Q.z),K=J.rotation,Z=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=W-Z;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,q=(Z+H)/2,F={x:0,y:Math.fround(Math.sin(q)),z:0,w:Math.fround(Math.cos(q))};if(J.setRotation(F),this._onFace)this._onFace(K,F)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(J.rotation)}}}_startIdleAnimations(J){if(this.idleLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.jumpOneshotAnimations),J.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(J){J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(J){if(this.moveLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);J.stopModelAnimations(this.jumpOneshotAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelLoopedAnimations(this.moveLoopedAnimations)}}class qd extends jL{_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(J={}){super(J)}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(J,$,X){if(this._target=J,this._speed=$,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/$,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(J){super.attach(J),this._entity=J}detach(J){super.detach(J),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return n.error("PathfindingEntityController._calculatePath: No target or world"),!1;let J=this._entity.height,$=this._findGroundedStart();if(!$){if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-$.x),Q=Math.abs(X.y-$.y),W=Math.abs(X.z-$.z);if(Y<=2&&Q<=2&&W<=2&&!this._isNeighborCoordinateBlocked($,X,this._entity.height))return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5},{x:X.x+0.5,y:X.y+J/2,z:X.z+0.5}],!0;if($.x===X.x&&$.y===X.y&&$.z===X.z)return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5}],!0;let Z=this._coordinateToKey($),G=new Map,V=new Map([[Z,0]]),H=new Map([[Z,this._pathfindingHeuristic($,X)]]),z=new Set,q=new RF8.Heap((D,w)=>{let R=H.get(D[0])??1/0,N=H.get(w[0])??1/0;return R-N});q.push([Z,$]);let F=[{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 D=this._maxJump;D>=this._maxFall;D--){if(D===0)continue;let w=Math.abs($.y+D-X.y);U.push({y:D,distanceToTargetY:w})}U.sort((D,w)=>D.distanceToTargetY-w.distanceToTargetY);let B=[...F,...U.flatMap(({y:D})=>F.map((w)=>({...w,y:D})))],L=0,j=Math.abs(X.x-$.x)+Math.abs(X.y-$.y)+Math.abs(X.z-$.z),M=Math.min(this._maxOpenSetIterations,j*20);while(!q.isEmpty()&&L<M){L++;let[D,w]=q.pop();if(w.x===X.x&&w.y===X.y&&w.z===X.z){let O=this._reconstructPath(G,w);if(this._waypoints=O.map((C)=>({x:C.x+0.5,y:C.y+J/2,z:C.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return!0}z.add(D);let R=V.get(D),N=new Map;for(let O of B){let C=`${O.x},${O.z}`,S=O.y<0;if(S&&N.has(C))continue;let _={x:w.x+O.x,y:w.y+O.y,z:w.z+O.z};if(Math.abs(X.x-_.x)+Math.abs(X.y-_.y)+Math.abs(X.z-_.z)>j*1.5)continue;let A=this._coordinateToKey(_);if(z.has(A))continue;let k=this._isNeighborCoordinateBlocked(w,_,this._entity.height);if(S&&k){N.set(C,!0);continue}if(k)continue;let I=Math.abs(O.x),y=Math.abs(O.y),v=Math.abs(O.z),x=y===0?0:this._verticalPenalty,h=(Math.max(I,y,v)===1&&I+y+v>1?1.4:1)+x,m=R+h,c=V.get(A)??1/0;if(m>=c)continue;G.set(A,w),V.set(A,m);let l=m+this._pathfindingHeuristic(_,X);H.set(A,l),q.push([A,_])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)n.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(J,$){let X=[$],Y=$;while(J.has(this._coordinateToKey(Y)))Y=J.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(J){return`${J.x},${J.y},${J.z}`}_moveToNextWaypoint(){let J=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,$=this._waypoints[this._waypointNextIndex];if(!$||!this._entity)return;let X=0;if(this._entity.isDynamic&&J&&$.y>J.y){let Y=$.y-J.y,Q=Math.min(Y,this._maxJump)+0.75;this.jump(Q);let W=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*W*Q),Z=J.x+0.5,G=J.z+0.5,V=$.x+0.5,H=$.z+0.5,z=V-Z,q=H-G,F=Math.sqrt(z*z+q*q),U=K/W,B=F/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face($,this._speed),this.move($,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(J,$){return Math.abs(J.x-$.x)+Math.abs(J.y-$.y)+Math.abs(J.z-$.z)}_isNeighborCoordinateBlocked(J,$,X){if(!this._entity?.world)return!1;let Y=this._entity.world,Q=Math.floor($.x),W=Math.floor($.y),K=Math.floor($.z),Z=Math.floor(J.x),G=Math.floor(J.z);if(!Y.chunkLattice.hasBlock({x:Q,y:W-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:Q,y:W+V,z:K}))return!0;if(Q!==Z&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:Q,y:W+V,z:G}),z=Y.chunkLattice.hasBlock({x:Z,y:W+V,z:K});if(H||z)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:J,y:$,z:X}=this._entity.position,Y={x:Math.floor(J),y:Math.floor($),z:Math.floor(X)};for(let Q=0;Q<=Math.abs(this._maxFall);Q++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-Q-1}))return{...Y,y:Y.y-Q};return}}export{uK6 as startServer,Aq8 as WorldManagerEvent,tW as WorldManager,Iq8 as WorldLoopEvent,FL as WorldLoop,Xd as WorldEvent,UL as World,ru as WebServerEvent,mq as WebServer,dq as Vector3,LL as Vector2,zL as Ticker,FG as TelemetrySpanOperation,w6 as Telemetry,$d as SimulationEvent,VL as Simulation,jL as SimpleEntityController,qL as SceneUIManager,sv as SceneUIEvent,X3 as SceneUI,Jr8 as SUPPORTED_INPUTS,zU as RigidBodyType,xQ as RigidBody,uq as Quaternion,uO as PlayerUIEvent,aU as PlayerUI,_q8 as PlayerManagerEvent,s$ as PlayerManager,oU as PlayerEvent,kX as PlayerEntity,MK0 as PlayerCameraMode,cv as PlayerCameraEvent,rU as PlayerCamera,TH as Player,sQ as PersistenceManager,qd as PathfindingEntityController,HL as ParticleEmitterManager,tu as ParticleEmitterEvent,eu as ParticleEmitter,wK0 as PLAYER_ROTATION_UPDATE_THRESHOLD,DK0 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,R9 as ModelRegistry,I7 as Matrix4,tX as Matrix3,jG as Matrix2,kq8 as LightType,GL as LightManager,au as LightEvent,ou as Light,H9 as IterationMap,vq8 as GameServerEvent,eW as GameServer,$8 as EventRouter,n as ErrorHandler,Y3 as EntityManager,$3 as EntityEvent,v6 as Entity,RK0 as ENTITY_ROTATION_UPDATE_THRESHOLD,OK0 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,f5 as DefaultPlayerEntityController,rv as DefaultPlayerEntity,NK0 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,L$ as CollisionGroupsBuilder,hK as CollisionGroup,WH as ColliderShape,J3 as ColliderMap,DJ as Collider,gA as CoefficientCombineRule,iv as ChunkLatticeEvent,eU as ChunkLattice,c7 as Chunk,tU as ChatManager,pv as ChatEvent,uA as BlockTypeRegistryEvent,FU as BlockTypeRegistry,mA as BlockTypeEvent,wJ as BlockType,RQ as BlockTextureRegistry,NG as Block,Dd as BaseEntityControllerEvent,WK as BaseEntityController,rq as AudioManager,HC as AudioEvent,sq as Audio,p6 as AssetsLibrary};
252
+ -----END PRIVATE KEY-----`;var pP=process.env.PORT??8080,su="0.14.17",ru;((Q)=>{Q.READY="WEBSERVER.READY";Q.STOPPED="WEBSERVER.STOPPED";Q.ERROR="WEBSERVER.ERROR";Q.UPGRADE="WEBSERVER.UPGRADE"})(ru||={});var gq={"access-control-allow-origin":"*"},AK6=JSON.stringify({status:"OK",version:su,runtime:"node"}),_K6={".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".gltf":"model/gltf+json",".glb":"model/gltf-binary",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".ktx2":"image/ktx2",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".bin":"application/octet-stream",".wasm":"application/wasm"};class mq extends $8{static instance=new mq;_server;_assetCache=new Map;_assetDirs=[];constructor(){super();this._assetDirs.push(iu.resolve("assets"));let J=p6.assetsLibraryPath;if(J)this._assetDirs.push(J)}start(){if(this._server)return n.warning("WebServer.start(): already started");this._server=IK6.createSecureServer({key:cP,cert:lP,allowHTTP1:!0}),this._server.on("stream",this._onStream),this._server.on("upgrade",this._onUpgrade),this._server.on("error",this._onError),this._server.on("close",this._onStopped),this._server.listen(pP,this._onStarted),console.info(`WebServer.start(): Server running on port ${pP}`)}stop(){if(!this._server)return n.warning("WebServer.stop(): not started"),Promise.resolve(!1);return new Promise((J,$)=>{this._server.close((X)=>X?$(X):J(!0))})}_onStarted=()=>this.emitWithGlobal("WEBSERVER.READY",{});_onStopped=()=>this.emitWithGlobal("WEBSERVER.STOPPED",{});_onError=(J)=>{n.error(`WebServer._onError(): ${J.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:J})};_onStream=(J,$)=>{let X=$[":path"]||"/",Q=($[":method"]||"GET")==="HEAD";if(X==="/"){J.respond({":status":200,"content-type":"application/json",...gq}),J.end(!Q?AK6:void 0);return}let W=decodeURIComponent(X.split("?")[0]);if(W.includes("..")){J.respond({":status":400,...gq}),J.end();return}for(let K of this._assetDirs){let Z=iu.join(K,W);if(!Z.startsWith(K))continue;let G=p6.assetsLibraryPath;if(G&&Z.startsWith(G))p6.instance.syncAsset(Z);let V=this._assetCache.get(Z);if(!V)try{let q=kK6.statSync(Z);if(!q.isFile())continue;V={size:q.size,etag:`"${q.mtimeMs.toString(36)}-${q.size.toString(36)}"`},this._assetCache.set(Z,V)}catch{continue}if($["if-none-match"]===V.etag){J.respond({":status":304,...gq}),J.end();return}let z={":status":200,"content-type":_K6[iu.extname(Z).toLowerCase()]||"application/octet-stream","content-length":V.size,etag:V.etag,"cache-control":"public, max-age=0, must-revalidate",...gq};if(Q){J.respond(z),J.end();return}J.respondWithFile(Z,z,{onError:(q)=>{if(!J.destroyed)J.respond({":status":500,...gq}),J.end();n.error(`WebServer: ${q.message}`)}});return}J.respond({":status":404,...gq}),J.end()};_onUpgrade=(J,$,X)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:J,socket:$,head:X})}}var FG;((B)=>{B.BUILD_PACKETS="build_packets";B.ENTITIES_EMIT_UPDATES="entities_emit_updates";B.ENTITIES_TICK="entities_tick";B.NETWORK_SYNCHRONIZE="network_synchronize";B.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";B.PHYSICS_CLEANUP="physics_cleanup";B.PHYSICS_STEP="physics_step";B.SEND_ALL_PACKETS="send_all_packets";B.SEND_PACKETS="send_packets";B.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";B.SERIALIZE_PACKETS="serialize_packets";B.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";B.SIMULATION_STEP="simulation_step";B.TICKER_TICK="ticker_tick";B.WORLD_TICK="world_tick"})(FG||={});class w6{static getProcessStats(J=!1){let $=process.memoryUsage(),X={jsHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:$.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:$.heapUsed/$.heapTotal,unit:"percent"},processHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:$.rss/1024/1024,unit:"megabyte"}};if(J)return X;return Object.fromEntries(Object.entries(X).map(([Y,Q])=>[Y,Q.value]))}static initializeSentry(J,$=50){dP({dsn:J,release:su,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=w6.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Q=X?.start_timestamp,W=X?.timestamp;if(!Q||!W)return null;if((W-Q)*1000>$)return X.measurements=w6.getProcessStats(!0),X}return null}})}static startSpan(J,$){if(A3())return w1({attributes:J.attributes,name:J.operation,op:J.operation},$);else return $()}static sentry(){return nu}}if(!aO)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var Sq8=new ZZ({useFloat32:Z3.ALWAYS}),yK6=30000;class i$ extends $8{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(J,$,X){super();this.id=kZ0(),this.onPacket(h0.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{$8.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:X})};if(J)this.bindWs(J),Y();else if($)this.bindWt($).then(Y).catch((Q)=>{this._onClose(),n.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${Q}`)})}static clearCachedPacketsSerializedBuffers(){if(i$._cachedPacketsSerializedBuffer.size>0)i$._cachedPacketsSerializedBuffer.clear()}static serializePackets(J){for(let X of J)if(!h0.isValidPacket(X))return n.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let $=i$._cachedPacketsSerializedBuffer.get(J);if($)return $;return w6.startSpan({operation:"serialize_packets",attributes:{packets:J.length,packetIds:J.map((X)=>X[0]).join(",")}},(X)=>{let Y=Sq8.pack(J);if(Y.byteLength>65536)Y=vK6(Y,{level:1});return X?.setAttribute("serializedBytes",Y.byteLength),i$._cachedPacketsSerializedBuffer.set(J,Y),Y})}bindWs(J){this._wsBinding=!0;let $=this._handleReconnect();if(this._cleanupConnections(),this._ws=J,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(J){this._wtBinding=!0;let $=this._handleReconnect();this._cleanupConnections(),J.userData.onclose=this._onClose,J.closed.catch(()=>{}).finally(()=>J.userData.onclose?.()),this._wt=J,await this._wt.ready;let X=this._wt.incomingBidirectionalStreams.getReader();try{let{value:Y}=await X.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{X.releaseLock()}if(this._wtUnreliableReader=this._wt.datagrams.readable,this._wtUnreliableWriter=this._wt.datagrams.createWritable().getWriter(),(async()=>{if(!this._wtReliableReader)return;let Y=this._wt,Q=h0.createPacketBufferUnframer((W)=>{this._onMessage(W)});for await(let W of this._wtReliableReader){if(Y!==this._wt)return;Q(W)}})().catch(()=>this._wt?.close()),(async()=>{if(!this._wtUnreliableReader)return;let Y=this._wt;for await(let Q of this._wtUnreliableReader){if(Y!==this._wt)return;this._onMessage(Q)}})().catch(()=>this._wt?.close()),this._wtBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(J){n.error(`Connection.disconnect(): Connection disconnect failed. Error: ${J}`)}}onPacket(J,$){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===J)$(X)})}send(J,$=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let X=this._ws&&this._ws.readyState===PH.default.OPEN,Y=this._wt&&(this._wt.state==="connected"||this._wt.state==="draining");if(!X&&!Y)return;w6.startSpan({operation:"send_packets"},()=>{try{let Q=i$.serializePackets(J);if(!Q)return;if(Y)if($||Q.byteLength>1200)this._wtReliableWriter?.write(h0.framePacketBuffer(Q)).catch(()=>{n.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(Q).catch(()=>{n.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(Q);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:J})}catch(Q){n.error(`Connection.send(): Packet send failed. Error: ${Q}`)}})}_onHeartbeatPacket=()=>{this.send([h0.createPacket(h0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(J)=>{try{let $=this._deserialize(J);if(!$)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:$})}catch($){n.error(`Connection._ws.onmessage(): Error: ${$}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},yK6)};_onError=(J)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:J})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill(),this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(J){let $=Sq8.unpack(J);if(!$||typeof $!=="object"||typeof $[0]!=="number")return n.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify($)}`);if(!h0.isValidPacket($))return n.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify($)}`);return $}_handleReconnect(){let J=!!this._ws||!!this._wt;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return J}_signalConnectionId(){this.send([h0.createPacket(h0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([h0.createPacket(h0.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class GL{_lights=new Map;_nextLightId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedLights(J){this.getAllEntityAttachedLights(J).forEach(($)=>{$.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(J){return this.getAllLights().filter(($)=>$.attachedToEntity===J)}registerLight(J){if(J.id!==void 0)return J.id;let $=this._nextLightId;return this._lights.set($,J),this._nextLightId++,$}unregisterLight(J){if(J.id===void 0)return;this._lights.delete(J.id)}}class H9{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(J){return this._map.get(J)}set(J,$){let X=this._map.has(J);if(this._map.set(J,$),!X)this._values.push($);else this._isDirty=!0;return this}has(J){return this._map.has(J)}delete(J){let $=this._map.delete(J);if($)this._isDirty=!0;return $}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(J,$){this._map.forEach((X,Y)=>{J.call($,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 J of this._map.values())this._values.push(J);this._isDirty=!1}}var kq8;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(kq8||={});var au;((q)=>{q.DESPAWN="LIGHT.DESPAWN";q.SET_ANGLE="LIGHT.SET_ANGLE";q.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";q.SET_COLOR="LIGHT.SET_COLOR";q.SET_DISTANCE="LIGHT.SET_DISTANCE";q.SET_INTENSITY="LIGHT.SET_INTENSITY";q.SET_OFFSET="LIGHT.SET_OFFSET";q.SET_PENUMBRA="LIGHT.SET_PENUMBRA";q.SET_POSITION="LIGHT.SET_POSITION";q.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";q.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";q.SPAWN="LIGHT.SPAWN"})(au||={});class ou extends $8{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");super();n.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=J.angle,this._attachedToEntity=J.attachedToEntity,this._color=J.color??{r:255,g:255,b:255},this._distance=J.distance,this._intensity=J.intensity??1,this._offset=J.offset,this._penumbra=J.penumbra,this._position=J.position,this._trackedEntity=J.trackedEntity,this._trackedPosition=J.trackedPosition,this._type=J.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(J){if(this._angle===J)return;if(this._angle=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`Light.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:J})}setColor(J){if(this._color.r===J.r&&this._color.g===J.g&&this._color.b===J.b)return;if(this._color=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:J})}setDistance(J){if(this._distance===J)return;if(this._distance=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:J})}setIntensity(J){if(this._intensity===J)return;if(this._intensity=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:J})}setPenumbra(J){if(this._penumbra===J)return;if(this._penumbra=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:J})}setTrackedEntity(J){if(!J.isSpawned)return n.error(`Light.setTrackedEntity(): Entity ${J.id} is not spawned!`);if(this._trackedEntity===J)return;if(this._trackedEntity=J,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:J})}setTrackedPosition(J){if(this._trackedPosition===J)return;if(this._trackedPosition=J,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:J})}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(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=J.lightManager.registerLight(this),this._world=J,this.emitWithWorld(J,"LIGHT.SPAWN",{light:this})}serialize(){return V8.serializeLight(this)}}var tu;((v)=>{v.BURST="PARTICLE_EMITTER.BURST";v.DESPAWN="PARTICLE_EMITTER.DESPAWN";v.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";v.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";v.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";v.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";v.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";v.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";v.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";v.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";v.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";v.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";v.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";v.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";v.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";v.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";v.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";v.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";v.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";v.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";v.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";v.SET_RATE="PARTICLE_EMITTER.SET_RATE";v.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";v.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";v.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";v.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";v.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";v.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";v.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";v.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";v.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";v.SPAWN="PARTICLE_EMITTER.SPAWN"})(tu||={});class eu extends $8{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");if(!J.textureUri)n.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=J.alphaTest??0.05,this._attachedToEntity=J.attachedToEntity,this._attachedToEntityNodeName=J.attachedToEntityNodeName,this._colorEnd=J.colorEnd,this._colorEndVariance=J.colorEndVariance,this._colorStart=J.colorStart,this._colorStartVariance=J.colorStartVariance,this._gravity=J.gravity,this._lifetime=J.lifetime,this._lifetimeVariance=J.lifetimeVariance,this._maxParticles=J.maxParticles,this._offset=J.offset,this._opacityEnd=J.opacityEnd,this._opacityEndVariance=J.opacityEndVariance,this._opacityStart=J.opacityStart,this._opacityStartVariance=J.opacityStartVariance,this._paused=!1,this._position=J.position,this._positionVariance=J.positionVariance,this._rate=J.rate,this._rateVariance=J.rateVariance,this._sizeEnd=J.sizeEnd,this._sizeEndVariance=J.sizeEndVariance,this._sizeStart=J.sizeStart,this._sizeStartVariance=J.sizeStartVariance,this._textureUri=J.textureUri,this._transparent=J.transparent,this._velocity=J.velocity,this._velocityVariance=J.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(J){if(this._alphaTest===J)return;if(this._alphaTest=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`ParticleEmitter.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:J})}setAttachedToEntityNodeName(J){if(this._attachedToEntityNodeName===J)return;if(this._attachedToEntityNodeName=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:J})}setColorEnd(J){if(this._colorEnd&&this._colorEnd.r===J.r&&this._colorEnd.g===J.g&&this._colorEnd.b===J.b)return;if(this._colorEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:J})}setColorEndVariance(J){if(this._colorEndVariance&&this._colorEndVariance.r===J.r&&this._colorEndVariance.g===J.g&&this._colorEndVariance.b===J.b)return;if(this._colorEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:J})}setColorStart(J){if(this._colorStart&&this._colorStart.r===J.r&&this._colorStart.g===J.g&&this._colorStart.b===J.b)return;if(this._colorStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:J})}setColorStartVariance(J){if(this._colorStartVariance&&this._colorStartVariance.r===J.r&&this._colorStartVariance.g===J.g&&this._colorStartVariance.b===J.b)return;if(this._colorStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:J})}setGravity(J){if(this._gravity&&this._gravity.x===J.x&&this._gravity.y===J.y&&this._gravity.z===J.z)return;if(this._gravity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:J})}setLifetime(J){if(this._lifetime===J)return;if(this._lifetime=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:J})}setLifetimeVariance(J){if(this._lifetimeVariance===J)return;if(this._lifetimeVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:J})}setMaxParticles(J){if(this._maxParticles===J)return;if(this._maxParticles=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:J})}setOpacityEnd(J){if(this._opacityEnd===J)return;if(this._opacityEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:J})}setOpacityEndVariance(J){if(this._opacityEndVariance===J)return;if(this._opacityEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:J})}setOpacityStart(J){if(this._opacityStart===J)return;if(this._opacityStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:J})}setOpacityStartVariance(J){if(this._opacityStartVariance===J)return;if(this._opacityStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:J})}setPositionVariance(J){if(this._positionVariance&&this._positionVariance.x===J.x&&this._positionVariance.y===J.y&&this._positionVariance.z===J.z)return;if(this._positionVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:J})}setRate(J){if(this._rate===J)return;if(this._rate=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:J})}setRateVariance(J){if(this._rateVariance===J)return;if(this._rateVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:J})}setSizeEnd(J){if(this._sizeEnd===J)return;if(this._sizeEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:J})}setSizeEndVariance(J){if(this._sizeEndVariance===J)return;if(this._sizeEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:J})}setSizeStart(J){if(this._sizeStart===J)return;if(this._sizeStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:J})}setSizeStartVariance(J){if(this._sizeStartVariance===J)return;if(this._sizeStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:J})}setTextureUri(J){if(this._textureUri===J)return;if(this._textureUri=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:J})}setTransparent(J){if(this._transparent===J)return;if(this._transparent=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:J})}setVelocity(J){if(this._velocity&&this._velocity.x===J.x&&this._velocity.y===J.y&&this._velocity.z===J.z)return;if(this._velocity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:J})}setVelocityVariance(J){if(this._velocityVariance&&this._velocityVariance.x===J.x&&this._velocityVariance.y===J.y&&this._velocityVariance.z===J.z)return;if(this._velocityVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:J})}burst(J){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=J.particleEmitterManager.registerParticleEmitter(this),this._world=J,this.emitWithWorld(J,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return V8.serializeParticleEmitter(this)}}var hK6={x:0,y:-32,z:0},Jd=60,$d;((Q)=>{Q.STEP_START="SIMULATION.STEP_START";Q.STEP_END="SIMULATION.STEP_END";Q.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Q.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})($d||={});class VL extends $8{_colliderMap=new J3;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(J,$=Jd,X=hK6){super();this._rapierEventQueue=new Y5.EventQueue(!0),this._rapierSimulation=new Y5.World(X),this._rapierSimulation.timestep=Math.fround(1/$),this._world=J}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(J,$){return this._rapierSimulation.createCollider(J,$)}createRawRigidBody(J){return this._rapierSimulation.createRigidBody(J)}enableDebugRaycasting(J){this._debugRaycastingEnabled=J}enableDebugRendering(J,$=Y5.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=J,this._debugRenderingFilterFlags=$}getContactManifolds(J,$){let X=[];return this._rapierSimulation.narrowPhase.contactPair(J,$,(Y,Q)=>{if(Y.numContacts()===0)return;let W=Y.normal(),K=[];for(let Z=0;Z<Y.numSolverContacts();Z++)K.push(Y.solverContactPoint(Z));X.push({contactPoints:K,localNormalA:!Q?Y.localNormal1():Y.localNormal2(),localNormalB:!Q?Y.localNormal2():Y.localNormal1(),normal:!Q?W:{x:-W.x,y:-W.y,z:-W.z}})}),X}intersectionsWithRawShape(J,$,X,Y={}){let Q=new Set,W=[];return this._rapierSimulation.intersectionsWithShape($,X,J,(K)=>{let Z=this._colliderMap.getColliderHandleBlockType(K.handle);if(Z&&!Q.has(Z))return Q.add(Z),W.push({intersectedBlockType:Z}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!Q.has(G))return Q.add(G),W.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),W}raycast(J,$,X,Y={}){let Q=new Y5.Ray(J,$),W=this._rapierSimulation.castRay(Q,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:J,direction:$,length:X,hit:!!W});if(!W)return null;let K=Q.pointAt(W.timeOfImpact),Z=W.timeOfImpact,G=W.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:NG.fromGlobalCoordinate({x:Math.floor(K.x-(Q.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-(Q.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-(Q.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:Z};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:Z};return null}removeRawCollider(J){this._colliderMap.queueColliderHandleForCleanup(J.handle),this._rapierSimulation.removeCollider(J,!1)}removeRawRigidBody(J){this._rapierSimulation.removeRigidBody(J)}setGravity(J){this._rapierSimulation.gravity=J}step=(J)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:J});let $=performance.now();if(w6.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),w6.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()-$}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(J,$,X)=>{let[Y,Q]=this._getCollisionObjects(J,$);if(!Y||!Q)return;let W=(K,Z)=>{if(K instanceof wJ&&Z instanceof v6&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof v6&&Z instanceof wJ&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof v6&&Z instanceof v6&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(typeof K==="function"&&(Z instanceof v6||Z instanceof wJ))K(Z,X,J,$)};W(Y,Q),W(Q,Y)};_onContactForceEvent=(J)=>{let[$,X]=this._getCollisionObjects(J.collider1(),J.collider2());if(!$||typeof $==="function"||!X||typeof X==="function")return;let Y={totalForce:J.totalForce(),totalForceMagnitude:J.totalForceMagnitude(),maxForceDirection:J.maxForceDirection(),maxForceMagnitude:J.maxForceMagnitude()},Q=(W,K)=>{if(W instanceof wJ&&K instanceof v6&&W.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))W.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:W,entity:K,contactForceData:Y});else if(W instanceof v6&&K instanceof wJ&&W.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))W.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:W,blockType:K,contactForceData:Y});else if(W instanceof v6&&K instanceof v6&&W.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))W.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:W,otherEntity:K,contactForceData:Y})};Q($,X),Q(X,$)};_getCollisionObjects(J,$){let X=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J),Y=this._colliderMap.getColliderHandleBlockType($)??this._colliderMap.getColliderHandleCollisionCallback($)??this._colliderMap.getColliderHandleEntity($);return[X,Y]}}class nP{_synchronizedPlayerReliablePackets=new H9;_queuedBroadcasts=[];_queuedAudioSynchronizations=new H9;_queuedBlockSynchronizations=new H9;_queuedBlockTypeSynchronizations=new H9;_queuedChunkSynchronizations=new H9;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new H9;_queuedLightSynchronizations=new H9;_queuedParticleEmitterSynchronizations=new H9;_queuedPerPlayerSynchronizations=new H9;_queuedPerPlayerCameraSynchronizations=new H9;_queuedPerPlayerUISynchronizations=new H9;_queuedPerPlayerUIDatasSynchronizations=new H9;_queuedPlayerSynchronizations=new H9;_queuedSceneUISynchronizations=new H9;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(J){this._world=J,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let J=[],$=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let Y=[],Q=[];for(let W of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let Z in W)if(Z!=="i"&&Z!=="p"&&Z!=="r"){K=!0;break}if(K)Y.push(W);else Q.push(W)}if(Q.length>0){let W=h0.createPacket(h0.outboundPackets.entitiesPacketDefinition,Q,X);$.push(W)}if(Y.length>0){let W=h0.createPacket(h0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(W);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(W)}}if(this._queuedAudioSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUISynchronizations){let W=h0.createPacket(h0.outboundPackets.uiPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUIDatasSynchronizations){let W=h0.createPacket(h0.outboundPackets.uiDatasPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedSceneUISynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedWorldSynchronization){let Y=h0.createPacket(h0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerCameraSynchronizations){let W=h0.createPacket(h0.outboundPackets.cameraPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPlayerSynchronizations.size>0){let Y=h0.createPacket(h0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=h0.createPacket(h0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}w6.startSpan({operation:"send_all_packets"},()=>{for(let Y of s$.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get(Y)??J;if(Q.length>0)Y.connection.send(Q);if($.length>0)Y.connection.send($,!1)}}),w6.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();i$.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pa=!0,delete $.pl,delete $.r};_onAudioPlay=(J)=>{let $=J.audio.serialize();$.pl=!0,delete $.pa,delete $.r,this._queuedAudioSynchronizations.set($.i,$)};_onAudioPlayRestart=(J)=>{let $=J.audio.serialize();$.r=!0,delete $.pa,delete $.pl,this._queuedAudioSynchronizations.set($.i,$)};_onAudioSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onAudioSetCutoffDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.cd=J.cutoffDistance};_onAudioSetDetune=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.de=J.detune};_onAudioSetDistortion=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.di=J.distortion};_onAudioSetPosition=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.position?void 0:$.e,$.p=J.position?V8.serializeVector(J.position):void 0};_onAudioSetPlaybackRate=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pr=J.playbackRate};_onAudioSetReferenceDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.rd=J.referenceDistance};_onAudioSetVolume=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.v=J.volume};_onBlockTypeRegistryRegisterBlockType=(J)=>{let $=J.blockType.serialize();this._queuedBlockTypeSynchronizations.set(J.blockType.id,$)};_onChatSendBroadcastMessage=(J)=>{let{player:$,message:X,color:Y}=J;this._queuedBroadcasts.push(h0.createPacket(h0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:$?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(J)=>{let{player:$,message:X,color:Y}=J,Q=this._queuedPerPlayerSynchronizations.get($)??[];Q.push(h0.createPacket(h0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,Q)};_onChunkLatticeAddChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk);$.b=Array.from(J.chunk.blocks),$.rm=void 0,this._spawnedChunks.add($.c.join(","))};_onChunkLatticeRemoveChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk),X=$.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else $.rm=!0};_onChunkLatticeSetBlock=(J)=>{let $=this._createOrGetQueuedBlockSync(J.globalCoordinate);$.i=J.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.ap=J.playbackRate};_onEntitySpawn=(J)=>{let $=J.entity.serialize();this._queuedEntitySynchronizations.set($.i,$),this._spawnedEntities.add($.i)};_onEntityDespawn=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if(this._spawnedEntities.has($.i))this._queuedEntitySynchronizations.delete($.i),this._spawnedEntities.delete($.i);else $.rm=!0};_onEntitySetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.h=Array.from(J.modelHiddenNodes)};_onEntitySetModelScale=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sv=J.modelScale?V8.serializeVector(J.modelScale):void 0};_onEntitySetModelShownNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sn=Array.from(J.modelShownNodes)};_onEntitySetModelTextureUri=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.mt=J.modelTextureUri};_onEntitySetOpacity=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.o=J.opacity};_onEntitySetParent=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.pe=J.parent?J.parent.id:void 0,$.pn=J.parentNodeName};_onEntitySetTintColor=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.t=J.tintColor?V8.serializeRgbColor(J.tintColor):void 0};_onEntityStartModelLoopedAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al=Array.from(new Set([...$.al??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.ao=Array.from(new Set([...$.ao??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al)$.al=$.al.filter((X)=>!J.animations.has(X)).filter(Boolean);if($.ao)$.ao=$.ao.filter((X)=>!J.animations.has(X)).filter(Boolean);$.as=Array.from(new Set([...$.as??[],...J.animations]))};_onEntityUpdateRotation=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.r=[J.rotation.x,J.rotation.y,J.rotation.z,J.rotation.w]};_onEntityUpdatePosition=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.p=[J.position.x,J.position.y,J.position.z]};_onLightDespawn=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.rm=!0};_onLightSetAngle=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.a=J.angle};_onLightSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onLightSetColor=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.c=V8.serializeRgbColor(J.color)};_onLightSetDistance=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.d=J.distance};_onLightSetIntensity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.n=J.intensity};_onLightSetOffset=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onLightSetPenumbra=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.pe=J.penumbra};_onLightSetPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.p=J.position?V8.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onLightSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.te=J.entity?J.entity.id:void 0,$.tp=J.entity?void 0:$.tp};_onLightSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.tp=J.position?V8.serializeVector(J.position):void 0,$.te=J.position?void 0:$.te};_onLightSpawn=(J)=>{let $=J.light.serialize();this._queuedLightSynchronizations.set($.i,$)};_onParticleEmitterBurst=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.b=J.count};_onParticleEmitterDespawn=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rm=!0};_onParticleEmitterSetAlphaTest=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.at=J.alphaTest};_onParticleEmitterSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onParticleEmitterSetAttachedToEntityNodeName=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.en=J.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ce=J.colorEnd?V8.serializeRgbColor(J.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cev=J.colorEndVariance?V8.serializeRgbColor(J.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cs=J.colorStart?V8.serializeRgbColor(J.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.csv=J.colorStartVariance?V8.serializeRgbColor(J.colorStartVariance):void 0};_onParticleEmitterSetGravity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.g=J.gravity?V8.serializeVector(J.gravity):void 0};_onParticleEmitterSetLifetime=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.l=J.lifetime};_onParticleEmitterSetLifetimeVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.lv=J.lifetimeVariance};_onParticleEmitterSetMaxParticles=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.mp=J.maxParticles};_onParticleEmitterSetOffset=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onParticleEmitterSetOpacityEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oe=J.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oev=J.opacityEndVariance};_onParticleEmitterSetOpacityStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.os=J.opacityStart};_onParticleEmitterSetOpacityStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.osv=J.opacityStartVariance};_onParticleEmitterSetPaused=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pa=J.paused};_onParticleEmitterSetPosition=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.p=J.position?V8.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e,$.en=J.position?void 0:$.en};_onParticleEmitterSetPositionVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pv=J.positionVariance?V8.serializeVector(J.positionVariance):void 0};_onParticleEmitterSetRate=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.r=J.rate};_onParticleEmitterSetRateVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rv=J.rateVariance};_onParticleEmitterSetSizeEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.se=J.sizeEnd};_onParticleEmitterSetSizeEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.sev=J.sizeEndVariance};_onParticleEmitterSetSizeStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ss=J.sizeStart};_onParticleEmitterSetSizeStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ssv=J.sizeStartVariance};_onParticleEmitterSetTextureUri=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.tu=J.textureUri};_onParticleEmitterSetTransparent=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.t=J.transparent};_onParticleEmitterSetVelocity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.v=J.velocity?V8.serializeVector(J.velocity):void 0};_onParticleEmitterSetVelocityVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.vv=J.velocityVariance?V8.serializeVector(J.velocityVariance):void 0};_onParticleEmitterSpawn=(J)=>{let $=J.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set($.i,$)};_onPlayerCameraLookAtEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=V8.serializeVector(J.entity.position),delete $.et,delete $.pt};_onPlayerCameraLookAtPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=J.position?V8.serializeVector(J.position):void 0,delete $.et,delete $.pt};_onPlayerCameraSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.e=J.entity.id,delete $.p};_onPlayerCameraSetAttachedToPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.p=J.position?V8.serializeVector(J.position):void 0,delete $.e};_onPlayerCameraSetFilmOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fo=J.filmOffset};_onPlayerCameraSetForwardOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.ffo=J.forwardOffset};_onPlayerCameraSetFov=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fv=J.fov};_onPlayerCameraSetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.h=Array.from(J.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.s=Array.from(J.modelShownNodes)};_onPlayerCameraSetMode=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.m=J.mode};_onPlayerCameraSetOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onPlayerCameraSetShoulderAngle=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.sa=J.shoulderAngle};_onPlayerCameraSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.et=J.entity?J.entity.id:void 0,delete $.pl,delete $.pt};_onPlayerCameraSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pt=J.position?V8.serializeVector(J.position):void 0,delete $.et,delete $.pl};_onPlayerCameraSetZoom=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.z=J.zoom};_onPlayerJoinedWorld=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(h0.createPacket(h0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Q)=>{if($.camera.attachedToEntity===void 0&&Q instanceof kX&&Q.player===$)$.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(h0.createPacket(h0.outboundPackets.playersPacketDefinition,s$.instance.getConnectedPlayers().map((Q)=>Q.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync($.camera);this._queuedPerPlayerCameraSynchronizations.set($,{...$.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set($,X),this._queuedPlayerSynchronizations.set($.id,$.serialize())};_onPlayerLeftWorld=(J)=>{let $=this._createOrGetQueuedPlayerSync(J.player);$.rm=!0};_onPlayerReconnectedWorld=(J)=>{this._onPlayerJoinedWorld(J)};_onPlayerRequestNotificationPermission=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(h0.createPacket(h0.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,X)};_onPlayerRequestSync=(J)=>{J.player.connection.send([h0.createPacket(h0.outboundPackets.syncResponsePacketDefinition,{r:J.receivedAt,s:Date.now(),p:performance.now()-J.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.u=J.htmlUri};_onPlayerUILockPointer=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.p=J.lock};_onPlayerUISendData=(J)=>{this._createOrGetQueuedPlayerUIDatasSync(J.playerUI).push(J.data)};_onSceneUILoad=(J)=>{let $=J.sceneUI.serialize();this._queuedSceneUISynchronizations.set($.i,$),this._loadedSceneUIs.add($.i)};_onSceneUISetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onSceneUISetOffset=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.o=J.offset?V8.serializeVector(J.offset):void 0};_onSceneUISetPosition=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.p=J.position?V8.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onSceneUISetState=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.s=J.state};_onSceneUISetViewDistance=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.v=J.viewDistance};_onSceneUIUnload=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);if(this._loadedSceneUIs.has($.i))this._queuedSceneUISynchronizations.delete($.i),this._loadedSceneUIs.delete($.i);else $.rm=!0};_onSimulationDebugRaycast=(J)=>{this._queuedDebugRaycastSynchronizations.push(V8.serializePhysicsDebugRaycast(J))};_onSimulationDebugRender=(J)=>{this._queuedBroadcasts.push(h0.createPacket(h0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(J.vertices),c:Array.from(J.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ac=V8.serializeRgbColor(J.color)};_onWorldSetAmbientLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ai=J.intensity};_onWorldSetDirectionalLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dc=V8.serializeRgbColor(J.color)};_onWorldSetDirectionalLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.di=J.intensity};_onWorldSetDirectionalLightPosition=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dp=V8.serializeVector(J.position)};_onWorldSetFogColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fc=V8.serializeRgbColor(J.color)};_onWorldSetFogFar=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ff=J.far};_onWorldSetFogNear=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fn=J.near};_onWorldSetSkyboxIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.si=J.intensity};_onWorldSetSkyboxUri=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.s=J.uri};_createOrGetQueuedAudioSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let $=this._queuedAudioSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedAudioSynchronizations.set(J.id,$);return $}_createOrGetQueuedBlockSync(J){let{x:$,y:X,z:Y}=J,Q=`${$},${X},${Y}`,W=this._queuedBlockSynchronizations.get(Q);if(!W)W={i:0,c:[$,X,Y]},this._queuedBlockSynchronizations.set(Q,W);return W}_createOrGetQueuedChunkSync(J){if(!J.originCoordinate)n.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:$,y:X,z:Y}=J.originCoordinate,Q=`${$},${X},${Y}`,W=this._queuedChunkSynchronizations.get(Q);if(!W)W={c:[$,X,Y]},this._queuedChunkSynchronizations.set(Q,W);return W}_createOrGetQueuedEntitySync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let $=this._queuedEntitySynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedEntitySynchronizations.set(J.id,$);return $}_createOrGetQueuedLightSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let $=this._queuedLightSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedLightSynchronizations.set(J.id,$);return $}_createOrGetQueuedParticleEmitterSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let $=this._queuedParticleEmitterSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedParticleEmitterSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let $=this._queuedPlayerSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedPlayerSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerCameraSync(J){let $=this._queuedPerPlayerCameraSynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerCameraSynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUISync(J){let $=this._queuedPerPlayerUISynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerUISynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUIDatasSync(J){let $=this._queuedPerPlayerUIDatasSynchronizations.get(J.player);if(!$)$=[],this._queuedPerPlayerUIDatasSynchronizations.set(J.player,$);return $}_createOrGetQueuedSceneUISync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let $=this._queuedSceneUISynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedSceneUISynchronizations.set(J.id,$);return $}_createOrGetQueuedWorldSync(J){if(J.id!==this._world.id)n.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:J.id}}_createOrGetSynchronizedPlayerReliablePackets(J,$){let X=this._synchronizedPlayerReliablePackets.get(J);if(!X)X=[...$],this._synchronizedPlayerReliablePackets.set(J,X);return X}}class HL{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedParticleEmitters(J){this.getAllEntityAttachedParticleEmitters(J).forEach(($)=>{$.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(J){return this.getAllParticleEmitters().filter(($)=>$.attachedToEntity===J)}registerParticleEmitter(J){if(J.id!==void 0)return J.id;let $=this._nextParticleEmitterId;return this._particleEmitters.set($,J),this._nextParticleEmitterId++,$}unregisterParticleEmitter(J){if(J.id===void 0)return;this._particleEmitters.delete(J.id)}}class qL{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(J){this._world=J}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(J){return this.getAllSceneUIs().filter(($)=>$.attachedToEntity===J)}getSceneUIById(J){return this._sceneUIs.get(J)}registerSceneUI(J){if(J.id!==void 0)return J.id;let $=this._nextSceneUIId;return this._sceneUIs.set($,J),this._nextSceneUIId++,$}unloadEntityAttachedSceneUIs(J){this.getAllEntityAttachedSceneUIs(J).forEach(($)=>{$.unload()})}unregisterSceneUI(J){if(J.id===void 0)return;this._sceneUIs.delete(J.id)}}var xK6=2,fK6=3;class zL{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(J,$,X){this._targetTicksPerSecond=J,this._fixedTimestepS=Math.fround(1/J),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*fK6,this._tickFunction=$,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 J=()=>{let $=performance.now(),X=$-this._lastLoopTimeMs;if(this._lastLoopTimeMs=$,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)w6.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<xK6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(J,this._nextTickMs)};J()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(J){try{this._tickFunction(J)}catch($){if($ instanceof Error&&this._tickErrorCallback)this._tickErrorCallback($);else n.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${$}`)}}}var Iq8;((W)=>{W.START="WORLD_LOOP.START";W.STOP="WORLD_LOOP.STOP";W.TICK_START="WORLD_LOOP.TICK_START";W.TICK_END="WORLD_LOOP.TICK_END";W.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(Iq8||={});class FL extends $8{_currentTick=0;_ticker;_world;constructor(J,$=Jd){super();this._ticker=new zL($,this._tick,this._onTickError),this._world=J}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=(J)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:J});let $=performance.now();w6.startSpan({operation:"world_tick",attributes:{serverPlayerCount:s$.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}},()=>{w6.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(J)),w6.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(J)),w6.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),w6.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-$})};_onTickError=(J)=>{n.error(`WorldLoop._onTickError(): Error: ${J}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:J})}}var Xd;((q)=>{q.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";q.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";q.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";q.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";q.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";q.SET_FOG_FAR="WORLD.SET_FOG_FAR";q.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";q.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";q.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";q.START="WORLD.START";q.STOP="WORLD.STOP"})(Xd||={});class UL extends $8{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(J){super();if(this._id=J.id,this._ambientLightColor=J.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=J.ambientLightIntensity??1,this._directionalLightColor=J.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=J.directionalLightIntensity??3,this._directionalLightPosition=J.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=J.fogColor,this._fogFar=J.fogFar??550,this._fogNear=J.fogNear??500,this._name=J.name,this._skyboxIntensity=J.skyboxIntensity??1,this._skyboxUri=J.skyboxUri,this._tag=J.tag,this._audioManager=new rq(this),this._blockTypeRegistry=new FU(this),this._chatManager=new tU(this),this._chunkLattice=new eU(this),this._entityManager=new Y3(this),this._lightManager=new GL(this),this._loop=new FL(this,J.tickRate),this._networkSynchronizer=new nP(this),this._particleEmitterManager=new HL(this),this._sceneUIManager=new qL(this),this._simulation=new VL(this,J.tickRate,J.gravity),J.map)this.loadMap(J.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(J){if(this.chunkLattice.clear(),J.blockTypes)for(let $ of J.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:$.id,isLiquid:$.isLiquid,lightLevel:$.lightLevel,name:$.name,textureUri:$.textureUri});if(J.blocks){let $={};for(let X in J.blocks){let Y=J.blocks[X],Q=X.indexOf(","),W=X.indexOf(",",Q+1),K=Number(X.slice(0,Q)),Z=Number(X.slice(Q+1,W)),G=Number(X.slice(W+1));if(!$[Y])$[Y]=[];$[Y].push({x:K,y:Z,z:G})}this.chunkLattice.initializeBlocks($)}if(J.entities)for(let $ in J.entities){let X=J.entities[$],Y=$.indexOf(","),Q=$.indexOf(",",Y+1),W=Number($.slice(0,Y)),K=Number($.slice(Y+1,Q)),Z=Number($.slice(Q+1));new v6({isEnvironmental:!0,...X}).spawn(this,{x:W,y:K,z:Z})}}setAmbientLightColor(J){this._ambientLightColor=J,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:J})}setAmbientLightIntensity(J){this._ambientLightIntensity=J,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightColor(J){this._directionalLightColor=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:J})}setDirectionalLightIntensity(J){this._directionalLightIntensity=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightPosition(J){this._directionalLightPosition=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:J})}setFogColor(J){this._fogColor=J,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:J})}setFogFar(J){this._fogFar=J,this.emit("WORLD.SET_FOG_FAR",{world:this,far:J})}setFogNear(J){this._fogNear=J,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:J})}setSkyboxIntensity(J){this._skyboxIntensity=J,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:J})}setSkyboxUri(J){this._skyboxUri=J,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:J})}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 V8.serializeWorld(this)}}var Aq8;(($)=>$.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(Aq8||={});class tW{static instance=new tW;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(J){let $=new UL({...J,id:this._nextWorldId++});return $.start(),this._worlds.set($.id,$),$8.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:$}),$}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(J){let $=[];return this._worlds.forEach((X)=>{if(X.tag===J)$.push(X)}),$}getWorld(J){return this._worlds.get(J)}setDefaultWorld(J){this._defaultWorld=J}}var _q8;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(_q8||={});class s${static instance=new s$;worldSelectionHandler;_connectionPlayers=new Map;constructor(){$8.globalInstance.on("CONNECTION.OPENED",({connection:J,session:$})=>{this._onConnectionOpened(J,$)}),$8.globalInstance.on("CONNECTION.DISCONNECTED",({connection:J})=>{this._onConnectionDisconnected(J)}),$8.globalInstance.on("CONNECTION.RECONNECTED",({connection:J})=>{this._onConnectionReconnected(J)}),$8.globalInstance.on("CONNECTION.CLOSED",({connection:J})=>{this._onConnectionClosed(J)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(J){return this.getConnectedPlayers().filter(($)=>$.world===J)}getConnectedPlayerByUsername(J){return Array.from(this._connectionPlayers.values()).find(($)=>{return $.username.toLowerCase()===J.toLowerCase()})}async _onConnectionOpened(J,$){let X=new TH(J,$);await X.loadInitialPersistedData(),$8.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??tW.instance.getDefaultWorld()),this._connectionPlayers.set(J,X)}_onConnectionDisconnected(J){let $=this._connectionPlayers.get(J);if($)$.resetInputs(),$.camera.reset()}_onConnectionReconnected(J){let $=this._connectionPlayers.get(J);if($)$.reconnected(),$8.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionReconnected(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(J){let $=this._connectionPlayers.get(J);if($)$.disconnect(),this._connectionPlayers.delete(J),sQ.instance.unloadPlayerData($).catch((X)=>{n.warning(`PlayerManager._onConnectionClosed(): Failed to unload player data for player ${$.id}. Error: ${X}`)}),$8.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionClosed(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as gK6}from"crypto";import{Http3Server as mK6}from"@fails-components/webtransport";class BL extends $8{static instance=new BL;_connectionIdConnections=new Map;_userIdConnections=new Map;_wss;_wts;constructor(){super();this._wss=new gv.default({noServer:!0}),this._wss.on("connection",(J,$)=>this._onConnection(J,void 0,$.connectionId,$.session)),this._wts=new mK6({port:pP,host:"0.0.0.0",secret:gK6(32).toString("hex"),cert:lP,privKey:cP,defaultDatagramsReadableMode:"bytes",initialStreamFlowControlWindow:1048576,streamShouldAutoTuneReceiveWindow:!0,streamFlowControlWindowSizeLimit:6291456,initialSessionFlowControlWindow:2097152,sessionShouldAutoTuneReceiveWindow:!0,sessionFlowControlWindowSizeLimit:15728640}),this._wts.setRequestCallback(this._onWebTransportRequest),this._startWebTransport().catch((J)=>{n.error(`Socket: WebTransport server failed to start or crashed while listening for sessions. Error: ${J}`)}),$8.globalInstance.on("WEBSERVER.UPGRADE",async({req:J,socket:$,head:X})=>{$.on("error",()=>{}),await this._authorizeAndConnectWebsocket(J,$,X)})}async _authorizeAndConnectWebsocket(J,$,X){let Y=await this._authorizeConnection(J.url??"");if(Y.error){$.end();return}J.connectionId=Y.connectionId,J.session=Y.session,$.setNoDelay(!0),this._wss.handleUpgrade(J,$,X,(Q)=>{if(Q.readyState!==PH.default.OPEN)Q.once("open",()=>this._wss.emit("connection",Q,J));else this._wss.emit("connection",Q,J)})}async _authorizeConnection(J){let $=J.includes("?")?J.slice(J.indexOf("?")):"",X=new URLSearchParams($),Y=X.get("connectionId")??void 0,Q=X.get("sessionToken")??"";if(Y&&this._isValidConnectionId(Y))return{connectionId:Y};else{let W=await L1.instance.getPlayerSession(Q);if(W?.error)return{error:W.error};else if(W)return{session:W}}return{}}_isValidConnectionId(J){return this._connectionIdConnections.has(J)}_onConnection=(J,$,X,Y)=>{let Q=Y?.user.id,W=(X&&this._connectionIdConnections.get(X))??(Q&&this._userIdConnections.get(Q));if(W){if(J)W.bindWs(J);if($)W.bindWt($).catch((K)=>{n.error(`Socket._onConnection(): WebTransport binding failed. Error: ${K}`)})}else{let K=new i$(J,$,Y);if(K.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(K.id),Q)this._userIdConnections.delete(Q)}),this._connectionIdConnections.set(K.id,K),Q)this._userIdConnections.set(Q,K)}};_onWebTransportRequest=async({header:J})=>{let{connectionId:$,session:X,error:Y}=await this._authorizeConnection(J[":path"]??"");return{status:Y?401:200,path:"/",userData:{connectionId:$,session:X}}};async _startWebTransport(){this._wts.startServer();for await(let J of this._wts.sessionStream("/"))try{let{connectionId:$,session:X}=J.userData;this._onConnection(void 0,J,$,X)}catch($){n.error(`Socket._startWebTransport(): WebTransport connection failed. Error: ${$}`)}}}Buffer.poolSize=134217728;var vq8;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(vq8||={});function uK6(J){Y5.init().then(()=>{return eW.instance.blockTextureRegistry.preloadAtlas()}).then(()=>{return eW.instance.modelRegistry.preloadModels()}).then(()=>{if(J.length>0)J(eW.instance.worldManager.getDefaultWorld());else J();eW.instance.start()}).catch(($)=>{n.fatalError(`Failed to initialize the game engine, exiting. Error: ${$}`)})}class eW{static _instance;_blockTextureRegistry=RQ.instance;_modelRegistry=R9.instance;_playerManager=s$.instance;_socket=BL.instance;_worldManager=tW.instance;_webServer=mq.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new eW;return this._instance}get blockTextureRegistry(){return this._blockTextureRegistry}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){if($8.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start(),process.env.NODE_ENV!=="production")console.log("---"),console.log("\uD83D\uDFE2 Server Running: You can test & play it at: https://hytopia.com/play");n.enableCrashProtection()}}var q9=O0(LG(),1);class jG extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get determinant(){return q9.mat2.determinant(this)}get frobeniusNorm(){return q9.mat2.frob(this)}static create(){let J=new jG(0,0,0,0);return q9.mat2.identity(J),J}static fromRotation(J){let $=jG.create();return q9.mat2.fromRotation($,J),$}static fromScaling(J){let $=jG.create();return q9.mat2.fromScaling($,J),$}add(J){return q9.mat2.add(this,this,J),this}adjoint(){return q9.mat2.adjoint(this,this),this}clone(){return new jG(this[0],this[1],this[2],this[3])}copy(J){return q9.mat2.copy(this,J),this}equals(J){return q9.mat2.equals(this,J)}exactEquals(J){return q9.mat2.exactEquals(this,J)}identity(){return q9.mat2.identity(this),this}invert(){return q9.mat2.invert(this,this),this}multiply(J){return q9.mat2.mul(this,this,J),this}multiplyScalar(J){return q9.mat2.multiplyScalar(this,this,J),this}rotate(J){return q9.mat2.rotate(this,this,J),this}subtract(J){return q9.mat2.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return q9.mat2.transpose(this,this),this}}var P6=O0(LG(),1);class tX extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G){super([J,$,X,Y,Q,W,K,Z,G])}get determinant(){return P6.mat3.determinant(this)}get frobeniusNorm(){return P6.mat3.frob(this)}static create(){let J=new tX(0,0,0,0,0,0,0,0,0);return P6.mat3.identity(J),J}static fromMatrix4(J){let $=tX.create();return P6.mat3.fromMat4($,J),$}static fromQuaternion(J){let $=tX.create();return P6.mat3.fromQuat($,J),$}static fromRotation(J){let $=tX.create();return P6.mat3.fromRotation($,J),$}static fromScaling(J){let $=tX.create();return P6.mat3.fromScaling($,J),$}static fromTranslation(J){let $=tX.create();return P6.mat3.fromTranslation($,J),$}add(J){return P6.mat3.add(this,this,J),this}adjoint(){return P6.mat3.adjoint(this,this),this}clone(){return new tX(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(J){return P6.mat3.copy(this,J),this}equals(J){return P6.mat3.equals(this,J)}exactEquals(J){return P6.mat3.exactEquals(this,J)}identity(){return P6.mat3.identity(this),this}invert(){return P6.mat3.invert(this,this),this}multiply(J){return P6.mat3.mul(this,this,J),this}multiplyScalar(J){return P6.mat3.multiplyScalar(this,this,J),this}transformVector(J){return J.transformMatrix3(this)}projection(J,$){return P6.mat3.projection(this,J,$),this}rotate(J){return P6.mat3.rotate(this,this,J),this}subtract(J){return P6.mat3.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return P6.mat3.transpose(this,this),this}}var e8=O0(LG(),1);class I7 extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G,V,H,z,q,F,U,B){super([J,$,X,Y,Q,W,K,Z,G,V,H,z,q,F,U,B])}get determinant(){return e8.mat4.determinant(this)}get frobeniusNorm(){return e8.mat4.frob(this)}static create(){let J=new I7(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e8.mat4.identity(J),J}static fromQuaternion(J){let $=I7.create();return e8.mat4.fromQuat($,J),$}static fromRotation(J,$){let X=I7.create();return e8.mat4.fromRotation(X,J,$),X}static fromRotationTranslation(J,$){let X=I7.create();return e8.mat4.fromRotationTranslation(X,J,$),X}static fromRotationTranslationScale(J,$,X){let Y=I7.create();return e8.mat4.fromRotationTranslationScale(Y,J,$,X),Y}static fromRotationTranslationScaleOrigin(J,$,X,Y){let Q=I7.create();return e8.mat4.fromRotationTranslationScaleOrigin(Q,J,$,X,Y),Q}static fromScaling(J){let $=I7.create();return e8.mat4.fromScaling($,J),$}static fromTranslation(J){let $=I7.create();return e8.mat4.fromTranslation($,J),$}static fromXRotation(J){let $=I7.create();return e8.mat4.fromXRotation($,J),$}static fromYRotation(J){let $=I7.create();return e8.mat4.fromYRotation($,J),$}static fromZRotation(J){let $=I7.create();return e8.mat4.fromZRotation($,J),$}add(J){return e8.mat4.add(this,this,J),this}adjoint(){return e8.mat4.adjoint(this,this),this}clone(){return new I7(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(J){return e8.mat4.copy(this,J),this}equals(J){return e8.mat4.equals(this,J)}exactEquals(J){return e8.mat4.exactEquals(this,J)}frustrum(J,$,X,Y,Q,W){return e8.mat4.frustum(this,J,$,X,Y,Q,W),this}identity(){return e8.mat4.identity(this),this}invert(){return e8.mat4.invert(this,this),this}lookAt(J,$,X){return e8.mat4.lookAt(this,J,$,X),this}multiply(J){return e8.mat4.mul(this,this,J),this}multiplyScalar(J){return e8.mat4.multiplyScalar(this,this,J),this}orthographic(J,$,X,Y,Q,W){return e8.mat4.ortho(this,J,$,X,Y,Q,W),this}perspective(J,$,X,Y){return e8.mat4.perspective(this,J,$,X,Y),this}rotate(J,$){return e8.mat4.rotate(this,this,J,$),this}rotateX(J){return e8.mat4.rotateX(this,this,J),this}rotateY(J){return e8.mat4.rotateY(this,this,J),this}rotateZ(J){return e8.mat4.rotateZ(this,this,J),this}scale(J){return e8.mat4.scale(this,this,J),this}subtract(J){return e8.mat4.sub(this,this,J),this}targetTo(J,$,X){return e8.mat4.targetTo(this,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(J){return e8.mat4.translate(this,this,J),this}transpose(){return e8.mat4.transpose(this,this),this}}var h5=O0(LG(),1);class uq extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get length(){return h5.quat.length(this)}get squaredLength(){return h5.quat.squaredLength(this)}get magnitude(){return h5.quat.length(this)}get squaredMagnitude(){return h5.quat.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}get w(){return this[3]}set w(J){this[3]=J}static fromEuler(J,$,X){let Y=h5.quat.fromEuler(new Float32Array(4),J,$,X);return new uq(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(J){return new uq(J.x,J.y,J.z,J.w)}clone(){return new uq(this.x,this.y,this.z,this.w)}conjugate(){return h5.quat.conjugate(this,this),this}copy(J){return h5.quat.copy(this,J),this}dot(J){return h5.quat.dot(this,J)}exponential(){return h5.quat.exp(this,this),this}equals(J){return h5.quat.equals(this,J)}exactEquals(J){return h5.quat.exactEquals(this,J)}getAngle(J){return h5.quat.getAngle(this,J)}identity(){return h5.quat.identity(this),this}invert(){return h5.quat.invert(this,this),this}lerp(J,$){return h5.quat.lerp(this,this,J,$),this}logarithm(){return h5.quat.ln(this,this),this}multiply(J){return h5.quat.multiply(this,this,J),this}transformVector(J){return J.transformQuaternion(this)}normalize(){return h5.quat.normalize(this,this),this}power(J){return h5.quat.pow(this,this,J),this}randomize(){return h5.quat.random(this),this}rotateX(J){return h5.quat.rotateX(this,this,J),this}rotateY(J){return h5.quat.rotateY(this,this,J),this}rotateZ(J){return h5.quat.rotateZ(this,this,J),this}scale(J){return h5.quat.scale(this,this,J),this}setAxisAngle(J,$){return h5.quat.setAxisAngle(this,J,$),this}slerp(J,$){return h5.quat.slerp(this,this,J,$),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var L5=O0(LG(),1);class LL extends Float32Array{constructor(J,$){super([J,$])}get length(){return L5.vec2.length(this)}get squaredLength(){return L5.vec2.squaredLength(this)}get magnitude(){return L5.vec2.length(this)}get squaredMagnitude(){return L5.vec2.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}static create(){return new LL(0,0)}add(J){return L5.vec2.add(this,this,J),this}angle(J){return L5.vec2.angle(this,J)}ceil(){return L5.vec2.ceil(this,this),this}clone(){return new LL(this.x,this.y)}copy(J){return L5.vec2.copy(this,J),this}distance(J){return L5.vec2.distance(this,J)}divide(J){return L5.vec2.divide(this,this,J),this}dot(J){return L5.vec2.dot(this,J)}equals(J){return L5.vec2.equals(this,J)}exactEquals(J){return L5.vec2.exactEquals(this,J)}floor(){return L5.vec2.floor(this,this),this}invert(){return L5.vec2.inverse(this,this),this}lerp(J,$){return L5.vec2.lerp(this,this,J,$),this}max(J){return L5.vec2.max(this,this,J),this}min(J){return L5.vec2.min(this,this,J),this}multiply(J){return L5.vec2.mul(this,this,J),this}negate(){return L5.vec2.negate(this,this),this}normalize(){return L5.vec2.normalize(this,this),this}randomize(J){return L5.vec2.random(this,J),this}rotate(J,$){return L5.vec2.rotate(this,this,J,$),this}round(){return L5.vec2.round(this,this),this}scale(J){return L5.vec2.scale(this,this,J),this}scaleAndAdd(J,$){return L5.vec2.scaleAndAdd(this,this,J,$),this}subtract(J){return L5.vec2.sub(this,this,J),this}toString(){return`${this.x},${this.y}`}transformMatrix2(J){return L5.vec2.transformMat2(this,this,J),this}transformMatrix3(J){return L5.vec2.transformMat3(this,this,J),this}transformMatrix4(J){return L5.vec2.transformMat4(this,this,J),this}zero(){return L5.vec2.zero(this),this}}var H5=O0(LG(),1);class dq extends Float32Array{constructor(J,$,X){super([J,$,X])}get length(){return H5.vec3.length(this)}get squaredLength(){return H5.vec3.squaredLength(this)}get magnitude(){return H5.vec3.length(this)}get squaredMagnitude(){return H5.vec3.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}static create(){return new dq(0,0,0)}static fromVector3Like(J){return new dq(J.x,J.y,J.z)}add(J){return H5.vec3.add(this,this,J),this}ceil(){return H5.vec3.ceil(this,this),this}clone(){return new dq(this.x,this.y,this.z)}copy(J){return H5.vec3.copy(this,J),this}cross(J){return H5.vec3.cross(this,this,J),this}distance(J){return H5.vec3.distance(this,J)}divide(J){return H5.vec3.div(this,this,J),this}dot(J){return H5.vec3.dot(this,J)}equals(J){return H5.vec3.equals(this,J)}exactEquals(J){return H5.vec3.exactEquals(this,J)}floor(){return H5.vec3.floor(this,this),this}invert(){return H5.vec3.inverse(this,this),this}lerp(J,$){return H5.vec3.lerp(this,this,J,$),this}max(J){return H5.vec3.max(this,this,J),this}min(J){return H5.vec3.min(this,this,J),this}multiply(J){return H5.vec3.mul(this,this,J),this}negate(){return H5.vec3.negate(this,this),this}normalize(){return H5.vec3.normalize(this,this),this}randomize(J){return H5.vec3.random(this,J),this}rotateX(J,$){return H5.vec3.rotateX(this,this,J,$),this}rotateY(J,$){return H5.vec3.rotateY(this,this,J,$),this}rotateZ(J,$){return H5.vec3.rotateZ(this,this,J,$),this}round(){return H5.vec3.round(this,this),this}scale(J){return H5.vec3.scale(this,this,J),this}scaleAndAdd(J,$){return H5.vec3.scaleAndAdd(this,this,J,$),this}subtract(J){return H5.vec3.sub(this,this,J),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(J){return H5.vec3.transformMat3(this,this,J),this}transformMatrix4(J){return H5.vec3.transformMat4(this,this,J),this}transformQuaternion(J){return H5.vec3.transformQuat(this,this,J),this}zero(){return H5.vec3.zero(this),this}}var RF8=O0(NF8(),1);var OF8=0.099856;class jL extends WK{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=OF8;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(J={}){super();this.idleLoopedAnimations=J.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=J.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=J.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=J.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=J.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(J){super.spawn(J),this._startIdleAnimations(J)}face(J,$,X){this._faceTarget=J,this.faceSpeed=$,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(J){this._jumpHeight=J}move(J,$,X){this.moveSpeed=$,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:OF8,this._moveTarget=J,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(J,$){if(super.tick(J,$),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(J),this._moveStartMoveAnimations=!1;let X=$/1000,Y=J.position;if(J.isDynamic&&this._jumpHeight>0){let Q=Math.abs(J.world.simulation.gravity.y),W=Math.sqrt(2*Q*this._jumpHeight);J.applyImpulse({x:0,y:W*J.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(J)}if(this._moveTarget){let Q={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},W=Q.x*Q.x+Q.y*Q.y+Q.z*Q.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=$,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let Z=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(Z*Z+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(W>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let Z=Math.sqrt(W),G=this.moveSpeed*X,H=Math.min(Z,G)/Z,z={x:Y.x+Q.x*H,y:Y.y+Q.y*H,z:Y.z+Q.z*H};if(J.setPosition(z),this._onMove)this._onMove(z,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(J);if(this._onMoveComplete){let Z=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,Z(Y)}}}if(this._faceTarget){let Q={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},W=Math.atan2(-Q.x,-Q.z),K=J.rotation,Z=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=W-Z;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,q=(Z+H)/2,F={x:0,y:Math.fround(Math.sin(q)),z:0,w:Math.fround(Math.cos(q))};if(J.setRotation(F),this._onFace)this._onFace(K,F)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(J.rotation)}}}_startIdleAnimations(J){if(this.idleLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.jumpOneshotAnimations),J.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(J){J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(J){if(this.moveLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);J.stopModelAnimations(this.jumpOneshotAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelLoopedAnimations(this.moveLoopedAnimations)}}class qd extends jL{_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(J={}){super(J)}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(J,$,X){if(this._target=J,this._speed=$,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/$,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(J){super.attach(J),this._entity=J}detach(J){super.detach(J),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return n.error("PathfindingEntityController._calculatePath: No target or world"),!1;let J=this._entity.height,$=this._findGroundedStart();if(!$){if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-$.x),Q=Math.abs(X.y-$.y),W=Math.abs(X.z-$.z);if(Y<=2&&Q<=2&&W<=2&&!this._isNeighborCoordinateBlocked($,X,this._entity.height))return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5},{x:X.x+0.5,y:X.y+J/2,z:X.z+0.5}],!0;if($.x===X.x&&$.y===X.y&&$.z===X.z)return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5}],!0;let Z=this._coordinateToKey($),G=new Map,V=new Map([[Z,0]]),H=new Map([[Z,this._pathfindingHeuristic($,X)]]),z=new Set,q=new RF8.Heap((D,w)=>{let R=H.get(D[0])??1/0,N=H.get(w[0])??1/0;return R-N});q.push([Z,$]);let F=[{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 D=this._maxJump;D>=this._maxFall;D--){if(D===0)continue;let w=Math.abs($.y+D-X.y);U.push({y:D,distanceToTargetY:w})}U.sort((D,w)=>D.distanceToTargetY-w.distanceToTargetY);let B=[...F,...U.flatMap(({y:D})=>F.map((w)=>({...w,y:D})))],L=0,j=Math.abs(X.x-$.x)+Math.abs(X.y-$.y)+Math.abs(X.z-$.z),M=Math.min(this._maxOpenSetIterations,j*20);while(!q.isEmpty()&&L<M){L++;let[D,w]=q.pop();if(w.x===X.x&&w.y===X.y&&w.z===X.z){let O=this._reconstructPath(G,w);if(this._waypoints=O.map((C)=>({x:C.x+0.5,y:C.y+J/2,z:C.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return!0}z.add(D);let R=V.get(D),N=new Map;for(let O of B){let C=`${O.x},${O.z}`,S=O.y<0;if(S&&N.has(C))continue;let _={x:w.x+O.x,y:w.y+O.y,z:w.z+O.z};if(Math.abs(X.x-_.x)+Math.abs(X.y-_.y)+Math.abs(X.z-_.z)>j*1.5)continue;let A=this._coordinateToKey(_);if(z.has(A))continue;let k=this._isNeighborCoordinateBlocked(w,_,this._entity.height);if(S&&k){N.set(C,!0);continue}if(k)continue;let I=Math.abs(O.x),y=Math.abs(O.y),v=Math.abs(O.z),x=y===0?0:this._verticalPenalty,h=(Math.max(I,y,v)===1&&I+y+v>1?1.4:1)+x,m=R+h,c=V.get(A)??1/0;if(m>=c)continue;G.set(A,w),V.set(A,m);let l=m+this._pathfindingHeuristic(_,X);H.set(A,l),q.push([A,_])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)n.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(J,$){let X=[$],Y=$;while(J.has(this._coordinateToKey(Y)))Y=J.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(J){return`${J.x},${J.y},${J.z}`}_moveToNextWaypoint(){let J=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,$=this._waypoints[this._waypointNextIndex];if(!$||!this._entity)return;let X=0;if(this._entity.isDynamic&&J&&$.y>J.y){let Y=$.y-J.y,Q=Math.min(Y,this._maxJump)+0.75;this.jump(Q);let W=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*W*Q),Z=J.x+0.5,G=J.z+0.5,V=$.x+0.5,H=$.z+0.5,z=V-Z,q=H-G,F=Math.sqrt(z*z+q*q),U=K/W,B=F/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face($,this._speed),this.move($,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(J,$){return Math.abs(J.x-$.x)+Math.abs(J.y-$.y)+Math.abs(J.z-$.z)}_isNeighborCoordinateBlocked(J,$,X){if(!this._entity?.world)return!1;let Y=this._entity.world,Q=Math.floor($.x),W=Math.floor($.y),K=Math.floor($.z),Z=Math.floor(J.x),G=Math.floor(J.z);if(!Y.chunkLattice.hasBlock({x:Q,y:W-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:Q,y:W+V,z:K}))return!0;if(Q!==Z&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:Q,y:W+V,z:G}),z=Y.chunkLattice.hasBlock({x:Z,y:W+V,z:K});if(H||z)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:J,y:$,z:X}=this._entity.position,Y={x:Math.floor(J),y:Math.floor($),z:Math.floor(X)};for(let Q=0;Q<=Math.abs(this._maxFall);Q++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-Q-1}))return{...Y,y:Y.y-Q};return}}export{uK6 as startServer,Aq8 as WorldManagerEvent,tW as WorldManager,Iq8 as WorldLoopEvent,FL as WorldLoop,Xd as WorldEvent,UL as World,ru as WebServerEvent,mq as WebServer,dq as Vector3,LL as Vector2,zL as Ticker,FG as TelemetrySpanOperation,w6 as Telemetry,$d as SimulationEvent,VL as Simulation,jL as SimpleEntityController,qL as SceneUIManager,sv as SceneUIEvent,X3 as SceneUI,Jr8 as SUPPORTED_INPUTS,zU as RigidBodyType,xQ as RigidBody,uq as Quaternion,uO as PlayerUIEvent,aU as PlayerUI,_q8 as PlayerManagerEvent,s$ as PlayerManager,oU as PlayerEvent,kX as PlayerEntity,MK0 as PlayerCameraMode,cv as PlayerCameraEvent,rU as PlayerCamera,TH as Player,sQ as PersistenceManager,qd as PathfindingEntityController,HL as ParticleEmitterManager,tu as ParticleEmitterEvent,eu as ParticleEmitter,wK0 as PLAYER_ROTATION_UPDATE_THRESHOLD,DK0 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,R9 as ModelRegistry,I7 as Matrix4,tX as Matrix3,jG as Matrix2,kq8 as LightType,GL as LightManager,au as LightEvent,ou as Light,H9 as IterationMap,vq8 as GameServerEvent,eW as GameServer,$8 as EventRouter,n as ErrorHandler,Y3 as EntityManager,$3 as EntityEvent,v6 as Entity,RK0 as ENTITY_ROTATION_UPDATE_THRESHOLD,OK0 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,f5 as DefaultPlayerEntityController,rv as DefaultPlayerEntity,NK0 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,L$ as CollisionGroupsBuilder,hK as CollisionGroup,WH as ColliderShape,J3 as ColliderMap,DJ as Collider,gA as CoefficientCombineRule,iv as ChunkLatticeEvent,eU as ChunkLattice,c7 as Chunk,tU as ChatManager,pv as ChatEvent,uA as BlockTypeRegistryEvent,FU as BlockTypeRegistry,mA as BlockTypeEvent,wJ as BlockType,RQ as BlockTextureRegistry,NG as Block,Dd as BaseEntityControllerEvent,WK as BaseEntityController,rq as AudioManager,HC as AudioEvent,sq as Audio,p6 as AssetsLibrary};