BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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