BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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