BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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