BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 75.2 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3import {
4 chunkKey,
5 chunkToRegion,
6 parseChunkKey,
7 regionKey,
8 tileKey,
9 tileToChunk,
10 tileToLocal,
11 tileToRegion,
12 tileIndex
13} from "../world/coordinates.js";
14import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
15import { closedNeighborEdges } from "../world/chunkFlags.js";
16import { EcsWorld } from "../ecs/world.js";
17import { Component } from "../ecs/components.js";
18import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20import { WorkerMessage } from "./protocol.js";
21import { collectSpawnRequests } from "./spawners.js";
22import { mobDefinition } from "../../../shared/definitions/mobs.js";
23import {
24 bagView,
25 applyBagView,
26 addGroundItem,
27 expireGroundItems,
28 groundItemsInChunk,
29 groundItemsInRegion,
30 handleItemCommand,
31 removeGroundItem,
32 publicGroundItem,
33 setGroundItemsForRegion,
34 stripCarriedCoinsForDeath
35} from "../items/bags.js";
36import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
37import { stepSummons } from "../spells/summons.js";
38import { stepJadeiteFairies } from "../spells/jadeiteFairy.js";
39import {
40 handleJewelryTeleportCommand,
41 stepJewelryTeleports,
42 cancelJewelryTeleport
43} from "../equipment/jewelryTeleport.js";
44import { publicSpellsView } from "../../../shared/spells/state.js";
45import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
46import {
47 handleGatherCommand,
48 stepGather,
49 cancelGather,
50 clearOreRespawnsForChunk,
51 clearTreeRespawnsForChunk,
52 clearPlantRespawnsForChunk
53} from "../gathering/service.js";
54import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
55import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
56import { handleFishingCommand, stepFishing } from "../fishing/service.js";
57import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
58import { handleAlchemyCommand } from "../alchemy/service.js";
59import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
60import {
61 applyRemoteMeleeSwing,
62 applyRemoteRangedShot,
63 attackProfileOf,
64 clearEngage,
65 engageTarget,
66 ensureMobCombat,
67 isUntargetable,
68 queueMeleeApproach,
69 queueStandInRangeApproach,
70 resolveCombatTarget,
71 silenceDeadPlayer,
72 stepAggression,
73 stepCombat,
74 stepPassiveHealthRegen,
75 chebyshev
76} from "../combat/service.js";
77import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
78import { SkillId } from "../../../shared/definitions/skills.js";
79import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
80import { passiveStaminaRegenMultiplier, dropAmuletInsteadOfCoins } from "../../../shared/equipment/jewelryEffects.js";
81import { JewelryItemId } from "../../../shared/definitions/jewelryItems.js";
82import { EQUIPMENT_SLOT } from "../../../shared/definitions/items.js";
83import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js";
84import {
85 STAMINA_REGEN_PER_SECOND,
86 STAMINA_XP_PER_POINT_SPENT,
87 staminaCostPerRunStep,
88 publicStaminaView
89} from "../../../shared/stamina/rules.js";
90import {
91 stepCostForGround,
92 PATH_GROUND_STEP_COST,
93 SOFT_OCCUPIED_DWELL_MS
94} from "../../../shared/navigation/pathGround.js";
95import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
96import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
97import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
98import { stepStatusEffects } from "../statusEffects/service.js";
99import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js";
100
101export class WorkerWorld
102{
103 constructor (workerId)
104 {
105 this.workerId = workerId;
106 this.ecs = new EcsWorld();
107 this.chunks = new Map();
108 this.ownedRegions = new Set();
109 this.occupancy = new Map();
110 this.ghosts = new Map();
111 this.ghostOccupancy = new Map();
112 this.characterEntities = new Map();
113 this.frozen = new Set();
114 this.groundItems = new Map();
115 this.groundByTile = new Map();
116 this.oreRespawns = new Map();
117 this.treeRespawns = new Map();
118 this.campfireExpires = new Map();
119 this.fireSessions = new Map();
120 this.fishingSpotRespawns = new Map();
121 this.fishSessions = new Map();
122 this.pendingSpellImpacts = [];
123 this.jadeiteFairyTimers = new Map();
124 this.jewelryTeleportSessions = new Map();
125 this.settings = { ...DEFAULT_WORLD_SETTINGS };
126 this.activeRevisionId = 1;
127 }
128
129 handle (message)
130 {
131 switch (message.type)
132 {
133 case WorkerMessage.configure:
134 return this.#configure(message);
135 case WorkerMessage.assignRegion:
136 return this.#assignRegion(message);
137 case WorkerMessage.dropRegion:
138 return this.#dropRegion(message);
139 case WorkerMessage.replaceRegionChunks:
140 return this.#replaceRegionChunks(message);
141 case WorkerMessage.setReplicas:
142 return this.#setReplicas(message);
143 case WorkerMessage.setSimulatingChunks:
144 return this.#setSimulatingChunks(message);
145 case WorkerMessage.setGhosts:
146 return this.#setGhosts(message);
147 case WorkerMessage.spawn:
148 return this.#spawn(message);
149 case WorkerMessage.despawn:
150 return this.#despawn(message.entityId);
151 case WorkerMessage.despawnCharacter:
152 return this.#despawnCharacter(message.characterId);
153 case WorkerMessage.reattachSession:
154 return this.#reattachSession(message.characterId, message.sessionId);
155 case WorkerMessage.command:
156 return this.#command(message);
157 case WorkerMessage.stepMovement:
158 return this.#stepMovement(message.now);
159 case WorkerMessage.stepSystems:
160 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
161 case WorkerMessage.stepSpawners:
162 return { spawnRequests: collectSpawnRequests(this, Date.now()) };
163 case WorkerMessage.setGroundItems:
164 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
165 return { ok: true };
166 case WorkerMessage.inspectBag:
167 return this.#inspectBag(message.entityId);
168 case WorkerMessage.inspectSkills:
169 return this.#inspectSkills(message.entityId);
170 case WorkerMessage.inspectSpells:
171 return this.#inspectSpells(message.entityId);
172 case WorkerMessage.inspectStamina:
173 return this.#inspectStamina(message.entityId);
174 case WorkerMessage.applyBag:
175 return this.#applyBag(message.entityId, message.bag);
176 case WorkerMessage.applyAppearance:
177 return this.#applyAppearance(message.entityId, message.appearance);
178 case WorkerMessage.engageTarget:
179 return this.#engageTargetMessage(message);
180 case WorkerMessage.listTownGuardsNear:
181 return this.#listTownGuardsNear(message);
182 case WorkerMessage.updateFlight:
183 return this.#updateFlight(message.entityId, message.flight, message.now);
184 case WorkerMessage.chunkIsSimulating:
185 return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId);
186 case WorkerMessage.applyTransfer:
187 return this.#applyTransfer(message);
188 case WorkerMessage.commitTransfer:
189 return this.#commitTransfer(message.entityId);
190 case WorkerMessage.abortTransfer:
191 return this.#abortTransfer(message.entityId);
192 case WorkerMessage.snapshotChunk:
193 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId);
194 case WorkerMessage.listLoaders:
195 return this.#listLoaders();
196 case WorkerMessage.listPublicEntities:
197 return this.#listPublicEntities();
198 case WorkerMessage.entitiesInRegion:
199 return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId);
200 case WorkerMessage.inspect:
201 return publicEntityView(this.ecs, message.entityId);
202 case WorkerMessage.remoteCombatEngage:
203 return this.#remoteCombatEngage(message);
204 case WorkerMessage.applyRemoteMelee:
205 return this.#applyRemoteMelee(message);
206 case WorkerMessage.applyRemoteRanged:
207 return this.#applyRemoteRanged(message);
208 case WorkerMessage.applyCombatHitXp:
209 return this.#applyCombatHitXp(message);
210 case WorkerMessage.spawnCorpseDrops:
211 return this.#spawnCorpseDrops(message);
212 case WorkerMessage.applyRespawn:
213 return this.#applyRespawn(message);
214 case WorkerMessage.relocateEntity:
215 return this.#relocateEntity(message);
216 case WorkerMessage.clearCombat:
217 {
218 clearEngage(this.ecs, message.entityId);
219 const handle = this.ecs.handleOf(message.entityId);
220 if (handle != null)
221 {
222 silenceDeadPlayer(this.ecs, handle);
223 cancelGather(this.ecs, handle);
224 clearFollow(this.ecs, message.entityId);
225 }
226 for (const entity of this.ecs.query(Component.combat))
227 {
228 if (entity.combat.targetEntityId === message.targetEntityId)
229 { entity.combat.targetEntityId = null; }
230 }
231 return { ok: true };
232 }
233 case WorkerMessage.setItemLastSales:
234 {
235 this.itemLastSales = new Map();
236 for (const [key, sale] of Object.entries(message.sales ?? {}))
237 { this.itemLastSales.set(Number(key), sale); }
238 return { ok: true };
239 }
240 case WorkerMessage.stationExchangeClerk:
241 return this.#stationExchangeClerk(message);
242 case WorkerMessage.releaseExchangeClerk:
243 return this.#releaseExchangeClerk(message);
244 case WorkerMessage.pinDialogue:
245 return this.#pinDialogue(message.entityId, message.characterId);
246 case WorkerMessage.unpinDialogue:
247 return this.#unpinDialogue(message.entityId, message.characterId);
248 default:
249 throw new Error(`Unknown worker message ${message.type}`);
250 }
251 }
252
253 ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
254 {
255 return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId));
256 }
257
258 requireOwnedEntity (sessionId, characterId)
259 {
260 return this.#requireOwnedEntity(sessionId, characterId);
261 }
262
263 chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
264 {
265 return this.#chunkData(chunkX, chunkY, dimensionId);
266 }
267
268 #configure (message)
269 {
270 if (message.settings)
271 { this.settings = { ...this.settings, ...message.settings }; }
272 if (message.activeRevisionId != null)
273 { this.activeRevisionId = message.activeRevisionId; }
274 return { ok: true };
275 }
276
277 #assignRegion (message)
278 {
279 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
280 this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim));
281 for (const chunk of message.chunks ?? [])
282 {
283 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
284 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
285 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
286 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
287 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
288 data: cloneChunkData(chunk.data),
289 simulating: false,
290 replica: false,
291 dimensionId: chunkDim
292 });
293 }
294 return { ok: true };
295 }
296
297 #replaceRegionChunks (message)
298 {
299 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
300 for (const chunk of message.chunks ?? [])
301 {
302 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
303 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
304 const existing = this.chunks.get(key);
305 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
306 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
307 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
308 this.chunks.set(key, {
309 data: cloneChunkData(chunk.data),
310 simulating: existing?.simulating ?? false,
311 replica: existing?.replica ?? false,
312 dimensionId: chunkDim
313 });
314 }
315 return { ok: true };
316 }
317
318 #dropRegion (message)
319 {
320 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
321 const dropped = [];
322 for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim))
323 {
324 const components = record.payload?.components;
325 if (components?.creature && !components?.character && components?.health)
326 { components.health.current = components.health.max; }
327 dropped.push(record);
328 this.#destroyEntity(record.entityId);
329 }
330 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
331 for (const item of groundItems)
332 { removeGroundItem(this, item.groundItemId); }
333 for (const [key, chunk] of [...this.chunks.entries()])
334 {
335 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
336 if (chunk.replica)
337 { continue; }
338 if (dimensionId !== dim)
339 { continue; }
340 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
341 {
342 clearOreRespawnsForChunk(this, chunkX, chunkY);
343 clearTreeRespawnsForChunk(this, chunkX, chunkY);
344 clearPlantRespawnsForChunk(this, chunkX, chunkY);
345 this.chunks.delete(key);
346 }
347 }
348 this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim));
349 return { dropped, groundItems };
350 }
351
352 #setReplicas (message)
353 {
354 const keep = new Set();
355 for (const chunk of message.chunks ?? [])
356 {
357 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID);
358 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
359 keep.add(key);
360 const existing = this.chunks.get(key);
361 if (existing && !existing.replica)
362 { continue; }
363 this.chunks.set(key, {
364 data: cloneChunkData(chunk.data),
365 simulating: false,
366 replica: true,
367 dimensionId: chunkDim
368 });
369 }
370 for (const [key, chunk] of [...this.chunks.entries()])
371 {
372 if (chunk.replica && !keep.has(key))
373 { this.chunks.delete(key); }
374 }
375 return { ok: true };
376 }
377
378 #setSimulatingChunks (message)
379 {
380 const simulating = new Set(message.chunkKeys ?? []);
381 for (const [key, chunk] of this.chunks)
382 {
383 if (chunk.replica)
384 {
385 chunk.simulating = false;
386 continue;
387 }
388 chunk.simulating = simulating.has(key);
389 }
390 return { ok: true };
391 }
392
393 #setGhosts (message)
394 {
395 this.ghosts.clear();
396 this.ghostOccupancy.clear();
397 for (const ghost of message.ghosts ?? [])
398 {
399 this.ghosts.set(ghost.entityId, ghost);
400 const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID);
401 const key = tileKey(ghost.tileX, ghost.tileY, dim);
402 let set = this.ghostOccupancy.get(key);
403 if (!set)
404 {
405 set = new Set();
406 this.ghostOccupancy.set(key, set);
407 }
408 set.add(ghost.entityId);
409 }
410 return { ok: true };
411 }
412
413 #spawn (message)
414 {
415 const entityId = deserializeEntity(this.ecs, message);
416 const handle = this.ecs.handleOf(entityId);
417 const position = this.ecs.get(handle, Component.position);
418 if (!position)
419 {
420 this.ecs.destroy(handle);
421 throw new Error("Spawned entity is missing position.");
422 }
423 const flying = this.#isFlying(handle);
424 if (!flying)
425 {
426 if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))
427 {
428 this.ecs.destroy(handle);
429 const error = new Error("That tile is occupied.");
430 error.userFacing = true;
431 throw error;
432 }
433 this.#occupy(entityId, position.tileX, position.tileY);
434 }
435 const creature = this.ecs.get(handle, Component.creature);
436 const def = creature ? mobDefinition(creature.mobTypeId) : null;
437 if (def?.freeFlight)
438 { ensureFlightComponent(this.ecs, handle, position, def); }
439 const character = this.ecs.get(handle, Component.character);
440 if (character?.characterId)
441 {
442 this.characterEntities.set(character.characterId, entityId);
443 syncCharacterChunkPresence(this.ecs, handle, Date.now());
444 }
445 return publicEntityView(this.ecs, entityId);
446 }
447
448 #despawn (entityId)
449 {
450 return this.#destroyEntity(entityId);
451 }
452
453 #despawnCharacter (characterId)
454 {
455 releaseShopBrowsersForCharacter(this, characterId);
456 const entityId = this.characterEntities.get(characterId);
457 if (!entityId)
458 { return null; }
459 return this.#destroyEntity(entityId);
460 }
461
462 #reattachSession (characterId, sessionId)
463 {
464 const entityId = this.characterEntities.get(characterId | 0);
465 if (!entityId)
466 { return { ok: false }; }
467 const handle = this.ecs.handleOf(entityId);
468 if (handle == null)
469 { return { ok: false }; }
470 this.ecs.add(handle, Component.networkIdentity, { sessionId });
471 return { ok: true, entityId };
472 }
473
474 #destroyEntity (entityId)
475 {
476 const handle = this.ecs.handleOf(entityId);
477 if (handle == null)
478 { return null; }
479 const view = publicEntityView(this.ecs, entityId);
480 const position = this.ecs.get(handle, Component.position);
481 const character = this.ecs.get(handle, Component.character);
482 if (position && !this.#isFlying(handle))
483 { this.#vacate(entityId, position.tileX, position.tileY); }
484 if (character?.characterId)
485 { this.characterEntities.delete(character.characterId); }
486 this.frozen.delete(entityId);
487 this.ecs.destroy(handle);
488 return view;
489 }
490
491 #command (message)
492 {
493 const { sessionId, command } = message;
494 switch (command.type)
495 {
496 case "move-to":
497 return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
498 case "set-gait":
499 return this.#setGait(sessionId, command.characterId, command.gait);
500 case "attack":
501 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
502 case "cancel-attack":
503 return this.#cancelAttack(sessionId, command.characterId);
504 case "interact":
505 return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose);
506 case "follow":
507 return this.#follow(sessionId, command.characterId, command.targetEntityId);
508 case "cancel-follow":
509 return this.#cancelFollow(sessionId, command.characterId);
510 case "jewelry-teleport":
511 {
512 const jewelry = handleJewelryTeleportCommand(this, sessionId, command, message.now ?? Date.now());
513 if (jewelry)
514 { return jewelry; }
515 return { events: [] };
516 }
517 case "set-spell-favorite":
518 case "set-spell-autocast":
519 case "arm-spell":
520 case "cancel-arm-spell":
521 case "cast-spell-tile":
522 case "cast-spell-entity":
523 case "read-spellbook":
524 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
525 default:
526 {
527 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
528 if (gather)
529 { return gather; }
530 const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now());
531 if (fire)
532 { return fire; }
533 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
534 if (fishing)
535 { return fishing; }
536 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
537 if (shearing)
538 { return shearing; }
539 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
540 if (craft)
541 { return craft; }
542 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
543 if (shop)
544 { return shop; }
545 const alchemy = handleAlchemyCommand(this, sessionId, command);
546 if (alchemy)
547 { return alchemy; }
548 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
549 return result ?? { events: [] };
550 }
551 }
552 }
553
554 #spawnCorpseDrops (message)
555 {
556 const events = [];
557 const drops = [...(message.drops ?? [])];
558 let privateBag = null;
559 if (message.dropCarriedCoins)
560 {
561 const entityId = this.characterEntities.get(message.characterId);
562 const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
563 const equipment = handle != null ? this.ecs.get(handle, Component.equipment) : null;
564 if (dropAmuletInsteadOfCoins(equipment))
565 {
566 const amulet = equipment?.slots?.[EQUIPMENT_SLOT.amulet]
567 ?? equipment?.slots?.amulet
568 ?? null;
569 if (amulet && (amulet.itemId | 0) === JewelryItemId.rubyAmulet)
570 {
571 equipment.slots[EQUIPMENT_SLOT.amulet] = null;
572 if (message.coinGroundItemId != null)
573 {
574 drops.push({
575 groundItemId: message.coinGroundItemId,
576 stack: {
577 itemId: JewelryItemId.rubyAmulet,
578 quantity: 1,
579 origins: amulet.origins ?? []
580 }
581 });
582 }
583 privateBag = bagView(this.ecs, handle);
584 }
585 }
586 else
587 {
588 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
589 privateBag = stripped.private;
590 if (stripped.stack && message.coinGroundItemId != null)
591 {
592 drops.push({
593 groundItemId: message.coinGroundItemId,
594 stack: stripped.stack
595 });
596 }
597 }
598 }
599 for (const drop of drops)
600 {
601 const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 };
602 const item = {
603 groundItemId: drop.groundItemId,
604 tileX: message.tileX,
605 tileY: message.tileY,
606 stack,
607 droppedAt: message.now,
608 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
609 source: "player-death",
610 droppedByCharacterId: message.characterId
611 };
612 addGroundItem(this, item);
613 events.push({
614 type: "ground-item-appear",
615 ...publicGroundItem(item),
616 stack: item.stack,
617 droppedAt: item.droppedAt,
618 source: item.source,
619 droppedByCharacterId: item.droppedByCharacterId,
620 expiresAt: item.expiresAt
621 });
622 }
623 return { events, private: privateBag };
624 }
625
626 #applyRespawn (message)
627 {
628 const handle = this.ecs.handleOf(message.entityId);
629 if (handle == null || !this.ecs.has(handle, Component.dead))
630 { return { accepted: false }; }
631 const position = this.ecs.get(handle, Component.position);
632 const fromTileX = position.tileX;
633 const fromTileY = position.tileY;
634 const health = this.ecs.get(handle, Component.health);
635 const stamina = this.ecs.get(handle, Component.stamina);
636 if (health)
637 {
638 health.max = message.maxHealth;
639 health.current = message.maxHealth;
640 }
641 if (stamina)
642 {
643 stamina.max = message.maxStamina;
644 stamina.current = message.maxStamina;
645 }
646 else
647 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
648 this.ecs.remove(handle, Component.dead);
649 clearEngage(this.ecs, message.entityId);
650 const path = this.ecs.get(handle, Component.path);
651 if (path)
652 { path.tiles = []; }
653 clearFollow(this.ecs, message.entityId);
654
655 const destRegionX = tileToRegion(message.tileX);
656 const destRegionY = tileToRegion(message.tileY);
657 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
658 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
659 {
660 this.frozen.add(message.entityId);
661 return {
662 accepted: true,
663 transferRequest: {
664 entityId: message.entityId,
665 fromTileX,
666 fromTileY,
667 destTileX: message.tileX,
668 destTileY: message.tileY,
669 toRegionX: destRegionX,
670 toRegionY: destRegionY,
671 dimensionId,
672 payload: serializeEntity(this.ecs, message.entityId)
673 }
674 };
675 }
676 if (!this.isEnterable(message.tileX, message.tileY, dimensionId))
677 { return { accepted: false }; }
678 this.#vacate(message.entityId, fromTileX, fromTileY);
679 position.tileX = message.tileX;
680 position.tileY = message.tileY;
681 syncCharacterChunkPresence(this.ecs, handle, Date.now());
682 this.#occupy(message.entityId, position.tileX, position.tileY);
683 return {
684 accepted: true,
685 event: {
686 type: "entity-move",
687 entityId: message.entityId,
688 fromTileX,
689 fromTileY,
690 tileX: position.tileX,
691 tileY: position.tileY,
692 dimensionId,
693 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
694 }
695 };
696 }
697
698 /** Move an entity to a tile/dimension; clears path and updates occupancy. */
699 #relocateEntity (message)
700 {
701 const handle = this.ecs.handleOf(message.entityId);
702 if (handle == null)
703 { return { accepted: false }; }
704 const position = this.ecs.get(handle, Component.position);
705 if (!position)
706 { return { accepted: false }; }
707 const fromTileX = position.tileX;
708 const fromTileY = position.tileY;
709 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
710 const destTileX = message.tileX | 0;
711 const destTileY = message.tileY | 0;
712 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
713
714 clearEngage(this.ecs, message.entityId);
715 const path = this.ecs.get(handle, Component.path);
716 if (path)
717 { path.tiles = []; }
718 clearFollow(this.ecs, message.entityId);
719
720 const destRegionX = tileToRegion(destTileX);
721 const destRegionY = tileToRegion(destTileY);
722 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
723 {
724 this.frozen.add(message.entityId);
725 const payload = serializeEntity(this.ecs, message.entityId);
726 if (payload.components?.position)
727 {
728 payload.components.position.tileX = destTileX;
729 payload.components.position.tileY = destTileY;
730 payload.components.position.dimensionId = dimensionId;
731 }
732 return {
733 accepted: true,
734 transferRequest: {
735 entityId: message.entityId,
736 fromTileX,
737 fromTileY,
738 fromDimensionId,
739 destTileX,
740 destTileY,
741 toRegionX: destRegionX,
742 toRegionY: destRegionY,
743 dimensionId,
744 payload
745 }
746 };
747 }
748 if (!this.isEnterable(destTileX, destTileY, dimensionId))
749 { return { accepted: false }; }
750 if (!this.#isFlying(handle))
751 { this.#vacate(message.entityId, fromTileX, fromTileY); }
752 position.tileX = destTileX;
753 position.tileY = destTileY;
754 position.dimensionId = dimensionId;
755 syncCharacterChunkPresence(this.ecs, handle, Date.now());
756 if (!this.#isFlying(handle))
757 { this.#occupy(message.entityId, destTileX, destTileY); }
758 return {
759 accepted: true,
760 event: {
761 type: "entity-move",
762 entityId: message.entityId,
763 fromTileX,
764 fromTileY,
765 fromDimensionId,
766 tileX: destTileX,
767 tileY: destTileY,
768 dimensionId,
769 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
770 }
771 };
772 }
773
774 #inspectBag (entityId)
775 {
776 const handle = this.ecs.handleOf(entityId);
777 if (handle == null)
778 { return null; }
779 return bagView(this.ecs, handle);
780 }
781
782 #inspectSkills (entityId)
783 {
784 const handle = this.ecs.handleOf(entityId);
785 if (handle == null)
786 { return null; }
787 const skills = this.ecs.get(handle, Component.skills);
788 if (!skills?.xp)
789 { return null; }
790 return skills;
791 }
792
793 #inspectSpells (entityId)
794 {
795 const handle = this.ecs.handleOf(entityId);
796 if (handle == null)
797 { return null; }
798 const spells = this.ecs.get(handle, Component.spells);
799 const skills = this.ecs.get(handle, Component.skills);
800 const casting = this.ecs.get(handle, Component.spellcasting);
801 if (!spells)
802 { return null; }
803 return {
804 spells: publicSpellsView(spells, skills),
805 autoCast: !!spells.autoCast,
806 armedSpellId: casting?.armedSpellId ?? null
807 };
808 }
809
810 #inspectStamina (entityId)
811 {
812 const handle = this.ecs.handleOf(entityId);
813 if (handle == null)
814 { return null; }
815 const stamina = this.ecs.get(handle, Component.stamina);
816 const movement = this.ecs.get(handle, Component.movement);
817 if (!stamina)
818 { return null; }
819 return {
820 ...publicStaminaView(stamina),
821 gait: movement?.gait ?? GAIT.walk
822 };
823 }
824
825 #applyBag (entityId, bag)
826 {
827 const handle = this.ecs.handleOf(entityId);
828 if (handle == null)
829 { return null; }
830 return applyBagView(this.ecs, handle, bag);
831 }
832
833 #applyAppearance (entityId, appearancePatch)
834 {
835 const handle = this.ecs.handleOf(entityId);
836 if (handle == null)
837 { return null; }
838 const appearance = this.ecs.get(handle, Component.appearance);
839 if (!appearance)
840 { return null; }
841 Object.assign(appearance, appearancePatch ?? {});
842 return publicEntityView(this.ecs, entityId);
843 }
844
845 #updateFlight (entityId, flightPatch, now = Date.now())
846 {
847 const handle = this.ecs.handleOf(entityId);
848 if (handle == null)
849 { return null; }
850 let flight = this.ecs.get(handle, Component.flight);
851 if (!flight)
852 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
853 else
854 { Object.assign(flight, flightPatch); }
855 const position = this.ecs.get(handle, Component.position);
856 const movement = this.ecs.get(handle, Component.movement);
857 const fromTileX = position.tileX;
858 const fromTileY = position.tileY;
859 const tileX = Math.floor(flight.x);
860 const tileY = Math.floor(flight.y);
861 position.tileX = tileX;
862 position.tileY = tileY;
863 syncCharacterChunkPresence(this.ecs, handle, now);
864 const destRegionX = tileToRegion(tileX);
865 const destRegionY = tileToRegion(tileY);
866 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
867 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
868 {
869 this.frozen.add(entityId);
870 return {
871 transferRequest: {
872 type: "transfer-request",
873 entityId,
874 fromTileX,
875 fromTileY,
876 destTileX: tileX,
877 destTileY: tileY,
878 toRegionX: destRegionX,
879 toRegionY: destRegionY,
880 dimensionId
881 }
882 };
883 }
884 const dt = flight.lastAt && now > flight.lastAt
885 ? Math.min(0.25, (now - flight.lastAt) / 1000)
886 : 1 / 20;
887 return {
888 event: {
889 type: "entity-move",
890 entityId,
891 fromTileX,
892 fromTileY,
893 tileX,
894 tileY,
895 worldX: flight.x,
896 worldY: flight.y,
897 gait: movement?.gait ?? "walk",
898 lerpMs: Math.max(50, Math.round(dt * 1000)),
899 freeFlight: true
900 }
901 };
902 }
903
904 #moveTo (sessionId, characterId, tileX, tileY)
905 {
906 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
907 if (this.frozen.has(entityId))
908 { return { events: [] }; }
909 clearEngage(this.ecs, entityId);
910 clearFollow(this.ecs, entityId);
911 cancelGather(this.ecs, handle);
912 cancelJewelryTeleport(this, characterId);
913 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
914 const position = this.ecs.get(handle, Component.position);
915 const movement = this.ecs.get(handle, Component.movement);
916 let path = this.ecs.get(handle, Component.path);
917 if (!path)
918 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
919 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
920 path.tiles = findPath(
921 position.tileX,
922 position.tileY,
923 tileX,
924 tileY,
925 (x, y) => this.walkableFor(entityId, x, y),
926 bounds.minX,
927 bounds.minY,
928 bounds.maxX,
929 bounds.maxY,
930 this.pathfindOptions({ preferVertical: true, preferPaths: true, entityId })
931 );
932 movement.walkCarry = 0;
933 const events = [];
934 /** Open immediately when the next step is a door (player already adjacent). */
935 const first = path.tiles[0];
936 if (first)
937 {
938 const doorDelta = maybeOpenDoorOnApproach(this, entityId, first.x, first.y);
939 if (doorDelta)
940 { events.push(doorDelta); }
941 }
942 return { events };
943 }
944
945 #attack (sessionId, characterId, targetEntityId, now)
946 {
947 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
948 if (targetEntityId === entityId)
949 {
950 const error = new Error("Cannot attack yourself.");
951 error.userFacing = true;
952 throw error;
953 }
954 const target = resolveCombatTarget(this, targetEntityId);
955 if (!target)
956 {
957 const error = new Error("Target is not here.");
958 error.userFacing = true;
959 throw error;
960 }
961 if (target.health && target.health.current <= 0)
962 {
963 const error = new Error("That cannot be attacked.");
964 error.userFacing = true;
965 throw error;
966 }
967 if (!this.ecs.get(handle, Component.combat))
968 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
969 clearFollow(this.ecs, entityId);
970 cancelGather(this.ecs, handle);
971 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
972 engageTarget(this.ecs, entityId, targetEntityId, now);
973 const position = this.ecs.get(handle, Component.position);
974 const profile = attackProfileOf(this.ecs, handle);
975 if (position && target.pos)
976 {
977 if (profile.mode === "ranged")
978 {
979 queueStandInRangeApproach(
980 this,
981 entityId,
982 handle,
983 position,
984 target.pos.tileX,
985 target.pos.tileY,
986 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
987 1
988 );
989 }
990 else if (profile.mode === "melee")
991 {
992 queueMeleeApproach(this, entityId, handle, position, target.pos);
993 }
994 }
995 return { events: [] };
996 }
997
998 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
999 {
1000 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
1001 void attackerEntityId;
1002 void targetEntityId;
1003 void now;
1004 return { events: [] };
1005 }
1006
1007 #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })
1008 {
1009 if (this.ecs.handleOf(attackerEntityId) == null)
1010 { return { ok: false }; }
1011 engageTarget(this.ecs, attackerEntityId, targetEntityId, now);
1012 return { ok: true };
1013 }
1014
1015 /**
1016 * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).
1017 * Optionally restrict to one spawnerId.
1018 */
1019 #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })
1020 {
1021 const guards = [];
1022 for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))
1023 {
1024 if (!entity.spawnOrigin?.townGuard)
1025 { continue; }
1026 if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)
1027 { continue; }
1028 const originX = entity.spawnOrigin.originTileX;
1029 const originY = entity.spawnOrigin.originTileY;
1030 const range = entity.spawnOrigin.wanderRangeTiles | 0;
1031 const dx = Math.abs(tileX - originX);
1032 const dy = Math.abs(tileY - originY);
1033 if (Math.max(dx, dy) > range)
1034 { continue; }
1035 const health = this.ecs.get(entity.handle, Component.health);
1036 if (health && health.current <= 0)
1037 { continue; }
1038 if (this.ecs.has(entity.handle, Component.dead))
1039 { continue; }
1040 guards.push({
1041 entityId: entity.entityId,
1042 spawnerId: entity.spawnOrigin.spawnerId,
1043 busy: entity.combat?.targetEntityId != null
1044 });
1045 if (guards.length >= limit)
1046 { break; }
1047 }
1048 return { guards };
1049 }
1050
1051 #applyRemoteMelee (payload)
1052 {
1053 return applyRemoteMeleeSwing(this, payload);
1054 }
1055
1056 #applyRemoteRanged (payload)
1057 {
1058 return applyRemoteRangedShot(this, payload);
1059 }
1060
1061 #applyCombatHitXp ({ entityId, profile, damage })
1062 {
1063 const handle = this.ecs.handleOf(entityId);
1064 if (handle == null)
1065 { return { events: [] }; }
1066 const character = this.ecs.get(handle, Component.character);
1067 if (!character)
1068 { return { events: [] }; }
1069 const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage);
1070 if (!xpAward)
1071 { return { events: [] }; }
1072 return {
1073 events: [{
1074 type: "skills-updated",
1075 entityId,
1076 characterId: character.characterId,
1077 skills: xpAward.skills,
1078 combatLevel: xpAward.combatLevel,
1079 stored: xpAward.stored,
1080 levelUps: xpAward.levelUps ?? []
1081 }]
1082 };
1083 }
1084
1085 #cancelAttack (sessionId, characterId)
1086 {
1087 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1088 clearEngage(this.ecs, entityId);
1089 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
1090 return { events: [] };
1091 }
1092
1093 #interact (sessionId, characterId, targetEntityId, purpose = null)
1094 {
1095 this.#requireOwnedEntity(sessionId, characterId);
1096 const targetHandle = this.ecs.handleOf(targetEntityId);
1097 if (targetHandle == null)
1098 {
1099 const error = new Error("Target is not here.");
1100 error.userFacing = true;
1101 throw error;
1102 }
1103 if (isUntargetable(this.ecs, targetHandle))
1104 {
1105 const error = new Error("Nothing to say.");
1106 error.userFacing = true;
1107 throw error;
1108 }
1109 const creature = this.ecs.get(targetHandle, Component.creature);
1110 const def = creature ? mobDefinition(creature.mobTypeId) : null;
1111 const shop = this.ecs.get(targetHandle, Component.shop);
1112 const hasShop = shopHasInterface(shop);
1113 const origin = this.ecs.get(targetHandle, Component.spawnOrigin);
1114 const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : "";
1115 const intent = purpose === "shop" || purpose === "talk" ? purpose : null;
1116
1117 if (intent === "shop" && hasShop)
1118 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1119 if (intent === "talk" && dialogueId)
1120 {
1121 // Pin in-worker before return so wander cannot start before the sim thread pins.
1122 this.#pinDialogue(targetEntityId, characterId);
1123 return {
1124 events: [{
1125 type: "open-dialogue",
1126 sessionId,
1127 characterId,
1128 entityId: targetEntityId,
1129 dialogueId
1130 }]
1131 };
1132 }
1133 if (intent === "talk" && hasShop)
1134 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1135
1136 // Default click: prefer dialogue when assigned, else shop, else talkable no-op.
1137 if (dialogueId)
1138 {
1139 this.#pinDialogue(targetEntityId, characterId);
1140 return {
1141 events: [{
1142 type: "open-dialogue",
1143 sessionId,
1144 characterId,
1145 entityId: targetEntityId,
1146 dialogueId
1147 }]
1148 };
1149 }
1150 if (hasShop)
1151 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1152 if (!def?.talkable)
1153 {
1154 const error = new Error("They have nothing to say.");
1155 error.userFacing = true;
1156 throw error;
1157 }
1158 return { events: [] };
1159 }
1160
1161 #follow (sessionId, characterId, targetEntityId)
1162 {
1163 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1164 const targetHandle = this.ecs.handleOf(targetEntityId);
1165 if (targetHandle == null)
1166 {
1167 const error = new Error("Target is not here.");
1168 error.userFacing = true;
1169 throw error;
1170 }
1171 if (targetEntityId === entityId)
1172 {
1173 const error = new Error("Cannot follow yourself.");
1174 error.userFacing = true;
1175 throw error;
1176 }
1177 if (!this.ecs.get(targetHandle, Component.position))
1178 {
1179 const error = new Error("That cannot be followed.");
1180 error.userFacing = true;
1181 throw error;
1182 }
1183 clearEngage(this.ecs, entityId);
1184 setFollow(this.ecs, entityId, targetEntityId);
1185 const path = this.ecs.get(handle, Component.path);
1186 if (path)
1187 { path.tiles = []; }
1188 return { events: [] };
1189 }
1190
1191 #cancelFollow (sessionId, characterId)
1192 {
1193 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
1194 clearFollow(this.ecs, entityId);
1195 return { events: [] };
1196 }
1197
1198 #setGait (sessionId, characterId, gait)
1199 {
1200 if (gait !== GAIT.walk && gait !== GAIT.run)
1201 {
1202 const error = new Error("Gait must be walk or run.");
1203 error.userFacing = true;
1204 throw error;
1205 }
1206 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
1207 const movement = this.ecs.get(handle, Component.movement);
1208 const stamina = this.ecs.get(handle, Component.stamina);
1209 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
1210 {
1211 const error = new Error("You are too exhausted to run.");
1212 error.userFacing = true;
1213 throw error;
1214 }
1215 movement.gait = gait;
1216 const character = this.ecs.get(handle, Component.character);
1217 return {
1218 events: character
1219 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
1220 : []
1221 };
1222 }
1223
1224 #staminaEvent (handle, characterId, gait = null)
1225 {
1226 const stamina = this.ecs.get(handle, Component.stamina);
1227 const movement = this.ecs.get(handle, Component.movement);
1228 return {
1229 type: "stamina",
1230 characterId,
1231 ...publicStaminaView(stamina),
1232 gait: gait ?? movement?.gait ?? GAIT.walk
1233 };
1234 }
1235
1236 #consumeRunStamina (handle, events)
1237 {
1238 const character = this.ecs.get(handle, Component.character);
1239 if (!character)
1240 { return; }
1241 let stamina = this.ecs.get(handle, Component.stamina);
1242 if (!stamina)
1243 {
1244 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
1245 }
1246 const skills = this.ecs.get(handle, Component.skills);
1247 syncPlayerStamina(this.ecs, handle);
1248 const position = this.ecs.get(handle, Component.position);
1249 const onPath = position
1250 ? this.groundTypeAt(position.tileX, position.tileY, position.dimensionId) === GroundType.path
1251 : false;
1252 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond, { onPath });
1253 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
1254 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
1255 let skillsChanged = false;
1256 const levelUps = [];
1257 while (stamina.xpDebt >= 1 && skills?.xp)
1258 {
1259 stamina.xpDebt -= 1;
1260 const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT);
1261 if (result.changed)
1262 {
1263 skillsChanged = true;
1264 syncPlayerStamina(this.ecs, handle);
1265 }
1266 if (result.levelUp)
1267 { levelUps.push(result.levelUp); }
1268 }
1269 const movement = this.ecs.get(handle, Component.movement);
1270 if (stamina.current <= 0 && movement)
1271 {
1272 stamina.current = 0;
1273 movement.gait = GAIT.walk;
1274 }
1275 events.push(this.#staminaEvent(handle, character.characterId));
1276 if (skillsChanged)
1277 {
1278 events.push({
1279 type: "skills-updated",
1280 entityId: this.ecs.entityIdOf(handle),
1281 characterId: character.characterId,
1282 ...publicSkillsPayload(skills),
1283 stored: storedSkillXp(skills),
1284 levelUps
1285 });
1286 }
1287 }
1288
1289 #regenStamina (dt, events)
1290 {
1291 if (!(dt > 0))
1292 { return; }
1293 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
1294 {
1295 const { handle, character, stamina, movement } = entity;
1296 if (this.ecs.has(handle, Component.dead))
1297 { continue; }
1298 const status = this.ecs.get(handle, Component.statusEffects);
1299 if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now()))
1300 { continue; }
1301 // Run gait only blocks regen while actually stepping along a path.
1302 const path = this.ecs.get(handle, Component.path);
1303 if (movement.gait === GAIT.run && path?.tiles?.length)
1304 { continue; }
1305 syncPlayerStamina(this.ecs, handle);
1306 const before = Number(stamina.current) || 0;
1307 if (before >= stamina.max)
1308 { continue; }
1309 stamina.current = Math.min(
1310 stamina.max,
1311 before + dt * STAMINA_REGEN_PER_SECOND * passiveStaminaRegenMultiplier(
1312 this.ecs.get(handle, Component.equipment)
1313 )
1314 );
1315 const after = Number(stamina.current) || 0;
1316 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1317 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
1318 { events.push(this.#staminaEvent(handle, character.characterId)); }
1319 }
1320 }
1321
1322 #requireOwnedEntity (sessionId, characterId)
1323 {
1324 const entityId = this.characterEntities.get(characterId);
1325 if (!entityId)
1326 {
1327 const error = new Error("Character is not in the world.");
1328 error.userFacing = true;
1329 throw error;
1330 }
1331 const handle = this.ecs.handleOf(entityId);
1332 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
1333 if (!identity || identity.sessionId !== sessionId)
1334 {
1335 const error = new Error("Character is not in the world.");
1336 error.userFacing = true;
1337 throw error;
1338 }
1339 if (this.ecs.has(handle, Component.dead))
1340 {
1341 const error = new Error("You are dead.");
1342 error.userFacing = true;
1343 throw error;
1344 }
1345 return { handle, entityId };
1346 }
1347
1348 #stepSystems (now = Date.now(), dt = 1 / 20)
1349 {
1350 const events = [];
1351 const transferRequests = [];
1352 this.#regenStamina(dt, events);
1353 events.push(...stepStatusEffects(this, now, dt));
1354 events.push(...stepPassiveHealthRegen(this, now, dt));
1355 const flight = stepFreeFlight(this, now);
1356 for (const event of flight)
1357 {
1358 if (event.type === "transfer-request")
1359 {
1360 const payload = serializeEntity(this.ecs, event.entityId);
1361 transferRequests.push({
1362 entityId: event.entityId,
1363 fromTileX: event.fromTileX,
1364 fromTileY: event.fromTileY,
1365 destTileX: event.destTileX,
1366 destTileY: event.destTileY,
1367 toRegionX: event.toRegionX,
1368 toRegionY: event.toRegionY,
1369 dimensionId: event.dimensionId ?? OVERWORLD_ID,
1370 payload
1371 });
1372 continue;
1373 }
1374 events.push(event);
1375 }
1376 stepAggression(this, now);
1377 events.push(...stepCombat(this, now));
1378 events.push(...stepPendingSpellCast(this, now));
1379 events.push(...processSpellImpacts(this, now));
1380 events.push(...stepSpellAutoCast(this, now));
1381 events.push(...tickSpellLights(this, now));
1382 const summons = stepSummons(this, now);
1383 events.push(...(summons.events ?? []));
1384 for (const entityId of summons.despawnIds ?? [])
1385 {
1386 const dropped = this.#destroyEntity(entityId);
1387 if (dropped)
1388 { events.push({ type: "entity-despawn", entityId }); }
1389 }
1390 const fairies = stepJadeiteFairies(this, now);
1391 events.push(...(fairies.events ?? []));
1392 for (const entityId of fairies.despawnIds ?? [])
1393 {
1394 const dropped = this.#destroyEntity(entityId);
1395 if (dropped)
1396 { events.push({ type: "entity-despawn", entityId }); }
1397 }
1398 events.push(...stepJewelryTeleports(this, now).events);
1399 stepFollow(this);
1400 const gather = stepGather(this, now);
1401 events.push(...gather.events);
1402 for (const entry of gather.privates ?? [])
1403 {
1404 events.push({
1405 type: "inventory",
1406 characterId: entry.characterId,
1407 ...entry.bag
1408 });
1409 }
1410 const fire = stepFirestarting(this, now);
1411 events.push(...fire.events);
1412 for (const entry of fire.privates ?? [])
1413 {
1414 events.push({
1415 type: "inventory",
1416 characterId: entry.characterId,
1417 ...entry.bag
1418 });
1419 }
1420 const fishing = stepFishing(this, now);
1421 events.push(...fishing.events);
1422 for (const entry of fishing.privates ?? [])
1423 {
1424 events.push({
1425 type: "inventory",
1426 characterId: entry.characterId,
1427 ...entry.bag
1428 });
1429 }
1430 const shearing = stepShearing(this, now);
1431 events.push(...shearing.events);
1432 for (const entry of shearing.privates ?? [])
1433 {
1434 events.push({
1435 type: "inventory",
1436 characterId: entry.characterId,
1437 ...entry.bag
1438 });
1439 }
1440 const craft = stepCrafting(this, now);
1441 events.push(...craft.events);
1442 for (const entry of craft.privates ?? [])
1443 {
1444 events.push({
1445 type: "inventory",
1446 characterId: entry.characterId,
1447 ...entry.bag
1448 });
1449 }
1450 events.push(...stepDoors(this));
1451 return { events, transferRequests };
1452 }
1453
1454 #stepMovement (now = Date.now())
1455 {
1456 const events = expireGroundItems(this, now);
1457 const transferRequests = [];
1458 events.push(...pruneShopBrowsers(this));
1459 events.push(...this.#pruneDialogueBrowsers());
1460 this.#queueAmbientWander();
1461 this.#queueSpawnerWander();
1462 this.#queueExchangeStations();
1463 for (const entity of this.ecs.query(Component.position, Component.movement))
1464 {
1465 const { handle, entityId, position, movement } = entity;
1466 if (this.ecs.has(handle, Component.dead))
1467 { continue; }
1468 if (this.ecs.has(handle, Component.flight))
1469 { continue; }
1470 const path = this.ecs.get(handle, Component.path);
1471 const tiles = path?.tiles;
1472 if (this.frozen.has(entityId) || !tiles?.length)
1473 {
1474 if (path)
1475 { path.stuckSince = null; }
1476 continue;
1477 }
1478 if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID))
1479 { continue; }
1480
1481 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1482
1483 const stamina = this.ecs.get(handle, Component.stamina);
1484 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1485 { movement.gait = GAIT.walk; }
1486 const isWalk = movement.gait !== GAIT.run;
1487 if (isWalk)
1488 {
1489 movement.walkCarry = (movement.walkCarry + 1) % 2;
1490 if (movement.walkCarry !== 0)
1491 { continue; }
1492 }
1493
1494 const next = tiles[0];
1495 if (!next)
1496 { continue; }
1497 const destRegionX = tileToRegion(next.x);
1498 const destRegionY = tileToRegion(next.y);
1499 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1500 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1501 {
1502 this.frozen.add(entityId);
1503 transferRequests.push({
1504 entityId,
1505 fromTileX: position.tileX,
1506 fromTileY: position.tileY,
1507 destTileX: next.x,
1508 destTileY: next.y,
1509 toRegionX: destRegionX,
1510 toRegionY: destRegionY,
1511 dimensionId,
1512 payload: serializeEntity(this.ecs, entityId)
1513 });
1514 continue;
1515 }
1516
1517 if (!this.walkableFor(entityId, next.x, next.y))
1518 {
1519 const combat = this.ecs.get(handle, Component.combat);
1520 if (combat?.targetEntityId != null)
1521 {
1522 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1523 const targetPos = targetHandle != null
1524 ? this.ecs.get(targetHandle, Component.position)
1525 : null;
1526 const blockedByTarget = targetPos
1527 && next.x === targetPos.tileX
1528 && next.y === targetPos.tileY;
1529 if (!blockedByTarget)
1530 { path.tiles = []; }
1531 }
1532 continue;
1533 }
1534
1535 const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y);
1536 if (doorDelta)
1537 { events.push(doorDelta); }
1538
1539 const combat = this.ecs.get(handle, Component.combat);
1540 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1541 { continue; }
1542
1543 const fromTileX = position.tileX;
1544 const fromTileY = position.tileY;
1545 const flying = this.#isFlying(handle);
1546 if (!flying)
1547 { this.#vacate(entityId, fromTileX, fromTileY); }
1548 position.tileX = next.x;
1549 position.tileY = next.y;
1550 tiles.shift();
1551 if (!flying)
1552 { this.#occupy(entityId, position.tileX, position.tileY, now); }
1553 path.stuckSince = now;
1554 path.stuckTileX = position.tileX;
1555 path.stuckTileY = position.tileY;
1556 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1557 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1558 syncCharacterChunkPresence(this.ecs, handle, now);
1559 if (!isWalk)
1560 { this.#consumeRunStamina(handle, events); }
1561 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1562 }
1563 return { events, transferRequests };
1564 }
1565
1566 /**
1567 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1568 * recompute A* to the same goal (around whoever is blocking the old route).
1569 */
1570 #repathIfNavigationStuck (entityId, position, movement, path, now)
1571 {
1572 if (!path?.tiles?.length)
1573 {
1574 path.stuckSince = null;
1575 return;
1576 }
1577 if (
1578 path.stuckSince == null
1579 || path.stuckTileX !== position.tileX
1580 || path.stuckTileY !== position.tileY
1581 )
1582 {
1583 path.stuckSince = now;
1584 path.stuckTileX = position.tileX;
1585 path.stuckTileY = position.tileY;
1586 return;
1587 }
1588 if (now - path.stuckSince < NAV_STUCK_MS)
1589 { return; }
1590
1591 const goal = path.tiles[path.tiles.length - 1];
1592 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1593 {
1594 path.tiles = [];
1595 path.stuckSince = null;
1596 return;
1597 }
1598 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1599 const stuckHandle = this.ecs.handleOf(entityId);
1600 const inCombat = stuckHandle != null
1601 && this.ecs.get(stuckHandle, Component.combat)?.targetEntityId != null;
1602 path.tiles = findPath(
1603 position.tileX,
1604 position.tileY,
1605 goal.x,
1606 goal.y,
1607 (x, y) => this.isClearStanding(entityId, x, y),
1608 bounds.minX,
1609 bounds.minY,
1610 bounds.maxX,
1611 bounds.maxY,
1612 this.pathfindOptions({
1613 preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1614 preferPaths: !inCombat,
1615 entityId
1616 })
1617 );
1618 path.stuckSince = now;
1619 path.stuckTileX = position.tileX;
1620 path.stuckTileY = position.tileY;
1621 if (movement)
1622 { movement.walkCarry = 0; }
1623 }
1624
1625 #queueAmbientWander ()
1626 {
1627 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1628 {
1629 const def = mobDefinition(entity.creature.mobTypeId);
1630 if (!def?.ambient || def.freeFlight)
1631 { continue; }
1632 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1633 { continue; }
1634 const path = this.ecs.get(entity.handle, Component.path);
1635 if (!path)
1636 { continue; }
1637 if (path.tiles?.length)
1638 { continue; }
1639 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1640 { continue; }
1641 if (Math.random() > 0.35)
1642 { continue; }
1643 const dirs = [
1644 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1645 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1646 ];
1647 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1648 const nextX = entity.position.tileX + dir.x;
1649 const nextY = entity.position.tileY + dir.y;
1650 if (!this.isClearStanding(entity.entityId, nextX, nextY))
1651 { continue; }
1652 path.tiles = [{ x: nextX, y: nextY }];
1653 }
1654 }
1655
1656 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
1657 #queueSpawnerWander ()
1658 {
1659 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1660 {
1661 const combat = this.ecs.get(entity.handle, Component.combat);
1662 if (combat?.targetEntityId != null)
1663 { continue; }
1664 const follow = this.ecs.get(entity.handle, Component.follow);
1665 if (follow?.targetEntityId != null)
1666 { continue; }
1667 const shop = this.ecs.get(entity.handle, Component.shop);
1668 if (shopHasActiveBrowsers(shop))
1669 { continue; }
1670 const origin = entity.spawnOrigin;
1671 if (originIsBusyPinned(origin))
1672 { continue; }
1673 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1674 { continue; }
1675 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1676 if (def?.freeFlight)
1677 { continue; }
1678 const path = this.ecs.get(entity.handle, Component.path);
1679 if (!path || path.tiles?.length)
1680 { continue; }
1681 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1682 { continue; }
1683
1684 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1685 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1686 const range = Math.max(0, origin.wanderRangeTiles | 0);
1687 const homeDist = Math.max(
1688 Math.abs(entity.position.tileX - originX),
1689 Math.abs(entity.position.tileY - originY)
1690 );
1691 const tooFar = homeDist > range;
1692
1693 // Outside the leash: always try to step home. Inside: mostly idle.
1694 if (!tooFar && Math.random() > 0.1)
1695 { continue; }
1696
1697 if (tooFar)
1698 {
1699 if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY))
1700 { continue; }
1701 queueLocalRandomWanderStep(this, entity.entityId, entity.position, path);
1702 continue;
1703 }
1704
1705 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1706 if (!goal)
1707 { continue; }
1708 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1709 { continue; }
1710 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1711 const tiles = findPath(
1712 entity.position.tileX,
1713 entity.position.tileY,
1714 goal.tileX,
1715 goal.tileY,
1716 (x, y) => this.walkableFor(entity.entityId, x, y),
1717 bounds.minX,
1718 bounds.minY,
1719 bounds.maxX,
1720 bounds.maxY,
1721 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
1722 );
1723 if (!tiles?.length)
1724 { continue; }
1725 path.tiles = tiles;
1726 }
1727 }
1728
1729 /**
1730 * Path toward the spawner within the current pathfinding window (chunk-step home).
1731 * @returns {boolean} true if a return path was queued
1732 */
1733 #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY)
1734 {
1735 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1736 const goal = pickClearGoalToward(
1737 this,
1738 entityId,
1739 position.tileX,
1740 position.tileY,
1741 originX,
1742 originY,
1743 bounds
1744 );
1745 if (!goal)
1746 { return false; }
1747 if (goal.tileX === position.tileX && goal.tileY === position.tileY)
1748 { return false; }
1749 const tiles = findPath(
1750 position.tileX,
1751 position.tileY,
1752 goal.tileX,
1753 goal.tileY,
1754 (x, y) => this.walkableFor(entityId, x, y),
1755 bounds.minX,
1756 bounds.minY,
1757 bounds.maxX,
1758 bounds.maxY,
1759 this.pathfindOptions({ preferPaths: true, entityId })
1760 );
1761 if (!tiles?.length)
1762 { return false; }
1763 path.tiles = tiles;
1764 const movement = this.ecs.get(handle, Component.movement);
1765 if (movement)
1766 { movement.walkCarry = 0; }
1767 return true;
1768 }
1769
1770 /**
1771 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1772 * message: { stationTileX, stationTileY }
1773 */
1774 #stationExchangeClerk (message)
1775 {
1776 const stationTileX = message.stationTileX | 0;
1777 const stationTileY = message.stationTileY | 0;
1778 if (!this.isEnterable(stationTileX, stationTileY))
1779 { return { ok: false, reason: "blocked" }; }
1780
1781 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1782 {
1783 if (!entity.spawnOrigin?.centralExchange)
1784 { continue; }
1785 if (
1786 Number.isInteger(entity.spawnOrigin.stationTileX)
1787 && entity.spawnOrigin.stationTileX === stationTileX
1788 && entity.spawnOrigin.stationTileY === stationTileY
1789 )
1790 { return { ok: true, entityId: entity.entityId, already: true }; }
1791 }
1792
1793 let best = null;
1794 let bestDist = Infinity;
1795 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1796 {
1797 if (!entity.spawnOrigin?.centralExchange)
1798 { continue; }
1799 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1800 { continue; }
1801 const dist = Math.max(
1802 Math.abs(entity.position.tileX - stationTileX),
1803 Math.abs(entity.position.tileY - stationTileY)
1804 );
1805 if (dist < bestDist)
1806 {
1807 bestDist = dist;
1808 best = entity;
1809 }
1810 }
1811 if (!best)
1812 { return { ok: false, reason: "none-available" }; }
1813
1814 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1815 const tiles = findPath(
1816 best.position.tileX,
1817 best.position.tileY,
1818 stationTileX,
1819 stationTileY,
1820 (x, y) => this.walkableFor(best.entityId, x, y),
1821 bounds.minX,
1822 bounds.minY,
1823 bounds.maxX,
1824 bounds.maxY,
1825 this.pathfindOptions({ preferPaths: true, entityId: best.entityId })
1826 );
1827 best.spawnOrigin.stationTileX = stationTileX;
1828 best.spawnOrigin.stationTileY = stationTileY;
1829 if (tiles?.length)
1830 { best.path.tiles = tiles; }
1831 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1832 { best.path.tiles = []; }
1833 else
1834 { return { ok: false, reason: "no-path" }; }
1835 return { ok: true, entityId: best.entityId };
1836 }
1837
1838 /**
1839 * Clear a CE clerk's station assignment so wander can resume.
1840 * message: { stationTileX, stationTileY }
1841 */
1842 #releaseExchangeClerk (message)
1843 {
1844 const stationTileX = message.stationTileX | 0;
1845 const stationTileY = message.stationTileY | 0;
1846 let released = 0;
1847 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1848 {
1849 if (!entity.spawnOrigin?.centralExchange)
1850 { continue; }
1851 if (
1852 entity.spawnOrigin.stationTileX !== stationTileX
1853 || entity.spawnOrigin.stationTileY !== stationTileY
1854 )
1855 { continue; }
1856 entity.spawnOrigin.stationTileX = null;
1857 entity.spawnOrigin.stationTileY = null;
1858 entity.path.tiles = [];
1859 released += 1;
1860 }
1861 return { ok: true, released };
1862 }
1863
1864 #pinDialogue (entityId, characterId)
1865 {
1866 const handle = this.ecs.handleOf(entityId | 0);
1867 if (handle == null)
1868 { return { ok: false }; }
1869 const origin = this.ecs.get(handle, Component.spawnOrigin);
1870 if (!origin)
1871 { return { ok: false }; }
1872 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
1873 { origin.dialogueBrowsers = Object.create(null); }
1874 origin.dialogueBrowsers[characterId | 0] = true;
1875 const path = this.ecs.get(handle, Component.path);
1876 if (path)
1877 { path.tiles = []; }
1878 return { ok: true };
1879 }
1880
1881 #unpinDialogue (entityId, characterId)
1882 {
1883 const handle = this.ecs.handleOf(entityId | 0);
1884 if (handle == null)
1885 { return { ok: false }; }
1886 const origin = this.ecs.get(handle, Component.spawnOrigin);
1887 if (!origin?.dialogueBrowsers)
1888 { return { ok: true }; }
1889 delete origin.dialogueBrowsers[characterId | 0];
1890 return { ok: true };
1891 }
1892
1893 #pruneDialogueBrowsers ()
1894 {
1895 const events = [];
1896 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1897 {
1898 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1899 const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
1900 const dialogueIds = browsers && typeof browsers === "object"
1901 ? Object.keys(browsers).map((id) => Number(id))
1902 : [];
1903 const shearIds = shearBrowsers && typeof shearBrowsers === "object"
1904 ? Object.keys(shearBrowsers).map((id) => Number(id))
1905 : [];
1906 if (!dialogueIds.length && !shearIds.length)
1907 { continue; }
1908 const path = this.ecs.get(entity.handle, Component.path);
1909 if (path)
1910 { path.tiles = []; }
1911 for (const characterId of dialogueIds)
1912 {
1913 const playerEntityId = this.characterEntities.get(characterId);
1914 if (playerEntityId == null)
1915 {
1916 delete browsers[characterId];
1917 continue;
1918 }
1919 const playerHandle = this.ecs.handleOf(playerEntityId);
1920 const playerPos = this.ecs.get(playerHandle, Component.position);
1921 const stillNear = playerPos
1922 && chebyshev(
1923 playerPos.tileX,
1924 playerPos.tileY,
1925 entity.position.tileX,
1926 entity.position.tileY
1927 ) <= 1;
1928 if (stillNear)
1929 { continue; }
1930 delete browsers[characterId];
1931 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
1932 events.push({
1933 type: "dialogue-walk-away",
1934 sessionId: identity?.sessionId ?? null,
1935 characterId,
1936 npcEntityId: entity.entityId
1937 });
1938 }
1939 for (const characterId of shearIds)
1940 {
1941 const playerEntityId = this.characterEntities.get(characterId);
1942 if (playerEntityId == null)
1943 {
1944 delete shearBrowsers[characterId];
1945 continue;
1946 }
1947 const playerHandle = this.ecs.handleOf(playerEntityId);
1948 const playerPos = this.ecs.get(playerHandle, Component.position);
1949 const stillNear = playerPos
1950 && chebyshev(
1951 playerPos.tileX,
1952 playerPos.tileY,
1953 entity.position.tileX,
1954 entity.position.tileY
1955 ) <= 1;
1956 if (stillNear)
1957 { continue; }
1958 delete shearBrowsers[characterId];
1959 }
1960 }
1961 return events;
1962 }
1963
1964 /** Keep stationed CE clerks at their counter tile. */
1965 #queueExchangeStations ()
1966 {
1967 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1968 {
1969 if (!entity.spawnOrigin?.centralExchange)
1970 { continue; }
1971 const sx = entity.spawnOrigin.stationTileX;
1972 const sy = entity.spawnOrigin.stationTileY;
1973 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1974 { continue; }
1975 if (entity.position.tileX === sx && entity.position.tileY === sy)
1976 {
1977 entity.path.tiles = [];
1978 continue;
1979 }
1980 if (entity.path.tiles?.length)
1981 { continue; }
1982 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1983 const tiles = findPath(
1984 entity.position.tileX,
1985 entity.position.tileY,
1986 sx,
1987 sy,
1988 (x, y) => this.walkableFor(entity.entityId, x, y),
1989 bounds.minX,
1990 bounds.minY,
1991 bounds.maxX,
1992 bounds.maxY,
1993 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
1994 );
1995 if (tiles?.length)
1996 { entity.path.tiles = tiles; }
1997 }
1998 }
1999
2000 #applyTransfer (message)
2001 {
2002 const payload = message.payload;
2003 const entityId = payload.entityId;
2004 if (this.ecs.hasEntity(entityId))
2005 { return { accepted: false, reason: "already-present" }; }
2006
2007 const position = payload.components?.position;
2008 const destTileX = message.destTileX ?? position?.tileX;
2009 const destTileY = message.destTileY ?? position?.tileY;
2010 const dimensionId = normalizeDimensionId(
2011 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
2012 );
2013 if (destTileX == null || destTileY == null)
2014 { return { accepted: false, reason: "missing-destination" }; }
2015 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
2016 { return { accepted: false, reason: "not-owner" }; }
2017
2018 const creature = payload.components?.creature;
2019 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
2020 if (flying)
2021 {
2022 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
2023 if (!data?.open)
2024 { return { accepted: false, reason: "blocked" }; }
2025 }
2026 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
2027 { return { accepted: false, reason: "blocked" }; }
2028
2029 deserializeEntity(this.ecs, payload);
2030 const handle = this.ecs.handleOf(entityId);
2031 const livePosition = this.ecs.get(handle, Component.position);
2032 const path = this.ecs.get(handle, Component.path);
2033 livePosition.tileX = destTileX;
2034 livePosition.tileY = destTileY;
2035 livePosition.dimensionId = dimensionId;
2036 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
2037 { path.tiles.shift(); }
2038 if (!flying)
2039 { this.#occupy(entityId, destTileX, destTileY); }
2040 const character = this.ecs.get(handle, Component.character);
2041 if (character?.characterId)
2042 { this.characterEntities.set(character.characterId, entityId); }
2043 this.frozen.delete(entityId);
2044 return {
2045 accepted: true,
2046 entity: publicEntityView(this.ecs, entityId)
2047 };
2048 }
2049
2050 #commitTransfer (entityId)
2051 {
2052 if (!this.ecs.hasEntity(entityId))
2053 { return null; }
2054 return this.#destroyEntity(entityId);
2055 }
2056
2057 #abortTransfer (entityId)
2058 {
2059 this.frozen.delete(entityId);
2060 return publicEntityView(this.ecs, entityId);
2061 }
2062
2063 #listLoaders ()
2064 {
2065 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
2066 entityId: entity.entityId,
2067 tileX: entity.position.tileX,
2068 tileY: entity.position.tileY,
2069 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
2070 chunkLoader: { ...entity.chunkLoader }
2071 }));
2072 }
2073
2074 #listPublicEntities ()
2075 {
2076 const out = [];
2077 for (const entity of this.ecs.query(Component.position))
2078 {
2079 if (this.ecs.has(entity.handle, Component.dead))
2080 { continue; }
2081 const view = publicEntityView(this.ecs, entity.entityId);
2082 if (view)
2083 { out.push(view); }
2084 }
2085 return out;
2086 }
2087
2088 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2089 {
2090 const dim = normalizeDimensionId(dimensionId);
2091 const records = [];
2092 for (const entity of this.ecs.query(Component.position))
2093 {
2094 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2095 if (entityDim !== dim)
2096 { continue; }
2097 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
2098 { continue; }
2099 records.push({
2100 ...publicEntityView(this.ecs, entity.entityId),
2101 persistent: this.ecs.has(entity.handle, Component.persistent),
2102 payload: serializeEntity(this.ecs, entity.entityId)
2103 });
2104 }
2105 return records;
2106 }
2107
2108 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
2109 {
2110 const dim = normalizeDimensionId(dimensionId);
2111 const data = this.#chunkData(chunkX, chunkY, dim);
2112 if (staticOnly)
2113 {
2114 return {
2115 chunkX,
2116 chunkY,
2117 dimensionId: dim,
2118 open: data.open,
2119 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2120 grounds: data.grounds,
2121 blocks: data.blocks,
2122 light: data.light,
2123 occlusion: data.occlusion,
2124 entities: [],
2125 groundItems: []
2126 };
2127 }
2128 const entities = [];
2129 for (const entity of this.ecs.query(Component.position, Component.appearance))
2130 {
2131 if (this.ecs.has(entity.handle, Component.dead))
2132 { continue; }
2133 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2134 if (entityDim !== dim)
2135 { continue; }
2136 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
2137 { continue; }
2138 entities.push(publicEntityView(this.ecs, entity.entityId));
2139 }
2140 return {
2141 chunkX,
2142 chunkY,
2143 dimensionId: dim,
2144 open: data.open,
2145 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2146 grounds: data.grounds,
2147 blocks: data.blocks,
2148 light: data.light,
2149 occlusion: data.occlusion,
2150 entities,
2151 groundItems: groundItemsInChunk(this, chunkX, chunkY)
2152 };
2153 }
2154
2155 #moveEvent (entityId, fromTileX, fromTileY)
2156 {
2157 const view = publicEntityView(this.ecs, entityId);
2158 return {
2159 type: "entity-move",
2160 entityId,
2161 fromTileX,
2162 fromTileY,
2163 tileX: view.tileX,
2164 tileY: view.tileY,
2165 worldX: view.worldX,
2166 worldY: view.worldY,
2167 gait: view.gait,
2168 freeFlight: !!view.freeFlight
2169 };
2170 }
2171
2172 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2173 {
2174 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
2175 return !!chunk && !chunk.replica && chunk.simulating;
2176 }
2177
2178 walkableFor (entityId, tileX, tileY)
2179 {
2180 const dim = this.#entityDimensionId(entityId);
2181 const handle = this.ecs.handleOf(entityId);
2182 if (this.#isFlying(handle))
2183 {
2184 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2185 return !!data?.open;
2186 }
2187 // Entities pass through each other; only terrain / closed chunks block movement.
2188 return this.isEnterable(tileX, tileY, dim, {
2189 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2190 });
2191 }
2192
2193 /** Ground type id at a world tile (defaults to world default ground). */
2194 groundTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID)
2195 {
2196 const dim = normalizeDimensionId(dimensionId) ?? OVERWORLD_ID;
2197 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2198 const entry = normalizeGround(data.grounds[tileIndex(tileToLocal(tileX), tileToLocal(tileY))]);
2199 return entry?.typeId ?? this.settings.defaultGroundTypeId ?? GroundType.grass;
2200 }
2201
2202 /**
2203 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options]
2204 */
2205 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {})
2206 {
2207 const options = { preferVertical: !!preferVertical };
2208 const now = Date.now();
2209 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2210 options.stepCost = (x, y) => stepCostForGround(
2211 this.groundTypeAt(x, y, dimensionId),
2212 {
2213 preferPaths: !!preferPaths,
2214 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2215 }
2216 );
2217 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2218 return options;
2219 }
2220
2221 /**
2222 * True when another living occupant has stood on this tile for SOFT_OCCUPIED_DWELL_MS+.
2223 * Soft cost only — never blocks pathing.
2224 */
2225 #isSoftOccupiedTile (tileX, tileY, dimensionId, selfEntityId, now = Date.now())
2226 {
2227 const key = tileKey(tileX, tileY, dimensionId);
2228 const local = this.occupancy.get(key);
2229 if (!local?.size)
2230 { return false; }
2231 for (const id of local)
2232 {
2233 if (id === selfEntityId)
2234 { continue; }
2235 const handle = this.ecs.handleOf(id);
2236 if (handle == null)
2237 { continue; }
2238 const position = this.ecs.get(handle, Component.position);
2239 const enteredAt = position?.tileEnteredAt;
2240 if (enteredAt == null)
2241 { continue; }
2242 if (now - enteredAt >= SOFT_OCCUPIED_DWELL_MS)
2243 { return true; }
2244 }
2245 return false;
2246 }
2247
2248 /**
2249 * Standing tile with no other mob/player (self allowed). Used for wander goals
2250 * and melee attack stance.
2251 */
2252 isClearStanding (entityId, tileX, tileY)
2253 {
2254 const dim = this.#entityDimensionId(entityId);
2255 if (!this.isEnterable(tileX, tileY, dim, {
2256 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2257 }))
2258 { return false; }
2259 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2260 }
2261
2262 destroyEntity (entityId)
2263 {
2264 return this.#destroyEntity(entityId);
2265 }
2266
2267 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2268 {
2269 return this.#anyOccupant(tileX, tileY, dimensionId);
2270 }
2271
2272 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2273 {
2274 return this.chunkIsSimulating(tileX, tileY, dimensionId);
2275 }
2276
2277 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2278 {
2279 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
2280 if (loaded)
2281 { return loaded.data; }
2282 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2283 }
2284
2285 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {})
2286 {
2287 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2288 if (!data.open)
2289 { return false; }
2290 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors });
2291 }
2292
2293 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
2294 {
2295 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2296 if (!data.open)
2297 { return false; }
2298 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
2299 }
2300
2301 #walkableFor (entityId, tileX, tileY)
2302 {
2303 return this.walkableFor(entityId, tileX, tileY);
2304 }
2305
2306 #isFlying (handle)
2307 {
2308 if (handle == null)
2309 { return false; }
2310 const creature = this.ecs.get(handle, Component.creature);
2311 return !!mobDefinition(creature?.mobTypeId)?.flying;
2312 }
2313
2314 #entityDimensionId (entityId)
2315 {
2316 const handle = this.ecs.handleOf(entityId);
2317 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2318 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2319 }
2320
2321 #occupy (entityId, tileX, tileY, now = Date.now())
2322 {
2323 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2324 let set = this.occupancy.get(key);
2325 if (!set)
2326 {
2327 set = new Set();
2328 this.occupancy.set(key, set);
2329 }
2330 set.add(entityId);
2331 const handle = this.ecs.handleOf(entityId);
2332 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2333 if (position)
2334 { position.tileEnteredAt = now; }
2335 }
2336
2337 #vacate (entityId, tileX, tileY)
2338 {
2339 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2340 const set = this.occupancy.get(key);
2341 if (!set)
2342 { return; }
2343 set.delete(entityId);
2344 if (set.size === 0)
2345 { this.occupancy.delete(key); }
2346 }
2347
2348 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
2349 {
2350 const key = tileKey(tileX, tileY, dimensionId);
2351 const local = this.occupancy.get(key);
2352 if (local?.size)
2353 { return local.values().next().value; }
2354 const ghosts = this.ghostOccupancy.get(key);
2355 if (ghosts?.size)
2356 { return ghosts.values().next().value; }
2357 return null;
2358 }
2359
2360 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
2361 {
2362 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
2363 const key = tileKey(tileX, tileY, dim);
2364 const local = this.occupancy.get(key);
2365 if (local)
2366 {
2367 for (const id of local)
2368 {
2369 if (id !== entityId)
2370 { return true; }
2371 }
2372 }
2373 const ghosts = this.ghostOccupancy.get(key);
2374 if (ghosts)
2375 {
2376 for (const id of ghosts)
2377 {
2378 if (id !== entityId)
2379 { return true; }
2380 }
2381 }
2382 return false;
2383 }
2384
2385 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
2386 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2387 {
2388 return this.#anyOccupant(tileX, tileY, dimensionId);
2389 }
2390}
2391
2392function pickWanderGoalInRange (world, entityId, originX, originY, range)
2393{
2394 const radius = Math.max(0, range | 0);
2395 for (let attempt = 0; attempt < 24; attempt++)
2396 {
2397 const tileX = originX + randInt(-radius, radius);
2398 const tileY = originY + randInt(-radius, radius);
2399 if (!world.isClearStanding(entityId, tileX, tileY))
2400 { continue; }
2401 return { tileX, tileY };
2402 }
2403 return null;
2404}
2405
2406/**
2407 * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY).
2408 * When the destination is outside the window this becomes a chunk-step toward home.
2409 */
2410function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds)
2411{
2412 const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0));
2413 const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0));
2414 if (world.isClearStanding(entityId, idealX, idealY))
2415 { return { tileX: idealX, tileY: idealY }; }
2416 for (let radius = 1; radius <= 4; radius++)
2417 {
2418 for (let dy = -radius; dy <= radius; dy++)
2419 {
2420 for (let dx = -radius; dx <= radius; dx++)
2421 {
2422 if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2423 { continue; }
2424 const tileX = idealX + dx;
2425 const tileY = idealY + dy;
2426 if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY)
2427 { continue; }
2428 if (tileX === fromX && tileY === fromY)
2429 { continue; }
2430 if (!world.isClearStanding(entityId, tileX, tileY))
2431 { continue; }
2432 return { tileX, tileY };
2433 }
2434 }
2435 }
2436 return null;
2437}
2438
2439/** One random adjacent step so a stranded mob does not freeze in place. */
2440function queueLocalRandomWanderStep (world, entityId, position, path)
2441{
2442 const dirs = [
2443 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2444 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2445 ];
2446 for (let i = dirs.length - 1; i > 0; i--)
2447 {
2448 const j = Math.floor(Math.random() * (i + 1));
2449 const tmp = dirs[i];
2450 dirs[i] = dirs[j];
2451 dirs[j] = tmp;
2452 }
2453 for (const dir of dirs)
2454 {
2455 const nextX = position.tileX + dir.x;
2456 const nextY = position.tileY + dir.y;
2457 if (!world.isClearStanding(entityId, nextX, nextY))
2458 { continue; }
2459 path.tiles = [{ x: nextX, y: nextY }];
2460 return true;
2461 }
2462 return false;
2463}
2464
2465function hasDialogueBrowsers (origin)
2466{
2467 return originIsBusyPinned(origin);
2468}
2469
2470function randInt (min, max)
2471{
2472 return min + Math.floor(Math.random() * (max - min + 1));
2473}
2474
2475export function replicaNeededForOwnedChunks (ownedChunkKeys)
2476{
2477 const needed = new Set();
2478 for (const key of ownedChunkKeys)
2479 {
2480 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2481 for (let dy = -1; dy <= 1; dy++)
2482 {
2483 for (let dx = -1; dx <= 1; dx++)
2484 {
2485 if (dx === 0 && dy === 0)
2486 { continue; }
2487 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
2488 }
2489 }
2490 }
2491 return needed;
2492}