BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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