BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 46.3 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 * Path an idle CE clerk to a staff-side station tile.
559 */
560 stationExchangeClerk (stationTileX, stationTileY)
561 {
562 const owner = this.#ownerOfTile(stationTileX, stationTileY);
563 if (owner == null)
564 { return { ok: false, reason: "unowned" }; }
565 return this.workers[owner].call({
566 type: WorkerMessage.stationExchangeClerk,
567 stationTileX,
568 stationTileY
569 });
570 }
571
572 /**
573 * When a player uses a marketplace counter, path idle CE clerks to the
574 * opposite side of each adjacent counter (staff side).
575 */
576 stationExchangeClerks (playerTileX, playerTileY)
577 {
578 const results = [];
579 for (const tile of this.market?.marketTiles ?? [])
580 {
581 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
582 { continue; }
583 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
584 { continue; }
585 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
586 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
587 if (stationTileX === playerTileX && stationTileY === playerTileY)
588 { continue; }
589 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
590 }
591 return results;
592 }
593
594 /** Release a CE clerk stationed at the given staff-side tile. */
595 releaseExchangeClerk (stationTileX, stationTileY)
596 {
597 const owner = this.#ownerOfTile(stationTileX, stationTileY);
598 if (owner == null)
599 { return { ok: false, reason: "unowned" }; }
600 return this.workers[owner].call({
601 type: WorkerMessage.releaseExchangeClerk,
602 stationTileX,
603 stationTileY
604 });
605 }
606
607 despawnCharacter (characterId)
608 {
609 this.market?.leaveExchangeStations?.(characterId);
610 const entityId = this.characterEntities.get(characterId);
611 if (!entityId)
612 { return; }
613 const record = this.directory.get(entityId);
614 if (!record)
615 {
616 this.characterEntities.delete(characterId);
617 return;
618 }
619 this.#saveBag(entityId, record.workerId);
620 const dropped = this.workers[record.workerId].call({
621 type: WorkerMessage.despawnCharacter,
622 characterId
623 });
624 if (dropped)
625 {
626 this.stateDb.saveCharacterPosition(
627 characterId,
628 dropped.tileX,
629 dropped.tileY,
630 dropped.gait ?? GAIT.walk
631 );
632 this.#queueReplication(replicationDespawn(dropped));
633 }
634 this.#forget(entityId);
635 this.#recalculateActivation(this.now);
636 this.#syncGhosts();
637 }
638
639 entityForCharacter (characterId)
640 {
641 return this.characterEntities.get(characterId) ?? null;
642 }
643
644 entityRecord (entityId)
645 {
646 const record = this.directory.get(entityId);
647 return record ? { ...record } : null;
648 }
649
650 positionOf (entityId)
651 {
652 const record = this.directory.get(entityId);
653 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
654 }
655
656 bagOf (entityId)
657 {
658 const record = this.directory.get(entityId);
659 if (!record)
660 { return null; }
661 return this.workers[record.workerId].call({
662 type: WorkerMessage.inspectBag,
663 entityId
664 });
665 }
666
667 snapshotFor (entityId)
668 {
669 const record = this.directory.get(entityId);
670 if (!record)
671 { return []; }
672 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
673 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
674 }
675
676 snapshotChunk (chunkX, chunkY)
677 {
678 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
679 if (owner == null)
680 { return this.#syntheticSnapshot(chunkX, chunkY); }
681 return this.workers[owner].call({
682 type: WorkerMessage.snapshotChunk,
683 chunkX,
684 chunkY
685 });
686 }
687
688 findOpenSpawn ()
689 {
690 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
691 for (const coord of coords)
692 {
693 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
694 if (!data.open)
695 { continue; }
696 for (let localY = 0; localY < CHUNK_SIZE; localY++)
697 {
698 for (let localX = 0; localX < CHUNK_SIZE; localX++)
699 {
700 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
701 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
702 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
703 { return { tileX, tileY }; }
704 }
705 }
706 }
707 return null;
708 }
709
710 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
711 #findResumeTile (tileX, tileY, radius = 24)
712 {
713 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
714 }
715
716 #findNearbyEnterable (originX, originY, maxRadius)
717 {
718 for (let radius = 0; radius <= maxRadius; radius++)
719 {
720 for (let dy = -radius; dy <= radius; dy++)
721 {
722 for (let dx = -radius; dx <= radius; dx++)
723 {
724 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
725 { continue; }
726 const tileX = originX + dx;
727 const tileY = originY + dy;
728 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
729 { return { tileX, tileY }; }
730 }
731 }
732 }
733 return null;
734 }
735
736 isEnterable (tileX, tileY)
737 {
738 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
739 if (!data.open)
740 { return false; }
741 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
742 }
743
744 debugWorld ()
745 {
746 const loaders = this.#allLoaders();
747 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
748 const simulatingChunks = [...chunkSim.entries()]
749 .filter(([, count]) => count > 0)
750 .map(([key]) => key)
751 .sort();
752 return {
753 tickIndex: this.tickIndex,
754 workerCount: this.workers.length,
755 workerMode: this.workerMode,
756 simulatingChunks,
757 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
758 ...parseRegionKey(key),
759 workerId,
760 state: REGION_RUNTIME_STATE.resident,
761 refs: regionRes.get(key) ?? 0,
762 graceUntil: this.regionGraceUntil.get(key) ?? null
763 })),
764 entities: [...this.directory.values()].map((entity) => ({
765 entityId: entity.entityId,
766 workerId: entity.workerId,
767 tileX: entity.tileX,
768 tileY: entity.tileY,
769 characterId: entity.characterId
770 }))
771 };
772 }
773
774 async shutdown ()
775 {
776 for (const characterId of [...this.characterEntities.keys()])
777 { this.despawnCharacter(characterId); }
778 this.forceUnloadAll();
779 await Promise.all(this.workers.map((worker) => worker.terminate()));
780 }
781
782 forceUnloadAll ()
783 {
784 for (const key of [...this.regionOwner.keys()])
785 {
786 const { regionX, regionY } = parseRegionKey(key);
787 this.#unloadRegion(regionX, regionY);
788 }
789 }
790
791 #configureWorkers ()
792 {
793 for (const worker of this.workers)
794 {
795 worker.call({
796 type: WorkerMessage.configure,
797 settings: this.settings,
798 activeRevisionId: this.activeRevisionId
799 });
800 }
801 }
802
803 #routeCommand (item)
804 {
805 if (item.command.type === "respawn")
806 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
807 if (
808 item.command.type === "open-market"
809 || item.command.type === "place-market-sell"
810 || item.command.type === "place-market-buy"
811 || item.command.type === "cancel-market-order"
812 || item.command.type === "close-market"
813 )
814 {
815 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
816 return result?.events ?? [];
817 }
818 const entityId = this.characterEntities.get(item.command.characterId);
819 const record = entityId ? this.directory.get(entityId) : null;
820 if (!record)
821 {
822 const error = new Error("Character is not in the world.");
823 error.userFacing = true;
824 throw error;
825 }
826 if (item.command.type === "drop-item" && item.command.groundItemId == null)
827 { item.command.groundItemId = this.nextGroundItemId++; }
828 if (item.command.type === "attack")
829 {
830 const targetRecord = this.directory.get(item.command.targetEntityId);
831 if (!targetRecord)
832 {
833 const error = new Error("Target is not here.");
834 error.userFacing = true;
835 throw error;
836 }
837 const events = this.#finishRoutedCommand(item, record);
838 if (targetRecord.workerId !== record.workerId)
839 {
840 this.workers[targetRecord.workerId].call({
841 type: WorkerMessage.remoteCombatEngage,
842 attackerEntityId: record.entityId,
843 targetEntityId: item.command.targetEntityId,
844 now: item.receivedAt ?? this.now
845 });
846 }
847 return events;
848 }
849 return this.#finishRoutedCommand(item, record);
850 }
851
852 #finishRoutedCommand (item, record)
853 {
854 const result = this.workers[record.workerId].call({
855 type: WorkerMessage.command,
856 sessionId: item.sessionId,
857 command: item.command,
858 now: item.receivedAt ?? this.now
859 });
860 const view = this.workers[record.workerId].call({
861 type: WorkerMessage.inspect,
862 entityId: record.entityId
863 });
864 if (view)
865 { this.#remember(view, record.workerId); }
866 if (result?.private)
867 { this.#saveBagFromView(item.command.characterId, result.private); }
868 if (result?.appearanceChanged && view)
869 { this.#queueReplication(replicationAppearance(view)); }
870 if (result?.remainder)
871 {
872 this.stateDb.saveInheritance(
873 this.stateDb.getCharacter(item.command.characterId).account_id,
874 { slots: result.remainder }
875 );
876 }
877 for (const event of result?.events ?? [])
878 { this.#persistGroundEvent(event); }
879 const events = [...(result?.events ?? [])];
880 if (result?.private)
881 {
882 events.push({
883 type: "inventory",
884 sessionId: item.sessionId,
885 bank: !!result.bank,
886 cauldron: result.cauldron,
887 cauldronState: result.cauldronState ?? null,
888 alchemyResult: result.alchemyResult ?? null,
889 ...result.private
890 });
891 }
892 return events;
893 }
894
895 #applyRemoteMelee (payload)
896 {
897 const targetRecord = this.directory.get(payload.targetId);
898 if (!targetRecord)
899 { return []; }
900 const result = this.workers[targetRecord.workerId].call({
901 ...payload,
902 type: WorkerMessage.applyRemoteMelee
903 });
904 const events = [];
905 for (const event of result?.events ?? [])
906 {
907 if (event.type === "entity-despawn")
908 { this.#forget(event.entityId); }
909 if (event.type === "skills-updated")
910 { this.#applySkillsUpdated(event); }
911 if (event.type === "player-died")
912 {
913 events.push(...this.#applyPlayerDeath(event));
914 continue;
915 }
916 this.#persistGroundEvent(event);
917 if (event.type !== "skills-updated")
918 { events.push(event); }
919 }
920 for (const forward of result?.forwards ?? [])
921 {
922 if (forward.type !== "forward-combat-xp")
923 { continue; }
924 const attackerRecord = this.directory.get(forward.entityId);
925 if (!attackerRecord)
926 { continue; }
927 const xpResult = this.workers[attackerRecord.workerId].call({
928 type: WorkerMessage.applyCombatHitXp,
929 entityId: forward.entityId,
930 profile: forward.profile
931 });
932 for (const xpEvent of xpResult?.events ?? [])
933 {
934 if (xpEvent.type === "skills-updated")
935 { this.#applySkillsUpdated(xpEvent); }
936 if (xpEvent.type !== "skills-updated")
937 { events.push(xpEvent); }
938 }
939 }
940 return events;
941 }
942
943 #applyPlayerDeath (event)
944 {
945 const record = this.directory.get(event.entityId);
946 if (!record)
947 { return [event]; }
948 this.stateDb.setCharacterDead(event.characterId, true);
949 this.stateDb.saveCharacterPosition(
950 event.characterId,
951 event.tileX,
952 event.tileY,
953 record.gait ?? GAIT.walk
954 );
955 for (const worker of this.workers)
956 {
957 worker.call({
958 type: WorkerMessage.clearCombat,
959 entityId: event.entityId,
960 targetEntityId: event.entityId
961 });
962 }
963 const result = this.workers[record.workerId].call({
964 type: WorkerMessage.spawnCorpseDrops,
965 characterId: event.characterId,
966 tileX: event.tileX,
967 tileY: event.tileY,
968 now: this.now,
969 drops: [
970 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
971 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
972 ]
973 });
974 const events = [event];
975 for (const dropEvent of result?.events ?? [])
976 {
977 this.#persistGroundEvent(dropEvent);
978 events.push(dropEvent);
979 }
980 return events;
981 }
982
983 #respawnCharacter (sessionId, characterId)
984 {
985 const row = this.stateDb.getCharacter(characterId);
986 if (!row?.is_dead)
987 {
988 const error = new Error("You are not dead.");
989 error.userFacing = true;
990 throw error;
991 }
992 const entityId = this.characterEntities.get(characterId);
993 const record = entityId ? this.directory.get(entityId) : null;
994 if (!record)
995 {
996 const error = new Error("Character is not in the world.");
997 error.userFacing = true;
998 throw error;
999 }
1000 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
1001 if (!destination)
1002 {
1003 const error = new Error("No open tile is available for respawn.");
1004 error.userFacing = true;
1005 throw error;
1006 }
1007 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1008 const loader = { ...DEFAULT_CHUNK_LOADER };
1009 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
1010 const result = this.workers[record.workerId].call({
1011 type: WorkerMessage.applyRespawn,
1012 entityId,
1013 sessionId,
1014 tileX: destination.tileX,
1015 tileY: destination.tileY,
1016 maxHealth: playerMaxHealth(skills),
1017 maxStamina: playerMaxStamina(skills)
1018 });
1019 if (!result?.accepted)
1020 {
1021 const error = new Error("That respawn tile is no longer available.");
1022 error.userFacing = true;
1023 throw error;
1024 }
1025 let moveEvents = [];
1026 if (result.transferRequest)
1027 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1028 else if (result.event)
1029 {
1030 this.#applyMoveToDirectory(result.event);
1031 moveEvents = [result.event];
1032 const view = this.workers[record.workerId].call({
1033 type: WorkerMessage.inspect,
1034 entityId
1035 });
1036 if (view)
1037 { this.#remember(view, record.workerId); }
1038 }
1039 if (!moveEvents.length)
1040 {
1041 const error = new Error("Respawn transfer failed.");
1042 error.userFacing = true;
1043 throw error;
1044 }
1045 this.stateDb.setCharacterDead(characterId, false);
1046 this.stateDb.saveCharacterPosition(
1047 characterId,
1048 destination.tileX,
1049 destination.tileY,
1050 record.gait ?? GAIT.walk
1051 );
1052 this.#recalculateActivation(this.now);
1053 this.#syncGhosts();
1054 return [
1055 ...moveEvents,
1056 {
1057 type: "player-respawned",
1058 entityId,
1059 characterId,
1060 sessionId,
1061 tileX: destination.tileX,
1062 tileY: destination.tileY,
1063 health: playerMaxHealth(skills),
1064 maxHealth: playerMaxHealth(skills),
1065 stamina: playerMaxStamina(skills),
1066 maxStamina: playerMaxStamina(skills)
1067 }
1068 ];
1069 }
1070
1071 #refreshAltarIndex ()
1072 {
1073 const altars = [];
1074 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1075 {
1076 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
1077 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1078 {
1079 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1080 {
1081 const block = data.blocks[localY * CHUNK_SIZE + localX];
1082 if (block?.typeId !== BlockType.churchAltar)
1083 { continue; }
1084 altars.push({
1085 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1086 tileY: coord.chunk_y * CHUNK_SIZE + localY
1087 });
1088 }
1089 }
1090 }
1091 this.altarTiles = altars;
1092 }
1093
1094 #findRespawnDestination (originX, originY, entityId)
1095 {
1096 const ordered = [...this.altarTiles].sort((left, right) =>
1097 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1098 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1099 );
1100 for (const altar of ordered)
1101 {
1102 const adjacent = [];
1103 for (let dy = -1; dy <= 1; dy++)
1104 {
1105 for (let dx = -1; dx <= 1; dx++)
1106 {
1107 if (dx === 0 && dy === 0)
1108 { continue; }
1109 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
1110 }
1111 }
1112 adjacent.sort((left, right) =>
1113 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1114 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1115 );
1116 const tile = adjacent.find((entry) =>
1117 this.isEnterable(entry.tileX, entry.tileY)
1118 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
1119 );
1120 if (tile)
1121 { return tile; }
1122 }
1123 for (let radius = 0; radius <= 24; radius++)
1124 {
1125 for (let dy = -radius; dy <= radius; dy++)
1126 {
1127 for (let dx = -radius; dx <= radius; dx++)
1128 {
1129 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1130 { continue; }
1131 const tileX = originX + dx;
1132 const tileY = originY + dy;
1133 if (this.isEnterable(tileX, tileY)
1134 && !this.#occupiedByOther(tileX, tileY, entityId))
1135 { return { tileX, tileY }; }
1136 }
1137 }
1138 }
1139 return this.findOpenSpawn();
1140 }
1141
1142 #occupiedByOther (tileX, tileY, entityId)
1143 {
1144 for (const record of this.directory.values())
1145 {
1146 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1147 { return true; }
1148 }
1149 return false;
1150 }
1151
1152 #recalculateActivation (now)
1153 {
1154 const loaders = this.#allLoaders();
1155 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1156
1157 for (const [key, count] of regionRes)
1158 {
1159 if (count <= 0)
1160 { continue; }
1161 const { regionX, regionY } = parseRegionKey(key);
1162 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
1163 this.regionGraceUntil.delete(key);
1164 }
1165
1166 for (const [key] of [...this.regionOwner.entries()])
1167 {
1168 if ((regionRes.get(key) ?? 0) > 0)
1169 { continue; }
1170 if (!this.regionGraceUntil.has(key))
1171 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1172 if (now >= this.regionGraceUntil.get(key))
1173 {
1174 const { regionX, regionY } = parseRegionKey(key);
1175 this.#unloadRegion(regionX, regionY);
1176 }
1177 }
1178
1179 for (const [workerId, worker] of this.workers.entries())
1180 {
1181 const chunkKeys = [];
1182 for (const [key, count] of chunkSim)
1183 {
1184 if (count <= 0)
1185 { continue; }
1186 const { chunkX, chunkY } = parseChunkKey(key);
1187 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
1188 { chunkKeys.push(key); }
1189 }
1190 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1191 }
1192 this.#syncAllReplicas();
1193
1194 const nextSimulating = new Set();
1195 for (const [key, count] of chunkSim)
1196 {
1197 if (count > 0)
1198 { nextSimulating.add(key); }
1199 }
1200 let preheated = false;
1201 for (const key of nextSimulating)
1202 {
1203 if (!this.simulatingChunkKeys.has(key))
1204 {
1205 preheated = true;
1206 break;
1207 }
1208 }
1209 this.simulatingChunkKeys = nextSimulating;
1210 if (preheated)
1211 { this.#stepSpawners(); }
1212 }
1213
1214 #ensureCoverage (tileX, tileY, loader)
1215 {
1216 const coverage = loaderCoverage(tileX, tileY, loader);
1217 let preferred = this.#ownerOfTile(tileX, tileY);
1218 for (const region of coverage.residentRegions)
1219 {
1220 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
1221 if (preferred == null)
1222 { preferred = owner; }
1223 }
1224 }
1225
1226 #ensureRegion (regionX, regionY, preferredWorkerId)
1227 {
1228 const key = regionKey(regionX, regionY);
1229 if (this.regionOwner.has(key))
1230 { return this.regionOwner.get(key); }
1231 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
1232 this.workers[workerId].call({
1233 type: WorkerMessage.assignRegion,
1234 regionX,
1235 regionY,
1236 chunks: this.#regionChunkBlobs(regionX, regionY)
1237 });
1238 this.regionOwner.set(key, workerId);
1239 this.#restorePersistent(regionX, regionY, workerId);
1240 this.#restoreGroundItems(regionX, regionY, workerId);
1241 return workerId;
1242 }
1243
1244 #unloadRegion (regionX, regionY)
1245 {
1246 const key = regionKey(regionX, regionY);
1247 const workerId = this.regionOwner.get(key);
1248 if (workerId == null)
1249 { return; }
1250 const bounds = regionTileBounds(regionX, regionY);
1251 const { dropped, groundItems } = this.workers[workerId].call({
1252 type: WorkerMessage.dropRegion,
1253 regionX,
1254 regionY
1255 });
1256 const persistent = [];
1257 for (const record of dropped ?? [])
1258 {
1259 if (record.characterId)
1260 {
1261 this.stateDb.saveCharacterPosition(
1262 record.characterId,
1263 record.tileX,
1264 record.tileY,
1265 record.gait ?? GAIT.walk
1266 );
1267 }
1268 if (record.persistent)
1269 { persistent.push(record); }
1270 this.#forget(record.entityId);
1271 }
1272 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
1273 for (const item of groundItems ?? [])
1274 { this.stateDb.upsertGroundItem(item); }
1275 this.regionOwner.delete(key);
1276 this.regionGraceUntil.delete(key);
1277 }
1278
1279 #restorePersistent (regionX, regionY, workerId)
1280 {
1281 const bounds = regionTileBounds(regionX, regionY);
1282 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
1283 for (const row of rows)
1284 {
1285 if (this.directory.has(row.entity_id))
1286 { continue; }
1287 const components = JSON.parse(row.components_blob);
1288 const view = this.workers[workerId].call({
1289 type: WorkerMessage.spawn,
1290 entityId: row.entity_id,
1291 components
1292 });
1293 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
1294 this.#remember(view, workerId);
1295 }
1296 }
1297
1298 #applyTransfers (requests)
1299 {
1300 const events = [];
1301 for (const request of requests)
1302 {
1303 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
1304 if (destWorkerId === request.fromWorkerId)
1305 {
1306 this.workers[request.fromWorkerId].call({
1307 type: WorkerMessage.abortTransfer,
1308 entityId: request.entityId
1309 });
1310 continue;
1311 }
1312 let result;
1313 try
1314 {
1315 result = this.workers[destWorkerId].call({
1316 type: WorkerMessage.applyTransfer,
1317 payload: request.payload,
1318 destTileX: request.destTileX,
1319 destTileY: request.destTileY
1320 });
1321 }
1322 catch
1323 {
1324 result = { accepted: false };
1325 }
1326 if (!result?.accepted)
1327 {
1328 this.workers[request.fromWorkerId].call({
1329 type: WorkerMessage.abortTransfer,
1330 entityId: request.entityId
1331 });
1332 continue;
1333 }
1334 this.workers[request.fromWorkerId].call({
1335 type: WorkerMessage.commitTransfer,
1336 entityId: request.entityId
1337 });
1338 this.#remember(result.entity, destWorkerId);
1339 events.push({
1340 type: "entity-move",
1341 entityId: request.entityId,
1342 fromTileX: request.fromTileX,
1343 fromTileY: request.fromTileY,
1344 tileX: result.entity.tileX,
1345 tileY: result.entity.tileY,
1346 gait: result.entity.gait
1347 });
1348 }
1349 return events;
1350 }
1351
1352 #syncAllReplicas ()
1353 {
1354 for (const [workerId, worker] of this.workers.entries())
1355 {
1356 const ownedKeys = new Set();
1357 for (const [key, owner] of this.regionOwner)
1358 {
1359 if (owner !== workerId)
1360 { continue; }
1361 const { regionX, regionY } = parseRegionKey(key);
1362 for (const chunk of chunksInRegion(regionX, regionY))
1363 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
1364 }
1365 const replicas = [];
1366 for (const key of replicaNeededForOwnedChunks(ownedKeys))
1367 {
1368 if (ownedKeys.has(key))
1369 { continue; }
1370 const { chunkX, chunkY } = parseChunkKey(key);
1371 replicas.push({
1372 chunkX,
1373 chunkY,
1374 data: this.#authoredChunk(chunkX, chunkY)
1375 });
1376 }
1377 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
1378 }
1379 }
1380
1381 #syncGhosts ()
1382 {
1383 const entities = [];
1384 for (const worker of this.workers)
1385 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
1386 for (const [workerId, worker] of this.workers.entries())
1387 {
1388 const ghosts = entities.filter((entity) =>
1389 {
1390 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
1391 { return false; }
1392 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
1393 });
1394 worker.call({ type: WorkerMessage.setGhosts, ghosts });
1395 }
1396 }
1397
1398 #nearWorker (workerId, tileX, tileY)
1399 {
1400 const chunkX = tileToChunk(tileX);
1401 const chunkY = tileToChunk(tileY);
1402 for (const [key, owner] of this.regionOwner)
1403 {
1404 if (owner !== workerId)
1405 { continue; }
1406 const { regionX, regionY } = parseRegionKey(key);
1407 for (const chunk of chunksInRegion(regionX, regionY))
1408 {
1409 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
1410 { return true; }
1411 }
1412 }
1413 return false;
1414 }
1415
1416 #allLoaders ()
1417 {
1418 const loaders = [];
1419 for (const worker of this.workers)
1420 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
1421 return loaders;
1422 }
1423
1424 #preferredWorkerForRegion (loaders, regionX, regionY)
1425 {
1426 const votes = new Map();
1427 for (const loader of loaders)
1428 {
1429 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
1430 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
1431 { continue; }
1432 const record = this.directory.get(loader.entityId);
1433 if (record?.workerId == null)
1434 { continue; }
1435 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
1436 }
1437 let best = null;
1438 let bestVotes = -1;
1439 for (const [workerId, count] of votes)
1440 {
1441 if (count > bestVotes)
1442 {
1443 best = workerId;
1444 bestVotes = count;
1445 }
1446 }
1447 return best;
1448 }
1449
1450 #pickWorker (regionX, regionY, preferredWorkerId)
1451 {
1452 const pinned = this.pinRegion?.(regionX, regionY);
1453 if (pinned != null)
1454 { return pinned; }
1455
1456 const neighborOwners = [];
1457 for (let dy = -1; dy <= 1; dy++)
1458 {
1459 for (let dx = -1; dx <= 1; dx++)
1460 {
1461 if (dx === 0 && dy === 0)
1462 { continue; }
1463 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
1464 if (owner != null)
1465 { neighborOwners.push(owner); }
1466 }
1467 }
1468
1469 const scores = this.workers.map((_, workerId) => ({
1470 workerId,
1471 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
1472 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
1473 }));
1474
1475 if (preferredWorkerId != null && scores[preferredWorkerId])
1476 {
1477 const preferred = scores[preferredWorkerId];
1478 if (preferred.neighbors > 0 || neighborOwners.length === 0)
1479 { return preferredWorkerId; }
1480 }
1481
1482 scores.sort((left, right) =>
1483 right.neighbors - left.neighbors
1484 || left.load - right.load
1485 || left.workerId - right.workerId
1486 );
1487 return scores[0].workerId;
1488 }
1489
1490 #ownerOfTile (tileX, tileY)
1491 {
1492 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
1493 }
1494
1495 #regionKeyForChunk (chunkX, chunkY)
1496 {
1497 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
1498 }
1499
1500 #regionChunkBlobs (regionX, regionY)
1501 {
1502 return chunksInRegion(regionX, regionY).map((coord) => ({
1503 chunkX: coord.chunkX,
1504 chunkY: coord.chunkY,
1505 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
1506 }));
1507 }
1508
1509 #authoredChunk (chunkX, chunkY)
1510 {
1511 const key = chunkKey(chunkX, chunkY);
1512 if (this.authoredCache.has(key))
1513 { return this.authoredCache.get(key); }
1514 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1515 const data = row
1516 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
1517 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1518 this.authoredCache.set(key, data);
1519 return data;
1520 }
1521
1522 #syntheticSnapshot (chunkX, chunkY)
1523 {
1524 const data = this.#authoredChunk(chunkX, chunkY);
1525 return {
1526 chunkX,
1527 chunkY,
1528 open: data.open,
1529 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
1530 grounds: data.grounds,
1531 blocks: data.blocks,
1532 light: data.light,
1533 entities: [],
1534 groundItems: []
1535 };
1536 }
1537
1538 #occupiedTile (tileX, tileY)
1539 {
1540 for (const record of this.directory.values())
1541 {
1542 if (record.tileX === tileX && record.tileY === tileY)
1543 { return record.entityId; }
1544 }
1545 return null;
1546 }
1547
1548 #queueReplication (event)
1549 {
1550 if (event)
1551 { this.replication.push(event); }
1552 }
1553
1554 #stepSpawners ()
1555 {
1556 const events = [];
1557 for (const worker of this.workers)
1558 {
1559 const result = worker.call({ type: WorkerMessage.stepSpawners });
1560 for (const request of result?.spawnRequests ?? [])
1561 {
1562 try
1563 {
1564 this.spawnEntity(mobComponents(request), { requireResident: true });
1565 }
1566 catch
1567 { continue; }
1568 }
1569 }
1570 return events;
1571 }
1572
1573 #restoreGroundItems (regionX, regionY, workerId)
1574 {
1575 const bounds = regionTileBounds(regionX, regionY);
1576 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
1577 .filter((item) => item.expiresAt > this.now);
1578 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
1579 this.workers[workerId].call({
1580 type: WorkerMessage.setGroundItems,
1581 regionX,
1582 regionY,
1583 items
1584 });
1585 }
1586
1587 #persistGroundEvent (event)
1588 {
1589 if (event.type === "ground-item-appear")
1590 {
1591 this.stateDb.upsertGroundItem({
1592 groundItemId: event.groundItemId,
1593 tileX: event.tileX,
1594 tileY: event.tileY,
1595 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
1596 droppedAt: event.droppedAt ?? this.now,
1597 expiresAt: event.expiresAt,
1598 source: event.source ?? "player-drop",
1599 droppedByCharacterId: event.droppedByCharacterId ?? null
1600 });
1601 }
1602 if (event.type === "ground-item-despawn")
1603 { this.stateDb.deleteGroundItem(event.groundItemId); }
1604 }
1605
1606 #saveBag (entityId, workerId)
1607 {
1608 const record = this.directory.get(entityId);
1609 const bag = this.workers[workerId].call({
1610 type: WorkerMessage.inspectBag,
1611 entityId
1612 });
1613 if (!bag || !record?.characterId)
1614 { return; }
1615 this.#saveBagFromView(record.characterId, bag);
1616 const skills = this.workers[workerId].call({
1617 type: WorkerMessage.inspectSkills,
1618 entityId
1619 });
1620 if (skills)
1621 { this.stateDb.saveSkills(record.characterId, skills); }
1622 }
1623
1624 #applySkillsUpdated (event)
1625 {
1626 if (!event?.characterId || !event.stored)
1627 { return; }
1628 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1629 this.pushSkills(event.characterId, event.skills ?? []);
1630 }
1631
1632 #saveBagFromView (characterId, bag)
1633 {
1634 this.stateDb.saveBag(characterId, {
1635 inventory: bag.inventory,
1636 equipment: bag.equipment,
1637 vault: bag.vault,
1638 vaultReserved: bag.vaultReserved
1639 });
1640 }
1641
1642 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
1643 {
1644 const onlineId = this.characterEntities.get(issuerCharacterId);
1645 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1646 if (!bag)
1647 { return { ok: false, error: "Issuer vault not found." }; }
1648 const reserved = [...(bag.vaultReserved ?? [])];
1649 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
1650 if (index < 0)
1651 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1652 const [stack] = reserved.splice(index, 1);
1653 bag.vaultReserved = reserved;
1654 this.stateDb.saveBag(issuerCharacterId, bag);
1655 if (onlineId)
1656 {
1657 this.applyBag(onlineId, bag);
1658 this.pushInventory(issuerCharacterId, bag);
1659 }
1660 return { ok: true, stack };
1661 }
1662
1663 restoreChequeReservation (issuerCharacterId, stack)
1664 {
1665 const onlineId = this.characterEntities.get(issuerCharacterId);
1666 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1667 if (!bag)
1668 { return; }
1669 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1670 this.stateDb.saveBag(issuerCharacterId, bag);
1671 if (onlineId)
1672 {
1673 this.applyBag(onlineId, bag);
1674 this.pushInventory(issuerCharacterId, bag);
1675 }
1676 }
1677
1678 #remember (view, workerId)
1679 {
1680 if (!view)
1681 { return; }
1682 this.directory.set(view.entityId, { ...view, workerId });
1683 if (view.characterId)
1684 { this.characterEntities.set(view.characterId, view.entityId); }
1685 }
1686
1687 #applyMoveToDirectory (event)
1688 {
1689 const record = this.directory.get(event.entityId);
1690 if (!record)
1691 { return; }
1692 record.tileX = event.tileX;
1693 record.tileY = event.tileY;
1694 record.gait = event.gait;
1695 if (event.worldX != null)
1696 { record.worldX = event.worldX; }
1697 if (event.worldY != null)
1698 { record.worldY = event.worldY; }
1699 if (event.freeFlight != null)
1700 { record.freeFlight = !!event.freeFlight; }
1701 }
1702
1703 #forget (entityId)
1704 {
1705 const record = this.directory.get(entityId);
1706 if (record?.characterId)
1707 { this.characterEntities.delete(record.characterId); }
1708 this.directory.delete(entityId);
1709 }
1710}