BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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