| 1 | import |
| 2 | { |
| 3 | CHUNK_SIZE, |
| 4 | DEFAULT_CHUNK_LOADER, |
| 5 | GAIT, |
| 6 | REGION_RUNTIME_STATE, |
| 7 | VISIBLE_CHUNK_RADIUS, |
| 8 | STATIC_CHUNK_RADIUS, |
| 9 | WORLD_YEAR_OFFSET |
| 10 | } from "../../../shared/protocol/constants.js"; |
| 11 | import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js"; |
| 12 | import |
| 13 | { |
| 14 | chunkKey, |
| 15 | chunkToRegion, |
| 16 | chunksInRegion, |
| 17 | parseChunkKey, |
| 18 | parseRegionKey, |
| 19 | regionKey, |
| 20 | regionTileBounds, |
| 21 | tileToChunk, |
| 22 | tileToLocal, |
| 23 | tileToRegion, |
| 24 | visibleChunkCoords |
| 25 | } from "../world/coordinates.js"; |
| 26 | import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; |
| 27 | import { closedNeighborEdges } from "../world/chunkFlags.js"; |
| 28 | import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js"; |
| 29 | import { InProcessWorker } from "./inProcessWorker.js"; |
| 30 | import { ThreadWorker } from "./threadWorker.js"; |
| 31 | import { WorkerMessage } from "./protocol.js"; |
| 32 | import { replicaNeededForOwnedChunks } from "./workerWorld.js"; |
| 33 | import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js"; |
| 34 | import { emptyEquipment, emptySlots, insertStackGrowable } from "../../../shared/items/inventory.js"; |
| 35 | import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; |
| 36 | import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js"; |
| 37 | import { COMBAT_LOGOUT_MS } from "../../../shared/combat/combatLogout.js"; |
| 38 | import |
| 39 | { |
| 40 | applyCombatLogoutCowardice, |
| 41 | coinsDroppedFromDeathEvents, |
| 42 | dispatchChurchOfflineResurrectionLetter |
| 43 | } from "../combat/combatLogout.js"; |
| 44 | import { mobComponents } from "./spawners.js"; |
| 45 | import { shadeSummonComponents } from "../spells/summons.js"; |
| 46 | import { jadeiteFairyComponents } from "../spells/jadeiteFairy.js"; |
| 47 | import { MobId } from "../../../shared/definitions/mobs.js"; |
| 48 | import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js"; |
| 49 | import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js"; |
| 50 | import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js"; |
| 51 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 52 | import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; |
| 53 | import { seasonIdAt } from "../../../shared/world/season.js"; |
| 54 | import { CourierService } from "../courier/service.js"; |
| 55 | import { MarketService } from "../market/service.js"; |
| 56 | import { TradeService } from "../trade/service.js"; |
| 57 | import { BountyService } from "../bounty/service.js"; |
| 58 | import { BarberService } from "../barber/service.js"; |
| 59 | import { findReservedChequeIndex } from "../items/bags.js"; |
| 60 | import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js"; |
| 61 | import { QuestContentCache } from "../quests/contentCache.js"; |
| 62 | import { QuestRuntime } from "../quests/runtime.js"; |
| 63 | import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; |
| 64 | import { buildConditionAccessSnapshot } from "../doors/conditionContext.js"; |
| 65 | |
| 66 | export class Simulation |
| 67 | { |
| 68 | constructor(worldDb, stateDb, options = {}) |
| 69 | { |
| 70 | this.worldDb = worldDb; |
| 71 | this.stateDb = stateDb; |
| 72 | this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2))); |
| 73 | this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess"; |
| 74 | this.pinRegion = options.pinRegion ?? null; |
| 75 | this.nowFn = options.now ?? (() => Date.now()); |
| 76 | this.workers = []; |
| 77 | this.regionOwner = new Map(); |
| 78 | this.regionGraceUntil = new Map(); |
| 79 | this.directory = new Map(); |
| 80 | this.characterEntities = new Map(); |
| 81 | /** @type {Map<number, { lastCombatEndedAt: number|null, lastOutboundAttackAt: number|null, lastCombatActivityAt: number|null, pvpInvolved: boolean, wasInCombat: boolean }>} */ |
| 82 | this.combatTracking = new Map(); |
| 83 | /** @type {Map<number, { savedAutoCast: boolean, pendingCowardice: boolean, startedAt: number }>} */ |
| 84 | this.combatLogouts = new Map(); |
| 85 | this.commandQueue = []; |
| 86 | this.replication = []; |
| 87 | this.pendingPrivate = []; |
| 88 | this.courier = null; |
| 89 | this.market = null; |
| 90 | this.altarTiles = []; |
| 91 | this.authoredCache = new Map(); |
| 92 | this.simulatingChunkKeys = new Set(); |
| 93 | this.nextEntityId = 1; |
| 94 | this.nextGroundItemId = stateDb.nextGroundItemId(); |
| 95 | this.tickIndex = 0; |
| 96 | this.movementTickCounter = 0; |
| 97 | this.lastTickAt = null; |
| 98 | this.movementAccumulator = 0; |
| 99 | this.activeRevisionId = worldDb.getActiveRevisionId(); |
| 100 | this.settings = worldDb.getLiveSettings(); |
| 101 | this.questContent = new QuestContentCache(worldDb); |
| 102 | this.dimensions = this.#loadDimensionsCache(); |
| 103 | this.quests = null; |
| 104 | |
| 105 | const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker; |
| 106 | for (let workerId = 0; workerId < this.workerCount; workerId++) |
| 107 | { |
| 108 | const worker = new WorkerImpl(workerId); |
| 109 | worker.call({ |
| 110 | type: WorkerMessage.configure, |
| 111 | settings: this.settings, |
| 112 | activeRevisionId: this.activeRevisionId |
| 113 | }); |
| 114 | this.workers.push(worker); |
| 115 | } |
| 116 | for (const worker of this.workers) |
| 117 | { |
| 118 | if (!worker.world) |
| 119 | { continue; } |
| 120 | worker.world.releaseChequeReservation = (issuerId, chequeId, instance) => |
| 121 | this.releaseChequeReservation(issuerId, chequeId, instance); |
| 122 | worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack); |
| 123 | worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack); |
| 124 | } |
| 125 | this.courier = new CourierService({ |
| 126 | stateDb: this.stateDb, |
| 127 | worldDb: this.worldDb, |
| 128 | simulation: this |
| 129 | }); |
| 130 | this.market = new MarketService({ |
| 131 | stateDb: this.stateDb, |
| 132 | worldDb: this.worldDb, |
| 133 | simulation: this |
| 134 | }); |
| 135 | this.trade = new TradeService({ |
| 136 | stateDb: this.stateDb, |
| 137 | simulation: this |
| 138 | }); |
| 139 | this.bounty = new BountyService(this.stateDb, this, this.courier); |
| 140 | this.barber = new BarberService(this.stateDb, this); |
| 141 | this.quests = new QuestRuntime({ |
| 142 | stateDb: this.stateDb, |
| 143 | content: this.questContent, |
| 144 | simulation: this |
| 145 | }); |
| 146 | this.#refreshAltarIndex(); |
| 147 | } |
| 148 | |
| 149 | get now () |
| 150 | { |
| 151 | return this.nowFn(); |
| 152 | } |
| 153 | |
| 154 | applySettings (settings, { grantInitialQuests = false } = {}) |
| 155 | { |
| 156 | this.settings = { ...this.settings, ...settings }; |
| 157 | this.#configureWorkers(); |
| 158 | if (grantInitialQuests) |
| 159 | { this.quests?.grantInitialQuestsToAllCharacters?.(); } |
| 160 | } |
| 161 | |
| 162 | /** Sparse last-sale map for editor base-price readouts. */ |
| 163 | itemLastSalesSnapshot () |
| 164 | { |
| 165 | return this.market?.snapshot?.() ?? {}; |
| 166 | } |
| 167 | |
| 168 | syncItemLastSales (lastSales) |
| 169 | { |
| 170 | const sales = {}; |
| 171 | for (const [itemId, sale] of lastSales?.entries?.() ?? []) |
| 172 | { sales[String(itemId)] = sale; } |
| 173 | for (const worker of this.workers) |
| 174 | { |
| 175 | worker.call({ |
| 176 | type: WorkerMessage.setItemLastSales, |
| 177 | sales |
| 178 | }); |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | reloadWorld () |
| 183 | { |
| 184 | this.activeRevisionId = this.worldDb.getActiveRevisionId(); |
| 185 | this.settings = this.worldDb.getLiveSettings(); |
| 186 | this.dimensions = this.#loadDimensionsCache(); |
| 187 | this.authoredCache.clear(); |
| 188 | this.#configureWorkers(); |
| 189 | for (const [key, workerId] of this.regionOwner) |
| 190 | { |
| 191 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 192 | this.workers[workerId].call({ |
| 193 | type: WorkerMessage.replaceRegionChunks, |
| 194 | regionX, |
| 195 | regionY, |
| 196 | dimensionId, |
| 197 | chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId) |
| 198 | }); |
| 199 | } |
| 200 | this.#syncAllReplicas(); |
| 201 | this.courier?.refreshBankIndex(); |
| 202 | this.courier?.refreshBountyOfficeIndex(); |
| 203 | this.market?.refreshIndex(); |
| 204 | this.questContent.reload(); |
| 205 | this.quests?.closeAllSessions(); |
| 206 | this.#refreshAltarIndex(); |
| 207 | } |
| 208 | |
| 209 | enqueue (sessionId, command) |
| 210 | { |
| 211 | this.commandQueue.push({ sessionId, command, receivedAt: this.now }); |
| 212 | } |
| 213 | |
| 214 | step (now = this.now) |
| 215 | { |
| 216 | this.tickIndex += 1; |
| 217 | if ((this.tickIndex % 1200) === 0) |
| 218 | { this.worldDb.purgeExpiredDimensions(now); } |
| 219 | const events = []; |
| 220 | const commands = this.commandQueue.splice(0); |
| 221 | for (const item of commands) |
| 222 | { |
| 223 | try |
| 224 | { |
| 225 | events.push(...this.#routeCommand(item)); |
| 226 | } |
| 227 | catch (error) |
| 228 | { |
| 229 | events.push({ |
| 230 | sessionId: item.sessionId, |
| 231 | type: "command-error", |
| 232 | message: error.userFacing ? error.message : "Command failed." |
| 233 | }); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | this.#recalculateActivation(now); |
| 238 | |
| 239 | const simHz = Math.max(1, this.settings.simulationTickHz || 20); |
| 240 | const expectedDt = 1 / simHz; |
| 241 | const dt = (this.lastTickAt == null || now <= this.lastTickAt) |
| 242 | ? expectedDt |
| 243 | : Math.min(0.25, (now - this.lastTickAt) / 1000); |
| 244 | this.lastTickAt = now; |
| 245 | |
| 246 | { |
| 247 | const transfers = []; |
| 248 | const remoteMelee = []; |
| 249 | const remoteRanged = []; |
| 250 | for (const worker of this.workers) |
| 251 | { |
| 252 | const result = worker.call({ type: WorkerMessage.stepSystems, now, dt }); |
| 253 | for (const event of result?.events ?? []) |
| 254 | { |
| 255 | if (event.type === "remote-melee-resolve") |
| 256 | { |
| 257 | remoteMelee.push(event); |
| 258 | continue; |
| 259 | } |
| 260 | if (event.type === "remote-ranged-resolve") |
| 261 | { |
| 262 | remoteRanged.push(event); |
| 263 | continue; |
| 264 | } |
| 265 | if (event.type === "summon-entity") |
| 266 | { |
| 267 | events.push(...this.#applySummonEntity(event)); |
| 268 | continue; |
| 269 | } |
| 270 | if (event.type === "jewelry-teleport-finish") |
| 271 | { |
| 272 | events.push(...this.#applyJewelryTeleport(event)); |
| 273 | continue; |
| 274 | } |
| 275 | if (event.type === "entity-move") |
| 276 | { this.#applyMoveToDirectory(event); } |
| 277 | if (event.type === "entity-despawn") |
| 278 | { this.#forget(event.entityId); } |
| 279 | if (event.type === "skills-updated") |
| 280 | { |
| 281 | this.#applySkillsUpdated(event); |
| 282 | events.push(...this.#skillLevelUpEvents(event)); |
| 283 | continue; |
| 284 | } |
| 285 | if (event.type === "spells-updated") |
| 286 | { |
| 287 | this.#applySpellsUpdated(event); |
| 288 | continue; |
| 289 | } |
| 290 | if (event.type === "inventory" && event.characterId) |
| 291 | { |
| 292 | this.#saveBagFromView(event.characterId, { |
| 293 | inventory: event.inventory, |
| 294 | equipment: event.equipment, |
| 295 | vault: event.vault, |
| 296 | vaultReserved: event.vaultReserved |
| 297 | }); |
| 298 | } |
| 299 | if (event.type === "player-died") |
| 300 | { |
| 301 | events.push(...this.#applyPlayerDeath(event)); |
| 302 | continue; |
| 303 | } |
| 304 | if ( |
| 305 | event.type === "combat-hit" |
| 306 | || event.type === "combat-miss" |
| 307 | || event.type === "combat-block" |
| 308 | || event.type === "combat-swing" |
| 309 | ) |
| 310 | { this.#noteCombatEvent(event); } |
| 311 | if (event.type === "mob-killed") |
| 312 | { |
| 313 | events.push(...this.#applyMobKilled(event)); |
| 314 | continue; |
| 315 | } |
| 316 | if (event.type === "dialogue-walk-away") |
| 317 | { |
| 318 | const closed = this.quests?.closeDialogue(event.characterId, "walk-away"); |
| 319 | events.push(...this.#mapQuestPrivateEvents( |
| 320 | closed?.events ?? [], |
| 321 | event.sessionId, |
| 322 | event.characterId |
| 323 | )); |
| 324 | continue; |
| 325 | } |
| 326 | this.#persistGroundEvent(event); |
| 327 | if (event.type !== "skills-updated") |
| 328 | { events.push(event); } |
| 329 | } |
| 330 | for (const request of result?.transferRequests ?? []) |
| 331 | { transfers.push({ ...request, fromWorkerId: worker.workerId }); } |
| 332 | } |
| 333 | for (const payload of remoteMelee) |
| 334 | { events.push(...this.#applyRemoteMelee(payload)); } |
| 335 | for (const payload of remoteRanged) |
| 336 | { events.push(...this.#applyRemoteRanged(payload)); } |
| 337 | if (transfers.length) |
| 338 | { |
| 339 | events.push(...this.#applyTransfers(transfers)); |
| 340 | this.#recalculateActivation(now); |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2); |
| 345 | this.movementAccumulator += dt * movementHz; |
| 346 | while (this.movementAccumulator >= 1) |
| 347 | { |
| 348 | this.movementAccumulator -= 1; |
| 349 | this.movementTickCounter += 1; |
| 350 | const transfers = []; |
| 351 | for (const worker of this.workers) |
| 352 | { |
| 353 | const result = worker.call({ type: WorkerMessage.stepMovement, now }); |
| 354 | for (const event of result?.events ?? []) |
| 355 | { |
| 356 | if (event.type === "entity-move") |
| 357 | { this.#applyMoveToDirectory(event); } |
| 358 | if (event.type === "skills-updated") |
| 359 | { |
| 360 | this.#applySkillsUpdated(event); |
| 361 | events.push(...this.#skillLevelUpEvents(event)); |
| 362 | continue; |
| 363 | } |
| 364 | if (event.type === "spells-updated") |
| 365 | { |
| 366 | this.#applySpellsUpdated(event); |
| 367 | continue; |
| 368 | } |
| 369 | this.#persistGroundEvent(event); |
| 370 | if (event.type !== "skills-updated") |
| 371 | { events.push(event); } |
| 372 | } |
| 373 | for (const request of result?.transferRequests ?? []) |
| 374 | { transfers.push({ ...request, fromWorkerId: worker.workerId }); } |
| 375 | } |
| 376 | events.push(...this.#applyTransfers(transfers)); |
| 377 | this.#recalculateActivation(now); |
| 378 | } |
| 379 | |
| 380 | if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0) |
| 381 | { events.push(...this.#stepSpawners()); } |
| 382 | |
| 383 | if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0) |
| 384 | { |
| 385 | this.#stepSkullDecay(); |
| 386 | events.push(...this.#stepCombatLogout()); |
| 387 | } |
| 388 | |
| 389 | if (this.courier) |
| 390 | { events.push(...this.courier.step(now, dt)); } |
| 391 | if (this.market) |
| 392 | { events.push(...this.market.step(now)); } |
| 393 | if (this.trade) |
| 394 | { events.push(...this.trade.step(now)); } |
| 395 | |
| 396 | this.#syncGhosts(); |
| 397 | events.push(...this.pendingPrivate.splice(0)); |
| 398 | return { now, events, replication: this.drainReplication() }; |
| 399 | } |
| 400 | |
| 401 | drainReplication () |
| 402 | { |
| 403 | return this.replication.splice(0); |
| 404 | } |
| 405 | |
| 406 | worldTime (now = this.now) |
| 407 | { |
| 408 | const date = new Date(now); |
| 409 | date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET); |
| 410 | return { |
| 411 | unixMs: now, |
| 412 | worldUnixMs: date.getTime(), |
| 413 | iso: date.toISOString(), |
| 414 | hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600, |
| 415 | season: seasonIdAt(now) |
| 416 | }; |
| 417 | } |
| 418 | |
| 419 | spawnCharacter (sessionId, character) |
| 420 | { |
| 421 | this.despawnCharacter(character.character_id); |
| 422 | // Despawn may have just written the live tile; never trust a stale row snapshot. |
| 423 | const row = this.stateDb.getCharacter(character.character_id) ?? character; |
| 424 | let tileX = row.tile_x; |
| 425 | let tileY = row.tile_y; |
| 426 | let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID); |
| 427 | const gait = row.gait || character.gait || GAIT.walk; |
| 428 | |
| 429 | // Soft-deleted / purged interiors eject to overworld spawn. |
| 430 | if (!this.#isDimensionUsable(dimensionId)) |
| 431 | { |
| 432 | dimensionId = OVERWORLD_ID; |
| 433 | const spawn = this.findOpenSpawn(); |
| 434 | if (!spawn) |
| 435 | { |
| 436 | const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); |
| 437 | error.userFacing = true; |
| 438 | throw error; |
| 439 | } |
| 440 | tileX = spawn.tileX; |
| 441 | tileY = spawn.tileY; |
| 442 | this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId); |
| 443 | } |
| 444 | |
| 445 | const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId); |
| 446 | if (!preferred) |
| 447 | { |
| 448 | const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); |
| 449 | error.userFacing = true; |
| 450 | throw error; |
| 451 | } |
| 452 | if ( |
| 453 | preferred.tileX !== tileX |
| 454 | || preferred.tileY !== tileY |
| 455 | || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId |
| 456 | ) |
| 457 | { |
| 458 | tileX = preferred.tileX; |
| 459 | tileY = preferred.tileY; |
| 460 | dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId); |
| 461 | this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId); |
| 462 | } |
| 463 | |
| 464 | const bag = this.stateDb.getBag(character.character_id) ?? { |
| 465 | inventory: emptySlots(), |
| 466 | equipment: emptyEquipment(), |
| 467 | vault: [], |
| 468 | vaultReserved: [] |
| 469 | }; |
| 470 | const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills(); |
| 471 | const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells(); |
| 472 | // Login floor: Health ≥ 5, every other skill ≥ 1 (persist if raised). |
| 473 | if (enforceMinimumSkillLevels(skills)) |
| 474 | { this.stateDb.saveSkills(character.character_id, skills); } |
| 475 | const maxHealth = playerMaxHealth(skills); |
| 476 | const maxStamina = playerMaxStamina(skills); |
| 477 | const isDead = !!row.is_dead; |
| 478 | const savedHealth = row.health_current; |
| 479 | const currentHealth = isDead |
| 480 | ? 0 |
| 481 | : savedHealth != null |
| 482 | ? Math.max(0, Math.min(maxHealth, savedHealth | 0)) |
| 483 | : maxHealth; |
| 484 | const entityId = this.nextEntityId++; |
| 485 | const components = { |
| 486 | position: { tileX, tileY, dimensionId }, |
| 487 | movement: { gait, walkCarry: 0 }, |
| 488 | path: { tiles: [] }, |
| 489 | appearance: { |
| 490 | sex: character.sex ?? row.sex, |
| 491 | firstName: character.first_name ?? row.first_name, |
| 492 | lastName: character.last_name ?? row.last_name, |
| 493 | ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character)) |
| 494 | }, |
| 495 | character: { |
| 496 | characterId: character.character_id ?? row.character_id, |
| 497 | accountId: character.account_id ?? row.account_id, |
| 498 | skullValue: this.characterSkullValue(character.character_id ?? row.character_id) |
| 499 | }, |
| 500 | networkIdentity: { sessionId }, |
| 501 | chunkLoader: { ...DEFAULT_CHUNK_LOADER }, |
| 502 | inventory: { slots: bag.inventory ?? emptySlots() }, |
| 503 | equipment: bag.equipment ?? emptyEquipment(), |
| 504 | vault: { |
| 505 | slots: bag.vault ?? [], |
| 506 | reserved: bag.vaultReserved ?? [] |
| 507 | }, |
| 508 | health: { current: currentHealth, max: maxHealth }, |
| 509 | stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 }, |
| 510 | combat: { targetEntityId: null, nextSwingAt: 0 }, |
| 511 | skills, |
| 512 | spells, |
| 513 | spellcasting: { |
| 514 | armedSpellId: null, |
| 515 | repeatSpellId: null, |
| 516 | repeatTargetEntityId: null, |
| 517 | repeatTileX: null, |
| 518 | repeatTileY: null, |
| 519 | nextCastAt: 0, |
| 520 | pendingCast: null |
| 521 | }, |
| 522 | chunkPresence: { |
| 523 | chunkX: tileToChunk(tileX), |
| 524 | chunkY: tileToChunk(tileY), |
| 525 | dimensionId, |
| 526 | sinceMs: this.now |
| 527 | }, |
| 528 | conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id) |
| 529 | }; |
| 530 | if (isDead) |
| 531 | { components.dead = {}; } |
| 532 | this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId); |
| 533 | const workerId = this.#ownerOfTile(tileX, tileY, dimensionId); |
| 534 | const view = this.workers[workerId].call({ |
| 535 | type: WorkerMessage.spawn, |
| 536 | entityId, |
| 537 | components |
| 538 | }); |
| 539 | this.#remember(view, workerId); |
| 540 | this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id); |
| 541 | this.stateDb.markDimensionVisited(character.character_id, dimensionId); |
| 542 | this.syncCharacterConditionAccess(character.character_id ?? row.character_id); |
| 543 | this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view)); |
| 544 | this.#recalculateActivation(this.now); |
| 545 | this.#syncGhosts(); |
| 546 | this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY); |
| 547 | this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id); |
| 548 | this.syncCharacterConditionAccess(character.character_id ?? row.character_id); |
| 549 | return entityId; |
| 550 | } |
| 551 | |
| 552 | characterSkullValue (characterId, now = this.now) |
| 553 | { |
| 554 | const bounty = this.stateDb.getCharacterBounty(characterId, now); |
| 555 | const killCounter = this.stateDb.peekKillCounter(characterId, now); |
| 556 | return skullValue(bounty, killCounter); |
| 557 | } |
| 558 | |
| 559 | refreshCharacterSkull (characterId, { force = false } = {}) |
| 560 | { |
| 561 | const id = characterId | 0; |
| 562 | if (!id) |
| 563 | { return null; } |
| 564 | const state = this.stateDb.getKillCounterState(id); |
| 565 | const elapsed = Math.max(0, this.now - (state.updatedAt | 0)); |
| 566 | const decayed = decayKillCounter(state.killCounter, elapsed); |
| 567 | if (decayed.killCounter !== state.killCounter) |
| 568 | { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); } |
| 569 | const value = this.characterSkullValue(id); |
| 570 | const entityId = this.characterEntities.get(id); |
| 571 | const record = entityId ? this.directory.get(entityId) : null; |
| 572 | if (!record) |
| 573 | { return null; } |
| 574 | if (!force && (record.skullValue | 0) === value) |
| 575 | { return null; } |
| 576 | record.skullValue = value; |
| 577 | this.workers[record.workerId]?.call({ |
| 578 | type: WorkerMessage.applySkullValue, |
| 579 | entityId, |
| 580 | skullValue: value |
| 581 | }); |
| 582 | const event = { |
| 583 | type: "entity-skull", |
| 584 | entityId, |
| 585 | skullValue: value, |
| 586 | tileX: record.tileX, |
| 587 | tileY: record.tileY, |
| 588 | dimensionId: record.dimensionId ?? OVERWORLD_ID |
| 589 | }; |
| 590 | this.#queueReplication(event); |
| 591 | return event; |
| 592 | } |
| 593 | |
| 594 | /** Push quest / dialogue / visited-dim snapshot onto the character's worker ECS. */ |
| 595 | syncCharacterConditionAccess (characterId) |
| 596 | { |
| 597 | const id = characterId | 0; |
| 598 | if (!id) |
| 599 | { return; } |
| 600 | const entityId = this.characterEntities.get(id); |
| 601 | const record = entityId ? this.directory.get(entityId) : null; |
| 602 | if (!record) |
| 603 | { return; } |
| 604 | this.workers[record.workerId]?.call({ |
| 605 | type: WorkerMessage.applyConditionAccess, |
| 606 | entityId, |
| 607 | conditionAccess: buildConditionAccessSnapshot(this.stateDb, id) |
| 608 | }); |
| 609 | } |
| 610 | |
| 611 | #attachSkullToRecord (entityId, characterId) |
| 612 | { |
| 613 | const record = this.directory.get(entityId); |
| 614 | if (!record) |
| 615 | { return; } |
| 616 | const value = this.characterSkullValue(characterId); |
| 617 | record.skullValue = value; |
| 618 | this.workers[record.workerId]?.call({ |
| 619 | type: WorkerMessage.applySkullValue, |
| 620 | entityId, |
| 621 | skullValue: value |
| 622 | }); |
| 623 | } |
| 624 | |
| 625 | #stepSkullDecay () |
| 626 | { |
| 627 | for (const characterId of this.characterEntities.keys()) |
| 628 | { |
| 629 | const state = this.stateDb.getKillCounterState(characterId); |
| 630 | if (!(state.killCounter > 0)) |
| 631 | { continue; } |
| 632 | this.refreshCharacterSkull(characterId); |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | isCharacterOnline (characterId) |
| 637 | { |
| 638 | const id = characterId | 0; |
| 639 | return this.characterEntities.has(id) && !this.combatLogouts.has(id); |
| 640 | } |
| 641 | |
| 642 | /** True while the entity exists, including combat-logout ghosts without a session. */ |
| 643 | isCharacterInWorld (characterId) |
| 644 | { |
| 645 | return this.characterEntities.has(characterId | 0); |
| 646 | } |
| 647 | |
| 648 | isCombatLogout (characterId) |
| 649 | { |
| 650 | return this.combatLogouts.has(characterId | 0); |
| 651 | } |
| 652 | |
| 653 | /** Apply a worker `player-died` event (also used by combat-logout tests). */ |
| 654 | applyPlayerDiedEvent (event) |
| 655 | { |
| 656 | return this.#applyPlayerDeath(event); |
| 657 | } |
| 658 | |
| 659 | /** |
| 660 | * Keep the character fighting after the controlling session leaves. |
| 661 | * @returns {boolean} true when the character stayed in the world |
| 662 | */ |
| 663 | beginCombatLogout (characterId) |
| 664 | { |
| 665 | const id = characterId | 0; |
| 666 | if (!this.characterEntities.has(id)) |
| 667 | { return false; } |
| 668 | if (this.combatLogouts.has(id)) |
| 669 | { return true; } |
| 670 | const row = this.stateDb.getCharacter(id); |
| 671 | if (row?.is_dead) |
| 672 | { return false; } |
| 673 | if (!this.#shouldStayOnLeave(id)) |
| 674 | { return false; } |
| 675 | this.market?.leaveExchangeStations?.(id); |
| 676 | const track = this.#ensureCombatTrack(id); |
| 677 | const spells = this.#setCharacterAutoCast(id, true); |
| 678 | this.combatLogouts.set(id, { |
| 679 | savedAutoCast: spells?.previousAutoCast ?? false, |
| 680 | pendingCowardice: !!track.pvpInvolved, |
| 681 | startedAt: this.now |
| 682 | }); |
| 683 | return true; |
| 684 | } |
| 685 | |
| 686 | /** |
| 687 | * Player reclaimed the character. Restore prefs and apply pending PvP cowardice. |
| 688 | */ |
| 689 | endCombatLogout (characterId, { applyCowardice = true } = {}) |
| 690 | { |
| 691 | const id = characterId | 0; |
| 692 | const logout = this.combatLogouts.get(id); |
| 693 | if (!logout) |
| 694 | { return { ended: false }; } |
| 695 | let cowardice = null; |
| 696 | // Apply while still marked combat-logout so system letters stay held offline. |
| 697 | if (applyCowardice && logout.pendingCowardice) |
| 698 | { cowardice = applyCombatLogoutCowardice(this, id, { now: this.now }); } |
| 699 | this.#restoreCombatLogoutAutoCast(id, logout); |
| 700 | this.combatLogouts.delete(id); |
| 701 | return { ended: true, cowardice }; |
| 702 | } |
| 703 | |
| 704 | reattachCharacterSession (characterId, sessionId) |
| 705 | { |
| 706 | const entityId = this.characterEntities.get(characterId | 0); |
| 707 | if (!entityId) |
| 708 | { return null; } |
| 709 | const record = this.directory.get(entityId); |
| 710 | if (!record) |
| 711 | { return null; } |
| 712 | const result = this.workers[record.workerId].call({ |
| 713 | type: WorkerMessage.reattachSession, |
| 714 | characterId, |
| 715 | sessionId |
| 716 | }); |
| 717 | if (!result?.ok) |
| 718 | { return null; } |
| 719 | this.market?.reattachSession?.(characterId, sessionId); |
| 720 | if (this.combatLogouts.has(characterId | 0)) |
| 721 | { this.endCombatLogout(characterId, { applyCowardice: true }); } |
| 722 | return entityId; |
| 723 | } |
| 724 | |
| 725 | #ensureCombatTrack (characterId) |
| 726 | { |
| 727 | const id = characterId | 0; |
| 728 | let track = this.combatTracking.get(id); |
| 729 | if (!track) |
| 730 | { |
| 731 | track = { |
| 732 | lastCombatEndedAt: null, |
| 733 | lastOutboundAttackAt: null, |
| 734 | lastCombatActivityAt: null, |
| 735 | pvpInvolved: false, |
| 736 | wasInCombat: false |
| 737 | }; |
| 738 | this.combatTracking.set(id, track); |
| 739 | } |
| 740 | return track; |
| 741 | } |
| 742 | |
| 743 | #notePlayerAttack (characterId, targetEntityId) |
| 744 | { |
| 745 | const id = characterId | 0; |
| 746 | if (!id) |
| 747 | { return; } |
| 748 | const track = this.#ensureCombatTrack(id); |
| 749 | const now = this.now; |
| 750 | track.lastOutboundAttackAt = now; |
| 751 | track.lastCombatActivityAt = now; |
| 752 | track.wasInCombat = true; |
| 753 | const targetRecord = this.directory.get(targetEntityId); |
| 754 | if (targetRecord?.characterId) |
| 755 | { |
| 756 | track.pvpInvolved = true; |
| 757 | const logout = this.combatLogouts.get(id); |
| 758 | if (logout) |
| 759 | { logout.pendingCowardice = true; } |
| 760 | const other = this.#ensureCombatTrack(targetRecord.characterId); |
| 761 | other.pvpInvolved = true; |
| 762 | other.lastCombatActivityAt = now; |
| 763 | other.wasInCombat = true; |
| 764 | const otherLogout = this.combatLogouts.get(targetRecord.characterId | 0); |
| 765 | if (otherLogout) |
| 766 | { otherLogout.pendingCowardice = true; } |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | #noteCombatEvent (event) |
| 771 | { |
| 772 | const attackerId = event.attackerId; |
| 773 | const targetId = event.targetId; |
| 774 | const attackerRecord = attackerId != null ? this.directory.get(attackerId) : null; |
| 775 | const targetRecord = targetId != null ? this.directory.get(targetId) : null; |
| 776 | const pvp = !!(attackerRecord?.characterId && targetRecord?.characterId); |
| 777 | const now = this.now; |
| 778 | if (attackerRecord?.characterId) |
| 779 | { |
| 780 | const track = this.#ensureCombatTrack(attackerRecord.characterId); |
| 781 | track.lastOutboundAttackAt = now; |
| 782 | track.lastCombatActivityAt = now; |
| 783 | track.wasInCombat = true; |
| 784 | if (pvp) |
| 785 | { |
| 786 | track.pvpInvolved = true; |
| 787 | const logout = this.combatLogouts.get(attackerRecord.characterId | 0); |
| 788 | if (logout) |
| 789 | { logout.pendingCowardice = true; } |
| 790 | } |
| 791 | } |
| 792 | if (targetRecord?.characterId && event.type !== "combat-swing") |
| 793 | { |
| 794 | const track = this.#ensureCombatTrack(targetRecord.characterId); |
| 795 | track.lastCombatActivityAt = now; |
| 796 | track.wasInCombat = true; |
| 797 | if (pvp) |
| 798 | { |
| 799 | track.pvpInvolved = true; |
| 800 | const logout = this.combatLogouts.get(targetRecord.characterId | 0); |
| 801 | if (logout) |
| 802 | { logout.pendingCowardice = true; } |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | #characterInCombat (entityId) |
| 808 | { |
| 809 | const record = this.directory.get(entityId); |
| 810 | if (!record) |
| 811 | { return false; } |
| 812 | const state = this.workers[record.workerId].call({ |
| 813 | type: WorkerMessage.inspectCombatState, |
| 814 | entityId |
| 815 | }); |
| 816 | return !!state?.inCombat; |
| 817 | } |
| 818 | |
| 819 | #shouldStayOnLeave (characterId) |
| 820 | { |
| 821 | const id = characterId | 0; |
| 822 | const entityId = this.characterEntities.get(id); |
| 823 | if (!entityId) |
| 824 | { return false; } |
| 825 | const inCombat = this.#characterInCombat(entityId); |
| 826 | if (inCombat) |
| 827 | { return true; } |
| 828 | const track = this.combatTracking.get(id); |
| 829 | if (!track) |
| 830 | { return false; } |
| 831 | const now = this.now; |
| 832 | const endedRecently = track.lastCombatEndedAt != null |
| 833 | && (now - track.lastCombatEndedAt) <= COMBAT_LOGOUT_MS; |
| 834 | const attackedRecently = track.lastOutboundAttackAt != null |
| 835 | && (now - track.lastOutboundAttackAt) <= COMBAT_LOGOUT_MS; |
| 836 | return endedRecently && attackedRecently; |
| 837 | } |
| 838 | |
| 839 | #setCharacterAutoCast (characterId, autoCast) |
| 840 | { |
| 841 | const entityId = this.characterEntities.get(characterId | 0); |
| 842 | const record = entityId ? this.directory.get(entityId) : null; |
| 843 | if (!record) |
| 844 | { return null; } |
| 845 | return this.workers[record.workerId].call({ |
| 846 | type: WorkerMessage.setSpellAutoCast, |
| 847 | entityId, |
| 848 | autoCast: !!autoCast |
| 849 | }); |
| 850 | } |
| 851 | |
| 852 | #restoreCombatLogoutAutoCast (characterId, logout) |
| 853 | { |
| 854 | if (!logout) |
| 855 | { return; } |
| 856 | this.#setCharacterAutoCast(characterId, !!logout.savedAutoCast); |
| 857 | const stored = this.stateDb.getSpells(characterId); |
| 858 | if (stored) |
| 859 | { |
| 860 | this.stateDb.saveSpells(characterId, { |
| 861 | ...stored, |
| 862 | autoCast: !!logout.savedAutoCast |
| 863 | }); |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | #stepCombatLogout () |
| 868 | { |
| 869 | const events = []; |
| 870 | const now = this.now; |
| 871 | for (const [characterId, entityId] of this.characterEntities) |
| 872 | { |
| 873 | const inCombat = this.#characterInCombat(entityId); |
| 874 | const track = this.#ensureCombatTrack(characterId); |
| 875 | if (track.wasInCombat && !inCombat) |
| 876 | { track.lastCombatEndedAt = now; } |
| 877 | track.wasInCombat = inCombat; |
| 878 | } |
| 879 | for (const [characterId, logout] of [...this.combatLogouts.entries()]) |
| 880 | { |
| 881 | const track = this.combatTracking.get(characterId); |
| 882 | const lastActivity = track?.lastCombatActivityAt ?? logout.startedAt; |
| 883 | if ((now - lastActivity) < COMBAT_LOGOUT_MS) |
| 884 | { continue; } |
| 885 | if (logout.pendingCowardice) |
| 886 | { applyCombatLogoutCowardice(this, characterId, { now }); } |
| 887 | this.#restoreCombatLogoutAutoCast(characterId, logout); |
| 888 | this.combatLogouts.delete(characterId); |
| 889 | this.despawnCharacter(characterId); |
| 890 | } |
| 891 | return events; |
| 892 | } |
| 893 | |
| 894 | despawnCharacter (characterId) |
| 895 | { |
| 896 | this.market?.leaveExchangeStations?.(characterId); |
| 897 | const tradeEvents = this.trade?.onCharacterGone?.(characterId) ?? []; |
| 898 | if (tradeEvents.length) |
| 899 | { this.pendingPrivate.push(...tradeEvents); } |
| 900 | const entityId = this.characterEntities.get(characterId); |
| 901 | if (!entityId) |
| 902 | { |
| 903 | this.combatLogouts.delete(characterId | 0); |
| 904 | return; |
| 905 | } |
| 906 | const record = this.directory.get(entityId); |
| 907 | if (!record) |
| 908 | { |
| 909 | this.characterEntities.delete(characterId); |
| 910 | this.combatLogouts.delete(characterId | 0); |
| 911 | return; |
| 912 | } |
| 913 | this.#saveBag(entityId, record.workerId); |
| 914 | const dropped = this.workers[record.workerId].call({ |
| 915 | type: WorkerMessage.despawnCharacter, |
| 916 | characterId |
| 917 | }); |
| 918 | if (dropped) |
| 919 | { |
| 920 | this.stateDb.saveCharacterPosition( |
| 921 | characterId, |
| 922 | dropped.tileX, |
| 923 | dropped.tileY, |
| 924 | dropped.gait ?? GAIT.walk, |
| 925 | dropped.dimensionId ?? OVERWORLD_ID |
| 926 | ); |
| 927 | if (dropped.health != null) |
| 928 | { this.stateDb.saveCharacterHealth(characterId, dropped.health); } |
| 929 | this.#queueReplication(replicationDespawn(dropped)); |
| 930 | } |
| 931 | this.#forget(entityId); |
| 932 | this.combatLogouts.delete(characterId | 0); |
| 933 | this.#recalculateActivation(this.now); |
| 934 | this.#syncGhosts(); |
| 935 | } |
| 936 | |
| 937 | spawnEntity (components, options = {}) |
| 938 | { |
| 939 | const entityId = options.entityId ?? this.nextEntityId++; |
| 940 | this.nextEntityId = Math.max(this.nextEntityId, entityId + 1); |
| 941 | const position = components.position; |
| 942 | if (!position) |
| 943 | { throw new Error("spawnEntity requires position."); } |
| 944 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 945 | position.dimensionId = dimensionId; |
| 946 | if (options.requireResident) |
| 947 | { |
| 948 | const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId); |
| 949 | if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId)) |
| 950 | { return null; } |
| 951 | const view = this.workers[workerId].call({ |
| 952 | type: WorkerMessage.spawn, |
| 953 | entityId, |
| 954 | components |
| 955 | }); |
| 956 | this.#remember(view, workerId); |
| 957 | if (components.appearance) |
| 958 | { this.#queueReplication(replicationSpawn(view)); } |
| 959 | this.#syncGhosts(); |
| 960 | return entityId; |
| 961 | } |
| 962 | if (components.chunkLoader) |
| 963 | { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); } |
| 964 | else |
| 965 | { |
| 966 | this.#ensureRegion( |
| 967 | tileToRegion(position.tileX), |
| 968 | tileToRegion(position.tileY), |
| 969 | null, |
| 970 | dimensionId |
| 971 | ); |
| 972 | } |
| 973 | const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId); |
| 974 | const view = this.workers[workerId].call({ |
| 975 | type: WorkerMessage.spawn, |
| 976 | entityId, |
| 977 | components |
| 978 | }); |
| 979 | this.#remember(view, workerId); |
| 980 | if (components.appearance) |
| 981 | { this.#queueReplication(replicationSpawn(view)); } |
| 982 | this.#recalculateActivation(this.now); |
| 983 | this.#syncGhosts(); |
| 984 | return entityId; |
| 985 | } |
| 986 | |
| 987 | despawnEntity (entityId) |
| 988 | { |
| 989 | const record = this.directory.get(entityId); |
| 990 | if (!record) |
| 991 | { return; } |
| 992 | const dropped = this.workers[record.workerId].call({ |
| 993 | type: WorkerMessage.despawn, |
| 994 | entityId |
| 995 | }); |
| 996 | if (dropped) |
| 997 | { this.#queueReplication(replicationDespawn(dropped)); } |
| 998 | this.#forget(entityId); |
| 999 | } |
| 1000 | |
| 1001 | chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1002 | { |
| 1003 | const loaders = this.#allLoaders(); |
| 1004 | const { chunkSim } = accumulateLoaderRefs(loaders); |
| 1005 | return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0; |
| 1006 | } |
| 1007 | |
| 1008 | updateCourierFlight (entityId, flightPatch, now = this.now) |
| 1009 | { |
| 1010 | const record = this.directory.get(entityId); |
| 1011 | if (!record) |
| 1012 | { return { despawned: true, entityId }; } |
| 1013 | const tileX = Math.floor(flightPatch.x); |
| 1014 | const tileY = Math.floor(flightPatch.y); |
| 1015 | const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 1016 | const owner = this.#ownerOfTile(tileX, tileY, dimensionId); |
| 1017 | if (owner == null || owner !== record.workerId) |
| 1018 | { |
| 1019 | this.despawnEntity(entityId); |
| 1020 | return { despawned: true, entityId }; |
| 1021 | } |
| 1022 | const result = this.workers[owner].call({ |
| 1023 | type: WorkerMessage.updateFlight, |
| 1024 | entityId, |
| 1025 | flight: flightPatch, |
| 1026 | now |
| 1027 | }); |
| 1028 | if (result?.transferRequest) |
| 1029 | { |
| 1030 | const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]); |
| 1031 | this.#recalculateActivation(now); |
| 1032 | const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId); |
| 1033 | if (move) |
| 1034 | { |
| 1035 | this.#applyMoveToDirectory(move); |
| 1036 | return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } }; |
| 1037 | } |
| 1038 | this.despawnEntity(entityId); |
| 1039 | return { despawned: true, entityId }; |
| 1040 | } |
| 1041 | if (result?.event) |
| 1042 | { |
| 1043 | this.#applyMoveToDirectory(result.event); |
| 1044 | return { event: result.event }; |
| 1045 | } |
| 1046 | return null; |
| 1047 | } |
| 1048 | |
| 1049 | applyBag (entityId, bag) |
| 1050 | { |
| 1051 | const record = this.directory.get(entityId); |
| 1052 | if (!record) |
| 1053 | { return null; } |
| 1054 | return this.workers[record.workerId].call({ |
| 1055 | type: WorkerMessage.applyBag, |
| 1056 | entityId, |
| 1057 | bag |
| 1058 | }); |
| 1059 | } |
| 1060 | |
| 1061 | /** |
| 1062 | * Persist hair + patch live appearance; returns public view. |
| 1063 | */ |
| 1064 | setCharacterHair (characterId, hair) |
| 1065 | { |
| 1066 | const row = this.stateDb.updateCharacterHair(characterId, hair); |
| 1067 | const entityId = this.characterEntities.get(characterId); |
| 1068 | if (!entityId) |
| 1069 | { return { row, view: null }; } |
| 1070 | const fields = appearanceHairFields({ |
| 1071 | sex: row.sex, |
| 1072 | style: hair.style, |
| 1073 | hue: hair.hue, |
| 1074 | saturation: hair.saturation, |
| 1075 | darkness: hair.darkness |
| 1076 | }); |
| 1077 | const record = this.directory.get(entityId); |
| 1078 | if (!record) |
| 1079 | { return { row, view: null }; } |
| 1080 | const view = this.workers[record.workerId].call({ |
| 1081 | type: WorkerMessage.applyAppearance, |
| 1082 | entityId, |
| 1083 | appearance: fields |
| 1084 | }); |
| 1085 | if (view) |
| 1086 | { |
| 1087 | this.#remember(view, record.workerId); |
| 1088 | this.#queueReplication(replicationAppearance(view)); |
| 1089 | } |
| 1090 | return { row, view }; |
| 1091 | } |
| 1092 | |
| 1093 | pushSkills (characterId, skills, combatLevel) |
| 1094 | { |
| 1095 | this.pendingPrivate.push({ |
| 1096 | type: "skills", |
| 1097 | characterId, |
| 1098 | skills, |
| 1099 | combatLevel |
| 1100 | }); |
| 1101 | } |
| 1102 | |
| 1103 | pushSpells (characterId, payload) |
| 1104 | { |
| 1105 | this.pendingPrivate.push({ |
| 1106 | type: "spells", |
| 1107 | characterId, |
| 1108 | ...payload |
| 1109 | }); |
| 1110 | } |
| 1111 | |
| 1112 | skillsOf (entityId) |
| 1113 | { |
| 1114 | const record = this.directory.get(entityId); |
| 1115 | if (!record) |
| 1116 | { return null; } |
| 1117 | return this.workers[record.workerId].call({ |
| 1118 | type: WorkerMessage.inspectSkills, |
| 1119 | entityId |
| 1120 | }); |
| 1121 | } |
| 1122 | |
| 1123 | spellsOf (entityId) |
| 1124 | { |
| 1125 | const record = this.directory.get(entityId); |
| 1126 | if (!record) |
| 1127 | { return null; } |
| 1128 | return this.workers[record.workerId].call({ |
| 1129 | type: WorkerMessage.inspectSpells, |
| 1130 | entityId |
| 1131 | }); |
| 1132 | } |
| 1133 | |
| 1134 | staminaOf (entityId) |
| 1135 | { |
| 1136 | const record = this.directory.get(entityId); |
| 1137 | if (!record) |
| 1138 | { return null; } |
| 1139 | return this.workers[record.workerId].call({ |
| 1140 | type: WorkerMessage.inspectStamina, |
| 1141 | entityId |
| 1142 | }); |
| 1143 | } |
| 1144 | |
| 1145 | pushInventory (characterId, bag) |
| 1146 | { |
| 1147 | this.pendingPrivate.push({ |
| 1148 | type: "inventory", |
| 1149 | characterId, |
| 1150 | inventory: bag.inventory, |
| 1151 | equipment: bag.equipment, |
| 1152 | vault: bag.vault, |
| 1153 | vaultReserved: bag.vaultReserved |
| 1154 | }); |
| 1155 | } |
| 1156 | |
| 1157 | dispatchPigeon ({ characterId, destination, cargo }) |
| 1158 | { |
| 1159 | const entityId = this.characterEntities.get(characterId); |
| 1160 | const position = entityId ? this.positionOf(entityId) : null; |
| 1161 | if (!position) |
| 1162 | { |
| 1163 | const error = new Error("Enter the world before sending a pigeon."); |
| 1164 | error.userFacing = true; |
| 1165 | throw error; |
| 1166 | } |
| 1167 | return this.courier.dispatchFromPlayer({ |
| 1168 | characterId, |
| 1169 | originTileX: position.tileX, |
| 1170 | originTileY: position.tileY, |
| 1171 | destination, |
| 1172 | cargo |
| 1173 | }); |
| 1174 | } |
| 1175 | |
| 1176 | /** |
| 1177 | * Path an idle CE clerk to a staff-side station tile. |
| 1178 | */ |
| 1179 | stationExchangeClerk (stationTileX, stationTileY) |
| 1180 | { |
| 1181 | const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID); |
| 1182 | if (owner == null) |
| 1183 | { return { ok: false, reason: "unowned" }; } |
| 1184 | return this.workers[owner].call({ |
| 1185 | type: WorkerMessage.stationExchangeClerk, |
| 1186 | stationTileX, |
| 1187 | stationTileY |
| 1188 | }); |
| 1189 | } |
| 1190 | |
| 1191 | /** |
| 1192 | * When a player uses a marketplace counter, path idle CE clerks to the |
| 1193 | * opposite side of each adjacent counter (staff side). |
| 1194 | */ |
| 1195 | stationExchangeClerks (playerTileX, playerTileY) |
| 1196 | { |
| 1197 | const results = []; |
| 1198 | for (const tile of this.market?.marketTiles ?? []) |
| 1199 | { |
| 1200 | if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1) |
| 1201 | { continue; } |
| 1202 | if (tile.tileX === playerTileX && tile.tileY === playerTileY) |
| 1203 | { continue; } |
| 1204 | const stationTileX = tile.tileX + (tile.tileX - playerTileX); |
| 1205 | const stationTileY = tile.tileY + (tile.tileY - playerTileY); |
| 1206 | if (stationTileX === playerTileX && stationTileY === playerTileY) |
| 1207 | { continue; } |
| 1208 | results.push(this.stationExchangeClerk(stationTileX, stationTileY)); |
| 1209 | } |
| 1210 | return results; |
| 1211 | } |
| 1212 | |
| 1213 | /** Release a CE clerk stationed at the given staff-side tile. */ |
| 1214 | releaseExchangeClerk (stationTileX, stationTileY) |
| 1215 | { |
| 1216 | const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID); |
| 1217 | if (owner == null) |
| 1218 | { return { ok: false, reason: "unowned" }; } |
| 1219 | return this.workers[owner].call({ |
| 1220 | type: WorkerMessage.releaseExchangeClerk, |
| 1221 | stationTileX, |
| 1222 | stationTileY |
| 1223 | }); |
| 1224 | } |
| 1225 | |
| 1226 | entityForCharacter (characterId) |
| 1227 | { |
| 1228 | return this.characterEntities.get(characterId) ?? null; |
| 1229 | } |
| 1230 | |
| 1231 | entityRecord (entityId) |
| 1232 | { |
| 1233 | const record = this.directory.get(entityId); |
| 1234 | return record ? { ...record } : null; |
| 1235 | } |
| 1236 | |
| 1237 | positionOf (entityId) |
| 1238 | { |
| 1239 | const record = this.directory.get(entityId); |
| 1240 | return record |
| 1241 | ? { |
| 1242 | tileX: record.tileX, |
| 1243 | tileY: record.tileY, |
| 1244 | dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID) |
| 1245 | } |
| 1246 | : null; |
| 1247 | } |
| 1248 | |
| 1249 | bagOf (entityId) |
| 1250 | { |
| 1251 | const record = this.directory.get(entityId); |
| 1252 | if (!record) |
| 1253 | { return null; } |
| 1254 | return this.workers[record.workerId].call({ |
| 1255 | type: WorkerMessage.inspectBag, |
| 1256 | entityId |
| 1257 | }); |
| 1258 | } |
| 1259 | |
| 1260 | snapshotFor (entityId) |
| 1261 | { |
| 1262 | const record = this.directory.get(entityId); |
| 1263 | if (!record) |
| 1264 | { return []; } |
| 1265 | const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 1266 | const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS); |
| 1267 | return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId)); |
| 1268 | } |
| 1269 | |
| 1270 | /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */ |
| 1271 | snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS) |
| 1272 | { |
| 1273 | const record = this.directory.get(entityId); |
| 1274 | if (!record) |
| 1275 | { return []; } |
| 1276 | const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 1277 | const centerChunkX = tileToChunk(record.tileX); |
| 1278 | const centerChunkY = tileToChunk(record.tileY); |
| 1279 | const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0); |
| 1280 | const entityKeys = new Set( |
| 1281 | visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS) |
| 1282 | .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)) |
| 1283 | ); |
| 1284 | return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius) |
| 1285 | .map((coord) => |
| 1286 | { |
| 1287 | const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId); |
| 1288 | const staticOnly = !entityKeys.has(key); |
| 1289 | const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId); |
| 1290 | const entities = (snapshot.entities ?? []).map((entity) => |
| 1291 | { |
| 1292 | const known = this.directory.get(entity.entityId); |
| 1293 | if (!known || entity.characterId == null) |
| 1294 | { return entity; } |
| 1295 | return { ...entity, skullValue: known.skullValue | 0 }; |
| 1296 | }); |
| 1297 | return { ...snapshot, entities, staticOnly }; |
| 1298 | }); |
| 1299 | } |
| 1300 | |
| 1301 | snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID) |
| 1302 | { |
| 1303 | const dim = normalizeDimensionId(dimensionId); |
| 1304 | const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim)); |
| 1305 | if (owner == null) |
| 1306 | { return this.#syntheticSnapshot(chunkX, chunkY, dim); } |
| 1307 | return this.workers[owner].call({ |
| 1308 | type: WorkerMessage.snapshotChunk, |
| 1309 | chunkX, |
| 1310 | chunkY, |
| 1311 | dimensionId: dim, |
| 1312 | staticOnly: !!staticOnly |
| 1313 | }); |
| 1314 | } |
| 1315 | |
| 1316 | findOpenSpawn () |
| 1317 | { |
| 1318 | const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID); |
| 1319 | for (const coord of coords) |
| 1320 | { |
| 1321 | const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID); |
| 1322 | if (!data.open) |
| 1323 | { continue; } |
| 1324 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 1325 | { |
| 1326 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 1327 | { |
| 1328 | const tileX = coord.chunk_x * CHUNK_SIZE + localX; |
| 1329 | const tileY = coord.chunk_y * CHUNK_SIZE + localY; |
| 1330 | if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID)) |
| 1331 | { return { tileX, tileY, dimensionId: OVERWORLD_ID }; } |
| 1332 | } |
| 1333 | } |
| 1334 | } |
| 1335 | return null; |
| 1336 | } |
| 1337 | |
| 1338 | /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */ |
| 1339 | #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID) |
| 1340 | { |
| 1341 | const dim = normalizeDimensionId(dimensionId); |
| 1342 | return this.#findNearbyEnterable(tileX, tileY, radius, dim) |
| 1343 | ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn()); |
| 1344 | } |
| 1345 | |
| 1346 | #isDimensionUsable (dimensionId) |
| 1347 | { |
| 1348 | const dim = normalizeDimensionId(dimensionId); |
| 1349 | if (dim === OVERWORLD_ID) |
| 1350 | { return true; } |
| 1351 | const record = this.getDimensionRecord(dim); |
| 1352 | if (!record) |
| 1353 | { return false; } |
| 1354 | if (record.deletedAt != null) |
| 1355 | { return false; } |
| 1356 | if (record.purgeAfter != null && record.purgeAfter <= this.now) |
| 1357 | { return false; } |
| 1358 | return true; |
| 1359 | } |
| 1360 | |
| 1361 | #loadDimensionsCache () |
| 1362 | { |
| 1363 | const map = new Map(); |
| 1364 | for (const dim of this.worldDb.listDimensions(this.activeRevisionId)) |
| 1365 | { map.set(dim.dimensionId, dim); } |
| 1366 | if (!map.has(OVERWORLD_ID)) |
| 1367 | { |
| 1368 | map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, { |
| 1369 | defaultGroundTypeId: this.settings.defaultGroundTypeId |
| 1370 | })); |
| 1371 | } |
| 1372 | return map; |
| 1373 | } |
| 1374 | |
| 1375 | getDimensionRecord (dimensionId) |
| 1376 | { |
| 1377 | const dim = normalizeDimensionId(dimensionId); |
| 1378 | return this.dimensions?.get(dim) |
| 1379 | ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim) |
| 1380 | ?? (dim === OVERWORLD_ID |
| 1381 | ? defaultDimensionRecord(OVERWORLD_ID, { |
| 1382 | defaultGroundTypeId: this.settings.defaultGroundTypeId |
| 1383 | }) |
| 1384 | : null); |
| 1385 | } |
| 1386 | |
| 1387 | listDimensionRecords () |
| 1388 | { |
| 1389 | return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))]; |
| 1390 | } |
| 1391 | |
| 1392 | #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID) |
| 1393 | { |
| 1394 | const dim = normalizeDimensionId(dimensionId); |
| 1395 | for (let radius = 0; radius <= maxRadius; radius++) |
| 1396 | { |
| 1397 | for (let dy = -radius; dy <= radius; dy++) |
| 1398 | { |
| 1399 | for (let dx = -radius; dx <= radius; dx++) |
| 1400 | { |
| 1401 | if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 1402 | { continue; } |
| 1403 | const tileX = originX + dx; |
| 1404 | const tileY = originY + dy; |
| 1405 | if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim)) |
| 1406 | { return { tileX, tileY, dimensionId: dim }; } |
| 1407 | } |
| 1408 | } |
| 1409 | } |
| 1410 | return null; |
| 1411 | } |
| 1412 | |
| 1413 | isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1414 | { |
| 1415 | const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 1416 | if (!data.open) |
| 1417 | { return false; } |
| 1418 | return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 1419 | } |
| 1420 | |
| 1421 | debugWorld () |
| 1422 | { |
| 1423 | const loaders = this.#allLoaders(); |
| 1424 | const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); |
| 1425 | const simulatingChunks = [...chunkSim.entries()] |
| 1426 | .filter(([, count]) => count > 0) |
| 1427 | .map(([key]) => key) |
| 1428 | .sort(); |
| 1429 | return { |
| 1430 | tickIndex: this.tickIndex, |
| 1431 | workerCount: this.workers.length, |
| 1432 | workerMode: this.workerMode, |
| 1433 | simulatingChunks, |
| 1434 | regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({ |
| 1435 | ...parseRegionKey(key), |
| 1436 | workerId, |
| 1437 | state: REGION_RUNTIME_STATE.resident, |
| 1438 | refs: regionRes.get(key) ?? 0, |
| 1439 | graceUntil: this.regionGraceUntil.get(key) ?? null |
| 1440 | })), |
| 1441 | entities: [...this.directory.values()].map((entity) => ({ |
| 1442 | entityId: entity.entityId, |
| 1443 | workerId: entity.workerId, |
| 1444 | tileX: entity.tileX, |
| 1445 | tileY: entity.tileY, |
| 1446 | characterId: entity.characterId |
| 1447 | })) |
| 1448 | }; |
| 1449 | } |
| 1450 | |
| 1451 | async shutdown () |
| 1452 | { |
| 1453 | for (const characterId of [...this.characterEntities.keys()]) |
| 1454 | { this.despawnCharacter(characterId); } |
| 1455 | this.forceUnloadAll(); |
| 1456 | await Promise.all(this.workers.map((worker) => worker.terminate())); |
| 1457 | } |
| 1458 | |
| 1459 | forceUnloadAll () |
| 1460 | { |
| 1461 | for (const key of [...this.regionOwner.keys()]) |
| 1462 | { |
| 1463 | const { regionX, regionY } = parseRegionKey(key); |
| 1464 | this.#unloadRegion(regionX, regionY); |
| 1465 | } |
| 1466 | } |
| 1467 | |
| 1468 | #configureWorkers () |
| 1469 | { |
| 1470 | for (const worker of this.workers) |
| 1471 | { |
| 1472 | worker.call({ |
| 1473 | type: WorkerMessage.configure, |
| 1474 | settings: this.settings, |
| 1475 | activeRevisionId: this.activeRevisionId |
| 1476 | }); |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | #routeCommand (item) |
| 1481 | { |
| 1482 | if (item.command.type === "respawn") |
| 1483 | { return this.#respawnCharacter(item.sessionId, item.command.characterId); } |
| 1484 | const routedCharacterId = item.command.characterId | 0; |
| 1485 | if (routedCharacterId && this.stateDb.getCharacter(routedCharacterId)?.is_dead) |
| 1486 | { |
| 1487 | // Queued intents after death (drop/use/send/craft/…) are discarded. |
| 1488 | return []; |
| 1489 | } |
| 1490 | if (item.command.type === "enter-doorway") |
| 1491 | { |
| 1492 | return this.#relocateCharacterThroughDoorway( |
| 1493 | item.sessionId, |
| 1494 | item.command.characterId, |
| 1495 | item.command.tileX, |
| 1496 | item.command.tileY |
| 1497 | ); |
| 1498 | } |
| 1499 | if ( |
| 1500 | item.command.type === "open-market" |
| 1501 | || item.command.type === "place-market-sell" |
| 1502 | || item.command.type === "place-market-buy" |
| 1503 | || item.command.type === "cancel-market-order" |
| 1504 | || item.command.type === "close-market" |
| 1505 | ) |
| 1506 | { |
| 1507 | const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); |
| 1508 | return result?.events ?? []; |
| 1509 | } |
| 1510 | if ( |
| 1511 | item.command.type === "trade-request" |
| 1512 | || item.command.type === "trade-respond-invite" |
| 1513 | || item.command.type === "trade-offer-set" |
| 1514 | || item.command.type === "trade-offer-remove" |
| 1515 | || item.command.type === "trade-accept" |
| 1516 | || item.command.type === "trade-cancel" |
| 1517 | ) |
| 1518 | { |
| 1519 | const result = this.trade.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); |
| 1520 | return result?.events ?? []; |
| 1521 | } |
| 1522 | if ( |
| 1523 | item.command.type === "open-bounty" |
| 1524 | || item.command.type === "raise-bounty" |
| 1525 | || item.command.type === "pay-bounty" |
| 1526 | || item.command.type === "get-character-bounty" |
| 1527 | || item.command.type === "close-bounty" |
| 1528 | ) |
| 1529 | { |
| 1530 | const result = this.bounty.handleCommand(item.sessionId, item.command); |
| 1531 | return result?.events ?? []; |
| 1532 | } |
| 1533 | if ( |
| 1534 | item.command.type === "open-barber" |
| 1535 | || item.command.type === "set-hair" |
| 1536 | || item.command.type === "close-barber" |
| 1537 | ) |
| 1538 | { |
| 1539 | const result = this.barber.handleCommand(item.sessionId, item.command); |
| 1540 | return result?.events ?? []; |
| 1541 | } |
| 1542 | if ( |
| 1543 | item.command.type === "dialogue-choose" |
| 1544 | || item.command.type === "dialogue-advance" |
| 1545 | || item.command.type === "close-dialogue" |
| 1546 | || item.command.type === "request-quests" |
| 1547 | ) |
| 1548 | { return this.#handleQuestCommand(item); } |
| 1549 | const entityId = this.characterEntities.get(item.command.characterId); |
| 1550 | const record = entityId ? this.directory.get(entityId) : null; |
| 1551 | if (!record) |
| 1552 | { |
| 1553 | const error = new Error("Character is not in the world."); |
| 1554 | error.userFacing = true; |
| 1555 | throw error; |
| 1556 | } |
| 1557 | if (item.command.type === "drop-item" && item.command.groundItemId == null) |
| 1558 | { item.command.groundItemId = this.nextGroundItemId++; } |
| 1559 | if (item.command.type === "attack") |
| 1560 | { |
| 1561 | const targetRecord = this.directory.get(item.command.targetEntityId); |
| 1562 | if (!targetRecord) |
| 1563 | { |
| 1564 | const error = new Error("Target is not here."); |
| 1565 | error.userFacing = true; |
| 1566 | throw error; |
| 1567 | } |
| 1568 | const events = this.#finishRoutedCommand(item, record); |
| 1569 | if (targetRecord.workerId !== record.workerId) |
| 1570 | { |
| 1571 | this.workers[targetRecord.workerId].call({ |
| 1572 | type: WorkerMessage.remoteCombatEngage, |
| 1573 | attackerEntityId: record.entityId, |
| 1574 | targetEntityId: item.command.targetEntityId, |
| 1575 | now: item.receivedAt ?? this.now |
| 1576 | }); |
| 1577 | } |
| 1578 | return events; |
| 1579 | } |
| 1580 | return this.#finishRoutedCommand(item, record); |
| 1581 | } |
| 1582 | |
| 1583 | #finishRoutedCommand (item, record) |
| 1584 | { |
| 1585 | const result = this.workers[record.workerId].call({ |
| 1586 | type: WorkerMessage.command, |
| 1587 | sessionId: item.sessionId, |
| 1588 | command: item.command, |
| 1589 | now: item.receivedAt ?? this.now |
| 1590 | }); |
| 1591 | const view = this.workers[record.workerId].call({ |
| 1592 | type: WorkerMessage.inspect, |
| 1593 | entityId: record.entityId |
| 1594 | }); |
| 1595 | if (view) |
| 1596 | { this.#remember(view, record.workerId); } |
| 1597 | if (result?.private) |
| 1598 | { this.#saveBagFromView(item.command.characterId, result.private); } |
| 1599 | if (result?.appearanceChanged && view) |
| 1600 | { this.#queueReplication(replicationAppearance(view)); } |
| 1601 | if (result?.remainder) |
| 1602 | { |
| 1603 | this.stateDb.saveInheritance( |
| 1604 | this.stateDb.getCharacter(item.command.characterId).account_id, |
| 1605 | { slots: result.remainder } |
| 1606 | ); |
| 1607 | } |
| 1608 | for (const event of result?.events ?? []) |
| 1609 | { this.#persistGroundEvent(event); } |
| 1610 | const events = []; |
| 1611 | for (const event of result?.events ?? []) |
| 1612 | { |
| 1613 | if (event.type === "skills-updated") |
| 1614 | { |
| 1615 | this.#applySkillsUpdated(event); |
| 1616 | events.push(...this.#skillLevelUpEvents(event)); |
| 1617 | continue; |
| 1618 | } |
| 1619 | if (event.type === "spells-updated") |
| 1620 | { |
| 1621 | this.#applySpellsUpdated(event); |
| 1622 | continue; |
| 1623 | } |
| 1624 | if (event.type === "open-dialogue") |
| 1625 | { |
| 1626 | events.push(...this.#handleOpenDialogue(event)); |
| 1627 | continue; |
| 1628 | } |
| 1629 | if ( |
| 1630 | event.type === "combat-hit" |
| 1631 | || event.type === "combat-miss" |
| 1632 | || event.type === "combat-block" |
| 1633 | || event.type === "combat-swing" |
| 1634 | ) |
| 1635 | { this.#noteCombatEvent(event); } |
| 1636 | if (event.type === "player-died") |
| 1637 | { |
| 1638 | events.push(...this.#applyPlayerDeath(event)); |
| 1639 | continue; |
| 1640 | } |
| 1641 | events.push(event); |
| 1642 | } |
| 1643 | if (item.command.type === "attack" && item.command.targetEntityId != null) |
| 1644 | { |
| 1645 | this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); |
| 1646 | events.push(...this.#mapQuestPrivateEvents( |
| 1647 | this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? [] |
| 1648 | )); |
| 1649 | } |
| 1650 | if ( |
| 1651 | (item.command.type === "cast-spell-entity") |
| 1652 | && item.command.targetEntityId != null |
| 1653 | ) |
| 1654 | { this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); } |
| 1655 | if (result?.private) |
| 1656 | { |
| 1657 | events.push({ |
| 1658 | type: "inventory", |
| 1659 | sessionId: item.sessionId, |
| 1660 | bank: !!result.bank, |
| 1661 | cauldron: result.cauldron, |
| 1662 | cauldronState: result.cauldronState ?? null, |
| 1663 | alchemyResult: result.alchemyResult ?? null, |
| 1664 | dyeConfirm: result.dyeConfirm ?? null, |
| 1665 | ...result.private |
| 1666 | }); |
| 1667 | } |
| 1668 | if (result?.statusEffectsChanged && view) |
| 1669 | { |
| 1670 | events.push({ |
| 1671 | type: "status-effects", |
| 1672 | sessionId: item.sessionId, |
| 1673 | characterId: view.characterId ?? item.command.characterId, |
| 1674 | effects: view.statusEffects ?? [], |
| 1675 | blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind") |
| 1676 | }); |
| 1677 | } |
| 1678 | if (result?.healthChanged && view) |
| 1679 | { |
| 1680 | events.push({ |
| 1681 | type: "entity-health", |
| 1682 | entityId: view.entityId, |
| 1683 | characterId: view.characterId ?? item.command.characterId, |
| 1684 | health: view.health, |
| 1685 | maxHealth: view.maxHealth, |
| 1686 | tileX: view.tileX, |
| 1687 | tileY: view.tileY |
| 1688 | }); |
| 1689 | } |
| 1690 | return events; |
| 1691 | } |
| 1692 | |
| 1693 | #applyRemoteMelee (payload) |
| 1694 | { |
| 1695 | const targetRecord = this.directory.get(payload.targetId); |
| 1696 | if (!targetRecord) |
| 1697 | { return []; } |
| 1698 | const result = this.workers[targetRecord.workerId].call({ |
| 1699 | ...payload, |
| 1700 | type: WorkerMessage.applyRemoteMelee |
| 1701 | }); |
| 1702 | const events = []; |
| 1703 | for (const event of result?.events ?? []) |
| 1704 | { |
| 1705 | if (event.type === "entity-despawn") |
| 1706 | { this.#forget(event.entityId); } |
| 1707 | if (event.type === "skills-updated") |
| 1708 | { |
| 1709 | this.#applySkillsUpdated(event); |
| 1710 | events.push(...this.#skillLevelUpEvents(event)); |
| 1711 | continue; |
| 1712 | } |
| 1713 | if (event.type === "spells-updated") |
| 1714 | { |
| 1715 | this.#applySpellsUpdated(event); |
| 1716 | continue; |
| 1717 | } |
| 1718 | if (event.type === "player-died") |
| 1719 | { |
| 1720 | events.push(...this.#applyPlayerDeath(event)); |
| 1721 | continue; |
| 1722 | } |
| 1723 | if ( |
| 1724 | event.type === "combat-hit" |
| 1725 | || event.type === "combat-miss" |
| 1726 | || event.type === "combat-block" |
| 1727 | || event.type === "combat-swing" |
| 1728 | ) |
| 1729 | { this.#noteCombatEvent(event); } |
| 1730 | if (event.type === "mob-killed") |
| 1731 | { |
| 1732 | events.push(...this.#applyMobKilled(event)); |
| 1733 | continue; |
| 1734 | } |
| 1735 | this.#persistGroundEvent(event); |
| 1736 | if (event.type !== "skills-updated") |
| 1737 | { events.push(event); } |
| 1738 | } |
| 1739 | for (const forward of result?.forwards ?? []) |
| 1740 | { |
| 1741 | if (forward.type !== "forward-combat-xp") |
| 1742 | { continue; } |
| 1743 | const attackerRecord = this.directory.get(forward.entityId); |
| 1744 | if (!attackerRecord) |
| 1745 | { continue; } |
| 1746 | const xpResult = this.workers[attackerRecord.workerId].call({ |
| 1747 | type: WorkerMessage.applyCombatHitXp, |
| 1748 | entityId: forward.entityId, |
| 1749 | profile: forward.profile, |
| 1750 | damage: forward.damage |
| 1751 | }); |
| 1752 | for (const xpEvent of xpResult?.events ?? []) |
| 1753 | { |
| 1754 | if (xpEvent.type === "skills-updated") |
| 1755 | { |
| 1756 | this.#applySkillsUpdated(xpEvent); |
| 1757 | events.push(...this.#skillLevelUpEvents(xpEvent)); |
| 1758 | continue; |
| 1759 | } |
| 1760 | events.push(xpEvent); |
| 1761 | } |
| 1762 | } |
| 1763 | return events; |
| 1764 | } |
| 1765 | |
| 1766 | #applyRemoteRanged (payload) |
| 1767 | { |
| 1768 | const targetRecord = this.directory.get(payload.targetId); |
| 1769 | if (!targetRecord) |
| 1770 | { return []; } |
| 1771 | const result = this.workers[targetRecord.workerId].call({ |
| 1772 | ...payload, |
| 1773 | type: WorkerMessage.applyRemoteRanged |
| 1774 | }); |
| 1775 | const events = []; |
| 1776 | for (const event of result?.events ?? []) |
| 1777 | { |
| 1778 | if (event.type === "entity-despawn") |
| 1779 | { this.#forget(event.entityId); } |
| 1780 | if (event.type === "skills-updated") |
| 1781 | { |
| 1782 | this.#applySkillsUpdated(event); |
| 1783 | events.push(...this.#skillLevelUpEvents(event)); |
| 1784 | continue; |
| 1785 | } |
| 1786 | if (event.type === "spells-updated") |
| 1787 | { |
| 1788 | this.#applySpellsUpdated(event); |
| 1789 | continue; |
| 1790 | } |
| 1791 | if (event.type === "player-died") |
| 1792 | { |
| 1793 | events.push(...this.#applyPlayerDeath(event)); |
| 1794 | continue; |
| 1795 | } |
| 1796 | if ( |
| 1797 | event.type === "combat-hit" |
| 1798 | || event.type === "combat-miss" |
| 1799 | || event.type === "combat-block" |
| 1800 | || event.type === "combat-swing" |
| 1801 | ) |
| 1802 | { this.#noteCombatEvent(event); } |
| 1803 | if (event.type === "mob-killed") |
| 1804 | { |
| 1805 | events.push(...this.#applyMobKilled(event)); |
| 1806 | continue; |
| 1807 | } |
| 1808 | this.#persistGroundEvent(event); |
| 1809 | if (event.type !== "skills-updated") |
| 1810 | { events.push(event); } |
| 1811 | } |
| 1812 | for (const forward of result?.forwards ?? []) |
| 1813 | { |
| 1814 | if (forward.type !== "forward-combat-xp") |
| 1815 | { continue; } |
| 1816 | const attackerRecord = this.directory.get(forward.entityId); |
| 1817 | if (!attackerRecord) |
| 1818 | { continue; } |
| 1819 | const xpResult = this.workers[attackerRecord.workerId].call({ |
| 1820 | type: WorkerMessage.applyCombatHitXp, |
| 1821 | entityId: forward.entityId, |
| 1822 | profile: forward.profile, |
| 1823 | damage: forward.damage |
| 1824 | }); |
| 1825 | for (const xpEvent of xpResult?.events ?? []) |
| 1826 | { |
| 1827 | if (xpEvent.type === "skills-updated") |
| 1828 | { |
| 1829 | this.#applySkillsUpdated(xpEvent); |
| 1830 | events.push(...this.#skillLevelUpEvents(xpEvent)); |
| 1831 | continue; |
| 1832 | } |
| 1833 | events.push(xpEvent); |
| 1834 | } |
| 1835 | } |
| 1836 | return events; |
| 1837 | } |
| 1838 | |
| 1839 | #handleQuestCommand (item) |
| 1840 | { |
| 1841 | const characterId = item.command.characterId | 0; |
| 1842 | const sessionId = item.sessionId; |
| 1843 | if (!this.quests) |
| 1844 | { return []; } |
| 1845 | if (item.command.type === "request-quests") |
| 1846 | { |
| 1847 | const snap = this.quests.questSnapshot(characterId); |
| 1848 | return [{ type: "quests-snapshot", sessionId, characterId, ...snap }]; |
| 1849 | } |
| 1850 | if (item.command.type === "close-dialogue") |
| 1851 | { |
| 1852 | const closed = this.quests.closeDialogue(characterId, "client"); |
| 1853 | return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId); |
| 1854 | } |
| 1855 | if (item.command.type === "dialogue-choose") |
| 1856 | { |
| 1857 | const result = this.quests.chooseDialogue(characterId, item.command.trigger); |
| 1858 | if (!result.ok) |
| 1859 | { |
| 1860 | const error = new Error(result.error || "Choice failed."); |
| 1861 | error.userFacing = true; |
| 1862 | throw error; |
| 1863 | } |
| 1864 | return this.#mapQuestPrivateEvents(result.events, sessionId, characterId); |
| 1865 | } |
| 1866 | if (item.command.type === "dialogue-advance") |
| 1867 | { |
| 1868 | const result = this.quests.advanceDialogue(characterId); |
| 1869 | if (!result.ok) |
| 1870 | { |
| 1871 | const error = new Error(result.error || "Cannot advance."); |
| 1872 | error.userFacing = true; |
| 1873 | throw error; |
| 1874 | } |
| 1875 | return this.#mapQuestPrivateEvents(result.events, sessionId, characterId); |
| 1876 | } |
| 1877 | return []; |
| 1878 | } |
| 1879 | |
| 1880 | #handleOpenDialogue (event) |
| 1881 | { |
| 1882 | const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId); |
| 1883 | if (!result.ok) |
| 1884 | { |
| 1885 | return [{ |
| 1886 | type: "toast", |
| 1887 | characterId: event.characterId, |
| 1888 | sessionId: event.sessionId, |
| 1889 | message: result.error || "Nothing to say." |
| 1890 | }]; |
| 1891 | } |
| 1892 | this.#pinDialogueNpc(event.entityId, event.characterId); |
| 1893 | return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId); |
| 1894 | } |
| 1895 | |
| 1896 | #pinDialogueNpc (entityId, characterId) |
| 1897 | { |
| 1898 | const record = this.directory.get(entityId | 0); |
| 1899 | if (!record) |
| 1900 | { return; } |
| 1901 | this.workers[record.workerId]?.call?.({ |
| 1902 | type: WorkerMessage.pinDialogue, |
| 1903 | entityId: entityId | 0, |
| 1904 | characterId: characterId | 0 |
| 1905 | }); |
| 1906 | } |
| 1907 | |
| 1908 | #unpinDialogueNpc (entityId, characterId) |
| 1909 | { |
| 1910 | const record = this.directory.get(entityId | 0); |
| 1911 | if (!record) |
| 1912 | { return; } |
| 1913 | this.workers[record.workerId]?.call?.({ |
| 1914 | type: WorkerMessage.unpinDialogue, |
| 1915 | entityId: entityId | 0, |
| 1916 | characterId: characterId | 0 |
| 1917 | }); |
| 1918 | } |
| 1919 | |
| 1920 | #mapQuestPrivateEvents (events, sessionId = null, characterId = null) |
| 1921 | { |
| 1922 | const out = []; |
| 1923 | let needSnapshot = false; |
| 1924 | const syncAccessIds = new Set(); |
| 1925 | for (const event of events ?? []) |
| 1926 | { |
| 1927 | const cid = event.characterId ?? characterId; |
| 1928 | const sid = sessionId ?? this.#sessionIdForCharacter(cid); |
| 1929 | if (event.type === "dialogueStep") |
| 1930 | { |
| 1931 | if (cid != null) |
| 1932 | { syncAccessIds.add(cid | 0); } |
| 1933 | out.push({ |
| 1934 | type: "dialogue-step", |
| 1935 | sessionId: sid, |
| 1936 | characterId: cid, |
| 1937 | dialogueId: event.dialogueId, |
| 1938 | stepId: event.stepId, |
| 1939 | label: event.label, |
| 1940 | npcEntityId: event.npcEntityId, |
| 1941 | lines: event.lines |
| 1942 | }); |
| 1943 | } |
| 1944 | else if (event.type === "dialogueChoices") |
| 1945 | { |
| 1946 | if (cid != null) |
| 1947 | { syncAccessIds.add(cid | 0); } |
| 1948 | out.push({ |
| 1949 | type: "dialogue-choices", |
| 1950 | sessionId: sid, |
| 1951 | characterId: cid, |
| 1952 | dialogueId: event.dialogueId, |
| 1953 | stepId: event.stepId, |
| 1954 | npcEntityId: event.npcEntityId, |
| 1955 | triggers: event.triggers |
| 1956 | }); |
| 1957 | } |
| 1958 | else if (event.type === "dialogueItemRewards") |
| 1959 | { |
| 1960 | out.push({ |
| 1961 | type: "dialogue-item-rewards", |
| 1962 | sessionId: sid, |
| 1963 | characterId: cid, |
| 1964 | dialogueId: event.dialogueId, |
| 1965 | stepId: event.stepId, |
| 1966 | npcEntityId: event.npcEntityId, |
| 1967 | messages: event.messages ?? [] |
| 1968 | }); |
| 1969 | } |
| 1970 | else if (event.type === "dialogueClose") |
| 1971 | { |
| 1972 | if (event.npcEntityId != null && cid != null) |
| 1973 | { this.#unpinDialogueNpc(event.npcEntityId, cid); } |
| 1974 | out.push({ |
| 1975 | type: "dialogue-close", |
| 1976 | sessionId: sid, |
| 1977 | characterId: cid, |
| 1978 | reason: event.reason |
| 1979 | }); |
| 1980 | } |
| 1981 | else if (event.type === "questStepComplete") |
| 1982 | { |
| 1983 | out.push({ |
| 1984 | type: "quest-step-complete", |
| 1985 | sessionId: sid, |
| 1986 | characterId: cid, |
| 1987 | questId: event.questId, |
| 1988 | title: event.title |
| 1989 | }); |
| 1990 | needSnapshot = true; |
| 1991 | } |
| 1992 | else if (event.type === "questsDirty") |
| 1993 | { needSnapshot = true; } |
| 1994 | else if (event.type === "inventoryDirty" && cid != null) |
| 1995 | { |
| 1996 | const onlineId = this.characterEntities.get(cid | 0); |
| 1997 | if (onlineId) |
| 1998 | { |
| 1999 | const live = this.bagOf(onlineId); |
| 2000 | if (live) |
| 2001 | { this.pushInventory(cid, live); } |
| 2002 | } |
| 2003 | } |
| 2004 | } |
| 2005 | if (needSnapshot && characterId != null) |
| 2006 | { |
| 2007 | const snap = this.quests.questSnapshot(characterId); |
| 2008 | out.push({ |
| 2009 | type: "quests-snapshot", |
| 2010 | sessionId: sessionId ?? this.#sessionIdForCharacter(characterId), |
| 2011 | characterId, |
| 2012 | ...snap |
| 2013 | }); |
| 2014 | syncAccessIds.add(characterId | 0); |
| 2015 | } |
| 2016 | for (const id of syncAccessIds) |
| 2017 | { this.syncCharacterConditionAccess(id); } |
| 2018 | return out; |
| 2019 | } |
| 2020 | |
| 2021 | #sessionIdForCharacter (characterId) |
| 2022 | { |
| 2023 | const entityId = this.characterEntities.get(characterId | 0); |
| 2024 | const record = entityId != null ? this.directory.get(entityId) : null; |
| 2025 | return record?.sessionId ?? null; |
| 2026 | } |
| 2027 | |
| 2028 | #applyMobKilled (event) |
| 2029 | { |
| 2030 | const out = [event]; |
| 2031 | const attackerRecord = this.directory.get(event.attackerId); |
| 2032 | const killerCharacterId = attackerRecord?.characterId ?? null; |
| 2033 | const killerPos = attackerRecord |
| 2034 | ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY } |
| 2035 | : null; |
| 2036 | if (killerCharacterId && this.quests) |
| 2037 | { |
| 2038 | out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, { |
| 2039 | mobTypeId: event.mobTypeId, |
| 2040 | spawnerId: event.spawnerId |
| 2041 | }))); |
| 2042 | } |
| 2043 | out.push(...this.#mapQuestPrivateEvents( |
| 2044 | this.quests?.interruptDialogueForEntity(event.entityId) ?? [] |
| 2045 | )); |
| 2046 | let bountyAwarded = 0; |
| 2047 | if (killerCharacterId && (event.bounty | 0) > 0) |
| 2048 | { |
| 2049 | bountyAwarded = event.bounty | 0; |
| 2050 | const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded); |
| 2051 | this.refreshCharacterSkull(killerCharacterId); |
| 2052 | out.push({ |
| 2053 | type: "toast", |
| 2054 | characterId: killerCharacterId, |
| 2055 | message: `Bounty +${bountyAwarded} (total ${total})` |
| 2056 | }); |
| 2057 | } |
| 2058 | |
| 2059 | if (killerCharacterId && killerPos) |
| 2060 | { |
| 2061 | if (bountyAwarded > 0) |
| 2062 | { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); } |
| 2063 | if (event.townGuard) |
| 2064 | { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); } |
| 2065 | } |
| 2066 | return out; |
| 2067 | } |
| 2068 | |
| 2069 | /** |
| 2070 | * Send up to `count` town guards at the killer. Prefer idle guards. |
| 2071 | * When `spawnerId` is set, only that spawner's guards are used. |
| 2072 | */ |
| 2073 | #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count) |
| 2074 | { |
| 2075 | const want = Math.max(0, count | 0); |
| 2076 | if (want <= 0 || targetEntityId == null || !killerPos) |
| 2077 | { return; } |
| 2078 | const candidates = []; |
| 2079 | for (const worker of this.workers) |
| 2080 | { |
| 2081 | const result = worker.call({ |
| 2082 | type: WorkerMessage.listTownGuardsNear, |
| 2083 | tileX: killerPos.tileX, |
| 2084 | tileY: killerPos.tileY, |
| 2085 | spawnerId, |
| 2086 | limit: 32 |
| 2087 | }); |
| 2088 | for (const guard of result?.guards ?? []) |
| 2089 | { candidates.push(guard); } |
| 2090 | } |
| 2091 | candidates.sort((a, b) => Number(a.busy) - Number(b.busy)); |
| 2092 | let sent = 0; |
| 2093 | for (const guard of candidates) |
| 2094 | { |
| 2095 | if (sent >= want) |
| 2096 | { break; } |
| 2097 | if (guard.entityId === targetEntityId) |
| 2098 | { continue; } |
| 2099 | const record = this.directory.get(guard.entityId); |
| 2100 | if (!record) |
| 2101 | { continue; } |
| 2102 | this.workers[record.workerId].call({ |
| 2103 | type: WorkerMessage.engageTarget, |
| 2104 | attackerEntityId: guard.entityId, |
| 2105 | targetEntityId, |
| 2106 | now: this.now |
| 2107 | }); |
| 2108 | sent += 1; |
| 2109 | } |
| 2110 | } |
| 2111 | |
| 2112 | #applyPlayerDeath (event) |
| 2113 | { |
| 2114 | const record = this.directory.get(event.entityId); |
| 2115 | if (!record) |
| 2116 | { return [event]; } |
| 2117 | this.stateDb.setCharacterDead(event.characterId, true); |
| 2118 | this.stateDb.saveCharacterPosition( |
| 2119 | event.characterId, |
| 2120 | event.tileX, |
| 2121 | event.tileY, |
| 2122 | record.gait ?? GAIT.walk, |
| 2123 | record.dimensionId ?? OVERWORLD_ID |
| 2124 | ); |
| 2125 | this.bounty?.settleKill( |
| 2126 | event.characterId, |
| 2127 | event.attackerId, |
| 2128 | event.tileX, |
| 2129 | event.tileY |
| 2130 | ); |
| 2131 | const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null; |
| 2132 | const killerCharacterId = Number(attackerRecord?.characterId) || 0; |
| 2133 | if (killerCharacterId && killerCharacterId !== (event.characterId | 0)) |
| 2134 | { this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now); } |
| 2135 | const events = [event]; |
| 2136 | const closedDialogue = this.quests?.closeDialogue(event.characterId, "death"); |
| 2137 | if (closedDialogue?.events?.length) |
| 2138 | { |
| 2139 | events.push(...this.#mapQuestPrivateEvents( |
| 2140 | closedDialogue.events, |
| 2141 | event.sessionId, |
| 2142 | event.characterId |
| 2143 | )); |
| 2144 | } |
| 2145 | if (event.sessionId != null) |
| 2146 | { |
| 2147 | for (const commandType of ["cancel-craft", "cauldron-close"]) |
| 2148 | { |
| 2149 | try |
| 2150 | { |
| 2151 | this.workers[record.workerId].call({ |
| 2152 | type: WorkerMessage.command, |
| 2153 | sessionId: event.sessionId, |
| 2154 | command: { type: commandType, characterId: event.characterId }, |
| 2155 | now: this.now |
| 2156 | }); |
| 2157 | } |
| 2158 | catch |
| 2159 | { /* best-effort session cleanup */ } |
| 2160 | } |
| 2161 | } |
| 2162 | // Bounty is cleared instantly on non-friend PvP death; only kill-counter decays over time. |
| 2163 | const victimSkull = this.refreshCharacterSkull(event.characterId, { force: true }); |
| 2164 | if (victimSkull) |
| 2165 | { events.push(victimSkull); } |
| 2166 | for (const worker of this.workers) |
| 2167 | { |
| 2168 | worker.call({ |
| 2169 | type: WorkerMessage.clearCombat, |
| 2170 | entityId: event.entityId, |
| 2171 | targetEntityId: event.entityId |
| 2172 | }); |
| 2173 | } |
| 2174 | const victimName = `${record.firstName ?? "someone"} ${record.lastName ?? ""}`.trim() |
| 2175 | || "someone"; |
| 2176 | const killerName = `${attackerRecord?.firstName ?? ""} ${attackerRecord?.lastName ?? ""}`.trim() |
| 2177 | || "someone"; |
| 2178 | const corpseOrigin = lootOrigin(victimName, killerName); |
| 2179 | const result = this.workers[record.workerId].call({ |
| 2180 | type: WorkerMessage.spawnCorpseDrops, |
| 2181 | characterId: event.characterId, |
| 2182 | tileX: event.tileX, |
| 2183 | tileY: event.tileY, |
| 2184 | now: this.now, |
| 2185 | dropCarriedCoins: true, |
| 2186 | coinGroundItemId: this.nextGroundItemId++, |
| 2187 | drops: [ |
| 2188 | { |
| 2189 | groundItemId: this.nextGroundItemId++, |
| 2190 | stack: attachOrigins({ |
| 2191 | itemId: ItemId.bones, |
| 2192 | quantity: 1, |
| 2193 | origins: [{ origin: corpseOrigin, quantity: 1 }] |
| 2194 | }) |
| 2195 | }, |
| 2196 | { |
| 2197 | groundItemId: this.nextGroundItemId++, |
| 2198 | stack: attachOrigins({ |
| 2199 | itemId: ItemId.skull, |
| 2200 | quantity: 1, |
| 2201 | origins: [{ origin: corpseOrigin, quantity: 1 }] |
| 2202 | }) |
| 2203 | } |
| 2204 | ] |
| 2205 | }); |
| 2206 | if (killerCharacterId && killerCharacterId !== (event.characterId | 0)) |
| 2207 | { |
| 2208 | const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true }); |
| 2209 | if (skullEvent) |
| 2210 | { events.push(skullEvent); } |
| 2211 | } |
| 2212 | events.push({ |
| 2213 | type: "entity-despawn", |
| 2214 | entityId: event.entityId, |
| 2215 | tileX: event.tileX, |
| 2216 | tileY: event.tileY, |
| 2217 | cause: "death" |
| 2218 | }); |
| 2219 | for (const dropEvent of result?.events ?? []) |
| 2220 | { |
| 2221 | this.#persistGroundEvent(dropEvent); |
| 2222 | events.push(dropEvent); |
| 2223 | } |
| 2224 | if (result?.private) |
| 2225 | { |
| 2226 | this.#saveBagFromView(event.characterId, result.private); |
| 2227 | if (event.sessionId != null) |
| 2228 | { |
| 2229 | events.push({ |
| 2230 | type: "inventory", |
| 2231 | sessionId: event.sessionId, |
| 2232 | ...result.private |
| 2233 | }); |
| 2234 | } |
| 2235 | } |
| 2236 | const coinsDropped = coinsDroppedFromDeathEvents(events); |
| 2237 | if (this.combatLogouts.has(event.characterId | 0)) |
| 2238 | { events.push(...this.#finishCombatLogoutDeath(event, coinsDropped)); } |
| 2239 | return events; |
| 2240 | } |
| 2241 | |
| 2242 | #finishCombatLogoutDeath (event, coinsDropped) |
| 2243 | { |
| 2244 | const characterId = event.characterId | 0; |
| 2245 | const logout = this.combatLogouts.get(characterId); |
| 2246 | const events = []; |
| 2247 | if (logout?.pendingCowardice) |
| 2248 | { |
| 2249 | applyCombatLogoutCowardice(this, characterId, { |
| 2250 | coinsDropped, |
| 2251 | now: this.now |
| 2252 | }); |
| 2253 | } |
| 2254 | dispatchChurchOfflineResurrectionLetter( |
| 2255 | this, |
| 2256 | characterId, |
| 2257 | event.tileX | 0, |
| 2258 | event.tileY | 0 |
| 2259 | ); |
| 2260 | try |
| 2261 | { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); } |
| 2262 | catch |
| 2263 | { |
| 2264 | // Respawn can fail without an altar tile; still despawn the corpse session. |
| 2265 | } |
| 2266 | this.#restoreCombatLogoutAutoCast(characterId, logout); |
| 2267 | this.combatLogouts.delete(characterId); |
| 2268 | this.combatTracking.delete(characterId); |
| 2269 | this.despawnCharacter(characterId); |
| 2270 | return events; |
| 2271 | } |
| 2272 | |
| 2273 | #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY) |
| 2274 | { |
| 2275 | const entityId = this.characterEntities.get(characterId); |
| 2276 | const record = entityId ? this.directory.get(entityId) : null; |
| 2277 | if (!record) |
| 2278 | { |
| 2279 | const error = new Error("Character is not in the world."); |
| 2280 | error.userFacing = true; |
| 2281 | throw error; |
| 2282 | } |
| 2283 | const tileX = doorwayTileX | 0; |
| 2284 | const tileY = doorwayTileY | 0; |
| 2285 | if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY)) |
| 2286 | { |
| 2287 | const error = new Error("You are too far from that doorway."); |
| 2288 | error.userFacing = true; |
| 2289 | throw error; |
| 2290 | } |
| 2291 | const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 2292 | const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId); |
| 2293 | const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)]; |
| 2294 | if (block?.typeId !== BlockType.doorway) |
| 2295 | { |
| 2296 | const error = new Error("There is no doorway there."); |
| 2297 | error.userFacing = true; |
| 2298 | throw error; |
| 2299 | } |
| 2300 | const config = block.config && typeof block.config === "object" ? block.config : null; |
| 2301 | const targetRaw = config?.targetDimensionId; |
| 2302 | if (targetRaw == null || String(targetRaw).trim() === "") |
| 2303 | { |
| 2304 | const error = new Error("That doorway leads nowhere."); |
| 2305 | error.userFacing = true; |
| 2306 | throw error; |
| 2307 | } |
| 2308 | const targetDimensionId = normalizeDimensionId(targetRaw); |
| 2309 | const destTileX = Number(config.tileX); |
| 2310 | const destTileY = Number(config.tileY); |
| 2311 | if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY)) |
| 2312 | { |
| 2313 | const error = new Error("That doorway leads nowhere."); |
| 2314 | error.userFacing = true; |
| 2315 | throw error; |
| 2316 | } |
| 2317 | const destX = destTileX | 0; |
| 2318 | const destY = destTileY | 0; |
| 2319 | if (!this.#isDimensionUsable(targetDimensionId)) |
| 2320 | { |
| 2321 | const error = new Error("That place is no longer reachable."); |
| 2322 | error.userFacing = true; |
| 2323 | throw error; |
| 2324 | } |
| 2325 | if (!this.isEnterable(destX, destY, targetDimensionId)) |
| 2326 | { |
| 2327 | const error = new Error("The other side is blocked."); |
| 2328 | error.userFacing = true; |
| 2329 | throw error; |
| 2330 | } |
| 2331 | |
| 2332 | const events = []; |
| 2333 | if (this.quests) |
| 2334 | { |
| 2335 | const closed = this.quests.closeDialogue(characterId, "doorway"); |
| 2336 | if (closed?.events?.length) |
| 2337 | { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); } |
| 2338 | } |
| 2339 | |
| 2340 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 2341 | this.#ensureCoverage(destX, destY, loader, targetDimensionId); |
| 2342 | const result = this.workers[record.workerId].call({ |
| 2343 | type: WorkerMessage.relocateEntity, |
| 2344 | entityId, |
| 2345 | tileX: destX, |
| 2346 | tileY: destY, |
| 2347 | dimensionId: targetDimensionId |
| 2348 | }); |
| 2349 | if (!result?.accepted) |
| 2350 | { |
| 2351 | const error = new Error("Could not enter that doorway."); |
| 2352 | error.userFacing = true; |
| 2353 | throw error; |
| 2354 | } |
| 2355 | let moveEvents = []; |
| 2356 | if (result.transferRequest) |
| 2357 | { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } |
| 2358 | else if (result.event) |
| 2359 | { |
| 2360 | this.#applyMoveToDirectory(result.event); |
| 2361 | moveEvents = [result.event]; |
| 2362 | const view = this.workers[record.workerId].call({ |
| 2363 | type: WorkerMessage.inspect, |
| 2364 | entityId |
| 2365 | }); |
| 2366 | if (view) |
| 2367 | { this.#remember(view, record.workerId); } |
| 2368 | } |
| 2369 | if (!moveEvents.length) |
| 2370 | { |
| 2371 | const error = new Error("Could not enter that doorway."); |
| 2372 | error.userFacing = true; |
| 2373 | throw error; |
| 2374 | } |
| 2375 | this.stateDb.saveCharacterPosition( |
| 2376 | characterId, |
| 2377 | destX, |
| 2378 | destY, |
| 2379 | record.gait ?? GAIT.walk, |
| 2380 | targetDimensionId |
| 2381 | ); |
| 2382 | this.stateDb.markDimensionVisited(characterId, targetDimensionId); |
| 2383 | this.syncCharacterConditionAccess(characterId); |
| 2384 | this.#recalculateActivation(this.now); |
| 2385 | this.#syncGhosts(); |
| 2386 | const dimRecord = this.getDimensionRecord(targetDimensionId); |
| 2387 | events.push(...moveEvents, { |
| 2388 | type: "dimension-changed", |
| 2389 | sessionId, |
| 2390 | characterId, |
| 2391 | entityId, |
| 2392 | dimensionId: targetDimensionId, |
| 2393 | tileX: destX, |
| 2394 | tileY: destY, |
| 2395 | lightingMode: dimRecord?.lightingMode ?? "dayNight", |
| 2396 | seasonMode: dimRecord?.seasonMode ?? "auto" |
| 2397 | }); |
| 2398 | return events; |
| 2399 | } |
| 2400 | |
| 2401 | #respawnCharacter (sessionId, characterId) |
| 2402 | { |
| 2403 | const row = this.stateDb.getCharacter(characterId); |
| 2404 | if (!row?.is_dead) |
| 2405 | { |
| 2406 | const error = new Error("You are not dead."); |
| 2407 | error.userFacing = true; |
| 2408 | throw error; |
| 2409 | } |
| 2410 | const entityId = this.characterEntities.get(characterId); |
| 2411 | const record = entityId ? this.directory.get(entityId) : null; |
| 2412 | if (!record) |
| 2413 | { |
| 2414 | const error = new Error("Character is not in the world."); |
| 2415 | error.userFacing = true; |
| 2416 | throw error; |
| 2417 | } |
| 2418 | const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId); |
| 2419 | if (!destination) |
| 2420 | { |
| 2421 | const error = new Error("No open tile is available for respawn."); |
| 2422 | error.userFacing = true; |
| 2423 | throw error; |
| 2424 | } |
| 2425 | const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills(); |
| 2426 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 2427 | this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID); |
| 2428 | const result = this.workers[record.workerId].call({ |
| 2429 | type: WorkerMessage.applyRespawn, |
| 2430 | entityId, |
| 2431 | sessionId, |
| 2432 | tileX: destination.tileX, |
| 2433 | tileY: destination.tileY, |
| 2434 | maxHealth: playerMaxHealth(skills), |
| 2435 | maxStamina: playerMaxStamina(skills) |
| 2436 | }); |
| 2437 | if (!result?.accepted) |
| 2438 | { |
| 2439 | const error = new Error("That respawn tile is no longer available."); |
| 2440 | error.userFacing = true; |
| 2441 | throw error; |
| 2442 | } |
| 2443 | let moveEvents = []; |
| 2444 | if (result.transferRequest) |
| 2445 | { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); } |
| 2446 | else if (result.event) |
| 2447 | { |
| 2448 | this.#applyMoveToDirectory(result.event); |
| 2449 | moveEvents = [result.event]; |
| 2450 | const view = this.workers[record.workerId].call({ |
| 2451 | type: WorkerMessage.inspect, |
| 2452 | entityId |
| 2453 | }); |
| 2454 | if (view) |
| 2455 | { this.#remember(view, record.workerId); } |
| 2456 | } |
| 2457 | if (!moveEvents.length) |
| 2458 | { |
| 2459 | const error = new Error("Respawn transfer failed."); |
| 2460 | error.userFacing = true; |
| 2461 | throw error; |
| 2462 | } |
| 2463 | this.stateDb.setCharacterDead(characterId, false); |
| 2464 | const respawnHealth = playerMaxHealth(skills); |
| 2465 | this.stateDb.saveCharacterHealth(characterId, respawnHealth); |
| 2466 | this.stateDb.saveCharacterPosition( |
| 2467 | characterId, |
| 2468 | destination.tileX, |
| 2469 | destination.tileY, |
| 2470 | record.gait ?? GAIT.walk, |
| 2471 | destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID |
| 2472 | ); |
| 2473 | this.#recalculateActivation(this.now); |
| 2474 | this.#syncGhosts(); |
| 2475 | const skullEvent = this.refreshCharacterSkull(characterId, { force: true }); |
| 2476 | const skullPoints = this.directory.get(entityId)?.skullValue | 0; |
| 2477 | const spawnView = this.workers[record.workerId].call({ |
| 2478 | type: WorkerMessage.inspect, |
| 2479 | entityId |
| 2480 | }); |
| 2481 | const spawn = spawnView |
| 2482 | ? replicationSpawn({ ...spawnView, skullValue: skullPoints }) |
| 2483 | : null; |
| 2484 | return [ |
| 2485 | ...moveEvents, |
| 2486 | ...(spawn ? [spawn] : []), |
| 2487 | ...(skullEvent ? [skullEvent] : []), |
| 2488 | { |
| 2489 | type: "player-respawned", |
| 2490 | entityId, |
| 2491 | characterId, |
| 2492 | sessionId, |
| 2493 | tileX: destination.tileX, |
| 2494 | tileY: destination.tileY, |
| 2495 | health: playerMaxHealth(skills), |
| 2496 | maxHealth: playerMaxHealth(skills), |
| 2497 | stamina: playerMaxStamina(skills), |
| 2498 | maxStamina: playerMaxStamina(skills), |
| 2499 | skullValue: skullPoints |
| 2500 | } |
| 2501 | ]; |
| 2502 | } |
| 2503 | |
| 2504 | #refreshAltarIndex () |
| 2505 | { |
| 2506 | const altars = []; |
| 2507 | for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId)) |
| 2508 | { |
| 2509 | const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID); |
| 2510 | const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim); |
| 2511 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 2512 | { |
| 2513 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 2514 | { |
| 2515 | const block = data.blocks[localY * CHUNK_SIZE + localX]; |
| 2516 | if (block?.typeId !== BlockType.churchAltar) |
| 2517 | { continue; } |
| 2518 | altars.push({ |
| 2519 | tileX: coord.chunk_x * CHUNK_SIZE + localX, |
| 2520 | tileY: coord.chunk_y * CHUNK_SIZE + localY, |
| 2521 | dimensionId: dim |
| 2522 | }); |
| 2523 | } |
| 2524 | } |
| 2525 | } |
| 2526 | this.altarTiles = altars; |
| 2527 | } |
| 2528 | |
| 2529 | #findRespawnDestination (originX, originY, entityId) |
| 2530 | { |
| 2531 | const record = this.directory.get(entityId); |
| 2532 | const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID); |
| 2533 | const ordered = [...this.altarTiles].sort((left, right) => |
| 2534 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 2535 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 2536 | ); |
| 2537 | for (const altar of ordered) |
| 2538 | { |
| 2539 | const adjacent = []; |
| 2540 | for (let dy = -1; dy <= 1; dy++) |
| 2541 | { |
| 2542 | for (let dx = -1; dx <= 1; dx++) |
| 2543 | { |
| 2544 | if (dx === 0 && dy === 0) |
| 2545 | { continue; } |
| 2546 | adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId }); |
| 2547 | } |
| 2548 | } |
| 2549 | adjacent.sort((left, right) => |
| 2550 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 2551 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 2552 | ); |
| 2553 | const tile = adjacent.find((entry) => |
| 2554 | this.isEnterable(entry.tileX, entry.tileY, dimensionId) |
| 2555 | && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId) |
| 2556 | ); |
| 2557 | if (tile) |
| 2558 | { return tile; } |
| 2559 | } |
| 2560 | for (let radius = 0; radius <= 24; radius++) |
| 2561 | { |
| 2562 | for (let dy = -radius; dy <= radius; dy++) |
| 2563 | { |
| 2564 | for (let dx = -radius; dx <= radius; dx++) |
| 2565 | { |
| 2566 | if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 2567 | { continue; } |
| 2568 | const tileX = originX + dx; |
| 2569 | const tileY = originY + dy; |
| 2570 | if (this.isEnterable(tileX, tileY, dimensionId) |
| 2571 | && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId)) |
| 2572 | { return { tileX, tileY, dimensionId }; } |
| 2573 | } |
| 2574 | } |
| 2575 | } |
| 2576 | return this.findOpenSpawn(); |
| 2577 | } |
| 2578 | |
| 2579 | #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID) |
| 2580 | { |
| 2581 | const dim = normalizeDimensionId(dimensionId); |
| 2582 | for (const record of this.directory.values()) |
| 2583 | { |
| 2584 | const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 2585 | if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim) |
| 2586 | { return true; } |
| 2587 | } |
| 2588 | return false; |
| 2589 | } |
| 2590 | |
| 2591 | #recalculateActivation (now) |
| 2592 | { |
| 2593 | const loaders = this.#allLoaders(); |
| 2594 | const { chunkSim, regionRes } = accumulateLoaderRefs(loaders); |
| 2595 | |
| 2596 | for (const [key, count] of regionRes) |
| 2597 | { |
| 2598 | if (count <= 0) |
| 2599 | { continue; } |
| 2600 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 2601 | this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId); |
| 2602 | this.regionGraceUntil.delete(key); |
| 2603 | } |
| 2604 | |
| 2605 | for (const [key] of [...this.regionOwner.entries()]) |
| 2606 | { |
| 2607 | if ((regionRes.get(key) ?? 0) > 0) |
| 2608 | { continue; } |
| 2609 | if (!this.regionGraceUntil.has(key)) |
| 2610 | { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); } |
| 2611 | if (now >= this.regionGraceUntil.get(key)) |
| 2612 | { |
| 2613 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 2614 | this.#unloadRegion(regionX, regionY, dimensionId); |
| 2615 | } |
| 2616 | } |
| 2617 | |
| 2618 | for (const [workerId, worker] of this.workers.entries()) |
| 2619 | { |
| 2620 | const chunkKeys = []; |
| 2621 | for (const [key, count] of chunkSim) |
| 2622 | { |
| 2623 | if (count <= 0) |
| 2624 | { continue; } |
| 2625 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 2626 | if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId) |
| 2627 | { chunkKeys.push(key); } |
| 2628 | } |
| 2629 | worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys }); |
| 2630 | } |
| 2631 | this.#syncAllReplicas(); |
| 2632 | |
| 2633 | const nextSimulating = new Set(); |
| 2634 | for (const [key, count] of chunkSim) |
| 2635 | { |
| 2636 | if (count > 0) |
| 2637 | { nextSimulating.add(key); } |
| 2638 | } |
| 2639 | let preheated = false; |
| 2640 | for (const key of nextSimulating) |
| 2641 | { |
| 2642 | if (!this.simulatingChunkKeys.has(key)) |
| 2643 | { |
| 2644 | preheated = true; |
| 2645 | break; |
| 2646 | } |
| 2647 | } |
| 2648 | this.simulatingChunkKeys = nextSimulating; |
| 2649 | if (preheated) |
| 2650 | { this.#stepSpawners(); } |
| 2651 | } |
| 2652 | |
| 2653 | #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID) |
| 2654 | { |
| 2655 | const dim = normalizeDimensionId(dimensionId); |
| 2656 | const coverage = loaderCoverage(tileX, tileY, loader, dim); |
| 2657 | let preferred = this.#ownerOfTile(tileX, tileY, dim); |
| 2658 | for (const region of coverage.residentRegions) |
| 2659 | { |
| 2660 | const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim); |
| 2661 | if (preferred == null) |
| 2662 | { preferred = owner; } |
| 2663 | } |
| 2664 | } |
| 2665 | |
| 2666 | #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID) |
| 2667 | { |
| 2668 | const dim = normalizeDimensionId(dimensionId); |
| 2669 | const key = regionKey(regionX, regionY, dim); |
| 2670 | if (this.regionOwner.has(key)) |
| 2671 | { return this.regionOwner.get(key); } |
| 2672 | const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim); |
| 2673 | this.workers[workerId].call({ |
| 2674 | type: WorkerMessage.assignRegion, |
| 2675 | regionX, |
| 2676 | regionY, |
| 2677 | dimensionId: dim, |
| 2678 | chunks: this.#regionChunkBlobs(regionX, regionY, dim) |
| 2679 | }); |
| 2680 | this.regionOwner.set(key, workerId); |
| 2681 | this.#restorePersistent(regionX, regionY, workerId); |
| 2682 | this.#restoreGroundItems(regionX, regionY, workerId); |
| 2683 | return workerId; |
| 2684 | } |
| 2685 | |
| 2686 | #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2687 | { |
| 2688 | const dim = normalizeDimensionId(dimensionId); |
| 2689 | const key = regionKey(regionX, regionY, dim); |
| 2690 | const workerId = this.regionOwner.get(key); |
| 2691 | if (workerId == null) |
| 2692 | { return; } |
| 2693 | const bounds = regionTileBounds(regionX, regionY); |
| 2694 | const { dropped, groundItems } = this.workers[workerId].call({ |
| 2695 | type: WorkerMessage.dropRegion, |
| 2696 | regionX, |
| 2697 | regionY, |
| 2698 | dimensionId: dim |
| 2699 | }); |
| 2700 | const persistent = []; |
| 2701 | for (const record of dropped ?? []) |
| 2702 | { |
| 2703 | if (record.characterId) |
| 2704 | { |
| 2705 | this.stateDb.saveCharacterPosition( |
| 2706 | record.characterId, |
| 2707 | record.tileX, |
| 2708 | record.tileY, |
| 2709 | record.gait ?? GAIT.walk, |
| 2710 | record.dimensionId ?? OVERWORLD_ID |
| 2711 | ); |
| 2712 | } |
| 2713 | if (record.persistent) |
| 2714 | { persistent.push(record); } |
| 2715 | this.#forget(record.entityId); |
| 2716 | } |
| 2717 | this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent); |
| 2718 | for (const item of groundItems ?? []) |
| 2719 | { this.stateDb.upsertGroundItem(item); } |
| 2720 | this.regionOwner.delete(key); |
| 2721 | this.regionGraceUntil.delete(key); |
| 2722 | } |
| 2723 | |
| 2724 | #restorePersistent (regionX, regionY, workerId) |
| 2725 | { |
| 2726 | const bounds = regionTileBounds(regionX, regionY); |
| 2727 | const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); |
| 2728 | for (const row of rows) |
| 2729 | { |
| 2730 | if (this.directory.has(row.entity_id)) |
| 2731 | { continue; } |
| 2732 | const components = JSON.parse(row.components_blob); |
| 2733 | const view = this.workers[workerId].call({ |
| 2734 | type: WorkerMessage.spawn, |
| 2735 | entityId: row.entity_id, |
| 2736 | components |
| 2737 | }); |
| 2738 | this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1); |
| 2739 | this.#remember(view, workerId); |
| 2740 | } |
| 2741 | } |
| 2742 | |
| 2743 | #applyTransfers (requests) |
| 2744 | { |
| 2745 | const events = []; |
| 2746 | for (const request of requests) |
| 2747 | { |
| 2748 | const destWorkerId = this.#ensureRegion( |
| 2749 | request.toRegionX, |
| 2750 | request.toRegionY, |
| 2751 | request.fromWorkerId, |
| 2752 | request.dimensionId ?? OVERWORLD_ID |
| 2753 | ); |
| 2754 | if (destWorkerId === request.fromWorkerId) |
| 2755 | { |
| 2756 | this.workers[request.fromWorkerId].call({ |
| 2757 | type: WorkerMessage.abortTransfer, |
| 2758 | entityId: request.entityId |
| 2759 | }); |
| 2760 | continue; |
| 2761 | } |
| 2762 | let result; |
| 2763 | try |
| 2764 | { |
| 2765 | result = this.workers[destWorkerId].call({ |
| 2766 | type: WorkerMessage.applyTransfer, |
| 2767 | payload: request.payload, |
| 2768 | destTileX: request.destTileX, |
| 2769 | destTileY: request.destTileY, |
| 2770 | dimensionId: request.dimensionId ?? OVERWORLD_ID |
| 2771 | }); |
| 2772 | } |
| 2773 | catch |
| 2774 | { |
| 2775 | result = { accepted: false }; |
| 2776 | } |
| 2777 | if (!result?.accepted) |
| 2778 | { |
| 2779 | this.workers[request.fromWorkerId].call({ |
| 2780 | type: WorkerMessage.abortTransfer, |
| 2781 | entityId: request.entityId |
| 2782 | }); |
| 2783 | continue; |
| 2784 | } |
| 2785 | this.workers[request.fromWorkerId].call({ |
| 2786 | type: WorkerMessage.commitTransfer, |
| 2787 | entityId: request.entityId |
| 2788 | }); |
| 2789 | this.#remember(result.entity, destWorkerId); |
| 2790 | events.push({ |
| 2791 | type: "entity-move", |
| 2792 | entityId: request.entityId, |
| 2793 | fromTileX: request.fromTileX, |
| 2794 | fromTileY: request.fromTileY, |
| 2795 | fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId, |
| 2796 | tileX: result.entity.tileX, |
| 2797 | tileY: result.entity.tileY, |
| 2798 | dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID, |
| 2799 | gait: result.entity.gait |
| 2800 | }); |
| 2801 | } |
| 2802 | return events; |
| 2803 | } |
| 2804 | |
| 2805 | #syncAllReplicas () |
| 2806 | { |
| 2807 | for (const [workerId, worker] of this.workers.entries()) |
| 2808 | { |
| 2809 | const ownedKeys = new Set(); |
| 2810 | for (const [key, owner] of this.regionOwner) |
| 2811 | { |
| 2812 | if (owner !== workerId) |
| 2813 | { continue; } |
| 2814 | const { regionX, regionY, dimensionId } = parseRegionKey(key); |
| 2815 | for (const chunk of chunksInRegion(regionX, regionY)) |
| 2816 | { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); } |
| 2817 | } |
| 2818 | const replicas = []; |
| 2819 | for (const key of replicaNeededForOwnedChunks(ownedKeys)) |
| 2820 | { |
| 2821 | if (ownedKeys.has(key)) |
| 2822 | { continue; } |
| 2823 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 2824 | replicas.push({ |
| 2825 | chunkX, |
| 2826 | chunkY, |
| 2827 | dimensionId, |
| 2828 | data: this.#authoredChunk(chunkX, chunkY, dimensionId) |
| 2829 | }); |
| 2830 | } |
| 2831 | worker.call({ type: WorkerMessage.setReplicas, chunks: replicas }); |
| 2832 | } |
| 2833 | } |
| 2834 | |
| 2835 | #syncGhosts () |
| 2836 | { |
| 2837 | const entities = []; |
| 2838 | for (const worker of this.workers) |
| 2839 | { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); } |
| 2840 | for (const [workerId, worker] of this.workers.entries()) |
| 2841 | { |
| 2842 | const ghosts = entities.filter((entity) => |
| 2843 | { |
| 2844 | const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID); |
| 2845 | if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId) |
| 2846 | { return false; } |
| 2847 | return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim); |
| 2848 | }); |
| 2849 | worker.call({ type: WorkerMessage.setGhosts, ghosts }); |
| 2850 | } |
| 2851 | } |
| 2852 | |
| 2853 | #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2854 | { |
| 2855 | const dim = normalizeDimensionId(dimensionId); |
| 2856 | const chunkX = tileToChunk(tileX); |
| 2857 | const chunkY = tileToChunk(tileY); |
| 2858 | for (const [key, owner] of this.regionOwner) |
| 2859 | { |
| 2860 | if (owner !== workerId) |
| 2861 | { continue; } |
| 2862 | const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key); |
| 2863 | if (regionDim !== dim) |
| 2864 | { continue; } |
| 2865 | for (const chunk of chunksInRegion(regionX, regionY)) |
| 2866 | { |
| 2867 | if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2) |
| 2868 | { return true; } |
| 2869 | } |
| 2870 | } |
| 2871 | return false; |
| 2872 | } |
| 2873 | |
| 2874 | #allLoaders () |
| 2875 | { |
| 2876 | const loaders = []; |
| 2877 | for (const worker of this.workers) |
| 2878 | { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); } |
| 2879 | return loaders; |
| 2880 | } |
| 2881 | |
| 2882 | #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2883 | { |
| 2884 | const dim = normalizeDimensionId(dimensionId); |
| 2885 | const votes = new Map(); |
| 2886 | for (const loader of loaders) |
| 2887 | { |
| 2888 | const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID); |
| 2889 | if (loaderDim !== dim) |
| 2890 | { continue; } |
| 2891 | const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim); |
| 2892 | if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY)) |
| 2893 | { continue; } |
| 2894 | const record = this.directory.get(loader.entityId); |
| 2895 | if (record?.workerId == null) |
| 2896 | { continue; } |
| 2897 | votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1); |
| 2898 | } |
| 2899 | let best = null; |
| 2900 | let bestVotes = -1; |
| 2901 | for (const [workerId, count] of votes) |
| 2902 | { |
| 2903 | if (count > bestVotes) |
| 2904 | { |
| 2905 | best = workerId; |
| 2906 | bestVotes = count; |
| 2907 | } |
| 2908 | } |
| 2909 | return best; |
| 2910 | } |
| 2911 | |
| 2912 | #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID) |
| 2913 | { |
| 2914 | const dim = normalizeDimensionId(dimensionId); |
| 2915 | const pinned = this.pinRegion?.(regionX, regionY, dim); |
| 2916 | if (pinned != null) |
| 2917 | { return pinned; } |
| 2918 | |
| 2919 | const neighborOwners = []; |
| 2920 | for (let dy = -1; dy <= 1; dy++) |
| 2921 | { |
| 2922 | for (let dx = -1; dx <= 1; dx++) |
| 2923 | { |
| 2924 | if (dx === 0 && dy === 0) |
| 2925 | { continue; } |
| 2926 | const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim)); |
| 2927 | if (owner != null) |
| 2928 | { neighborOwners.push(owner); } |
| 2929 | } |
| 2930 | } |
| 2931 | |
| 2932 | const scores = this.workers.map((_, workerId) => ({ |
| 2933 | workerId, |
| 2934 | neighbors: neighborOwners.filter((owner) => owner === workerId).length, |
| 2935 | load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length |
| 2936 | })); |
| 2937 | |
| 2938 | if (preferredWorkerId != null && scores[preferredWorkerId]) |
| 2939 | { |
| 2940 | const preferred = scores[preferredWorkerId]; |
| 2941 | if (preferred.neighbors > 0 || neighborOwners.length === 0) |
| 2942 | { return preferredWorkerId; } |
| 2943 | } |
| 2944 | |
| 2945 | scores.sort((left, right) => |
| 2946 | right.neighbors - left.neighbors |
| 2947 | || left.load - right.load |
| 2948 | || left.workerId - right.workerId |
| 2949 | ); |
| 2950 | return scores[0].workerId; |
| 2951 | } |
| 2952 | |
| 2953 | #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2954 | { |
| 2955 | return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null; |
| 2956 | } |
| 2957 | |
| 2958 | #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2959 | { |
| 2960 | return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId); |
| 2961 | } |
| 2962 | |
| 2963 | #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2964 | { |
| 2965 | const dim = normalizeDimensionId(dimensionId); |
| 2966 | return chunksInRegion(regionX, regionY).map((coord) => ({ |
| 2967 | chunkX: coord.chunkX, |
| 2968 | chunkY: coord.chunkY, |
| 2969 | dimensionId: dim, |
| 2970 | data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim) |
| 2971 | })); |
| 2972 | } |
| 2973 | |
| 2974 | #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2975 | { |
| 2976 | const dim = normalizeDimensionId(dimensionId); |
| 2977 | const key = chunkKey(chunkX, chunkY, dim); |
| 2978 | if (this.authoredCache.has(key)) |
| 2979 | { return this.authoredCache.get(key); } |
| 2980 | const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim); |
| 2981 | const dimRecord = this.getDimensionRecord(dim); |
| 2982 | const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId; |
| 2983 | const data = row |
| 2984 | ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY) |
| 2985 | : createEmptyChunkData(defaultGroundTypeId); |
| 2986 | this.authoredCache.set(key, data); |
| 2987 | return data; |
| 2988 | } |
| 2989 | |
| 2990 | #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2991 | { |
| 2992 | const dim = normalizeDimensionId(dimensionId); |
| 2993 | const data = this.#authoredChunk(chunkX, chunkY, dim); |
| 2994 | return { |
| 2995 | chunkX, |
| 2996 | chunkY, |
| 2997 | dimensionId: dim, |
| 2998 | open: data.open, |
| 2999 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open), |
| 3000 | grounds: data.grounds, |
| 3001 | blocks: data.blocks, |
| 3002 | light: data.light, |
| 3003 | entities: [], |
| 3004 | groundItems: [] |
| 3005 | }; |
| 3006 | } |
| 3007 | |
| 3008 | #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 3009 | { |
| 3010 | const dim = normalizeDimensionId(dimensionId); |
| 3011 | for (const record of this.directory.values()) |
| 3012 | { |
| 3013 | const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID); |
| 3014 | if (record.tileX === tileX && record.tileY === tileY && recordDim === dim) |
| 3015 | { return record.entityId; } |
| 3016 | } |
| 3017 | return null; |
| 3018 | } |
| 3019 | |
| 3020 | #queueReplication (event) |
| 3021 | { |
| 3022 | if (event) |
| 3023 | { this.replication.push(event); } |
| 3024 | } |
| 3025 | |
| 3026 | #stepSpawners () |
| 3027 | { |
| 3028 | const events = []; |
| 3029 | for (const worker of this.workers) |
| 3030 | { |
| 3031 | const result = worker.call({ type: WorkerMessage.stepSpawners }); |
| 3032 | for (const request of result?.spawnRequests ?? []) |
| 3033 | { |
| 3034 | try |
| 3035 | { |
| 3036 | this.spawnEntity(mobComponents(request), { requireResident: true }); |
| 3037 | } |
| 3038 | catch |
| 3039 | { continue; } |
| 3040 | } |
| 3041 | } |
| 3042 | return events; |
| 3043 | } |
| 3044 | |
| 3045 | #restoreGroundItems (regionX, regionY, workerId) |
| 3046 | { |
| 3047 | const bounds = regionTileBounds(regionX, regionY); |
| 3048 | const items = []; |
| 3049 | for (const item of this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)) |
| 3050 | { |
| 3051 | if (item.expiresAt > this.now) |
| 3052 | { |
| 3053 | items.push(item); |
| 3054 | continue; |
| 3055 | } |
| 3056 | // Expired while unloaded: destroy and free any cheque reservation. |
| 3057 | this.#destroyExpiredGroundItem(item); |
| 3058 | } |
| 3059 | this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId()); |
| 3060 | this.workers[workerId].call({ |
| 3061 | type: WorkerMessage.setGroundItems, |
| 3062 | regionX, |
| 3063 | regionY, |
| 3064 | items |
| 3065 | }); |
| 3066 | } |
| 3067 | |
| 3068 | /** Cheque paper that no longer exists must free reserved vault goods. */ |
| 3069 | voidFilledCheque (stack) |
| 3070 | { |
| 3071 | if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque") |
| 3072 | { return { ok: false }; } |
| 3073 | const issuerId = stack.instance.issuerCharacterId | 0; |
| 3074 | const chequeId = stack.instance.chequeId; |
| 3075 | const release = this.releaseChequeReservation(issuerId, chequeId, stack.instance); |
| 3076 | if (!release?.ok || !release.stack) |
| 3077 | { |
| 3078 | // Already redeemed/voided — treat as success so despawn stays idempotent. |
| 3079 | return { ok: true, alreadyReleased: true }; |
| 3080 | } |
| 3081 | const onlineId = this.characterEntities.get(issuerId); |
| 3082 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerId); |
| 3083 | if (!bag) |
| 3084 | { return { ok: false, error: "Issuer vault not found." }; } |
| 3085 | const goodsDef = itemDefinition(release.stack.itemId); |
| 3086 | if (!goodsDef) |
| 3087 | { return { ok: false, error: "Unknown reserved goods." }; } |
| 3088 | const goods = attachOrigins({ |
| 3089 | itemId: release.stack.itemId, |
| 3090 | quantity: release.stack.quantity, |
| 3091 | instance: release.stack.instance ? structuredClone(release.stack.instance) : null, |
| 3092 | origins: release.stack.origins |
| 3093 | }); |
| 3094 | const inserted = insertStackGrowable(bag.vault ?? [], goods, goodsDef); |
| 3095 | bag.vault = inserted.slots; |
| 3096 | this.stateDb.saveBag(issuerId, bag); |
| 3097 | if (onlineId) |
| 3098 | { |
| 3099 | this.applyBag(onlineId, bag); |
| 3100 | this.pushInventory(issuerId, bag); |
| 3101 | } |
| 3102 | this.pendingPrivate.push({ |
| 3103 | type: "toast", |
| 3104 | characterId: issuerId, |
| 3105 | message: "An uncashed cheque expired. Reserved goods returned to your vault." |
| 3106 | }); |
| 3107 | return { ok: true }; |
| 3108 | } |
| 3109 | |
| 3110 | #destroyExpiredGroundItem (item) |
| 3111 | { |
| 3112 | if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque") |
| 3113 | { this.voidFilledCheque(item.stack); } |
| 3114 | this.stateDb.deleteGroundItem(item.groundItemId); |
| 3115 | } |
| 3116 | |
| 3117 | #persistGroundEvent (event) |
| 3118 | { |
| 3119 | if (event.type === "ground-item-appear") |
| 3120 | { |
| 3121 | this.stateDb.upsertGroundItem({ |
| 3122 | groundItemId: event.groundItemId, |
| 3123 | tileX: event.tileX, |
| 3124 | tileY: event.tileY, |
| 3125 | stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity }, |
| 3126 | droppedAt: event.droppedAt ?? this.now, |
| 3127 | expiresAt: event.expiresAt, |
| 3128 | source: event.source ?? "player-drop", |
| 3129 | droppedByCharacterId: event.droppedByCharacterId ?? null |
| 3130 | }); |
| 3131 | } |
| 3132 | if (event.type === "ground-item-despawn") |
| 3133 | { this.stateDb.deleteGroundItem(event.groundItemId); } |
| 3134 | } |
| 3135 | |
| 3136 | #saveBag (entityId, workerId) |
| 3137 | { |
| 3138 | const record = this.directory.get(entityId); |
| 3139 | const bag = this.workers[workerId].call({ |
| 3140 | type: WorkerMessage.inspectBag, |
| 3141 | entityId |
| 3142 | }); |
| 3143 | if (!bag || !record?.characterId) |
| 3144 | { return; } |
| 3145 | this.#saveBagFromView(record.characterId, bag); |
| 3146 | const skills = this.workers[workerId].call({ |
| 3147 | type: WorkerMessage.inspectSkills, |
| 3148 | entityId |
| 3149 | }); |
| 3150 | if (skills) |
| 3151 | { this.stateDb.saveSkills(record.characterId, skills); } |
| 3152 | } |
| 3153 | |
| 3154 | #applySkillsUpdated (event) |
| 3155 | { |
| 3156 | if (!event?.characterId || !event.stored) |
| 3157 | { return; } |
| 3158 | this.stateDb.saveSkills(event.characterId, { xp: event.stored }); |
| 3159 | this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0); |
| 3160 | } |
| 3161 | |
| 3162 | #applySpellsUpdated (event) |
| 3163 | { |
| 3164 | if (!event?.characterId || !event.stored) |
| 3165 | { return; } |
| 3166 | this.stateDb.saveSpells(event.characterId, event.stored); |
| 3167 | this.pushSpells(event.characterId, { |
| 3168 | spells: event.spells ?? [], |
| 3169 | favorites: event.favorites ?? [], |
| 3170 | autoCast: !!event.autoCast |
| 3171 | }); |
| 3172 | } |
| 3173 | |
| 3174 | #applySummonEntity (event) |
| 3175 | { |
| 3176 | const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy"; |
| 3177 | const components = isFairy |
| 3178 | ? jadeiteFairyComponents({ |
| 3179 | tileX: event.tileX | 0, |
| 3180 | tileY: event.tileY | 0, |
| 3181 | level: event.level | 0 || 1, |
| 3182 | ownerEntityId: event.ownerEntityId, |
| 3183 | ownerCharacterId: event.ownerCharacterId ?? null, |
| 3184 | ownerName: event.ownerName, |
| 3185 | dimensionId: event.dimensionId |
| 3186 | }) |
| 3187 | : shadeSummonComponents({ |
| 3188 | tileX: event.tileX | 0, |
| 3189 | tileY: event.tileY | 0, |
| 3190 | level: event.level | 0 || 1, |
| 3191 | ownerEntityId: event.ownerEntityId, |
| 3192 | expiresAt: event.expiresAt, |
| 3193 | dimensionId: event.dimensionId |
| 3194 | }); |
| 3195 | try |
| 3196 | { |
| 3197 | const entityId = this.spawnEntity(components, { requireResident: true }); |
| 3198 | if (entityId == null) |
| 3199 | { return []; } |
| 3200 | return []; |
| 3201 | } |
| 3202 | catch |
| 3203 | { |
| 3204 | return []; |
| 3205 | } |
| 3206 | } |
| 3207 | |
| 3208 | #applyJewelryTeleport (event) |
| 3209 | { |
| 3210 | const entityId = event.entityId ?? this.characterEntities.get(event.characterId); |
| 3211 | const record = entityId ? this.directory.get(entityId) : null; |
| 3212 | if (!record) |
| 3213 | { return []; } |
| 3214 | const destination = this.#findJewelryTeleportDestination( |
| 3215 | event.fromTileX | 0, |
| 3216 | event.fromTileY | 0, |
| 3217 | entityId, |
| 3218 | event.destination |
| 3219 | ); |
| 3220 | if (!destination) |
| 3221 | { |
| 3222 | return [{ |
| 3223 | type: "command-error", |
| 3224 | sessionId: event.sessionId, |
| 3225 | message: event.destination === "bank" |
| 3226 | ? "No bank is available." |
| 3227 | : "No church altar is available." |
| 3228 | }]; |
| 3229 | } |
| 3230 | const loader = { ...DEFAULT_CHUNK_LOADER }; |
| 3231 | this.#ensureCoverage( |
| 3232 | destination.tileX, |
| 3233 | destination.tileY, |
| 3234 | loader, |
| 3235 | destination.dimensionId ?? OVERWORLD_ID |
| 3236 | ); |
| 3237 | const result = this.workers[record.workerId].call({ |
| 3238 | type: WorkerMessage.relocateEntity, |
| 3239 | entityId, |
| 3240 | tileX: destination.tileX, |
| 3241 | tileY: destination.tileY, |
| 3242 | dimensionId: destination.dimensionId ?? OVERWORLD_ID |
| 3243 | }); |
| 3244 | if (!result?.accepted) |
| 3245 | { |
| 3246 | return [{ |
| 3247 | type: "command-error", |
| 3248 | sessionId: event.sessionId, |
| 3249 | message: "The destination is no longer available." |
| 3250 | }]; |
| 3251 | } |
| 3252 | const events = []; |
| 3253 | if (result.transferRequest) |
| 3254 | { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); } |
| 3255 | else if (result.event) |
| 3256 | { |
| 3257 | this.#applyMoveToDirectory(result.event); |
| 3258 | events.push(result.event); |
| 3259 | const view = this.workers[record.workerId].call({ |
| 3260 | type: WorkerMessage.inspect, |
| 3261 | entityId |
| 3262 | }); |
| 3263 | if (view) |
| 3264 | { this.#remember(view, record.workerId); } |
| 3265 | } |
| 3266 | return events; |
| 3267 | } |
| 3268 | |
| 3269 | #findJewelryTeleportDestination (originX, originY, entityId, destination) |
| 3270 | { |
| 3271 | if (destination === "church") |
| 3272 | { return this.#findRespawnDestination(originX, originY, entityId); } |
| 3273 | if (destination !== "bank") |
| 3274 | { return null; } |
| 3275 | const record = this.directory.get(entityId); |
| 3276 | const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID); |
| 3277 | const bank = this.courier?.nearestBank(originX, originY); |
| 3278 | if (!bank) |
| 3279 | { return null; } |
| 3280 | const adjacent = []; |
| 3281 | for (let dy = -1; dy <= 1; dy++) |
| 3282 | { |
| 3283 | for (let dx = -1; dx <= 1; dx++) |
| 3284 | { |
| 3285 | if (dx === 0 && dy === 0) |
| 3286 | { continue; } |
| 3287 | adjacent.push({ |
| 3288 | tileX: bank.tileX + dx, |
| 3289 | tileY: bank.tileY + dy, |
| 3290 | dimensionId |
| 3291 | }); |
| 3292 | } |
| 3293 | } |
| 3294 | adjacent.sort((left, right) => |
| 3295 | Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY)) |
| 3296 | - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY)) |
| 3297 | ); |
| 3298 | const tile = adjacent.find((entry) => |
| 3299 | this.isEnterable(entry.tileX, entry.tileY, dimensionId) |
| 3300 | && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId) |
| 3301 | ); |
| 3302 | return tile ?? null; |
| 3303 | } |
| 3304 | |
| 3305 | #skillLevelUpEvents (event) |
| 3306 | { |
| 3307 | const levelUps = event?.levelUps ?? []; |
| 3308 | if (!levelUps.length) |
| 3309 | { return []; } |
| 3310 | const entityId = event.entityId ?? this.characterEntities.get(event.characterId); |
| 3311 | if (entityId == null) |
| 3312 | { return []; } |
| 3313 | const record = this.directory.get(entityId); |
| 3314 | const tileX = record?.tileX ?? 0; |
| 3315 | const tileY = record?.tileY ?? 0; |
| 3316 | return levelUps.map((levelUp) => ({ |
| 3317 | type: "skill-level-up", |
| 3318 | entityId, |
| 3319 | characterId: event.characterId, |
| 3320 | tileX, |
| 3321 | tileY, |
| 3322 | skillId: levelUp.skillId, |
| 3323 | level: levelUp.level, |
| 3324 | previousLevel: levelUp.previousLevel, |
| 3325 | displayName: levelUp.displayName, |
| 3326 | icon: levelUp.icon |
| 3327 | })); |
| 3328 | } |
| 3329 | |
| 3330 | #saveBagFromView (characterId, bag) |
| 3331 | { |
| 3332 | this.stateDb.saveBag(characterId, { |
| 3333 | inventory: bag.inventory, |
| 3334 | equipment: bag.equipment, |
| 3335 | vault: bag.vault, |
| 3336 | vaultReserved: bag.vaultReserved |
| 3337 | }); |
| 3338 | } |
| 3339 | |
| 3340 | releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null) |
| 3341 | { |
| 3342 | const onlineId = this.characterEntities.get(issuerCharacterId); |
| 3343 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); |
| 3344 | if (!bag) |
| 3345 | { return { ok: false, error: "Issuer vault not found." }; } |
| 3346 | const reserved = [...(bag.vaultReserved ?? [])]; |
| 3347 | const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId }); |
| 3348 | if (index < 0) |
| 3349 | { return { ok: false, error: "That cheque cannot be redeemed." }; } |
| 3350 | const [stack] = reserved.splice(index, 1); |
| 3351 | bag.vaultReserved = reserved; |
| 3352 | this.stateDb.saveBag(issuerCharacterId, bag); |
| 3353 | if (onlineId) |
| 3354 | { |
| 3355 | this.applyBag(onlineId, bag); |
| 3356 | this.pushInventory(issuerCharacterId, bag); |
| 3357 | } |
| 3358 | return { ok: true, stack }; |
| 3359 | } |
| 3360 | |
| 3361 | restoreChequeReservation (issuerCharacterId, stack) |
| 3362 | { |
| 3363 | const onlineId = this.characterEntities.get(issuerCharacterId); |
| 3364 | const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); |
| 3365 | if (!bag) |
| 3366 | { return; } |
| 3367 | bag.vaultReserved = [...(bag.vaultReserved ?? []), stack]; |
| 3368 | this.stateDb.saveBag(issuerCharacterId, bag); |
| 3369 | if (onlineId) |
| 3370 | { |
| 3371 | this.applyBag(onlineId, bag); |
| 3372 | this.pushInventory(issuerCharacterId, bag); |
| 3373 | } |
| 3374 | } |
| 3375 | |
| 3376 | #remember (view, workerId) |
| 3377 | { |
| 3378 | if (!view) |
| 3379 | { return; } |
| 3380 | const previous = this.directory.get(view.entityId); |
| 3381 | this.directory.set(view.entityId, { |
| 3382 | ...view, |
| 3383 | workerId, |
| 3384 | // Keep simulation-only fields that publicEntityView does not carry. |
| 3385 | skullValue: previous?.skullValue ?? view.skullValue ?? 0 |
| 3386 | }); |
| 3387 | if (view.characterId) |
| 3388 | { this.characterEntities.set(view.characterId, view.entityId); } |
| 3389 | } |
| 3390 | |
| 3391 | #applyMoveToDirectory (event) |
| 3392 | { |
| 3393 | const record = this.directory.get(event.entityId); |
| 3394 | if (!record) |
| 3395 | { return; } |
| 3396 | record.tileX = event.tileX; |
| 3397 | record.tileY = event.tileY; |
| 3398 | record.gait = event.gait; |
| 3399 | if (event.dimensionId != null) |
| 3400 | { record.dimensionId = normalizeDimensionId(event.dimensionId); } |
| 3401 | if (event.worldX != null) |
| 3402 | { record.worldX = event.worldX; } |
| 3403 | if (event.worldY != null) |
| 3404 | { record.worldY = event.worldY; } |
| 3405 | if (event.freeFlight != null) |
| 3406 | { record.freeFlight = !!event.freeFlight; } |
| 3407 | } |
| 3408 | |
| 3409 | #forget (entityId) |
| 3410 | { |
| 3411 | const record = this.directory.get(entityId); |
| 3412 | if (record?.characterId) |
| 3413 | { this.characterEntities.delete(record.characterId); } |
| 3414 | this.directory.delete(entityId); |
| 3415 | } |
| 3416 | } |