BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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