BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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