BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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