BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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