BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 25.8 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";
32
33export class Simulation
34{
35 constructor (worldDb, stateDb, options = {})
36 {
37 this.worldDb = worldDb;
38 this.stateDb = stateDb;
39 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
40 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
41 this.pinRegion = options.pinRegion ?? null;
42 this.nowFn = options.now ?? (() => Date.now());
43 this.workers = [];
44 this.regionOwner = new Map();
45 this.regionGraceUntil = new Map();
46 this.directory = new Map();
47 this.characterEntities = new Map();
48 this.commandQueue = [];
49 this.replication = [];
50 this.authoredCache = new Map();
51 this.nextEntityId = 1;
52 this.nextGroundItemId = stateDb.nextGroundItemId();
53 this.tickIndex = 0;
54 this.movementTickCounter = 0;
55 this.lastTickAt = null;
56 this.movementAccumulator = 0;
57 this.activeRevisionId = worldDb.getActiveRevisionId();
58 this.settings = worldDb.getLiveSettings();
59
60 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
61 for (let workerId = 0; workerId < this.workerCount; workerId++)
62 {
63 const worker = new WorkerImpl(workerId);
64 worker.call({
65 type: WorkerMessage.configure,
66 settings: this.settings,
67 activeRevisionId: this.activeRevisionId
68 });
69 this.workers.push(worker);
70 }
71 }
72
73 get now ()
74 {
75 return this.nowFn();
76 }
77
78 applySettings (settings)
79 {
80 this.settings = { ...this.settings, ...settings };
81 this.#configureWorkers();
82 }
83
84 reloadWorld ()
85 {
86 this.activeRevisionId = this.worldDb.getActiveRevisionId();
87 this.settings = this.worldDb.getLiveSettings();
88 this.authoredCache.clear();
89 this.#configureWorkers();
90 for (const [key, workerId] of this.regionOwner)
91 {
92 const { regionX, regionY } = parseRegionKey(key);
93 this.workers[workerId].call({
94 type: WorkerMessage.replaceRegionChunks,
95 chunks: this.#regionChunkBlobs(regionX, regionY)
96 });
97 }
98 this.#syncAllReplicas();
99 }
100
101 enqueue (sessionId, command)
102 {
103 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
104 }
105
106 step (now = this.now)
107 {
108 this.tickIndex += 1;
109 const events = [];
110 const commands = this.commandQueue.splice(0);
111 for (const item of commands)
112 {
113 try
114 {
115 events.push(...this.#routeCommand(item));
116 }
117 catch (error)
118 {
119 events.push({
120 sessionId: item.sessionId,
121 type: "command-error",
122 message: error.userFacing ? error.message : "Command failed."
123 });
124 }
125 }
126
127 this.#recalculateActivation(now);
128
129 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
130 const expectedDt = 1 / simHz;
131 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
132 ? expectedDt
133 : Math.min(0.25, (now - this.lastTickAt) / 1000);
134 this.lastTickAt = now;
135
136 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
137 this.movementAccumulator += dt * movementHz;
138 while (this.movementAccumulator >= 1)
139 {
140 this.movementAccumulator -= 1;
141 this.movementTickCounter += 1;
142 const transfers = [];
143 for (const worker of this.workers)
144 {
145 const result = worker.call({ type: WorkerMessage.stepMovement, now });
146 for (const event of result?.events ?? [])
147 {
148 if (event.type === "entity-move")
149 { this.#applyMoveToDirectory(event); }
150 this.#persistGroundEvent(event);
151 events.push(event);
152 }
153 for (const request of result?.transferRequests ?? [])
154 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
155 }
156 events.push(...this.#applyTransfers(transfers));
157 this.#recalculateActivation(now);
158 }
159
160 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
161 { events.push(...this.#stepSpawners()); }
162
163 this.#syncGhosts();
164 return { now, events, replication: this.drainReplication() };
165 }
166
167 drainReplication ()
168 {
169 return this.replication.splice(0);
170 }
171
172 worldTime (now = this.now)
173 {
174 const date = new Date(now);
175 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
176 return {
177 unixMs: now,
178 worldUnixMs: date.getTime(),
179 iso: date.toISOString(),
180 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600
181 };
182 }
183
184 spawnCharacter (sessionId, character)
185 {
186 this.despawnCharacter(character.character_id);
187 let tileX = character.tile_x;
188 let tileY = character.tile_y;
189 if (!this.isEnterable(tileX, tileY) || this.#occupiedTile(tileX, tileY))
190 {
191 const spawn = this.findOpenSpawn();
192 if (!spawn)
193 {
194 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
195 error.userFacing = true;
196 throw error;
197 }
198 tileX = spawn.tileX;
199 tileY = spawn.tileY;
200 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, character.gait);
201 }
202
203 const bag = this.stateDb.getBag(character.character_id) ?? {
204 inventory: emptySlots(),
205 equipment: emptyEquipment(),
206 currency: 0,
207 vault: emptySlots(),
208 vaultCurrency: 0
209 };
210 const entityId = this.nextEntityId++;
211 const components = {
212 position: { tileX, tileY },
213 movement: { gait: character.gait || GAIT.walk, walkCarry: 0 },
214 path: { tiles: [] },
215 appearance: {
216 sex: character.sex,
217 firstName: character.first_name,
218 lastName: character.last_name
219 },
220 character: {
221 characterId: character.character_id,
222 accountId: character.account_id
223 },
224 networkIdentity: { sessionId },
225 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
226 inventory: { slots: bag.inventory ?? emptySlots() },
227 equipment: bag.equipment ?? emptyEquipment(),
228 currency: { amount: bag.currency ?? 0 },
229 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 }
230 };
231 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
232 const workerId = this.#ownerOfTile(tileX, tileY);
233 const view = this.workers[workerId].call({
234 type: WorkerMessage.spawn,
235 entityId,
236 components
237 });
238 this.#remember(view, workerId);
239 this.#queueReplication(replicationSpawn(view));
240 this.#recalculateActivation(this.now);
241 this.#syncGhosts();
242 return entityId;
243 }
244
245 spawnEntity (components, options = {})
246 {
247 const entityId = options.entityId ?? this.nextEntityId++;
248 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
249 const position = components.position;
250 if (!position)
251 { throw new Error("spawnEntity requires position."); }
252 if (components.chunkLoader)
253 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
254 else
255 {
256 this.#ensureRegion(
257 tileToRegion(position.tileX),
258 tileToRegion(position.tileY),
259 null
260 );
261 }
262 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
263 const view = this.workers[workerId].call({
264 type: WorkerMessage.spawn,
265 entityId,
266 components
267 });
268 this.#remember(view, workerId);
269 if (components.appearance)
270 { this.#queueReplication(replicationSpawn(view)); }
271 this.#recalculateActivation(this.now);
272 this.#syncGhosts();
273 return entityId;
274 }
275
276 despawnCharacter (characterId)
277 {
278 const entityId = this.characterEntities.get(characterId);
279 if (!entityId)
280 { return; }
281 const record = this.directory.get(entityId);
282 if (!record)
283 {
284 this.characterEntities.delete(characterId);
285 return;
286 }
287 this.#saveBag(entityId, record.workerId);
288 const dropped = this.workers[record.workerId].call({
289 type: WorkerMessage.despawnCharacter,
290 characterId
291 });
292 if (dropped)
293 {
294 this.stateDb.saveCharacterPosition(
295 characterId,
296 dropped.tileX,
297 dropped.tileY,
298 dropped.gait ?? GAIT.walk
299 );
300 this.#queueReplication(replicationDespawn(dropped));
301 }
302 this.#forget(entityId);
303 this.#recalculateActivation(this.now);
304 this.#syncGhosts();
305 }
306
307 entityForCharacter (characterId)
308 {
309 return this.characterEntities.get(characterId) ?? null;
310 }
311
312 entityRecord (entityId)
313 {
314 const record = this.directory.get(entityId);
315 return record ? { ...record } : null;
316 }
317
318 positionOf (entityId)
319 {
320 const record = this.directory.get(entityId);
321 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
322 }
323
324 bagOf (entityId)
325 {
326 const record = this.directory.get(entityId);
327 if (!record)
328 { return null; }
329 return this.workers[record.workerId].call({
330 type: WorkerMessage.inspectBag,
331 entityId
332 });
333 }
334
335 snapshotFor (entityId)
336 {
337 const record = this.directory.get(entityId);
338 if (!record)
339 { return []; }
340 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
341 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
342 }
343
344 snapshotChunk (chunkX, chunkY)
345 {
346 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
347 if (owner == null)
348 { return this.#syntheticSnapshot(chunkX, chunkY); }
349 return this.workers[owner].call({
350 type: WorkerMessage.snapshotChunk,
351 chunkX,
352 chunkY
353 });
354 }
355
356 findOpenSpawn ()
357 {
358 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
359 for (const coord of coords)
360 {
361 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
362 if (!data.open)
363 { continue; }
364 for (let localY = 0; localY < CHUNK_SIZE; localY++)
365 {
366 for (let localX = 0; localX < CHUNK_SIZE; localX++)
367 {
368 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
369 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
370 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
371 { return { tileX, tileY }; }
372 }
373 }
374 }
375 return null;
376 }
377
378 isEnterable (tileX, tileY)
379 {
380 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
381 if (!data.open)
382 { return false; }
383 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
384 }
385
386 debugWorld ()
387 {
388 const loaders = this.#allLoaders();
389 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
390 const simulatingChunks = [...chunkSim.entries()]
391 .filter(([, count]) => count > 0)
392 .map(([key]) => key)
393 .sort();
394 return {
395 tickIndex: this.tickIndex,
396 workerCount: this.workers.length,
397 workerMode: this.workerMode,
398 simulatingChunks,
399 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
400 ...parseRegionKey(key),
401 workerId,
402 state: REGION_RUNTIME_STATE.resident,
403 refs: regionRes.get(key) ?? 0,
404 graceUntil: this.regionGraceUntil.get(key) ?? null
405 })),
406 entities: [...this.directory.values()].map((entity) => ({
407 entityId: entity.entityId,
408 workerId: entity.workerId,
409 tileX: entity.tileX,
410 tileY: entity.tileY,
411 characterId: entity.characterId
412 }))
413 };
414 }
415
416 async shutdown ()
417 {
418 for (const characterId of [...this.characterEntities.keys()])
419 { this.despawnCharacter(characterId); }
420 this.forceUnloadAll();
421 await Promise.all(this.workers.map((worker) => worker.terminate()));
422 }
423
424 forceUnloadAll ()
425 {
426 for (const key of [...this.regionOwner.keys()])
427 {
428 const { regionX, regionY } = parseRegionKey(key);
429 this.#unloadRegion(regionX, regionY);
430 }
431 }
432
433 #configureWorkers ()
434 {
435 for (const worker of this.workers)
436 {
437 worker.call({
438 type: WorkerMessage.configure,
439 settings: this.settings,
440 activeRevisionId: this.activeRevisionId
441 });
442 }
443 }
444
445 #routeCommand (item)
446 {
447 const entityId = this.characterEntities.get(item.command.characterId);
448 const record = entityId ? this.directory.get(entityId) : null;
449 if (!record)
450 {
451 const error = new Error("Character is not in the world.");
452 error.userFacing = true;
453 throw error;
454 }
455 if (item.command.type === "drop-item" && item.command.groundItemId == null)
456 { item.command.groundItemId = this.nextGroundItemId++; }
457 const result = this.workers[record.workerId].call({
458 type: WorkerMessage.command,
459 sessionId: item.sessionId,
460 command: item.command,
461 now: item.receivedAt ?? this.now
462 });
463 const view = this.workers[record.workerId].call({
464 type: WorkerMessage.inspect,
465 entityId: record.entityId
466 });
467 if (view)
468 { this.#remember(view, record.workerId); }
469 if (result?.private)
470 { this.#saveBagFromView(item.command.characterId, result.private); }
471 if (result?.appearanceChanged && view)
472 { this.#queueReplication(replicationAppearance(view)); }
473 if (result?.remainder)
474 {
475 this.stateDb.saveInheritance(
476 this.stateDb.getCharacter(item.command.characterId).account_id,
477 { slots: result.remainder, currency: 0 }
478 );
479 }
480 for (const event of result?.events ?? [])
481 { this.#persistGroundEvent(event); }
482 const events = [...(result?.events ?? [])];
483 if (result?.private)
484 {
485 events.push({
486 type: "inventory",
487 sessionId: item.sessionId,
488 bank: !!result.bank,
489 ...result.private
490 });
491 }
492 return events;
493 }
494
495 #recalculateActivation (now)
496 {
497 const loaders = this.#allLoaders();
498 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
499
500 for (const [key, count] of regionRes)
501 {
502 if (count <= 0)
503 { continue; }
504 const { regionX, regionY } = parseRegionKey(key);
505 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
506 this.regionGraceUntil.delete(key);
507 }
508
509 for (const [key] of [...this.regionOwner.entries()])
510 {
511 if ((regionRes.get(key) ?? 0) > 0)
512 { continue; }
513 if (!this.regionGraceUntil.has(key))
514 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
515 if (now >= this.regionGraceUntil.get(key))
516 {
517 const { regionX, regionY } = parseRegionKey(key);
518 this.#unloadRegion(regionX, regionY);
519 }
520 }
521
522 for (const [workerId, worker] of this.workers.entries())
523 {
524 const chunkKeys = [];
525 for (const [key, count] of chunkSim)
526 {
527 if (count <= 0)
528 { continue; }
529 const { chunkX, chunkY } = parseChunkKey(key);
530 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
531 { chunkKeys.push(key); }
532 }
533 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
534 }
535 this.#syncAllReplicas();
536 }
537
538 #ensureCoverage (tileX, tileY, loader)
539 {
540 const coverage = loaderCoverage(tileX, tileY, loader);
541 let preferred = this.#ownerOfTile(tileX, tileY);
542 for (const region of coverage.residentRegions)
543 {
544 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
545 if (preferred == null)
546 { preferred = owner; }
547 }
548 }
549
550 #ensureRegion (regionX, regionY, preferredWorkerId)
551 {
552 const key = regionKey(regionX, regionY);
553 if (this.regionOwner.has(key))
554 { return this.regionOwner.get(key); }
555 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
556 this.workers[workerId].call({
557 type: WorkerMessage.assignRegion,
558 regionX,
559 regionY,
560 chunks: this.#regionChunkBlobs(regionX, regionY)
561 });
562 this.regionOwner.set(key, workerId);
563 this.#restorePersistent(regionX, regionY, workerId);
564 this.#restoreGroundItems(regionX, regionY, workerId);
565 return workerId;
566 }
567
568 #unloadRegion (regionX, regionY)
569 {
570 const key = regionKey(regionX, regionY);
571 const workerId = this.regionOwner.get(key);
572 if (workerId == null)
573 { return; }
574 const bounds = regionTileBounds(regionX, regionY);
575 const { dropped, groundItems } = this.workers[workerId].call({
576 type: WorkerMessage.dropRegion,
577 regionX,
578 regionY
579 });
580 const persistent = [];
581 for (const record of dropped ?? [])
582 {
583 if (record.characterId)
584 {
585 this.stateDb.saveCharacterPosition(
586 record.characterId,
587 record.tileX,
588 record.tileY,
589 record.gait ?? GAIT.walk
590 );
591 }
592 if (record.persistent)
593 { persistent.push(record); }
594 this.#forget(record.entityId);
595 }
596 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
597 for (const item of groundItems ?? [])
598 { this.stateDb.upsertGroundItem(item); }
599 this.regionOwner.delete(key);
600 this.regionGraceUntil.delete(key);
601 }
602
603 #restorePersistent (regionX, regionY, workerId)
604 {
605 const bounds = regionTileBounds(regionX, regionY);
606 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
607 for (const row of rows)
608 {
609 if (this.directory.has(row.entity_id))
610 { continue; }
611 const components = JSON.parse(row.components_blob);
612 const view = this.workers[workerId].call({
613 type: WorkerMessage.spawn,
614 entityId: row.entity_id,
615 components
616 });
617 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
618 this.#remember(view, workerId);
619 }
620 }
621
622 #applyTransfers (requests)
623 {
624 const events = [];
625 for (const request of requests)
626 {
627 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
628 if (destWorkerId === request.fromWorkerId)
629 {
630 this.workers[request.fromWorkerId].call({
631 type: WorkerMessage.abortTransfer,
632 entityId: request.entityId
633 });
634 continue;
635 }
636 let result;
637 try
638 {
639 result = this.workers[destWorkerId].call({
640 type: WorkerMessage.applyTransfer,
641 payload: request.payload,
642 destTileX: request.destTileX,
643 destTileY: request.destTileY
644 });
645 }
646 catch
647 {
648 result = { accepted: false };
649 }
650 if (!result?.accepted)
651 {
652 this.workers[request.fromWorkerId].call({
653 type: WorkerMessage.abortTransfer,
654 entityId: request.entityId
655 });
656 continue;
657 }
658 this.workers[request.fromWorkerId].call({
659 type: WorkerMessage.commitTransfer,
660 entityId: request.entityId
661 });
662 this.#remember(result.entity, destWorkerId);
663 events.push({
664 type: "entity-move",
665 entityId: request.entityId,
666 fromTileX: request.fromTileX,
667 fromTileY: request.fromTileY,
668 tileX: result.entity.tileX,
669 tileY: result.entity.tileY,
670 gait: result.entity.gait
671 });
672 }
673 return events;
674 }
675
676 #syncAllReplicas ()
677 {
678 for (const [workerId, worker] of this.workers.entries())
679 {
680 const ownedKeys = new Set();
681 for (const [key, owner] of this.regionOwner)
682 {
683 if (owner !== workerId)
684 { continue; }
685 const { regionX, regionY } = parseRegionKey(key);
686 for (const chunk of chunksInRegion(regionX, regionY))
687 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
688 }
689 const replicas = [];
690 for (const key of replicaNeededForOwnedChunks(ownedKeys))
691 {
692 if (ownedKeys.has(key))
693 { continue; }
694 const { chunkX, chunkY } = parseChunkKey(key);
695 replicas.push({
696 chunkX,
697 chunkY,
698 data: this.#authoredChunk(chunkX, chunkY)
699 });
700 }
701 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
702 }
703 }
704
705 #syncGhosts ()
706 {
707 const entities = [];
708 for (const worker of this.workers)
709 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
710 for (const [workerId, worker] of this.workers.entries())
711 {
712 const ghosts = entities.filter((entity) =>
713 {
714 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
715 { return false; }
716 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
717 });
718 worker.call({ type: WorkerMessage.setGhosts, ghosts });
719 }
720 }
721
722 #nearWorker (workerId, tileX, tileY)
723 {
724 const chunkX = tileToChunk(tileX);
725 const chunkY = tileToChunk(tileY);
726 for (const [key, owner] of this.regionOwner)
727 {
728 if (owner !== workerId)
729 { continue; }
730 const { regionX, regionY } = parseRegionKey(key);
731 for (const chunk of chunksInRegion(regionX, regionY))
732 {
733 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
734 { return true; }
735 }
736 }
737 return false;
738 }
739
740 #allLoaders ()
741 {
742 const loaders = [];
743 for (const worker of this.workers)
744 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
745 return loaders;
746 }
747
748 #preferredWorkerForRegion (loaders, regionX, regionY)
749 {
750 const votes = new Map();
751 for (const loader of loaders)
752 {
753 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
754 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
755 { continue; }
756 const record = this.directory.get(loader.entityId);
757 if (record?.workerId == null)
758 { continue; }
759 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
760 }
761 let best = null;
762 let bestVotes = -1;
763 for (const [workerId, count] of votes)
764 {
765 if (count > bestVotes)
766 {
767 best = workerId;
768 bestVotes = count;
769 }
770 }
771 return best;
772 }
773
774 #pickWorker (regionX, regionY, preferredWorkerId)
775 {
776 const pinned = this.pinRegion?.(regionX, regionY);
777 if (pinned != null)
778 { return pinned; }
779
780 const neighborOwners = [];
781 for (let dy = -1; dy <= 1; dy++)
782 {
783 for (let dx = -1; dx <= 1; dx++)
784 {
785 if (dx === 0 && dy === 0)
786 { continue; }
787 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
788 if (owner != null)
789 { neighborOwners.push(owner); }
790 }
791 }
792
793 const scores = this.workers.map((_, workerId) => ({
794 workerId,
795 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
796 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
797 }));
798
799 if (preferredWorkerId != null && scores[preferredWorkerId])
800 {
801 const preferred = scores[preferredWorkerId];
802 if (preferred.neighbors > 0 || neighborOwners.length === 0)
803 { return preferredWorkerId; }
804 }
805
806 scores.sort((left, right) =>
807 right.neighbors - left.neighbors
808 || left.load - right.load
809 || left.workerId - right.workerId
810 );
811 return scores[0].workerId;
812 }
813
814 #ownerOfTile (tileX, tileY)
815 {
816 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
817 }
818
819 #regionKeyForChunk (chunkX, chunkY)
820 {
821 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
822 }
823
824 #regionChunkBlobs (regionX, regionY)
825 {
826 return chunksInRegion(regionX, regionY).map((coord) => ({
827 chunkX: coord.chunkX,
828 chunkY: coord.chunkY,
829 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
830 }));
831 }
832
833 #authoredChunk (chunkX, chunkY)
834 {
835 const key = chunkKey(chunkX, chunkY);
836 if (this.authoredCache.has(key))
837 { return this.authoredCache.get(key); }
838 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
839 const data = row
840 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
841 : createEmptyChunkData(this.settings.defaultGroundTypeId);
842 this.authoredCache.set(key, data);
843 return data;
844 }
845
846 #syntheticSnapshot (chunkX, chunkY)
847 {
848 const data = this.#authoredChunk(chunkX, chunkY);
849 return {
850 chunkX,
851 chunkY,
852 open: data.open,
853 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
854 grounds: data.grounds,
855 blocks: data.blocks,
856 light: data.light,
857 entities: [],
858 groundItems: []
859 };
860 }
861
862 #occupiedTile (tileX, tileY)
863 {
864 for (const record of this.directory.values())
865 {
866 if (record.tileX === tileX && record.tileY === tileY)
867 { return record.entityId; }
868 }
869 return null;
870 }
871
872 #queueReplication (event)
873 {
874 if (event)
875 { this.replication.push(event); }
876 }
877
878 #stepSpawners ()
879 {
880 const events = [];
881 for (const worker of this.workers)
882 {
883 const result = worker.call({ type: WorkerMessage.stepSpawners });
884 for (const request of result?.spawnRequests ?? [])
885 {
886 try
887 {
888 this.spawnEntity(mobComponents(request));
889 }
890 catch
891 { continue; }
892 }
893 }
894 return events;
895 }
896
897 #restoreGroundItems (regionX, regionY, workerId)
898 {
899 const bounds = regionTileBounds(regionX, regionY);
900 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
901 .filter((item) => item.expiresAt > this.now);
902 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
903 this.workers[workerId].call({
904 type: WorkerMessage.setGroundItems,
905 regionX,
906 regionY,
907 items
908 });
909 }
910
911 #persistGroundEvent (event)
912 {
913 if (event.type === "ground-item-appear")
914 {
915 this.stateDb.upsertGroundItem({
916 groundItemId: event.groundItemId,
917 tileX: event.tileX,
918 tileY: event.tileY,
919 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
920 droppedAt: event.droppedAt ?? this.now,
921 expiresAt: event.expiresAt,
922 source: event.source ?? "player-drop",
923 droppedByCharacterId: event.droppedByCharacterId ?? null
924 });
925 }
926 if (event.type === "ground-item-despawn")
927 { this.stateDb.deleteGroundItem(event.groundItemId); }
928 }
929
930 #saveBag (entityId, workerId)
931 {
932 const record = this.directory.get(entityId);
933 const bag = this.workers[workerId].call({
934 type: WorkerMessage.inspectBag,
935 entityId
936 });
937 if (!bag || !record?.characterId)
938 { return; }
939 this.#saveBagFromView(record.characterId, bag);
940 }
941
942 #saveBagFromView (characterId, bag)
943 {
944 this.stateDb.saveBag(characterId, {
945 inventory: bag.inventory,
946 equipment: bag.equipment,
947 currency: bag.currency,
948 vault: bag.vault,
949 vaultCurrency: bag.vaultCurrency
950 });
951 }
952
953 #remember (view, workerId)
954 {
955 if (!view)
956 { return; }
957 this.directory.set(view.entityId, { ...view, workerId });
958 if (view.characterId)
959 { this.characterEntities.set(view.characterId, view.entityId); }
960 }
961
962 #applyMoveToDirectory (event)
963 {
964 const record = this.directory.get(event.entityId);
965 if (!record)
966 { return; }
967 record.tileX = event.tileX;
968 record.tileY = event.tileY;
969 record.gait = event.gait;
970 }
971
972 #forget (entityId)
973 {
974 const record = this.directory.get(entityId);
975 if (record?.characterId)
976 { this.characterEntities.delete(record.characterId); }
977 this.directory.delete(entityId);
978 }
979}