BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 52.6 KiB Download Raw
1import {
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 STATIC_CHUNK_RADIUS,
8 WORLD_YEAR_OFFSET
9} from "../../../shared/protocol/constants.js";
10import {
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 damage: forward.damage
1064 });
1065 for (const xpEvent of xpResult?.events ?? [])
1066 {
1067 if (xpEvent.type === "skills-updated")
1068 {
1069 this.#applySkillsUpdated(xpEvent);
1070 events.push(...this.#skillLevelUpEvents(xpEvent));
1071 continue;
1072 }
1073 events.push(xpEvent);
1074 }
1075 }
1076 return events;
1077 }
1078
1079 #applyRemoteRanged (payload)
1080 {
1081 const targetRecord = this.directory.get(payload.targetId);
1082 if (!targetRecord)
1083 { return []; }
1084 const result = this.workers[targetRecord.workerId].call({
1085 ...payload,
1086 type: WorkerMessage.applyRemoteRanged
1087 });
1088 const events = [];
1089 for (const event of result?.events ?? [])
1090 {
1091 if (event.type === "entity-despawn")
1092 { this.#forget(event.entityId); }
1093 if (event.type === "skills-updated")
1094 {
1095 this.#applySkillsUpdated(event);
1096 events.push(...this.#skillLevelUpEvents(event));
1097 continue;
1098 }
1099 if (event.type === "player-died")
1100 {
1101 events.push(...this.#applyPlayerDeath(event));
1102 continue;
1103 }
1104 this.#persistGroundEvent(event);
1105 if (event.type !== "skills-updated")
1106 { events.push(event); }
1107 }
1108 for (const forward of result?.forwards ?? [])
1109 {
1110 if (forward.type !== "forward-combat-xp")
1111 { continue; }
1112 const attackerRecord = this.directory.get(forward.entityId);
1113 if (!attackerRecord)
1114 { continue; }
1115 const xpResult = this.workers[attackerRecord.workerId].call({
1116 type: WorkerMessage.applyCombatHitXp,
1117 entityId: forward.entityId,
1118 profile: forward.profile,
1119 damage: forward.damage
1120 });
1121 for (const xpEvent of xpResult?.events ?? [])
1122 {
1123 if (xpEvent.type === "skills-updated")
1124 {
1125 this.#applySkillsUpdated(xpEvent);
1126 events.push(...this.#skillLevelUpEvents(xpEvent));
1127 continue;
1128 }
1129 events.push(xpEvent);
1130 }
1131 }
1132 return events;
1133 }
1134
1135 #applyPlayerDeath (event)
1136 {
1137 const record = this.directory.get(event.entityId);
1138 if (!record)
1139 { return [event]; }
1140 this.stateDb.setCharacterDead(event.characterId, true);
1141 this.stateDb.saveCharacterPosition(
1142 event.characterId,
1143 event.tileX,
1144 event.tileY,
1145 record.gait ?? GAIT.walk
1146 );
1147 this.bounty?.settleKill(
1148 event.characterId,
1149 event.attackerId,
1150 event.tileX,
1151 event.tileY
1152 );
1153 for (const worker of this.workers)
1154 {
1155 worker.call({
1156 type: WorkerMessage.clearCombat,
1157 entityId: event.entityId,
1158 targetEntityId: event.entityId
1159 });
1160 }
1161 const result = this.workers[record.workerId].call({
1162 type: WorkerMessage.spawnCorpseDrops,
1163 characterId: event.characterId,
1164 tileX: event.tileX,
1165 tileY: event.tileY,
1166 now: this.now,
1167 drops: [
1168 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
1169 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
1170 ]
1171 });
1172 const events = [event];
1173 for (const dropEvent of result?.events ?? [])
1174 {
1175 this.#persistGroundEvent(dropEvent);
1176 events.push(dropEvent);
1177 }
1178 return events;
1179 }
1180
1181 #respawnCharacter (sessionId, characterId)
1182 {
1183 const row = this.stateDb.getCharacter(characterId);
1184 if (!row?.is_dead)
1185 {
1186 const error = new Error("You are not dead.");
1187 error.userFacing = true;
1188 throw error;
1189 }
1190 const entityId = this.characterEntities.get(characterId);
1191 const record = entityId ? this.directory.get(entityId) : null;
1192 if (!record)
1193 {
1194 const error = new Error("Character is not in the world.");
1195 error.userFacing = true;
1196 throw error;
1197 }
1198 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
1199 if (!destination)
1200 {
1201 const error = new Error("No open tile is available for respawn.");
1202 error.userFacing = true;
1203 throw error;
1204 }
1205 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1206 const loader = { ...DEFAULT_CHUNK_LOADER };
1207 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
1208 const result = this.workers[record.workerId].call({
1209 type: WorkerMessage.applyRespawn,
1210 entityId,
1211 sessionId,
1212 tileX: destination.tileX,
1213 tileY: destination.tileY,
1214 maxHealth: playerMaxHealth(skills),
1215 maxStamina: playerMaxStamina(skills)
1216 });
1217 if (!result?.accepted)
1218 {
1219 const error = new Error("That respawn tile is no longer available.");
1220 error.userFacing = true;
1221 throw error;
1222 }
1223 let moveEvents = [];
1224 if (result.transferRequest)
1225 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1226 else if (result.event)
1227 {
1228 this.#applyMoveToDirectory(result.event);
1229 moveEvents = [result.event];
1230 const view = this.workers[record.workerId].call({
1231 type: WorkerMessage.inspect,
1232 entityId
1233 });
1234 if (view)
1235 { this.#remember(view, record.workerId); }
1236 }
1237 if (!moveEvents.length)
1238 {
1239 const error = new Error("Respawn transfer failed.");
1240 error.userFacing = true;
1241 throw error;
1242 }
1243 this.stateDb.setCharacterDead(characterId, false);
1244 this.stateDb.saveCharacterPosition(
1245 characterId,
1246 destination.tileX,
1247 destination.tileY,
1248 record.gait ?? GAIT.walk
1249 );
1250 this.#recalculateActivation(this.now);
1251 this.#syncGhosts();
1252 return [
1253 ...moveEvents,
1254 {
1255 type: "player-respawned",
1256 entityId,
1257 characterId,
1258 sessionId,
1259 tileX: destination.tileX,
1260 tileY: destination.tileY,
1261 health: playerMaxHealth(skills),
1262 maxHealth: playerMaxHealth(skills),
1263 stamina: playerMaxStamina(skills),
1264 maxStamina: playerMaxStamina(skills)
1265 }
1266 ];
1267 }
1268
1269 #refreshAltarIndex ()
1270 {
1271 const altars = [];
1272 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1273 {
1274 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
1275 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1276 {
1277 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1278 {
1279 const block = data.blocks[localY * CHUNK_SIZE + localX];
1280 if (block?.typeId !== BlockType.churchAltar)
1281 { continue; }
1282 altars.push({
1283 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1284 tileY: coord.chunk_y * CHUNK_SIZE + localY
1285 });
1286 }
1287 }
1288 }
1289 this.altarTiles = altars;
1290 }
1291
1292 #findRespawnDestination (originX, originY, entityId)
1293 {
1294 const ordered = [...this.altarTiles].sort((left, right) =>
1295 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1296 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1297 );
1298 for (const altar of ordered)
1299 {
1300 const adjacent = [];
1301 for (let dy = -1; dy <= 1; dy++)
1302 {
1303 for (let dx = -1; dx <= 1; dx++)
1304 {
1305 if (dx === 0 && dy === 0)
1306 { continue; }
1307 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
1308 }
1309 }
1310 adjacent.sort((left, right) =>
1311 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1312 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1313 );
1314 const tile = adjacent.find((entry) =>
1315 this.isEnterable(entry.tileX, entry.tileY)
1316 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
1317 );
1318 if (tile)
1319 { return tile; }
1320 }
1321 for (let radius = 0; radius <= 24; radius++)
1322 {
1323 for (let dy = -radius; dy <= radius; dy++)
1324 {
1325 for (let dx = -radius; dx <= radius; dx++)
1326 {
1327 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1328 { continue; }
1329 const tileX = originX + dx;
1330 const tileY = originY + dy;
1331 if (this.isEnterable(tileX, tileY)
1332 && !this.#occupiedByOther(tileX, tileY, entityId))
1333 { return { tileX, tileY }; }
1334 }
1335 }
1336 }
1337 return this.findOpenSpawn();
1338 }
1339
1340 #occupiedByOther (tileX, tileY, entityId)
1341 {
1342 for (const record of this.directory.values())
1343 {
1344 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1345 { return true; }
1346 }
1347 return false;
1348 }
1349
1350 #recalculateActivation (now)
1351 {
1352 const loaders = this.#allLoaders();
1353 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1354
1355 for (const [key, count] of regionRes)
1356 {
1357 if (count <= 0)
1358 { continue; }
1359 const { regionX, regionY } = parseRegionKey(key);
1360 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
1361 this.regionGraceUntil.delete(key);
1362 }
1363
1364 for (const [key] of [...this.regionOwner.entries()])
1365 {
1366 if ((regionRes.get(key) ?? 0) > 0)
1367 { continue; }
1368 if (!this.regionGraceUntil.has(key))
1369 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1370 if (now >= this.regionGraceUntil.get(key))
1371 {
1372 const { regionX, regionY } = parseRegionKey(key);
1373 this.#unloadRegion(regionX, regionY);
1374 }
1375 }
1376
1377 for (const [workerId, worker] of this.workers.entries())
1378 {
1379 const chunkKeys = [];
1380 for (const [key, count] of chunkSim)
1381 {
1382 if (count <= 0)
1383 { continue; }
1384 const { chunkX, chunkY } = parseChunkKey(key);
1385 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
1386 { chunkKeys.push(key); }
1387 }
1388 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1389 }
1390 this.#syncAllReplicas();
1391
1392 const nextSimulating = new Set();
1393 for (const [key, count] of chunkSim)
1394 {
1395 if (count > 0)
1396 { nextSimulating.add(key); }
1397 }
1398 let preheated = false;
1399 for (const key of nextSimulating)
1400 {
1401 if (!this.simulatingChunkKeys.has(key))
1402 {
1403 preheated = true;
1404 break;
1405 }
1406 }
1407 this.simulatingChunkKeys = nextSimulating;
1408 if (preheated)
1409 { this.#stepSpawners(); }
1410 }
1411
1412 #ensureCoverage (tileX, tileY, loader)
1413 {
1414 const coverage = loaderCoverage(tileX, tileY, loader);
1415 let preferred = this.#ownerOfTile(tileX, tileY);
1416 for (const region of coverage.residentRegions)
1417 {
1418 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
1419 if (preferred == null)
1420 { preferred = owner; }
1421 }
1422 }
1423
1424 #ensureRegion (regionX, regionY, preferredWorkerId)
1425 {
1426 const key = regionKey(regionX, regionY);
1427 if (this.regionOwner.has(key))
1428 { return this.regionOwner.get(key); }
1429 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
1430 this.workers[workerId].call({
1431 type: WorkerMessage.assignRegion,
1432 regionX,
1433 regionY,
1434 chunks: this.#regionChunkBlobs(regionX, regionY)
1435 });
1436 this.regionOwner.set(key, workerId);
1437 this.#restorePersistent(regionX, regionY, workerId);
1438 this.#restoreGroundItems(regionX, regionY, workerId);
1439 return workerId;
1440 }
1441
1442 #unloadRegion (regionX, regionY)
1443 {
1444 const key = regionKey(regionX, regionY);
1445 const workerId = this.regionOwner.get(key);
1446 if (workerId == null)
1447 { return; }
1448 const bounds = regionTileBounds(regionX, regionY);
1449 const { dropped, groundItems } = this.workers[workerId].call({
1450 type: WorkerMessage.dropRegion,
1451 regionX,
1452 regionY
1453 });
1454 const persistent = [];
1455 for (const record of dropped ?? [])
1456 {
1457 if (record.characterId)
1458 {
1459 this.stateDb.saveCharacterPosition(
1460 record.characterId,
1461 record.tileX,
1462 record.tileY,
1463 record.gait ?? GAIT.walk
1464 );
1465 }
1466 if (record.persistent)
1467 { persistent.push(record); }
1468 this.#forget(record.entityId);
1469 }
1470 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
1471 for (const item of groundItems ?? [])
1472 { this.stateDb.upsertGroundItem(item); }
1473 this.regionOwner.delete(key);
1474 this.regionGraceUntil.delete(key);
1475 }
1476
1477 #restorePersistent (regionX, regionY, workerId)
1478 {
1479 const bounds = regionTileBounds(regionX, regionY);
1480 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
1481 for (const row of rows)
1482 {
1483 if (this.directory.has(row.entity_id))
1484 { continue; }
1485 const components = JSON.parse(row.components_blob);
1486 const view = this.workers[workerId].call({
1487 type: WorkerMessage.spawn,
1488 entityId: row.entity_id,
1489 components
1490 });
1491 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
1492 this.#remember(view, workerId);
1493 }
1494 }
1495
1496 #applyTransfers (requests)
1497 {
1498 const events = [];
1499 for (const request of requests)
1500 {
1501 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
1502 if (destWorkerId === request.fromWorkerId)
1503 {
1504 this.workers[request.fromWorkerId].call({
1505 type: WorkerMessage.abortTransfer,
1506 entityId: request.entityId
1507 });
1508 continue;
1509 }
1510 let result;
1511 try
1512 {
1513 result = this.workers[destWorkerId].call({
1514 type: WorkerMessage.applyTransfer,
1515 payload: request.payload,
1516 destTileX: request.destTileX,
1517 destTileY: request.destTileY
1518 });
1519 }
1520 catch
1521 {
1522 result = { accepted: false };
1523 }
1524 if (!result?.accepted)
1525 {
1526 this.workers[request.fromWorkerId].call({
1527 type: WorkerMessage.abortTransfer,
1528 entityId: request.entityId
1529 });
1530 continue;
1531 }
1532 this.workers[request.fromWorkerId].call({
1533 type: WorkerMessage.commitTransfer,
1534 entityId: request.entityId
1535 });
1536 this.#remember(result.entity, destWorkerId);
1537 events.push({
1538 type: "entity-move",
1539 entityId: request.entityId,
1540 fromTileX: request.fromTileX,
1541 fromTileY: request.fromTileY,
1542 tileX: result.entity.tileX,
1543 tileY: result.entity.tileY,
1544 gait: result.entity.gait
1545 });
1546 }
1547 return events;
1548 }
1549
1550 #syncAllReplicas ()
1551 {
1552 for (const [workerId, worker] of this.workers.entries())
1553 {
1554 const ownedKeys = new Set();
1555 for (const [key, owner] of this.regionOwner)
1556 {
1557 if (owner !== workerId)
1558 { continue; }
1559 const { regionX, regionY } = parseRegionKey(key);
1560 for (const chunk of chunksInRegion(regionX, regionY))
1561 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
1562 }
1563 const replicas = [];
1564 for (const key of replicaNeededForOwnedChunks(ownedKeys))
1565 {
1566 if (ownedKeys.has(key))
1567 { continue; }
1568 const { chunkX, chunkY } = parseChunkKey(key);
1569 replicas.push({
1570 chunkX,
1571 chunkY,
1572 data: this.#authoredChunk(chunkX, chunkY)
1573 });
1574 }
1575 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
1576 }
1577 }
1578
1579 #syncGhosts ()
1580 {
1581 const entities = [];
1582 for (const worker of this.workers)
1583 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
1584 for (const [workerId, worker] of this.workers.entries())
1585 {
1586 const ghosts = entities.filter((entity) =>
1587 {
1588 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
1589 { return false; }
1590 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
1591 });
1592 worker.call({ type: WorkerMessage.setGhosts, ghosts });
1593 }
1594 }
1595
1596 #nearWorker (workerId, tileX, tileY)
1597 {
1598 const chunkX = tileToChunk(tileX);
1599 const chunkY = tileToChunk(tileY);
1600 for (const [key, owner] of this.regionOwner)
1601 {
1602 if (owner !== workerId)
1603 { continue; }
1604 const { regionX, regionY } = parseRegionKey(key);
1605 for (const chunk of chunksInRegion(regionX, regionY))
1606 {
1607 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
1608 { return true; }
1609 }
1610 }
1611 return false;
1612 }
1613
1614 #allLoaders ()
1615 {
1616 const loaders = [];
1617 for (const worker of this.workers)
1618 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
1619 return loaders;
1620 }
1621
1622 #preferredWorkerForRegion (loaders, regionX, regionY)
1623 {
1624 const votes = new Map();
1625 for (const loader of loaders)
1626 {
1627 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
1628 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
1629 { continue; }
1630 const record = this.directory.get(loader.entityId);
1631 if (record?.workerId == null)
1632 { continue; }
1633 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
1634 }
1635 let best = null;
1636 let bestVotes = -1;
1637 for (const [workerId, count] of votes)
1638 {
1639 if (count > bestVotes)
1640 {
1641 best = workerId;
1642 bestVotes = count;
1643 }
1644 }
1645 return best;
1646 }
1647
1648 #pickWorker (regionX, regionY, preferredWorkerId)
1649 {
1650 const pinned = this.pinRegion?.(regionX, regionY);
1651 if (pinned != null)
1652 { return pinned; }
1653
1654 const neighborOwners = [];
1655 for (let dy = -1; dy <= 1; dy++)
1656 {
1657 for (let dx = -1; dx <= 1; dx++)
1658 {
1659 if (dx === 0 && dy === 0)
1660 { continue; }
1661 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
1662 if (owner != null)
1663 { neighborOwners.push(owner); }
1664 }
1665 }
1666
1667 const scores = this.workers.map((_, workerId) => ({
1668 workerId,
1669 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
1670 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
1671 }));
1672
1673 if (preferredWorkerId != null && scores[preferredWorkerId])
1674 {
1675 const preferred = scores[preferredWorkerId];
1676 if (preferred.neighbors > 0 || neighborOwners.length === 0)
1677 { return preferredWorkerId; }
1678 }
1679
1680 scores.sort((left, right) =>
1681 right.neighbors - left.neighbors
1682 || left.load - right.load
1683 || left.workerId - right.workerId
1684 );
1685 return scores[0].workerId;
1686 }
1687
1688 #ownerOfTile (tileX, tileY)
1689 {
1690 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
1691 }
1692
1693 #regionKeyForChunk (chunkX, chunkY)
1694 {
1695 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
1696 }
1697
1698 #regionChunkBlobs (regionX, regionY)
1699 {
1700 return chunksInRegion(regionX, regionY).map((coord) => ({
1701 chunkX: coord.chunkX,
1702 chunkY: coord.chunkY,
1703 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
1704 }));
1705 }
1706
1707 #authoredChunk (chunkX, chunkY)
1708 {
1709 const key = chunkKey(chunkX, chunkY);
1710 if (this.authoredCache.has(key))
1711 { return this.authoredCache.get(key); }
1712 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1713 const data = row
1714 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY)
1715 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1716 this.authoredCache.set(key, data);
1717 return data;
1718 }
1719
1720 #syntheticSnapshot (chunkX, chunkY)
1721 {
1722 const data = this.#authoredChunk(chunkX, chunkY);
1723 return {
1724 chunkX,
1725 chunkY,
1726 open: data.open,
1727 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
1728 grounds: data.grounds,
1729 blocks: data.blocks,
1730 light: data.light,
1731 entities: [],
1732 groundItems: []
1733 };
1734 }
1735
1736 #occupiedTile (tileX, tileY)
1737 {
1738 for (const record of this.directory.values())
1739 {
1740 if (record.tileX === tileX && record.tileY === tileY)
1741 { return record.entityId; }
1742 }
1743 return null;
1744 }
1745
1746 #queueReplication (event)
1747 {
1748 if (event)
1749 { this.replication.push(event); }
1750 }
1751
1752 #stepSpawners ()
1753 {
1754 const events = [];
1755 for (const worker of this.workers)
1756 {
1757 const result = worker.call({ type: WorkerMessage.stepSpawners });
1758 for (const request of result?.spawnRequests ?? [])
1759 {
1760 try
1761 {
1762 this.spawnEntity(mobComponents(request), { requireResident: true });
1763 }
1764 catch
1765 { continue; }
1766 }
1767 }
1768 return events;
1769 }
1770
1771 #restoreGroundItems (regionX, regionY, workerId)
1772 {
1773 const bounds = regionTileBounds(regionX, regionY);
1774 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
1775 .filter((item) => item.expiresAt > this.now);
1776 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
1777 this.workers[workerId].call({
1778 type: WorkerMessage.setGroundItems,
1779 regionX,
1780 regionY,
1781 items
1782 });
1783 }
1784
1785 #persistGroundEvent (event)
1786 {
1787 if (event.type === "ground-item-appear")
1788 {
1789 this.stateDb.upsertGroundItem({
1790 groundItemId: event.groundItemId,
1791 tileX: event.tileX,
1792 tileY: event.tileY,
1793 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
1794 droppedAt: event.droppedAt ?? this.now,
1795 expiresAt: event.expiresAt,
1796 source: event.source ?? "player-drop",
1797 droppedByCharacterId: event.droppedByCharacterId ?? null
1798 });
1799 }
1800 if (event.type === "ground-item-despawn")
1801 { this.stateDb.deleteGroundItem(event.groundItemId); }
1802 }
1803
1804 #saveBag (entityId, workerId)
1805 {
1806 const record = this.directory.get(entityId);
1807 const bag = this.workers[workerId].call({
1808 type: WorkerMessage.inspectBag,
1809 entityId
1810 });
1811 if (!bag || !record?.characterId)
1812 { return; }
1813 this.#saveBagFromView(record.characterId, bag);
1814 const skills = this.workers[workerId].call({
1815 type: WorkerMessage.inspectSkills,
1816 entityId
1817 });
1818 if (skills)
1819 { this.stateDb.saveSkills(record.characterId, skills); }
1820 }
1821
1822 #applySkillsUpdated (event)
1823 {
1824 if (!event?.characterId || !event.stored)
1825 { return; }
1826 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1827 this.pushSkills(event.characterId, event.skills ?? []);
1828 }
1829
1830 #skillLevelUpEvents (event)
1831 {
1832 const levelUps = event?.levelUps ?? [];
1833 if (!levelUps.length)
1834 { return []; }
1835 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
1836 if (entityId == null)
1837 { return []; }
1838 const record = this.directory.get(entityId);
1839 const tileX = record?.tileX ?? 0;
1840 const tileY = record?.tileY ?? 0;
1841 return levelUps.map((levelUp) => ({
1842 type: "skill-level-up",
1843 entityId,
1844 characterId: event.characterId,
1845 tileX,
1846 tileY,
1847 skillId: levelUp.skillId,
1848 level: levelUp.level,
1849 displayName: levelUp.displayName,
1850 icon: levelUp.icon
1851 }));
1852 }
1853
1854 #saveBagFromView (characterId, bag)
1855 {
1856 this.stateDb.saveBag(characterId, {
1857 inventory: bag.inventory,
1858 equipment: bag.equipment,
1859 vault: bag.vault,
1860 vaultReserved: bag.vaultReserved
1861 });
1862 }
1863
1864 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
1865 {
1866 const onlineId = this.characterEntities.get(issuerCharacterId);
1867 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1868 if (!bag)
1869 { return { ok: false, error: "Issuer vault not found." }; }
1870 const reserved = [...(bag.vaultReserved ?? [])];
1871 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
1872 if (index < 0)
1873 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1874 const [stack] = reserved.splice(index, 1);
1875 bag.vaultReserved = reserved;
1876 this.stateDb.saveBag(issuerCharacterId, bag);
1877 if (onlineId)
1878 {
1879 this.applyBag(onlineId, bag);
1880 this.pushInventory(issuerCharacterId, bag);
1881 }
1882 return { ok: true, stack };
1883 }
1884
1885 restoreChequeReservation (issuerCharacterId, stack)
1886 {
1887 const onlineId = this.characterEntities.get(issuerCharacterId);
1888 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1889 if (!bag)
1890 { return; }
1891 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1892 this.stateDb.saveBag(issuerCharacterId, bag);
1893 if (onlineId)
1894 {
1895 this.applyBag(onlineId, bag);
1896 this.pushInventory(issuerCharacterId, bag);
1897 }
1898 }
1899
1900 #remember (view, workerId)
1901 {
1902 if (!view)
1903 { return; }
1904 this.directory.set(view.entityId, { ...view, workerId });
1905 if (view.characterId)
1906 { this.characterEntities.set(view.characterId, view.entityId); }
1907 }
1908
1909 #applyMoveToDirectory (event)
1910 {
1911 const record = this.directory.get(event.entityId);
1912 if (!record)
1913 { return; }
1914 record.tileX = event.tileX;
1915 record.tileY = event.tileY;
1916 record.gait = event.gait;
1917 if (event.worldX != null)
1918 { record.worldX = event.worldX; }
1919 if (event.worldY != null)
1920 { record.worldY = event.worldY; }
1921 if (event.freeFlight != null)
1922 { record.freeFlight = !!event.freeFlight; }
1923 }
1924
1925 #forget (entityId)
1926 {
1927 const record = this.directory.get(entityId);
1928 if (record?.characterId)
1929 { this.characterEntities.delete(record.characterId); }
1930 this.directory.delete(entityId);
1931 }
1932}