BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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