BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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