BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 80.0 KiB Download Raw
1import
2 {
3 CHUNK_SIZE,
4 DEFAULT_CHUNK_LOADER,
5 GAIT,
6 REGION_RUNTIME_STATE,
7 VISIBLE_CHUNK_RADIUS,
8 STATIC_CHUNK_RADIUS,
9 WORLD_YEAR_OFFSET
10 } from "../../../shared/protocol/constants.js";
11import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";
12import
13 {
14 chunkKey,
15 chunkToRegion,
16 chunksInRegion,
17 parseChunkKey,
18 parseRegionKey,
19 regionKey,
20 regionTileBounds,
21 tileToChunk,
22 tileToLocal,
23 tileToRegion,
24 visibleChunkCoords
25 } from "../world/coordinates.js";
26import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
27import { closedNeighborEdges } from "../world/chunkFlags.js";
28import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
29import { InProcessWorker } from "./inProcessWorker.js";
30import { ThreadWorker } from "./threadWorker.js";
31import { WorkerMessage } from "./protocol.js";
32import { replicaNeededForOwnedChunks } from "./workerWorld.js";
33import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
34import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
35import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
36import { skullValue, decayKillCounter, SKULL_KILL_BONUS } from "../../../shared/combat/skull.js";
37import { mobComponents } from "./spawners.js";
38import { shadeSummonComponents } from "../spells/summons.js";
39import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
40import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
41import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
42import { BlockType } from "../../../shared/definitions/tiles.js";
43import { ItemId } from "../../../shared/definitions/items.js";
44import { seasonIdAt } from "../../../shared/world/season.js";
45import { CourierService } from "../courier/service.js";
46import { MarketService } from "../market/service.js";
47import { BountyService } from "../bounty/service.js";
48import { BarberService } from "../barber/service.js";
49import { findReservedChequeIndex } from "../items/bags.js";
50import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
51import { QuestContentCache } from "../quests/contentCache.js";
52import { QuestRuntime } from "../quests/runtime.js";
53import { chebyshev } from "../combat/service.js";
54
55export class Simulation
56{
57 constructor(worldDb, stateDb, options = {})
58 {
59 this.worldDb = worldDb;
60 this.stateDb = stateDb;
61 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
62 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
63 this.pinRegion = options.pinRegion ?? null;
64 this.nowFn = options.now ?? (() => Date.now());
65 this.workers = [];
66 this.regionOwner = new Map();
67 this.regionGraceUntil = new Map();
68 this.directory = new Map();
69 this.characterEntities = new Map();
70 this.commandQueue = [];
71 this.replication = [];
72 this.pendingPrivate = [];
73 this.courier = null;
74 this.market = null;
75 this.altarTiles = [];
76 this.authoredCache = new Map();
77 this.simulatingChunkKeys = new Set();
78 this.nextEntityId = 1;
79 this.nextGroundItemId = stateDb.nextGroundItemId();
80 this.tickIndex = 0;
81 this.movementTickCounter = 0;
82 this.lastTickAt = null;
83 this.movementAccumulator = 0;
84 this.activeRevisionId = worldDb.getActiveRevisionId();
85 this.settings = worldDb.getLiveSettings();
86 this.questContent = new QuestContentCache(worldDb);
87 this.dimensions = this.#loadDimensionsCache();
88 this.quests = null;
89
90 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
91 for (let workerId = 0; workerId < this.workerCount; workerId++)
92 {
93 const worker = new WorkerImpl(workerId);
94 worker.call({
95 type: WorkerMessage.configure,
96 settings: this.settings,
97 activeRevisionId: this.activeRevisionId
98 });
99 this.workers.push(worker);
100 }
101 for (const worker of this.workers)
102 {
103 if (!worker.world)
104 { continue; }
105 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
106 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
107 }
108 this.courier = new CourierService({
109 stateDb: this.stateDb,
110 worldDb: this.worldDb,
111 simulation: this
112 });
113 this.market = new MarketService({
114 stateDb: this.stateDb,
115 worldDb: this.worldDb,
116 simulation: this
117 });
118 this.bounty = new BountyService(this.stateDb, this, this.courier);
119 this.barber = new BarberService(this.stateDb, this);
120 this.quests = new QuestRuntime({
121 stateDb: this.stateDb,
122 content: this.questContent,
123 simulation: this
124 });
125 this.#refreshAltarIndex();
126 }
127
128 get now ()
129 {
130 return this.nowFn();
131 }
132
133 applySettings (settings)
134 {
135 this.settings = { ...this.settings, ...settings };
136 this.#configureWorkers();
137 }
138
139 /** Sparse last-sale map for editor base-price readouts. */
140 itemLastSalesSnapshot ()
141 {
142 return this.market?.snapshot?.() ?? {};
143 }
144
145 syncItemLastSales (lastSales)
146 {
147 const sales = {};
148 for (const [itemId, sale] of lastSales?.entries?.() ?? [])
149 { sales[String(itemId)] = sale; }
150 for (const worker of this.workers)
151 {
152 worker.call({
153 type: WorkerMessage.setItemLastSales,
154 sales
155 });
156 }
157 }
158
159 reloadWorld ()
160 {
161 this.activeRevisionId = this.worldDb.getActiveRevisionId();
162 this.settings = this.worldDb.getLiveSettings();
163 this.dimensions = this.#loadDimensionsCache();
164 this.authoredCache.clear();
165 this.#configureWorkers();
166 for (const [key, workerId] of this.regionOwner)
167 {
168 const { regionX, regionY, dimensionId } = parseRegionKey(key);
169 this.workers[workerId].call({
170 type: WorkerMessage.replaceRegionChunks,
171 regionX,
172 regionY,
173 dimensionId,
174 chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId)
175 });
176 }
177 this.#syncAllReplicas();
178 this.courier?.refreshBankIndex();
179 this.courier?.refreshBountyOfficeIndex();
180 this.market?.refreshIndex();
181 this.questContent.reload();
182 this.quests?.closeAllSessions();
183 this.#refreshAltarIndex();
184 }
185
186 enqueue (sessionId, command)
187 {
188 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
189 }
190
191 step (now = this.now)
192 {
193 this.tickIndex += 1;
194 if ((this.tickIndex % 1200) === 0)
195 { this.worldDb.purgeExpiredDimensions(now); }
196 const events = [];
197 const commands = this.commandQueue.splice(0);
198 for (const item of commands)
199 {
200 try
201 {
202 events.push(...this.#routeCommand(item));
203 }
204 catch (error)
205 {
206 events.push({
207 sessionId: item.sessionId,
208 type: "command-error",
209 message: error.userFacing ? error.message : "Command failed."
210 });
211 }
212 }
213
214 this.#recalculateActivation(now);
215
216 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
217 const expectedDt = 1 / simHz;
218 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
219 ? expectedDt
220 : Math.min(0.25, (now - this.lastTickAt) / 1000);
221 this.lastTickAt = now;
222
223 {
224 const transfers = [];
225 const remoteMelee = [];
226 const remoteRanged = [];
227 for (const worker of this.workers)
228 {
229 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
230 for (const event of result?.events ?? [])
231 {
232 if (event.type === "remote-melee-resolve")
233 {
234 remoteMelee.push(event);
235 continue;
236 }
237 if (event.type === "remote-ranged-resolve")
238 {
239 remoteRanged.push(event);
240 continue;
241 }
242 if (event.type === "summon-entity")
243 {
244 events.push(...this.#applySummonEntity(event));
245 continue;
246 }
247 if (event.type === "entity-move")
248 { this.#applyMoveToDirectory(event); }
249 if (event.type === "entity-despawn")
250 { this.#forget(event.entityId); }
251 if (event.type === "skills-updated")
252 {
253 this.#applySkillsUpdated(event);
254 events.push(...this.#skillLevelUpEvents(event));
255 continue;
256 }
257 if (event.type === "spells-updated")
258 {
259 this.#applySpellsUpdated(event);
260 continue;
261 }
262 if (event.type === "inventory" && event.characterId)
263 {
264 this.#saveBagFromView(event.characterId, {
265 inventory: event.inventory,
266 equipment: event.equipment,
267 vault: event.vault,
268 vaultReserved: event.vaultReserved
269 });
270 }
271 if (event.type === "player-died")
272 {
273 events.push(...this.#applyPlayerDeath(event));
274 continue;
275 }
276 if (event.type === "mob-killed")
277 {
278 events.push(...this.#applyMobKilled(event));
279 continue;
280 }
281 if (event.type === "dialogue-walk-away")
282 {
283 const closed = this.quests?.closeDialogue(event.characterId, "walk-away");
284 events.push(...this.#mapQuestPrivateEvents(
285 closed?.events ?? [],
286 event.sessionId,
287 event.characterId
288 ));
289 continue;
290 }
291 this.#persistGroundEvent(event);
292 if (event.type !== "skills-updated")
293 { events.push(event); }
294 }
295 for (const request of result?.transferRequests ?? [])
296 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
297 }
298 for (const payload of remoteMelee)
299 { events.push(...this.#applyRemoteMelee(payload)); }
300 for (const payload of remoteRanged)
301 { events.push(...this.#applyRemoteRanged(payload)); }
302 if (transfers.length)
303 {
304 events.push(...this.#applyTransfers(transfers));
305 this.#recalculateActivation(now);
306 }
307 }
308
309 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
310 this.movementAccumulator += dt * movementHz;
311 while (this.movementAccumulator >= 1)
312 {
313 this.movementAccumulator -= 1;
314 this.movementTickCounter += 1;
315 const transfers = [];
316 for (const worker of this.workers)
317 {
318 const result = worker.call({ type: WorkerMessage.stepMovement, now });
319 for (const event of result?.events ?? [])
320 {
321 if (event.type === "entity-move")
322 { this.#applyMoveToDirectory(event); }
323 if (event.type === "skills-updated")
324 {
325 this.#applySkillsUpdated(event);
326 events.push(...this.#skillLevelUpEvents(event));
327 continue;
328 }
329 if (event.type === "spells-updated")
330 {
331 this.#applySpellsUpdated(event);
332 continue;
333 }
334 this.#persistGroundEvent(event);
335 if (event.type !== "skills-updated")
336 { events.push(event); }
337 }
338 for (const request of result?.transferRequests ?? [])
339 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
340 }
341 events.push(...this.#applyTransfers(transfers));
342 this.#recalculateActivation(now);
343 }
344
345 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
346 { events.push(...this.#stepSpawners()); }
347
348 if (this.tickIndex % Math.max(1, Math.round(simHz)) === 0)
349 { this.#stepSkullDecay(); }
350
351 if (this.courier)
352 { events.push(...this.courier.step(now, dt)); }
353 if (this.market)
354 { events.push(...this.market.step(now)); }
355
356 this.#syncGhosts();
357 events.push(...this.pendingPrivate.splice(0));
358 return { now, events, replication: this.drainReplication() };
359 }
360
361 drainReplication ()
362 {
363 return this.replication.splice(0);
364 }
365
366 worldTime (now = this.now)
367 {
368 const date = new Date(now);
369 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
370 return {
371 unixMs: now,
372 worldUnixMs: date.getTime(),
373 iso: date.toISOString(),
374 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,
375 season: seasonIdAt(now)
376 };
377 }
378
379 spawnCharacter (sessionId, character)
380 {
381 this.despawnCharacter(character.character_id);
382 // Despawn may have just written the live tile; never trust a stale row snapshot.
383 const row = this.stateDb.getCharacter(character.character_id) ?? character;
384 let tileX = row.tile_x;
385 let tileY = row.tile_y;
386 let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID);
387 const gait = row.gait || character.gait || GAIT.walk;
388
389 // Soft-deleted / purged interiors eject to overworld spawn.
390 if (!this.#isDimensionUsable(dimensionId))
391 {
392 dimensionId = OVERWORLD_ID;
393 const spawn = this.findOpenSpawn();
394 if (!spawn)
395 {
396 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
397 error.userFacing = true;
398 throw error;
399 }
400 tileX = spawn.tileX;
401 tileY = spawn.tileY;
402 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
403 }
404
405 const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId);
406 if (!preferred)
407 {
408 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
409 error.userFacing = true;
410 throw error;
411 }
412 if (
413 preferred.tileX !== tileX
414 || preferred.tileY !== tileY
415 || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId
416 )
417 {
418 tileX = preferred.tileX;
419 tileY = preferred.tileY;
420 dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId);
421 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
422 }
423
424 const bag = this.stateDb.getBag(character.character_id) ?? {
425 inventory: emptySlots(),
426 equipment: emptyEquipment(),
427 vault: [],
428 vaultReserved: []
429 };
430 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
431 const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();
432 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
433 if (enforceMinimumSkillLevels(skills))
434 { this.stateDb.saveSkills(character.character_id, skills); }
435 const maxHealth = playerMaxHealth(skills);
436 const maxStamina = playerMaxStamina(skills);
437 const isDead = !!row.is_dead;
438 const savedHealth = row.health_current;
439 const currentHealth = isDead
440 ? 0
441 : savedHealth != null
442 ? Math.max(0, Math.min(maxHealth, savedHealth | 0))
443 : maxHealth;
444 const entityId = this.nextEntityId++;
445 const components = {
446 position: { tileX, tileY, dimensionId },
447 movement: { gait, walkCarry: 0 },
448 path: { tiles: [] },
449 appearance: {
450 sex: character.sex ?? row.sex,
451 firstName: character.first_name ?? row.first_name,
452 lastName: character.last_name ?? row.last_name,
453 ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character))
454 },
455 character: {
456 characterId: character.character_id ?? row.character_id,
457 accountId: character.account_id ?? row.account_id
458 },
459 networkIdentity: { sessionId },
460 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
461 inventory: { slots: bag.inventory ?? emptySlots() },
462 equipment: bag.equipment ?? emptyEquipment(),
463 vault: {
464 slots: bag.vault ?? [],
465 reserved: bag.vaultReserved ?? []
466 },
467 health: { current: currentHealth, max: maxHealth },
468 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
469 combat: { targetEntityId: null, nextSwingAt: 0 },
470 skills,
471 spells,
472 spellcasting: {
473 armedSpellId: null,
474 repeatSpellId: null,
475 repeatTargetEntityId: null,
476 repeatTileX: null,
477 repeatTileY: null,
478 nextCastAt: 0,
479 pendingCast: null
480 },
481 };
482 if (isDead)
483 { components.dead = {}; }
484 this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId);
485 const workerId = this.#ownerOfTile(tileX, tileY, dimensionId);
486 const view = this.workers[workerId].call({
487 type: WorkerMessage.spawn,
488 entityId,
489 components
490 });
491 this.#remember(view, workerId);
492 this.#attachSkullToRecord(view.entityId, character.character_id ?? row.character_id);
493 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
494 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
495 this.#recalculateActivation(this.now);
496 this.#syncGhosts();
497 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
498 return entityId;
499 }
500
501 characterSkullValue (characterId, now = this.now)
502 {
503 const bounty = this.stateDb.getCharacterBounty(characterId);
504 const killCounter = this.stateDb.peekKillCounter(characterId, now);
505 return skullValue(bounty, killCounter);
506 }
507
508 refreshCharacterSkull (characterId, { force = false } = {})
509 {
510 const id = characterId | 0;
511 if (!id)
512 { return null; }
513 const state = this.stateDb.getKillCounterState(id);
514 const elapsed = Math.max(0, this.now - (state.updatedAt | 0));
515 const decayed = decayKillCounter(state.killCounter, elapsed);
516 if (decayed.killCounter !== state.killCounter)
517 { this.stateDb.setKillCounter(id, decayed.killCounter, this.now); }
518 const value = this.characterSkullValue(id);
519 const entityId = this.characterEntities.get(id);
520 const record = entityId ? this.directory.get(entityId) : null;
521 if (!record)
522 { return null; }
523 if (!force && (record.skullValue | 0) === value)
524 { return null; }
525 record.skullValue = value;
526 const event = {
527 type: "entity-skull",
528 entityId,
529 skullValue: value,
530 tileX: record.tileX,
531 tileY: record.tileY,
532 dimensionId: record.dimensionId ?? OVERWORLD_ID
533 };
534 this.#queueReplication(event);
535 return event;
536 }
537
538 #attachSkullToRecord (entityId, characterId)
539 {
540 const record = this.directory.get(entityId);
541 if (!record)
542 { return; }
543 record.skullValue = this.characterSkullValue(characterId);
544 }
545
546 #stepSkullDecay ()
547 {
548 for (const characterId of this.characterEntities.keys())
549 {
550 const state = this.stateDb.getKillCounterState(characterId);
551 if (!(state.killCounter > 0))
552 { continue; }
553 this.refreshCharacterSkull(characterId);
554 }
555 }
556
557 isCharacterOnline (characterId)
558 {
559 return this.characterEntities.has(characterId);
560 }
561
562 reattachCharacterSession (characterId, sessionId)
563 {
564 const entityId = this.characterEntities.get(characterId | 0);
565 if (!entityId)
566 { return null; }
567 const record = this.directory.get(entityId);
568 if (!record)
569 { return null; }
570 const result = this.workers[record.workerId].call({
571 type: WorkerMessage.reattachSession,
572 characterId,
573 sessionId
574 });
575 if (!result?.ok)
576 { return null; }
577 this.market?.reattachSession?.(characterId, sessionId);
578 return entityId;
579 }
580
581 spawnEntity (components, options = {})
582 {
583 const entityId = options.entityId ?? this.nextEntityId++;
584 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
585 const position = components.position;
586 if (!position)
587 { throw new Error("spawnEntity requires position."); }
588 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
589 position.dimensionId = dimensionId;
590 if (options.requireResident)
591 {
592 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
593 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId))
594 { return null; }
595 const view = this.workers[workerId].call({
596 type: WorkerMessage.spawn,
597 entityId,
598 components
599 });
600 this.#remember(view, workerId);
601 if (components.appearance)
602 { this.#queueReplication(replicationSpawn(view)); }
603 this.#syncGhosts();
604 return entityId;
605 }
606 if (components.chunkLoader)
607 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); }
608 else
609 {
610 this.#ensureRegion(
611 tileToRegion(position.tileX),
612 tileToRegion(position.tileY),
613 null,
614 dimensionId
615 );
616 }
617 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
618 const view = this.workers[workerId].call({
619 type: WorkerMessage.spawn,
620 entityId,
621 components
622 });
623 this.#remember(view, workerId);
624 if (components.appearance)
625 { this.#queueReplication(replicationSpawn(view)); }
626 this.#recalculateActivation(this.now);
627 this.#syncGhosts();
628 return entityId;
629 }
630
631 despawnEntity (entityId)
632 {
633 const record = this.directory.get(entityId);
634 if (!record)
635 { return; }
636 const dropped = this.workers[record.workerId].call({
637 type: WorkerMessage.despawn,
638 entityId
639 });
640 if (dropped)
641 { this.#queueReplication(replicationDespawn(dropped)); }
642 this.#forget(entityId);
643 }
644
645 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
646 {
647 const loaders = this.#allLoaders();
648 const { chunkSim } = accumulateLoaderRefs(loaders);
649 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0;
650 }
651
652 updateCourierFlight (entityId, flightPatch, now = this.now)
653 {
654 const record = this.directory.get(entityId);
655 if (!record)
656 { return { despawned: true, entityId }; }
657 const tileX = Math.floor(flightPatch.x);
658 const tileY = Math.floor(flightPatch.y);
659 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
660 const owner = this.#ownerOfTile(tileX, tileY, dimensionId);
661 if (owner == null || owner !== record.workerId)
662 {
663 this.despawnEntity(entityId);
664 return { despawned: true, entityId };
665 }
666 const result = this.workers[owner].call({
667 type: WorkerMessage.updateFlight,
668 entityId,
669 flight: flightPatch,
670 now
671 });
672 if (result?.transferRequest)
673 {
674 const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
675 this.#recalculateActivation(now);
676 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
677 if (move)
678 {
679 this.#applyMoveToDirectory(move);
680 return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
681 }
682 this.despawnEntity(entityId);
683 return { despawned: true, entityId };
684 }
685 if (result?.event)
686 {
687 this.#applyMoveToDirectory(result.event);
688 return { event: result.event };
689 }
690 return null;
691 }
692
693 applyBag (entityId, bag)
694 {
695 const record = this.directory.get(entityId);
696 if (!record)
697 { return null; }
698 return this.workers[record.workerId].call({
699 type: WorkerMessage.applyBag,
700 entityId,
701 bag
702 });
703 }
704
705 /**
706 * Persist hair + patch live appearance; returns public view.
707 */
708 setCharacterHair (characterId, hair)
709 {
710 const row = this.stateDb.updateCharacterHair(characterId, hair);
711 const entityId = this.characterEntities.get(characterId);
712 if (!entityId)
713 { return { row, view: null }; }
714 const fields = appearanceHairFields({
715 sex: row.sex,
716 style: hair.style,
717 hue: hair.hue,
718 saturation: hair.saturation,
719 darkness: hair.darkness
720 });
721 const record = this.directory.get(entityId);
722 if (!record)
723 { return { row, view: null }; }
724 const view = this.workers[record.workerId].call({
725 type: WorkerMessage.applyAppearance,
726 entityId,
727 appearance: fields
728 });
729 if (view)
730 {
731 this.#remember(view, record.workerId);
732 this.#queueReplication(replicationAppearance(view));
733 }
734 return { row, view };
735 }
736
737 pushSkills (characterId, skills)
738 {
739 this.pendingPrivate.push({
740 type: "skills",
741 characterId,
742 skills
743 });
744 }
745
746 pushSpells (characterId, payload)
747 {
748 this.pendingPrivate.push({
749 type: "spells",
750 characterId,
751 ...payload
752 });
753 }
754
755 skillsOf (entityId)
756 {
757 const record = this.directory.get(entityId);
758 if (!record)
759 { return null; }
760 return this.workers[record.workerId].call({
761 type: WorkerMessage.inspectSkills,
762 entityId
763 });
764 }
765
766 spellsOf (entityId)
767 {
768 const record = this.directory.get(entityId);
769 if (!record)
770 { return null; }
771 return this.workers[record.workerId].call({
772 type: WorkerMessage.inspectSpells,
773 entityId
774 });
775 }
776
777 staminaOf (entityId)
778 {
779 const record = this.directory.get(entityId);
780 if (!record)
781 { return null; }
782 return this.workers[record.workerId].call({
783 type: WorkerMessage.inspectStamina,
784 entityId
785 });
786 }
787
788 pushInventory (characterId, bag)
789 {
790 this.pendingPrivate.push({
791 type: "inventory",
792 characterId,
793 inventory: bag.inventory,
794 equipment: bag.equipment,
795 vault: bag.vault,
796 vaultReserved: bag.vaultReserved
797 });
798 }
799
800 dispatchPigeon ({ characterId, destination, cargo })
801 {
802 const entityId = this.characterEntities.get(characterId);
803 const position = entityId ? this.positionOf(entityId) : null;
804 if (!position)
805 {
806 const error = new Error("Enter the world before sending a pigeon.");
807 error.userFacing = true;
808 throw error;
809 }
810 return this.courier.dispatchFromPlayer({
811 characterId,
812 originTileX: position.tileX,
813 originTileY: position.tileY,
814 destination,
815 cargo
816 });
817 }
818
819 /**
820 * Path an idle CE clerk to a staff-side station tile.
821 */
822 stationExchangeClerk (stationTileX, stationTileY)
823 {
824 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
825 if (owner == null)
826 { return { ok: false, reason: "unowned" }; }
827 return this.workers[owner].call({
828 type: WorkerMessage.stationExchangeClerk,
829 stationTileX,
830 stationTileY
831 });
832 }
833
834 /**
835 * When a player uses a marketplace counter, path idle CE clerks to the
836 * opposite side of each adjacent counter (staff side).
837 */
838 stationExchangeClerks (playerTileX, playerTileY)
839 {
840 const results = [];
841 for (const tile of this.market?.marketTiles ?? [])
842 {
843 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
844 { continue; }
845 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
846 { continue; }
847 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
848 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
849 if (stationTileX === playerTileX && stationTileY === playerTileY)
850 { continue; }
851 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
852 }
853 return results;
854 }
855
856 /** Release a CE clerk stationed at the given staff-side tile. */
857 releaseExchangeClerk (stationTileX, stationTileY)
858 {
859 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
860 if (owner == null)
861 { return { ok: false, reason: "unowned" }; }
862 return this.workers[owner].call({
863 type: WorkerMessage.releaseExchangeClerk,
864 stationTileX,
865 stationTileY
866 });
867 }
868
869 despawnCharacter (characterId)
870 {
871 this.market?.leaveExchangeStations?.(characterId);
872 const entityId = this.characterEntities.get(characterId);
873 if (!entityId)
874 { return; }
875 const record = this.directory.get(entityId);
876 if (!record)
877 {
878 this.characterEntities.delete(characterId);
879 return;
880 }
881 this.#saveBag(entityId, record.workerId);
882 const dropped = this.workers[record.workerId].call({
883 type: WorkerMessage.despawnCharacter,
884 characterId
885 });
886 if (dropped)
887 {
888 this.stateDb.saveCharacterPosition(
889 characterId,
890 dropped.tileX,
891 dropped.tileY,
892 dropped.gait ?? GAIT.walk,
893 dropped.dimensionId ?? OVERWORLD_ID
894 );
895 if (dropped.health != null)
896 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
897 this.#queueReplication(replicationDespawn(dropped));
898 }
899 this.#forget(entityId);
900 this.#recalculateActivation(this.now);
901 this.#syncGhosts();
902 }
903
904 entityForCharacter (characterId)
905 {
906 return this.characterEntities.get(characterId) ?? null;
907 }
908
909 entityRecord (entityId)
910 {
911 const record = this.directory.get(entityId);
912 return record ? { ...record } : null;
913 }
914
915 positionOf (entityId)
916 {
917 const record = this.directory.get(entityId);
918 return record
919 ? {
920 tileX: record.tileX,
921 tileY: record.tileY,
922 dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID)
923 }
924 : null;
925 }
926
927 bagOf (entityId)
928 {
929 const record = this.directory.get(entityId);
930 if (!record)
931 { return null; }
932 return this.workers[record.workerId].call({
933 type: WorkerMessage.inspectBag,
934 entityId
935 });
936 }
937
938 snapshotFor (entityId)
939 {
940 const record = this.directory.get(entityId);
941 if (!record)
942 { return []; }
943 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
944 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
945 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId));
946 }
947
948 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
949 snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
950 {
951 const record = this.directory.get(entityId);
952 if (!record)
953 { return []; }
954 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
955 const centerChunkX = tileToChunk(record.tileX);
956 const centerChunkY = tileToChunk(record.tileY);
957 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
958 const entityKeys = new Set(
959 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
960 .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId))
961 );
962 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
963 .map((coord) =>
964 {
965 const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId);
966 const staticOnly = !entityKeys.has(key);
967 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId);
968 const entities = (snapshot.entities ?? []).map((entity) =>
969 {
970 const known = this.directory.get(entity.entityId);
971 if (!known || entity.characterId == null)
972 { return entity; }
973 return { ...entity, skullValue: known.skullValue | 0 };
974 });
975 return { ...snapshot, entities, staticOnly };
976 });
977 }
978
979 snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
980 {
981 const dim = normalizeDimensionId(dimensionId);
982 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim));
983 if (owner == null)
984 { return this.#syntheticSnapshot(chunkX, chunkY, dim); }
985 return this.workers[owner].call({
986 type: WorkerMessage.snapshotChunk,
987 chunkX,
988 chunkY,
989 dimensionId: dim,
990 staticOnly: !!staticOnly
991 });
992 }
993
994 findOpenSpawn ()
995 {
996 const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID);
997 for (const coord of coords)
998 {
999 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID);
1000 if (!data.open)
1001 { continue; }
1002 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1003 {
1004 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1005 {
1006 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
1007 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
1008 if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID))
1009 { return { tileX, tileY, dimensionId: OVERWORLD_ID }; }
1010 }
1011 }
1012 }
1013 return null;
1014 }
1015
1016 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
1017 #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID)
1018 {
1019 const dim = normalizeDimensionId(dimensionId);
1020 return this.#findNearbyEnterable(tileX, tileY, radius, dim)
1021 ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn());
1022 }
1023
1024 #isDimensionUsable (dimensionId)
1025 {
1026 const dim = normalizeDimensionId(dimensionId);
1027 if (dim === OVERWORLD_ID)
1028 { return true; }
1029 const record = this.getDimensionRecord(dim);
1030 if (!record)
1031 { return false; }
1032 if (record.deletedAt != null)
1033 { return false; }
1034 if (record.purgeAfter != null && record.purgeAfter <= this.now)
1035 { return false; }
1036 return true;
1037 }
1038
1039 #loadDimensionsCache ()
1040 {
1041 const map = new Map();
1042 for (const dim of this.worldDb.listDimensions(this.activeRevisionId))
1043 { map.set(dim.dimensionId, dim); }
1044 if (!map.has(OVERWORLD_ID))
1045 {
1046 map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, {
1047 defaultGroundTypeId: this.settings.defaultGroundTypeId
1048 }));
1049 }
1050 return map;
1051 }
1052
1053 getDimensionRecord (dimensionId)
1054 {
1055 const dim = normalizeDimensionId(dimensionId);
1056 return this.dimensions?.get(dim)
1057 ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim)
1058 ?? (dim === OVERWORLD_ID
1059 ? defaultDimensionRecord(OVERWORLD_ID, {
1060 defaultGroundTypeId: this.settings.defaultGroundTypeId
1061 })
1062 : null);
1063 }
1064
1065 listDimensionRecords ()
1066 {
1067 return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))];
1068 }
1069
1070 #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID)
1071 {
1072 const dim = normalizeDimensionId(dimensionId);
1073 for (let radius = 0; radius <= maxRadius; radius++)
1074 {
1075 for (let dy = -radius; dy <= radius; dy++)
1076 {
1077 for (let dx = -radius; dx <= radius; dx++)
1078 {
1079 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1080 { continue; }
1081 const tileX = originX + dx;
1082 const tileY = originY + dy;
1083 if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim))
1084 { return { tileX, tileY, dimensionId: dim }; }
1085 }
1086 }
1087 }
1088 return null;
1089 }
1090
1091 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1092 {
1093 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1094 if (!data.open)
1095 { return false; }
1096 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1097 }
1098
1099 debugWorld ()
1100 {
1101 const loaders = this.#allLoaders();
1102 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
1103 const simulatingChunks = [...chunkSim.entries()]
1104 .filter(([, count]) => count > 0)
1105 .map(([key]) => key)
1106 .sort();
1107 return {
1108 tickIndex: this.tickIndex,
1109 workerCount: this.workers.length,
1110 workerMode: this.workerMode,
1111 simulatingChunks,
1112 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
1113 ...parseRegionKey(key),
1114 workerId,
1115 state: REGION_RUNTIME_STATE.resident,
1116 refs: regionRes.get(key) ?? 0,
1117 graceUntil: this.regionGraceUntil.get(key) ?? null
1118 })),
1119 entities: [...this.directory.values()].map((entity) => ({
1120 entityId: entity.entityId,
1121 workerId: entity.workerId,
1122 tileX: entity.tileX,
1123 tileY: entity.tileY,
1124 characterId: entity.characterId
1125 }))
1126 };
1127 }
1128
1129 async shutdown ()
1130 {
1131 for (const characterId of [...this.characterEntities.keys()])
1132 { this.despawnCharacter(characterId); }
1133 this.forceUnloadAll();
1134 await Promise.all(this.workers.map((worker) => worker.terminate()));
1135 }
1136
1137 forceUnloadAll ()
1138 {
1139 for (const key of [...this.regionOwner.keys()])
1140 {
1141 const { regionX, regionY } = parseRegionKey(key);
1142 this.#unloadRegion(regionX, regionY);
1143 }
1144 }
1145
1146 #configureWorkers ()
1147 {
1148 for (const worker of this.workers)
1149 {
1150 worker.call({
1151 type: WorkerMessage.configure,
1152 settings: this.settings,
1153 activeRevisionId: this.activeRevisionId
1154 });
1155 }
1156 }
1157
1158 #routeCommand (item)
1159 {
1160 if (item.command.type === "respawn")
1161 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1162 const routedCharacterId = item.command.characterId | 0;
1163 if (routedCharacterId && this.stateDb.getCharacter(routedCharacterId)?.is_dead)
1164 {
1165 // Queued intents after death (drop/use/send/craft/…) are discarded.
1166 return [];
1167 }
1168 if (item.command.type === "enter-doorway")
1169 {
1170 return this.#relocateCharacterThroughDoorway(
1171 item.sessionId,
1172 item.command.characterId,
1173 item.command.tileX,
1174 item.command.tileY
1175 );
1176 }
1177 if (
1178 item.command.type === "open-market"
1179 || item.command.type === "place-market-sell"
1180 || item.command.type === "place-market-buy"
1181 || item.command.type === "cancel-market-order"
1182 || item.command.type === "close-market"
1183 )
1184 {
1185 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1186 return result?.events ?? [];
1187 }
1188 if (
1189 item.command.type === "open-bounty"
1190 || item.command.type === "raise-bounty"
1191 || item.command.type === "get-character-bounty"
1192 || item.command.type === "close-bounty"
1193 )
1194 {
1195 const result = this.bounty.handleCommand(item.sessionId, item.command);
1196 return result?.events ?? [];
1197 }
1198 if (
1199 item.command.type === "open-barber"
1200 || item.command.type === "set-hair"
1201 || item.command.type === "close-barber"
1202 )
1203 {
1204 const result = this.barber.handleCommand(item.sessionId, item.command);
1205 return result?.events ?? [];
1206 }
1207 if (
1208 item.command.type === "dialogue-choose"
1209 || item.command.type === "dialogue-advance"
1210 || item.command.type === "close-dialogue"
1211 || item.command.type === "request-quests"
1212 )
1213 { return this.#handleQuestCommand(item); }
1214 const entityId = this.characterEntities.get(item.command.characterId);
1215 const record = entityId ? this.directory.get(entityId) : null;
1216 if (!record)
1217 {
1218 const error = new Error("Character is not in the world.");
1219 error.userFacing = true;
1220 throw error;
1221 }
1222 if (item.command.type === "drop-item" && item.command.groundItemId == null)
1223 { item.command.groundItemId = this.nextGroundItemId++; }
1224 if (item.command.type === "attack")
1225 {
1226 const targetRecord = this.directory.get(item.command.targetEntityId);
1227 if (!targetRecord)
1228 {
1229 const error = new Error("Target is not here.");
1230 error.userFacing = true;
1231 throw error;
1232 }
1233 const events = this.#finishRoutedCommand(item, record);
1234 if (targetRecord.workerId !== record.workerId)
1235 {
1236 this.workers[targetRecord.workerId].call({
1237 type: WorkerMessage.remoteCombatEngage,
1238 attackerEntityId: record.entityId,
1239 targetEntityId: item.command.targetEntityId,
1240 now: item.receivedAt ?? this.now
1241 });
1242 }
1243 return events;
1244 }
1245 return this.#finishRoutedCommand(item, record);
1246 }
1247
1248 #finishRoutedCommand (item, record)
1249 {
1250 const result = this.workers[record.workerId].call({
1251 type: WorkerMessage.command,
1252 sessionId: item.sessionId,
1253 command: item.command,
1254 now: item.receivedAt ?? this.now
1255 });
1256 const view = this.workers[record.workerId].call({
1257 type: WorkerMessage.inspect,
1258 entityId: record.entityId
1259 });
1260 if (view)
1261 { this.#remember(view, record.workerId); }
1262 if (result?.private)
1263 { this.#saveBagFromView(item.command.characterId, result.private); }
1264 if (result?.appearanceChanged && view)
1265 { this.#queueReplication(replicationAppearance(view)); }
1266 if (result?.remainder)
1267 {
1268 this.stateDb.saveInheritance(
1269 this.stateDb.getCharacter(item.command.characterId).account_id,
1270 { slots: result.remainder }
1271 );
1272 }
1273 for (const event of result?.events ?? [])
1274 { this.#persistGroundEvent(event); }
1275 const events = [];
1276 for (const event of result?.events ?? [])
1277 {
1278 if (event.type === "skills-updated")
1279 {
1280 this.#applySkillsUpdated(event);
1281 events.push(...this.#skillLevelUpEvents(event));
1282 continue;
1283 }
1284 if (event.type === "spells-updated")
1285 {
1286 this.#applySpellsUpdated(event);
1287 continue;
1288 }
1289 if (event.type === "open-dialogue")
1290 {
1291 events.push(...this.#handleOpenDialogue(event));
1292 continue;
1293 }
1294 events.push(event);
1295 }
1296 if (item.command.type === "attack" && item.command.targetEntityId != null)
1297 {
1298 events.push(...this.#mapQuestPrivateEvents(
1299 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1300 ));
1301 }
1302 if (result?.private)
1303 {
1304 events.push({
1305 type: "inventory",
1306 sessionId: item.sessionId,
1307 bank: !!result.bank,
1308 cauldron: result.cauldron,
1309 cauldronState: result.cauldronState ?? null,
1310 alchemyResult: result.alchemyResult ?? null,
1311 dyeConfirm: result.dyeConfirm ?? null,
1312 ...result.private
1313 });
1314 }
1315 if (result?.statusEffectsChanged && view)
1316 {
1317 events.push({
1318 type: "status-effects",
1319 sessionId: item.sessionId,
1320 characterId: view.characterId ?? item.command.characterId,
1321 effects: view.statusEffects ?? [],
1322 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
1323 });
1324 }
1325 if (result?.healthChanged && view)
1326 {
1327 events.push({
1328 type: "entity-health",
1329 entityId: view.entityId,
1330 characterId: view.characterId ?? item.command.characterId,
1331 health: view.health,
1332 maxHealth: view.maxHealth,
1333 tileX: view.tileX,
1334 tileY: view.tileY
1335 });
1336 }
1337 return events;
1338 }
1339
1340 #applyRemoteMelee (payload)
1341 {
1342 const targetRecord = this.directory.get(payload.targetId);
1343 if (!targetRecord)
1344 { return []; }
1345 const result = this.workers[targetRecord.workerId].call({
1346 ...payload,
1347 type: WorkerMessage.applyRemoteMelee
1348 });
1349 const events = [];
1350 for (const event of result?.events ?? [])
1351 {
1352 if (event.type === "entity-despawn")
1353 { this.#forget(event.entityId); }
1354 if (event.type === "skills-updated")
1355 {
1356 this.#applySkillsUpdated(event);
1357 events.push(...this.#skillLevelUpEvents(event));
1358 continue;
1359 }
1360 if (event.type === "spells-updated")
1361 {
1362 this.#applySpellsUpdated(event);
1363 continue;
1364 }
1365 if (event.type === "player-died")
1366 {
1367 events.push(...this.#applyPlayerDeath(event));
1368 continue;
1369 }
1370 if (event.type === "mob-killed")
1371 {
1372 events.push(...this.#applyMobKilled(event));
1373 continue;
1374 }
1375 this.#persistGroundEvent(event);
1376 if (event.type !== "skills-updated")
1377 { events.push(event); }
1378 }
1379 for (const forward of result?.forwards ?? [])
1380 {
1381 if (forward.type !== "forward-combat-xp")
1382 { continue; }
1383 const attackerRecord = this.directory.get(forward.entityId);
1384 if (!attackerRecord)
1385 { continue; }
1386 const xpResult = this.workers[attackerRecord.workerId].call({
1387 type: WorkerMessage.applyCombatHitXp,
1388 entityId: forward.entityId,
1389 profile: forward.profile,
1390 damage: forward.damage
1391 });
1392 for (const xpEvent of xpResult?.events ?? [])
1393 {
1394 if (xpEvent.type === "skills-updated")
1395 {
1396 this.#applySkillsUpdated(xpEvent);
1397 events.push(...this.#skillLevelUpEvents(xpEvent));
1398 continue;
1399 }
1400 events.push(xpEvent);
1401 }
1402 }
1403 return events;
1404 }
1405
1406 #applyRemoteRanged (payload)
1407 {
1408 const targetRecord = this.directory.get(payload.targetId);
1409 if (!targetRecord)
1410 { return []; }
1411 const result = this.workers[targetRecord.workerId].call({
1412 ...payload,
1413 type: WorkerMessage.applyRemoteRanged
1414 });
1415 const events = [];
1416 for (const event of result?.events ?? [])
1417 {
1418 if (event.type === "entity-despawn")
1419 { this.#forget(event.entityId); }
1420 if (event.type === "skills-updated")
1421 {
1422 this.#applySkillsUpdated(event);
1423 events.push(...this.#skillLevelUpEvents(event));
1424 continue;
1425 }
1426 if (event.type === "spells-updated")
1427 {
1428 this.#applySpellsUpdated(event);
1429 continue;
1430 }
1431 if (event.type === "player-died")
1432 {
1433 events.push(...this.#applyPlayerDeath(event));
1434 continue;
1435 }
1436 if (event.type === "mob-killed")
1437 {
1438 events.push(...this.#applyMobKilled(event));
1439 continue;
1440 }
1441 this.#persistGroundEvent(event);
1442 if (event.type !== "skills-updated")
1443 { events.push(event); }
1444 }
1445 for (const forward of result?.forwards ?? [])
1446 {
1447 if (forward.type !== "forward-combat-xp")
1448 { continue; }
1449 const attackerRecord = this.directory.get(forward.entityId);
1450 if (!attackerRecord)
1451 { continue; }
1452 const xpResult = this.workers[attackerRecord.workerId].call({
1453 type: WorkerMessage.applyCombatHitXp,
1454 entityId: forward.entityId,
1455 profile: forward.profile,
1456 damage: forward.damage
1457 });
1458 for (const xpEvent of xpResult?.events ?? [])
1459 {
1460 if (xpEvent.type === "skills-updated")
1461 {
1462 this.#applySkillsUpdated(xpEvent);
1463 events.push(...this.#skillLevelUpEvents(xpEvent));
1464 continue;
1465 }
1466 events.push(xpEvent);
1467 }
1468 }
1469 return events;
1470 }
1471
1472 #handleQuestCommand (item)
1473 {
1474 const characterId = item.command.characterId | 0;
1475 const sessionId = item.sessionId;
1476 if (!this.quests)
1477 { return []; }
1478 if (item.command.type === "request-quests")
1479 {
1480 const snap = this.quests.questSnapshot(characterId);
1481 return [{ type: "quests-snapshot", sessionId, characterId, ...snap }];
1482 }
1483 if (item.command.type === "close-dialogue")
1484 {
1485 const closed = this.quests.closeDialogue(characterId, "client");
1486 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1487 }
1488 if (item.command.type === "dialogue-choose")
1489 {
1490 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1491 if (!result.ok)
1492 {
1493 const error = new Error(result.error || "Choice failed.");
1494 error.userFacing = true;
1495 throw error;
1496 }
1497 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1498 }
1499 if (item.command.type === "dialogue-advance")
1500 {
1501 const result = this.quests.advanceDialogue(characterId);
1502 if (!result.ok)
1503 {
1504 const error = new Error(result.error || "Cannot advance.");
1505 error.userFacing = true;
1506 throw error;
1507 }
1508 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1509 }
1510 return [];
1511 }
1512
1513 #handleOpenDialogue (event)
1514 {
1515 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1516 if (!result.ok)
1517 {
1518 return [{
1519 type: "toast",
1520 characterId: event.characterId,
1521 sessionId: event.sessionId,
1522 message: result.error || "Nothing to say."
1523 }];
1524 }
1525 this.#pinDialogueNpc(event.entityId, event.characterId);
1526 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
1527 }
1528
1529 #pinDialogueNpc (entityId, characterId)
1530 {
1531 const record = this.directory.get(entityId | 0);
1532 if (!record)
1533 { return; }
1534 this.workers[record.workerId]?.call?.({
1535 type: WorkerMessage.pinDialogue,
1536 entityId: entityId | 0,
1537 characterId: characterId | 0
1538 });
1539 }
1540
1541 #unpinDialogueNpc (entityId, characterId)
1542 {
1543 const record = this.directory.get(entityId | 0);
1544 if (!record)
1545 { return; }
1546 this.workers[record.workerId]?.call?.({
1547 type: WorkerMessage.unpinDialogue,
1548 entityId: entityId | 0,
1549 characterId: characterId | 0
1550 });
1551 }
1552
1553 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
1554 {
1555 const out = [];
1556 let needSnapshot = false;
1557 for (const event of events ?? [])
1558 {
1559 const cid = event.characterId ?? characterId;
1560 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1561 if (event.type === "dialogueStep")
1562 {
1563 out.push({
1564 type: "dialogue-step",
1565 sessionId: sid,
1566 characterId: cid,
1567 dialogueId: event.dialogueId,
1568 stepId: event.stepId,
1569 label: event.label,
1570 npcEntityId: event.npcEntityId,
1571 lines: event.lines
1572 });
1573 }
1574 else if (event.type === "dialogueChoices")
1575 {
1576 out.push({
1577 type: "dialogue-choices",
1578 sessionId: sid,
1579 characterId: cid,
1580 dialogueId: event.dialogueId,
1581 stepId: event.stepId,
1582 npcEntityId: event.npcEntityId,
1583 triggers: event.triggers
1584 });
1585 }
1586 else if (event.type === "dialogueItemRewards")
1587 {
1588 out.push({
1589 type: "dialogue-item-rewards",
1590 sessionId: sid,
1591 characterId: cid,
1592 dialogueId: event.dialogueId,
1593 stepId: event.stepId,
1594 npcEntityId: event.npcEntityId,
1595 messages: event.messages ?? []
1596 });
1597 }
1598 else if (event.type === "dialogueClose")
1599 {
1600 if (event.npcEntityId != null && cid != null)
1601 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
1602 out.push({
1603 type: "dialogue-close",
1604 sessionId: sid,
1605 characterId: cid,
1606 reason: event.reason
1607 });
1608 }
1609 else if (event.type === "questStepComplete")
1610 {
1611 out.push({
1612 type: "quest-step-complete",
1613 sessionId: sid,
1614 characterId: cid,
1615 questId: event.questId,
1616 title: event.title
1617 });
1618 needSnapshot = true;
1619 }
1620 else if (event.type === "questsDirty")
1621 { needSnapshot = true; }
1622 else if (event.type === "inventoryDirty" && cid != null)
1623 {
1624 const onlineId = this.characterEntities.get(cid | 0);
1625 if (onlineId)
1626 {
1627 const live = this.bagOf(onlineId);
1628 if (live)
1629 { this.pushInventory(cid, live); }
1630 }
1631 }
1632 }
1633 if (needSnapshot && characterId != null)
1634 {
1635 const snap = this.quests.questSnapshot(characterId);
1636 out.push({
1637 type: "quests-snapshot",
1638 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
1639 characterId,
1640 ...snap
1641 });
1642 }
1643 return out;
1644 }
1645
1646 #sessionIdForCharacter (characterId)
1647 {
1648 const entityId = this.characterEntities.get(characterId | 0);
1649 const record = entityId != null ? this.directory.get(entityId) : null;
1650 return record?.sessionId ?? null;
1651 }
1652
1653 #applyMobKilled (event)
1654 {
1655 const out = [event];
1656 const attackerRecord = this.directory.get(event.attackerId);
1657 const killerCharacterId = attackerRecord?.characterId ?? null;
1658 const killerPos = attackerRecord
1659 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1660 : null;
1661 if (killerCharacterId && this.quests)
1662 {
1663 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
1664 mobTypeId: event.mobTypeId,
1665 spawnerId: event.spawnerId
1666 })));
1667 }
1668 out.push(...this.#mapQuestPrivateEvents(
1669 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
1670 ));
1671 let bountyAwarded = 0;
1672 if (killerCharacterId && (event.bounty | 0) > 0)
1673 {
1674 bountyAwarded = event.bounty | 0;
1675 const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1676 this.refreshCharacterSkull(killerCharacterId);
1677 out.push({
1678 type: "toast",
1679 characterId: killerCharacterId,
1680 message: `Bounty +${bountyAwarded} (total ${total})`
1681 });
1682 }
1683
1684 if (killerCharacterId && killerPos)
1685 {
1686 if (bountyAwarded > 0)
1687 { this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }
1688 if (event.townGuard)
1689 { this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }
1690 }
1691 return out;
1692 }
1693
1694 /**
1695 * Send up to `count` town guards at the killer. Prefer idle guards.
1696 * When `spawnerId` is set, only that spawner's guards are used.
1697 */
1698 #dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)
1699 {
1700 const want = Math.max(0, count | 0);
1701 if (want <= 0 || targetEntityId == null || !killerPos)
1702 { return; }
1703 const candidates = [];
1704 for (const worker of this.workers)
1705 {
1706 const result = worker.call({
1707 type: WorkerMessage.listTownGuardsNear,
1708 tileX: killerPos.tileX,
1709 tileY: killerPos.tileY,
1710 spawnerId,
1711 limit: 32
1712 });
1713 for (const guard of result?.guards ?? [])
1714 { candidates.push(guard); }
1715 }
1716 candidates.sort((a, b) => Number(a.busy) - Number(b.busy));
1717 let sent = 0;
1718 for (const guard of candidates)
1719 {
1720 if (sent >= want)
1721 { break; }
1722 if (guard.entityId === targetEntityId)
1723 { continue; }
1724 const record = this.directory.get(guard.entityId);
1725 if (!record)
1726 { continue; }
1727 this.workers[record.workerId].call({
1728 type: WorkerMessage.engageTarget,
1729 attackerEntityId: guard.entityId,
1730 targetEntityId,
1731 now: this.now
1732 });
1733 sent += 1;
1734 }
1735 }
1736
1737 #applyPlayerDeath (event)
1738 {
1739 const record = this.directory.get(event.entityId);
1740 if (!record)
1741 { return [event]; }
1742 this.stateDb.setCharacterDead(event.characterId, true);
1743 this.stateDb.saveCharacterPosition(
1744 event.characterId,
1745 event.tileX,
1746 event.tileY,
1747 record.gait ?? GAIT.walk,
1748 record.dimensionId ?? OVERWORLD_ID
1749 );
1750 this.bounty?.settleKill(
1751 event.characterId,
1752 event.attackerId,
1753 event.tileX,
1754 event.tileY
1755 );
1756 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1757 const killerCharacterId = Number(attackerRecord?.characterId) || 0;
1758 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1759 { this.stateDb.addKillCounter(killerCharacterId, SKULL_KILL_BONUS, this.now); }
1760 const events = [event];
1761 const closedDialogue = this.quests?.closeDialogue(event.characterId, "death");
1762 if (closedDialogue?.events?.length)
1763 {
1764 events.push(...this.#mapQuestPrivateEvents(
1765 closedDialogue.events,
1766 event.sessionId,
1767 event.characterId
1768 ));
1769 }
1770 if (event.sessionId != null)
1771 {
1772 for (const commandType of ["cancel-craft", "cauldron-close"])
1773 {
1774 try
1775 {
1776 this.workers[record.workerId].call({
1777 type: WorkerMessage.command,
1778 sessionId: event.sessionId,
1779 command: { type: commandType, characterId: event.characterId },
1780 now: this.now
1781 });
1782 }
1783 catch
1784 { /* best-effort session cleanup */ }
1785 }
1786 }
1787 // Bounty is cleared instantly on non-friend PvP death; only kill-counter decays over time.
1788 const victimSkull = this.refreshCharacterSkull(event.characterId, { force: true });
1789 if (victimSkull)
1790 { events.push(victimSkull); }
1791 for (const worker of this.workers)
1792 {
1793 worker.call({
1794 type: WorkerMessage.clearCombat,
1795 entityId: event.entityId,
1796 targetEntityId: event.entityId
1797 });
1798 }
1799 const victimName = `${record.firstName ?? "someone"} ${record.lastName ?? ""}`.trim()
1800 || "someone";
1801 const killerName = `${attackerRecord?.firstName ?? ""} ${attackerRecord?.lastName ?? ""}`.trim()
1802 || "someone";
1803 const corpseOrigin = lootOrigin(victimName, killerName);
1804 const result = this.workers[record.workerId].call({
1805 type: WorkerMessage.spawnCorpseDrops,
1806 characterId: event.characterId,
1807 tileX: event.tileX,
1808 tileY: event.tileY,
1809 now: this.now,
1810 dropCarriedCoins: true,
1811 coinGroundItemId: this.nextGroundItemId++,
1812 drops: [
1813 {
1814 groundItemId: this.nextGroundItemId++,
1815 stack: attachOrigins({
1816 itemId: ItemId.bones,
1817 quantity: 1,
1818 origins: [{ origin: corpseOrigin, quantity: 1 }]
1819 })
1820 },
1821 {
1822 groundItemId: this.nextGroundItemId++,
1823 stack: attachOrigins({
1824 itemId: ItemId.skull,
1825 quantity: 1,
1826 origins: [{ origin: corpseOrigin, quantity: 1 }]
1827 })
1828 }
1829 ]
1830 });
1831 if (killerCharacterId && killerCharacterId !== (event.characterId | 0))
1832 {
1833 const skullEvent = this.refreshCharacterSkull(killerCharacterId, { force: true });
1834 if (skullEvent)
1835 { events.push(skullEvent); }
1836 }
1837 events.push({
1838 type: "entity-despawn",
1839 entityId: event.entityId,
1840 tileX: event.tileX,
1841 tileY: event.tileY
1842 });
1843 for (const dropEvent of result?.events ?? [])
1844 {
1845 this.#persistGroundEvent(dropEvent);
1846 events.push(dropEvent);
1847 }
1848 if (result?.private)
1849 {
1850 this.#saveBagFromView(event.characterId, result.private);
1851 if (event.sessionId != null)
1852 {
1853 events.push({
1854 type: "inventory",
1855 sessionId: event.sessionId,
1856 ...result.private
1857 });
1858 }
1859 }
1860 return events;
1861 }
1862
1863 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
1864 {
1865 const entityId = this.characterEntities.get(characterId);
1866 const record = entityId ? this.directory.get(entityId) : null;
1867 if (!record)
1868 {
1869 const error = new Error("Character is not in the world.");
1870 error.userFacing = true;
1871 throw error;
1872 }
1873 const tileX = doorwayTileX | 0;
1874 const tileY = doorwayTileY | 0;
1875 if (chebyshev(record.tileX, record.tileY, tileX, tileY) > 1)
1876 {
1877 const error = new Error("You are too far from that doorway.");
1878 error.userFacing = true;
1879 throw error;
1880 }
1881 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1882 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
1883 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
1884 if (block?.typeId !== BlockType.doorway)
1885 {
1886 const error = new Error("There is no doorway there.");
1887 error.userFacing = true;
1888 throw error;
1889 }
1890 const config = block.config && typeof block.config === "object" ? block.config : null;
1891 const targetRaw = config?.targetDimensionId;
1892 if (targetRaw == null || String(targetRaw).trim() === "")
1893 {
1894 const error = new Error("That doorway leads nowhere.");
1895 error.userFacing = true;
1896 throw error;
1897 }
1898 const targetDimensionId = normalizeDimensionId(targetRaw);
1899 const destTileX = Number(config.tileX);
1900 const destTileY = Number(config.tileY);
1901 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
1902 {
1903 const error = new Error("That doorway leads nowhere.");
1904 error.userFacing = true;
1905 throw error;
1906 }
1907 const destX = destTileX | 0;
1908 const destY = destTileY | 0;
1909 if (!this.#isDimensionUsable(targetDimensionId))
1910 {
1911 const error = new Error("That place is no longer reachable.");
1912 error.userFacing = true;
1913 throw error;
1914 }
1915 if (!this.isEnterable(destX, destY, targetDimensionId))
1916 {
1917 const error = new Error("The other side is blocked.");
1918 error.userFacing = true;
1919 throw error;
1920 }
1921
1922 const events = [];
1923 if (this.quests)
1924 {
1925 const closed = this.quests.closeDialogue(characterId, "doorway");
1926 if (closed?.events?.length)
1927 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
1928 }
1929
1930 const loader = { ...DEFAULT_CHUNK_LOADER };
1931 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
1932 const result = this.workers[record.workerId].call({
1933 type: WorkerMessage.relocateEntity,
1934 entityId,
1935 tileX: destX,
1936 tileY: destY,
1937 dimensionId: targetDimensionId
1938 });
1939 if (!result?.accepted)
1940 {
1941 const error = new Error("Could not enter that doorway.");
1942 error.userFacing = true;
1943 throw error;
1944 }
1945 let moveEvents = [];
1946 if (result.transferRequest)
1947 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1948 else if (result.event)
1949 {
1950 this.#applyMoveToDirectory(result.event);
1951 moveEvents = [result.event];
1952 const view = this.workers[record.workerId].call({
1953 type: WorkerMessage.inspect,
1954 entityId
1955 });
1956 if (view)
1957 { this.#remember(view, record.workerId); }
1958 }
1959 if (!moveEvents.length)
1960 {
1961 const error = new Error("Could not enter that doorway.");
1962 error.userFacing = true;
1963 throw error;
1964 }
1965 this.stateDb.saveCharacterPosition(
1966 characterId,
1967 destX,
1968 destY,
1969 record.gait ?? GAIT.walk,
1970 targetDimensionId
1971 );
1972 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
1973 this.#recalculateActivation(this.now);
1974 this.#syncGhosts();
1975 const dimRecord = this.getDimensionRecord(targetDimensionId);
1976 events.push(...moveEvents, {
1977 type: "dimension-changed",
1978 sessionId,
1979 characterId,
1980 entityId,
1981 dimensionId: targetDimensionId,
1982 tileX: destX,
1983 tileY: destY,
1984 lightingMode: dimRecord?.lightingMode ?? "dayNight",
1985 seasonMode: dimRecord?.seasonMode ?? "auto"
1986 });
1987 return events;
1988 }
1989
1990 #respawnCharacter (sessionId, characterId)
1991 {
1992 const row = this.stateDb.getCharacter(characterId);
1993 if (!row?.is_dead)
1994 {
1995 const error = new Error("You are not dead.");
1996 error.userFacing = true;
1997 throw error;
1998 }
1999 const entityId = this.characterEntities.get(characterId);
2000 const record = entityId ? this.directory.get(entityId) : null;
2001 if (!record)
2002 {
2003 const error = new Error("Character is not in the world.");
2004 error.userFacing = true;
2005 throw error;
2006 }
2007 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
2008 if (!destination)
2009 {
2010 const error = new Error("No open tile is available for respawn.");
2011 error.userFacing = true;
2012 throw error;
2013 }
2014 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2015 const loader = { ...DEFAULT_CHUNK_LOADER };
2016 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
2017 const result = this.workers[record.workerId].call({
2018 type: WorkerMessage.applyRespawn,
2019 entityId,
2020 sessionId,
2021 tileX: destination.tileX,
2022 tileY: destination.tileY,
2023 maxHealth: playerMaxHealth(skills),
2024 maxStamina: playerMaxStamina(skills)
2025 });
2026 if (!result?.accepted)
2027 {
2028 const error = new Error("That respawn tile is no longer available.");
2029 error.userFacing = true;
2030 throw error;
2031 }
2032 let moveEvents = [];
2033 if (result.transferRequest)
2034 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
2035 else if (result.event)
2036 {
2037 this.#applyMoveToDirectory(result.event);
2038 moveEvents = [result.event];
2039 const view = this.workers[record.workerId].call({
2040 type: WorkerMessage.inspect,
2041 entityId
2042 });
2043 if (view)
2044 { this.#remember(view, record.workerId); }
2045 }
2046 if (!moveEvents.length)
2047 {
2048 const error = new Error("Respawn transfer failed.");
2049 error.userFacing = true;
2050 throw error;
2051 }
2052 this.stateDb.setCharacterDead(characterId, false);
2053 const respawnHealth = playerMaxHealth(skills);
2054 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
2055 this.stateDb.saveCharacterPosition(
2056 characterId,
2057 destination.tileX,
2058 destination.tileY,
2059 record.gait ?? GAIT.walk,
2060 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
2061 );
2062 this.#recalculateActivation(this.now);
2063 this.#syncGhosts();
2064 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2065 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2066 const spawnView = this.workers[record.workerId].call({
2067 type: WorkerMessage.inspect,
2068 entityId
2069 });
2070 const spawn = spawnView
2071 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2072 : null;
2073 return [
2074 ...moveEvents,
2075 ...(spawn ? [spawn] : []),
2076 ...(skullEvent ? [skullEvent] : []),
2077 {
2078 type: "player-respawned",
2079 entityId,
2080 characterId,
2081 sessionId,
2082 tileX: destination.tileX,
2083 tileY: destination.tileY,
2084 health: playerMaxHealth(skills),
2085 maxHealth: playerMaxHealth(skills),
2086 stamina: playerMaxStamina(skills),
2087 maxStamina: playerMaxStamina(skills),
2088 skullValue: skullPoints
2089 }
2090 ];
2091 }
2092
2093 #refreshAltarIndex ()
2094 {
2095 const altars = [];
2096 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
2097 {
2098 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
2099 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
2100 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2101 {
2102 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2103 {
2104 const block = data.blocks[localY * CHUNK_SIZE + localX];
2105 if (block?.typeId !== BlockType.churchAltar)
2106 { continue; }
2107 altars.push({
2108 tileX: coord.chunk_x * CHUNK_SIZE + localX,
2109 tileY: coord.chunk_y * CHUNK_SIZE + localY,
2110 dimensionId: dim
2111 });
2112 }
2113 }
2114 }
2115 this.altarTiles = altars;
2116 }
2117
2118 #findRespawnDestination (originX, originY, entityId)
2119 {
2120 const record = this.directory.get(entityId);
2121 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2122 const ordered = [...this.altarTiles].sort((left, right) =>
2123 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2124 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2125 );
2126 for (const altar of ordered)
2127 {
2128 const adjacent = [];
2129 for (let dy = -1; dy <= 1; dy++)
2130 {
2131 for (let dx = -1; dx <= 1; dx++)
2132 {
2133 if (dx === 0 && dy === 0)
2134 { continue; }
2135 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
2136 }
2137 }
2138 adjacent.sort((left, right) =>
2139 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2140 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2141 );
2142 const tile = adjacent.find((entry) =>
2143 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2144 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2145 );
2146 if (tile)
2147 { return tile; }
2148 }
2149 for (let radius = 0; radius <= 24; radius++)
2150 {
2151 for (let dy = -radius; dy <= radius; dy++)
2152 {
2153 for (let dx = -radius; dx <= radius; dx++)
2154 {
2155 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2156 { continue; }
2157 const tileX = originX + dx;
2158 const tileY = originY + dy;
2159 if (this.isEnterable(tileX, tileY, dimensionId)
2160 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
2161 { return { tileX, tileY, dimensionId }; }
2162 }
2163 }
2164 }
2165 return this.findOpenSpawn();
2166 }
2167
2168 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2169 {
2170 const dim = normalizeDimensionId(dimensionId);
2171 for (const record of this.directory.values())
2172 {
2173 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2174 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2175 { return true; }
2176 }
2177 return false;
2178 }
2179
2180 #recalculateActivation (now)
2181 {
2182 const loaders = this.#allLoaders();
2183 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
2184
2185 for (const [key, count] of regionRes)
2186 {
2187 if (count <= 0)
2188 { continue; }
2189 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2190 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
2191 this.regionGraceUntil.delete(key);
2192 }
2193
2194 for (const [key] of [...this.regionOwner.entries()])
2195 {
2196 if ((regionRes.get(key) ?? 0) > 0)
2197 { continue; }
2198 if (!this.regionGraceUntil.has(key))
2199 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
2200 if (now >= this.regionGraceUntil.get(key))
2201 {
2202 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2203 this.#unloadRegion(regionX, regionY, dimensionId);
2204 }
2205 }
2206
2207 for (const [workerId, worker] of this.workers.entries())
2208 {
2209 const chunkKeys = [];
2210 for (const [key, count] of chunkSim)
2211 {
2212 if (count <= 0)
2213 { continue; }
2214 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2215 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
2216 { chunkKeys.push(key); }
2217 }
2218 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2219 }
2220 this.#syncAllReplicas();
2221
2222 const nextSimulating = new Set();
2223 for (const [key, count] of chunkSim)
2224 {
2225 if (count > 0)
2226 { nextSimulating.add(key); }
2227 }
2228 let preheated = false;
2229 for (const key of nextSimulating)
2230 {
2231 if (!this.simulatingChunkKeys.has(key))
2232 {
2233 preheated = true;
2234 break;
2235 }
2236 }
2237 this.simulatingChunkKeys = nextSimulating;
2238 if (preheated)
2239 { this.#stepSpawners(); }
2240 }
2241
2242 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
2243 {
2244 const dim = normalizeDimensionId(dimensionId);
2245 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2246 let preferred = this.#ownerOfTile(tileX, tileY, dim);
2247 for (const region of coverage.residentRegions)
2248 {
2249 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
2250 if (preferred == null)
2251 { preferred = owner; }
2252 }
2253 }
2254
2255 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2256 {
2257 const dim = normalizeDimensionId(dimensionId);
2258 const key = regionKey(regionX, regionY, dim);
2259 if (this.regionOwner.has(key))
2260 { return this.regionOwner.get(key); }
2261 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
2262 this.workers[workerId].call({
2263 type: WorkerMessage.assignRegion,
2264 regionX,
2265 regionY,
2266 dimensionId: dim,
2267 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
2268 });
2269 this.regionOwner.set(key, workerId);
2270 this.#restorePersistent(regionX, regionY, workerId);
2271 this.#restoreGroundItems(regionX, regionY, workerId);
2272 return workerId;
2273 }
2274
2275 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2276 {
2277 const dim = normalizeDimensionId(dimensionId);
2278 const key = regionKey(regionX, regionY, dim);
2279 const workerId = this.regionOwner.get(key);
2280 if (workerId == null)
2281 { return; }
2282 const bounds = regionTileBounds(regionX, regionY);
2283 const { dropped, groundItems } = this.workers[workerId].call({
2284 type: WorkerMessage.dropRegion,
2285 regionX,
2286 regionY,
2287 dimensionId: dim
2288 });
2289 const persistent = [];
2290 for (const record of dropped ?? [])
2291 {
2292 if (record.characterId)
2293 {
2294 this.stateDb.saveCharacterPosition(
2295 record.characterId,
2296 record.tileX,
2297 record.tileY,
2298 record.gait ?? GAIT.walk,
2299 record.dimensionId ?? OVERWORLD_ID
2300 );
2301 }
2302 if (record.persistent)
2303 { persistent.push(record); }
2304 this.#forget(record.entityId);
2305 }
2306 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
2307 for (const item of groundItems ?? [])
2308 { this.stateDb.upsertGroundItem(item); }
2309 this.regionOwner.delete(key);
2310 this.regionGraceUntil.delete(key);
2311 }
2312
2313 #restorePersistent (regionX, regionY, workerId)
2314 {
2315 const bounds = regionTileBounds(regionX, regionY);
2316 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
2317 for (const row of rows)
2318 {
2319 if (this.directory.has(row.entity_id))
2320 { continue; }
2321 const components = JSON.parse(row.components_blob);
2322 const view = this.workers[workerId].call({
2323 type: WorkerMessage.spawn,
2324 entityId: row.entity_id,
2325 components
2326 });
2327 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
2328 this.#remember(view, workerId);
2329 }
2330 }
2331
2332 #applyTransfers (requests)
2333 {
2334 const events = [];
2335 for (const request of requests)
2336 {
2337 const destWorkerId = this.#ensureRegion(
2338 request.toRegionX,
2339 request.toRegionY,
2340 request.fromWorkerId,
2341 request.dimensionId ?? OVERWORLD_ID
2342 );
2343 if (destWorkerId === request.fromWorkerId)
2344 {
2345 this.workers[request.fromWorkerId].call({
2346 type: WorkerMessage.abortTransfer,
2347 entityId: request.entityId
2348 });
2349 continue;
2350 }
2351 let result;
2352 try
2353 {
2354 result = this.workers[destWorkerId].call({
2355 type: WorkerMessage.applyTransfer,
2356 payload: request.payload,
2357 destTileX: request.destTileX,
2358 destTileY: request.destTileY,
2359 dimensionId: request.dimensionId ?? OVERWORLD_ID
2360 });
2361 }
2362 catch
2363 {
2364 result = { accepted: false };
2365 }
2366 if (!result?.accepted)
2367 {
2368 this.workers[request.fromWorkerId].call({
2369 type: WorkerMessage.abortTransfer,
2370 entityId: request.entityId
2371 });
2372 continue;
2373 }
2374 this.workers[request.fromWorkerId].call({
2375 type: WorkerMessage.commitTransfer,
2376 entityId: request.entityId
2377 });
2378 this.#remember(result.entity, destWorkerId);
2379 events.push({
2380 type: "entity-move",
2381 entityId: request.entityId,
2382 fromTileX: request.fromTileX,
2383 fromTileY: request.fromTileY,
2384 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
2385 tileX: result.entity.tileX,
2386 tileY: result.entity.tileY,
2387 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
2388 gait: result.entity.gait
2389 });
2390 }
2391 return events;
2392 }
2393
2394 #syncAllReplicas ()
2395 {
2396 for (const [workerId, worker] of this.workers.entries())
2397 {
2398 const ownedKeys = new Set();
2399 for (const [key, owner] of this.regionOwner)
2400 {
2401 if (owner !== workerId)
2402 { continue; }
2403 const { regionX, regionY, dimensionId } = parseRegionKey(key);
2404 for (const chunk of chunksInRegion(regionX, regionY))
2405 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
2406 }
2407 const replicas = [];
2408 for (const key of replicaNeededForOwnedChunks(ownedKeys))
2409 {
2410 if (ownedKeys.has(key))
2411 { continue; }
2412 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2413 replicas.push({
2414 chunkX,
2415 chunkY,
2416 dimensionId,
2417 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
2418 });
2419 }
2420 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
2421 }
2422 }
2423
2424 #syncGhosts ()
2425 {
2426 const entities = [];
2427 for (const worker of this.workers)
2428 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
2429 for (const [workerId, worker] of this.workers.entries())
2430 {
2431 const ghosts = entities.filter((entity) =>
2432 {
2433 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
2434 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
2435 { return false; }
2436 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
2437 });
2438 worker.call({ type: WorkerMessage.setGhosts, ghosts });
2439 }
2440 }
2441
2442 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
2443 {
2444 const dim = normalizeDimensionId(dimensionId);
2445 const chunkX = tileToChunk(tileX);
2446 const chunkY = tileToChunk(tileY);
2447 for (const [key, owner] of this.regionOwner)
2448 {
2449 if (owner !== workerId)
2450 { continue; }
2451 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
2452 if (regionDim !== dim)
2453 { continue; }
2454 for (const chunk of chunksInRegion(regionX, regionY))
2455 {
2456 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
2457 { return true; }
2458 }
2459 }
2460 return false;
2461 }
2462
2463 #allLoaders ()
2464 {
2465 const loaders = [];
2466 for (const worker of this.workers)
2467 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
2468 return loaders;
2469 }
2470
2471 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
2472 {
2473 const dim = normalizeDimensionId(dimensionId);
2474 const votes = new Map();
2475 for (const loader of loaders)
2476 {
2477 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
2478 if (loaderDim !== dim)
2479 { continue; }
2480 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
2481 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
2482 { continue; }
2483 const record = this.directory.get(loader.entityId);
2484 if (record?.workerId == null)
2485 { continue; }
2486 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
2487 }
2488 let best = null;
2489 let bestVotes = -1;
2490 for (const [workerId, count] of votes)
2491 {
2492 if (count > bestVotes)
2493 {
2494 best = workerId;
2495 bestVotes = count;
2496 }
2497 }
2498 return best;
2499 }
2500
2501 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
2502 {
2503 const dim = normalizeDimensionId(dimensionId);
2504 const pinned = this.pinRegion?.(regionX, regionY, dim);
2505 if (pinned != null)
2506 { return pinned; }
2507
2508 const neighborOwners = [];
2509 for (let dy = -1; dy <= 1; dy++)
2510 {
2511 for (let dx = -1; dx <= 1; dx++)
2512 {
2513 if (dx === 0 && dy === 0)
2514 { continue; }
2515 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
2516 if (owner != null)
2517 { neighborOwners.push(owner); }
2518 }
2519 }
2520
2521 const scores = this.workers.map((_, workerId) => ({
2522 workerId,
2523 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
2524 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
2525 }));
2526
2527 if (preferredWorkerId != null && scores[preferredWorkerId])
2528 {
2529 const preferred = scores[preferredWorkerId];
2530 if (preferred.neighbors > 0 || neighborOwners.length === 0)
2531 { return preferredWorkerId; }
2532 }
2533
2534 scores.sort((left, right) =>
2535 right.neighbors - left.neighbors
2536 || left.load - right.load
2537 || left.workerId - right.workerId
2538 );
2539 return scores[0].workerId;
2540 }
2541
2542 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2543 {
2544 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
2545 }
2546
2547 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2548 {
2549 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
2550 }
2551
2552 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
2553 {
2554 const dim = normalizeDimensionId(dimensionId);
2555 return chunksInRegion(regionX, regionY).map((coord) => ({
2556 chunkX: coord.chunkX,
2557 chunkY: coord.chunkY,
2558 dimensionId: dim,
2559 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
2560 }));
2561 }
2562
2563 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2564 {
2565 const dim = normalizeDimensionId(dimensionId);
2566 const key = chunkKey(chunkX, chunkY, dim);
2567 if (this.authoredCache.has(key))
2568 { return this.authoredCache.get(key); }
2569 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
2570 const dimRecord = this.getDimensionRecord(dim);
2571 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
2572 const data = row
2573 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
2574 : createEmptyChunkData(defaultGroundTypeId);
2575 this.authoredCache.set(key, data);
2576 return data;
2577 }
2578
2579 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2580 {
2581 const dim = normalizeDimensionId(dimensionId);
2582 const data = this.#authoredChunk(chunkX, chunkY, dim);
2583 return {
2584 chunkX,
2585 chunkY,
2586 dimensionId: dim,
2587 open: data.open,
2588 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
2589 grounds: data.grounds,
2590 blocks: data.blocks,
2591 light: data.light,
2592 entities: [],
2593 groundItems: []
2594 };
2595 }
2596
2597 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
2598 {
2599 const dim = normalizeDimensionId(dimensionId);
2600 for (const record of this.directory.values())
2601 {
2602 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2603 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
2604 { return record.entityId; }
2605 }
2606 return null;
2607 }
2608
2609 #queueReplication (event)
2610 {
2611 if (event)
2612 { this.replication.push(event); }
2613 }
2614
2615 #stepSpawners ()
2616 {
2617 const events = [];
2618 for (const worker of this.workers)
2619 {
2620 const result = worker.call({ type: WorkerMessage.stepSpawners });
2621 for (const request of result?.spawnRequests ?? [])
2622 {
2623 try
2624 {
2625 this.spawnEntity(mobComponents(request), { requireResident: true });
2626 }
2627 catch
2628 { continue; }
2629 }
2630 }
2631 return events;
2632 }
2633
2634 #restoreGroundItems (regionX, regionY, workerId)
2635 {
2636 const bounds = regionTileBounds(regionX, regionY);
2637 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
2638 .filter((item) => item.expiresAt > this.now);
2639 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
2640 this.workers[workerId].call({
2641 type: WorkerMessage.setGroundItems,
2642 regionX,
2643 regionY,
2644 items
2645 });
2646 }
2647
2648 #persistGroundEvent (event)
2649 {
2650 if (event.type === "ground-item-appear")
2651 {
2652 this.stateDb.upsertGroundItem({
2653 groundItemId: event.groundItemId,
2654 tileX: event.tileX,
2655 tileY: event.tileY,
2656 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
2657 droppedAt: event.droppedAt ?? this.now,
2658 expiresAt: event.expiresAt,
2659 source: event.source ?? "player-drop",
2660 droppedByCharacterId: event.droppedByCharacterId ?? null
2661 });
2662 }
2663 if (event.type === "ground-item-despawn")
2664 { this.stateDb.deleteGroundItem(event.groundItemId); }
2665 }
2666
2667 #saveBag (entityId, workerId)
2668 {
2669 const record = this.directory.get(entityId);
2670 const bag = this.workers[workerId].call({
2671 type: WorkerMessage.inspectBag,
2672 entityId
2673 });
2674 if (!bag || !record?.characterId)
2675 { return; }
2676 this.#saveBagFromView(record.characterId, bag);
2677 const skills = this.workers[workerId].call({
2678 type: WorkerMessage.inspectSkills,
2679 entityId
2680 });
2681 if (skills)
2682 { this.stateDb.saveSkills(record.characterId, skills); }
2683 }
2684
2685 #applySkillsUpdated (event)
2686 {
2687 if (!event?.characterId || !event.stored)
2688 { return; }
2689 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
2690 this.pushSkills(event.characterId, event.skills ?? []);
2691 }
2692
2693 #applySpellsUpdated (event)
2694 {
2695 if (!event?.characterId || !event.stored)
2696 { return; }
2697 this.stateDb.saveSpells(event.characterId, event.stored);
2698 this.pushSpells(event.characterId, {
2699 spells: event.spells ?? [],
2700 autoCast: !!event.autoCast
2701 });
2702 }
2703
2704 #applySummonEntity (event)
2705 {
2706 const components = shadeSummonComponents({
2707 tileX: event.tileX | 0,
2708 tileY: event.tileY | 0,
2709 level: event.level | 0 || 1,
2710 ownerEntityId: event.ownerEntityId,
2711 expiresAt: event.expiresAt,
2712 dimensionId: event.dimensionId
2713 });
2714 try
2715 {
2716 const entityId = this.spawnEntity(components, { requireResident: true });
2717 if (entityId == null)
2718 { return []; }
2719 return [];
2720 }
2721 catch
2722 {
2723 return [];
2724 }
2725 }
2726
2727 #skillLevelUpEvents (event)
2728 {
2729 const levelUps = event?.levelUps ?? [];
2730 if (!levelUps.length)
2731 { return []; }
2732 const entityId = event.entityId ?? this.characterEntities.get(event.characterId);
2733 if (entityId == null)
2734 { return []; }
2735 const record = this.directory.get(entityId);
2736 const tileX = record?.tileX ?? 0;
2737 const tileY = record?.tileY ?? 0;
2738 return levelUps.map((levelUp) => ({
2739 type: "skill-level-up",
2740 entityId,
2741 characterId: event.characterId,
2742 tileX,
2743 tileY,
2744 skillId: levelUp.skillId,
2745 level: levelUp.level,
2746 previousLevel: levelUp.previousLevel,
2747 displayName: levelUp.displayName,
2748 icon: levelUp.icon
2749 }));
2750 }
2751
2752 #saveBagFromView (characterId, bag)
2753 {
2754 this.stateDb.saveBag(characterId, {
2755 inventory: bag.inventory,
2756 equipment: bag.equipment,
2757 vault: bag.vault,
2758 vaultReserved: bag.vaultReserved
2759 });
2760 }
2761
2762 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
2763 {
2764 const onlineId = this.characterEntities.get(issuerCharacterId);
2765 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2766 if (!bag)
2767 { return { ok: false, error: "Issuer vault not found." }; }
2768 const reserved = [...(bag.vaultReserved ?? [])];
2769 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
2770 if (index < 0)
2771 { return { ok: false, error: "That cheque cannot be redeemed." }; }
2772 const [stack] = reserved.splice(index, 1);
2773 bag.vaultReserved = reserved;
2774 this.stateDb.saveBag(issuerCharacterId, bag);
2775 if (onlineId)
2776 {
2777 this.applyBag(onlineId, bag);
2778 this.pushInventory(issuerCharacterId, bag);
2779 }
2780 return { ok: true, stack };
2781 }
2782
2783 restoreChequeReservation (issuerCharacterId, stack)
2784 {
2785 const onlineId = this.characterEntities.get(issuerCharacterId);
2786 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
2787 if (!bag)
2788 { return; }
2789 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
2790 this.stateDb.saveBag(issuerCharacterId, bag);
2791 if (onlineId)
2792 {
2793 this.applyBag(onlineId, bag);
2794 this.pushInventory(issuerCharacterId, bag);
2795 }
2796 }
2797
2798 #remember (view, workerId)
2799 {
2800 if (!view)
2801 { return; }
2802 const previous = this.directory.get(view.entityId);
2803 this.directory.set(view.entityId, {
2804 ...view,
2805 workerId,
2806 // Keep simulation-only fields that publicEntityView does not carry.
2807 skullValue: previous?.skullValue ?? view.skullValue ?? 0
2808 });
2809 if (view.characterId)
2810 { this.characterEntities.set(view.characterId, view.entityId); }
2811 }
2812
2813 #applyMoveToDirectory (event)
2814 {
2815 const record = this.directory.get(event.entityId);
2816 if (!record)
2817 { return; }
2818 record.tileX = event.tileX;
2819 record.tileY = event.tileY;
2820 record.gait = event.gait;
2821 if (event.dimensionId != null)
2822 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
2823 if (event.worldX != null)
2824 { record.worldX = event.worldX; }
2825 if (event.worldY != null)
2826 { record.worldY = event.worldY; }
2827 if (event.freeFlight != null)
2828 { record.freeFlight = !!event.freeFlight; }
2829 }
2830
2831 #forget (entityId)
2832 {
2833 const record = this.directory.get(entityId);
2834 if (record?.characterId)
2835 { this.characterEntities.delete(record.characterId); }
2836 this.directory.delete(entityId);
2837 }
2838}