BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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