BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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