BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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