BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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