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