BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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