BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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