BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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