import { CHUNK_SIZE, DEFAULT_CHUNK_LOADER, GAIT, REGION_RUNTIME_STATE, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js"; import { chunkKey, chunkToRegion, chunksInRegion, parseChunkKey, parseRegionKey, regionKey, regionTileBounds, tileToChunk, tileToLocal, tileToRegion, visibleChunkCoords } from "../world/coordinates.js"; import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; import { closedNeighborEdges } from "../world/chunkFlags.js"; import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js"; import { InProcessWorker } from "./inProcessWorker.js"; import { ThreadWorker } from "./threadWorker.js"; import { WorkerMessage } from "./protocol.js"; import { replicaNeededForOwnedChunks } from "./workerWorld.js"; import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js"; import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js"; import { mobComponents } from "./spawners.js"; import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js"; import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { ItemId } from "../../../shared/definitions/items.js"; import { seasonIdAt } from "../../../shared/world/season.js"; import { CourierService } from "../courier/service.js"; import { MarketService } from "../market/service.js"; import { findReservedChequeIndex } from "../items/bags.js"; export class Simulation { constructor (worldDb, stateDb, options = {}) { this.worldDb = worldDb; this.stateDb = stateDb; this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2))); this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess"; this.pinRegion = options.pinRegion ?? null; this.nowFn = options.now ?? (() => Date.now()); this.workers = []; this.regionOwner = new Map(); this.regionGraceUntil = new Map(); this.directory = new Map(); this.characterEntities = new Map(); this.commandQueue = []; this.replication = []; this.pendingPrivate = []; this.courier = null; this.market = null; this.altarTiles = []; this.authoredCache = new Map(); this.simulatingChunkKeys = new Set(); this.nextEntityId = 1; this.nextGroundItemId = stateDb.nextGroundItemId(); this.tickIndex = 0; this.movementTickCounter = 0; this.lastTickAt = null; this.movementAccumulator = 0; this.activeRevisionId = worldDb.getActiveRevisionId(); this.settings = worldDb.getLiveSettings(); const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker; for (let workerId = 0; workerId < this.workerCount; workerId++) { const worker = new WorkerImpl(workerId); worker.call({ type: WorkerMessage.configure, settings: this.settings, activeRevisionId: this.activeRevisionId }); this.workers.push(worker); } for (const worker of this.workers) { if (!worker.world) { continue; } worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId); worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack); } this.courier = new CourierService({ stateDb: this.stateDb, worldDb: this.worldDb, simulation: this }); this.market = new MarketService({ stateDb: this.stateDb, worldDb: this.worldDb, simulation: this }); this.#refreshAltarIndex(); } get now () { return this.nowFn(); } applySettings (settings) { this.settings = { ...this.settings, ...settings }; this.#configureWorkers(); } /** Sparse last-sale map for editor base-price readouts. */ itemLastSalesSnapshot () { return this.market?.snapshot?.() ?? {}; } syncItemLastSales (lastSales) { const sales = {}; for (const [itemId, sale] of lastSales?.entries?.() ?? []) { sales[String(itemId)] = sale; } for (const worker of this.workers) { worker.call({ type: WorkerMessage.setItemLastSales, sales }); } } reloadWorld () { this.activeRevisionId = this.worldDb.getActiveRevisionId(); this.settings = this.worldDb.getLiveSettings(); this.authoredCache.clear(); this.#configureWorkers(); for (const [key, workerId] of this.regionOwner) { const { regionX, regionY } = parseRegionKey(key); this.workers[workerId].call({ type: WorkerMessage.replaceRegionChunks, chunks: this.#regionChunkBlobs(regionX, regionY) }); } this.#syncAllReplicas(); this.courier?.refreshBankIndex(); this.market?.refreshIndex(); this.#refreshAltarIndex(); } enqueue (sessionId, command) { this.commandQueue.push({ sessionId, command, receivedAt: this.now }); } step (now = this.now) { this.tickIndex += 1; const events = []; const commands = this.commandQueue.splice(0); for (const item of commands) { try { events.push(...this.#routeCommand(item)); } catch (error) { events.push({ sessionId: item.sessionId, type: "command-error", message: error.userFacing ? error.message : "Command failed." }); } } this.#recalculateActivation(now); const simHz = Math.max(1, this.settings.simulationTickHz || 20); const expectedDt = 1 / simHz; const dt = (this.lastTickAt == null || now <= this.lastTickAt) ? expectedDt : Math.min(0.25, (now - this.lastTickAt) / 1000); this.lastTickAt = now; { const transfers = []; const remoteMelee = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.stepSystems, now, dt }); for (const event of result?.events ?? []) { if (event.type === "remote-melee-resolve") { remoteMelee.push(event); continue; } if (event.type === "entity-move") { this.#applyMoveToDirectory(event); } if (event.type === "entity-despawn") { this.#forget(event.entityId); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); } if (event.type === "inventory" && event.characterId) { this.#saveBagFromView(event.characterId, { inventory: event.inventory, equipment: event.equipment, vault: event.vault, vaultReserved: event.vaultReserved }); } if (event.type === "player-died") { events.push(...this.#applyPlayerDeath(event)); continue; } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const request of result?.transferRequests ?? []) { transfers.push({ ...request, fromWorkerId: worker.workerId }); } } for (const payload of remoteMelee) { events.push(...this.#applyRemoteMelee(payload)); } if (transfers.length) { events.push(...this.#applyTransfers(transfers)); this.#recalculateActivation(now); } } const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2); this.movementAccumulator += dt * movementHz; while (this.movementAccumulator >= 1) { this.movementAccumulator -= 1; this.movementTickCounter += 1; const transfers = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.stepMovement, now }); for (const event of result?.events ?? []) { if (event.type === "entity-move") { this.#applyMoveToDirectory(event); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const request of result?.transferRequests ?? []) { transfers.push({ ...request, fromWorkerId: worker.workerId }); } } events.push(...this.#applyTransfers(transfers)); this.#recalculateActivation(now); } if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0) { events.push(...this.#stepSpawners()); } if (this.courier) { events.push(...this.courier.step(now, dt)); } if (this.market) { events.push(...this.market.step(now)); } this.#syncGhosts(); events.push(...this.pendingPrivate.splice(0)); return { now, events, replication: this.drainReplication() }; } drainReplication () { return this.replication.splice(0); } worldTime (now = this.now) { const date = new Date(now); date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET); return { unixMs: now, worldUnixMs: date.getTime(), iso: date.toISOString(), hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600, season: seasonIdAt(now) }; } spawnCharacter (sessionId, character) { this.despawnCharacter(character.character_id); // Despawn may have just written the live tile; never trust a stale row snapshot. const row = this.stateDb.getCharacter(character.character_id) ?? character; let tileX = row.tile_x; let tileY = row.tile_y; const gait = row.gait || character.gait || GAIT.walk; const preferred = this.#findResumeTile(tileX, tileY); if (!preferred) { const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); error.userFacing = true; throw error; } if (preferred.tileX !== tileX || preferred.tileY !== tileY) { tileX = preferred.tileX; tileY = preferred.tileY; this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait); } const bag = this.stateDb.getBag(character.character_id) ?? { inventory: emptySlots(), equipment: emptyEquipment(), vault: [], vaultReserved: [] }; const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills(); // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised). if (enforceMinimumSkillLevels(skills)) { this.stateDb.saveSkills(character.character_id, skills); } const maxHealth = playerMaxHealth(skills); const maxStamina = playerMaxStamina(skills); const isDead = !!row.is_dead; const entityId = this.nextEntityId++; const components = { position: { tileX, tileY }, movement: { gait, walkCarry: 0 }, path: { tiles: [] }, appearance: { sex: character.sex ?? row.sex, firstName: character.first_name ?? row.first_name, lastName: character.last_name ?? row.last_name }, character: { characterId: character.character_id ?? row.character_id, accountId: character.account_id ?? row.account_id }, networkIdentity: { sessionId }, chunkLoader: { ...DEFAULT_CHUNK_LOADER }, inventory: { slots: bag.inventory ?? emptySlots() }, equipment: bag.equipment ?? emptyEquipment(), vault: { slots: bag.vault ?? [], reserved: bag.vaultReserved ?? [] }, health: { current: isDead ? 0 : maxHealth, max: maxHealth }, stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 }, combat: { targetEntityId: null, nextSwingAt: 0 }, skills, }; if (isDead) { components.dead = {}; } this.#ensureCoverage(tileX, tileY, components.chunkLoader); const workerId = this.#ownerOfTile(tileX, tileY); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); this.#queueReplication(replicationSpawn(view)); this.#recalculateActivation(this.now); this.#syncGhosts(); return entityId; } spawnEntity (components, options = {}) { const entityId = options.entityId ?? this.nextEntityId++; this.nextEntityId = Math.max(this.nextEntityId, entityId + 1); const position = components.position; if (!position) { throw new Error("spawnEntity requires position."); } if (options.requireResident) { const workerId = this.#ownerOfTile(position.tileX, position.tileY); if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY)) { return null; } const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); if (components.appearance) { this.#queueReplication(replicationSpawn(view)); } this.#syncGhosts(); return entityId; } if (components.chunkLoader) { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); } else { this.#ensureRegion( tileToRegion(position.tileX), tileToRegion(position.tileY), null ); } const workerId = this.#ownerOfTile(position.tileX, position.tileY); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId, components }); this.#remember(view, workerId); if (components.appearance) { this.#queueReplication(replicationSpawn(view)); } this.#recalculateActivation(this.now); this.#syncGhosts(); return entityId; } despawnEntity (entityId) { const record = this.directory.get(entityId); if (!record) { return; } const dropped = this.workers[record.workerId].call({ type: WorkerMessage.despawn, entityId }); if (dropped) { this.#queueReplication(replicationDespawn(dropped)); } this.#forget(entityId); } chunkIsSimulating (tileX, tileY) { const loaders = this.#allLoaders(); const { chunkSim } = accumulateLoaderRefs(loaders); return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0; } updateCourierFlight (entityId, flightPatch, now = this.now) { const record = this.directory.get(entityId); if (!record) { return { despawned: true, entityId }; } const tileX = Math.floor(flightPatch.x); const tileY = Math.floor(flightPatch.y); const owner = this.#ownerOfTile(tileX, tileY); if (owner == null || owner !== record.workerId) { this.despawnEntity(entityId); return { despawned: true, entityId }; } const result = this.workers[owner].call({ type: WorkerMessage.updateFlight, entityId, flight: flightPatch, now }); if (result?.transferRequest) { const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]); this.#recalculateActivation(now); const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId); if (move) { this.#applyMoveToDirectory(move); return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } }; } this.despawnEntity(entityId); return { despawned: true, entityId }; } if (result?.event) { this.#applyMoveToDirectory(result.event); return { event: result.event }; } return null; } applyBag (entityId, bag) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.applyBag, entityId, bag }); } pushSkills (characterId, skills) { this.pendingPrivate.push({ type: "skills", characterId, skills }); } skillsOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectSkills, entityId }); } staminaOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectStamina, entityId }); } pushInventory (characterId, bag) { this.pendingPrivate.push({ type: "inventory", characterId, inventory: bag.inventory, equipment: bag.equipment, vault: bag.vault, vaultReserved: bag.vaultReserved }); } dispatchPigeon ({ characterId, destination, cargo }) { const entityId = this.characterEntities.get(characterId); const position = entityId ? this.positionOf(entityId) : null; if (!position) { const error = new Error("Enter the world before sending a pigeon."); error.userFacing = true; throw error; } return this.courier.dispatchFromPlayer({ characterId, originTileX: position.tileX, originTileY: position.tileY, destination, cargo }); } /** * Path an idle CE clerk to a staff-side station tile. */ stationExchangeClerk (stationTileX, stationTileY) { const owner = this.#ownerOfTile(stationTileX, stationTileY); if (owner == null) { return { ok: false, reason: "unowned" }; } return this.workers[owner].call({ type: WorkerMessage.stationExchangeClerk, stationTileX, stationTileY }); } /** * When a player uses a marketplace counter, path idle CE clerks to the * opposite side of each adjacent counter (staff side). */ stationExchangeClerks (playerTileX, playerTileY) { const results = []; for (const tile of this.market?.marketTiles ?? []) { if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1) { continue; } if (tile.tileX === playerTileX && tile.tileY === playerTileY) { continue; } const stationTileX = tile.tileX + (tile.tileX - playerTileX); const stationTileY = tile.tileY + (tile.tileY - playerTileY); if (stationTileX === playerTileX && stationTileY === playerTileY) { continue; } results.push(this.stationExchangeClerk(stationTileX, stationTileY)); } return results; } /** Release a CE clerk stationed at the given staff-side tile. */ releaseExchangeClerk (stationTileX, stationTileY) { const owner = this.#ownerOfTile(stationTileX, stationTileY); if (owner == null) { return { ok: false, reason: "unowned" }; } return this.workers[owner].call({ type: WorkerMessage.releaseExchangeClerk, stationTileX, stationTileY }); } despawnCharacter (characterId) { this.market?.leaveExchangeStations?.(characterId); const entityId = this.characterEntities.get(characterId); if (!entityId) { return; } const record = this.directory.get(entityId); if (!record) { this.characterEntities.delete(characterId); return; } this.#saveBag(entityId, record.workerId); const dropped = this.workers[record.workerId].call({ type: WorkerMessage.despawnCharacter, characterId }); if (dropped) { this.stateDb.saveCharacterPosition( characterId, dropped.tileX, dropped.tileY, dropped.gait ?? GAIT.walk ); this.#queueReplication(replicationDespawn(dropped)); } this.#forget(entityId); this.#recalculateActivation(this.now); this.#syncGhosts(); } entityForCharacter (characterId) { return this.characterEntities.get(characterId) ?? null; } entityRecord (entityId) { const record = this.directory.get(entityId); return record ? { ...record } : null; } positionOf (entityId) { const record = this.directory.get(entityId); return record ? { tileX: record.tileX, tileY: record.tileY } : null; } bagOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectBag, entityId }); } snapshotFor (entityId) { const record = this.directory.get(entityId); if (!record) { return []; } const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS); return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY)); } snapshotChunk (chunkX, chunkY) { const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)); if (owner == null) { return this.#syntheticSnapshot(chunkX, chunkY); } return this.workers[owner].call({ type: WorkerMessage.snapshotChunk, chunkX, chunkY }); } findOpenSpawn () { const coords = this.worldDb.listChunkCoords(this.activeRevisionId); for (const coord of coords) { const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y); if (!data.open) { continue; } for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const tileX = coord.chunk_x * CHUNK_SIZE + localX; const tileY = coord.chunk_y * CHUNK_SIZE + localY; if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY)) { return { tileX, tileY }; } } } } return null; } /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */ #findResumeTile (tileX, tileY, radius = 24) { return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn(); } #findNearbyEnterable (originX, originY, maxRadius) { for (let radius = 0; radius <= maxRadius; radius++) { for (let dy = -radius; dy <= radius; dy++) { for (let dx = -radius; dx <= radius; dx++) { if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) { continue; } const tileX = originX + dx; const tileY = originY + dy; if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY)) { return { tileX, tileY }; } } } } return null; } isEnterable (tileX, tileY) { const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY)); if (!data.open) { return false; } return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); } debugWorld () { const loaders = this.#allLoaders(); const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); const simulatingChunks = [...chunkSim.entries()] .filter(([, count]) => count > 0) .map(([key]) => key) .sort(); return { tickIndex: this.tickIndex, workerCount: this.workers.length, workerMode: this.workerMode, simulatingChunks, regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({ ...parseRegionKey(key), workerId, state: REGION_RUNTIME_STATE.resident, refs: regionRes.get(key) ?? 0, graceUntil: this.regionGraceUntil.get(key) ?? null })), entities: [...this.directory.values()].map((entity) => ({ entityId: entity.entityId, workerId: entity.workerId, tileX: entity.tileX, tileY: entity.tileY, characterId: entity.characterId })) }; } async shutdown () { for (const characterId of [...this.characterEntities.keys()]) { this.despawnCharacter(characterId); } this.forceUnloadAll(); await Promise.all(this.workers.map((worker) => worker.terminate())); } forceUnloadAll () { for (const key of [...this.regionOwner.keys()]) { const { regionX, regionY } = parseRegionKey(key); this.#unloadRegion(regionX, regionY); } } #configureWorkers () { for (const worker of this.workers) { worker.call({ type: WorkerMessage.configure, settings: this.settings, activeRevisionId: this.activeRevisionId }); } } #routeCommand (item) { if (item.command.type === "respawn") { return this.#respawnCharacter(item.sessionId, item.command.characterId); } if ( item.command.type === "open-market" || item.command.type === "place-market-sell" || item.command.type === "place-market-buy" || item.command.type === "cancel-market-order" || item.command.type === "close-market" ) { const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); return result?.events ?? []; } const entityId = this.characterEntities.get(item.command.characterId); const record = entityId ? this.directory.get(entityId) : null; if (!record) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } if (item.command.type === "drop-item" && item.command.groundItemId == null) { item.command.groundItemId = this.nextGroundItemId++; } if (item.command.type === "attack") { const targetRecord = this.directory.get(item.command.targetEntityId); if (!targetRecord) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } const events = this.#finishRoutedCommand(item, record); if (targetRecord.workerId !== record.workerId) { this.workers[targetRecord.workerId].call({ type: WorkerMessage.remoteCombatEngage, attackerEntityId: record.entityId, targetEntityId: item.command.targetEntityId, now: item.receivedAt ?? this.now }); } return events; } return this.#finishRoutedCommand(item, record); } #finishRoutedCommand (item, record) { const result = this.workers[record.workerId].call({ type: WorkerMessage.command, sessionId: item.sessionId, command: item.command, now: item.receivedAt ?? this.now }); const view = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId: record.entityId }); if (view) { this.#remember(view, record.workerId); } if (result?.private) { this.#saveBagFromView(item.command.characterId, result.private); } if (result?.appearanceChanged && view) { this.#queueReplication(replicationAppearance(view)); } if (result?.remainder) { this.stateDb.saveInheritance( this.stateDb.getCharacter(item.command.characterId).account_id, { slots: result.remainder } ); } for (const event of result?.events ?? []) { this.#persistGroundEvent(event); } const events = [...(result?.events ?? [])]; if (result?.private) { events.push({ type: "inventory", sessionId: item.sessionId, bank: !!result.bank, cauldron: result.cauldron, cauldronState: result.cauldronState ?? null, alchemyResult: result.alchemyResult ?? null, ...result.private }); } return events; } #applyRemoteMelee (payload) { const targetRecord = this.directory.get(payload.targetId); if (!targetRecord) { return []; } const result = this.workers[targetRecord.workerId].call({ ...payload, type: WorkerMessage.applyRemoteMelee }); const events = []; for (const event of result?.events ?? []) { if (event.type === "entity-despawn") { this.#forget(event.entityId); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); } if (event.type === "player-died") { events.push(...this.#applyPlayerDeath(event)); continue; } this.#persistGroundEvent(event); if (event.type !== "skills-updated") { events.push(event); } } for (const forward of result?.forwards ?? []) { if (forward.type !== "forward-combat-xp") { continue; } const attackerRecord = this.directory.get(forward.entityId); if (!attackerRecord) { continue; } const xpResult = this.workers[attackerRecord.workerId].call({ type: WorkerMessage.applyCombatHitXp, entityId: forward.entityId, profile: forward.profile }); for (const xpEvent of xpResult?.events ?? []) { if (xpEvent.type === "skills-updated") { this.#applySkillsUpdated(xpEvent); } if (xpEvent.type !== "skills-updated") { events.push(xpEvent); } } } return events; } #applyPlayerDeath (event) { const record = this.directory.get(event.entityId); if (!record) { return [event]; } this.stateDb.setCharacterDead(event.characterId, true); this.stateDb.saveCharacterPosition( event.characterId, event.tileX, event.tileY, record.gait ?? GAIT.walk ); for (const worker of this.workers) { worker.call({ type: WorkerMessage.clearCombat, entityId: event.entityId, targetEntityId: event.entityId }); } const result = this.workers[record.workerId].call({ type: WorkerMessage.spawnCorpseDrops, characterId: event.characterId, tileX: event.tileX, tileY: event.tileY, now: this.now, drops: [ { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones }, { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull } ] }); const events = [event]; for (const dropEvent of result?.events ?? []) { this.#persistGroundEvent(dropEvent); events.push(dropEvent); } return events; } #respawnCharacter (sessionId, characterId) { const row = this.stateDb.getCharacter(characterId); if (!row?.is_dead) { const error = new Error("You are not dead."); error.userFacing = true; throw error; } const entityId = this.characterEntities.get(characterId); const record = entityId ? this.directory.get(entityId) : null; if (!record) { const error = new Error("Character is not in the world."); error.userFacing = true; throw error; } const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId); if (!destination) { const error = new Error("No open tile is available for respawn."); error.userFacing = true; throw error; } const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills(); const loader = { ...DEFAULT_CHUNK_LOADER }; this.#ensureCoverage(destination.tileX, destination.tileY, loader); const result = this.workers[record.workerId].call({ type: WorkerMessage.applyRespawn, entityId, sessionId, tileX: destination.tileX, tileY: destination.tileY, maxHealth: playerMaxHealth(skills), maxStamina: playerMaxStamina(skills) }); if (!result?.accepted) { const error = new Error("That respawn tile is no longer available."); error.userFacing = true; throw error; } let moveEvents = []; if (result.transferRequest) { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } else if (result.event) { this.#applyMoveToDirectory(result.event); moveEvents = [result.event]; const view = this.workers[record.workerId].call({ type: WorkerMessage.inspect, entityId }); if (view) { this.#remember(view, record.workerId); } } if (!moveEvents.length) { const error = new Error("Respawn transfer failed."); error.userFacing = true; throw error; } this.stateDb.setCharacterDead(characterId, false); this.stateDb.saveCharacterPosition( characterId, destination.tileX, destination.tileY, record.gait ?? GAIT.walk ); this.#recalculateActivation(this.now); this.#syncGhosts(); return [ ...moveEvents, { type: "player-respawned", entityId, characterId, sessionId, tileX: destination.tileX, tileY: destination.tileY, health: playerMaxHealth(skills), maxHealth: playerMaxHealth(skills), stamina: playerMaxStamina(skills), maxStamina: playerMaxStamina(skills) } ]; } #refreshAltarIndex () { const altars = []; for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId)) { const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = data.blocks[localY * CHUNK_SIZE + localX]; if (block?.typeId !== BlockType.churchAltar) { continue; } altars.push({ tileX: coord.chunk_x * CHUNK_SIZE + localX, tileY: coord.chunk_y * CHUNK_SIZE + localY }); } } } this.altarTiles = altars; } #findRespawnDestination (originX, originY, entityId) { const ordered = [...this.altarTiles].sort((left, right) => Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) ); for (const altar of ordered) { const adjacent = []; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy }); } } adjacent.sort((left, right) => Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) ); const tile = adjacent.find((entry) => this.isEnterable(entry.tileX, entry.tileY) && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId) ); if (tile) { return tile; } } for (let radius = 0; radius <= 24; radius++) { for (let dy = -radius; dy <= radius; dy++) { for (let dx = -radius; dx <= radius; dx++) { if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) { continue; } const tileX = originX + dx; const tileY = originY + dy; if (this.isEnterable(tileX, tileY) && !this.#occupiedByOther(tileX, tileY, entityId)) { return { tileX, tileY }; } } } } return this.findOpenSpawn(); } #occupiedByOther (tileX, tileY, entityId) { for (const record of this.directory.values()) { if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY) { return true; } } return false; } #recalculateActivation (now) { const loaders = this.#allLoaders(); const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); for (const [key, count] of regionRes) { if (count <= 0) { continue; } const { regionX, regionY } = parseRegionKey(key); this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY)); this.regionGraceUntil.delete(key); } for (const [key] of [...this.regionOwner.entries()]) { if ((regionRes.get(key) ?? 0) > 0) { continue; } if (!this.regionGraceUntil.has(key)) { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); } if (now >= this.regionGraceUntil.get(key)) { const { regionX, regionY } = parseRegionKey(key); this.#unloadRegion(regionX, regionY); } } for (const [workerId, worker] of this.workers.entries()) { const chunkKeys = []; for (const [key, count] of chunkSim) { if (count <= 0) { continue; } const { chunkX, chunkY } = parseChunkKey(key); if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId) { chunkKeys.push(key); } } worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys }); } this.#syncAllReplicas(); const nextSimulating = new Set(); for (const [key, count] of chunkSim) { if (count > 0) { nextSimulating.add(key); } } let preheated = false; for (const key of nextSimulating) { if (!this.simulatingChunkKeys.has(key)) { preheated = true; break; } } this.simulatingChunkKeys = nextSimulating; if (preheated) { this.#stepSpawners(); } } #ensureCoverage (tileX, tileY, loader) { const coverage = loaderCoverage(tileX, tileY, loader); let preferred = this.#ownerOfTile(tileX, tileY); for (const region of coverage.residentRegions) { const owner = this.#ensureRegion(region.regionX, region.regionY, preferred); if (preferred == null) { preferred = owner; } } } #ensureRegion (regionX, regionY, preferredWorkerId) { const key = regionKey(regionX, regionY); if (this.regionOwner.has(key)) { return this.regionOwner.get(key); } const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId); this.workers[workerId].call({ type: WorkerMessage.assignRegion, regionX, regionY, chunks: this.#regionChunkBlobs(regionX, regionY) }); this.regionOwner.set(key, workerId); this.#restorePersistent(regionX, regionY, workerId); this.#restoreGroundItems(regionX, regionY, workerId); return workerId; } #unloadRegion (regionX, regionY) { const key = regionKey(regionX, regionY); const workerId = this.regionOwner.get(key); if (workerId == null) { return; } const bounds = regionTileBounds(regionX, regionY); const { dropped, groundItems } = this.workers[workerId].call({ type: WorkerMessage.dropRegion, regionX, regionY }); const persistent = []; for (const record of dropped ?? []) { if (record.characterId) { this.stateDb.saveCharacterPosition( record.characterId, record.tileX, record.tileY, record.gait ?? GAIT.walk ); } if (record.persistent) { persistent.push(record); } this.#forget(record.entityId); } this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent); for (const item of groundItems ?? []) { this.stateDb.upsertGroundItem(item); } this.regionOwner.delete(key); this.regionGraceUntil.delete(key); } #restorePersistent (regionX, regionY, workerId) { const bounds = regionTileBounds(regionX, regionY); const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); for (const row of rows) { if (this.directory.has(row.entity_id)) { continue; } const components = JSON.parse(row.components_blob); const view = this.workers[workerId].call({ type: WorkerMessage.spawn, entityId: row.entity_id, components }); this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1); this.#remember(view, workerId); } } #applyTransfers (requests) { const events = []; for (const request of requests) { const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId); if (destWorkerId === request.fromWorkerId) { this.workers[request.fromWorkerId].call({ type: WorkerMessage.abortTransfer, entityId: request.entityId }); continue; } let result; try { result = this.workers[destWorkerId].call({ type: WorkerMessage.applyTransfer, payload: request.payload, destTileX: request.destTileX, destTileY: request.destTileY }); } catch { result = { accepted: false }; } if (!result?.accepted) { this.workers[request.fromWorkerId].call({ type: WorkerMessage.abortTransfer, entityId: request.entityId }); continue; } this.workers[request.fromWorkerId].call({ type: WorkerMessage.commitTransfer, entityId: request.entityId }); this.#remember(result.entity, destWorkerId); events.push({ type: "entity-move", entityId: request.entityId, fromTileX: request.fromTileX, fromTileY: request.fromTileY, tileX: result.entity.tileX, tileY: result.entity.tileY, gait: result.entity.gait }); } return events; } #syncAllReplicas () { for (const [workerId, worker] of this.workers.entries()) { const ownedKeys = new Set(); for (const [key, owner] of this.regionOwner) { if (owner !== workerId) { continue; } const { regionX, regionY } = parseRegionKey(key); for (const chunk of chunksInRegion(regionX, regionY)) { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); } } const replicas = []; for (const key of replicaNeededForOwnedChunks(ownedKeys)) { if (ownedKeys.has(key)) { continue; } const { chunkX, chunkY } = parseChunkKey(key); replicas.push({ chunkX, chunkY, data: this.#authoredChunk(chunkX, chunkY) }); } worker.call({ type: WorkerMessage.setReplicas, chunks: replicas }); } } #syncGhosts () { const entities = []; for (const worker of this.workers) { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); } for (const [workerId, worker] of this.workers.entries()) { const ghosts = entities.filter((entity) => { if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId) { return false; } return this.#nearWorker(workerId, entity.tileX, entity.tileY); }); worker.call({ type: WorkerMessage.setGhosts, ghosts }); } } #nearWorker (workerId, tileX, tileY) { const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); for (const [key, owner] of this.regionOwner) { if (owner !== workerId) { continue; } const { regionX, regionY } = parseRegionKey(key); for (const chunk of chunksInRegion(regionX, regionY)) { if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2) { return true; } } } return false; } #allLoaders () { const loaders = []; for (const worker of this.workers) { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); } return loaders; } #preferredWorkerForRegion (loaders, regionX, regionY) { const votes = new Map(); for (const loader of loaders) { const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader); if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY)) { continue; } const record = this.directory.get(loader.entityId); if (record?.workerId == null) { continue; } votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1); } let best = null; let bestVotes = -1; for (const [workerId, count] of votes) { if (count > bestVotes) { best = workerId; bestVotes = count; } } return best; } #pickWorker (regionX, regionY, preferredWorkerId) { const pinned = this.pinRegion?.(regionX, regionY); if (pinned != null) { return pinned; } const neighborOwners = []; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy)); if (owner != null) { neighborOwners.push(owner); } } } const scores = this.workers.map((_, workerId) => ({ workerId, neighbors: neighborOwners.filter((owner) => owner === workerId).length, load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length })); if (preferredWorkerId != null && scores[preferredWorkerId]) { const preferred = scores[preferredWorkerId]; if (preferred.neighbors > 0 || neighborOwners.length === 0) { return preferredWorkerId; } } scores.sort((left, right) => right.neighbors - left.neighbors || left.load - right.load || left.workerId - right.workerId ); return scores[0].workerId; } #ownerOfTile (tileX, tileY) { return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null; } #regionKeyForChunk (chunkX, chunkY) { return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY)); } #regionChunkBlobs (regionX, regionY) { return chunksInRegion(regionX, regionY).map((coord) => ({ chunkX: coord.chunkX, chunkY: coord.chunkY, data: this.#authoredChunk(coord.chunkX, coord.chunkY) })); } #authoredChunk (chunkX, chunkY) { const key = chunkKey(chunkX, chunkY); if (this.authoredCache.has(key)) { return this.authoredCache.get(key); } const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId); const data = row ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId) : createEmptyChunkData(this.settings.defaultGroundTypeId); this.authoredCache.set(key, data); return data; } #syntheticSnapshot (chunkX, chunkY) { const data = this.#authoredChunk(chunkX, chunkY); return { chunkX, chunkY, open: data.open, closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open), grounds: data.grounds, blocks: data.blocks, light: data.light, entities: [], groundItems: [] }; } #occupiedTile (tileX, tileY) { for (const record of this.directory.values()) { if (record.tileX === tileX && record.tileY === tileY) { return record.entityId; } } return null; } #queueReplication (event) { if (event) { this.replication.push(event); } } #stepSpawners () { const events = []; for (const worker of this.workers) { const result = worker.call({ type: WorkerMessage.stepSpawners }); for (const request of result?.spawnRequests ?? []) { try { this.spawnEntity(mobComponents(request), { requireResident: true }); } catch { continue; } } } return events; } #restoreGroundItems (regionX, regionY, workerId) { const bounds = regionTileBounds(regionX, regionY); const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY) .filter((item) => item.expiresAt > this.now); this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId()); this.workers[workerId].call({ type: WorkerMessage.setGroundItems, regionX, regionY, items }); } #persistGroundEvent (event) { if (event.type === "ground-item-appear") { this.stateDb.upsertGroundItem({ groundItemId: event.groundItemId, tileX: event.tileX, tileY: event.tileY, stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity }, droppedAt: event.droppedAt ?? this.now, expiresAt: event.expiresAt, source: event.source ?? "player-drop", droppedByCharacterId: event.droppedByCharacterId ?? null }); } if (event.type === "ground-item-despawn") { this.stateDb.deleteGroundItem(event.groundItemId); } } #saveBag (entityId, workerId) { const record = this.directory.get(entityId); const bag = this.workers[workerId].call({ type: WorkerMessage.inspectBag, entityId }); if (!bag || !record?.characterId) { return; } this.#saveBagFromView(record.characterId, bag); const skills = this.workers[workerId].call({ type: WorkerMessage.inspectSkills, entityId }); if (skills) { this.stateDb.saveSkills(record.characterId, skills); } } #applySkillsUpdated (event) { if (!event?.characterId || !event.stored) { return; } this.stateDb.saveSkills(event.characterId, { xp: event.stored }); this.pushSkills(event.characterId, event.skills ?? []); } #saveBagFromView (characterId, bag) { this.stateDb.saveBag(characterId, { inventory: bag.inventory, equipment: bag.equipment, vault: bag.vault, vaultReserved: bag.vaultReserved }); } releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null) { const onlineId = this.characterEntities.get(issuerCharacterId); const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); if (!bag) { return { ok: false, error: "Issuer vault not found." }; } const reserved = [...(bag.vaultReserved ?? [])]; const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId }); if (index < 0) { return { ok: false, error: "That cheque cannot be redeemed." }; } const [stack] = reserved.splice(index, 1); bag.vaultReserved = reserved; this.stateDb.saveBag(issuerCharacterId, bag); if (onlineId) { this.applyBag(onlineId, bag); this.pushInventory(issuerCharacterId, bag); } return { ok: true, stack }; } restoreChequeReservation (issuerCharacterId, stack) { const onlineId = this.characterEntities.get(issuerCharacterId); const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); if (!bag) { return; } bag.vaultReserved = [...(bag.vaultReserved ?? []), stack]; this.stateDb.saveBag(issuerCharacterId, bag); if (onlineId) { this.applyBag(onlineId, bag); this.pushInventory(issuerCharacterId, bag); } } #remember (view, workerId) { if (!view) { return; } this.directory.set(view.entityId, { ...view, workerId }); if (view.characterId) { this.characterEntities.set(view.characterId, view.entityId); } } #applyMoveToDirectory (event) { const record = this.directory.get(event.entityId); if (!record) { return; } record.tileX = event.tileX; record.tileY = event.tileY; record.gait = event.gait; if (event.worldX != null) { record.worldX = event.worldX; } if (event.worldY != null) { record.worldY = event.worldY; } if (event.freeFlight != null) { record.freeFlight = !!event.freeFlight; } } #forget (entityId) { const record = this.directory.get(entityId); if (record?.characterId) { this.characterEntities.delete(record.characterId); } this.directory.delete(entityId); } }