BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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