import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js"; import { chunkKey, chunkToRegion, parseChunkKey, regionKey, tileKey, tileToChunk, tileToLocal, tileToRegion } from "../world/coordinates.js"; import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js"; import { closedNeighborEdges } from "../world/chunkFlags.js"; import { EcsWorld } from "../ecs/world.js"; import { Component } from "../ecs/components.js"; import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js"; import { chunkBoundsAround, findPath } from "../navigation/astar.js"; import { WorkerMessage } from "./protocol.js"; import { collectSpawnRequests } from "./spawners.js"; import { bagView, expireGroundItems, groundItemsInChunk, groundItemsInRegion, handleItemCommand, removeGroundItem, setGroundItemsForRegion } from "../items/bags.js"; export class WorkerWorld { constructor (workerId) { this.workerId = workerId; this.ecs = new EcsWorld(); this.chunks = new Map(); this.ownedRegions = new Set(); this.occupancy = new Map(); this.ghosts = new Map(); this.ghostOccupancy = new Map(); this.characterEntities = new Map(); this.frozen = new Set(); this.groundItems = new Map(); this.groundByTile = new Map(); this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.activeRevisionId = 1; } handle (message) { switch (message.type) { case WorkerMessage.configure: return this.#configure(message); case WorkerMessage.assignRegion: return this.#assignRegion(message); case WorkerMessage.dropRegion: return this.#dropRegion(message); case WorkerMessage.replaceRegionChunks: return this.#replaceRegionChunks(message); case WorkerMessage.setReplicas: return this.#setReplicas(message); case WorkerMessage.setSimulatingChunks: return this.#setSimulatingChunks(message); case WorkerMessage.setGhosts: return this.#setGhosts(message); case WorkerMessage.spawn: return this.#spawn(message); case WorkerMessage.despawn: return this.#despawn(message.entityId); case WorkerMessage.despawnCharacter: return this.#despawnCharacter(message.characterId); case WorkerMessage.command: return this.#command(message); case WorkerMessage.stepMovement: return this.#stepMovement(message.now); case WorkerMessage.stepSpawners: return { spawnRequests: collectSpawnRequests(this) }; case WorkerMessage.setGroundItems: setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion); return { ok: true }; case WorkerMessage.inspectBag: return this.#inspectBag(message.entityId); case WorkerMessage.applyTransfer: return this.#applyTransfer(message); case WorkerMessage.commitTransfer: return this.#commitTransfer(message.entityId); case WorkerMessage.abortTransfer: return this.#abortTransfer(message.entityId); case WorkerMessage.snapshotChunk: return this.#chunkSnapshot(message.chunkX, message.chunkY); case WorkerMessage.listLoaders: return this.#listLoaders(); case WorkerMessage.listPublicEntities: return this.#listPublicEntities(); case WorkerMessage.entitiesInRegion: return this.#entitiesInRegion(message.regionX, message.regionY); case WorkerMessage.inspect: return publicEntityView(this.ecs, message.entityId); default: throw new Error(`Unknown worker message ${message.type}`); } } ownsRegion (regionX, regionY) { return this.ownedRegions.has(regionKey(regionX, regionY)); } requireOwnedEntity (sessionId, characterId) { return this.#requireOwnedEntity(sessionId, characterId); } chunkData (chunkX, chunkY) { return this.#chunkData(chunkX, chunkY); } occupied (tileX, tileY) { return this.#occupied(tileX, tileY); } #configure (message) { if (message.settings) { this.settings = { ...this.settings, ...message.settings }; } if (message.activeRevisionId != null) { this.activeRevisionId = message.activeRevisionId; } return { ok: true }; } #assignRegion (message) { this.ownedRegions.add(regionKey(message.regionX, message.regionY)); for (const chunk of message.chunks ?? []) { this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), { data: cloneChunkData(chunk.data), simulating: false, replica: false }); } return { ok: true }; } #replaceRegionChunks (message) { for (const chunk of message.chunks ?? []) { const key = chunkKey(chunk.chunkX, chunk.chunkY); const existing = this.chunks.get(key); this.chunks.set(key, { data: cloneChunkData(chunk.data), simulating: existing?.simulating ?? false, replica: existing?.replica ?? false }); } return { ok: true }; } #dropRegion (message) { const dropped = []; for (const record of this.#entitiesInRegion(message.regionX, message.regionY)) { dropped.push(record); this.#destroyEntity(record.entityId); } const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion); for (const item of groundItems) { removeGroundItem(this, item.groundItemId); } for (const [key, chunk] of [...this.chunks.entries()]) { const { chunkX, chunkY } = parseChunkKey(key); if (chunk.replica) { continue; } if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY) { this.chunks.delete(key); } } this.ownedRegions.delete(regionKey(message.regionX, message.regionY)); return { dropped, groundItems }; } #setReplicas (message) { const keep = new Set(); for (const chunk of message.chunks ?? []) { const key = chunkKey(chunk.chunkX, chunk.chunkY); keep.add(key); const existing = this.chunks.get(key); if (existing && !existing.replica) { continue; } this.chunks.set(key, { data: cloneChunkData(chunk.data), simulating: false, replica: true }); } for (const [key, chunk] of [...this.chunks.entries()]) { if (chunk.replica && !keep.has(key)) { this.chunks.delete(key); } } return { ok: true }; } #setSimulatingChunks (message) { const simulating = new Set(message.chunkKeys ?? []); for (const [key, chunk] of this.chunks) { if (chunk.replica) { chunk.simulating = false; continue; } chunk.simulating = simulating.has(key); } return { ok: true }; } #setGhosts (message) { this.ghosts.clear(); this.ghostOccupancy.clear(); for (const ghost of message.ghosts ?? []) { this.ghosts.set(ghost.entityId, ghost); this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId); } return { ok: true }; } #spawn (message) { const entityId = deserializeEntity(this.ecs, message); const handle = this.ecs.handleOf(entityId); const position = this.ecs.get(handle, Component.position); if (!position) { this.ecs.destroy(handle); throw new Error("Spawned entity is missing position."); } const occupant = this.#occupied(position.tileX, position.tileY); if (occupant && occupant !== entityId) { this.ecs.destroy(handle); const error = new Error("That tile is occupied."); error.userFacing = true; throw error; } this.#occupy(entityId, position.tileX, position.tileY); const character = this.ecs.get(handle, Component.character); if (character?.characterId) { this.characterEntities.set(character.characterId, entityId); } return publicEntityView(this.ecs, entityId); } #despawn (entityId) { return this.#destroyEntity(entityId); } #despawnCharacter (characterId) { const entityId = this.characterEntities.get(characterId); if (!entityId) { return null; } return this.#destroyEntity(entityId); } #destroyEntity (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const view = publicEntityView(this.ecs, entityId); const position = this.ecs.get(handle, Component.position); const character = this.ecs.get(handle, Component.character); if (position) { this.#vacate(entityId, position.tileX, position.tileY); } if (character?.characterId) { this.characterEntities.delete(character.characterId); } this.frozen.delete(entityId); this.ecs.destroy(handle); return view; } #command (message) { const { sessionId, command } = message; switch (command.type) { case "move-to": this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY); return { events: [] }; case "set-gait": this.#setGait(sessionId, command.characterId, command.gait); return { events: [] }; default: { const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now()); return result ?? { events: [] }; } } } #inspectBag (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } return bagView(this.ecs, handle); } #moveTo (sessionId, characterId, tileX, tileY) { const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); if (this.frozen.has(entityId)) { return; } const position = this.ecs.get(handle, Component.position); const movement = this.ecs.get(handle, Component.movement); let path = this.ecs.get(handle, Component.path); if (!path) { path = this.ecs.add(handle, Component.path, { tiles: [] }); } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); path.tiles = findPath( position.tileX, position.tileY, tileX, tileY, (x, y) => this.#walkableFor(entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); movement.walkCarry = 0; } #setGait (sessionId, characterId, gait) { if (gait !== GAIT.walk && gait !== GAIT.run) { const error = new Error("Gait must be walk or run."); error.userFacing = true; throw error; } const { handle } = this.#requireOwnedEntity(sessionId, characterId); this.ecs.get(handle, Component.movement).gait = gait; } #requireOwnedEntity (sessionId, characterId) { const entityId = this.characterEntities.get(characterId); if (!entityId) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } const handle = this.ecs.handleOf(entityId); const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null; if (!identity || identity.sessionId !== sessionId) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } return { handle, entityId }; } #stepMovement (now = Date.now()) { const events = expireGroundItems(this, now); const transferRequests = []; for (const entity of this.ecs.query(Component.position, Component.movement)) { const { handle, entityId, position, movement } = entity; const path = this.ecs.get(handle, Component.path); const tiles = path?.tiles; if (this.frozen.has(entityId) || !tiles?.length) { continue; } if (!this.#chunkIsSimulating(position.tileX, position.tileY)) { continue; } const isWalk = movement.gait !== GAIT.run; if (isWalk) { movement.walkCarry = (movement.walkCarry + 1) % 2; if (movement.walkCarry !== 0) { continue; } } const next = tiles[0]; const destRegionX = tileToRegion(next.x); const destRegionY = tileToRegion(next.y); if (!this.ownsRegion(destRegionX, destRegionY)) { this.frozen.add(entityId); transferRequests.push({ entityId, fromTileX: position.tileX, fromTileY: position.tileY, destTileX: next.x, destTileY: next.y, toRegionX: destRegionX, toRegionY: destRegionY, payload: serializeEntity(this.ecs, entityId) }); continue; } if (!this.#walkableFor(entityId, next.x, next.y)) { continue; } const fromTileX = position.tileX; const fromTileY = position.tileY; this.#vacate(entityId, fromTileX, fromTileY); position.tileX = next.x; position.tileY = next.y; tiles.shift(); this.#occupy(entityId, position.tileX, position.tileY); events.push(this.#moveEvent(entityId, fromTileX, fromTileY)); } return { events, transferRequests }; } #applyTransfer (message) { const payload = message.payload; const entityId = payload.entityId; if (this.ecs.hasEntity(entityId)) { return { accepted: false, reason: "already-present" }; } const position = payload.components?.position; const destTileX = message.destTileX ?? position?.tileX; const destTileY = message.destTileY ?? position?.tileY; if (destTileX == null || destTileY == null) { return { accepted: false, reason: "missing-destination" }; } if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY))) { return { accepted: false, reason: "not-owner" }; } if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY)) { return { accepted: false, reason: "blocked" }; } deserializeEntity(this.ecs, payload); const handle = this.ecs.handleOf(entityId); const livePosition = this.ecs.get(handle, Component.position); const path = this.ecs.get(handle, Component.path); livePosition.tileX = destTileX; livePosition.tileY = destTileY; if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY) { path.tiles.shift(); } this.#occupy(entityId, destTileX, destTileY); const character = this.ecs.get(handle, Component.character); if (character?.characterId) { this.characterEntities.set(character.characterId, entityId); } this.frozen.delete(entityId); return { accepted: true, entity: publicEntityView(this.ecs, entityId) }; } #commitTransfer (entityId) { if (!this.ecs.hasEntity(entityId)) { return null; } return this.#destroyEntity(entityId); } #abortTransfer (entityId) { this.frozen.delete(entityId); return publicEntityView(this.ecs, entityId); } #listLoaders () { return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({ entityId: entity.entityId, tileX: entity.position.tileX, tileY: entity.position.tileY, chunkLoader: { ...entity.chunkLoader } })); } #listPublicEntities () { return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean); } #entitiesInRegion (regionX, regionY) { const records = []; for (const entity of this.ecs.query(Component.position)) { if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY) { continue; } records.push({ ...publicEntityView(this.ecs, entity.entityId), persistent: this.ecs.has(entity.handle, Component.persistent), payload: serializeEntity(this.ecs, entity.entityId) }); } return records; } #chunkSnapshot (chunkX, chunkY) { const data = this.#chunkData(chunkX, chunkY); const entities = []; for (const entity of this.ecs.query(Component.position, Component.appearance)) { if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY) { continue; } entities.push(publicEntityView(this.ecs, entity.entityId)); } return { chunkX, chunkY, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open), grounds: data.grounds, blocks: data.blocks, light: data.light, entities, groundItems: groundItemsInChunk(this, chunkX, chunkY) }; } #moveEvent (entityId, fromTileX, fromTileY) { const view = publicEntityView(this.ecs, entityId); return { type: "entity-move", entityId, fromTileX, fromTileY, tileX: view.tileX, tileY: view.tileY, gait: view.gait }; } #chunkIsSimulating (tileX, tileY) { const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))); return !!chunk && !chunk.replica && chunk.simulating; } #chunkData (chunkX, chunkY) { const loaded = this.chunks.get(chunkKey(chunkX, chunkY)); if (loaded) { return loaded.data; } return createEmptyChunkData(this.settings.defaultGroundTypeId); } isEnterable (tileX, tileY) { const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY)); if (!data.open) { return false; } return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); } #walkableFor (entityId, tileX, tileY) { if (!this.isEnterable(tileX, tileY)) { return false; } const occupant = this.#occupied(tileX, tileY); return !occupant || occupant === entityId; } #occupy (entityId, tileX, tileY) { this.occupancy.set(tileKey(tileX, tileY), entityId); } #vacate (entityId, tileX, tileY) { const key = tileKey(tileX, tileY); if (this.occupancy.get(key) === entityId) { this.occupancy.delete(key); } } #occupied (tileX, tileY) { return this.occupancy.get(tileKey(tileX, tileY)) ?? this.ghostOccupancy.get(tileKey(tileX, tileY)) ?? null; } } export function replicaNeededForOwnedChunks (ownedChunkKeys) { const needed = new Set(); for (const key of ownedChunkKeys) { const { chunkX, chunkY } = parseChunkKey(key); for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } needed.add(chunkKey(chunkX + dx, chunkY + dy)); } } } return needed; }