BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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