BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 33.7 KiB Download Raw
1import {
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 WORLD_YEAR_OFFSET
8} from "../../../shared/protocol/constants.js";
9import {
10 chunkKey,
11 chunkToRegion,
12 chunksInRegion,
13 parseChunkKey,
14 parseRegionKey,
15 regionKey,
16 regionTileBounds,
17 tileToChunk,
18 tileToLocal,
19 tileToRegion,
20 visibleChunkCoords
21} from "../world/coordinates.js";
22import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
23import { closedNeighborEdges } from "../world/chunkFlags.js";
24import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
25import { InProcessWorker } from "./inProcessWorker.js";
26import { ThreadWorker } from "./threadWorker.js";
27import { WorkerMessage } from "./protocol.js";
28import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
32import { defaultPlayerSkills } from "../../../shared/skills/state.js";
33import { playerMaxHealth } from "../../../shared/definitions/skills.js";
34import { CourierService } from "../courier/service.js";
35
36export class Simulation
37{
38 constructor (worldDb, stateDb, options = {})
39 {
40 this.worldDb = worldDb;
41 this.stateDb = stateDb;
42 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
43 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
44 this.pinRegion = options.pinRegion ?? null;
45 this.nowFn = options.now ?? (() => Date.now());
46 this.workers = [];
47 this.regionOwner = new Map();
48 this.regionGraceUntil = new Map();
49 this.directory = new Map();
50 this.characterEntities = new Map();
51 this.commandQueue = [];
52 this.replication = [];
53 this.pendingPrivate = [];
54 this.courier = null;
55 this.authoredCache = new Map();
56 this.nextEntityId = 1;
57 this.nextGroundItemId = stateDb.nextGroundItemId();
58 this.tickIndex = 0;
59 this.movementTickCounter = 0;
60 this.lastTickAt = null;
61 this.movementAccumulator = 0;
62 this.activeRevisionId = worldDb.getActiveRevisionId();
63 this.settings = worldDb.getLiveSettings();
64
65 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
66 for (let workerId = 0; workerId < this.workerCount; workerId++)
67 {
68 const worker = new WorkerImpl(workerId);
69 worker.call({
70 type: WorkerMessage.configure,
71 settings: this.settings,
72 activeRevisionId: this.activeRevisionId
73 });
74 this.workers.push(worker);
75 }
76 for (const worker of this.workers)
77 {
78 if (!worker.world)
79 { continue; }
80 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
81 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
82 }
83 this.courier = new CourierService({
84 stateDb: this.stateDb,
85 worldDb: this.worldDb,
86 simulation: this
87 });
88 }
89
90 get now ()
91 {
92 return this.nowFn();
93 }
94
95 applySettings (settings)
96 {
97 this.settings = { ...this.settings, ...settings };
98 this.#configureWorkers();
99 }
100
101 reloadWorld ()
102 {
103 this.activeRevisionId = this.worldDb.getActiveRevisionId();
104 this.settings = this.worldDb.getLiveSettings();
105 this.authoredCache.clear();
106 this.#configureWorkers();
107 for (const [key, workerId] of this.regionOwner)
108 {
109 const { regionX, regionY } = parseRegionKey(key);
110 this.workers[workerId].call({
111 type: WorkerMessage.replaceRegionChunks,
112 chunks: this.#regionChunkBlobs(regionX, regionY)
113 });
114 }
115 this.#syncAllReplicas();
116 this.courier?.refreshBankIndex();
117 }
118
119 enqueue (sessionId, command)
120 {
121 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
122 }
123
124 step (now = this.now)
125 {
126 this.tickIndex += 1;
127 const events = [];
128 const commands = this.commandQueue.splice(0);
129 for (const item of commands)
130 {
131 try
132 {
133 events.push(...this.#routeCommand(item));
134 }
135 catch (error)
136 {
137 events.push({
138 sessionId: item.sessionId,
139 type: "command-error",
140 message: error.userFacing ? error.message : "Command failed."
141 });
142 }
143 }
144
145 this.#recalculateActivation(now);
146
147 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
148 const expectedDt = 1 / simHz;
149 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
150 ? expectedDt
151 : Math.min(0.25, (now - this.lastTickAt) / 1000);
152 this.lastTickAt = now;
153
154 {
155 const transfers = [];
156 for (const worker of this.workers)
157 {
158 const result = worker.call({ type: WorkerMessage.stepSystems, now });
159 for (const event of result?.events ?? [])
160 {
161 if (event.type === "entity-move")
162 { this.#applyMoveToDirectory(event); }
163 if (event.type === "entity-despawn")
164 { this.#forget(event.entityId); }
165 if (event.type === "skills-updated")
166 { this.#applySkillsUpdated(event); }
167 this.#persistGroundEvent(event);
168 if (event.type !== "skills-updated")
169 { events.push(event); }
170 }
171 for (const request of result?.transferRequests ?? [])
172 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
173 }
174 if (transfers.length)
175 {
176 events.push(...this.#applyTransfers(transfers));
177 this.#recalculateActivation(now);
178 }
179 }
180
181 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
182 this.movementAccumulator += dt * movementHz;
183 while (this.movementAccumulator >= 1)
184 {
185 this.movementAccumulator -= 1;
186 this.movementTickCounter += 1;
187 const transfers = [];
188 for (const worker of this.workers)
189 {
190 const result = worker.call({ type: WorkerMessage.stepMovement, now });
191 for (const event of result?.events ?? [])
192 {
193 if (event.type === "entity-move")
194 { this.#applyMoveToDirectory(event); }
195 this.#persistGroundEvent(event);
196 events.push(event);
197 }
198 for (const request of result?.transferRequests ?? [])
199 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
200 }
201 events.push(...this.#applyTransfers(transfers));
202 this.#recalculateActivation(now);
203 }
204
205 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
206 { events.push(...this.#stepSpawners()); }
207
208 if (this.courier)
209 { events.push(...this.courier.step(now, dt)); }
210
211 this.#syncGhosts();
212 events.push(...this.pendingPrivate.splice(0));
213 return { now, events, replication: this.drainReplication() };
214 }
215
216 drainReplication ()
217 {
218 return this.replication.splice(0);
219 }
220
221 worldTime (now = this.now)
222 {
223 const date = new Date(now);
224 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
225 return {
226 unixMs: now,
227 worldUnixMs: date.getTime(),
228 iso: date.toISOString(),
229 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600
230 };
231 }
232
233 spawnCharacter (sessionId, character)
234 {
235 this.despawnCharacter(character.character_id);
236 // Despawn may have just written the live tile; never trust a stale row snapshot.
237 const row = this.stateDb.getCharacter(character.character_id) ?? character;
238 let tileX = row.tile_x;
239 let tileY = row.tile_y;
240 const gait = row.gait || character.gait || GAIT.walk;
241 const preferred = this.#findResumeTile(tileX, tileY);
242 if (!preferred)
243 {
244 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
245 error.userFacing = true;
246 throw error;
247 }
248 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
249 {
250 tileX = preferred.tileX;
251 tileY = preferred.tileY;
252 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
253 }
254
255 const bag = this.stateDb.getBag(character.character_id) ?? {
256 inventory: emptySlots(),
257 equipment: emptyEquipment(),
258 vault: [],
259 vaultReserved: []
260 };
261 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
262 const maxHealth = playerMaxHealth(skills);
263 const entityId = this.nextEntityId++;
264 const components = {
265 position: { tileX, tileY },
266 movement: { gait, walkCarry: 0 },
267 path: { tiles: [] },
268 appearance: {
269 sex: character.sex ?? row.sex,
270 firstName: character.first_name ?? row.first_name,
271 lastName: character.last_name ?? row.last_name
272 },
273 character: {
274 characterId: character.character_id ?? row.character_id,
275 accountId: character.account_id ?? row.account_id
276 },
277 networkIdentity: { sessionId },
278 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
279 inventory: { slots: bag.inventory ?? emptySlots() },
280 equipment: bag.equipment ?? emptyEquipment(),
281 vault: {
282 slots: bag.vault ?? [],
283 reserved: bag.vaultReserved ?? []
284 },
285 health: { current: maxHealth, max: maxHealth },
286 combat: { targetEntityId: null, nextSwingAt: 0 },
287 skills,
288 };
289 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
290 const workerId = this.#ownerOfTile(tileX, tileY);
291 const view = this.workers[workerId].call({
292 type: WorkerMessage.spawn,
293 entityId,
294 components
295 });
296 this.#remember(view, workerId);
297 this.#queueReplication(replicationSpawn(view));
298 this.#recalculateActivation(this.now);
299 this.#syncGhosts();
300 return entityId;
301 }
302
303 spawnEntity (components, options = {})
304 {
305 const entityId = options.entityId ?? this.nextEntityId++;
306 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
307 const position = components.position;
308 if (!position)
309 { throw new Error("spawnEntity requires position."); }
310 if (options.requireResident)
311 {
312 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
313 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))
314 { return null; }
315 const view = this.workers[workerId].call({
316 type: WorkerMessage.spawn,
317 entityId,
318 components
319 });
320 this.#remember(view, workerId);
321 if (components.appearance)
322 { this.#queueReplication(replicationSpawn(view)); }
323 this.#syncGhosts();
324 return entityId;
325 }
326 if (components.chunkLoader)
327 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
328 else
329 {
330 this.#ensureRegion(
331 tileToRegion(position.tileX),
332 tileToRegion(position.tileY),
333 null
334 );
335 }
336 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
337 const view = this.workers[workerId].call({
338 type: WorkerMessage.spawn,
339 entityId,
340 components
341 });
342 this.#remember(view, workerId);
343 if (components.appearance)
344 { this.#queueReplication(replicationSpawn(view)); }
345 this.#recalculateActivation(this.now);
346 this.#syncGhosts();
347 return entityId;
348 }
349
350 despawnEntity (entityId)
351 {
352 const record = this.directory.get(entityId);
353 if (!record)
354 { return; }
355 const dropped = this.workers[record.workerId].call({
356 type: WorkerMessage.despawn,
357 entityId
358 });
359 if (dropped)
360 { this.#queueReplication(replicationDespawn(dropped)); }
361 this.#forget(entityId);
362 }
363
364 chunkIsSimulating (tileX, tileY)
365 {
366 const loaders = this.#allLoaders();
367 const { chunkSim } = accumulateLoaderRefs(loaders);
368 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;
369 }
370
371 updateCourierFlight (entityId, flightPatch, now = this.now)
372 {
373 const record = this.directory.get(entityId);
374 if (!record)
375 { return { despawned: true, entityId }; }
376 const tileX = Math.floor(flightPatch.x);
377 const tileY = Math.floor(flightPatch.y);
378 const owner = this.#ownerOfTile(tileX, tileY);
379 if (owner == null || owner !== record.workerId)
380 {
381 this.despawnEntity(entityId);
382 return { despawned: true, entityId };
383 }
384 const result = this.workers[owner].call({
385 type: WorkerMessage.updateFlight,
386 entityId,
387 flight: flightPatch,
388 now
389 });
390 if (result?.transferRequest)
391 {
392 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
393 this.#recalculateActivation(now);
394 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
395 if (move)
396 {
397 this.#applyMoveToDirectory(move);
398 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
399 }
400 this.despawnEntity(entityId);
401 return { despawned: true, entityId };
402 }
403 if (result?.event)
404 {
405 this.#applyMoveToDirectory(result.event);
406 return { event: result.event };
407 }
408 return null;
409 }
410
411 applyBag (entityId, bag)
412 {
413 const record = this.directory.get(entityId);
414 if (!record)
415 { return null; }
416 return this.workers[record.workerId].call({
417 type: WorkerMessage.applyBag,
418 entityId,
419 bag
420 });
421 }
422
423 pushSkills (characterId, skills)
424 {
425 this.pendingPrivate.push({
426 type: "skills",
427 characterId,
428 skills
429 });
430 }
431
432 skillsOf (entityId)
433 {
434 const record = this.directory.get(entityId);
435 if (!record)
436 { return null; }
437 return this.workers[record.workerId].call({
438 type: WorkerMessage.inspectSkills,
439 entityId
440 });
441 }
442
443 pushInventory (characterId, bag)
444 {
445 this.pendingPrivate.push({
446 type: "inventory",
447 characterId,
448 inventory: bag.inventory,
449 equipment: bag.equipment,
450 vault: bag.vault,
451 vaultReserved: bag.vaultReserved
452 });
453 }
454
455 dispatchPigeon ({ characterId, destination, cargo })
456 {
457 const entityId = this.characterEntities.get(characterId);
458 const position = entityId ? this.positionOf(entityId) : null;
459 if (!position)
460 {
461 const error = new Error("Enter the world before sending a pigeon.");
462 error.userFacing = true;
463 throw error;
464 }
465 return this.courier.dispatchFromPlayer({
466 characterId,
467 originTileX: position.tileX,
468 originTileY: position.tileY,
469 destination,
470 cargo
471 });
472 }
473
474 despawnCharacter (characterId)
475 {
476 const entityId = this.characterEntities.get(characterId);
477 if (!entityId)
478 { return; }
479 const record = this.directory.get(entityId);
480 if (!record)
481 {
482 this.characterEntities.delete(characterId);
483 return;
484 }
485 this.#saveBag(entityId, record.workerId);
486 const dropped = this.workers[record.workerId].call({
487 type: WorkerMessage.despawnCharacter,
488 characterId
489 });
490 if (dropped)
491 {
492 this.stateDb.saveCharacterPosition(
493 characterId,
494 dropped.tileX,
495 dropped.tileY,
496 dropped.gait ?? GAIT.walk
497 );
498 this.#queueReplication(replicationDespawn(dropped));
499 }
500 this.#forget(entityId);
501 this.#recalculateActivation(this.now);
502 this.#syncGhosts();
503 }
504
505 entityForCharacter (characterId)
506 {
507 return this.characterEntities.get(characterId) ?? null;
508 }
509
510 entityRecord (entityId)
511 {
512 const record = this.directory.get(entityId);
513 return record ? { ...record } : null;
514 }
515
516 positionOf (entityId)
517 {
518 const record = this.directory.get(entityId);
519 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
520 }
521
522 bagOf (entityId)
523 {
524 const record = this.directory.get(entityId);
525 if (!record)
526 { return null; }
527 return this.workers[record.workerId].call({
528 type: WorkerMessage.inspectBag,
529 entityId
530 });
531 }
532
533 snapshotFor (entityId)
534 {
535 const record = this.directory.get(entityId);
536 if (!record)
537 { return []; }
538 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
539 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
540 }
541
542 snapshotChunk (chunkX, chunkY)
543 {
544 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
545 if (owner == null)
546 { return this.#syntheticSnapshot(chunkX, chunkY); }
547 return this.workers[owner].call({
548 type: WorkerMessage.snapshotChunk,
549 chunkX,
550 chunkY
551 });
552 }
553
554 findOpenSpawn ()
555 {
556 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
557 for (const coord of coords)
558 {
559 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
560 if (!data.open)
561 { continue; }
562 for (let localY = 0; localY < CHUNK_SIZE; localY++)
563 {
564 for (let localX = 0; localX < CHUNK_SIZE; localX++)
565 {
566 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
567 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
568 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
569 { return { tileX, tileY }; }
570 }
571 }
572 }
573 return null;
574 }
575
576 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
577 #findResumeTile (tileX, tileY, radius = 24)
578 {
579 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
580 }
581
582 #findNearbyEnterable (originX, originY, maxRadius)
583 {
584 for (let radius = 0; radius <= maxRadius; radius++)
585 {
586 for (let dy = -radius; dy <= radius; dy++)
587 {
588 for (let dx = -radius; dx <= radius; dx++)
589 {
590 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
591 { continue; }
592 const tileX = originX + dx;
593 const tileY = originY + dy;
594 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
595 { return { tileX, tileY }; }
596 }
597 }
598 }
599 return null;
600 }
601
602 isEnterable (tileX, tileY)
603 {
604 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
605 if (!data.open)
606 { return false; }
607 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
608 }
609
610 debugWorld ()
611 {
612 const loaders = this.#allLoaders();
613 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
614 const simulatingChunks = [...chunkSim.entries()]
615 .filter(([, count]) => count > 0)
616 .map(([key]) => key)
617 .sort();
618 return {
619 tickIndex: this.tickIndex,
620 workerCount: this.workers.length,
621 workerMode: this.workerMode,
622 simulatingChunks,
623 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
624 ...parseRegionKey(key),
625 workerId,
626 state: REGION_RUNTIME_STATE.resident,
627 refs: regionRes.get(key) ?? 0,
628 graceUntil: this.regionGraceUntil.get(key) ?? null
629 })),
630 entities: [...this.directory.values()].map((entity) => ({
631 entityId: entity.entityId,
632 workerId: entity.workerId,
633 tileX: entity.tileX,
634 tileY: entity.tileY,
635 characterId: entity.characterId
636 }))
637 };
638 }
639
640 async shutdown ()
641 {
642 for (const characterId of [...this.characterEntities.keys()])
643 { this.despawnCharacter(characterId); }
644 this.forceUnloadAll();
645 await Promise.all(this.workers.map((worker) => worker.terminate()));
646 }
647
648 forceUnloadAll ()
649 {
650 for (const key of [...this.regionOwner.keys()])
651 {
652 const { regionX, regionY } = parseRegionKey(key);
653 this.#unloadRegion(regionX, regionY);
654 }
655 }
656
657 #configureWorkers ()
658 {
659 for (const worker of this.workers)
660 {
661 worker.call({
662 type: WorkerMessage.configure,
663 settings: this.settings,
664 activeRevisionId: this.activeRevisionId
665 });
666 }
667 }
668
669 #routeCommand (item)
670 {
671 const entityId = this.characterEntities.get(item.command.characterId);
672 const record = entityId ? this.directory.get(entityId) : null;
673 if (!record)
674 {
675 const error = new Error("Character is not in the world.");
676 error.userFacing = true;
677 throw error;
678 }
679 if (item.command.type === "drop-item" && item.command.groundItemId == null)
680 { item.command.groundItemId = this.nextGroundItemId++; }
681 const result = this.workers[record.workerId].call({
682 type: WorkerMessage.command,
683 sessionId: item.sessionId,
684 command: item.command,
685 now: item.receivedAt ?? this.now
686 });
687 const view = this.workers[record.workerId].call({
688 type: WorkerMessage.inspect,
689 entityId: record.entityId
690 });
691 if (view)
692 { this.#remember(view, record.workerId); }
693 if (result?.private)
694 { this.#saveBagFromView(item.command.characterId, result.private); }
695 if (result?.appearanceChanged && view)
696 { this.#queueReplication(replicationAppearance(view)); }
697 if (result?.remainder)
698 {
699 this.stateDb.saveInheritance(
700 this.stateDb.getCharacter(item.command.characterId).account_id,
701 { slots: result.remainder }
702 );
703 }
704 for (const event of result?.events ?? [])
705 { this.#persistGroundEvent(event); }
706 const events = [...(result?.events ?? [])];
707 if (result?.private)
708 {
709 events.push({
710 type: "inventory",
711 sessionId: item.sessionId,
712 bank: !!result.bank,
713 ...result.private
714 });
715 }
716 return events;
717 }
718
719 #recalculateActivation (now)
720 {
721 const loaders = this.#allLoaders();
722 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
723
724 for (const [key, count] of regionRes)
725 {
726 if (count <= 0)
727 { continue; }
728 const { regionX, regionY } = parseRegionKey(key);
729 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
730 this.regionGraceUntil.delete(key);
731 }
732
733 for (const [key] of [...this.regionOwner.entries()])
734 {
735 if ((regionRes.get(key) ?? 0) > 0)
736 { continue; }
737 if (!this.regionGraceUntil.has(key))
738 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
739 if (now >= this.regionGraceUntil.get(key))
740 {
741 const { regionX, regionY } = parseRegionKey(key);
742 this.#unloadRegion(regionX, regionY);
743 }
744 }
745
746 for (const [workerId, worker] of this.workers.entries())
747 {
748 const chunkKeys = [];
749 for (const [key, count] of chunkSim)
750 {
751 if (count <= 0)
752 { continue; }
753 const { chunkX, chunkY } = parseChunkKey(key);
754 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
755 { chunkKeys.push(key); }
756 }
757 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
758 }
759 this.#syncAllReplicas();
760 }
761
762 #ensureCoverage (tileX, tileY, loader)
763 {
764 const coverage = loaderCoverage(tileX, tileY, loader);
765 let preferred = this.#ownerOfTile(tileX, tileY);
766 for (const region of coverage.residentRegions)
767 {
768 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
769 if (preferred == null)
770 { preferred = owner; }
771 }
772 }
773
774 #ensureRegion (regionX, regionY, preferredWorkerId)
775 {
776 const key = regionKey(regionX, regionY);
777 if (this.regionOwner.has(key))
778 { return this.regionOwner.get(key); }
779 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
780 this.workers[workerId].call({
781 type: WorkerMessage.assignRegion,
782 regionX,
783 regionY,
784 chunks: this.#regionChunkBlobs(regionX, regionY)
785 });
786 this.regionOwner.set(key, workerId);
787 this.#restorePersistent(regionX, regionY, workerId);
788 this.#restoreGroundItems(regionX, regionY, workerId);
789 return workerId;
790 }
791
792 #unloadRegion (regionX, regionY)
793 {
794 const key = regionKey(regionX, regionY);
795 const workerId = this.regionOwner.get(key);
796 if (workerId == null)
797 { return; }
798 const bounds = regionTileBounds(regionX, regionY);
799 const { dropped, groundItems } = this.workers[workerId].call({
800 type: WorkerMessage.dropRegion,
801 regionX,
802 regionY
803 });
804 const persistent = [];
805 for (const record of dropped ?? [])
806 {
807 if (record.characterId)
808 {
809 this.stateDb.saveCharacterPosition(
810 record.characterId,
811 record.tileX,
812 record.tileY,
813 record.gait ?? GAIT.walk
814 );
815 }
816 if (record.persistent)
817 { persistent.push(record); }
818 this.#forget(record.entityId);
819 }
820 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
821 for (const item of groundItems ?? [])
822 { this.stateDb.upsertGroundItem(item); }
823 this.regionOwner.delete(key);
824 this.regionGraceUntil.delete(key);
825 }
826
827 #restorePersistent (regionX, regionY, workerId)
828 {
829 const bounds = regionTileBounds(regionX, regionY);
830 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
831 for (const row of rows)
832 {
833 if (this.directory.has(row.entity_id))
834 { continue; }
835 const components = JSON.parse(row.components_blob);
836 const view = this.workers[workerId].call({
837 type: WorkerMessage.spawn,
838 entityId: row.entity_id,
839 components
840 });
841 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
842 this.#remember(view, workerId);
843 }
844 }
845
846 #applyTransfers (requests)
847 {
848 const events = [];
849 for (const request of requests)
850 {
851 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
852 if (destWorkerId === request.fromWorkerId)
853 {
854 this.workers[request.fromWorkerId].call({
855 type: WorkerMessage.abortTransfer,
856 entityId: request.entityId
857 });
858 continue;
859 }
860 let result;
861 try
862 {
863 result = this.workers[destWorkerId].call({
864 type: WorkerMessage.applyTransfer,
865 payload: request.payload,
866 destTileX: request.destTileX,
867 destTileY: request.destTileY
868 });
869 }
870 catch
871 {
872 result = { accepted: false };
873 }
874 if (!result?.accepted)
875 {
876 this.workers[request.fromWorkerId].call({
877 type: WorkerMessage.abortTransfer,
878 entityId: request.entityId
879 });
880 continue;
881 }
882 this.workers[request.fromWorkerId].call({
883 type: WorkerMessage.commitTransfer,
884 entityId: request.entityId
885 });
886 this.#remember(result.entity, destWorkerId);
887 events.push({
888 type: "entity-move",
889 entityId: request.entityId,
890 fromTileX: request.fromTileX,
891 fromTileY: request.fromTileY,
892 tileX: result.entity.tileX,
893 tileY: result.entity.tileY,
894 gait: result.entity.gait
895 });
896 }
897 return events;
898 }
899
900 #syncAllReplicas ()
901 {
902 for (const [workerId, worker] of this.workers.entries())
903 {
904 const ownedKeys = new Set();
905 for (const [key, owner] of this.regionOwner)
906 {
907 if (owner !== workerId)
908 { continue; }
909 const { regionX, regionY } = parseRegionKey(key);
910 for (const chunk of chunksInRegion(regionX, regionY))
911 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
912 }
913 const replicas = [];
914 for (const key of replicaNeededForOwnedChunks(ownedKeys))
915 {
916 if (ownedKeys.has(key))
917 { continue; }
918 const { chunkX, chunkY } = parseChunkKey(key);
919 replicas.push({
920 chunkX,
921 chunkY,
922 data: this.#authoredChunk(chunkX, chunkY)
923 });
924 }
925 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
926 }
927 }
928
929 #syncGhosts ()
930 {
931 const entities = [];
932 for (const worker of this.workers)
933 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
934 for (const [workerId, worker] of this.workers.entries())
935 {
936 const ghosts = entities.filter((entity) =>
937 {
938 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
939 { return false; }
940 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
941 });
942 worker.call({ type: WorkerMessage.setGhosts, ghosts });
943 }
944 }
945
946 #nearWorker (workerId, tileX, tileY)
947 {
948 const chunkX = tileToChunk(tileX);
949 const chunkY = tileToChunk(tileY);
950 for (const [key, owner] of this.regionOwner)
951 {
952 if (owner !== workerId)
953 { continue; }
954 const { regionX, regionY } = parseRegionKey(key);
955 for (const chunk of chunksInRegion(regionX, regionY))
956 {
957 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
958 { return true; }
959 }
960 }
961 return false;
962 }
963
964 #allLoaders ()
965 {
966 const loaders = [];
967 for (const worker of this.workers)
968 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
969 return loaders;
970 }
971
972 #preferredWorkerForRegion (loaders, regionX, regionY)
973 {
974 const votes = new Map();
975 for (const loader of loaders)
976 {
977 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
978 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
979 { continue; }
980 const record = this.directory.get(loader.entityId);
981 if (record?.workerId == null)
982 { continue; }
983 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
984 }
985 let best = null;
986 let bestVotes = -1;
987 for (const [workerId, count] of votes)
988 {
989 if (count > bestVotes)
990 {
991 best = workerId;
992 bestVotes = count;
993 }
994 }
995 return best;
996 }
997
998 #pickWorker (regionX, regionY, preferredWorkerId)
999 {
1000 const pinned = this.pinRegion?.(regionX, regionY);
1001 if (pinned != null)
1002 { return pinned; }
1003
1004 const neighborOwners = [];
1005 for (let dy = -1; dy <= 1; dy++)
1006 {
1007 for (let dx = -1; dx <= 1; dx++)
1008 {
1009 if (dx === 0 && dy === 0)
1010 { continue; }
1011 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
1012 if (owner != null)
1013 { neighborOwners.push(owner); }
1014 }
1015 }
1016
1017 const scores = this.workers.map((_, workerId) => ({
1018 workerId,
1019 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
1020 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
1021 }));
1022
1023 if (preferredWorkerId != null && scores[preferredWorkerId])
1024 {
1025 const preferred = scores[preferredWorkerId];
1026 if (preferred.neighbors > 0 || neighborOwners.length === 0)
1027 { return preferredWorkerId; }
1028 }
1029
1030 scores.sort((left, right) =>
1031 right.neighbors - left.neighbors
1032 || left.load - right.load
1033 || left.workerId - right.workerId
1034 );
1035 return scores[0].workerId;
1036 }
1037
1038 #ownerOfTile (tileX, tileY)
1039 {
1040 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
1041 }
1042
1043 #regionKeyForChunk (chunkX, chunkY)
1044 {
1045 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
1046 }
1047
1048 #regionChunkBlobs (regionX, regionY)
1049 {
1050 return chunksInRegion(regionX, regionY).map((coord) => ({
1051 chunkX: coord.chunkX,
1052 chunkY: coord.chunkY,
1053 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
1054 }));
1055 }
1056
1057 #authoredChunk (chunkX, chunkY)
1058 {
1059 const key = chunkKey(chunkX, chunkY);
1060 if (this.authoredCache.has(key))
1061 { return this.authoredCache.get(key); }
1062 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1063 const data = row
1064 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
1065 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1066 this.authoredCache.set(key, data);
1067 return data;
1068 }
1069
1070 #syntheticSnapshot (chunkX, chunkY)
1071 {
1072 const data = this.#authoredChunk(chunkX, chunkY);
1073 return {
1074 chunkX,
1075 chunkY,
1076 open: data.open,
1077 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
1078 grounds: data.grounds,
1079 blocks: data.blocks,
1080 light: data.light,
1081 entities: [],
1082 groundItems: []
1083 };
1084 }
1085
1086 #occupiedTile (tileX, tileY)
1087 {
1088 for (const record of this.directory.values())
1089 {
1090 if (record.tileX === tileX && record.tileY === tileY)
1091 { return record.entityId; }
1092 }
1093 return null;
1094 }
1095
1096 #queueReplication (event)
1097 {
1098 if (event)
1099 { this.replication.push(event); }
1100 }
1101
1102 #stepSpawners ()
1103 {
1104 const events = [];
1105 for (const worker of this.workers)
1106 {
1107 const result = worker.call({ type: WorkerMessage.stepSpawners });
1108 for (const request of result?.spawnRequests ?? [])
1109 {
1110 try
1111 {
1112 this.spawnEntity(mobComponents(request));
1113 }
1114 catch
1115 { continue; }
1116 }
1117 }
1118 return events;
1119 }
1120
1121 #restoreGroundItems (regionX, regionY, workerId)
1122 {
1123 const bounds = regionTileBounds(regionX, regionY);
1124 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
1125 .filter((item) => item.expiresAt > this.now);
1126 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
1127 this.workers[workerId].call({
1128 type: WorkerMessage.setGroundItems,
1129 regionX,
1130 regionY,
1131 items
1132 });
1133 }
1134
1135 #persistGroundEvent (event)
1136 {
1137 if (event.type === "ground-item-appear")
1138 {
1139 this.stateDb.upsertGroundItem({
1140 groundItemId: event.groundItemId,
1141 tileX: event.tileX,
1142 tileY: event.tileY,
1143 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
1144 droppedAt: event.droppedAt ?? this.now,
1145 expiresAt: event.expiresAt,
1146 source: event.source ?? "player-drop",
1147 droppedByCharacterId: event.droppedByCharacterId ?? null
1148 });
1149 }
1150 if (event.type === "ground-item-despawn")
1151 { this.stateDb.deleteGroundItem(event.groundItemId); }
1152 }
1153
1154 #saveBag (entityId, workerId)
1155 {
1156 const record = this.directory.get(entityId);
1157 const bag = this.workers[workerId].call({
1158 type: WorkerMessage.inspectBag,
1159 entityId
1160 });
1161 if (!bag || !record?.characterId)
1162 { return; }
1163 this.#saveBagFromView(record.characterId, bag);
1164 const skills = this.workers[workerId].call({
1165 type: WorkerMessage.inspectSkills,
1166 entityId
1167 });
1168 if (skills)
1169 { this.stateDb.saveSkills(record.characterId, skills); }
1170 }
1171
1172 #applySkillsUpdated (event)
1173 {
1174 if (!event?.characterId || !event.stored)
1175 { return; }
1176 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1177 this.pushSkills(event.characterId, event.skills ?? []);
1178 }
1179
1180 #saveBagFromView (characterId, bag)
1181 {
1182 this.stateDb.saveBag(characterId, {
1183 inventory: bag.inventory,
1184 equipment: bag.equipment,
1185 vault: bag.vault,
1186 vaultReserved: bag.vaultReserved
1187 });
1188 }
1189
1190 releaseChequeReservation (issuerCharacterId, chequeId)
1191 {
1192 const onlineId = this.characterEntities.get(issuerCharacterId);
1193 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1194 if (!bag)
1195 { return { ok: false, error: "Issuer vault not found." }; }
1196 const reserved = [...(bag.vaultReserved ?? [])];
1197 const index = reserved.findIndex((entry) => entry?.chequeId === chequeId);
1198 if (index < 0)
1199 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1200 const [stack] = reserved.splice(index, 1);
1201 bag.vaultReserved = reserved;
1202 this.stateDb.saveBag(issuerCharacterId, bag);
1203 if (onlineId)
1204 {
1205 this.applyBag(onlineId, bag);
1206 this.pushInventory(issuerCharacterId, bag);
1207 }
1208 return { ok: true, stack };
1209 }
1210
1211 restoreChequeReservation (issuerCharacterId, stack)
1212 {
1213 const onlineId = this.characterEntities.get(issuerCharacterId);
1214 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1215 if (!bag)
1216 { return; }
1217 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1218 this.stateDb.saveBag(issuerCharacterId, bag);
1219 if (onlineId)
1220 {
1221 this.applyBag(onlineId, bag);
1222 this.pushInventory(issuerCharacterId, bag);
1223 }
1224 }
1225
1226 #remember (view, workerId)
1227 {
1228 if (!view)
1229 { return; }
1230 this.directory.set(view.entityId, { ...view, workerId });
1231 if (view.characterId)
1232 { this.characterEntities.set(view.characterId, view.entityId); }
1233 }
1234
1235 #applyMoveToDirectory (event)
1236 {
1237 const record = this.directory.get(event.entityId);
1238 if (!record)
1239 { return; }
1240 record.tileX = event.tileX;
1241 record.tileY = event.tileY;
1242 record.gait = event.gait;
1243 if (event.worldX != null)
1244 { record.worldX = event.worldX; }
1245 if (event.worldY != null)
1246 { record.worldY = event.worldY; }
1247 if (event.freeFlight != null)
1248 { record.freeFlight = !!event.freeFlight; }
1249 }
1250
1251 #forget (entityId)
1252 {
1253 const record = this.directory.get(entityId);
1254 if (record?.characterId)
1255 { this.characterEntities.delete(record.characterId); }
1256 this.directory.delete(entityId);
1257 }
1258}