BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 52.4 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import {
3 chunkKey,
4 chunkToRegion,
5 parseChunkKey,
6 regionKey,
7 tileKey,
8 tileToChunk,
9 tileToLocal,
10 tileToRegion
11} from "../world/coordinates.js";
12import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
13import { closedNeighborEdges } from "../world/chunkFlags.js";
14import { EcsWorld } from "../ecs/world.js";
15import { Component } from "../ecs/components.js";
16import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
17import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18import { WorkerMessage } from "./protocol.js";
19import { collectSpawnRequests } from "./spawners.js";
20import { mobDefinition } from "../../../shared/definitions/mobs.js";
21import {
22 bagView,
23 applyBagView,
24 addGroundItem,
25 expireGroundItems,
26 groundItemsInChunk,
27 groundItemsInRegion,
28 handleItemCommand,
29 removeGroundItem,
30 publicGroundItem,
31 setGroundItemsForRegion
32} from "../items/bags.js";
33import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";
34import { publicSpellsView } from "../../../shared/spells/state.js";
35import {
36 handleGatherCommand,
37 stepGather,
38 cancelGather,
39 clearOreRespawnsForChunk,
40 clearTreeRespawnsForChunk,
41 clearPlantRespawnsForChunk
42} from "../gathering/service.js";
43import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
44import { handleAlchemyCommand } from "../alchemy/service.js";
45import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
46import {
47 applyRemoteMeleeSwing,
48 applyRemoteRangedShot,
49 attackProfileOf,
50 clearEngage,
51 engageTarget,
52 ensureMobCombat,
53 isUntargetable,
54 queueMeleeApproach,
55 queueStandInRangeApproach,
56 resolveCombatTarget,
57 stepAggression,
58 stepCombat
59} from "../combat/service.js";
60import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
61import { SkillId } from "../../../shared/definitions/skills.js";
62import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
63import {
64 STAMINA_REGEN_PER_SECOND,
65 STAMINA_XP_PER_POINT_SPENT,
66 staminaCostPerRunStep,
67 publicStaminaView
68} from "../../../shared/stamina/rules.js";
69import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
70import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
71import { stepStatusEffects } from "../statusEffects/service.js";
72
73export class WorkerWorld
74{
75 constructor (workerId)
76 {
77 this.workerId = workerId;
78 this.ecs = new EcsWorld();
79 this.chunks = new Map();
80 this.ownedRegions = new Set();
81 this.occupancy = new Map();
82 this.ghosts = new Map();
83 this.ghostOccupancy = new Map();
84 this.characterEntities = new Map();
85 this.frozen = new Set();
86 this.groundItems = new Map();
87 this.groundByTile = new Map();
88 this.oreRespawns = new Map();
89 this.treeRespawns = new Map();
90 this.pendingSpellImpacts = [];
91 this.settings = { ...DEFAULT_WORLD_SETTINGS };
92 this.activeRevisionId = 1;
93 }
94
95 handle (message)
96 {
97 switch (message.type)
98 {
99 case WorkerMessage.configure:
100 return this.#configure(message);
101 case WorkerMessage.assignRegion:
102 return this.#assignRegion(message);
103 case WorkerMessage.dropRegion:
104 return this.#dropRegion(message);
105 case WorkerMessage.replaceRegionChunks:
106 return this.#replaceRegionChunks(message);
107 case WorkerMessage.setReplicas:
108 return this.#setReplicas(message);
109 case WorkerMessage.setSimulatingChunks:
110 return this.#setSimulatingChunks(message);
111 case WorkerMessage.setGhosts:
112 return this.#setGhosts(message);
113 case WorkerMessage.spawn:
114 return this.#spawn(message);
115 case WorkerMessage.despawn:
116 return this.#despawn(message.entityId);
117 case WorkerMessage.despawnCharacter:
118 return this.#despawnCharacter(message.characterId);
119 case WorkerMessage.command:
120 return this.#command(message);
121 case WorkerMessage.stepMovement:
122 return this.#stepMovement(message.now);
123 case WorkerMessage.stepSystems:
124 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
125 case WorkerMessage.stepSpawners:
126 return { spawnRequests: collectSpawnRequests(this) };
127 case WorkerMessage.setGroundItems:
128 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
129 return { ok: true };
130 case WorkerMessage.inspectBag:
131 return this.#inspectBag(message.entityId);
132 case WorkerMessage.inspectSkills:
133 return this.#inspectSkills(message.entityId);
134 case WorkerMessage.inspectSpells:
135 return this.#inspectSpells(message.entityId);
136 case WorkerMessage.inspectStamina:
137 return this.#inspectStamina(message.entityId);
138 case WorkerMessage.applyBag:
139 return this.#applyBag(message.entityId, message.bag);
140 case WorkerMessage.applyAppearance:
141 return this.#applyAppearance(message.entityId, message.appearance);
142 case WorkerMessage.engageTarget:
143 return this.#engageTargetMessage(message);
144 case WorkerMessage.listTownGuardsNear:
145 return this.#listTownGuardsNear(message);
146 case WorkerMessage.updateFlight:
147 return this.#updateFlight(message.entityId, message.flight, message.now);
148 case WorkerMessage.chunkIsSimulating:
149 return this.chunkIsSimulating(message.tileX, message.tileY);
150 case WorkerMessage.applyTransfer:
151 return this.#applyTransfer(message);
152 case WorkerMessage.commitTransfer:
153 return this.#commitTransfer(message.entityId);
154 case WorkerMessage.abortTransfer:
155 return this.#abortTransfer(message.entityId);
156 case WorkerMessage.snapshotChunk:
157 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly);
158 case WorkerMessage.listLoaders:
159 return this.#listLoaders();
160 case WorkerMessage.listPublicEntities:
161 return this.#listPublicEntities();
162 case WorkerMessage.entitiesInRegion:
163 return this.#entitiesInRegion(message.regionX, message.regionY);
164 case WorkerMessage.inspect:
165 return publicEntityView(this.ecs, message.entityId);
166 case WorkerMessage.remoteCombatEngage:
167 return this.#remoteCombatEngage(message);
168 case WorkerMessage.applyRemoteMelee:
169 return this.#applyRemoteMelee(message);
170 case WorkerMessage.applyRemoteRanged:
171 return this.#applyRemoteRanged(message);
172 case WorkerMessage.applyCombatHitXp:
173 return this.#applyCombatHitXp(message);
174 case WorkerMessage.spawnCorpseDrops:
175 return this.#spawnCorpseDrops(message);
176 case WorkerMessage.applyRespawn:
177 return this.#applyRespawn(message);
178 case WorkerMessage.clearCombat:
179 clearEngage(this.ecs, message.entityId);
180 for (const entity of this.ecs.query(Component.combat))
181 {
182 if (entity.combat.targetEntityId === message.targetEntityId)
183 { entity.combat.targetEntityId = null; }
184 }
185 return { ok: true };
186 case WorkerMessage.setItemLastSales:
187 {
188 this.itemLastSales = new Map();
189 for (const [key, sale] of Object.entries(message.sales ?? {}))
190 { this.itemLastSales.set(Number(key), sale); }
191 return { ok: true };
192 }
193 case WorkerMessage.stationExchangeClerk:
194 return this.#stationExchangeClerk(message);
195 case WorkerMessage.releaseExchangeClerk:
196 return this.#releaseExchangeClerk(message);
197 default:
198 throw new Error(`Unknown worker message ${message.type}`);
199 }
200 }
201
202 ownsRegion (regionX, regionY)
203 {
204 return this.ownedRegions.has(regionKey(regionX, regionY));
205 }
206
207 requireOwnedEntity (sessionId, characterId)
208 {
209 return this.#requireOwnedEntity(sessionId, characterId);
210 }
211
212 chunkData (chunkX, chunkY)
213 {
214 return this.#chunkData(chunkX, chunkY);
215 }
216
217 #configure (message)
218 {
219 if (message.settings)
220 { this.settings = { ...this.settings, ...message.settings }; }
221 if (message.activeRevisionId != null)
222 { this.activeRevisionId = message.activeRevisionId; }
223 return { ok: true };
224 }
225
226 #assignRegion (message)
227 {
228 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
229 for (const chunk of message.chunks ?? [])
230 {
231 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
232 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
233 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
234 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
235 data: cloneChunkData(chunk.data),
236 simulating: false,
237 replica: false
238 });
239 }
240 return { ok: true };
241 }
242
243 #replaceRegionChunks (message)
244 {
245 for (const chunk of message.chunks ?? [])
246 {
247 const key = chunkKey(chunk.chunkX, chunk.chunkY);
248 const existing = this.chunks.get(key);
249 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
250 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
251 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
252 this.chunks.set(key, {
253 data: cloneChunkData(chunk.data),
254 simulating: existing?.simulating ?? false,
255 replica: existing?.replica ?? false
256 });
257 }
258 return { ok: true };
259 }
260
261 #dropRegion (message)
262 {
263 const dropped = [];
264 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
265 {
266 const components = record.payload?.components;
267 if (components?.creature && !components?.character && components?.health)
268 { components.health.current = components.health.max; }
269 dropped.push(record);
270 this.#destroyEntity(record.entityId);
271 }
272 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
273 for (const item of groundItems)
274 { removeGroundItem(this, item.groundItemId); }
275 for (const [key, chunk] of [...this.chunks.entries()])
276 {
277 const { chunkX, chunkY } = parseChunkKey(key);
278 if (chunk.replica)
279 { continue; }
280 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
281 {
282 clearOreRespawnsForChunk(this, chunkX, chunkY);
283 clearTreeRespawnsForChunk(this, chunkX, chunkY);
284 clearPlantRespawnsForChunk(this, chunkX, chunkY);
285 this.chunks.delete(key);
286 }
287 }
288 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
289 return { dropped, groundItems };
290 }
291
292 #setReplicas (message)
293 {
294 const keep = new Set();
295 for (const chunk of message.chunks ?? [])
296 {
297 const key = chunkKey(chunk.chunkX, chunk.chunkY);
298 keep.add(key);
299 const existing = this.chunks.get(key);
300 if (existing && !existing.replica)
301 { continue; }
302 this.chunks.set(key, {
303 data: cloneChunkData(chunk.data),
304 simulating: false,
305 replica: true
306 });
307 }
308 for (const [key, chunk] of [...this.chunks.entries()])
309 {
310 if (chunk.replica && !keep.has(key))
311 { this.chunks.delete(key); }
312 }
313 return { ok: true };
314 }
315
316 #setSimulatingChunks (message)
317 {
318 const simulating = new Set(message.chunkKeys ?? []);
319 for (const [key, chunk] of this.chunks)
320 {
321 if (chunk.replica)
322 {
323 chunk.simulating = false;
324 continue;
325 }
326 chunk.simulating = simulating.has(key);
327 }
328 return { ok: true };
329 }
330
331 #setGhosts (message)
332 {
333 this.ghosts.clear();
334 this.ghostOccupancy.clear();
335 for (const ghost of message.ghosts ?? [])
336 {
337 this.ghosts.set(ghost.entityId, ghost);
338 const key = tileKey(ghost.tileX, ghost.tileY);
339 let set = this.ghostOccupancy.get(key);
340 if (!set)
341 {
342 set = new Set();
343 this.ghostOccupancy.set(key, set);
344 }
345 set.add(ghost.entityId);
346 }
347 return { ok: true };
348 }
349
350 #spawn (message)
351 {
352 const entityId = deserializeEntity(this.ecs, message);
353 const handle = this.ecs.handleOf(entityId);
354 const position = this.ecs.get(handle, Component.position);
355 if (!position)
356 {
357 this.ecs.destroy(handle);
358 throw new Error("Spawned entity is missing position.");
359 }
360 const flying = this.#isFlying(handle);
361 if (!flying)
362 {
363 if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))
364 {
365 this.ecs.destroy(handle);
366 const error = new Error("That tile is occupied.");
367 error.userFacing = true;
368 throw error;
369 }
370 this.#occupy(entityId, position.tileX, position.tileY);
371 }
372 const creature = this.ecs.get(handle, Component.creature);
373 const def = creature ? mobDefinition(creature.mobTypeId) : null;
374 if (def?.freeFlight)
375 { ensureFlightComponent(this.ecs, handle, position, def); }
376 const character = this.ecs.get(handle, Component.character);
377 if (character?.characterId)
378 { this.characterEntities.set(character.characterId, entityId); }
379 return publicEntityView(this.ecs, entityId);
380 }
381
382 #despawn (entityId)
383 {
384 return this.#destroyEntity(entityId);
385 }
386
387 #despawnCharacter (characterId)
388 {
389 releaseShopBrowsersForCharacter(this, characterId);
390 const entityId = this.characterEntities.get(characterId);
391 if (!entityId)
392 { return null; }
393 return this.#destroyEntity(entityId);
394 }
395
396 #destroyEntity (entityId)
397 {
398 const handle = this.ecs.handleOf(entityId);
399 if (handle == null)
400 { return null; }
401 const view = publicEntityView(this.ecs, entityId);
402 const position = this.ecs.get(handle, Component.position);
403 const character = this.ecs.get(handle, Component.character);
404 if (position && !this.#isFlying(handle))
405 { this.#vacate(entityId, position.tileX, position.tileY); }
406 if (character?.characterId)
407 { this.characterEntities.delete(character.characterId); }
408 this.frozen.delete(entityId);
409 this.ecs.destroy(handle);
410 return view;
411 }
412
413 #command (message)
414 {
415 const { sessionId, command } = message;
416 switch (command.type)
417 {
418 case "move-to":
419 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
420 return { events: [] };
421 case "set-gait":
422 return this.#setGait(sessionId, command.characterId, command.gait);
423 case "attack":
424 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
425 case "cancel-attack":
426 return this.#cancelAttack(sessionId, command.characterId);
427 case "interact":
428 return this.#interact(sessionId, command.characterId, command.targetEntityId);
429 case "follow":
430 return this.#follow(sessionId, command.characterId, command.targetEntityId);
431 case "cancel-follow":
432 return this.#cancelFollow(sessionId, command.characterId);
433 case "set-spell-favorite":
434 case "set-spell-autocast":
435 case "arm-spell":
436 case "cancel-arm-spell":
437 case "cast-spell-tile":
438 case "cast-spell-entity":
439 case "read-spellbook":
440 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
441 default:
442 {
443 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
444 if (gather)
445 { return gather; }
446 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
447 if (craft)
448 { return craft; }
449 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
450 if (shop)
451 { return shop; }
452 const alchemy = handleAlchemyCommand(this, sessionId, command);
453 if (alchemy)
454 { return alchemy; }
455 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
456 return result ?? { events: [] };
457 }
458 }
459 }
460
461 #spawnCorpseDrops (message)
462 {
463 const events = [];
464 for (const drop of message.drops ?? [])
465 {
466 const item = {
467 groundItemId: drop.groundItemId,
468 tileX: message.tileX,
469 tileY: message.tileY,
470 stack: { itemId: drop.itemId, quantity: 1 },
471 droppedAt: message.now,
472 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
473 source: "player-death",
474 droppedByCharacterId: message.characterId
475 };
476 addGroundItem(this, item);
477 events.push({
478 type: "ground-item-appear",
479 ...publicGroundItem(item),
480 stack: item.stack,
481 droppedAt: item.droppedAt,
482 source: item.source,
483 droppedByCharacterId: item.droppedByCharacterId,
484 expiresAt: item.expiresAt
485 });
486 }
487 return { events };
488 }
489
490 #applyRespawn (message)
491 {
492 const handle = this.ecs.handleOf(message.entityId);
493 if (handle == null || !this.ecs.has(handle, Component.dead))
494 { return { accepted: false }; }
495 const position = this.ecs.get(handle, Component.position);
496 const fromTileX = position.tileX;
497 const fromTileY = position.tileY;
498 const health = this.ecs.get(handle, Component.health);
499 const stamina = this.ecs.get(handle, Component.stamina);
500 if (health)
501 {
502 health.max = message.maxHealth;
503 health.current = message.maxHealth;
504 }
505 if (stamina)
506 {
507 stamina.max = message.maxStamina;
508 stamina.current = message.maxStamina;
509 }
510 else
511 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
512 this.ecs.remove(handle, Component.dead);
513 clearEngage(this.ecs, message.entityId);
514 const path = this.ecs.get(handle, Component.path);
515 if (path)
516 { path.tiles = []; }
517 clearFollow(this.ecs, message.entityId);
518
519 const destRegionX = tileToRegion(message.tileX);
520 const destRegionY = tileToRegion(message.tileY);
521 if (!this.ownsRegion(destRegionX, destRegionY))
522 {
523 this.frozen.add(message.entityId);
524 return {
525 accepted: true,
526 transferRequest: {
527 entityId: message.entityId,
528 fromTileX,
529 fromTileY,
530 destTileX: message.tileX,
531 destTileY: message.tileY,
532 toRegionX: destRegionX,
533 toRegionY: destRegionY,
534 payload: serializeEntity(this.ecs, message.entityId)
535 }
536 };
537 }
538 if (!this.isEnterable(message.tileX, message.tileY))
539 { return { accepted: false }; }
540 this.#vacate(message.entityId, fromTileX, fromTileY);
541 position.tileX = message.tileX;
542 position.tileY = message.tileY;
543 this.#occupy(message.entityId, position.tileX, position.tileY);
544 return {
545 accepted: true,
546 event: {
547 type: "entity-move",
548 entityId: message.entityId,
549 fromTileX,
550 fromTileY,
551 tileX: position.tileX,
552 tileY: position.tileY,
553 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
554 }
555 };
556 }
557
558 #inspectBag (entityId)
559 {
560 const handle = this.ecs.handleOf(entityId);
561 if (handle == null)
562 { return null; }
563 return bagView(this.ecs, handle);
564 }
565
566 #inspectSkills (entityId)
567 {
568 const handle = this.ecs.handleOf(entityId);
569 if (handle == null)
570 { return null; }
571 const skills = this.ecs.get(handle, Component.skills);
572 if (!skills?.xp)
573 { return null; }
574 return skills;
575 }
576
577 #inspectSpells (entityId)
578 {
579 const handle = this.ecs.handleOf(entityId);
580 if (handle == null)
581 { return null; }
582 const spells = this.ecs.get(handle, Component.spells);
583 const skills = this.ecs.get(handle, Component.skills);
584 const casting = this.ecs.get(handle, Component.spellcasting);
585 if (!spells)
586 { return null; }
587 return {
588 spells: publicSpellsView(spells, skills),
589 autoCast: !!spells.autoCast,
590 armedSpellId: casting?.armedSpellId ?? null
591 };
592 }
593
594 #inspectStamina (entityId)
595 {
596 const handle = this.ecs.handleOf(entityId);
597 if (handle == null)
598 { return null; }
599 const stamina = this.ecs.get(handle, Component.stamina);
600 const movement = this.ecs.get(handle, Component.movement);
601 if (!stamina)
602 { return null; }
603 return {
604 ...publicStaminaView(stamina),
605 gait: movement?.gait ?? GAIT.walk
606 };
607 }
608
609 #applyBag (entityId, bag)
610 {
611 const handle = this.ecs.handleOf(entityId);
612 if (handle == null)
613 { return null; }
614 return applyBagView(this.ecs, handle, bag);
615 }
616
617 #applyAppearance (entityId, appearancePatch)
618 {
619 const handle = this.ecs.handleOf(entityId);
620 if (handle == null)
621 { return null; }
622 const appearance = this.ecs.get(handle, Component.appearance);
623 if (!appearance)
624 { return null; }
625 Object.assign(appearance, appearancePatch ?? {});
626 return publicEntityView(this.ecs, entityId);
627 }
628
629 #updateFlight (entityId, flightPatch, now = Date.now())
630 {
631 const handle = this.ecs.handleOf(entityId);
632 if (handle == null)
633 { return null; }
634 let flight = this.ecs.get(handle, Component.flight);
635 if (!flight)
636 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
637 else
638 { Object.assign(flight, flightPatch); }
639 const position = this.ecs.get(handle, Component.position);
640 const movement = this.ecs.get(handle, Component.movement);
641 const fromTileX = position.tileX;
642 const fromTileY = position.tileY;
643 const tileX = Math.floor(flight.x);
644 const tileY = Math.floor(flight.y);
645 position.tileX = tileX;
646 position.tileY = tileY;
647 const destRegionX = tileToRegion(tileX);
648 const destRegionY = tileToRegion(tileY);
649 if (!this.ownsRegion(destRegionX, destRegionY))
650 {
651 this.frozen.add(entityId);
652 return {
653 transferRequest: {
654 type: "transfer-request",
655 entityId,
656 fromTileX,
657 fromTileY,
658 destTileX: tileX,
659 destTileY: tileY,
660 toRegionX: destRegionX,
661 toRegionY: destRegionY
662 }
663 };
664 }
665 const dt = flight.lastAt && now > flight.lastAt
666 ? Math.min(0.25, (now - flight.lastAt) / 1000)
667 : 1 / 20;
668 return {
669 event: {
670 type: "entity-move",
671 entityId,
672 fromTileX,
673 fromTileY,
674 tileX,
675 tileY,
676 worldX: flight.x,
677 worldY: flight.y,
678 gait: movement?.gait ?? "walk",
679 lerpMs: Math.max(50, Math.round(dt * 1000)),
680 freeFlight: true
681 }
682 };
683 }
684
685 #moveTo (sessionId, characterId, tileX, tileY)
686 {
687 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
688 if (this.frozen.has(entityId))
689 { return; }
690 clearEngage(this.ecs, entityId);
691 clearFollow(this.ecs, entityId);
692 cancelGather(this.ecs, handle);
693 const casting = this.ecs.get(handle, Component.spellcasting);
694 if (casting)
695 { casting.pendingCast = null; }
696 const position = this.ecs.get(handle, Component.position);
697 const movement = this.ecs.get(handle, Component.movement);
698 let path = this.ecs.get(handle, Component.path);
699 if (!path)
700 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
701 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
702 path.tiles = findPath(
703 position.tileX,
704 position.tileY,
705 tileX,
706 tileY,
707 (x, y) => this.walkableFor(entityId, x, y),
708 bounds.minX,
709 bounds.minY,
710 bounds.maxX,
711 bounds.maxY,
712 { preferVertical: true }
713 );
714 movement.walkCarry = 0;
715 }
716
717 #attack (sessionId, characterId, targetEntityId, now)
718 {
719 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
720 if (targetEntityId === entityId)
721 {
722 const error = new Error("Cannot attack yourself.");
723 error.userFacing = true;
724 throw error;
725 }
726 const target = resolveCombatTarget(this, targetEntityId);
727 if (!target)
728 {
729 const error = new Error("Target is not here.");
730 error.userFacing = true;
731 throw error;
732 }
733 if (target.health && target.health.current <= 0)
734 {
735 const error = new Error("That cannot be attacked.");
736 error.userFacing = true;
737 throw error;
738 }
739 if (!this.ecs.get(handle, Component.combat))
740 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
741 clearFollow(this.ecs, entityId);
742 cancelGather(this.ecs, handle);
743 engageTarget(this.ecs, entityId, targetEntityId, now);
744 const position = this.ecs.get(handle, Component.position);
745 const profile = attackProfileOf(this.ecs, handle);
746 if (position && target.pos)
747 {
748 if (profile.mode === "ranged")
749 {
750 queueStandInRangeApproach(
751 this,
752 entityId,
753 handle,
754 position,
755 target.pos.tileX,
756 target.pos.tileY,
757 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
758 1
759 );
760 }
761 else if (profile.mode === "melee")
762 {
763 queueMeleeApproach(this, entityId, handle, position, target.pos);
764 }
765 }
766 return { events: [] };
767 }
768
769 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
770 {
771 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
772 void attackerEntityId;
773 void targetEntityId;
774 void now;
775 return { events: [] };
776 }
777
778 #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })
779 {
780 if (this.ecs.handleOf(attackerEntityId) == null)
781 { return { ok: false }; }
782 engageTarget(this.ecs, attackerEntityId, targetEntityId, now);
783 return { ok: true };
784 }
785
786 /**
787 * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).
788 * Optionally restrict to one spawnerId.
789 */
790 #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })
791 {
792 const guards = [];
793 for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))
794 {
795 if (!entity.spawnOrigin?.townGuard)
796 { continue; }
797 if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)
798 { continue; }
799 const originX = entity.spawnOrigin.originTileX;
800 const originY = entity.spawnOrigin.originTileY;
801 const range = entity.spawnOrigin.wanderRangeTiles | 0;
802 const dx = Math.abs(tileX - originX);
803 const dy = Math.abs(tileY - originY);
804 if (Math.max(dx, dy) > range)
805 { continue; }
806 const health = this.ecs.get(entity.handle, Component.health);
807 if (health && health.current <= 0)
808 { continue; }
809 if (this.ecs.has(entity.handle, Component.dead))
810 { continue; }
811 guards.push({
812 entityId: entity.entityId,
813 spawnerId: entity.spawnOrigin.spawnerId,
814 busy: entity.combat?.targetEntityId != null
815 });
816 if (guards.length >= limit)
817 { break; }
818 }
819 return { guards };
820 }
821
822 #applyRemoteMelee (payload)
823 {
824 return applyRemoteMeleeSwing(this, payload);
825 }
826
827 #applyRemoteRanged (payload)
828 {
829 return applyRemoteRangedShot(this, payload);
830 }
831
832 #applyCombatHitXp ({ entityId, profile, damage })
833 {
834 const handle = this.ecs.handleOf(entityId);
835 if (handle == null)
836 { return { events: [] }; }
837 const character = this.ecs.get(handle, Component.character);
838 if (!character)
839 { return { events: [] }; }
840 const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage);
841 if (!xpAward)
842 { return { events: [] }; }
843 return {
844 events: [{
845 type: "skills-updated",
846 entityId,
847 characterId: character.characterId,
848 skills: xpAward.view,
849 stored: xpAward.stored,
850 levelUps: xpAward.levelUps ?? []
851 }]
852 };
853 }
854
855 #cancelAttack (sessionId, characterId)
856 {
857 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
858 clearEngage(this.ecs, entityId);
859 return { events: [] };
860 }
861
862 #interact (sessionId, characterId, targetEntityId)
863 {
864 this.#requireOwnedEntity(sessionId, characterId);
865 const targetHandle = this.ecs.handleOf(targetEntityId);
866 if (targetHandle == null)
867 {
868 const error = new Error("Target is not here.");
869 error.userFacing = true;
870 throw error;
871 }
872 if (isUntargetable(this.ecs, targetHandle))
873 {
874 const error = new Error("Nothing to say.");
875 error.userFacing = true;
876 throw error;
877 }
878 const creature = this.ecs.get(targetHandle, Component.creature);
879 const def = creature ? mobDefinition(creature.mobTypeId) : null;
880 const shop = this.ecs.get(targetHandle, Component.shop);
881 if (shopHasInterface(shop))
882 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
883 if (!def?.talkable)
884 {
885 const error = new Error("They have nothing to say.");
886 error.userFacing = true;
887 throw error;
888 }
889 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
890 return { events: [] };
891 }
892
893 #follow (sessionId, characterId, targetEntityId)
894 {
895 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
896 const targetHandle = this.ecs.handleOf(targetEntityId);
897 if (targetHandle == null)
898 {
899 const error = new Error("Target is not here.");
900 error.userFacing = true;
901 throw error;
902 }
903 if (targetEntityId === entityId)
904 {
905 const error = new Error("Cannot follow yourself.");
906 error.userFacing = true;
907 throw error;
908 }
909 if (!this.ecs.get(targetHandle, Component.position))
910 {
911 const error = new Error("That cannot be followed.");
912 error.userFacing = true;
913 throw error;
914 }
915 clearEngage(this.ecs, entityId);
916 setFollow(this.ecs, entityId, targetEntityId);
917 const path = this.ecs.get(handle, Component.path);
918 if (path)
919 { path.tiles = []; }
920 return { events: [] };
921 }
922
923 #cancelFollow (sessionId, characterId)
924 {
925 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
926 clearFollow(this.ecs, entityId);
927 return { events: [] };
928 }
929
930 #setGait (sessionId, characterId, gait)
931 {
932 if (gait !== GAIT.walk && gait !== GAIT.run)
933 {
934 const error = new Error("Gait must be walk or run.");
935 error.userFacing = true;
936 throw error;
937 }
938 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
939 const movement = this.ecs.get(handle, Component.movement);
940 const stamina = this.ecs.get(handle, Component.stamina);
941 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
942 {
943 const error = new Error("You are too exhausted to run.");
944 error.userFacing = true;
945 throw error;
946 }
947 movement.gait = gait;
948 const character = this.ecs.get(handle, Component.character);
949 return {
950 events: character
951 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
952 : []
953 };
954 }
955
956 #staminaEvent (handle, characterId, gait = null)
957 {
958 const stamina = this.ecs.get(handle, Component.stamina);
959 const movement = this.ecs.get(handle, Component.movement);
960 return {
961 type: "stamina",
962 characterId,
963 ...publicStaminaView(stamina),
964 gait: gait ?? movement?.gait ?? GAIT.walk
965 };
966 }
967
968 #consumeRunStamina (handle, events)
969 {
970 const character = this.ecs.get(handle, Component.character);
971 if (!character)
972 { return; }
973 let stamina = this.ecs.get(handle, Component.stamina);
974 if (!stamina)
975 {
976 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
977 }
978 const skills = this.ecs.get(handle, Component.skills);
979 syncPlayerStamina(this.ecs, handle);
980 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
981 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
982 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
983 let skillsChanged = false;
984 const levelUps = [];
985 while (stamina.xpDebt >= 1 && skills?.xp)
986 {
987 stamina.xpDebt -= 1;
988 const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT);
989 if (result.changed)
990 {
991 skillsChanged = true;
992 syncPlayerStamina(this.ecs, handle);
993 }
994 if (result.levelUp)
995 { levelUps.push(result.levelUp); }
996 }
997 const movement = this.ecs.get(handle, Component.movement);
998 if (stamina.current <= 0 && movement)
999 {
1000 stamina.current = 0;
1001 movement.gait = GAIT.walk;
1002 }
1003 events.push(this.#staminaEvent(handle, character.characterId));
1004 if (skillsChanged)
1005 {
1006 events.push({
1007 type: "skills-updated",
1008 entityId: this.ecs.entityIdOf(handle),
1009 characterId: character.characterId,
1010 skills: publicSkillsView(skills),
1011 stored: storedSkillXp(skills),
1012 levelUps
1013 });
1014 }
1015 }
1016
1017 #regenStamina (dt, events)
1018 {
1019 if (!(dt > 0))
1020 { return; }
1021 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
1022 {
1023 const { handle, character, stamina, movement } = entity;
1024 if (this.ecs.has(handle, Component.dead))
1025 { continue; }
1026 // Run gait only blocks regen while actually stepping along a path.
1027 const path = this.ecs.get(handle, Component.path);
1028 if (movement.gait === GAIT.run && path?.tiles?.length)
1029 { continue; }
1030 syncPlayerStamina(this.ecs, handle);
1031 const before = Number(stamina.current) || 0;
1032 if (before >= stamina.max)
1033 { continue; }
1034 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
1035 const after = Number(stamina.current) || 0;
1036 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1037 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
1038 { events.push(this.#staminaEvent(handle, character.characterId)); }
1039 }
1040 }
1041
1042 #requireOwnedEntity (sessionId, characterId)
1043 {
1044 const entityId = this.characterEntities.get(characterId);
1045 if (!entityId)
1046 {
1047 const error = new Error("Character is not in the world.");
1048 error.userFacing = true;
1049 throw error;
1050 }
1051 const handle = this.ecs.handleOf(entityId);
1052 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
1053 if (!identity || identity.sessionId !== sessionId)
1054 {
1055 const error = new Error("Character is not in the world.");
1056 error.userFacing = true;
1057 throw error;
1058 }
1059 if (this.ecs.has(handle, Component.dead))
1060 {
1061 const error = new Error("You are dead.");
1062 error.userFacing = true;
1063 throw error;
1064 }
1065 return { handle, entityId };
1066 }
1067
1068 #stepSystems (now = Date.now(), dt = 1 / 20)
1069 {
1070 const events = [];
1071 const transferRequests = [];
1072 this.#regenStamina(dt, events);
1073 events.push(...stepStatusEffects(this, now, dt));
1074 const flight = stepFreeFlight(this, now);
1075 for (const event of flight)
1076 {
1077 if (event.type === "transfer-request")
1078 {
1079 const payload = serializeEntity(this.ecs, event.entityId);
1080 transferRequests.push({
1081 entityId: event.entityId,
1082 fromTileX: event.fromTileX,
1083 fromTileY: event.fromTileY,
1084 destTileX: event.destTileX,
1085 destTileY: event.destTileY,
1086 toRegionX: event.toRegionX,
1087 toRegionY: event.toRegionY,
1088 payload
1089 });
1090 continue;
1091 }
1092 events.push(event);
1093 }
1094 stepAggression(this, now);
1095 events.push(...stepCombat(this, now));
1096 events.push(...stepPendingSpellCast(this, now));
1097 events.push(...processSpellImpacts(this, now));
1098 events.push(...stepSpellAutoCast(this, now));
1099 events.push(...tickSpellLights(this, now));
1100 stepFollow(this);
1101 const gather = stepGather(this, now);
1102 events.push(...gather.events);
1103 for (const entry of gather.privates ?? [])
1104 {
1105 events.push({
1106 type: "inventory",
1107 characterId: entry.characterId,
1108 ...entry.bag
1109 });
1110 }
1111 const craft = stepCrafting(this, now);
1112 events.push(...craft.events);
1113 for (const entry of craft.privates ?? [])
1114 {
1115 events.push({
1116 type: "inventory",
1117 characterId: entry.characterId,
1118 ...entry.bag
1119 });
1120 }
1121 return { events, transferRequests };
1122 }
1123
1124 #stepMovement (now = Date.now())
1125 {
1126 const events = expireGroundItems(this, now);
1127 const transferRequests = [];
1128 events.push(...pruneShopBrowsers(this));
1129 this.#queueAmbientWander();
1130 this.#queueSpawnerWander();
1131 this.#queueExchangeStations();
1132 for (const entity of this.ecs.query(Component.position, Component.movement))
1133 {
1134 const { handle, entityId, position, movement } = entity;
1135 if (this.ecs.has(handle, Component.dead))
1136 { continue; }
1137 if (this.ecs.has(handle, Component.flight))
1138 { continue; }
1139 const path = this.ecs.get(handle, Component.path);
1140 const tiles = path?.tiles;
1141 if (this.frozen.has(entityId) || !tiles?.length)
1142 {
1143 if (path)
1144 { path.stuckSince = null; }
1145 continue;
1146 }
1147 if (!this.chunkIsSimulating(position.tileX, position.tileY))
1148 { continue; }
1149
1150 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1151
1152 const stamina = this.ecs.get(handle, Component.stamina);
1153 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1154 { movement.gait = GAIT.walk; }
1155 const isWalk = movement.gait !== GAIT.run;
1156 if (isWalk)
1157 {
1158 movement.walkCarry = (movement.walkCarry + 1) % 2;
1159 if (movement.walkCarry !== 0)
1160 { continue; }
1161 }
1162
1163 const next = tiles[0];
1164 if (!next)
1165 { continue; }
1166 const destRegionX = tileToRegion(next.x);
1167 const destRegionY = tileToRegion(next.y);
1168 if (!this.ownsRegion(destRegionX, destRegionY))
1169 {
1170 this.frozen.add(entityId);
1171 transferRequests.push({
1172 entityId,
1173 fromTileX: position.tileX,
1174 fromTileY: position.tileY,
1175 destTileX: next.x,
1176 destTileY: next.y,
1177 toRegionX: destRegionX,
1178 toRegionY: destRegionY,
1179 payload: serializeEntity(this.ecs, entityId)
1180 });
1181 continue;
1182 }
1183
1184 if (!this.walkableFor(entityId, next.x, next.y))
1185 {
1186 const combat = this.ecs.get(handle, Component.combat);
1187 if (combat?.targetEntityId != null)
1188 {
1189 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1190 const targetPos = targetHandle != null
1191 ? this.ecs.get(targetHandle, Component.position)
1192 : null;
1193 const blockedByTarget = targetPos
1194 && next.x === targetPos.tileX
1195 && next.y === targetPos.tileY;
1196 if (!blockedByTarget)
1197 { path.tiles = []; }
1198 }
1199 continue;
1200 }
1201
1202 const fromTileX = position.tileX;
1203 const fromTileY = position.tileY;
1204 const flying = this.#isFlying(handle);
1205 if (!flying)
1206 { this.#vacate(entityId, fromTileX, fromTileY); }
1207 position.tileX = next.x;
1208 position.tileY = next.y;
1209 tiles.shift();
1210 if (!flying)
1211 { this.#occupy(entityId, position.tileX, position.tileY); }
1212 path.stuckSince = now;
1213 path.stuckTileX = position.tileX;
1214 path.stuckTileY = position.tileY;
1215 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1216 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1217 if (!isWalk)
1218 { this.#consumeRunStamina(handle, events); }
1219 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1220 }
1221 return { events, transferRequests };
1222 }
1223
1224 /**
1225 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1226 * recompute A* to the same goal (around whoever is blocking the old route).
1227 */
1228 #repathIfNavigationStuck (entityId, position, movement, path, now)
1229 {
1230 if (!path?.tiles?.length)
1231 {
1232 path.stuckSince = null;
1233 return;
1234 }
1235 if (
1236 path.stuckSince == null
1237 || path.stuckTileX !== position.tileX
1238 || path.stuckTileY !== position.tileY
1239 )
1240 {
1241 path.stuckSince = now;
1242 path.stuckTileX = position.tileX;
1243 path.stuckTileY = position.tileY;
1244 return;
1245 }
1246 if (now - path.stuckSince < NAV_STUCK_MS)
1247 { return; }
1248
1249 const goal = path.tiles[path.tiles.length - 1];
1250 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1251 {
1252 path.tiles = [];
1253 path.stuckSince = null;
1254 return;
1255 }
1256 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1257 const stuckHandle = this.ecs.handleOf(entityId);
1258 path.tiles = findPath(
1259 position.tileX,
1260 position.tileY,
1261 goal.x,
1262 goal.y,
1263 (x, y) => this.isClearStanding(entityId, x, y),
1264 bounds.minX,
1265 bounds.minY,
1266 bounds.maxX,
1267 bounds.maxY,
1268 { preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character) }
1269 );
1270 path.stuckSince = now;
1271 path.stuckTileX = position.tileX;
1272 path.stuckTileY = position.tileY;
1273 if (movement)
1274 { movement.walkCarry = 0; }
1275 }
1276
1277 #queueAmbientWander ()
1278 {
1279 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1280 {
1281 const def = mobDefinition(entity.creature.mobTypeId);
1282 if (!def?.ambient || def.freeFlight)
1283 { continue; }
1284 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1285 { continue; }
1286 const path = this.ecs.get(entity.handle, Component.path);
1287 if (!path)
1288 { continue; }
1289 if (path.tiles?.length)
1290 { continue; }
1291 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1292 { continue; }
1293 if (Math.random() > 0.35)
1294 { continue; }
1295 const dirs = [
1296 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1297 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1298 ];
1299 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1300 const nextX = entity.position.tileX + dir.x;
1301 const nextY = entity.position.tileY + dir.y;
1302 if (!this.isClearStanding(entity.entityId, nextX, nextY))
1303 { continue; }
1304 path.tiles = [{ x: nextX, y: nextY }];
1305 }
1306 }
1307
1308 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
1309 #queueSpawnerWander ()
1310 {
1311 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1312 {
1313 const combat = this.ecs.get(entity.handle, Component.combat);
1314 if (combat?.targetEntityId != null)
1315 { continue; }
1316 const follow = this.ecs.get(entity.handle, Component.follow);
1317 if (follow?.targetEntityId != null)
1318 { continue; }
1319 const shop = this.ecs.get(entity.handle, Component.shop);
1320 if (shopHasActiveBrowsers(shop))
1321 { continue; }
1322 const origin = entity.spawnOrigin;
1323 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1324 { continue; }
1325 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1326 if (def?.freeFlight)
1327 { continue; }
1328 const path = this.ecs.get(entity.handle, Component.path);
1329 if (!path || path.tiles?.length)
1330 { continue; }
1331 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1332 { continue; }
1333 if (Math.random() > 0.4)
1334 { continue; }
1335
1336 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1337 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1338 const range = Math.max(0, origin.wanderRangeTiles | 0);
1339 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1340 if (!goal)
1341 { continue; }
1342 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1343 { continue; }
1344 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1345 const tiles = findPath(
1346 entity.position.tileX,
1347 entity.position.tileY,
1348 goal.tileX,
1349 goal.tileY,
1350 (x, y) => this.walkableFor(entity.entityId, x, y),
1351 bounds.minX,
1352 bounds.minY,
1353 bounds.maxX,
1354 bounds.maxY
1355 );
1356 if (!tiles?.length)
1357 { continue; }
1358 path.tiles = tiles;
1359 }
1360 }
1361
1362 /**
1363 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1364 * message: { stationTileX, stationTileY }
1365 */
1366 #stationExchangeClerk (message)
1367 {
1368 const stationTileX = message.stationTileX | 0;
1369 const stationTileY = message.stationTileY | 0;
1370 if (!this.isEnterable(stationTileX, stationTileY))
1371 { return { ok: false, reason: "blocked" }; }
1372
1373 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1374 {
1375 if (!entity.spawnOrigin?.centralExchange)
1376 { continue; }
1377 if (
1378 Number.isInteger(entity.spawnOrigin.stationTileX)
1379 && entity.spawnOrigin.stationTileX === stationTileX
1380 && entity.spawnOrigin.stationTileY === stationTileY
1381 )
1382 { return { ok: true, entityId: entity.entityId, already: true }; }
1383 }
1384
1385 let best = null;
1386 let bestDist = Infinity;
1387 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1388 {
1389 if (!entity.spawnOrigin?.centralExchange)
1390 { continue; }
1391 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1392 { continue; }
1393 const dist = Math.max(
1394 Math.abs(entity.position.tileX - stationTileX),
1395 Math.abs(entity.position.tileY - stationTileY)
1396 );
1397 if (dist < bestDist)
1398 {
1399 bestDist = dist;
1400 best = entity;
1401 }
1402 }
1403 if (!best)
1404 { return { ok: false, reason: "none-available" }; }
1405
1406 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1407 const tiles = findPath(
1408 best.position.tileX,
1409 best.position.tileY,
1410 stationTileX,
1411 stationTileY,
1412 (x, y) => this.walkableFor(best.entityId, x, y),
1413 bounds.minX,
1414 bounds.minY,
1415 bounds.maxX,
1416 bounds.maxY
1417 );
1418 best.spawnOrigin.stationTileX = stationTileX;
1419 best.spawnOrigin.stationTileY = stationTileY;
1420 if (tiles?.length)
1421 { best.path.tiles = tiles; }
1422 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1423 { best.path.tiles = []; }
1424 else
1425 { return { ok: false, reason: "no-path" }; }
1426 return { ok: true, entityId: best.entityId };
1427 }
1428
1429 /**
1430 * Clear a CE clerk's station assignment so wander can resume.
1431 * message: { stationTileX, stationTileY }
1432 */
1433 #releaseExchangeClerk (message)
1434 {
1435 const stationTileX = message.stationTileX | 0;
1436 const stationTileY = message.stationTileY | 0;
1437 let released = 0;
1438 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1439 {
1440 if (!entity.spawnOrigin?.centralExchange)
1441 { continue; }
1442 if (
1443 entity.spawnOrigin.stationTileX !== stationTileX
1444 || entity.spawnOrigin.stationTileY !== stationTileY
1445 )
1446 { continue; }
1447 entity.spawnOrigin.stationTileX = null;
1448 entity.spawnOrigin.stationTileY = null;
1449 entity.path.tiles = [];
1450 released += 1;
1451 }
1452 return { ok: true, released };
1453 }
1454
1455 /** Keep stationed CE clerks at their counter tile. */
1456 #queueExchangeStations ()
1457 {
1458 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1459 {
1460 if (!entity.spawnOrigin?.centralExchange)
1461 { continue; }
1462 const sx = entity.spawnOrigin.stationTileX;
1463 const sy = entity.spawnOrigin.stationTileY;
1464 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1465 { continue; }
1466 if (entity.position.tileX === sx && entity.position.tileY === sy)
1467 {
1468 entity.path.tiles = [];
1469 continue;
1470 }
1471 if (entity.path.tiles?.length)
1472 { continue; }
1473 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1474 const tiles = findPath(
1475 entity.position.tileX,
1476 entity.position.tileY,
1477 sx,
1478 sy,
1479 (x, y) => this.walkableFor(entity.entityId, x, y),
1480 bounds.minX,
1481 bounds.minY,
1482 bounds.maxX,
1483 bounds.maxY
1484 );
1485 if (tiles?.length)
1486 { entity.path.tiles = tiles; }
1487 }
1488 }
1489
1490 #applyTransfer (message)
1491 {
1492 const payload = message.payload;
1493 const entityId = payload.entityId;
1494 if (this.ecs.hasEntity(entityId))
1495 { return { accepted: false, reason: "already-present" }; }
1496
1497 const position = payload.components?.position;
1498 const destTileX = message.destTileX ?? position?.tileX;
1499 const destTileY = message.destTileY ?? position?.tileY;
1500 if (destTileX == null || destTileY == null)
1501 { return { accepted: false, reason: "missing-destination" }; }
1502 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
1503 { return { accepted: false, reason: "not-owner" }; }
1504
1505 const creature = payload.components?.creature;
1506 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1507 if (flying)
1508 {
1509 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
1510 if (!data?.open)
1511 { return { accepted: false, reason: "blocked" }; }
1512 }
1513 else if (!this.isEnterable(destTileX, destTileY))
1514 { return { accepted: false, reason: "blocked" }; }
1515
1516 deserializeEntity(this.ecs, payload);
1517 const handle = this.ecs.handleOf(entityId);
1518 const livePosition = this.ecs.get(handle, Component.position);
1519 const path = this.ecs.get(handle, Component.path);
1520 livePosition.tileX = destTileX;
1521 livePosition.tileY = destTileY;
1522 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1523 { path.tiles.shift(); }
1524 if (!flying)
1525 { this.#occupy(entityId, destTileX, destTileY); }
1526 const character = this.ecs.get(handle, Component.character);
1527 if (character?.characterId)
1528 { this.characterEntities.set(character.characterId, entityId); }
1529 this.frozen.delete(entityId);
1530 return {
1531 accepted: true,
1532 entity: publicEntityView(this.ecs, entityId)
1533 };
1534 }
1535
1536 #commitTransfer (entityId)
1537 {
1538 if (!this.ecs.hasEntity(entityId))
1539 { return null; }
1540 return this.#destroyEntity(entityId);
1541 }
1542
1543 #abortTransfer (entityId)
1544 {
1545 this.frozen.delete(entityId);
1546 return publicEntityView(this.ecs, entityId);
1547 }
1548
1549 #listLoaders ()
1550 {
1551 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
1552 entityId: entity.entityId,
1553 tileX: entity.position.tileX,
1554 tileY: entity.position.tileY,
1555 chunkLoader: { ...entity.chunkLoader }
1556 }));
1557 }
1558
1559 #listPublicEntities ()
1560 {
1561 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1562 }
1563
1564 #entitiesInRegion (regionX, regionY)
1565 {
1566 const records = [];
1567 for (const entity of this.ecs.query(Component.position))
1568 {
1569 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1570 { continue; }
1571 records.push({
1572 ...publicEntityView(this.ecs, entity.entityId),
1573 persistent: this.ecs.has(entity.handle, Component.persistent),
1574 payload: serializeEntity(this.ecs, entity.entityId)
1575 });
1576 }
1577 return records;
1578 }
1579
1580 #chunkSnapshot (chunkX, chunkY, staticOnly = false)
1581 {
1582 const data = this.#chunkData(chunkX, chunkY);
1583 if (staticOnly)
1584 {
1585 return {
1586 chunkX,
1587 chunkY,
1588 open: data.open,
1589 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1590 grounds: data.grounds,
1591 blocks: data.blocks,
1592 light: data.light,
1593 entities: [],
1594 groundItems: []
1595 };
1596 }
1597 const entities = [];
1598 for (const entity of this.ecs.query(Component.position, Component.appearance))
1599 {
1600 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1601 { continue; }
1602 entities.push(publicEntityView(this.ecs, entity.entityId));
1603 }
1604 return {
1605 chunkX,
1606 chunkY,
1607 open: data.open,
1608 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1609 grounds: data.grounds,
1610 blocks: data.blocks,
1611 light: data.light,
1612 entities,
1613 groundItems: groundItemsInChunk(this, chunkX, chunkY)
1614 };
1615 }
1616
1617 #moveEvent (entityId, fromTileX, fromTileY)
1618 {
1619 const view = publicEntityView(this.ecs, entityId);
1620 return {
1621 type: "entity-move",
1622 entityId,
1623 fromTileX,
1624 fromTileY,
1625 tileX: view.tileX,
1626 tileY: view.tileY,
1627 worldX: view.worldX,
1628 worldY: view.worldY,
1629 gait: view.gait,
1630 freeFlight: !!view.freeFlight
1631 };
1632 }
1633
1634 chunkIsSimulating (tileX, tileY)
1635 {
1636 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1637 return !!chunk && !chunk.replica && chunk.simulating;
1638 }
1639
1640 walkableFor (entityId, tileX, tileY)
1641 {
1642 const handle = this.ecs.handleOf(entityId);
1643 if (this.#isFlying(handle))
1644 {
1645 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1646 return !!data?.open;
1647 }
1648 // Entities pass through each other; only terrain / closed chunks block movement.
1649 return this.isEnterable(tileX, tileY);
1650 }
1651
1652 /**
1653 * Standing tile with no other mob/player (self allowed). Used for wander goals
1654 * and melee attack stance.
1655 */
1656 isClearStanding (entityId, tileX, tileY)
1657 {
1658 if (!this.isEnterable(tileX, tileY))
1659 { return false; }
1660 return !this.#hasOtherOccupant(entityId, tileX, tileY);
1661 }
1662
1663 destroyEntity (entityId)
1664 {
1665 return this.#destroyEntity(entityId);
1666 }
1667
1668 occupied (tileX, tileY)
1669 {
1670 return this.#anyOccupant(tileX, tileY);
1671 }
1672
1673 #chunkIsSimulating (tileX, tileY)
1674 {
1675 return this.chunkIsSimulating(tileX, tileY);
1676 }
1677
1678 #chunkData (chunkX, chunkY)
1679 {
1680 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1681 if (loaded)
1682 { return loaded.data; }
1683 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1684 }
1685
1686 isEnterable (tileX, tileY)
1687 {
1688 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1689 if (!data.open)
1690 { return false; }
1691 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1692 }
1693
1694 isClearForRangedAttack (tileX, tileY)
1695 {
1696 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1697 if (!data.open)
1698 { return false; }
1699 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
1700 }
1701
1702 #walkableFor (entityId, tileX, tileY)
1703 {
1704 return this.walkableFor(entityId, tileX, tileY);
1705 }
1706
1707 #isFlying (handle)
1708 {
1709 if (handle == null)
1710 { return false; }
1711 const creature = this.ecs.get(handle, Component.creature);
1712 return !!mobDefinition(creature?.mobTypeId)?.flying;
1713 }
1714
1715 #occupy (entityId, tileX, tileY)
1716 {
1717 const key = tileKey(tileX, tileY);
1718 let set = this.occupancy.get(key);
1719 if (!set)
1720 {
1721 set = new Set();
1722 this.occupancy.set(key, set);
1723 }
1724 set.add(entityId);
1725 }
1726
1727 #vacate (entityId, tileX, tileY)
1728 {
1729 const key = tileKey(tileX, tileY);
1730 const set = this.occupancy.get(key);
1731 if (!set)
1732 { return; }
1733 set.delete(entityId);
1734 if (set.size === 0)
1735 { this.occupancy.delete(key); }
1736 }
1737
1738 #anyOccupant (tileX, tileY)
1739 {
1740 const key = tileKey(tileX, tileY);
1741 const local = this.occupancy.get(key);
1742 if (local?.size)
1743 { return local.values().next().value; }
1744 const ghosts = this.ghostOccupancy.get(key);
1745 if (ghosts?.size)
1746 { return ghosts.values().next().value; }
1747 return null;
1748 }
1749
1750 #hasOtherOccupant (entityId, tileX, tileY)
1751 {
1752 const key = tileKey(tileX, tileY);
1753 const local = this.occupancy.get(key);
1754 if (local)
1755 {
1756 for (const id of local)
1757 {
1758 if (id !== entityId)
1759 { return true; }
1760 }
1761 }
1762 const ghosts = this.ghostOccupancy.get(key);
1763 if (ghosts)
1764 {
1765 for (const id of ghosts)
1766 {
1767 if (id !== entityId)
1768 { return true; }
1769 }
1770 }
1771 return false;
1772 }
1773
1774 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
1775 #occupied (tileX, tileY)
1776 {
1777 return this.#anyOccupant(tileX, tileY);
1778 }
1779}
1780
1781function pickWanderGoalInRange (world, entityId, originX, originY, range)
1782{
1783 const radius = Math.max(0, range | 0);
1784 for (let attempt = 0; attempt < 24; attempt++)
1785 {
1786 const tileX = originX + randInt(-radius, radius);
1787 const tileY = originY + randInt(-radius, radius);
1788 if (!world.isClearStanding(entityId, tileX, tileY))
1789 { continue; }
1790 return { tileX, tileY };
1791 }
1792 return null;
1793}
1794
1795function randInt (min, max)
1796{
1797 return min + Math.floor(Math.random() * (max - min + 1));
1798}
1799
1800export function replicaNeededForOwnedChunks (ownedChunkKeys)
1801{
1802 const needed = new Set();
1803 for (const key of ownedChunkKeys)
1804 {
1805 const { chunkX, chunkY } = parseChunkKey(key);
1806 for (let dy = -1; dy <= 1; dy++)
1807 {
1808 for (let dx = -1; dx <= 1; dx++)
1809 {
1810 if (dx === 0 && dy === 0)
1811 { continue; }
1812 needed.add(chunkKey(chunkX + dx, chunkY + dy));
1813 }
1814 }
1815 }
1816 return needed;
1817}