BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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