BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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