BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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