BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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