BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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