BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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