BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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