BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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