BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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