BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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