BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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