BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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