BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

rweaks
timfa Tim Falken · pushed by timfa · 2 months ago
2b34e2dd History
simulation.js 45.7 KiB Download Raw
1import {
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 WORLD_YEAR_OFFSET
8} from "../../../shared/protocol/constants.js";
9import {
10 chunkKey,
11 chunkToRegion,
12 chunksInRegion,
13 parseChunkKey,
14 parseRegionKey,
15 regionKey,
16 regionTileBounds,
17 tileToChunk,
18 tileToLocal,
19 tileToRegion,
20 visibleChunkCoords
21} from "../world/coordinates.js";
22import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
23import { closedNeighborEdges } from "../world/chunkFlags.js";
24import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
25import { InProcessWorker } from "./inProcessWorker.js";
26import { ThreadWorker } from "./threadWorker.js";
27import { WorkerMessage } from "./protocol.js";
28import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
32import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
33import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34import { BlockType } from "../../../shared/definitions/tiles.js";
35import { ItemId } from "../../../shared/definitions/items.js";
36import { seasonIdAt } from "../../../shared/world/season.js";
37import { CourierService } from "../courier/service.js";
38import { MarketService } from "../market/service.js";
39import { findReservedChequeIndex } from "../items/bags.js";
40
41export class Simulation
42{
43 constructor (worldDb, stateDb, options = {})
44 {
45 this.worldDb = worldDb;
46 this.stateDb = stateDb;
47 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
48 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
49 this.pinRegion = options.pinRegion ?? null;
50 this.nowFn = options.now ?? (() => Date.now());
51 this.workers = [];
52 this.regionOwner = new Map();
53 this.regionGraceUntil = new Map();
54 this.directory = new Map();
55 this.characterEntities = new Map();
56 this.commandQueue = [];
57 this.replication = [];
58 this.pendingPrivate = [];
59 this.courier = null;
60 this.market = null;
61 this.altarTiles = [];
62 this.authoredCache = new Map();
63 this.simulatingChunkKeys = new Set();
64 this.nextEntityId = 1;
65 this.nextGroundItemId = stateDb.nextGroundItemId();
66 this.tickIndex = 0;
67 this.movementTickCounter = 0;
68 this.lastTickAt = null;
69 this.movementAccumulator = 0;
70 this.activeRevisionId = worldDb.getActiveRevisionId();
71 this.settings = worldDb.getLiveSettings();
72
73 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
74 for (let workerId = 0; workerId < this.workerCount; workerId++)
75 {
76 const worker = new WorkerImpl(workerId);
77 worker.call({
78 type: WorkerMessage.configure,
79 settings: this.settings,
80 activeRevisionId: this.activeRevisionId
81 });
82 this.workers.push(worker);
83 }
84 for (const worker of this.workers)
85 {
86 if (!worker.world)
87 { continue; }
88 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
89 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
90 }
91 this.courier = new CourierService({
92 stateDb: this.stateDb,
93 worldDb: this.worldDb,
94 simulation: this
95 });
96 this.market = new MarketService({
97 stateDb: this.stateDb,
98 worldDb: this.worldDb,
99 simulation: this
100 });
101 this.#refreshAltarIndex();
102 }
103
104 get now ()
105 {
106 return this.nowFn();
107 }
108
109 applySettings (settings)
110 {
111 this.settings = { ...this.settings, ...settings };
112 this.#configureWorkers();
113 }
114
115 /** Sparse last-sale map for editor base-price readouts. */
116 itemLastSalesSnapshot ()
117 {
118 return this.market?.snapshot?.() ?? {};
119 }
120
121 syncItemLastSales (lastSales)
122 {
123 const sales = {};
124 for (const [itemId, sale] of lastSales?.entries?.() ?? [])
125 { sales[String(itemId)] = sale; }
126 for (const worker of this.workers)
127 {
128 worker.call({
129 type: WorkerMessage.setItemLastSales,
130 sales
131 });
132 }
133 }
134
135 reloadWorld ()
136 {
137 this.activeRevisionId = this.worldDb.getActiveRevisionId();
138 this.settings = this.worldDb.getLiveSettings();
139 this.authoredCache.clear();
140 this.#configureWorkers();
141 for (const [key, workerId] of this.regionOwner)
142 {
143 const { regionX, regionY } = parseRegionKey(key);
144 this.workers[workerId].call({
145 type: WorkerMessage.replaceRegionChunks,
146 chunks: this.#regionChunkBlobs(regionX, regionY)
147 });
148 }
149 this.#syncAllReplicas();
150 this.courier?.refreshBankIndex();
151 this.market?.refreshIndex();
152 this.#refreshAltarIndex();
153 }
154
155 enqueue (sessionId, command)
156 {
157 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
158 }
159
160 step (now = this.now)
161 {
162 this.tickIndex += 1;
163 const events = [];
164 const commands = this.commandQueue.splice(0);
165 for (const item of commands)
166 {
167 try
168 {
169 events.push(...this.#routeCommand(item));
170 }
171 catch (error)
172 {
173 events.push({
174 sessionId: item.sessionId,
175 type: "command-error",
176 message: error.userFacing ? error.message : "Command failed."
177 });
178 }
179 }
180
181 this.#recalculateActivation(now);
182
183 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
184 const expectedDt = 1 / simHz;
185 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
186 ? expectedDt
187 : Math.min(0.25, (now - this.lastTickAt) / 1000);
188 this.lastTickAt = now;
189
190 {
191 const transfers = [];
192 const remoteMelee = [];
193 for (const worker of this.workers)
194 {
195 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
196 for (const event of result?.events ?? [])
197 {
198 if (event.type === "remote-melee-resolve")
199 {
200 remoteMelee.push(event);
201 continue;
202 }
203 if (event.type === "entity-move")
204 { this.#applyMoveToDirectory(event); }
205 if (event.type === "entity-despawn")
206 { this.#forget(event.entityId); }
207 if (event.type === "skills-updated")
208 { this.#applySkillsUpdated(event); }
209 if (event.type === "inventory" && event.characterId)
210 {
211 this.#saveBagFromView(event.characterId, {
212 inventory: event.inventory,
213 equipment: event.equipment,
214 vault: event.vault,
215 vaultReserved: event.vaultReserved
216 });
217 }
218 if (event.type === "player-died")
219 {
220 events.push(...this.#applyPlayerDeath(event));
221 continue;
222 }
223 this.#persistGroundEvent(event);
224 if (event.type !== "skills-updated")
225 { events.push(event); }
226 }
227 for (const request of result?.transferRequests ?? [])
228 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
229 }
230 for (const payload of remoteMelee)
231 { events.push(...this.#applyRemoteMelee(payload)); }
232 if (transfers.length)
233 {
234 events.push(...this.#applyTransfers(transfers));
235 this.#recalculateActivation(now);
236 }
237 }
238
239 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
240 this.movementAccumulator += dt * movementHz;
241 while (this.movementAccumulator >= 1)
242 {
243 this.movementAccumulator -= 1;
244 this.movementTickCounter += 1;
245 const transfers = [];
246 for (const worker of this.workers)
247 {
248 const result = worker.call({ type: WorkerMessage.stepMovement, now });
249 for (const event of result?.events ?? [])
250 {
251 if (event.type === "entity-move")
252 { this.#applyMoveToDirectory(event); }
253 if (event.type === "skills-updated")
254 { this.#applySkillsUpdated(event); }
255 this.#persistGroundEvent(event);
256 if (event.type !== "skills-updated")
257 { events.push(event); }
258 }
259 for (const request of result?.transferRequests ?? [])
260 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
261 }
262 events.push(...this.#applyTransfers(transfers));
263 this.#recalculateActivation(now);
264 }
265
266 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
267 { events.push(...this.#stepSpawners()); }
268
269 if (this.courier)
270 { events.push(...this.courier.step(now, dt)); }
271 if (this.market)
272 { events.push(...this.market.step(now)); }
273
274 this.#syncGhosts();
275 events.push(...this.pendingPrivate.splice(0));
276 return { now, events, replication: this.drainReplication() };
277 }
278
279 drainReplication ()
280 {
281 return this.replication.splice(0);
282 }
283
284 worldTime (now = this.now)
285 {
286 const date = new Date(now);
287 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
288 return {
289 unixMs: now,
290 worldUnixMs: date.getTime(),
291 iso: date.toISOString(),
292 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,
293 season: seasonIdAt(now)
294 };
295 }
296
297 spawnCharacter (sessionId, character)
298 {
299 this.despawnCharacter(character.character_id);
300 // Despawn may have just written the live tile; never trust a stale row snapshot.
301 const row = this.stateDb.getCharacter(character.character_id) ?? character;
302 let tileX = row.tile_x;
303 let tileY = row.tile_y;
304 const gait = row.gait || character.gait || GAIT.walk;
305 const preferred = this.#findResumeTile(tileX, tileY);
306 if (!preferred)
307 {
308 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
309 error.userFacing = true;
310 throw error;
311 }
312 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
313 {
314 tileX = preferred.tileX;
315 tileY = preferred.tileY;
316 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
317 }
318
319 const bag = this.stateDb.getBag(character.character_id) ?? {
320 inventory: emptySlots(),
321 equipment: emptyEquipment(),
322 vault: [],
323 vaultReserved: []
324 };
325 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
326 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
327 if (enforceMinimumSkillLevels(skills))
328 { this.stateDb.saveSkills(character.character_id, skills); }
329 const maxHealth = playerMaxHealth(skills);
330 const maxStamina = playerMaxStamina(skills);
331 const isDead = !!row.is_dead;
332 const entityId = this.nextEntityId++;
333 const components = {
334 position: { tileX, tileY },
335 movement: { gait, walkCarry: 0 },
336 path: { tiles: [] },
337 appearance: {
338 sex: character.sex ?? row.sex,
339 firstName: character.first_name ?? row.first_name,
340 lastName: character.last_name ?? row.last_name
341 },
342 character: {
343 characterId: character.character_id ?? row.character_id,
344 accountId: character.account_id ?? row.account_id
345 },
346 networkIdentity: { sessionId },
347 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
348 inventory: { slots: bag.inventory ?? emptySlots() },
349 equipment: bag.equipment ?? emptyEquipment(),
350 vault: {
351 slots: bag.vault ?? [],
352 reserved: bag.vaultReserved ?? []
353 },
354 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
355 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
356 combat: { targetEntityId: null, nextSwingAt: 0 },
357 skills,
358 };
359 if (isDead)
360 { components.dead = {}; }
361 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
362 const workerId = this.#ownerOfTile(tileX, tileY);
363 const view = this.workers[workerId].call({
364 type: WorkerMessage.spawn,
365 entityId,
366 components
367 });
368 this.#remember(view, workerId);
369 this.#queueReplication(replicationSpawn(view));
370 this.#recalculateActivation(this.now);
371 this.#syncGhosts();
372 return entityId;
373 }
374
375 spawnEntity (components, options = {})
376 {
377 const entityId = options.entityId ?? this.nextEntityId++;
378 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
379 const position = components.position;
380 if (!position)
381 { throw new Error("spawnEntity requires position."); }
382 if (options.requireResident)
383 {
384 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
385 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))
386 { return null; }
387 const view = this.workers[workerId].call({
388 type: WorkerMessage.spawn,
389 entityId,
390 components
391 });
392 this.#remember(view, workerId);
393 if (components.appearance)
394 { this.#queueReplication(replicationSpawn(view)); }
395 this.#syncGhosts();
396 return entityId;
397 }
398 if (components.chunkLoader)
399 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
400 else
401 {
402 this.#ensureRegion(
403 tileToRegion(position.tileX),
404 tileToRegion(position.tileY),
405 null
406 );
407 }
408 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
409 const view = this.workers[workerId].call({
410 type: WorkerMessage.spawn,
411 entityId,
412 components
413 });
414 this.#remember(view, workerId);
415 if (components.appearance)
416 { this.#queueReplication(replicationSpawn(view)); }
417 this.#recalculateActivation(this.now);
418 this.#syncGhosts();
419 return entityId;
420 }
421
422 despawnEntity (entityId)
423 {
424 const record = this.directory.get(entityId);
425 if (!record)
426 { return; }
427 const dropped = this.workers[record.workerId].call({
428 type: WorkerMessage.despawn,
429 entityId
430 });
431 if (dropped)
432 { this.#queueReplication(replicationDespawn(dropped)); }
433 this.#forget(entityId);
434 }
435
436 chunkIsSimulating (tileX, tileY)
437 {
438 const loaders = this.#allLoaders();
439 const { chunkSim } = accumulateLoaderRefs(loaders);
440 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;
441 }
442
443 updateCourierFlight (entityId, flightPatch, now = this.now)
444 {
445 const record = this.directory.get(entityId);
446 if (!record)
447 { return { despawned: true, entityId }; }
448 const tileX = Math.floor(flightPatch.x);
449 const tileY = Math.floor(flightPatch.y);
450 const owner = this.#ownerOfTile(tileX, tileY);
451 if (owner == null || owner !== record.workerId)
452 {
453 this.despawnEntity(entityId);
454 return { despawned: true, entityId };
455 }
456 const result = this.workers[owner].call({
457 type: WorkerMessage.updateFlight,
458 entityId,
459 flight: flightPatch,
460 now
461 });
462 if (result?.transferRequest)
463 {
464 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
465 this.#recalculateActivation(now);
466 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
467 if (move)
468 {
469 this.#applyMoveToDirectory(move);
470 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
471 }
472 this.despawnEntity(entityId);
473 return { despawned: true, entityId };
474 }
475 if (result?.event)
476 {
477 this.#applyMoveToDirectory(result.event);
478 return { event: result.event };
479 }
480 return null;
481 }
482
483 applyBag (entityId, bag)
484 {
485 const record = this.directory.get(entityId);
486 if (!record)
487 { return null; }
488 return this.workers[record.workerId].call({
489 type: WorkerMessage.applyBag,
490 entityId,
491 bag
492 });
493 }
494
495 pushSkills (characterId, skills)
496 {
497 this.pendingPrivate.push({
498 type: "skills",
499 characterId,
500 skills
501 });
502 }
503
504 skillsOf (entityId)
505 {
506 const record = this.directory.get(entityId);
507 if (!record)
508 { return null; }
509 return this.workers[record.workerId].call({
510 type: WorkerMessage.inspectSkills,
511 entityId
512 });
513 }
514
515 staminaOf (entityId)
516 {
517 const record = this.directory.get(entityId);
518 if (!record)
519 { return null; }
520 return this.workers[record.workerId].call({
521 type: WorkerMessage.inspectStamina,
522 entityId
523 });
524 }
525
526 pushInventory (characterId, bag)
527 {
528 this.pendingPrivate.push({
529 type: "inventory",
530 characterId,
531 inventory: bag.inventory,
532 equipment: bag.equipment,
533 vault: bag.vault,
534 vaultReserved: bag.vaultReserved
535 });
536 }
537
538 dispatchPigeon ({ characterId, destination, cargo })
539 {
540 const entityId = this.characterEntities.get(characterId);
541 const position = entityId ? this.positionOf(entityId) : null;
542 if (!position)
543 {
544 const error = new Error("Enter the world before sending a pigeon.");
545 error.userFacing = true;
546 throw error;
547 }
548 return this.courier.dispatchFromPlayer({
549 characterId,
550 originTileX: position.tileX,
551 originTileY: position.tileY,
552 destination,
553 cargo
554 });
555 }
556
557 /**
558 * When a player uses a marketplace counter, path an idle CE clerk to the
559 * opposite side of that counter (staff side).
560 */
561 stationExchangeClerks (playerTileX, playerTileY)
562 {
563 const results = [];
564 for (const tile of this.market?.marketTiles ?? [])
565 {
566 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
567 { continue; }
568 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
569 { continue; }
570 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
571 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
572 if (stationTileX === playerTileX && stationTileY === playerTileY)
573 { continue; }
574 const owner = this.#ownerOfTile(stationTileX, stationTileY);
575 if (owner == null)
576 { continue; }
577 const result = this.workers[owner].call({
578 type: WorkerMessage.stationExchangeClerk,
579 stationTileX,
580 stationTileY
581 });
582 results.push(result);
583 }
584 return results;
585 }
586
587 despawnCharacter (characterId)
588 {
589 const entityId = this.characterEntities.get(characterId);
590 if (!entityId)
591 { return; }
592 const record = this.directory.get(entityId);
593 if (!record)
594 {
595 this.characterEntities.delete(characterId);
596 return;
597 }
598 this.#saveBag(entityId, record.workerId);
599 const dropped = this.workers[record.workerId].call({
600 type: WorkerMessage.despawnCharacter,
601 characterId
602 });
603 if (dropped)
604 {
605 this.stateDb.saveCharacterPosition(
606 characterId,
607 dropped.tileX,
608 dropped.tileY,
609 dropped.gait ?? GAIT.walk
610 );
611 this.#queueReplication(replicationDespawn(dropped));
612 }
613 this.#forget(entityId);
614 this.#recalculateActivation(this.now);
615 this.#syncGhosts();
616 }
617
618 entityForCharacter (characterId)
619 {
620 return this.characterEntities.get(characterId) ?? null;
621 }
622
623 entityRecord (entityId)
624 {
625 const record = this.directory.get(entityId);
626 return record ? { ...record } : null;
627 }
628
629 positionOf (entityId)
630 {
631 const record = this.directory.get(entityId);
632 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
633 }
634
635 bagOf (entityId)
636 {
637 const record = this.directory.get(entityId);
638 if (!record)
639 { return null; }
640 return this.workers[record.workerId].call({
641 type: WorkerMessage.inspectBag,
642 entityId
643 });
644 }
645
646 snapshotFor (entityId)
647 {
648 const record = this.directory.get(entityId);
649 if (!record)
650 { return []; }
651 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
652 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
653 }
654
655 snapshotChunk (chunkX, chunkY)
656 {
657 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
658 if (owner == null)
659 { return this.#syntheticSnapshot(chunkX, chunkY); }
660 return this.workers[owner].call({
661 type: WorkerMessage.snapshotChunk,
662 chunkX,
663 chunkY
664 });
665 }
666
667 findOpenSpawn ()
668 {
669 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
670 for (const coord of coords)
671 {
672 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
673 if (!data.open)
674 { continue; }
675 for (let localY = 0; localY < CHUNK_SIZE; localY++)
676 {
677 for (let localX = 0; localX < CHUNK_SIZE; localX++)
678 {
679 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
680 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
681 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
682 { return { tileX, tileY }; }
683 }
684 }
685 }
686 return null;
687 }
688
689 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
690 #findResumeTile (tileX, tileY, radius = 24)
691 {
692 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
693 }
694
695 #findNearbyEnterable (originX, originY, maxRadius)
696 {
697 for (let radius = 0; radius <= maxRadius; radius++)
698 {
699 for (let dy = -radius; dy <= radius; dy++)
700 {
701 for (let dx = -radius; dx <= radius; dx++)
702 {
703 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
704 { continue; }
705 const tileX = originX + dx;
706 const tileY = originY + dy;
707 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
708 { return { tileX, tileY }; }
709 }
710 }
711 }
712 return null;
713 }
714
715 isEnterable (tileX, tileY)
716 {
717 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
718 if (!data.open)
719 { return false; }
720 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
721 }
722
723 debugWorld ()
724 {
725 const loaders = this.#allLoaders();
726 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
727 const simulatingChunks = [...chunkSim.entries()]
728 .filter(([, count]) => count > 0)
729 .map(([key]) => key)
730 .sort();
731 return {
732 tickIndex: this.tickIndex,
733 workerCount: this.workers.length,
734 workerMode: this.workerMode,
735 simulatingChunks,
736 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
737 ...parseRegionKey(key),
738 workerId,
739 state: REGION_RUNTIME_STATE.resident,
740 refs: regionRes.get(key) ?? 0,
741 graceUntil: this.regionGraceUntil.get(key) ?? null
742 })),
743 entities: [...this.directory.values()].map((entity) => ({
744 entityId: entity.entityId,
745 workerId: entity.workerId,
746 tileX: entity.tileX,
747 tileY: entity.tileY,
748 characterId: entity.characterId
749 }))
750 };
751 }
752
753 async shutdown ()
754 {
755 for (const characterId of [...this.characterEntities.keys()])
756 { this.despawnCharacter(characterId); }
757 this.forceUnloadAll();
758 await Promise.all(this.workers.map((worker) => worker.terminate()));
759 }
760
761 forceUnloadAll ()
762 {
763 for (const key of [...this.regionOwner.keys()])
764 {
765 const { regionX, regionY } = parseRegionKey(key);
766 this.#unloadRegion(regionX, regionY);
767 }
768 }
769
770 #configureWorkers ()
771 {
772 for (const worker of this.workers)
773 {
774 worker.call({
775 type: WorkerMessage.configure,
776 settings: this.settings,
777 activeRevisionId: this.activeRevisionId
778 });
779 }
780 }
781
782 #routeCommand (item)
783 {
784 if (item.command.type === "respawn")
785 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
786 if (
787 item.command.type === "open-market"
788 || item.command.type === "place-market-sell"
789 || item.command.type === "place-market-buy"
790 || item.command.type === "cancel-market-order"
791 || item.command.type === "close-market"
792 )
793 {
794 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
795 return result?.events ?? [];
796 }
797 const entityId = this.characterEntities.get(item.command.characterId);
798 const record = entityId ? this.directory.get(entityId) : null;
799 if (!record)
800 {
801 const error = new Error("Character is not in the world.");
802 error.userFacing = true;
803 throw error;
804 }
805 if (item.command.type === "drop-item" && item.command.groundItemId == null)
806 { item.command.groundItemId = this.nextGroundItemId++; }
807 if (item.command.type === "attack")
808 {
809 const targetRecord = this.directory.get(item.command.targetEntityId);
810 if (!targetRecord)
811 {
812 const error = new Error("Target is not here.");
813 error.userFacing = true;
814 throw error;
815 }
816 const events = this.#finishRoutedCommand(item, record);
817 if (targetRecord.workerId !== record.workerId)
818 {
819 this.workers[targetRecord.workerId].call({
820 type: WorkerMessage.remoteCombatEngage,
821 attackerEntityId: record.entityId,
822 targetEntityId: item.command.targetEntityId,
823 now: item.receivedAt ?? this.now
824 });
825 }
826 return events;
827 }
828 return this.#finishRoutedCommand(item, record);
829 }
830
831 #finishRoutedCommand (item, record)
832 {
833 const result = this.workers[record.workerId].call({
834 type: WorkerMessage.command,
835 sessionId: item.sessionId,
836 command: item.command,
837 now: item.receivedAt ?? this.now
838 });
839 const view = this.workers[record.workerId].call({
840 type: WorkerMessage.inspect,
841 entityId: record.entityId
842 });
843 if (view)
844 { this.#remember(view, record.workerId); }
845 if (result?.private)
846 { this.#saveBagFromView(item.command.characterId, result.private); }
847 if (result?.appearanceChanged && view)
848 { this.#queueReplication(replicationAppearance(view)); }
849 if (result?.remainder)
850 {
851 this.stateDb.saveInheritance(
852 this.stateDb.getCharacter(item.command.characterId).account_id,
853 { slots: result.remainder }
854 );
855 }
856 for (const event of result?.events ?? [])
857 { this.#persistGroundEvent(event); }
858 const events = [...(result?.events ?? [])];
859 if (result?.private)
860 {
861 events.push({
862 type: "inventory",
863 sessionId: item.sessionId,
864 bank: !!result.bank,
865 cauldron: result.cauldron,
866 cauldronState: result.cauldronState ?? null,
867 alchemyResult: result.alchemyResult ?? null,
868 ...result.private
869 });
870 }
871 return events;
872 }
873
874 #applyRemoteMelee (payload)
875 {
876 const targetRecord = this.directory.get(payload.targetId);
877 if (!targetRecord)
878 { return []; }
879 const result = this.workers[targetRecord.workerId].call({
880 ...payload,
881 type: WorkerMessage.applyRemoteMelee
882 });
883 const events = [];
884 for (const event of result?.events ?? [])
885 {
886 if (event.type === "entity-despawn")
887 { this.#forget(event.entityId); }
888 if (event.type === "skills-updated")
889 { this.#applySkillsUpdated(event); }
890 if (event.type === "player-died")
891 {
892 events.push(...this.#applyPlayerDeath(event));
893 continue;
894 }
895 this.#persistGroundEvent(event);
896 if (event.type !== "skills-updated")
897 { events.push(event); }
898 }
899 for (const forward of result?.forwards ?? [])
900 {
901 if (forward.type !== "forward-combat-xp")
902 { continue; }
903 const attackerRecord = this.directory.get(forward.entityId);
904 if (!attackerRecord)
905 { continue; }
906 const xpResult = this.workers[attackerRecord.workerId].call({
907 type: WorkerMessage.applyCombatHitXp,
908 entityId: forward.entityId,
909 profile: forward.profile
910 });
911 for (const xpEvent of xpResult?.events ?? [])
912 {
913 if (xpEvent.type === "skills-updated")
914 { this.#applySkillsUpdated(xpEvent); }
915 if (xpEvent.type !== "skills-updated")
916 { events.push(xpEvent); }
917 }
918 }
919 return events;
920 }
921
922 #applyPlayerDeath (event)
923 {
924 const record = this.directory.get(event.entityId);
925 if (!record)
926 { return [event]; }
927 this.stateDb.setCharacterDead(event.characterId, true);
928 this.stateDb.saveCharacterPosition(
929 event.characterId,
930 event.tileX,
931 event.tileY,
932 record.gait ?? GAIT.walk
933 );
934 for (const worker of this.workers)
935 {
936 worker.call({
937 type: WorkerMessage.clearCombat,
938 entityId: event.entityId,
939 targetEntityId: event.entityId
940 });
941 }
942 const result = this.workers[record.workerId].call({
943 type: WorkerMessage.spawnCorpseDrops,
944 characterId: event.characterId,
945 tileX: event.tileX,
946 tileY: event.tileY,
947 now: this.now,
948 drops: [
949 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
950 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
951 ]
952 });
953 const events = [event];
954 for (const dropEvent of result?.events ?? [])
955 {
956 this.#persistGroundEvent(dropEvent);
957 events.push(dropEvent);
958 }
959 return events;
960 }
961
962 #respawnCharacter (sessionId, characterId)
963 {
964 const row = this.stateDb.getCharacter(characterId);
965 if (!row?.is_dead)
966 {
967 const error = new Error("You are not dead.");
968 error.userFacing = true;
969 throw error;
970 }
971 const entityId = this.characterEntities.get(characterId);
972 const record = entityId ? this.directory.get(entityId) : null;
973 if (!record)
974 {
975 const error = new Error("Character is not in the world.");
976 error.userFacing = true;
977 throw error;
978 }
979 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
980 if (!destination)
981 {
982 const error = new Error("No open tile is available for respawn.");
983 error.userFacing = true;
984 throw error;
985 }
986 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
987 const loader = { ...DEFAULT_CHUNK_LOADER };
988 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
989 const result = this.workers[record.workerId].call({
990 type: WorkerMessage.applyRespawn,
991 entityId,
992 sessionId,
993 tileX: destination.tileX,
994 tileY: destination.tileY,
995 maxHealth: playerMaxHealth(skills),
996 maxStamina: playerMaxStamina(skills)
997 });
998 if (!result?.accepted)
999 {
1000 const error = new Error("That respawn tile is no longer available.");
1001 error.userFacing = true;
1002 throw error;
1003 }
1004 let moveEvents = [];
1005 if (result.transferRequest)
1006 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1007 else if (result.event)
1008 {
1009 this.#applyMoveToDirectory(result.event);
1010 moveEvents = [result.event];
1011 const view = this.workers[record.workerId].call({
1012 type: WorkerMessage.inspect,
1013 entityId
1014 });
1015 if (view)
1016 { this.#remember(view, record.workerId); }
1017 }
1018 if (!moveEvents.length)
1019 {
1020 const error = new Error("Respawn transfer failed.");
1021 error.userFacing = true;
1022 throw error;
1023 }
1024 this.stateDb.setCharacterDead(characterId, false);
1025 this.stateDb.saveCharacterPosition(
1026 characterId,
1027 destination.tileX,
1028 destination.tileY,
1029 record.gait ?? GAIT.walk
1030 );
1031 this.#recalculateActivation(this.now);
1032 this.#syncGhosts();
1033 return [
1034 ...moveEvents,
1035 {
1036 type: "player-respawned",
1037 entityId,
1038 characterId,
1039 sessionId,
1040 tileX: destination.tileX,
1041 tileY: destination.tileY,
1042 health: playerMaxHealth(skills),
1043 maxHealth: playerMaxHealth(skills),
1044 stamina: playerMaxStamina(skills),
1045 maxStamina: playerMaxStamina(skills)
1046 }
1047 ];
1048 }
1049
1050 #refreshAltarIndex ()
1051 {
1052 const altars = [];
1053 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1054 {
1055 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
1056 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1057 {
1058 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1059 {
1060 const block = data.blocks[localY * CHUNK_SIZE + localX];
1061 if (block?.typeId !== BlockType.churchAltar)
1062 { continue; }
1063 altars.push({
1064 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1065 tileY: coord.chunk_y * CHUNK_SIZE + localY
1066 });
1067 }
1068 }
1069 }
1070 this.altarTiles = altars;
1071 }
1072
1073 #findRespawnDestination (originX, originY, entityId)
1074 {
1075 const ordered = [...this.altarTiles].sort((left, right) =>
1076 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1077 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1078 );
1079 for (const altar of ordered)
1080 {
1081 const adjacent = [];
1082 for (let dy = -1; dy <= 1; dy++)
1083 {
1084 for (let dx = -1; dx <= 1; dx++)
1085 {
1086 if (dx === 0 && dy === 0)
1087 { continue; }
1088 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
1089 }
1090 }
1091 adjacent.sort((left, right) =>
1092 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1093 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1094 );
1095 const tile = adjacent.find((entry) =>
1096 this.isEnterable(entry.tileX, entry.tileY)
1097 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
1098 );
1099 if (tile)
1100 { return tile; }
1101 }
1102 for (let radius = 0; radius <= 24; radius++)
1103 {
1104 for (let dy = -radius; dy <= radius; dy++)
1105 {
1106 for (let dx = -radius; dx <= radius; dx++)
1107 {
1108 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1109 { continue; }
1110 const tileX = originX + dx;
1111 const tileY = originY + dy;
1112 if (this.isEnterable(tileX, tileY)
1113 && !this.#occupiedByOther(tileX, tileY, entityId))
1114 { return { tileX, tileY }; }
1115 }
1116 }
1117 }
1118 return this.findOpenSpawn();
1119 }
1120
1121 #occupiedByOther (tileX, tileY, entityId)
1122 {
1123 for (const record of this.directory.values())
1124 {
1125 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1126 { return true; }
1127 }
1128 return false;
1129 }
1130
1131 #recalculateActivation (now)
1132 {
1133 const loaders = this.#allLoaders();
1134 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1135
1136 for (const [key, count] of regionRes)
1137 {
1138 if (count <= 0)
1139 { continue; }
1140 const { regionX, regionY } = parseRegionKey(key);
1141 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
1142 this.regionGraceUntil.delete(key);
1143 }
1144
1145 for (const [key] of [...this.regionOwner.entries()])
1146 {
1147 if ((regionRes.get(key) ?? 0) > 0)
1148 { continue; }
1149 if (!this.regionGraceUntil.has(key))
1150 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1151 if (now >= this.regionGraceUntil.get(key))
1152 {
1153 const { regionX, regionY } = parseRegionKey(key);
1154 this.#unloadRegion(regionX, regionY);
1155 }
1156 }
1157
1158 for (const [workerId, worker] of this.workers.entries())
1159 {
1160 const chunkKeys = [];
1161 for (const [key, count] of chunkSim)
1162 {
1163 if (count <= 0)
1164 { continue; }
1165 const { chunkX, chunkY } = parseChunkKey(key);
1166 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
1167 { chunkKeys.push(key); }
1168 }
1169 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1170 }
1171 this.#syncAllReplicas();
1172
1173 const nextSimulating = new Set();
1174 for (const [key, count] of chunkSim)
1175 {
1176 if (count > 0)
1177 { nextSimulating.add(key); }
1178 }
1179 let preheated = false;
1180 for (const key of nextSimulating)
1181 {
1182 if (!this.simulatingChunkKeys.has(key))
1183 {
1184 preheated = true;
1185 break;
1186 }
1187 }
1188 this.simulatingChunkKeys = nextSimulating;
1189 if (preheated)
1190 { this.#stepSpawners(); }
1191 }
1192
1193 #ensureCoverage (tileX, tileY, loader)
1194 {
1195 const coverage = loaderCoverage(tileX, tileY, loader);
1196 let preferred = this.#ownerOfTile(tileX, tileY);
1197 for (const region of coverage.residentRegions)
1198 {
1199 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
1200 if (preferred == null)
1201 { preferred = owner; }
1202 }
1203 }
1204
1205 #ensureRegion (regionX, regionY, preferredWorkerId)
1206 {
1207 const key = regionKey(regionX, regionY);
1208 if (this.regionOwner.has(key))
1209 { return this.regionOwner.get(key); }
1210 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
1211 this.workers[workerId].call({
1212 type: WorkerMessage.assignRegion,
1213 regionX,
1214 regionY,
1215 chunks: this.#regionChunkBlobs(regionX, regionY)
1216 });
1217 this.regionOwner.set(key, workerId);
1218 this.#restorePersistent(regionX, regionY, workerId);
1219 this.#restoreGroundItems(regionX, regionY, workerId);
1220 return workerId;
1221 }
1222
1223 #unloadRegion (regionX, regionY)
1224 {
1225 const key = regionKey(regionX, regionY);
1226 const workerId = this.regionOwner.get(key);
1227 if (workerId == null)
1228 { return; }
1229 const bounds = regionTileBounds(regionX, regionY);
1230 const { dropped, groundItems } = this.workers[workerId].call({
1231 type: WorkerMessage.dropRegion,
1232 regionX,
1233 regionY
1234 });
1235 const persistent = [];
1236 for (const record of dropped ?? [])
1237 {
1238 if (record.characterId)
1239 {
1240 this.stateDb.saveCharacterPosition(
1241 record.characterId,
1242 record.tileX,
1243 record.tileY,
1244 record.gait ?? GAIT.walk
1245 );
1246 }
1247 if (record.persistent)
1248 { persistent.push(record); }
1249 this.#forget(record.entityId);
1250 }
1251 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
1252 for (const item of groundItems ?? [])
1253 { this.stateDb.upsertGroundItem(item); }
1254 this.regionOwner.delete(key);
1255 this.regionGraceUntil.delete(key);
1256 }
1257
1258 #restorePersistent (regionX, regionY, workerId)
1259 {
1260 const bounds = regionTileBounds(regionX, regionY);
1261 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
1262 for (const row of rows)
1263 {
1264 if (this.directory.has(row.entity_id))
1265 { continue; }
1266 const components = JSON.parse(row.components_blob);
1267 const view = this.workers[workerId].call({
1268 type: WorkerMessage.spawn,
1269 entityId: row.entity_id,
1270 components
1271 });
1272 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
1273 this.#remember(view, workerId);
1274 }
1275 }
1276
1277 #applyTransfers (requests)
1278 {
1279 const events = [];
1280 for (const request of requests)
1281 {
1282 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
1283 if (destWorkerId === request.fromWorkerId)
1284 {
1285 this.workers[request.fromWorkerId].call({
1286 type: WorkerMessage.abortTransfer,
1287 entityId: request.entityId
1288 });
1289 continue;
1290 }
1291 let result;
1292 try
1293 {
1294 result = this.workers[destWorkerId].call({
1295 type: WorkerMessage.applyTransfer,
1296 payload: request.payload,
1297 destTileX: request.destTileX,
1298 destTileY: request.destTileY
1299 });
1300 }
1301 catch
1302 {
1303 result = { accepted: false };
1304 }
1305 if (!result?.accepted)
1306 {
1307 this.workers[request.fromWorkerId].call({
1308 type: WorkerMessage.abortTransfer,
1309 entityId: request.entityId
1310 });
1311 continue;
1312 }
1313 this.workers[request.fromWorkerId].call({
1314 type: WorkerMessage.commitTransfer,
1315 entityId: request.entityId
1316 });
1317 this.#remember(result.entity, destWorkerId);
1318 events.push({
1319 type: "entity-move",
1320 entityId: request.entityId,
1321 fromTileX: request.fromTileX,
1322 fromTileY: request.fromTileY,
1323 tileX: result.entity.tileX,
1324 tileY: result.entity.tileY,
1325 gait: result.entity.gait
1326 });
1327 }
1328 return events;
1329 }
1330
1331 #syncAllReplicas ()
1332 {
1333 for (const [workerId, worker] of this.workers.entries())
1334 {
1335 const ownedKeys = new Set();
1336 for (const [key, owner] of this.regionOwner)
1337 {
1338 if (owner !== workerId)
1339 { continue; }
1340 const { regionX, regionY } = parseRegionKey(key);
1341 for (const chunk of chunksInRegion(regionX, regionY))
1342 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
1343 }
1344 const replicas = [];
1345 for (const key of replicaNeededForOwnedChunks(ownedKeys))
1346 {
1347 if (ownedKeys.has(key))
1348 { continue; }
1349 const { chunkX, chunkY } = parseChunkKey(key);
1350 replicas.push({
1351 chunkX,
1352 chunkY,
1353 data: this.#authoredChunk(chunkX, chunkY)
1354 });
1355 }
1356 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
1357 }
1358 }
1359
1360 #syncGhosts ()
1361 {
1362 const entities = [];
1363 for (const worker of this.workers)
1364 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
1365 for (const [workerId, worker] of this.workers.entries())
1366 {
1367 const ghosts = entities.filter((entity) =>
1368 {
1369 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
1370 { return false; }
1371 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
1372 });
1373 worker.call({ type: WorkerMessage.setGhosts, ghosts });
1374 }
1375 }
1376
1377 #nearWorker (workerId, tileX, tileY)
1378 {
1379 const chunkX = tileToChunk(tileX);
1380 const chunkY = tileToChunk(tileY);
1381 for (const [key, owner] of this.regionOwner)
1382 {
1383 if (owner !== workerId)
1384 { continue; }
1385 const { regionX, regionY } = parseRegionKey(key);
1386 for (const chunk of chunksInRegion(regionX, regionY))
1387 {
1388 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
1389 { return true; }
1390 }
1391 }
1392 return false;
1393 }
1394
1395 #allLoaders ()
1396 {
1397 const loaders = [];
1398 for (const worker of this.workers)
1399 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
1400 return loaders;
1401 }
1402
1403 #preferredWorkerForRegion (loaders, regionX, regionY)
1404 {
1405 const votes = new Map();
1406 for (const loader of loaders)
1407 {
1408 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
1409 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
1410 { continue; }
1411 const record = this.directory.get(loader.entityId);
1412 if (record?.workerId == null)
1413 { continue; }
1414 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
1415 }
1416 let best = null;
1417 let bestVotes = -1;
1418 for (const [workerId, count] of votes)
1419 {
1420 if (count > bestVotes)
1421 {
1422 best = workerId;
1423 bestVotes = count;
1424 }
1425 }
1426 return best;
1427 }
1428
1429 #pickWorker (regionX, regionY, preferredWorkerId)
1430 {
1431 const pinned = this.pinRegion?.(regionX, regionY);
1432 if (pinned != null)
1433 { return pinned; }
1434
1435 const neighborOwners = [];
1436 for (let dy = -1; dy <= 1; dy++)
1437 {
1438 for (let dx = -1; dx <= 1; dx++)
1439 {
1440 if (dx === 0 && dy === 0)
1441 { continue; }
1442 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
1443 if (owner != null)
1444 { neighborOwners.push(owner); }
1445 }
1446 }
1447
1448 const scores = this.workers.map((_, workerId) => ({
1449 workerId,
1450 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
1451 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
1452 }));
1453
1454 if (preferredWorkerId != null && scores[preferredWorkerId])
1455 {
1456 const preferred = scores[preferredWorkerId];
1457 if (preferred.neighbors > 0 || neighborOwners.length === 0)
1458 { return preferredWorkerId; }
1459 }
1460
1461 scores.sort((left, right) =>
1462 right.neighbors - left.neighbors
1463 || left.load - right.load
1464 || left.workerId - right.workerId
1465 );
1466 return scores[0].workerId;
1467 }
1468
1469 #ownerOfTile (tileX, tileY)
1470 {
1471 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
1472 }
1473
1474 #regionKeyForChunk (chunkX, chunkY)
1475 {
1476 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
1477 }
1478
1479 #regionChunkBlobs (regionX, regionY)
1480 {
1481 return chunksInRegion(regionX, regionY).map((coord) => ({
1482 chunkX: coord.chunkX,
1483 chunkY: coord.chunkY,
1484 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
1485 }));
1486 }
1487
1488 #authoredChunk (chunkX, chunkY)
1489 {
1490 const key = chunkKey(chunkX, chunkY);
1491 if (this.authoredCache.has(key))
1492 { return this.authoredCache.get(key); }
1493 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1494 const data = row
1495 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
1496 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1497 this.authoredCache.set(key, data);
1498 return data;
1499 }
1500
1501 #syntheticSnapshot (chunkX, chunkY)
1502 {
1503 const data = this.#authoredChunk(chunkX, chunkY);
1504 return {
1505 chunkX,
1506 chunkY,
1507 open: data.open,
1508 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
1509 grounds: data.grounds,
1510 blocks: data.blocks,
1511 light: data.light,
1512 entities: [],
1513 groundItems: []
1514 };
1515 }
1516
1517 #occupiedTile (tileX, tileY)
1518 {
1519 for (const record of this.directory.values())
1520 {
1521 if (record.tileX === tileX && record.tileY === tileY)
1522 { return record.entityId; }
1523 }
1524 return null;
1525 }
1526
1527 #queueReplication (event)
1528 {
1529 if (event)
1530 { this.replication.push(event); }
1531 }
1532
1533 #stepSpawners ()
1534 {
1535 const events = [];
1536 for (const worker of this.workers)
1537 {
1538 const result = worker.call({ type: WorkerMessage.stepSpawners });
1539 for (const request of result?.spawnRequests ?? [])
1540 {
1541 try
1542 {
1543 this.spawnEntity(mobComponents(request), { requireResident: true });
1544 }
1545 catch
1546 { continue; }
1547 }
1548 }
1549 return events;
1550 }
1551
1552 #restoreGroundItems (regionX, regionY, workerId)
1553 {
1554 const bounds = regionTileBounds(regionX, regionY);
1555 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
1556 .filter((item) => item.expiresAt > this.now);
1557 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
1558 this.workers[workerId].call({
1559 type: WorkerMessage.setGroundItems,
1560 regionX,
1561 regionY,
1562 items
1563 });
1564 }
1565
1566 #persistGroundEvent (event)
1567 {
1568 if (event.type === "ground-item-appear")
1569 {
1570 this.stateDb.upsertGroundItem({
1571 groundItemId: event.groundItemId,
1572 tileX: event.tileX,
1573 tileY: event.tileY,
1574 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
1575 droppedAt: event.droppedAt ?? this.now,
1576 expiresAt: event.expiresAt,
1577 source: event.source ?? "player-drop",
1578 droppedByCharacterId: event.droppedByCharacterId ?? null
1579 });
1580 }
1581 if (event.type === "ground-item-despawn")
1582 { this.stateDb.deleteGroundItem(event.groundItemId); }
1583 }
1584
1585 #saveBag (entityId, workerId)
1586 {
1587 const record = this.directory.get(entityId);
1588 const bag = this.workers[workerId].call({
1589 type: WorkerMessage.inspectBag,
1590 entityId
1591 });
1592 if (!bag || !record?.characterId)
1593 { return; }
1594 this.#saveBagFromView(record.characterId, bag);
1595 const skills = this.workers[workerId].call({
1596 type: WorkerMessage.inspectSkills,
1597 entityId
1598 });
1599 if (skills)
1600 { this.stateDb.saveSkills(record.characterId, skills); }
1601 }
1602
1603 #applySkillsUpdated (event)
1604 {
1605 if (!event?.characterId || !event.stored)
1606 { return; }
1607 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1608 this.pushSkills(event.characterId, event.skills ?? []);
1609 }
1610
1611 #saveBagFromView (characterId, bag)
1612 {
1613 this.stateDb.saveBag(characterId, {
1614 inventory: bag.inventory,
1615 equipment: bag.equipment,
1616 vault: bag.vault,
1617 vaultReserved: bag.vaultReserved
1618 });
1619 }
1620
1621 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
1622 {
1623 const onlineId = this.characterEntities.get(issuerCharacterId);
1624 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1625 if (!bag)
1626 { return { ok: false, error: "Issuer vault not found." }; }
1627 const reserved = [...(bag.vaultReserved ?? [])];
1628 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
1629 if (index < 0)
1630 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1631 const [stack] = reserved.splice(index, 1);
1632 bag.vaultReserved = reserved;
1633 this.stateDb.saveBag(issuerCharacterId, bag);
1634 if (onlineId)
1635 {
1636 this.applyBag(onlineId, bag);
1637 this.pushInventory(issuerCharacterId, bag);
1638 }
1639 return { ok: true, stack };
1640 }
1641
1642 restoreChequeReservation (issuerCharacterId, stack)
1643 {
1644 const onlineId = this.characterEntities.get(issuerCharacterId);
1645 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1646 if (!bag)
1647 { return; }
1648 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1649 this.stateDb.saveBag(issuerCharacterId, bag);
1650 if (onlineId)
1651 {
1652 this.applyBag(onlineId, bag);
1653 this.pushInventory(issuerCharacterId, bag);
1654 }
1655 }
1656
1657 #remember (view, workerId)
1658 {
1659 if (!view)
1660 { return; }
1661 this.directory.set(view.entityId, { ...view, workerId });
1662 if (view.characterId)
1663 { this.characterEntities.set(view.characterId, view.entityId); }
1664 }
1665
1666 #applyMoveToDirectory (event)
1667 {
1668 const record = this.directory.get(event.entityId);
1669 if (!record)
1670 { return; }
1671 record.tileX = event.tileX;
1672 record.tileY = event.tileY;
1673 record.gait = event.gait;
1674 if (event.worldX != null)
1675 { record.worldX = event.worldX; }
1676 if (event.worldY != null)
1677 { record.worldY = event.worldY; }
1678 if (event.freeFlight != null)
1679 { record.freeFlight = !!event.freeFlight; }
1680 }
1681
1682 #forget (entityId)
1683 {
1684 const record = this.directory.get(entityId);
1685 if (record?.characterId)
1686 { this.characterEntities.delete(record.characterId); }
1687 this.directory.delete(entityId);
1688 }
1689}