BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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