BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 111.4 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 startedAt = logout.startedAt ?? now;
930 const lastActivity = track?.lastCombatActivityAt ?? startedAt;
931 const quietDone = (now - lastActivity) >= COMBAT_LOGOUT_MS;
932 // Hard cap from disconnect so auto-cast / hits cannot extend forever.
933 const hardCapDone = (now - startedAt) >= COMBAT_LOGOUT_MS;
934 if (!quietDone && !hardCapDone)
935 { continue; }
936 if (logout.pendingCowardice)
937 { applyCombatLogoutCowardice(this, characterId, { now }); }
938 this.#restoreCombatLogoutAutoCast(characterId, logout);
939 this.combatLogouts.delete(characterId);
940 this.despawnCharacter(characterId);
941 }
942 return events;
943 }
944
945 despawnCharacter (characterId)
946 {
947 this.market?.leaveExchangeStations?.(characterId);
948 const tradeEvents = this.trade?.onCharacterGone?.(characterId) ?? [];
949 if (tradeEvents.length)
950 { this.pendingPrivate.push(...tradeEvents); }
951 const entityId = this.characterEntities.get(characterId);
952 if (!entityId)
953 {
954 this.combatLogouts.delete(characterId | 0);
955 return;
956 }
957 const record = this.directory.get(entityId);
958 if (!record)
959 {
960 this.characterEntities.delete(characterId);
961 this.combatLogouts.delete(characterId | 0);
962 return;
963 }
964 this.#saveBag(entityId, record.workerId);
965 const dropped = this.workers[record.workerId].call({
966 type: WorkerMessage.despawnCharacter,
967 characterId
968 });
969 if (dropped)
970 {
971 const dimensionId = normalizeDimensionId(
972 dropped.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
973 );
974 this.stateDb.saveCharacterPosition(
975 characterId,
976 dropped.tileX,
977 dropped.tileY,
978 dropped.gait ?? GAIT.walk,
979 dimensionId
980 );
981 if (dropped.health != null)
982 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
983 this.#queueReplication({
984 ...replicationDespawn(dropped),
985 dimensionId
986 });
987 }
988 this.#forget(entityId);
989 this.combatLogouts.delete(characterId | 0);
990 this.#recalculateActivation(this.now);
991 this.#syncGhosts();
992 }
993
994 spawnEntity (components, options = {})
995 {
996 const entityId = options.entityId ?? this.nextEntityId++;
997 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
998 const position = components.position;
999 if (!position)
1000 { throw new Error("spawnEntity requires position."); }
1001 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1002 position.dimensionId = dimensionId;
1003 if (options.requireResident)
1004 {
1005 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
1006 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId))
1007 { return null; }
1008 const view = this.workers[workerId].call({
1009 type: WorkerMessage.spawn,
1010 entityId,
1011 components
1012 });
1013 this.#remember(view, workerId);
1014 if (components.appearance)
1015 { this.#queueReplication(replicationSpawn(view)); }
1016 this.#syncGhosts();
1017 return entityId;
1018 }
1019 if (components.chunkLoader)
1020 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); }
1021 else
1022 {
1023 this.#ensureRegion(
1024 tileToRegion(position.tileX),
1025 tileToRegion(position.tileY),
1026 null,
1027 dimensionId
1028 );
1029 }
1030 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
1031 const view = this.workers[workerId].call({
1032 type: WorkerMessage.spawn,
1033 entityId,
1034 components
1035 });
1036 this.#remember(view, workerId);
1037 if (components.appearance)
1038 { this.#queueReplication(replicationSpawn(view)); }
1039 this.#recalculateActivation(this.now);
1040 this.#syncGhosts();
1041 return entityId;
1042 }
1043
1044 despawnEntity (entityId)
1045 {
1046 const record = this.directory.get(entityId);
1047 if (!record)
1048 { return; }
1049 const dropped = this.workers[record.workerId].call({
1050 type: WorkerMessage.despawn,
1051 entityId
1052 });
1053 if (dropped)
1054 { this.#queueReplication(replicationDespawn(dropped)); }
1055 this.#forget(entityId);
1056 }
1057
1058 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1059 {
1060 const loaders = this.#allLoaders();
1061 const { chunkSim } = accumulateLoaderRefs(loaders);
1062 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0;
1063 }
1064
1065 updateCourierFlight (entityId, flightPatch, now = this.now)
1066 {
1067 const record = this.directory.get(entityId);
1068 if (!record)
1069 { return { despawned: true, entityId }; }
1070 const tileX = Math.floor(flightPatch.x);
1071 const tileY = Math.floor(flightPatch.y);
1072 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1073 const owner = this.#ownerOfTile(tileX, tileY, dimensionId);
1074 if (owner == null || owner !== record.workerId)
1075 {
1076 this.despawnEntity(entityId);
1077 return { despawned: true, entityId };
1078 }
1079 const result = this.workers[owner].call({
1080 type: WorkerMessage.updateFlight,
1081 entityId,
1082 flight: flightPatch,
1083 now
1084 });
1085 if (result?.transferRequest)
1086 {
1087 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
1088 this.#recalculateActivation(now);
1089 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
1090 if (move)
1091 {
1092 this.#applyMoveToDirectory(move);
1093 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
1094 }
1095 this.despawnEntity(entityId);
1096 return { despawned: true, entityId };
1097 }
1098 if (result?.event)
1099 {
1100 this.#applyMoveToDirectory(result.event);
1101 return { event: result.event };
1102 }
1103 return null;
1104 }
1105
1106 applyBag (entityId, bag)
1107 {
1108 const record = this.directory.get(entityId);
1109 if (!record)
1110 { return null; }
1111 const result = this.workers[record.workerId].call({
1112 type: WorkerMessage.applyBag,
1113 entityId,
1114 bag
1115 });
1116 if (record.characterId)
1117 { this.#markQuestReeval(record.characterId); }
1118 return result;
1119 }
1120
1121 applySkills (entityId, skills)
1122 {
1123 const record = this.directory.get(entityId);
1124 if (!record)
1125 { return null; }
1126 return this.workers[record.workerId].call({
1127 type: WorkerMessage.applySkills,
1128 entityId,
1129 skills
1130 });
1131 }
1132
1133 /** Persist skills from stateDb onto the live worker and push a client snapshot. */
1134 syncCharacterSkillsFromDb (characterId)
1135 {
1136 const id = characterId | 0;
1137 const skills = this.stateDb.getSkills(id);
1138 if (!skills)
1139 { return; }
1140 const entityId = this.characterEntities.get(id);
1141 if (entityId)
1142 { this.applySkills(entityId, skills); }
1143 const payload = publicSkillsPayload(skills);
1144 this.pushSkills(id, payload.skills, payload.combatLevel);
1145 }
1146
1147 /**
1148 * Persist hair + patch live appearance; returns public view.
1149 */
1150 setCharacterHair (characterId, hair)
1151 {
1152 const row = this.stateDb.updateCharacterHair(characterId, hair);
1153 const entityId = this.characterEntities.get(characterId);
1154 if (!entityId)
1155 { return { row, view: null }; }
1156 const fields = appearanceHairFields({
1157 sex: row.sex,
1158 style: hair.style,
1159 hue: hair.hue,
1160 saturation: hair.saturation,
1161 darkness: hair.darkness
1162 });
1163 const record = this.directory.get(entityId);
1164 if (!record)
1165 { return { row, view: null }; }
1166 const view = this.workers[record.workerId].call({
1167 type: WorkerMessage.applyAppearance,
1168 entityId,
1169 appearance: fields
1170 });
1171 if (view)
1172 {
1173 this.#remember(view, record.workerId);
1174 this.#queueReplication(replicationAppearance(view));
1175 }
1176 return { row, view };
1177 }
1178
1179 pushSkills (characterId, skills, combatLevel)
1180 {
1181 this.pendingPrivate.push({
1182 type: "skills",
1183 characterId,
1184 skills,
1185 combatLevel
1186 });
1187 }
1188
1189 pushSpells (characterId, payload)
1190 {
1191 this.pendingPrivate.push({
1192 type: "spells",
1193 characterId,
1194 ...payload
1195 });
1196 }
1197
1198 skillsOf (entityId)
1199 {
1200 const record = this.directory.get(entityId);
1201 if (!record)
1202 { return null; }
1203 return this.workers[record.workerId].call({
1204 type: WorkerMessage.inspectSkills,
1205 entityId
1206 });
1207 }
1208
1209 spellsOf (entityId)
1210 {
1211 const record = this.directory.get(entityId);
1212 if (!record)
1213 { return null; }
1214 return this.workers[record.workerId].call({
1215 type: WorkerMessage.inspectSpells,
1216 entityId
1217 });
1218 }
1219
1220 staminaOf (entityId)
1221 {
1222 const record = this.directory.get(entityId);
1223 if (!record)
1224 { return null; }
1225 return this.workers[record.workerId].call({
1226 type: WorkerMessage.inspectStamina,
1227 entityId
1228 });
1229 }
1230
1231 pushInventory (characterId, bag)
1232 {
1233 this.pendingPrivate.push({
1234 type: "inventory",
1235 characterId,
1236 inventory: bag.inventory,
1237 equipment: bag.equipment,
1238 vault: bag.vault,
1239 vaultReserved: bag.vaultReserved
1240 });
1241 }
1242
1243 dispatchPigeon ({ characterId, destination, cargo })
1244 {
1245 const entityId = this.characterEntities.get(characterId);
1246 const position = entityId ? this.positionOf(entityId) : null;
1247 if (!position)
1248 {
1249 const error = new Error("Enter the world before sending a pigeon.");
1250 error.userFacing = true;
1251 throw error;
1252 }
1253 return this.courier.dispatchFromPlayer({
1254 characterId,
1255 originTileX: position.tileX,
1256 originTileY: position.tileY,
1257 originDimensionId: position.dimensionId ?? OVERWORLD_ID,
1258 destination,
1259 cargo
1260 });
1261 }
1262
1263 /**
1264 * Path an idle CE clerk to a staff-side station tile.
1265 */
1266 stationExchangeClerk (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
1267 {
1268 const dim = normalizeDimensionId(dimensionId);
1269 const owner = this.#ownerOfTile(stationTileX, stationTileY, dim);
1270 if (owner == null)
1271 { return { ok: false, reason: "unowned" }; }
1272 return this.workers[owner].call({
1273 type: WorkerMessage.stationExchangeClerk,
1274 stationTileX,
1275 stationTileY,
1276 dimensionId: dim
1277 });
1278 }
1279
1280 /**
1281 * When a player uses a marketplace counter, path idle CE clerks to the
1282 * opposite side of each adjacent counter (staff side).
1283 */
1284 stationExchangeClerks (playerTileX, playerTileY, dimensionId = OVERWORLD_ID)
1285 {
1286 const dim = normalizeDimensionId(dimensionId);
1287 const results = [];
1288 for (const tile of this.market?.marketTiles ?? [])
1289 {
1290 if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
1291 { continue; }
1292 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
1293 { continue; }
1294 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
1295 { continue; }
1296 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
1297 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
1298 if (stationTileX === playerTileX && stationTileY === playerTileY)
1299 { continue; }
1300 results.push(this.stationExchangeClerk(stationTileX, stationTileY, dim));
1301 }
1302 return results;
1303 }
1304
1305 /** Release a CE clerk stationed at the given staff-side tile. */
1306 releaseExchangeClerk (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
1307 {
1308 const dim = normalizeDimensionId(dimensionId);
1309 const owner = this.#ownerOfTile(stationTileX, stationTileY, dim);
1310 if (owner == null)
1311 { return { ok: false, reason: "unowned" }; }
1312 return this.workers[owner].call({
1313 type: WorkerMessage.releaseExchangeClerk,
1314 stationTileX,
1315 stationTileY,
1316 dimensionId: dim
1317 });
1318 }
1319
1320 entityForCharacter (characterId)
1321 {
1322 return this.characterEntities.get(characterId) ?? null;
1323 }
1324
1325 entityRecord (entityId)
1326 {
1327 const record = this.directory.get(entityId);
1328 return record ? { ...record } : null;
1329 }
1330
1331 positionOf (entityId)
1332 {
1333 const record = this.directory.get(entityId);
1334 return record
1335 ? {
1336 tileX: record.tileX,
1337 tileY: record.tileY,
1338 dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID)
1339 }
1340 : null;
1341 }
1342
1343 bagOf (entityId)
1344 {
1345 const record = this.directory.get(entityId);
1346 if (!record)
1347 { return null; }
1348 return this.workers[record.workerId].call({
1349 type: WorkerMessage.inspectBag,
1350 entityId
1351 });
1352 }
1353
1354 snapshotFor (entityId)
1355 {
1356 const record = this.directory.get(entityId);
1357 if (!record)
1358 { return []; }
1359 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1360 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
1361 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId));
1362 }
1363
1364 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
1365 snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
1366 {
1367 const record = this.directory.get(entityId);
1368 if (!record)
1369 { return []; }
1370 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1371 const centerChunkX = tileToChunk(record.tileX);
1372 const centerChunkY = tileToChunk(record.tileY);
1373 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
1374 const entityKeys = new Set(
1375 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
1376 .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId))
1377 );
1378 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
1379 .map((coord) =>
1380 {
1381 const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId);
1382 const staticOnly = !entityKeys.has(key);
1383 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId);
1384 const entities = (snapshot.entities ?? []).map((entity) =>
1385 {
1386 const known = this.directory.get(entity.entityId);
1387 if (!known || entity.characterId == null)
1388 { return entity; }
1389 return { ...entity, skullValue: known.skullValue | 0 };
1390 });
1391 return { ...snapshot, entities, staticOnly };
1392 });
1393 }
1394
1395 snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
1396 {
1397 const dim = normalizeDimensionId(dimensionId);
1398 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim));
1399 if (owner == null)
1400 { return this.#syntheticSnapshot(chunkX, chunkY, dim); }
1401 return this.workers[owner].call({
1402 type: WorkerMessage.snapshotChunk,
1403 chunkX,
1404 chunkY,
1405 dimensionId: dim,
1406 staticOnly: !!staticOnly
1407 });
1408 }
1409
1410 findOpenSpawn ()
1411 {
1412 const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID);
1413 for (const coord of coords)
1414 {
1415 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID);
1416 if (!data.open)
1417 { continue; }
1418 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1419 {
1420 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1421 {
1422 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
1423 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
1424 if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID))
1425 { return { tileX, tileY, dimensionId: OVERWORLD_ID }; }
1426 }
1427 }
1428 }
1429 return null;
1430 }
1431
1432 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
1433 #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID)
1434 {
1435 const dim = normalizeDimensionId(dimensionId);
1436 return this.#findNearbyEnterable(tileX, tileY, radius, dim)
1437 ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn());
1438 }
1439
1440 #isDimensionUsable (dimensionId)
1441 {
1442 const dim = normalizeDimensionId(dimensionId);
1443 if (dim === OVERWORLD_ID)
1444 { return true; }
1445 const record = this.getDimensionRecord(dim);
1446 if (!record)
1447 { return false; }
1448 if (record.deletedAt != null)
1449 { return false; }
1450 if (record.purgeAfter != null && record.purgeAfter <= this.now)
1451 { return false; }
1452 return true;
1453 }
1454
1455 #loadDimensionsCache ()
1456 {
1457 const map = new Map();
1458 for (const dim of this.worldDb.listDimensions(this.activeRevisionId))
1459 { map.set(dim.dimensionId, dim); }
1460 if (!map.has(OVERWORLD_ID))
1461 {
1462 map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, {
1463 defaultGroundTypeId: this.settings.defaultGroundTypeId
1464 }));
1465 }
1466 return map;
1467 }
1468
1469 getDimensionRecord (dimensionId)
1470 {
1471 const dim = normalizeDimensionId(dimensionId);
1472 return this.dimensions?.get(dim)
1473 ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim)
1474 ?? (dim === OVERWORLD_ID
1475 ? defaultDimensionRecord(OVERWORLD_ID, {
1476 defaultGroundTypeId: this.settings.defaultGroundTypeId
1477 })
1478 : null);
1479 }
1480
1481 listDimensionRecords ()
1482 {
1483 return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))];
1484 }
1485
1486 #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID)
1487 {
1488 const dim = normalizeDimensionId(dimensionId);
1489 for (let radius = 0; radius <= maxRadius; radius++)
1490 {
1491 for (let dy = -radius; dy <= radius; dy++)
1492 {
1493 for (let dx = -radius; dx <= radius; dx++)
1494 {
1495 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1496 { continue; }
1497 const tileX = originX + dx;
1498 const tileY = originY + dy;
1499 if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim))
1500 { return { tileX, tileY, dimensionId: dim }; }
1501 }
1502 }
1503 }
1504 return null;
1505 }
1506
1507 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1508 {
1509 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1510 if (!data.open)
1511 { return false; }
1512 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1513 }
1514
1515 debugWorld ()
1516 {
1517 const loaders = this.#allLoaders();
1518 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1519 const simulatingChunks = [...chunkSim.entries()]
1520 .filter(([, count]) => count > 0)
1521 .map(([key]) => key)
1522 .sort();
1523 return {
1524 tickIndex: this.tickIndex,
1525 workerCount: this.workers.length,
1526 workerMode: this.workerMode,
1527 simulatingChunks,
1528 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
1529 ...parseRegionKey(key),
1530 workerId,
1531 state: REGION_RUNTIME_STATE.resident,
1532 refs: regionRes.get(key) ?? 0,
1533 graceUntil: this.regionGraceUntil.get(key) ?? null
1534 })),
1535 entities: [...this.directory.values()].map((entity) => ({
1536 entityId: entity.entityId,
1537 workerId: entity.workerId,
1538 tileX: entity.tileX,
1539 tileY: entity.tileY,
1540 characterId: entity.characterId
1541 }))
1542 };
1543 }
1544
1545 async shutdown ()
1546 {
1547 for (const characterId of [...this.characterEntities.keys()])
1548 { this.despawnCharacter(characterId); }
1549 this.forceUnloadAll();
1550 await Promise.all(this.workers.map((worker) => worker.terminate()));
1551 }
1552
1553 forceUnloadAll ()
1554 {
1555 for (const key of [...this.regionOwner.keys()])
1556 {
1557 const { regionX, regionY } = parseRegionKey(key);
1558 this.#unloadRegion(regionX, regionY);
1559 }
1560 }
1561
1562 #configureWorkers ()
1563 {
1564 for (const worker of this.workers)
1565 {
1566 worker.call({
1567 type: WorkerMessage.configure,
1568 settings: this.settings,
1569 activeRevisionId: this.activeRevisionId
1570 });
1571 }
1572 }
1573
1574 #routeCommand (item)
1575 {
1576 if (item.command.type === "respawn")
1577 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1578 const routedCharacterId = item.command.characterId | 0;
1579 if (routedCharacterId && this.stateDb.getCharacter(routedCharacterId)?.is_dead)
1580 {
1581 // Queued intents after death (drop/use/send/craft/…) are discarded.
1582 return [];
1583 }
1584 if (item.command.type === "pray-at-altar")
1585 {
1586 return this.#prayAtAltar(
1587 item.sessionId,
1588 item.command.characterId,
1589 item.command.tileX,
1590 item.command.tileY
1591 );
1592 }
1593 if (item.command.type === "enter-doorway")
1594 {
1595 return this.#relocateCharacterThroughDoorway(
1596 item.sessionId,
1597 item.command.characterId,
1598 item.command.tileX,
1599 item.command.tileY
1600 );
1601 }
1602 if (
1603 item.command.type === "open-market"
1604 || item.command.type === "place-market-sell"
1605 || item.command.type === "place-market-buy"
1606 || item.command.type === "cancel-market-order"
1607 || item.command.type === "close-market"
1608 )
1609 {
1610 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1611 return result?.events ?? [];
1612 }
1613 if (
1614 item.command.type === "trade-request"
1615 || item.command.type === "trade-respond-invite"
1616 || item.command.type === "trade-offer-set"
1617 || item.command.type === "trade-offer-remove"
1618 || item.command.type === "trade-accept"
1619 || item.command.type === "trade-cancel"
1620 )
1621 {
1622 const result = this.trade.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1623 return result?.events ?? [];
1624 }
1625 if (
1626 item.command.type === "open-bounty"
1627 || item.command.type === "raise-bounty"
1628 || item.command.type === "pay-bounty"
1629 || item.command.type === "get-character-bounty"
1630 || item.command.type === "close-bounty"
1631 )
1632 {
1633 const result = this.bounty.handleCommand(item.sessionId, item.command);
1634 return result?.events ?? [];
1635 }
1636 if (
1637 item.command.type === "open-barber"
1638 || item.command.type === "set-hair"
1639 || item.command.type === "close-barber"
1640 )
1641 {
1642 const result = this.barber.handleCommand(item.sessionId, item.command);
1643 return result?.events ?? [];
1644 }
1645 if (
1646 item.command.type === "dialogue-choose"
1647 || item.command.type === "dialogue-advance"
1648 || item.command.type === "close-dialogue"
1649 || item.command.type === "request-quests"
1650 )
1651 { return this.#handleQuestCommand(item); }
1652 const entityId = this.characterEntities.get(item.command.characterId);
1653 const record = entityId ? this.directory.get(entityId) : null;
1654 if (!record)
1655 {
1656 const error = new Error("Character is not in the world.");
1657 error.userFacing = true;
1658 throw error;
1659 }
1660 if (item.command.type === "drop-item" && item.command.groundItemId == null)
1661 { item.command.groundItemId = this.nextGroundItemId++; }
1662 if (item.command.type === "attack")
1663 {
1664 const targetRecord = this.directory.get(item.command.targetEntityId);
1665 if (!targetRecord)
1666 {
1667 const error = new Error("Target is not here.");
1668 error.userFacing = true;
1669 throw error;
1670 }
1671 const events = this.#finishRoutedCommand(item, record);
1672 if (targetRecord.workerId !== record.workerId)
1673 {
1674 this.workers[targetRecord.workerId].call({
1675 type: WorkerMessage.remoteCombatEngage,
1676 attackerEntityId: record.entityId,
1677 targetEntityId: item.command.targetEntityId,
1678 now: item.receivedAt ?? this.now
1679 });
1680 }
1681 return events;
1682 }
1683 return this.#finishRoutedCommand(item, record);
1684 }
1685
1686 #finishRoutedCommand (item, record)
1687 {
1688 const result = this.workers[record.workerId].call({
1689 type: WorkerMessage.command,
1690 sessionId: item.sessionId,
1691 command: item.command,
1692 now: item.receivedAt ?? this.now
1693 });
1694 const view = this.workers[record.workerId].call({
1695 type: WorkerMessage.inspect,
1696 entityId: record.entityId
1697 });
1698 if (view)
1699 { this.#remember(view, record.workerId); }
1700 if (result?.private)
1701 { this.#saveBagFromView(item.command.characterId, result.private); }
1702 if (result?.appearanceChanged && view)
1703 { this.#queueReplication(replicationAppearance(view)); }
1704 if (result?.remainder)
1705 {
1706 this.stateDb.saveInheritance(
1707 this.stateDb.getCharacter(item.command.characterId).account_id,
1708 { slots: result.remainder }
1709 );
1710 }
1711 for (const event of result?.events ?? [])
1712 { this.#persistGroundEvent(event); }
1713 const events = [];
1714 for (const event of result?.events ?? [])
1715 {
1716 if (event.type === "skills-updated")
1717 {
1718 this.#applySkillsUpdated(event);
1719 events.push(...this.#skillLevelUpEvents(event));
1720 continue;
1721 }
1722 if (event.type === "spells-updated")
1723 {
1724 this.#applySpellsUpdated(event);
1725 continue;
1726 }
1727 if (event.type === "open-dialogue")
1728 {
1729 events.push(...this.#handleOpenDialogue(event));
1730 continue;
1731 }
1732 if (
1733 event.type === "combat-hit"
1734 || event.type === "combat-miss"
1735 || event.type === "combat-block"
1736 || event.type === "combat-swing"
1737 )
1738 { this.#noteCombatEvent(event); }
1739 if (event.type === "player-died")
1740 {
1741 events.push(...this.#applyPlayerDeath(event));
1742 continue;
1743 }
1744 events.push(event);
1745 }
1746 if (item.command.type === "attack" && item.command.targetEntityId != null)
1747 {
1748 this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId);
1749 events.push(...this.#mapQuestPrivateEvents(
1750 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1751 ));
1752 }
1753 if (
1754 (item.command.type === "cast-spell-entity")
1755 && item.command.targetEntityId != null
1756 )
1757 { this.#notePlayerAttack(item.command.characterId, item.command.targetEntityId); }
1758 if (result?.private)
1759 {
1760 events.push({
1761 type: "inventory",
1762 sessionId: item.sessionId,
1763 bank: !!result.bank,
1764 cauldron: result.cauldron,
1765 cauldronState: result.cauldronState ?? null,
1766 alchemyResult: result.alchemyResult ?? null,
1767 dyeConfirm: result.dyeConfirm ?? null,
1768 ...result.private
1769 });
1770 }
1771 if (result?.statusEffectsChanged && view)
1772 {
1773 events.push({
1774 type: "status-effects",
1775 sessionId: item.sessionId,
1776 characterId: view.characterId ?? item.command.characterId,
1777 effects: view.statusEffects ?? [],
1778 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
1779 });
1780 }
1781 if (result?.healthChanged && view)
1782 {
1783 events.push({
1784 type: "entity-health",
1785 entityId: view.entityId,
1786 characterId: view.characterId ?? item.command.characterId,
1787 health: view.health,
1788 maxHealth: view.maxHealth,
1789 tileX: view.tileX,
1790 tileY: view.tileY
1791 });
1792 }
1793 return events;
1794 }
1795
1796 #applyRemoteMelee (payload)
1797 {
1798 const targetRecord = this.directory.get(payload.targetId);
1799 if (!targetRecord)
1800 { return []; }
1801 const result = this.workers[targetRecord.workerId].call({
1802 ...payload,
1803 type: WorkerMessage.applyRemoteMelee
1804 });
1805 const events = [];
1806 for (const event of result?.events ?? [])
1807 {
1808 if (event.type === "entity-despawn")
1809 { this.#forget(event.entityId); }
1810 if (event.type === "skills-updated")
1811 {
1812 this.#applySkillsUpdated(event);
1813 events.push(...this.#skillLevelUpEvents(event));
1814 continue;
1815 }
1816 if (event.type === "spells-updated")
1817 {
1818 this.#applySpellsUpdated(event);
1819 continue;
1820 }
1821 if (event.type === "player-died")
1822 {
1823 events.push(...this.#applyPlayerDeath(event));
1824 continue;
1825 }
1826 if (
1827 event.type === "combat-hit"
1828 || event.type === "combat-miss"
1829 || event.type === "combat-block"
1830 || event.type === "combat-swing"
1831 )
1832 { this.#noteCombatEvent(event); }
1833 if (event.type === "mob-killed")
1834 {
1835 events.push(...this.#applyMobKilled(event));
1836 continue;
1837 }
1838 this.#persistGroundEvent(event);
1839 if (event.type !== "skills-updated")
1840 { events.push(event); }
1841 }
1842 for (const forward of result?.forwards ?? [])
1843 {
1844 if (forward.type !== "forward-combat-xp")
1845 { continue; }
1846 const attackerRecord = this.directory.get(forward.entityId);
1847 if (!attackerRecord)
1848 { continue; }
1849 const xpResult = this.workers[attackerRecord.workerId].call({
1850 type: WorkerMessage.applyCombatHitXp,
1851 entityId: forward.entityId,
1852 profile: forward.profile,
1853 damage: forward.damage
1854 });
1855 for (const xpEvent of xpResult?.events ?? [])
1856 {
1857 if (xpEvent.type === "skills-updated")
1858 {
1859 this.#applySkillsUpdated(xpEvent);
1860 events.push(...this.#skillLevelUpEvents(xpEvent));
1861 continue;
1862 }
1863 events.push(xpEvent);
1864 }
1865 }
1866 return events;
1867 }
1868
1869 #applyRemoteRanged (payload)
1870 {
1871 const targetRecord = this.directory.get(payload.targetId);
1872 if (!targetRecord)
1873 { return []; }
1874 const result = this.workers[targetRecord.workerId].call({
1875 ...payload,
1876 type: WorkerMessage.applyRemoteRanged
1877 });
1878 const events = [];
1879 for (const event of result?.events ?? [])
1880 {
1881 if (event.type === "entity-despawn")
1882 { this.#forget(event.entityId); }
1883 if (event.type === "skills-updated")
1884 {
1885 this.#applySkillsUpdated(event);
1886 events.push(...this.#skillLevelUpEvents(event));
1887 continue;
1888 }
1889 if (event.type === "spells-updated")
1890 {
1891 this.#applySpellsUpdated(event);
1892 continue;
1893 }
1894 if (event.type === "player-died")
1895 {
1896 events.push(...this.#applyPlayerDeath(event));
1897 continue;
1898 }
1899 if (
1900 event.type === "combat-hit"
1901 || event.type === "combat-miss"
1902 || event.type === "combat-block"
1903 || event.type === "combat-swing"
1904 )
1905 { this.#noteCombatEvent(event); }
1906 if (event.type === "mob-killed")
1907 {
1908 events.push(...this.#applyMobKilled(event));
1909 continue;
1910 }
1911 this.#persistGroundEvent(event);
1912 if (event.type !== "skills-updated")
1913 { events.push(event); }
1914 }
1915 for (const forward of result?.forwards ?? [])
1916 {
1917 if (forward.type !== "forward-combat-xp")
1918 { continue; }
1919 const attackerRecord = this.directory.get(forward.entityId);
1920 if (!attackerRecord)
1921 { continue; }
1922 const xpResult = this.workers[attackerRecord.workerId].call({
1923 type: WorkerMessage.applyCombatHitXp,
1924 entityId: forward.entityId,
1925 profile: forward.profile,
1926 damage: forward.damage
1927 });
1928 for (const xpEvent of xpResult?.events ?? [])
1929 {
1930 if (xpEvent.type === "skills-updated")
1931 {
1932 this.#applySkillsUpdated(xpEvent);
1933 events.push(...this.#skillLevelUpEvents(xpEvent));
1934 continue;
1935 }
1936 events.push(xpEvent);
1937 }
1938 }
1939 return events;
1940 }
1941
1942 #handleQuestCommand (item)
1943 {
1944 const characterId = item.command.characterId | 0;
1945 const sessionId = item.sessionId;
1946 if (!this.quests)
1947 { return []; }
1948 if (item.command.type === "request-quests")
1949 {
1950 const events = [];
1951 const playerView = this.quests.playerViewFor(characterId);
1952 this.quests.ensureInitialQuests(characterId, playerView, events);
1953 // Objectives like hasItem only update when re-checked; refresh on open.
1954 this.quests.reevaluateQuests(characterId, playerView, events);
1955 const out = this.#mapQuestPrivateEvents(events, sessionId, characterId);
1956 if (!out.some((event) => event.type === "quests-snapshot"))
1957 {
1958 const snap = this.quests.questSnapshot(characterId);
1959 out.push({ type: "quests-snapshot", sessionId, characterId, ...snap });
1960 }
1961 return out;
1962 }
1963 if (item.command.type === "close-dialogue")
1964 {
1965 const closed = this.quests.closeDialogue(characterId, "client");
1966 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1967 }
1968 if (item.command.type === "dialogue-choose")
1969 {
1970 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1971 if (!result.ok)
1972 {
1973 const error = new Error(result.error || "Choice failed.");
1974 error.userFacing = true;
1975 throw error;
1976 }
1977 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1978 }
1979 if (item.command.type === "dialogue-advance")
1980 {
1981 const result = this.quests.advanceDialogue(characterId);
1982 if (!result.ok)
1983 {
1984 const error = new Error(result.error || "Cannot advance.");
1985 error.userFacing = true;
1986 throw error;
1987 }
1988 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1989 }
1990 return [];
1991 }
1992
1993 #handleOpenDialogue (event)
1994 {
1995 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1996 if (!result.ok)
1997 {
1998 return [{
1999 type: "toast",
2000 characterId: event.characterId,
2001 sessionId: event.sessionId,
2002 message: result.error || "Nothing to say."
2003 }];
2004 }
2005 this.#pinDialogueNpc(event.entityId, event.characterId);
2006 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
2007 }
2008
2009 #pinDialogueNpc (entityId, characterId)
2010 {
2011 const record = this.directory.get(entityId | 0);
2012 if (!record)
2013 { return; }
2014 this.workers[record.workerId]?.call?.({
2015 type: WorkerMessage.pinDialogue,
2016 entityId: entityId | 0,
2017 characterId: characterId | 0
2018 });
2019 }
2020
2021 #unpinDialogueNpc (entityId, characterId)
2022 {
2023 const record = this.directory.get(entityId | 0);
2024 if (!record)
2025 { return; }
2026 this.workers[record.workerId]?.call?.({
2027 type: WorkerMessage.unpinDialogue,
2028 entityId: entityId | 0,
2029 characterId: characterId | 0
2030 });
2031 }
2032
2033 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
2034 {
2035 const out = [];
2036 let needSnapshot = false;
2037 const snapshotCharacterIds = new Set();
2038 const syncAccessIds = new Set();
2039 for (const event of events ?? [])
2040 {
2041 const cid = event.characterId ?? characterId;
2042 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
2043 if (event.type === "dialogueStep")
2044 {
2045 if (cid != null)
2046 { syncAccessIds.add(cid | 0); }
2047 out.push({
2048 type: "dialogue-step",
2049 sessionId: sid,
2050 characterId: cid,
2051 dialogueId: event.dialogueId,
2052 stepId: event.stepId,
2053 label: event.label,
2054 npcEntityId: event.npcEntityId,
2055 lines: event.lines
2056 });
2057 }
2058 else if (event.type === "dialogueChoices")
2059 {
2060 if (cid != null)
2061 { syncAccessIds.add(cid | 0); }
2062 out.push({
2063 type: "dialogue-choices",
2064 sessionId: sid,
2065 characterId: cid,
2066 dialogueId: event.dialogueId,
2067 stepId: event.stepId,
2068 npcEntityId: event.npcEntityId,
2069 triggers: event.triggers
2070 });
2071 }
2072 else if (event.type === "dialogueItemRewards")
2073 {
2074 out.push({
2075 type: "dialogue-item-rewards",
2076 sessionId: sid,
2077 characterId: cid,
2078 dialogueId: event.dialogueId,
2079 stepId: event.stepId,
2080 npcEntityId: event.npcEntityId,
2081 messages: event.messages ?? []
2082 });
2083 }
2084 else if (event.type === "dialogueClose")
2085 {
2086 if (event.npcEntityId != null && cid != null)
2087 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
2088 out.push({
2089 type: "dialogue-close",
2090 sessionId: sid,
2091 characterId: cid,
2092 reason: event.reason
2093 });
2094 }
2095 else if (event.type === "questStepComplete")
2096 {
2097 out.push({
2098 type: "quest-step-complete",
2099 sessionId: sid,
2100 characterId: cid,
2101 questId: event.questId,
2102 title: event.title
2103 });
2104 needSnapshot = true;
2105 }
2106 else if (event.type === "questObjectiveComplete")
2107 {
2108 out.push({
2109 type: "quest-objective-complete",
2110 sessionId: sid,
2111 characterId: cid,
2112 questId: event.questId,
2113 objectiveId: event.objectiveId,
2114 text: event.text
2115 });
2116 }
2117 else if (event.type === "questsDirty")
2118 {
2119 needSnapshot = true;
2120 if (cid != null)
2121 { snapshotCharacterIds.add(cid | 0); }
2122 }
2123 else if (event.type === "inventoryDirty" && cid != null)
2124 {
2125 const onlineId = this.characterEntities.get(cid | 0);
2126 if (onlineId)
2127 {
2128 const live = this.bagOf(onlineId);
2129 if (live)
2130 { this.pushInventory(cid, live); }
2131 }
2132 }
2133 else if (event.type === "skillsDirty" && cid != null)
2134 { this.syncCharacterSkillsFromDb(cid); }
2135 else if (event.type === "questComplete")
2136 {
2137 out.push({
2138 type: "quest-complete",
2139 sessionId: sid,
2140 characterId: cid,
2141 questId: event.questId,
2142 title: event.title,
2143 xp: event.xp ?? [],
2144 items: event.items ?? []
2145 });
2146 needSnapshot = true;
2147 }
2148 }
2149 if (needSnapshot)
2150 {
2151 if (characterId != null)
2152 { snapshotCharacterIds.add(characterId | 0); }
2153 for (const snapCharacterId of snapshotCharacterIds)
2154 {
2155 const snap = this.quests.questSnapshot(snapCharacterId);
2156 out.push({
2157 type: "quests-snapshot",
2158 sessionId: sessionId ?? this.#sessionIdForCharacter(snapCharacterId),
2159 characterId: snapCharacterId,
2160 ...snap
2161 });
2162 syncAccessIds.add(snapCharacterId | 0);
2163 }
2164 }
2165 for (const id of syncAccessIds)
2166 { this.syncCharacterConditionAccess(id); }
2167 return out;
2168 }
2169
2170 #sessionIdForCharacter (characterId)
2171 {
2172 const entityId = this.characterEntities.get(characterId | 0);
2173 const record = entityId != null ? this.directory.get(entityId) : null;
2174 return record?.sessionId ?? null;
2175 }
2176
2177 #applyMobKilled (event)
2178 {
2179 const out = [event];
2180 const attackerRecord = this.directory.get(event.attackerId);
2181 const killerCharacterId = attackerRecord?.characterId ?? null;
2182 const killerPos = attackerRecord
2183 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
2184 : null;
2185 if (killerCharacterId && this.quests)
2186 {
2187 // Pass characterId so questsDirty produces a quests-snapshot for the killer.
2188 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
2189 mobTypeId: event.mobTypeId,
2190 spawnerId: event.spawnerId
2191 }), null, killerCharacterId));
2192 }
2193 out.push(...this.#mapQuestPrivateEvents(
2194 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
2195 ));
2196 let bountyAwarded = 0;
2197 if (killerCharacterId && (event.bounty | 0) > 0)
2198 {
2199 bountyAwarded = event.bounty | 0;
2200 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
2201 this.refreshCharacterSkull(killerCharacterId);
2202 out.push({
2203 type: "toast",
2204 characterId: killerCharacterId,
2205 message: `Bounty +${bountyAwarded} (total ${total})`
2206 });
2207 }
2208
2209 if (killerCharacterId && killerPos)
2210 {
2211 if (bountyAwarded > 0)
2212 { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }
2213 if (event.townGuard)
2214 { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }
2215 }
2216 return out;
2217 }
2218
2219 /**
2220 * Send up to `count` town guards at the killer. Prefer idle guards.
2221 * When `spawnerId` is set, only that spawner's guards are used.
2222 */
2223 #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)
2224 {
2225 const want = Math.max(0, count | 0);
2226 if (want <= 0 || targetEntityId == null || !killerPos)
2227 { return; }
2228 const candidates = [];
2229 for (const worker of this.workers)
2230 {
2231 const result = worker.call({
2232 type: WorkerMessage.listTownGuardsNear,
2233 tileX: killerPos.tileX,
2234 tileY: killerPos.tileY,
2235 spawnerId,
2236 limit: 32
2237 });
2238 for (const guard of result?.guards ?? [])
2239 { candidates.push(guard); }
2240 }
2241 candidates.sort((a, b) => Number(a.busy) - Number(b.busy));
2242 let sent = 0;
2243 for (const guard of candidates)
2244 {
2245 if (sent >= want)
2246 { break; }
2247 if (guard.entityId === targetEntityId)
2248 { continue; }
2249 const record = this.directory.get(guard.entityId);
2250 if (!record)
2251 { continue; }
2252 this.workers[record.workerId].call({
2253 type: WorkerMessage.engageTarget,
2254 attackerEntityId: guard.entityId,
2255 targetEntityId,
2256 now: this.now
2257 });
2258 sent += 1;
2259 }
2260 }
2261
2262 #applyPlayerDeath (event)
2263 {
2264 const record = this.directory.get(event.entityId);
2265 if (!record)
2266 { return [event]; }
2267 this.stateDb.setCharacterDead(event.characterId, true);
2268 this.stateDb.saveCharacterPosition(
2269 event.characterId,
2270 event.tileX,
2271 event.tileY,
2272 record.gait ?? GAIT.walk,
2273 record.dimensionId ?? OVERWORLD_ID
2274 );
2275 this.bounty?.settleKill(
2276 event.characterId,
2277 event.attackerId,
2278 event.tileX,
2279 event.tileY,
2280 record.dimensionId ?? OVERWORLD_ID
2281 );
2282 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
2283 const killerCharacterId = Number(attackerRecord?.characterId) || 0;
2284 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
2285 { this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now); }
2286 const events = [event];
2287 const closedDialogue = this.quests?.closeDialogue(event.characterId, "death");
2288 if (closedDialogue?.events?.length)
2289 {
2290 events.push(...this.#mapQuestPrivateEvents(
2291 closedDialogue.events,
2292 event.sessionId,
2293 event.characterId
2294 ));
2295 }
2296 if (event.sessionId != null)
2297 {
2298 for (const commandType of ["cancel-craft", "cauldron-close"])
2299 {
2300 try
2301 {
2302 this.workers[record.workerId].call({
2303 type: WorkerMessage.command,
2304 sessionId: event.sessionId,
2305 command: { type: commandType, characterId: event.characterId },
2306 now: this.now
2307 });
2308 }
2309 catch
2310 { /* best-effort session cleanup */ }
2311 }
2312 }
2313 // Bounty is cleared instantly on non-friend PvP death; only kill-counter decays over time.
2314 const victimSkull = this.refreshCharacterSkull(event.characterId, { force: true });
2315 if (victimSkull)
2316 { events.push(victimSkull); }
2317 for (const worker of this.workers)
2318 {
2319 worker.call({
2320 type: WorkerMessage.clearCombat,
2321 entityId: event.entityId,
2322 targetEntityId: event.entityId
2323 });
2324 }
2325 const victimName = `${record.firstName ?? "someone"} ${record.lastName ?? ""}`.trim()
2326 || "someone";
2327 const killerName = `${attackerRecord?.firstName ?? ""} ${attackerRecord?.lastName ?? ""}`.trim()
2328 || "someone";
2329 const corpseOrigin = lootOrigin(victimName, killerName);
2330 const result = this.workers[record.workerId].call({
2331 type: WorkerMessage.spawnCorpseDrops,
2332 characterId: event.characterId,
2333 tileX: event.tileX,
2334 tileY: event.tileY,
2335 dimensionId: record.dimensionId ?? OVERWORLD_ID,
2336 now: this.now,
2337 dropCarriedCoins: true,
2338 coinGroundItemId: this.nextGroundItemId++,
2339 drops: [
2340 {
2341 groundItemId: this.nextGroundItemId++,
2342 stack: attachOrigins({
2343 itemId: ItemId.bones,
2344 quantity: 1,
2345 origins: [{ origin: corpseOrigin, quantity: 1 }]
2346 })
2347 },
2348 {
2349 groundItemId: this.nextGroundItemId++,
2350 stack: attachOrigins({
2351 itemId: ItemId.skull,
2352 quantity: 1,
2353 origins: [{ origin: corpseOrigin, quantity: 1 }]
2354 })
2355 }
2356 ]
2357 });
2358 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
2359 {
2360 const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true });
2361 if (skullEvent)
2362 { events.push(skullEvent); }
2363 }
2364 events.push({
2365 type: "entity-despawn",
2366 entityId: event.entityId,
2367 tileX: event.tileX,
2368 tileY: event.tileY,
2369 dimensionId: record.dimensionId ?? OVERWORLD_ID,
2370 cause: "death"
2371 });
2372 for (const dropEvent of result?.events ?? [])
2373 {
2374 this.#persistGroundEvent(dropEvent);
2375 events.push(dropEvent);
2376 }
2377 if (result?.private)
2378 {
2379 this.#saveBagFromView(event.characterId, result.private);
2380 if (event.sessionId != null)
2381 {
2382 events.push({
2383 type: "inventory",
2384 sessionId: event.sessionId,
2385 ...result.private
2386 });
2387 }
2388 }
2389 const coinsDropped = coinsDroppedFromDeathEvents(events);
2390 if (this.combatLogouts.has(event.characterId | 0))
2391 { events.push(...this.#finishCombatLogoutDeath(event, coinsDropped)); }
2392 return events;
2393 }
2394
2395 #finishCombatLogoutDeath (event, coinsDropped)
2396 {
2397 const characterId = event.characterId | 0;
2398 const logout = this.combatLogouts.get(characterId);
2399 const events = [];
2400 if (logout?.pendingCowardice)
2401 {
2402 applyCombatLogoutCowardice(this, characterId, {
2403 coinsDropped,
2404 now: this.now
2405 });
2406 }
2407 const deathRecord = this.directory.get(event.entityId);
2408 const deathDimensionId = normalizeDimensionId(
2409 deathRecord?.dimensionId ?? event.dimensionId ?? OVERWORLD_ID
2410 );
2411 dispatchChurchOfflineResurrectionLetter(
2412 this,
2413 characterId,
2414 event.tileX | 0,
2415 event.tileY | 0,
2416 deathDimensionId
2417 );
2418 try
2419 { events.push(...this.#respawnCharacter(event.sessionId ?? null, characterId)); }
2420 catch
2421 {
2422 // Respawn can fail without an altar tile; still despawn the corpse session.
2423 }
2424 this.#restoreCombatLogoutAutoCast(characterId, logout);
2425 this.combatLogouts.delete(characterId);
2426 this.combatTracking.delete(characterId);
2427 this.despawnCharacter(characterId);
2428 return events;
2429 }
2430
2431 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
2432 {
2433 const entityId = this.characterEntities.get(characterId);
2434 const record = entityId ? this.directory.get(entityId) : null;
2435 if (!record)
2436 {
2437 const error = new Error("Character is not in the world.");
2438 error.userFacing = true;
2439 throw error;
2440 }
2441 const tileX = doorwayTileX | 0;
2442 const tileY = doorwayTileY | 0;
2443 if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY))
2444 {
2445 const error = new Error("You are too far from that doorway.");
2446 error.userFacing = true;
2447 throw error;
2448 }
2449 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2450 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
2451 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
2452 if (block?.typeId !== BlockType.doorway)
2453 {
2454 const error = new Error("There is no doorway there.");
2455 error.userFacing = true;
2456 throw error;
2457 }
2458 const config = block.config && typeof block.config === "object" ? block.config : null;
2459 const targetRaw = config?.targetDimensionId;
2460 if (targetRaw == null || String(targetRaw).trim() === "")
2461 {
2462 const error = new Error("That doorway leads nowhere.");
2463 error.userFacing = true;
2464 throw error;
2465 }
2466 const targetDimensionId = normalizeDimensionId(targetRaw);
2467 const destTileX = Number(config.tileX);
2468 const destTileY = Number(config.tileY);
2469 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
2470 {
2471 const error = new Error("That doorway leads nowhere.");
2472 error.userFacing = true;
2473 throw error;
2474 }
2475 const destX = destTileX | 0;
2476 const destY = destTileY | 0;
2477 if (!this.#isDimensionUsable(targetDimensionId))
2478 {
2479 const error = new Error("That place is no longer reachable.");
2480 error.userFacing = true;
2481 throw error;
2482 }
2483 if (!this.isEnterable(destX, destY, targetDimensionId))
2484 {
2485 const error = new Error("The other side is blocked.");
2486 error.userFacing = true;
2487 throw error;
2488 }
2489
2490 const events = [];
2491 if (this.quests)
2492 {
2493 const closed = this.quests.closeDialogue(characterId, "doorway");
2494 if (closed?.events?.length)
2495 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
2496 }
2497
2498 const loader = { ...DEFAULT_CHUNK_LOADER };
2499 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
2500 const result = this.workers[record.workerId].call({
2501 type: WorkerMessage.relocateEntity,
2502 entityId,
2503 tileX: destX,
2504 tileY: destY,
2505 dimensionId: targetDimensionId
2506 });
2507 if (!result?.accepted)
2508 {
2509 const error = new Error("Could not enter that doorway.");
2510 error.userFacing = true;
2511 throw error;
2512 }
2513 let moveEvents = [];
2514 if (result.transferRequest)
2515 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
2516 else if (result.event)
2517 {
2518 this.#applyMoveToDirectory(result.event);
2519 moveEvents = [result.event];
2520 const view = this.workers[record.workerId].call({
2521 type: WorkerMessage.inspect,
2522 entityId
2523 });
2524 if (view)
2525 { this.#remember(view, record.workerId); }
2526 }
2527 if (!moveEvents.length)
2528 {
2529 const error = new Error("Could not enter that doorway.");
2530 error.userFacing = true;
2531 throw error;
2532 }
2533 this.stateDb.saveCharacterPosition(
2534 characterId,
2535 destX,
2536 destY,
2537 record.gait ?? GAIT.walk,
2538 targetDimensionId
2539 );
2540 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
2541 this.syncCharacterConditionAccess(characterId);
2542 this.#recalculateActivation(this.now);
2543 this.#syncGhosts();
2544 const dimRecord = this.getDimensionRecord(targetDimensionId);
2545 events.push(...moveEvents, {
2546 type: "dimension-changed",
2547 sessionId,
2548 characterId,
2549 entityId,
2550 dimensionId: targetDimensionId,
2551 tileX: destX,
2552 tileY: destY,
2553 lightingMode: dimRecord?.lightingMode ?? "dayNight",
2554 seasonMode: dimRecord?.seasonMode ?? "auto"
2555 });
2556 return events;
2557 }
2558
2559 #prayAtAltar (sessionId, characterId, altarTileX, altarTileY)
2560 {
2561 const entityId = this.characterEntities.get(characterId);
2562 const record = entityId ? this.directory.get(entityId) : null;
2563 if (!record)
2564 {
2565 const error = new Error("Character is not in the world.");
2566 error.userFacing = true;
2567 throw error;
2568 }
2569 const tileX = altarTileX | 0;
2570 const tileY = altarTileY | 0;
2571 if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY))
2572 {
2573 const error = new Error("You are too far from that altar.");
2574 error.userFacing = true;
2575 throw error;
2576 }
2577 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2578 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2579 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
2580 if (block?.typeId !== BlockType.churchAltar)
2581 {
2582 const error = new Error("There is no altar there.");
2583 error.userFacing = true;
2584 throw error;
2585 }
2586 this.stateDb.setCharacterRespawnAltar(characterId, tileX, tileY, dimensionId);
2587 return [{
2588 type: "toast",
2589 sessionId,
2590 characterId,
2591 message: "Altar set as respawn point."
2592 }];
2593 }
2594
2595 #respawnCharacter (sessionId, characterId)
2596 {
2597 const row = this.stateDb.getCharacter(characterId);
2598 if (!row?.is_dead)
2599 {
2600 const error = new Error("You are not dead.");
2601 error.userFacing = true;
2602 throw error;
2603 }
2604 const entityId = this.characterEntities.get(characterId);
2605 const record = entityId ? this.directory.get(entityId) : null;
2606 if (!record)
2607 {
2608 const error = new Error("Character is not in the world.");
2609 error.userFacing = true;
2610 throw error;
2611 }
2612 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2613 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId, characterId);
2614 if (!destination)
2615 {
2616 const error = new Error("No open tile is available for respawn.");
2617 error.userFacing = true;
2618 throw error;
2619 }
2620 const destDimensionId = normalizeDimensionId(destination.dimensionId ?? fromDimensionId);
2621 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2622 const loader = { ...DEFAULT_CHUNK_LOADER };
2623 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destDimensionId);
2624 const result = this.workers[record.workerId].call({
2625 type: WorkerMessage.applyRespawn,
2626 entityId,
2627 sessionId,
2628 tileX: destination.tileX,
2629 tileY: destination.tileY,
2630 dimensionId: destDimensionId,
2631 maxHealth: playerMaxHealth(skills),
2632 maxStamina: playerMaxStamina(skills)
2633 });
2634 if (!result?.accepted)
2635 {
2636 const error = new Error("That respawn tile is no longer available.");
2637 error.userFacing = true;
2638 throw error;
2639 }
2640 let moveEvents = [];
2641 if (result.transferRequest)
2642 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
2643 else if (result.event)
2644 {
2645 this.#applyMoveToDirectory(result.event);
2646 moveEvents = [result.event];
2647 const view = this.workers[record.workerId].call({
2648 type: WorkerMessage.inspect,
2649 entityId
2650 });
2651 if (view)
2652 { this.#remember(view, record.workerId); }
2653 }
2654 if (!moveEvents.length)
2655 {
2656 const error = new Error("Respawn transfer failed.");
2657 error.userFacing = true;
2658 throw error;
2659 }
2660 this.stateDb.setCharacterDead(characterId, false);
2661 const respawnHealth = playerMaxHealth(skills);
2662 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
2663 this.stateDb.saveCharacterPosition(
2664 characterId,
2665 destination.tileX,
2666 destination.tileY,
2667 record.gait ?? GAIT.walk,
2668 destDimensionId
2669 );
2670 if (destination.altar)
2671 {
2672 this.stateDb.setCharacterRespawnAltar(
2673 characterId,
2674 destination.altar.tileX,
2675 destination.altar.tileY,
2676 destination.altar.dimensionId
2677 );
2678 }
2679 this.stateDb.markDimensionVisited(characterId, destDimensionId);
2680 this.syncCharacterConditionAccess(characterId);
2681 this.#recalculateActivation(this.now);
2682 this.#syncGhosts();
2683 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2684 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2685 const after = this.directory.get(entityId);
2686 const inspectWorkerId = after?.workerId ?? record.workerId;
2687 const spawnView = this.workers[inspectWorkerId].call({
2688 type: WorkerMessage.inspect,
2689 entityId
2690 });
2691 const spawn = spawnView
2692 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2693 : null;
2694 const events = [
2695 ...moveEvents,
2696 ...(spawn ? [spawn] : []),
2697 ...(skullEvent ? [skullEvent] : []),
2698 {
2699 type: "player-respawned",
2700 entityId,
2701 characterId,
2702 sessionId,
2703 tileX: destination.tileX,
2704 tileY: destination.tileY,
2705 dimensionId: destDimensionId,
2706 health: playerMaxHealth(skills),
2707 maxHealth: playerMaxHealth(skills),
2708 stamina: playerMaxStamina(skills),
2709 maxStamina: playerMaxStamina(skills),
2710 skullValue: skullPoints
2711 }
2712 ];
2713 if (destDimensionId !== fromDimensionId)
2714 {
2715 const dimRecord = this.getDimensionRecord(destDimensionId);
2716 events.push({
2717 type: "dimension-changed",
2718 sessionId,
2719 characterId,
2720 entityId,
2721 dimensionId: destDimensionId,
2722 tileX: destination.tileX,
2723 tileY: destination.tileY,
2724 lightingMode: dimRecord?.lightingMode ?? "dayNight",
2725 seasonMode: dimRecord?.seasonMode ?? "auto"
2726 });
2727 }
2728 return events;
2729 }
2730
2731 #refreshAltarIndex ()
2732 {
2733 const altars = [];
2734 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
2735 {
2736 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
2737 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
2738 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2739 {
2740 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2741 {
2742 const block = data.blocks[localY * CHUNK_SIZE + localX];
2743 if (block?.typeId !== BlockType.churchAltar)
2744 { continue; }
2745 altars.push({
2746 tileX: coord.chunk_x * CHUNK_SIZE + localX,
2747 tileY: coord.chunk_y * CHUNK_SIZE + localY,
2748 dimensionId: dim
2749 });
2750 }
2751 }
2752 }
2753 this.altarTiles = altars;
2754 }
2755
2756 #chebyshevDistance (originX, originY, tileX, tileY)
2757 {
2758 return Math.max(Math.abs(tileX - originX), Math.abs(tileY - originY));
2759 }
2760
2761 #sortAltarsByDistance (altars, originX, originY)
2762 {
2763 return [...altars].sort((left, right) =>
2764 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2765 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2766 );
2767 }
2768
2769 #findAdjacentOpenToAltar (altar, originX, originY, entityId)
2770 {
2771 const dimensionId = normalizeDimensionId(altar.dimensionId ?? OVERWORLD_ID);
2772 const adjacent = [];
2773 for (let dy = -1; dy <= 1; dy++)
2774 {
2775 for (let dx = -1; dx <= 1; dx++)
2776 {
2777 if (dx === 0 && dy === 0)
2778 { continue; }
2779 adjacent.push({
2780 tileX: altar.tileX + dx,
2781 tileY: altar.tileY + dy,
2782 dimensionId,
2783 altar: {
2784 tileX: altar.tileX | 0,
2785 tileY: altar.tileY | 0,
2786 dimensionId
2787 }
2788 });
2789 }
2790 }
2791 adjacent.sort((left, right) =>
2792 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2793 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2794 );
2795 return adjacent.find((entry) =>
2796 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2797 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2798 ) ?? null;
2799 }
2800
2801 #findNearestAltarDestination (originX, originY, entityId, preferredDimensionId = null)
2802 {
2803 const preferred = preferredDimensionId != null
2804 ? normalizeDimensionId(preferredDimensionId)
2805 : null;
2806 const preferredAltars = preferred
2807 ? this.altarTiles.filter((altar) =>
2808 normalizeDimensionId(altar.dimensionId) === preferred)
2809 : [];
2810 const otherAltars = preferred
2811 ? this.altarTiles.filter((altar) =>
2812 normalizeDimensionId(altar.dimensionId) !== preferred)
2813 : this.altarTiles;
2814 for (const altar of this.#sortAltarsByDistance(preferredAltars, originX, originY))
2815 {
2816 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2817 if (tile)
2818 { return tile; }
2819 }
2820 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2821 {
2822 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2823 if (tile)
2824 { return tile; }
2825 }
2826 return null;
2827 }
2828
2829 #findSavedAltarDestination (characterId, originX, originY, entityId)
2830 {
2831 const saved = this.stateDb.getCharacterRespawnAltar(characterId);
2832 if (!saved)
2833 { return null; }
2834 const dimensionId = normalizeDimensionId(saved.dimensionId ?? OVERWORLD_ID);
2835 const altar = this.altarTiles.find((entry) =>
2836 (entry.tileX | 0) === (saved.tileX | 0)
2837 && (entry.tileY | 0) === (saved.tileY | 0)
2838 && normalizeDimensionId(entry.dimensionId) === dimensionId
2839 );
2840 if (!altar)
2841 { return null; }
2842 return this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2843 }
2844
2845 #findDeathTileFallback (originX, originY, entityId, dimensionId)
2846 {
2847 const dim = normalizeDimensionId(dimensionId);
2848 for (let radius = 0; radius <= 24; radius++)
2849 {
2850 for (let dy = -radius; dy <= radius; dy++)
2851 {
2852 for (let dx = -radius; dx <= radius; dx++)
2853 {
2854 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2855 { continue; }
2856 const tileX = originX + dx;
2857 const tileY = originY + dy;
2858 if (this.isEnterable(tileX, tileY, dim)
2859 && !this.#occupiedByOther(tileX, tileY, entityId, dim))
2860 { return { tileX, tileY, dimensionId: dim }; }
2861 }
2862 }
2863 }
2864 return null;
2865 }
2866
2867 #findRespawnDestination (originX, originY, entityId, characterId = null)
2868 {
2869 const record = this.directory.get(entityId);
2870 const deathDimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2871 const deathAltars = this.altarTiles.filter((altar) =>
2872 normalizeDimensionId(altar.dimensionId) === deathDimensionId
2873 );
2874 for (const altar of this.#sortAltarsByDistance(deathAltars, originX, originY))
2875 {
2876 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2877 if (tile)
2878 { return tile; }
2879 }
2880 if (characterId != null)
2881 {
2882 const saved = this.#findSavedAltarDestination(characterId, originX, originY, entityId);
2883 if (saved)
2884 { return saved; }
2885 }
2886 const otherAltars = this.altarTiles.filter((altar) =>
2887 normalizeDimensionId(altar.dimensionId) !== deathDimensionId
2888 );
2889 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2890 {
2891 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2892 if (tile)
2893 { return tile; }
2894 }
2895 return this.#findDeathTileFallback(originX, originY, entityId, deathDimensionId)
2896 ?? this.findOpenSpawn();
2897 }
2898
2899 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2900 {
2901 const dim = normalizeDimensionId(dimensionId);
2902 for (const record of this.directory.values())
2903 {
2904 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2905 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2906 { return true; }
2907 }
2908 return false;
2909 }
2910
2911 #recalculateActivation (now)
2912 {
2913 const loaders = this.#allLoaders();
2914 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
2915
2916 for (const [key, count] of regionRes)
2917 {
2918 if (count <= 0)
2919 { continue; }
2920 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2921 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
2922 this.regionGraceUntil.delete(key);
2923 }
2924
2925 for (const [key] of [...this.regionOwner.entries()])
2926 {
2927 if ((regionRes.get(key) ?? 0) > 0)
2928 { continue; }
2929 if (!this.regionGraceUntil.has(key))
2930 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
2931 if (now >= this.regionGraceUntil.get(key))
2932 {
2933 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2934 this.#unloadRegion(regionX, regionY, dimensionId);
2935 }
2936 }
2937
2938 for (const [workerId, worker] of this.workers.entries())
2939 {
2940 const chunkKeys = [];
2941 for (const [key, count] of chunkSim)
2942 {
2943 if (count <= 0)
2944 { continue; }
2945 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2946 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
2947 { chunkKeys.push(key); }
2948 }
2949 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2950 }
2951 this.#syncAllReplicas();
2952
2953 const nextSimulating = new Set();
2954 for (const [key, count] of chunkSim)
2955 {
2956 if (count > 0)
2957 { nextSimulating.add(key); }
2958 }
2959 let preheated = false;
2960 for (const key of nextSimulating)
2961 {
2962 if (!this.simulatingChunkKeys.has(key))
2963 {
2964 preheated = true;
2965 break;
2966 }
2967 }
2968 this.simulatingChunkKeys = nextSimulating;
2969 if (preheated)
2970 { this.#stepSpawners(); }
2971 }
2972
2973 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
2974 {
2975 const dim = normalizeDimensionId(dimensionId);
2976 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2977 let preferred = this.#ownerOfTile(tileX, tileY, dim);
2978 for (const region of coverage.residentRegions)
2979 {
2980 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
2981 if (preferred == null)
2982 { preferred = owner; }
2983 }
2984 }
2985
2986 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2987 {
2988 const dim = normalizeDimensionId(dimensionId);
2989 const key = regionKey(regionX, regionY, dim);
2990 if (this.regionOwner.has(key))
2991 { return this.regionOwner.get(key); }
2992 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
2993 this.workers[workerId].call({
2994 type: WorkerMessage.assignRegion,
2995 regionX,
2996 regionY,
2997 dimensionId: dim,
2998 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
2999 });
3000 this.regionOwner.set(key, workerId);
3001 this.#restorePersistent(regionX, regionY, workerId, dim);
3002 this.#restoreGroundItems(regionX, regionY, workerId, dim);
3003 return workerId;
3004 }
3005
3006 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
3007 {
3008 const dim = normalizeDimensionId(dimensionId);
3009 const key = regionKey(regionX, regionY, dim);
3010 const workerId = this.regionOwner.get(key);
3011 if (workerId == null)
3012 { return; }
3013 const bounds = regionTileBounds(regionX, regionY);
3014 const { dropped, groundItems } = this.workers[workerId].call({
3015 type: WorkerMessage.dropRegion,
3016 regionX,
3017 regionY,
3018 dimensionId: dim
3019 });
3020 const persistent = [];
3021 for (const record of dropped ?? [])
3022 {
3023 if (record.characterId)
3024 {
3025 this.stateDb.saveCharacterPosition(
3026 record.characterId,
3027 record.tileX,
3028 record.tileY,
3029 record.gait ?? GAIT.walk,
3030 record.dimensionId ?? OVERWORLD_ID
3031 );
3032 }
3033 if (record.persistent)
3034 { persistent.push(record); }
3035 this.#forget(record.entityId);
3036 }
3037 this.stateDb.replacePersistentInRegion(
3038 bounds.minX,
3039 bounds.minY,
3040 bounds.maxX,
3041 bounds.maxY,
3042 persistent,
3043 dim
3044 );
3045 for (const item of groundItems ?? [])
3046 { this.stateDb.upsertGroundItem(item); }
3047 this.regionOwner.delete(key);
3048 this.regionGraceUntil.delete(key);
3049 }
3050
3051 #restorePersistent (regionX, regionY, workerId, dimensionId = OVERWORLD_ID)
3052 {
3053 const dim = normalizeDimensionId(dimensionId);
3054 const bounds = regionTileBounds(regionX, regionY);
3055 const rows = this.stateDb.listPersistentInRegion(
3056 bounds.minX,
3057 bounds.minY,
3058 bounds.maxX,
3059 bounds.maxY,
3060 dim
3061 );
3062 for (const row of rows)
3063 {
3064 if (this.directory.has(row.entity_id))
3065 { continue; }
3066 const components = JSON.parse(row.components_blob);
3067 const view = this.workers[workerId].call({
3068 type: WorkerMessage.spawn,
3069 entityId: row.entity_id,
3070 components
3071 });
3072 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
3073 this.#remember(view, workerId);
3074 }
3075 }
3076
3077 #applyTransfers (requests)
3078 {
3079 const events = [];
3080 for (const request of requests)
3081 {
3082 const destWorkerId = this.#ensureRegion(
3083 request.toRegionX,
3084 request.toRegionY,
3085 request.fromWorkerId,
3086 request.dimensionId ?? OVERWORLD_ID
3087 );
3088 if (destWorkerId === request.fromWorkerId)
3089 {
3090 this.workers[request.fromWorkerId].call({
3091 type: WorkerMessage.abortTransfer,
3092 entityId: request.entityId
3093 });
3094 continue;
3095 }
3096 let result;
3097 try
3098 {
3099 result = this.workers[destWorkerId].call({
3100 type: WorkerMessage.applyTransfer,
3101 payload: request.payload,
3102 destTileX: request.destTileX,
3103 destTileY: request.destTileY,
3104 dimensionId: request.dimensionId ?? OVERWORLD_ID
3105 });
3106 }
3107 catch
3108 {
3109 result = { accepted: false };
3110 }
3111 if (!result?.accepted)
3112 {
3113 this.workers[request.fromWorkerId].call({
3114 type: WorkerMessage.abortTransfer,
3115 entityId: request.entityId
3116 });
3117 continue;
3118 }
3119 this.workers[request.fromWorkerId].call({
3120 type: WorkerMessage.commitTransfer,
3121 entityId: request.entityId
3122 });
3123 this.#remember(result.entity, destWorkerId);
3124 events.push({
3125 type: "entity-move",
3126 entityId: request.entityId,
3127 fromTileX: request.fromTileX,
3128 fromTileY: request.fromTileY,
3129 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
3130 tileX: result.entity.tileX,
3131 tileY: result.entity.tileY,
3132 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
3133 gait: result.entity.gait
3134 });
3135 }
3136 return events;
3137 }
3138
3139 #syncAllReplicas ()
3140 {
3141 for (const [workerId, worker] of this.workers.entries())
3142 {
3143 const ownedKeys = new Set();
3144 for (const [key, owner] of this.regionOwner)
3145 {
3146 if (owner !== workerId)
3147 { continue; }
3148 const { regionX, regionY, dimensionId } = parseRegionKey(key);
3149 for (const chunk of chunksInRegion(regionX, regionY))
3150 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
3151 }
3152 const replicas = [];
3153 for (const key of replicaNeededForOwnedChunks(ownedKeys))
3154 {
3155 if (ownedKeys.has(key))
3156 { continue; }
3157 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
3158 replicas.push({
3159 chunkX,
3160 chunkY,
3161 dimensionId,
3162 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
3163 });
3164 }
3165 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
3166 }
3167 }
3168
3169 #syncGhosts ()
3170 {
3171 const entities = [];
3172 for (const worker of this.workers)
3173 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
3174 for (const [workerId, worker] of this.workers.entries())
3175 {
3176 const ghosts = entities.filter((entity) =>
3177 {
3178 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
3179 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
3180 { return false; }
3181 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
3182 });
3183 worker.call({ type: WorkerMessage.setGhosts, ghosts });
3184 }
3185 }
3186
3187 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
3188 {
3189 const dim = normalizeDimensionId(dimensionId);
3190 const chunkX = tileToChunk(tileX);
3191 const chunkY = tileToChunk(tileY);
3192 for (const [key, owner] of this.regionOwner)
3193 {
3194 if (owner !== workerId)
3195 { continue; }
3196 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
3197 if (regionDim !== dim)
3198 { continue; }
3199 for (const chunk of chunksInRegion(regionX, regionY))
3200 {
3201 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
3202 { return true; }
3203 }
3204 }
3205 return false;
3206 }
3207
3208 #allLoaders ()
3209 {
3210 const loaders = [];
3211 for (const worker of this.workers)
3212 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
3213 return loaders;
3214 }
3215
3216 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
3217 {
3218 const dim = normalizeDimensionId(dimensionId);
3219 const votes = new Map();
3220 for (const loader of loaders)
3221 {
3222 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
3223 if (loaderDim !== dim)
3224 { continue; }
3225 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
3226 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
3227 { continue; }
3228 const record = this.directory.get(loader.entityId);
3229 if (record?.workerId == null)
3230 { continue; }
3231 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
3232 }
3233 let best = null;
3234 let bestVotes = -1;
3235 for (const [workerId, count] of votes)
3236 {
3237 if (count > bestVotes)
3238 {
3239 best = workerId;
3240 bestVotes = count;
3241 }
3242 }
3243 return best;
3244 }
3245
3246 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
3247 {
3248 const dim = normalizeDimensionId(dimensionId);
3249 const pinned = this.pinRegion?.(regionX, regionY, dim);
3250 if (pinned != null)
3251 { return pinned; }
3252
3253 const neighborOwners = [];
3254 for (let dy = -1; dy <= 1; dy++)
3255 {
3256 for (let dx = -1; dx <= 1; dx++)
3257 {
3258 if (dx === 0 && dy === 0)
3259 { continue; }
3260 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
3261 if (owner != null)
3262 { neighborOwners.push(owner); }
3263 }
3264 }
3265
3266 const scores = this.workers.map((_, workerId) => ({
3267 workerId,
3268 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
3269 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
3270 }));
3271
3272 if (preferredWorkerId != null && scores[preferredWorkerId])
3273 {
3274 const preferred = scores[preferredWorkerId];
3275 if (preferred.neighbors > 0 || neighborOwners.length === 0)
3276 { return preferredWorkerId; }
3277 }
3278
3279 scores.sort((left, right) =>
3280 right.neighbors - left.neighbors
3281 || left.load - right.load
3282 || left.workerId - right.workerId
3283 );
3284 return scores[0].workerId;
3285 }
3286
3287 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
3288 {
3289 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
3290 }
3291
3292 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
3293 {
3294 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
3295 }
3296
3297 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
3298 {
3299 const dim = normalizeDimensionId(dimensionId);
3300 return chunksInRegion(regionX, regionY).map((coord) => ({
3301 chunkX: coord.chunkX,
3302 chunkY: coord.chunkY,
3303 dimensionId: dim,
3304 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
3305 }));
3306 }
3307
3308 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
3309 {
3310 const dim = normalizeDimensionId(dimensionId);
3311 const key = chunkKey(chunkX, chunkY, dim);
3312 if (this.authoredCache.has(key))
3313 { return this.authoredCache.get(key); }
3314 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
3315 const dimRecord = this.getDimensionRecord(dim);
3316 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
3317 const data = row
3318 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
3319 : createEmptyChunkData(defaultGroundTypeId);
3320 this.authoredCache.set(key, data);
3321 return data;
3322 }
3323
3324 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
3325 {
3326 const dim = normalizeDimensionId(dimensionId);
3327 const data = this.#authoredChunk(chunkX, chunkY, dim);
3328 return {
3329 chunkX,
3330 chunkY,
3331 dimensionId: dim,
3332 open: data.open,
3333 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
3334 grounds: data.grounds,
3335 blocks: data.blocks,
3336 light: data.light,
3337 enclosed: data.enclosed,
3338 entities: [],
3339 groundItems: []
3340 };
3341 }
3342
3343 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
3344 {
3345 const dim = normalizeDimensionId(dimensionId);
3346 for (const record of this.directory.values())
3347 {
3348 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
3349 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
3350 { return record.entityId; }
3351 }
3352 return null;
3353 }
3354
3355 #queueReplication (event)
3356 {
3357 if (event)
3358 { this.replication.push(event); }
3359 }
3360
3361 #stepSpawners ()
3362 {
3363 const events = [];
3364 for (const worker of this.workers)
3365 {
3366 const result = worker.call({ type: WorkerMessage.stepSpawners });
3367 for (const request of result?.spawnRequests ?? [])
3368 {
3369 try
3370 {
3371 this.spawnEntity(mobComponents(request), { requireResident: true });
3372 }
3373 catch
3374 { continue; }
3375 }
3376 }
3377 return events;
3378 }
3379
3380 #restoreGroundItems (regionX, regionY, workerId, dimensionId = OVERWORLD_ID)
3381 {
3382 const dim = normalizeDimensionId(dimensionId);
3383 const bounds = regionTileBounds(regionX, regionY);
3384 const items = [];
3385 for (const item of this.stateDb.listGroundItemsInRegion(
3386 bounds.minX,
3387 bounds.minY,
3388 bounds.maxX,
3389 bounds.maxY,
3390 dim
3391 ))
3392 {
3393 if (chequeIsExpired(item.stack, this.now))
3394 {
3395 this.voidFilledCheque(item.stack, { toast: true });
3396 item.stack = {
3397 itemId: ItemId.expiredCheque,
3398 quantity: 1,
3399 instance: null
3400 };
3401 this.stateDb.upsertGroundItem(item);
3402 }
3403 if (item.itemSpawnerId || item.source === "item-spawner"
3404 || item.expiresAt == null || item.expiresAt > this.now)
3405 {
3406 items.push(item);
3407 continue;
3408 }
3409 // Expired while unloaded: destroy and free any cheque reservation.
3410 this.#destroyExpiredGroundItem(item);
3411 }
3412 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
3413 this.workers[workerId].call({
3414 type: WorkerMessage.setGroundItems,
3415 regionX,
3416 regionY,
3417 dimensionId: dim,
3418 items
3419 });
3420 }
3421
3422 /** Cheque paper that no longer exists must free reserved vault goods. */
3423 voidFilledCheque (stack, { toast = true } = {})
3424 {
3425 if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")
3426 { return { ok: false }; }
3427 const issuerId = stack.instance.issuerCharacterId | 0;
3428 const chequeId = stack.instance.chequeId;
3429 const release = this.releaseChequeReservation(issuerId, chequeId, stack.instance);
3430 if (!release?.ok || !release.stack)
3431 {
3432 // Already redeemed/voided — treat as success so despawn stays idempotent.
3433 return { ok: true, alreadyReleased: true };
3434 }
3435 const onlineId = this.characterEntities.get(issuerId);
3436 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerId);
3437 if (!bag)
3438 { return { ok: false, error: "Issuer vault not found." }; }
3439 const goodsDef = itemDefinition(release.stack.itemId);
3440 if (!goodsDef)
3441 { return { ok: false, error: "Unknown reserved goods." }; }
3442 const goods = attachOrigins({
3443 itemId: release.stack.itemId,
3444 quantity: release.stack.quantity,
3445 instance: release.stack.instance ? structuredClone(release.stack.instance) : null,
3446 origins: release.stack.origins
3447 });
3448 const inserted = insertStackGrowable(bag.vault ?? [], goods, goodsDef);
3449 bag.vault = inserted.slots;
3450 this.stateDb.saveBag(issuerId, bag);
3451 if (onlineId)
3452 {
3453 this.applyBag(onlineId, bag);
3454 this.pushInventory(issuerId, bag);
3455 }
3456 if (toast)
3457 {
3458 this.pendingPrivate.push({
3459 type: "toast",
3460 characterId: issuerId,
3461 message: "An uncashed cheque expired. Reserved goods returned to your vault."
3462 });
3463 }
3464 return { ok: true };
3465 }
3466
3467 /**
3468 * Convert an aged filled cheque in a character's bag into an expired cheque
3469 * and release its reservation back to the issuer.
3470 */
3471 expireFilledChequePaper (characterId, slotIndex, { now = this.now } = {})
3472 {
3473 const cid = characterId | 0;
3474 const onlineId = this.characterEntities.get(cid);
3475 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3476 if (!bag?.inventory)
3477 { return { ok: false }; }
3478 const index = slotIndex | 0;
3479 const stack = bag.inventory[index];
3480 if (!isFilledChequeStack(stack))
3481 { return { ok: false }; }
3482 if (!chequeIsExpired(stack, now))
3483 { return { ok: false, expired: false }; }
3484 bag.inventory[index] = {
3485 itemId: ItemId.expiredCheque,
3486 quantity: 1,
3487 instance: null,
3488 origins: []
3489 };
3490 this.stateDb.saveBag(cid, bag);
3491 if (onlineId)
3492 {
3493 this.applyBag(onlineId, bag);
3494 this.pushInventory(cid, bag);
3495 }
3496 this.voidFilledCheque(stack, { toast: true });
3497 return { ok: true, expired: true };
3498 }
3499
3500 /** Scan inventory (and convert) any filled cheques past their 30-day life. */
3501 sweepExpiredCheques (characterId, { now = this.now } = {})
3502 {
3503 const cid = characterId | 0;
3504 const onlineId = this.characterEntities.get(cid);
3505 let bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3506 if (!bag?.inventory)
3507 { return { ok: true, converted: 0 }; }
3508 const toRelease = [];
3509 for (let i = 0; i < bag.inventory.length; i++)
3510 {
3511 const stack = bag.inventory[i];
3512 if (!chequeIsExpired(stack, now))
3513 { continue; }
3514 toRelease.push(stack);
3515 bag.inventory[i] = {
3516 itemId: ItemId.expiredCheque,
3517 quantity: 1,
3518 instance: null,
3519 origins: []
3520 };
3521 }
3522 if (!toRelease.length)
3523 { return { ok: true, converted: 0 }; }
3524 this.stateDb.saveBag(cid, bag);
3525 if (onlineId)
3526 {
3527 this.applyBag(onlineId, bag);
3528 this.pushInventory(cid, bag);
3529 }
3530 let toasted = false;
3531 for (const stack of toRelease)
3532 {
3533 this.voidFilledCheque(stack, { toast: !toasted });
3534 toasted = true;
3535 }
3536 return { ok: true, converted: toRelease.length };
3537 }
3538
3539 #destroyExpiredGroundItem (item)
3540 {
3541 if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
3542 { this.voidFilledCheque(item.stack); }
3543 this.stateDb.deleteGroundItem(item.groundItemId);
3544 }
3545
3546 #persistGroundEvent (event)
3547 {
3548 if (event.type === "ground-item-appear")
3549 {
3550 this.stateDb.upsertGroundItem({
3551 groundItemId: event.groundItemId,
3552 tileX: event.tileX,
3553 tileY: event.tileY,
3554 dimensionId: event.dimensionId ?? OVERWORLD_ID,
3555 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
3556 droppedAt: event.droppedAt ?? this.now,
3557 expiresAt: event.expiresAt,
3558 source: event.source ?? "player-drop",
3559 droppedByCharacterId: event.droppedByCharacterId ?? null
3560 });
3561 }
3562 if (event.type === "ground-item-despawn")
3563 { this.stateDb.deleteGroundItem(event.groundItemId); }
3564 }
3565
3566 #saveBag (entityId, workerId)
3567 {
3568 const record = this.directory.get(entityId);
3569 const bag = this.workers[workerId].call({
3570 type: WorkerMessage.inspectBag,
3571 entityId
3572 });
3573 if (!bag || !record?.characterId)
3574 { return; }
3575 this.#saveBagFromView(record.characterId, bag);
3576 const skills = this.workers[workerId].call({
3577 type: WorkerMessage.inspectSkills,
3578 entityId
3579 });
3580 if (skills)
3581 { this.stateDb.saveSkills(record.characterId, skills); }
3582 }
3583
3584 #applySkillsUpdated (event)
3585 {
3586 if (!event?.characterId || !event.stored)
3587 { return; }
3588 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
3589 this.pushSkills(event.characterId, event.skills ?? [], event.combatLevel ?? 0);
3590 this.#markQuestReeval(event.characterId);
3591 }
3592
3593 #markQuestReeval (characterId)
3594 {
3595 const id = characterId | 0;
3596 if (!id || !this.quests)
3597 { return; }
3598 this.questReevalCharacterIds.add(id);
3599 }
3600
3601 #flushQuestReevaluations ()
3602 {
3603 if (!this.quests || this.questReevalCharacterIds.size === 0)
3604 { return []; }
3605 const out = [];
3606 // Effects from completions (e.g. giveItem) can mark again; iterate a few times.
3607 for (let pass = 0; pass < 8 && this.questReevalCharacterIds.size > 0; pass++)
3608 {
3609 const batch = [...this.questReevalCharacterIds];
3610 this.questReevalCharacterIds.clear();
3611 for (const characterId of batch)
3612 {
3613 out.push(...this.#mapQuestPrivateEvents(
3614 this.quests.reevaluateQuests(characterId),
3615 null,
3616 characterId
3617 ));
3618 }
3619 }
3620 this.questReevalCharacterIds.clear();
3621 return out;
3622 }
3623
3624 #applySpellsUpdated (event)
3625 {
3626 if (!event?.characterId || !event.stored)
3627 { return; }
3628 this.stateDb.saveSpells(event.characterId, event.stored);
3629 this.pushSpells(event.characterId, {
3630 spells: event.spells ?? [],
3631 favorites: event.favorites ?? [],
3632 autoCast: !!event.autoCast
3633 });
3634 }
3635
3636 #applySummonEntity (event)
3637 {
3638 const isFairy = event.mobTypeId === MobId.fairy || event.mobTypeId === "fairy";
3639 const components = isFairy
3640 ? jadeiteFairyComponents({
3641 tileX: event.tileX | 0,
3642 tileY: event.tileY | 0,
3643 level: event.level | 0 || 1,
3644 ownerEntityId: event.ownerEntityId,
3645 ownerCharacterId: event.ownerCharacterId ?? null,
3646 ownerName: event.ownerName,
3647 dimensionId: event.dimensionId
3648 })
3649 : shadeSummonComponents({
3650 tileX: event.tileX | 0,
3651 tileY: event.tileY | 0,
3652 level: event.level | 0 || 1,
3653 ownerEntityId: event.ownerEntityId,
3654 expiresAt: event.expiresAt,
3655 dimensionId: event.dimensionId
3656 });
3657 try
3658 {
3659 const entityId = this.spawnEntity(components, { requireResident: true });
3660 if (entityId == null)
3661 { return []; }
3662 return [];
3663 }
3664 catch
3665 {
3666 return [];
3667 }
3668 }
3669
3670 #applyJewelryTeleport (event)
3671 {
3672 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
3673 const record = entityId ? this.directory.get(entityId) : null;
3674 if (!record)
3675 { return []; }
3676 const destination = this.#findJewelryTeleportDestination(
3677 event.fromTileX | 0,
3678 event.fromTileY | 0,
3679 entityId,
3680 event.destination
3681 );
3682 if (!destination)
3683 {
3684 return [{
3685 type: "command-error",
3686 sessionId: event.sessionId,
3687 message: event.destination === "bank"
3688 ? "No bank is available."
3689 : "No church altar is available."
3690 }];
3691 }
3692 const loader = { ...DEFAULT_CHUNK_LOADER };
3693 this.#ensureCoverage(
3694 destination.tileX,
3695 destination.tileY,
3696 loader,
3697 destination.dimensionId ?? OVERWORLD_ID
3698 );
3699 const result = this.workers[record.workerId].call({
3700 type: WorkerMessage.relocateEntity,
3701 entityId,
3702 tileX: destination.tileX,
3703 tileY: destination.tileY,
3704 dimensionId: destination.dimensionId ?? OVERWORLD_ID
3705 });
3706 if (!result?.accepted)
3707 {
3708 return [{
3709 type: "command-error",
3710 sessionId: event.sessionId,
3711 message: "The destination is no longer available."
3712 }];
3713 }
3714 const events = [];
3715 if (result.transferRequest)
3716 { events.push(...this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }])); }
3717 else if (result.event)
3718 {
3719 this.#applyMoveToDirectory(result.event);
3720 events.push(result.event);
3721 const view = this.workers[record.workerId].call({
3722 type: WorkerMessage.inspect,
3723 entityId
3724 });
3725 if (view)
3726 { this.#remember(view, record.workerId); }
3727 }
3728 return events;
3729 }
3730
3731 #findJewelryTeleportDestination (originX, originY, entityId, destination)
3732 {
3733 if (destination === "church")
3734 {
3735 const record = this.directory.get(entityId);
3736 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3737 return this.#findNearestAltarDestination(originX, originY, entityId, dimensionId);
3738 }
3739 if (destination !== "bank")
3740 { return null; }
3741 const record = this.directory.get(entityId);
3742 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3743 const bank = this.courier?.nearestBank(originX, originY, dimensionId);
3744 if (!bank)
3745 { return null; }
3746 const adjacent = [];
3747 for (let dy = -1; dy <= 1; dy++)
3748 {
3749 for (let dx = -1; dx <= 1; dx++)
3750 {
3751 if (dx === 0 && dy === 0)
3752 { continue; }
3753 adjacent.push({
3754 tileX: bank.tileX + dx,
3755 tileY: bank.tileY + dy,
3756 dimensionId
3757 });
3758 }
3759 }
3760 adjacent.sort((left, right) =>
3761 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
3762 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
3763 );
3764 const tile = adjacent.find((entry) =>
3765 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
3766 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
3767 );
3768 return tile ?? null;
3769 }
3770
3771 #skillLevelUpEvents (event)
3772 {
3773 const levelUps = event?.levelUps ?? [];
3774 if (!levelUps.length)
3775 { return []; }
3776 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
3777 if (entityId == null)
3778 { return []; }
3779 const record = this.directory.get(entityId);
3780 const tileX = record?.tileX ?? 0;
3781 const tileY = record?.tileY ?? 0;
3782 return levelUps.map((levelUp) => ({
3783 type: "skill-level-up",
3784 entityId,
3785 characterId: event.characterId,
3786 tileX,
3787 tileY,
3788 skillId: levelUp.skillId,
3789 level: levelUp.level,
3790 previousLevel: levelUp.previousLevel,
3791 displayName: levelUp.displayName,
3792 icon: levelUp.icon
3793 }));
3794 }
3795
3796 #saveBagFromView (characterId, bag)
3797 {
3798 this.stateDb.saveBag(characterId, {
3799 inventory: bag.inventory,
3800 equipment: bag.equipment,
3801 vault: bag.vault,
3802 vaultReserved: bag.vaultReserved
3803 });
3804 this.#markQuestReeval(characterId);
3805 }
3806
3807 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
3808 {
3809 const onlineId = this.characterEntities.get(issuerCharacterId);
3810 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
3811 if (!bag)
3812 { return { ok: false, error: "Issuer vault not found." }; }
3813 const reserved = [...(bag.vaultReserved ?? [])];
3814 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
3815 if (index < 0)
3816 { return { ok: false, error: "That cheque cannot be redeemed." }; }
3817 const [stack] = reserved.splice(index, 1);
3818 bag.vaultReserved = reserved;
3819 this.stateDb.saveBag(issuerCharacterId, bag);
3820 if (onlineId)
3821 {
3822 this.applyBag(onlineId, bag);
3823 this.pushInventory(issuerCharacterId, bag);
3824 }
3825 return { ok: true, stack };
3826 }
3827
3828 restoreChequeReservation (issuerCharacterId, stack)
3829 {
3830 const onlineId = this.characterEntities.get(issuerCharacterId);
3831 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
3832 if (!bag)
3833 { return; }
3834 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
3835 this.stateDb.saveBag(issuerCharacterId, bag);
3836 if (onlineId)
3837 {
3838 this.applyBag(onlineId, bag);
3839 this.pushInventory(issuerCharacterId, bag);
3840 }
3841 }
3842
3843 #remember (view, workerId)
3844 {
3845 if (!view)
3846 { return; }
3847 const previous = this.directory.get(view.entityId);
3848 this.directory.set(view.entityId, {
3849 ...view,
3850 workerId,
3851 // Keep simulation-only fields that publicEntityView does not carry.
3852 skullValue: previous?.skullValue ?? view.skullValue ?? 0
3853 });
3854 if (view.characterId)
3855 { this.characterEntities.set(view.characterId, view.entityId); }
3856 }
3857
3858 #applyMoveToDirectory (event)
3859 {
3860 const record = this.directory.get(event.entityId);
3861 if (!record)
3862 { return; }
3863 record.tileX = event.tileX;
3864 record.tileY = event.tileY;
3865 record.gait = event.gait;
3866 if (event.dimensionId != null)
3867 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
3868 if (event.worldX != null)
3869 { record.worldX = event.worldX; }
3870 if (event.worldY != null)
3871 { record.worldY = event.worldY; }
3872 if (event.freeFlight != null)
3873 { record.freeFlight = !!event.freeFlight; }
3874 }
3875
3876 #forget (entityId)
3877 {
3878 const record = this.directory.get(entityId);
3879 if (record?.characterId)
3880 { this.characterEntities.delete(record.characterId); }
3881 this.directory.delete(entityId);
3882 }
3883}