BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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