BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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