BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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