| 1 | import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js"; |
| 2 | import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; |
| 3 | import { |
| 4 | chunkKey, |
| 5 | chunkToRegion, |
| 6 | parseChunkKey, |
| 7 | regionKey, |
| 8 | tileKey, |
| 9 | tileToChunk, |
| 10 | tileToLocal, |
| 11 | tileToRegion |
| 12 | } from "../world/coordinates.js"; |
| 13 | import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js"; |
| 14 | import { closedNeighborEdges } from "../world/chunkFlags.js"; |
| 15 | import { EcsWorld } from "../ecs/world.js"; |
| 16 | import { Component } from "../ecs/components.js"; |
| 17 | import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js"; |
| 18 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 19 | import { WorkerMessage } from "./protocol.js"; |
| 20 | import { collectSpawnRequests } from "./spawners.js"; |
| 21 | import { mobDefinition } from "../../../shared/definitions/mobs.js"; |
| 22 | import { |
| 23 | bagView, |
| 24 | applyBagView, |
| 25 | addGroundItem, |
| 26 | expireGroundItems, |
| 27 | groundItemsInChunk, |
| 28 | groundItemsInRegion, |
| 29 | handleItemCommand, |
| 30 | removeGroundItem, |
| 31 | publicGroundItem, |
| 32 | setGroundItemsForRegion |
| 33 | } from "../items/bags.js"; |
| 34 | import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js"; |
| 35 | import { publicSpellsView } from "../../../shared/spells/state.js"; |
| 36 | import { |
| 37 | handleGatherCommand, |
| 38 | stepGather, |
| 39 | cancelGather, |
| 40 | clearOreRespawnsForChunk, |
| 41 | clearTreeRespawnsForChunk, |
| 42 | clearPlantRespawnsForChunk |
| 43 | } from "../gathering/service.js"; |
| 44 | import { handleCraftCommand, stepCrafting } from "../crafting/service.js"; |
| 45 | import { handleAlchemyCommand } from "../alchemy/service.js"; |
| 46 | import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js"; |
| 47 | import { |
| 48 | applyRemoteMeleeSwing, |
| 49 | applyRemoteRangedShot, |
| 50 | attackProfileOf, |
| 51 | clearEngage, |
| 52 | engageTarget, |
| 53 | ensureMobCombat, |
| 54 | isUntargetable, |
| 55 | queueMeleeApproach, |
| 56 | queueStandInRangeApproach, |
| 57 | resolveCombatTarget, |
| 58 | stepAggression, |
| 59 | stepCombat, |
| 60 | chebyshev |
| 61 | } from "../combat/service.js"; |
| 62 | import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js"; |
| 63 | import { SkillId } from "../../../shared/definitions/skills.js"; |
| 64 | import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js"; |
| 65 | import { |
| 66 | STAMINA_REGEN_PER_SECOND, |
| 67 | STAMINA_XP_PER_POINT_SPENT, |
| 68 | staminaCostPerRunStep, |
| 69 | publicStaminaView |
| 70 | } from "../../../shared/stamina/rules.js"; |
| 71 | import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js"; |
| 72 | import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js"; |
| 73 | import { stepStatusEffects } from "../statusEffects/service.js"; |
| 74 | |
| 75 | export class WorkerWorld |
| 76 | { |
| 77 | constructor (workerId) |
| 78 | { |
| 79 | this.workerId = workerId; |
| 80 | this.ecs = new EcsWorld(); |
| 81 | this.chunks = new Map(); |
| 82 | this.ownedRegions = new Set(); |
| 83 | this.occupancy = new Map(); |
| 84 | this.ghosts = new Map(); |
| 85 | this.ghostOccupancy = new Map(); |
| 86 | this.characterEntities = new Map(); |
| 87 | this.frozen = new Set(); |
| 88 | this.groundItems = new Map(); |
| 89 | this.groundByTile = new Map(); |
| 90 | this.oreRespawns = new Map(); |
| 91 | this.treeRespawns = new Map(); |
| 92 | this.pendingSpellImpacts = []; |
| 93 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 94 | this.activeRevisionId = 1; |
| 95 | } |
| 96 | |
| 97 | handle (message) |
| 98 | { |
| 99 | switch (message.type) |
| 100 | { |
| 101 | case WorkerMessage.configure: |
| 102 | return this.#configure(message); |
| 103 | case WorkerMessage.assignRegion: |
| 104 | return this.#assignRegion(message); |
| 105 | case WorkerMessage.dropRegion: |
| 106 | return this.#dropRegion(message); |
| 107 | case WorkerMessage.replaceRegionChunks: |
| 108 | return this.#replaceRegionChunks(message); |
| 109 | case WorkerMessage.setReplicas: |
| 110 | return this.#setReplicas(message); |
| 111 | case WorkerMessage.setSimulatingChunks: |
| 112 | return this.#setSimulatingChunks(message); |
| 113 | case WorkerMessage.setGhosts: |
| 114 | return this.#setGhosts(message); |
| 115 | case WorkerMessage.spawn: |
| 116 | return this.#spawn(message); |
| 117 | case WorkerMessage.despawn: |
| 118 | return this.#despawn(message.entityId); |
| 119 | case WorkerMessage.despawnCharacter: |
| 120 | return this.#despawnCharacter(message.characterId); |
| 121 | case WorkerMessage.command: |
| 122 | return this.#command(message); |
| 123 | case WorkerMessage.stepMovement: |
| 124 | return this.#stepMovement(message.now); |
| 125 | case WorkerMessage.stepSystems: |
| 126 | return this.#stepSystems(message.now, message.dt ?? (1 / 20)); |
| 127 | case WorkerMessage.stepSpawners: |
| 128 | return { spawnRequests: collectSpawnRequests(this) }; |
| 129 | case WorkerMessage.setGroundItems: |
| 130 | setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion); |
| 131 | return { ok: true }; |
| 132 | case WorkerMessage.inspectBag: |
| 133 | return this.#inspectBag(message.entityId); |
| 134 | case WorkerMessage.inspectSkills: |
| 135 | return this.#inspectSkills(message.entityId); |
| 136 | case WorkerMessage.inspectSpells: |
| 137 | return this.#inspectSpells(message.entityId); |
| 138 | case WorkerMessage.inspectStamina: |
| 139 | return this.#inspectStamina(message.entityId); |
| 140 | case WorkerMessage.applyBag: |
| 141 | return this.#applyBag(message.entityId, message.bag); |
| 142 | case WorkerMessage.applyAppearance: |
| 143 | return this.#applyAppearance(message.entityId, message.appearance); |
| 144 | case WorkerMessage.engageTarget: |
| 145 | return this.#engageTargetMessage(message); |
| 146 | case WorkerMessage.listTownGuardsNear: |
| 147 | return this.#listTownGuardsNear(message); |
| 148 | case WorkerMessage.updateFlight: |
| 149 | return this.#updateFlight(message.entityId, message.flight, message.now); |
| 150 | case WorkerMessage.chunkIsSimulating: |
| 151 | return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId); |
| 152 | case WorkerMessage.applyTransfer: |
| 153 | return this.#applyTransfer(message); |
| 154 | case WorkerMessage.commitTransfer: |
| 155 | return this.#commitTransfer(message.entityId); |
| 156 | case WorkerMessage.abortTransfer: |
| 157 | return this.#abortTransfer(message.entityId); |
| 158 | case WorkerMessage.snapshotChunk: |
| 159 | return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId); |
| 160 | case WorkerMessage.listLoaders: |
| 161 | return this.#listLoaders(); |
| 162 | case WorkerMessage.listPublicEntities: |
| 163 | return this.#listPublicEntities(); |
| 164 | case WorkerMessage.entitiesInRegion: |
| 165 | return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId); |
| 166 | case WorkerMessage.inspect: |
| 167 | return publicEntityView(this.ecs, message.entityId); |
| 168 | case WorkerMessage.remoteCombatEngage: |
| 169 | return this.#remoteCombatEngage(message); |
| 170 | case WorkerMessage.applyRemoteMelee: |
| 171 | return this.#applyRemoteMelee(message); |
| 172 | case WorkerMessage.applyRemoteRanged: |
| 173 | return this.#applyRemoteRanged(message); |
| 174 | case WorkerMessage.applyCombatHitXp: |
| 175 | return this.#applyCombatHitXp(message); |
| 176 | case WorkerMessage.spawnCorpseDrops: |
| 177 | return this.#spawnCorpseDrops(message); |
| 178 | case WorkerMessage.applyRespawn: |
| 179 | return this.#applyRespawn(message); |
| 180 | case WorkerMessage.relocateEntity: |
| 181 | return this.#relocateEntity(message); |
| 182 | case WorkerMessage.clearCombat: |
| 183 | clearEngage(this.ecs, message.entityId); |
| 184 | for (const entity of this.ecs.query(Component.combat)) |
| 185 | { |
| 186 | if (entity.combat.targetEntityId === message.targetEntityId) |
| 187 | { entity.combat.targetEntityId = null; } |
| 188 | } |
| 189 | return { ok: true }; |
| 190 | case WorkerMessage.setItemLastSales: |
| 191 | { |
| 192 | this.itemLastSales = new Map(); |
| 193 | for (const [key, sale] of Object.entries(message.sales ?? {})) |
| 194 | { this.itemLastSales.set(Number(key), sale); } |
| 195 | return { ok: true }; |
| 196 | } |
| 197 | case WorkerMessage.stationExchangeClerk: |
| 198 | return this.#stationExchangeClerk(message); |
| 199 | case WorkerMessage.releaseExchangeClerk: |
| 200 | return this.#releaseExchangeClerk(message); |
| 201 | case WorkerMessage.pinDialogue: |
| 202 | return this.#pinDialogue(message.entityId, message.characterId); |
| 203 | case WorkerMessage.unpinDialogue: |
| 204 | return this.#unpinDialogue(message.entityId, message.characterId); |
| 205 | default: |
| 206 | throw new Error(`Unknown worker message ${message.type}`); |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 211 | { |
| 212 | return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId)); |
| 213 | } |
| 214 | |
| 215 | requireOwnedEntity (sessionId, characterId) |
| 216 | { |
| 217 | return this.#requireOwnedEntity(sessionId, characterId); |
| 218 | } |
| 219 | |
| 220 | chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 221 | { |
| 222 | return this.#chunkData(chunkX, chunkY, dimensionId); |
| 223 | } |
| 224 | |
| 225 | #configure (message) |
| 226 | { |
| 227 | if (message.settings) |
| 228 | { this.settings = { ...this.settings, ...message.settings }; } |
| 229 | if (message.activeRevisionId != null) |
| 230 | { this.activeRevisionId = message.activeRevisionId; } |
| 231 | return { ok: true }; |
| 232 | } |
| 233 | |
| 234 | #assignRegion (message) |
| 235 | { |
| 236 | const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 237 | this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim)); |
| 238 | for (const chunk of message.chunks ?? []) |
| 239 | { |
| 240 | const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim); |
| 241 | clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 242 | clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 243 | clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 244 | this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), { |
| 245 | data: cloneChunkData(chunk.data), |
| 246 | simulating: false, |
| 247 | replica: false, |
| 248 | dimensionId: chunkDim |
| 249 | }); |
| 250 | } |
| 251 | return { ok: true }; |
| 252 | } |
| 253 | |
| 254 | #replaceRegionChunks (message) |
| 255 | { |
| 256 | const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 257 | for (const chunk of message.chunks ?? []) |
| 258 | { |
| 259 | const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim); |
| 260 | const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim); |
| 261 | const existing = this.chunks.get(key); |
| 262 | clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 263 | clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 264 | clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 265 | this.chunks.set(key, { |
| 266 | data: cloneChunkData(chunk.data), |
| 267 | simulating: existing?.simulating ?? false, |
| 268 | replica: existing?.replica ?? false, |
| 269 | dimensionId: chunkDim |
| 270 | }); |
| 271 | } |
| 272 | return { ok: true }; |
| 273 | } |
| 274 | |
| 275 | #dropRegion (message) |
| 276 | { |
| 277 | const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 278 | const dropped = []; |
| 279 | for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim)) |
| 280 | { |
| 281 | const components = record.payload?.components; |
| 282 | if (components?.creature && !components?.character && components?.health) |
| 283 | { components.health.current = components.health.max; } |
| 284 | dropped.push(record); |
| 285 | this.#destroyEntity(record.entityId); |
| 286 | } |
| 287 | const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion); |
| 288 | for (const item of groundItems) |
| 289 | { removeGroundItem(this, item.groundItemId); } |
| 290 | for (const [key, chunk] of [...this.chunks.entries()]) |
| 291 | { |
| 292 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 293 | if (chunk.replica) |
| 294 | { continue; } |
| 295 | if (dimensionId !== dim) |
| 296 | { continue; } |
| 297 | if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY) |
| 298 | { |
| 299 | clearOreRespawnsForChunk(this, chunkX, chunkY); |
| 300 | clearTreeRespawnsForChunk(this, chunkX, chunkY); |
| 301 | clearPlantRespawnsForChunk(this, chunkX, chunkY); |
| 302 | this.chunks.delete(key); |
| 303 | } |
| 304 | } |
| 305 | this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim)); |
| 306 | return { dropped, groundItems }; |
| 307 | } |
| 308 | |
| 309 | #setReplicas (message) |
| 310 | { |
| 311 | const keep = new Set(); |
| 312 | for (const chunk of message.chunks ?? []) |
| 313 | { |
| 314 | const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID); |
| 315 | const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim); |
| 316 | keep.add(key); |
| 317 | const existing = this.chunks.get(key); |
| 318 | if (existing && !existing.replica) |
| 319 | { continue; } |
| 320 | this.chunks.set(key, { |
| 321 | data: cloneChunkData(chunk.data), |
| 322 | simulating: false, |
| 323 | replica: true, |
| 324 | dimensionId: chunkDim |
| 325 | }); |
| 326 | } |
| 327 | for (const [key, chunk] of [...this.chunks.entries()]) |
| 328 | { |
| 329 | if (chunk.replica && !keep.has(key)) |
| 330 | { this.chunks.delete(key); } |
| 331 | } |
| 332 | return { ok: true }; |
| 333 | } |
| 334 | |
| 335 | #setSimulatingChunks (message) |
| 336 | { |
| 337 | const simulating = new Set(message.chunkKeys ?? []); |
| 338 | for (const [key, chunk] of this.chunks) |
| 339 | { |
| 340 | if (chunk.replica) |
| 341 | { |
| 342 | chunk.simulating = false; |
| 343 | continue; |
| 344 | } |
| 345 | chunk.simulating = simulating.has(key); |
| 346 | } |
| 347 | return { ok: true }; |
| 348 | } |
| 349 | |
| 350 | #setGhosts (message) |
| 351 | { |
| 352 | this.ghosts.clear(); |
| 353 | this.ghostOccupancy.clear(); |
| 354 | for (const ghost of message.ghosts ?? []) |
| 355 | { |
| 356 | this.ghosts.set(ghost.entityId, ghost); |
| 357 | const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID); |
| 358 | const key = tileKey(ghost.tileX, ghost.tileY, dim); |
| 359 | let set = this.ghostOccupancy.get(key); |
| 360 | if (!set) |
| 361 | { |
| 362 | set = new Set(); |
| 363 | this.ghostOccupancy.set(key, set); |
| 364 | } |
| 365 | set.add(ghost.entityId); |
| 366 | } |
| 367 | return { ok: true }; |
| 368 | } |
| 369 | |
| 370 | #spawn (message) |
| 371 | { |
| 372 | const entityId = deserializeEntity(this.ecs, message); |
| 373 | const handle = this.ecs.handleOf(entityId); |
| 374 | const position = this.ecs.get(handle, Component.position); |
| 375 | if (!position) |
| 376 | { |
| 377 | this.ecs.destroy(handle); |
| 378 | throw new Error("Spawned entity is missing position."); |
| 379 | } |
| 380 | const flying = this.#isFlying(handle); |
| 381 | if (!flying) |
| 382 | { |
| 383 | if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY)) |
| 384 | { |
| 385 | this.ecs.destroy(handle); |
| 386 | const error = new Error("That tile is occupied."); |
| 387 | error.userFacing = true; |
| 388 | throw error; |
| 389 | } |
| 390 | this.#occupy(entityId, position.tileX, position.tileY); |
| 391 | } |
| 392 | const creature = this.ecs.get(handle, Component.creature); |
| 393 | const def = creature ? mobDefinition(creature.mobTypeId) : null; |
| 394 | if (def?.freeFlight) |
| 395 | { ensureFlightComponent(this.ecs, handle, position, def); } |
| 396 | const character = this.ecs.get(handle, Component.character); |
| 397 | if (character?.characterId) |
| 398 | { this.characterEntities.set(character.characterId, entityId); } |
| 399 | return publicEntityView(this.ecs, entityId); |
| 400 | } |
| 401 | |
| 402 | #despawn (entityId) |
| 403 | { |
| 404 | return this.#destroyEntity(entityId); |
| 405 | } |
| 406 | |
| 407 | #despawnCharacter (characterId) |
| 408 | { |
| 409 | releaseShopBrowsersForCharacter(this, characterId); |
| 410 | const entityId = this.characterEntities.get(characterId); |
| 411 | if (!entityId) |
| 412 | { return null; } |
| 413 | return this.#destroyEntity(entityId); |
| 414 | } |
| 415 | |
| 416 | #destroyEntity (entityId) |
| 417 | { |
| 418 | const handle = this.ecs.handleOf(entityId); |
| 419 | if (handle == null) |
| 420 | { return null; } |
| 421 | const view = publicEntityView(this.ecs, entityId); |
| 422 | const position = this.ecs.get(handle, Component.position); |
| 423 | const character = this.ecs.get(handle, Component.character); |
| 424 | if (position && !this.#isFlying(handle)) |
| 425 | { this.#vacate(entityId, position.tileX, position.tileY); } |
| 426 | if (character?.characterId) |
| 427 | { this.characterEntities.delete(character.characterId); } |
| 428 | this.frozen.delete(entityId); |
| 429 | this.ecs.destroy(handle); |
| 430 | return view; |
| 431 | } |
| 432 | |
| 433 | #command (message) |
| 434 | { |
| 435 | const { sessionId, command } = message; |
| 436 | switch (command.type) |
| 437 | { |
| 438 | case "move-to": |
| 439 | this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY); |
| 440 | return { events: [] }; |
| 441 | case "set-gait": |
| 442 | return this.#setGait(sessionId, command.characterId, command.gait); |
| 443 | case "attack": |
| 444 | return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now()); |
| 445 | case "cancel-attack": |
| 446 | return this.#cancelAttack(sessionId, command.characterId); |
| 447 | case "interact": |
| 448 | return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose); |
| 449 | case "follow": |
| 450 | return this.#follow(sessionId, command.characterId, command.targetEntityId); |
| 451 | case "cancel-follow": |
| 452 | return this.#cancelFollow(sessionId, command.characterId); |
| 453 | case "set-spell-favorite": |
| 454 | case "set-spell-autocast": |
| 455 | case "arm-spell": |
| 456 | case "cancel-arm-spell": |
| 457 | case "cast-spell-tile": |
| 458 | case "cast-spell-entity": |
| 459 | case "read-spellbook": |
| 460 | return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] }; |
| 461 | default: |
| 462 | { |
| 463 | const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now()); |
| 464 | if (gather) |
| 465 | { return gather; } |
| 466 | const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now()); |
| 467 | if (craft) |
| 468 | { return craft; } |
| 469 | const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now()); |
| 470 | if (shop) |
| 471 | { return shop; } |
| 472 | const alchemy = handleAlchemyCommand(this, sessionId, command); |
| 473 | if (alchemy) |
| 474 | { return alchemy; } |
| 475 | const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now()); |
| 476 | return result ?? { events: [] }; |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | #spawnCorpseDrops (message) |
| 482 | { |
| 483 | const events = []; |
| 484 | for (const drop of message.drops ?? []) |
| 485 | { |
| 486 | const item = { |
| 487 | groundItemId: drop.groundItemId, |
| 488 | tileX: message.tileX, |
| 489 | tileY: message.tileY, |
| 490 | stack: { itemId: drop.itemId, quantity: 1 }, |
| 491 | droppedAt: message.now, |
| 492 | expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000), |
| 493 | source: "player-death", |
| 494 | droppedByCharacterId: message.characterId |
| 495 | }; |
| 496 | addGroundItem(this, item); |
| 497 | events.push({ |
| 498 | type: "ground-item-appear", |
| 499 | ...publicGroundItem(item), |
| 500 | stack: item.stack, |
| 501 | droppedAt: item.droppedAt, |
| 502 | source: item.source, |
| 503 | droppedByCharacterId: item.droppedByCharacterId, |
| 504 | expiresAt: item.expiresAt |
| 505 | }); |
| 506 | } |
| 507 | return { events }; |
| 508 | } |
| 509 | |
| 510 | #applyRespawn (message) |
| 511 | { |
| 512 | const handle = this.ecs.handleOf(message.entityId); |
| 513 | if (handle == null || !this.ecs.has(handle, Component.dead)) |
| 514 | { return { accepted: false }; } |
| 515 | const position = this.ecs.get(handle, Component.position); |
| 516 | const fromTileX = position.tileX; |
| 517 | const fromTileY = position.tileY; |
| 518 | const health = this.ecs.get(handle, Component.health); |
| 519 | const stamina = this.ecs.get(handle, Component.stamina); |
| 520 | if (health) |
| 521 | { |
| 522 | health.max = message.maxHealth; |
| 523 | health.current = message.maxHealth; |
| 524 | } |
| 525 | if (stamina) |
| 526 | { |
| 527 | stamina.max = message.maxStamina; |
| 528 | stamina.current = message.maxStamina; |
| 529 | } |
| 530 | else |
| 531 | { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); } |
| 532 | this.ecs.remove(handle, Component.dead); |
| 533 | clearEngage(this.ecs, message.entityId); |
| 534 | const path = this.ecs.get(handle, Component.path); |
| 535 | if (path) |
| 536 | { path.tiles = []; } |
| 537 | clearFollow(this.ecs, message.entityId); |
| 538 | |
| 539 | const destRegionX = tileToRegion(message.tileX); |
| 540 | const destRegionY = tileToRegion(message.tileY); |
| 541 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 542 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 543 | { |
| 544 | this.frozen.add(message.entityId); |
| 545 | return { |
| 546 | accepted: true, |
| 547 | transferRequest: { |
| 548 | entityId: message.entityId, |
| 549 | fromTileX, |
| 550 | fromTileY, |
| 551 | destTileX: message.tileX, |
| 552 | destTileY: message.tileY, |
| 553 | toRegionX: destRegionX, |
| 554 | toRegionY: destRegionY, |
| 555 | dimensionId, |
| 556 | payload: serializeEntity(this.ecs, message.entityId) |
| 557 | } |
| 558 | }; |
| 559 | } |
| 560 | if (!this.isEnterable(message.tileX, message.tileY, dimensionId)) |
| 561 | { return { accepted: false }; } |
| 562 | this.#vacate(message.entityId, fromTileX, fromTileY); |
| 563 | position.tileX = message.tileX; |
| 564 | position.tileY = message.tileY; |
| 565 | this.#occupy(message.entityId, position.tileX, position.tileY); |
| 566 | return { |
| 567 | accepted: true, |
| 568 | event: { |
| 569 | type: "entity-move", |
| 570 | entityId: message.entityId, |
| 571 | fromTileX, |
| 572 | fromTileY, |
| 573 | tileX: position.tileX, |
| 574 | tileY: position.tileY, |
| 575 | dimensionId, |
| 576 | gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk |
| 577 | } |
| 578 | }; |
| 579 | } |
| 580 | |
| 581 | /** Move an entity to a tile/dimension; clears path and updates occupancy. */ |
| 582 | #relocateEntity (message) |
| 583 | { |
| 584 | const handle = this.ecs.handleOf(message.entityId); |
| 585 | if (handle == null) |
| 586 | { return { accepted: false }; } |
| 587 | const position = this.ecs.get(handle, Component.position); |
| 588 | if (!position) |
| 589 | { return { accepted: false }; } |
| 590 | const fromTileX = position.tileX; |
| 591 | const fromTileY = position.tileY; |
| 592 | const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 593 | const destTileX = message.tileX | 0; |
| 594 | const destTileY = message.tileY | 0; |
| 595 | const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId); |
| 596 | |
| 597 | clearEngage(this.ecs, message.entityId); |
| 598 | const path = this.ecs.get(handle, Component.path); |
| 599 | if (path) |
| 600 | { path.tiles = []; } |
| 601 | clearFollow(this.ecs, message.entityId); |
| 602 | |
| 603 | const destRegionX = tileToRegion(destTileX); |
| 604 | const destRegionY = tileToRegion(destTileY); |
| 605 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 606 | { |
| 607 | this.frozen.add(message.entityId); |
| 608 | const payload = serializeEntity(this.ecs, message.entityId); |
| 609 | if (payload.components?.position) |
| 610 | { |
| 611 | payload.components.position.tileX = destTileX; |
| 612 | payload.components.position.tileY = destTileY; |
| 613 | payload.components.position.dimensionId = dimensionId; |
| 614 | } |
| 615 | return { |
| 616 | accepted: true, |
| 617 | transferRequest: { |
| 618 | entityId: message.entityId, |
| 619 | fromTileX, |
| 620 | fromTileY, |
| 621 | fromDimensionId, |
| 622 | destTileX, |
| 623 | destTileY, |
| 624 | toRegionX: destRegionX, |
| 625 | toRegionY: destRegionY, |
| 626 | dimensionId, |
| 627 | payload |
| 628 | } |
| 629 | }; |
| 630 | } |
| 631 | if (!this.isEnterable(destTileX, destTileY, dimensionId)) |
| 632 | { return { accepted: false }; } |
| 633 | if (!this.#isFlying(handle)) |
| 634 | { this.#vacate(message.entityId, fromTileX, fromTileY); } |
| 635 | position.tileX = destTileX; |
| 636 | position.tileY = destTileY; |
| 637 | position.dimensionId = dimensionId; |
| 638 | if (!this.#isFlying(handle)) |
| 639 | { this.#occupy(message.entityId, destTileX, destTileY); } |
| 640 | return { |
| 641 | accepted: true, |
| 642 | event: { |
| 643 | type: "entity-move", |
| 644 | entityId: message.entityId, |
| 645 | fromTileX, |
| 646 | fromTileY, |
| 647 | fromDimensionId, |
| 648 | tileX: destTileX, |
| 649 | tileY: destTileY, |
| 650 | dimensionId, |
| 651 | gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk |
| 652 | } |
| 653 | }; |
| 654 | } |
| 655 | |
| 656 | #inspectBag (entityId) |
| 657 | { |
| 658 | const handle = this.ecs.handleOf(entityId); |
| 659 | if (handle == null) |
| 660 | { return null; } |
| 661 | return bagView(this.ecs, handle); |
| 662 | } |
| 663 | |
| 664 | #inspectSkills (entityId) |
| 665 | { |
| 666 | const handle = this.ecs.handleOf(entityId); |
| 667 | if (handle == null) |
| 668 | { return null; } |
| 669 | const skills = this.ecs.get(handle, Component.skills); |
| 670 | if (!skills?.xp) |
| 671 | { return null; } |
| 672 | return skills; |
| 673 | } |
| 674 | |
| 675 | #inspectSpells (entityId) |
| 676 | { |
| 677 | const handle = this.ecs.handleOf(entityId); |
| 678 | if (handle == null) |
| 679 | { return null; } |
| 680 | const spells = this.ecs.get(handle, Component.spells); |
| 681 | const skills = this.ecs.get(handle, Component.skills); |
| 682 | const casting = this.ecs.get(handle, Component.spellcasting); |
| 683 | if (!spells) |
| 684 | { return null; } |
| 685 | return { |
| 686 | spells: publicSpellsView(spells, skills), |
| 687 | autoCast: !!spells.autoCast, |
| 688 | armedSpellId: casting?.armedSpellId ?? null |
| 689 | }; |
| 690 | } |
| 691 | |
| 692 | #inspectStamina (entityId) |
| 693 | { |
| 694 | const handle = this.ecs.handleOf(entityId); |
| 695 | if (handle == null) |
| 696 | { return null; } |
| 697 | const stamina = this.ecs.get(handle, Component.stamina); |
| 698 | const movement = this.ecs.get(handle, Component.movement); |
| 699 | if (!stamina) |
| 700 | { return null; } |
| 701 | return { |
| 702 | ...publicStaminaView(stamina), |
| 703 | gait: movement?.gait ?? GAIT.walk |
| 704 | }; |
| 705 | } |
| 706 | |
| 707 | #applyBag (entityId, bag) |
| 708 | { |
| 709 | const handle = this.ecs.handleOf(entityId); |
| 710 | if (handle == null) |
| 711 | { return null; } |
| 712 | return applyBagView(this.ecs, handle, bag); |
| 713 | } |
| 714 | |
| 715 | #applyAppearance (entityId, appearancePatch) |
| 716 | { |
| 717 | const handle = this.ecs.handleOf(entityId); |
| 718 | if (handle == null) |
| 719 | { return null; } |
| 720 | const appearance = this.ecs.get(handle, Component.appearance); |
| 721 | if (!appearance) |
| 722 | { return null; } |
| 723 | Object.assign(appearance, appearancePatch ?? {}); |
| 724 | return publicEntityView(this.ecs, entityId); |
| 725 | } |
| 726 | |
| 727 | #updateFlight (entityId, flightPatch, now = Date.now()) |
| 728 | { |
| 729 | const handle = this.ecs.handleOf(entityId); |
| 730 | if (handle == null) |
| 731 | { return null; } |
| 732 | let flight = this.ecs.get(handle, Component.flight); |
| 733 | if (!flight) |
| 734 | { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); } |
| 735 | else |
| 736 | { Object.assign(flight, flightPatch); } |
| 737 | const position = this.ecs.get(handle, Component.position); |
| 738 | const movement = this.ecs.get(handle, Component.movement); |
| 739 | const fromTileX = position.tileX; |
| 740 | const fromTileY = position.tileY; |
| 741 | const tileX = Math.floor(flight.x); |
| 742 | const tileY = Math.floor(flight.y); |
| 743 | position.tileX = tileX; |
| 744 | position.tileY = tileY; |
| 745 | const destRegionX = tileToRegion(tileX); |
| 746 | const destRegionY = tileToRegion(tileY); |
| 747 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 748 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 749 | { |
| 750 | this.frozen.add(entityId); |
| 751 | return { |
| 752 | transferRequest: { |
| 753 | type: "transfer-request", |
| 754 | entityId, |
| 755 | fromTileX, |
| 756 | fromTileY, |
| 757 | destTileX: tileX, |
| 758 | destTileY: tileY, |
| 759 | toRegionX: destRegionX, |
| 760 | toRegionY: destRegionY, |
| 761 | dimensionId |
| 762 | } |
| 763 | }; |
| 764 | } |
| 765 | const dt = flight.lastAt && now > flight.lastAt |
| 766 | ? Math.min(0.25, (now - flight.lastAt) / 1000) |
| 767 | : 1 / 20; |
| 768 | return { |
| 769 | event: { |
| 770 | type: "entity-move", |
| 771 | entityId, |
| 772 | fromTileX, |
| 773 | fromTileY, |
| 774 | tileX, |
| 775 | tileY, |
| 776 | worldX: flight.x, |
| 777 | worldY: flight.y, |
| 778 | gait: movement?.gait ?? "walk", |
| 779 | lerpMs: Math.max(50, Math.round(dt * 1000)), |
| 780 | freeFlight: true |
| 781 | } |
| 782 | }; |
| 783 | } |
| 784 | |
| 785 | #moveTo (sessionId, characterId, tileX, tileY) |
| 786 | { |
| 787 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 788 | if (this.frozen.has(entityId)) |
| 789 | { return; } |
| 790 | clearEngage(this.ecs, entityId); |
| 791 | clearFollow(this.ecs, entityId); |
| 792 | cancelGather(this.ecs, handle); |
| 793 | const casting = this.ecs.get(handle, Component.spellcasting); |
| 794 | if (casting) |
| 795 | { casting.pendingCast = null; } |
| 796 | const position = this.ecs.get(handle, Component.position); |
| 797 | const movement = this.ecs.get(handle, Component.movement); |
| 798 | let path = this.ecs.get(handle, Component.path); |
| 799 | if (!path) |
| 800 | { path = this.ecs.add(handle, Component.path, { tiles: [] }); } |
| 801 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 802 | path.tiles = findPath( |
| 803 | position.tileX, |
| 804 | position.tileY, |
| 805 | tileX, |
| 806 | tileY, |
| 807 | (x, y) => this.walkableFor(entityId, x, y), |
| 808 | bounds.minX, |
| 809 | bounds.minY, |
| 810 | bounds.maxX, |
| 811 | bounds.maxY, |
| 812 | { preferVertical: true } |
| 813 | ); |
| 814 | movement.walkCarry = 0; |
| 815 | } |
| 816 | |
| 817 | #attack (sessionId, characterId, targetEntityId, now) |
| 818 | { |
| 819 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 820 | if (targetEntityId === entityId) |
| 821 | { |
| 822 | const error = new Error("Cannot attack yourself."); |
| 823 | error.userFacing = true; |
| 824 | throw error; |
| 825 | } |
| 826 | const target = resolveCombatTarget(this, targetEntityId); |
| 827 | if (!target) |
| 828 | { |
| 829 | const error = new Error("Target is not here."); |
| 830 | error.userFacing = true; |
| 831 | throw error; |
| 832 | } |
| 833 | if (target.health && target.health.current <= 0) |
| 834 | { |
| 835 | const error = new Error("That cannot be attacked."); |
| 836 | error.userFacing = true; |
| 837 | throw error; |
| 838 | } |
| 839 | if (!this.ecs.get(handle, Component.combat)) |
| 840 | { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } |
| 841 | clearFollow(this.ecs, entityId); |
| 842 | cancelGather(this.ecs, handle); |
| 843 | engageTarget(this.ecs, entityId, targetEntityId, now); |
| 844 | const position = this.ecs.get(handle, Component.position); |
| 845 | const profile = attackProfileOf(this.ecs, handle); |
| 846 | if (position && target.pos) |
| 847 | { |
| 848 | if (profile.mode === "ranged") |
| 849 | { |
| 850 | queueStandInRangeApproach( |
| 851 | this, |
| 852 | entityId, |
| 853 | handle, |
| 854 | position, |
| 855 | target.pos.tileX, |
| 856 | target.pos.tileY, |
| 857 | profile.rangeTiles | 0 || COMBAT_RANGE_TILES, |
| 858 | 1 |
| 859 | ); |
| 860 | } |
| 861 | else if (profile.mode === "melee") |
| 862 | { |
| 863 | queueMeleeApproach(this, entityId, handle, position, target.pos); |
| 864 | } |
| 865 | } |
| 866 | return { events: [] }; |
| 867 | } |
| 868 | |
| 869 | #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() }) |
| 870 | { |
| 871 | // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click. |
| 872 | void attackerEntityId; |
| 873 | void targetEntityId; |
| 874 | void now; |
| 875 | return { events: [] }; |
| 876 | } |
| 877 | |
| 878 | #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() }) |
| 879 | { |
| 880 | if (this.ecs.handleOf(attackerEntityId) == null) |
| 881 | { return { ok: false }; } |
| 882 | engageTarget(this.ecs, attackerEntityId, targetEntityId, now); |
| 883 | return { ok: true }; |
| 884 | } |
| 885 | |
| 886 | /** |
| 887 | * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY). |
| 888 | * Optionally restrict to one spawnerId. |
| 889 | */ |
| 890 | #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 }) |
| 891 | { |
| 892 | const guards = []; |
| 893 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position)) |
| 894 | { |
| 895 | if (!entity.spawnOrigin?.townGuard) |
| 896 | { continue; } |
| 897 | if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId) |
| 898 | { continue; } |
| 899 | const originX = entity.spawnOrigin.originTileX; |
| 900 | const originY = entity.spawnOrigin.originTileY; |
| 901 | const range = entity.spawnOrigin.wanderRangeTiles | 0; |
| 902 | const dx = Math.abs(tileX - originX); |
| 903 | const dy = Math.abs(tileY - originY); |
| 904 | if (Math.max(dx, dy) > range) |
| 905 | { continue; } |
| 906 | const health = this.ecs.get(entity.handle, Component.health); |
| 907 | if (health && health.current <= 0) |
| 908 | { continue; } |
| 909 | if (this.ecs.has(entity.handle, Component.dead)) |
| 910 | { continue; } |
| 911 | guards.push({ |
| 912 | entityId: entity.entityId, |
| 913 | spawnerId: entity.spawnOrigin.spawnerId, |
| 914 | busy: entity.combat?.targetEntityId != null |
| 915 | }); |
| 916 | if (guards.length >= limit) |
| 917 | { break; } |
| 918 | } |
| 919 | return { guards }; |
| 920 | } |
| 921 | |
| 922 | #applyRemoteMelee (payload) |
| 923 | { |
| 924 | return applyRemoteMeleeSwing(this, payload); |
| 925 | } |
| 926 | |
| 927 | #applyRemoteRanged (payload) |
| 928 | { |
| 929 | return applyRemoteRangedShot(this, payload); |
| 930 | } |
| 931 | |
| 932 | #applyCombatHitXp ({ entityId, profile, damage }) |
| 933 | { |
| 934 | const handle = this.ecs.handleOf(entityId); |
| 935 | if (handle == null) |
| 936 | { return { events: [] }; } |
| 937 | const character = this.ecs.get(handle, Component.character); |
| 938 | if (!character) |
| 939 | { return { events: [] }; } |
| 940 | const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage); |
| 941 | if (!xpAward) |
| 942 | { return { events: [] }; } |
| 943 | return { |
| 944 | events: [{ |
| 945 | type: "skills-updated", |
| 946 | entityId, |
| 947 | characterId: character.characterId, |
| 948 | skills: xpAward.view, |
| 949 | stored: xpAward.stored, |
| 950 | levelUps: xpAward.levelUps ?? [] |
| 951 | }] |
| 952 | }; |
| 953 | } |
| 954 | |
| 955 | #cancelAttack (sessionId, characterId) |
| 956 | { |
| 957 | const { entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 958 | clearEngage(this.ecs, entityId); |
| 959 | return { events: [] }; |
| 960 | } |
| 961 | |
| 962 | #interact (sessionId, characterId, targetEntityId, purpose = null) |
| 963 | { |
| 964 | this.#requireOwnedEntity(sessionId, characterId); |
| 965 | const targetHandle = this.ecs.handleOf(targetEntityId); |
| 966 | if (targetHandle == null) |
| 967 | { |
| 968 | const error = new Error("Target is not here."); |
| 969 | error.userFacing = true; |
| 970 | throw error; |
| 971 | } |
| 972 | if (isUntargetable(this.ecs, targetHandle)) |
| 973 | { |
| 974 | const error = new Error("Nothing to say."); |
| 975 | error.userFacing = true; |
| 976 | throw error; |
| 977 | } |
| 978 | const creature = this.ecs.get(targetHandle, Component.creature); |
| 979 | const def = creature ? mobDefinition(creature.mobTypeId) : null; |
| 980 | const shop = this.ecs.get(targetHandle, Component.shop); |
| 981 | const hasShop = shopHasInterface(shop); |
| 982 | const origin = this.ecs.get(targetHandle, Component.spawnOrigin); |
| 983 | const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : ""; |
| 984 | const intent = purpose === "shop" || purpose === "talk" ? purpose : null; |
| 985 | |
| 986 | if (intent === "shop" && hasShop) |
| 987 | { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } |
| 988 | if (intent === "talk" && dialogueId) |
| 989 | { |
| 990 | // Pin in-worker before return so wander cannot start before the sim thread pins. |
| 991 | this.#pinDialogue(targetEntityId, characterId); |
| 992 | return { |
| 993 | events: [{ |
| 994 | type: "open-dialogue", |
| 995 | sessionId, |
| 996 | characterId, |
| 997 | entityId: targetEntityId, |
| 998 | dialogueId |
| 999 | }] |
| 1000 | }; |
| 1001 | } |
| 1002 | if (intent === "talk" && hasShop) |
| 1003 | { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } |
| 1004 | |
| 1005 | // Default click: prefer dialogue when assigned, else shop, else talkable no-op. |
| 1006 | if (dialogueId) |
| 1007 | { |
| 1008 | this.#pinDialogue(targetEntityId, characterId); |
| 1009 | return { |
| 1010 | events: [{ |
| 1011 | type: "open-dialogue", |
| 1012 | sessionId, |
| 1013 | characterId, |
| 1014 | entityId: targetEntityId, |
| 1015 | dialogueId |
| 1016 | }] |
| 1017 | }; |
| 1018 | } |
| 1019 | if (hasShop) |
| 1020 | { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } |
| 1021 | if (!def?.talkable) |
| 1022 | { |
| 1023 | const error = new Error("They have nothing to say."); |
| 1024 | error.userFacing = true; |
| 1025 | throw error; |
| 1026 | } |
| 1027 | return { events: [] }; |
| 1028 | } |
| 1029 | |
| 1030 | #follow (sessionId, characterId, targetEntityId) |
| 1031 | { |
| 1032 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 1033 | const targetHandle = this.ecs.handleOf(targetEntityId); |
| 1034 | if (targetHandle == null) |
| 1035 | { |
| 1036 | const error = new Error("Target is not here."); |
| 1037 | error.userFacing = true; |
| 1038 | throw error; |
| 1039 | } |
| 1040 | if (targetEntityId === entityId) |
| 1041 | { |
| 1042 | const error = new Error("Cannot follow yourself."); |
| 1043 | error.userFacing = true; |
| 1044 | throw error; |
| 1045 | } |
| 1046 | if (!this.ecs.get(targetHandle, Component.position)) |
| 1047 | { |
| 1048 | const error = new Error("That cannot be followed."); |
| 1049 | error.userFacing = true; |
| 1050 | throw error; |
| 1051 | } |
| 1052 | clearEngage(this.ecs, entityId); |
| 1053 | setFollow(this.ecs, entityId, targetEntityId); |
| 1054 | const path = this.ecs.get(handle, Component.path); |
| 1055 | if (path) |
| 1056 | { path.tiles = []; } |
| 1057 | return { events: [] }; |
| 1058 | } |
| 1059 | |
| 1060 | #cancelFollow (sessionId, characterId) |
| 1061 | { |
| 1062 | const { entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 1063 | clearFollow(this.ecs, entityId); |
| 1064 | return { events: [] }; |
| 1065 | } |
| 1066 | |
| 1067 | #setGait (sessionId, characterId, gait) |
| 1068 | { |
| 1069 | if (gait !== GAIT.walk && gait !== GAIT.run) |
| 1070 | { |
| 1071 | const error = new Error("Gait must be walk or run."); |
| 1072 | error.userFacing = true; |
| 1073 | throw error; |
| 1074 | } |
| 1075 | const { handle } = this.#requireOwnedEntity(sessionId, characterId); |
| 1076 | const movement = this.ecs.get(handle, Component.movement); |
| 1077 | const stamina = this.ecs.get(handle, Component.stamina); |
| 1078 | if (gait === GAIT.run && !(Number(stamina?.current) > 0)) |
| 1079 | { |
| 1080 | const error = new Error("You are too exhausted to run."); |
| 1081 | error.userFacing = true; |
| 1082 | throw error; |
| 1083 | } |
| 1084 | movement.gait = gait; |
| 1085 | const character = this.ecs.get(handle, Component.character); |
| 1086 | return { |
| 1087 | events: character |
| 1088 | ? [this.#staminaEvent(handle, character.characterId, movement.gait)] |
| 1089 | : [] |
| 1090 | }; |
| 1091 | } |
| 1092 | |
| 1093 | #staminaEvent (handle, characterId, gait = null) |
| 1094 | { |
| 1095 | const stamina = this.ecs.get(handle, Component.stamina); |
| 1096 | const movement = this.ecs.get(handle, Component.movement); |
| 1097 | return { |
| 1098 | type: "stamina", |
| 1099 | characterId, |
| 1100 | ...publicStaminaView(stamina), |
| 1101 | gait: gait ?? movement?.gait ?? GAIT.walk |
| 1102 | }; |
| 1103 | } |
| 1104 | |
| 1105 | #consumeRunStamina (handle, events) |
| 1106 | { |
| 1107 | const character = this.ecs.get(handle, Component.character); |
| 1108 | if (!character) |
| 1109 | { return; } |
| 1110 | let stamina = this.ecs.get(handle, Component.stamina); |
| 1111 | if (!stamina) |
| 1112 | { |
| 1113 | stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 }); |
| 1114 | } |
| 1115 | const skills = this.ecs.get(handle, Component.skills); |
| 1116 | syncPlayerStamina(this.ecs, handle); |
| 1117 | const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond); |
| 1118 | stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost); |
| 1119 | stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost; |
| 1120 | let skillsChanged = false; |
| 1121 | const levelUps = []; |
| 1122 | while (stamina.xpDebt >= 1 && skills?.xp) |
| 1123 | { |
| 1124 | stamina.xpDebt -= 1; |
| 1125 | const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT); |
| 1126 | if (result.changed) |
| 1127 | { |
| 1128 | skillsChanged = true; |
| 1129 | syncPlayerStamina(this.ecs, handle); |
| 1130 | } |
| 1131 | if (result.levelUp) |
| 1132 | { levelUps.push(result.levelUp); } |
| 1133 | } |
| 1134 | const movement = this.ecs.get(handle, Component.movement); |
| 1135 | if (stamina.current <= 0 && movement) |
| 1136 | { |
| 1137 | stamina.current = 0; |
| 1138 | movement.gait = GAIT.walk; |
| 1139 | } |
| 1140 | events.push(this.#staminaEvent(handle, character.characterId)); |
| 1141 | if (skillsChanged) |
| 1142 | { |
| 1143 | events.push({ |
| 1144 | type: "skills-updated", |
| 1145 | entityId: this.ecs.entityIdOf(handle), |
| 1146 | characterId: character.characterId, |
| 1147 | skills: publicSkillsView(skills), |
| 1148 | stored: storedSkillXp(skills), |
| 1149 | levelUps |
| 1150 | }); |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | #regenStamina (dt, events) |
| 1155 | { |
| 1156 | if (!(dt > 0)) |
| 1157 | { return; } |
| 1158 | for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement)) |
| 1159 | { |
| 1160 | const { handle, character, stamina, movement } = entity; |
| 1161 | if (this.ecs.has(handle, Component.dead)) |
| 1162 | { continue; } |
| 1163 | // Run gait only blocks regen while actually stepping along a path. |
| 1164 | const path = this.ecs.get(handle, Component.path); |
| 1165 | if (movement.gait === GAIT.run && path?.tiles?.length) |
| 1166 | { continue; } |
| 1167 | syncPlayerStamina(this.ecs, handle); |
| 1168 | const before = Number(stamina.current) || 0; |
| 1169 | if (before >= stamina.max) |
| 1170 | { continue; } |
| 1171 | stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND); |
| 1172 | const after = Number(stamina.current) || 0; |
| 1173 | // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam. |
| 1174 | if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max)) |
| 1175 | { events.push(this.#staminaEvent(handle, character.characterId)); } |
| 1176 | } |
| 1177 | } |
| 1178 | |
| 1179 | #requireOwnedEntity (sessionId, characterId) |
| 1180 | { |
| 1181 | const entityId = this.characterEntities.get(characterId); |
| 1182 | if (!entityId) |
| 1183 | { |
| 1184 | const error = new Error("Character is not in the world."); |
| 1185 | error.userFacing = true; |
| 1186 | throw error; |
| 1187 | } |
| 1188 | const handle = this.ecs.handleOf(entityId); |
| 1189 | const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null; |
| 1190 | if (!identity || identity.sessionId !== sessionId) |
| 1191 | { |
| 1192 | const error = new Error("Character is not in the world."); |
| 1193 | error.userFacing = true; |
| 1194 | throw error; |
| 1195 | } |
| 1196 | if (this.ecs.has(handle, Component.dead)) |
| 1197 | { |
| 1198 | const error = new Error("You are dead."); |
| 1199 | error.userFacing = true; |
| 1200 | throw error; |
| 1201 | } |
| 1202 | return { handle, entityId }; |
| 1203 | } |
| 1204 | |
| 1205 | #stepSystems (now = Date.now(), dt = 1 / 20) |
| 1206 | { |
| 1207 | const events = []; |
| 1208 | const transferRequests = []; |
| 1209 | this.#regenStamina(dt, events); |
| 1210 | events.push(...stepStatusEffects(this, now, dt)); |
| 1211 | const flight = stepFreeFlight(this, now); |
| 1212 | for (const event of flight) |
| 1213 | { |
| 1214 | if (event.type === "transfer-request") |
| 1215 | { |
| 1216 | const payload = serializeEntity(this.ecs, event.entityId); |
| 1217 | transferRequests.push({ |
| 1218 | entityId: event.entityId, |
| 1219 | fromTileX: event.fromTileX, |
| 1220 | fromTileY: event.fromTileY, |
| 1221 | destTileX: event.destTileX, |
| 1222 | destTileY: event.destTileY, |
| 1223 | toRegionX: event.toRegionX, |
| 1224 | toRegionY: event.toRegionY, |
| 1225 | dimensionId: event.dimensionId ?? OVERWORLD_ID, |
| 1226 | payload |
| 1227 | }); |
| 1228 | continue; |
| 1229 | } |
| 1230 | events.push(event); |
| 1231 | } |
| 1232 | stepAggression(this, now); |
| 1233 | events.push(...stepCombat(this, now)); |
| 1234 | events.push(...stepPendingSpellCast(this, now)); |
| 1235 | events.push(...processSpellImpacts(this, now)); |
| 1236 | events.push(...stepSpellAutoCast(this, now)); |
| 1237 | events.push(...tickSpellLights(this, now)); |
| 1238 | stepFollow(this); |
| 1239 | const gather = stepGather(this, now); |
| 1240 | events.push(...gather.events); |
| 1241 | for (const entry of gather.privates ?? []) |
| 1242 | { |
| 1243 | events.push({ |
| 1244 | type: "inventory", |
| 1245 | characterId: entry.characterId, |
| 1246 | ...entry.bag |
| 1247 | }); |
| 1248 | } |
| 1249 | const craft = stepCrafting(this, now); |
| 1250 | events.push(...craft.events); |
| 1251 | for (const entry of craft.privates ?? []) |
| 1252 | { |
| 1253 | events.push({ |
| 1254 | type: "inventory", |
| 1255 | characterId: entry.characterId, |
| 1256 | ...entry.bag |
| 1257 | }); |
| 1258 | } |
| 1259 | return { events, transferRequests }; |
| 1260 | } |
| 1261 | |
| 1262 | #stepMovement (now = Date.now()) |
| 1263 | { |
| 1264 | const events = expireGroundItems(this, now); |
| 1265 | const transferRequests = []; |
| 1266 | events.push(...pruneShopBrowsers(this)); |
| 1267 | events.push(...this.#pruneDialogueBrowsers()); |
| 1268 | this.#queueAmbientWander(); |
| 1269 | this.#queueSpawnerWander(); |
| 1270 | this.#queueExchangeStations(); |
| 1271 | for (const entity of this.ecs.query(Component.position, Component.movement)) |
| 1272 | { |
| 1273 | const { handle, entityId, position, movement } = entity; |
| 1274 | if (this.ecs.has(handle, Component.dead)) |
| 1275 | { continue; } |
| 1276 | if (this.ecs.has(handle, Component.flight)) |
| 1277 | { continue; } |
| 1278 | const path = this.ecs.get(handle, Component.path); |
| 1279 | const tiles = path?.tiles; |
| 1280 | if (this.frozen.has(entityId) || !tiles?.length) |
| 1281 | { |
| 1282 | if (path) |
| 1283 | { path.stuckSince = null; } |
| 1284 | continue; |
| 1285 | } |
| 1286 | if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID)) |
| 1287 | { continue; } |
| 1288 | |
| 1289 | this.#repathIfNavigationStuck(entityId, position, movement, path, now); |
| 1290 | |
| 1291 | const stamina = this.ecs.get(handle, Component.stamina); |
| 1292 | if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0)) |
| 1293 | { movement.gait = GAIT.walk; } |
| 1294 | const isWalk = movement.gait !== GAIT.run; |
| 1295 | if (isWalk) |
| 1296 | { |
| 1297 | movement.walkCarry = (movement.walkCarry + 1) % 2; |
| 1298 | if (movement.walkCarry !== 0) |
| 1299 | { continue; } |
| 1300 | } |
| 1301 | |
| 1302 | const next = tiles[0]; |
| 1303 | if (!next) |
| 1304 | { continue; } |
| 1305 | const destRegionX = tileToRegion(next.x); |
| 1306 | const destRegionY = tileToRegion(next.y); |
| 1307 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 1308 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 1309 | { |
| 1310 | this.frozen.add(entityId); |
| 1311 | transferRequests.push({ |
| 1312 | entityId, |
| 1313 | fromTileX: position.tileX, |
| 1314 | fromTileY: position.tileY, |
| 1315 | destTileX: next.x, |
| 1316 | destTileY: next.y, |
| 1317 | toRegionX: destRegionX, |
| 1318 | toRegionY: destRegionY, |
| 1319 | dimensionId, |
| 1320 | payload: serializeEntity(this.ecs, entityId) |
| 1321 | }); |
| 1322 | continue; |
| 1323 | } |
| 1324 | |
| 1325 | if (!this.walkableFor(entityId, next.x, next.y)) |
| 1326 | { |
| 1327 | const combat = this.ecs.get(handle, Component.combat); |
| 1328 | if (combat?.targetEntityId != null) |
| 1329 | { |
| 1330 | const targetHandle = this.ecs.handleOf(combat.targetEntityId); |
| 1331 | const targetPos = targetHandle != null |
| 1332 | ? this.ecs.get(targetHandle, Component.position) |
| 1333 | : null; |
| 1334 | const blockedByTarget = targetPos |
| 1335 | && next.x === targetPos.tileX |
| 1336 | && next.y === targetPos.tileY; |
| 1337 | if (!blockedByTarget) |
| 1338 | { path.tiles = []; } |
| 1339 | } |
| 1340 | continue; |
| 1341 | } |
| 1342 | |
| 1343 | const fromTileX = position.tileX; |
| 1344 | const fromTileY = position.tileY; |
| 1345 | const flying = this.#isFlying(handle); |
| 1346 | if (!flying) |
| 1347 | { this.#vacate(entityId, fromTileX, fromTileY); } |
| 1348 | position.tileX = next.x; |
| 1349 | position.tileY = next.y; |
| 1350 | tiles.shift(); |
| 1351 | if (!flying) |
| 1352 | { this.#occupy(entityId, position.tileX, position.tileY); } |
| 1353 | path.stuckSince = now; |
| 1354 | path.stuckTileX = position.tileX; |
| 1355 | path.stuckTileY = position.tileY; |
| 1356 | recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY); |
| 1357 | consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY); |
| 1358 | if (!isWalk) |
| 1359 | { this.#consumeRunStamina(handle, events); } |
| 1360 | events.push(this.#moveEvent(entityId, fromTileX, fromTileY)); |
| 1361 | } |
| 1362 | return { events, transferRequests }; |
| 1363 | } |
| 1364 | |
| 1365 | /** |
| 1366 | * If we still have a destination but have not left this tile for NAV_STUCK_MS, |
| 1367 | * recompute A* to the same goal (around whoever is blocking the old route). |
| 1368 | */ |
| 1369 | #repathIfNavigationStuck (entityId, position, movement, path, now) |
| 1370 | { |
| 1371 | if (!path?.tiles?.length) |
| 1372 | { |
| 1373 | path.stuckSince = null; |
| 1374 | return; |
| 1375 | } |
| 1376 | if ( |
| 1377 | path.stuckSince == null |
| 1378 | || path.stuckTileX !== position.tileX |
| 1379 | || path.stuckTileY !== position.tileY |
| 1380 | ) |
| 1381 | { |
| 1382 | path.stuckSince = now; |
| 1383 | path.stuckTileX = position.tileX; |
| 1384 | path.stuckTileY = position.tileY; |
| 1385 | return; |
| 1386 | } |
| 1387 | if (now - path.stuckSince < NAV_STUCK_MS) |
| 1388 | { return; } |
| 1389 | |
| 1390 | const goal = path.tiles[path.tiles.length - 1]; |
| 1391 | if (!goal || (goal.x === position.tileX && goal.y === position.tileY)) |
| 1392 | { |
| 1393 | path.tiles = []; |
| 1394 | path.stuckSince = null; |
| 1395 | return; |
| 1396 | } |
| 1397 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1398 | const stuckHandle = this.ecs.handleOf(entityId); |
| 1399 | path.tiles = findPath( |
| 1400 | position.tileX, |
| 1401 | position.tileY, |
| 1402 | goal.x, |
| 1403 | goal.y, |
| 1404 | (x, y) => this.isClearStanding(entityId, x, y), |
| 1405 | bounds.minX, |
| 1406 | bounds.minY, |
| 1407 | bounds.maxX, |
| 1408 | bounds.maxY, |
| 1409 | { preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character) } |
| 1410 | ); |
| 1411 | path.stuckSince = now; |
| 1412 | path.stuckTileX = position.tileX; |
| 1413 | path.stuckTileY = position.tileY; |
| 1414 | if (movement) |
| 1415 | { movement.walkCarry = 0; } |
| 1416 | } |
| 1417 | |
| 1418 | #queueAmbientWander () |
| 1419 | { |
| 1420 | for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature)) |
| 1421 | { |
| 1422 | const def = mobDefinition(entity.creature.mobTypeId); |
| 1423 | if (!def?.ambient || def.freeFlight) |
| 1424 | { continue; } |
| 1425 | if (this.ecs.get(entity.handle, Component.spawnOrigin)) |
| 1426 | { continue; } |
| 1427 | const path = this.ecs.get(entity.handle, Component.path); |
| 1428 | if (!path) |
| 1429 | { continue; } |
| 1430 | if (path.tiles?.length) |
| 1431 | { continue; } |
| 1432 | if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID)) |
| 1433 | { continue; } |
| 1434 | if (Math.random() > 0.35) |
| 1435 | { continue; } |
| 1436 | const dirs = [ |
| 1437 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1438 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1439 | ]; |
| 1440 | const dir = dirs[Math.floor(Math.random() * dirs.length)]; |
| 1441 | const nextX = entity.position.tileX + dir.x; |
| 1442 | const nextY = entity.position.tileY + dir.y; |
| 1443 | if (!this.isClearStanding(entity.entityId, nextX, nextY)) |
| 1444 | { continue; } |
| 1445 | path.tiles = [{ x: nextX, y: nextY }]; |
| 1446 | } |
| 1447 | } |
| 1448 | |
| 1449 | /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */ |
| 1450 | #queueSpawnerWander () |
| 1451 | { |
| 1452 | for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin)) |
| 1453 | { |
| 1454 | const combat = this.ecs.get(entity.handle, Component.combat); |
| 1455 | if (combat?.targetEntityId != null) |
| 1456 | { continue; } |
| 1457 | const follow = this.ecs.get(entity.handle, Component.follow); |
| 1458 | if (follow?.targetEntityId != null) |
| 1459 | { continue; } |
| 1460 | const shop = this.ecs.get(entity.handle, Component.shop); |
| 1461 | if (shopHasActiveBrowsers(shop)) |
| 1462 | { continue; } |
| 1463 | const origin = entity.spawnOrigin; |
| 1464 | if (hasDialogueBrowsers(origin)) |
| 1465 | { continue; } |
| 1466 | if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY)) |
| 1467 | { continue; } |
| 1468 | const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId); |
| 1469 | if (def?.freeFlight) |
| 1470 | { continue; } |
| 1471 | const path = this.ecs.get(entity.handle, Component.path); |
| 1472 | if (!path || path.tiles?.length) |
| 1473 | { continue; } |
| 1474 | if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID)) |
| 1475 | { continue; } |
| 1476 | // ~4× longer idle stands than the old 0.4 chance (mobs mostly idle, rarely walk). |
| 1477 | if (Math.random() > 0.1) |
| 1478 | { continue; } |
| 1479 | |
| 1480 | const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX; |
| 1481 | const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY; |
| 1482 | const range = Math.max(0, origin.wanderRangeTiles | 0); |
| 1483 | const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range); |
| 1484 | if (!goal) |
| 1485 | { continue; } |
| 1486 | if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY) |
| 1487 | { continue; } |
| 1488 | const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1489 | const tiles = findPath( |
| 1490 | entity.position.tileX, |
| 1491 | entity.position.tileY, |
| 1492 | goal.tileX, |
| 1493 | goal.tileY, |
| 1494 | (x, y) => this.walkableFor(entity.entityId, x, y), |
| 1495 | bounds.minX, |
| 1496 | bounds.minY, |
| 1497 | bounds.maxX, |
| 1498 | bounds.maxY |
| 1499 | ); |
| 1500 | if (!tiles?.length) |
| 1501 | { continue; } |
| 1502 | path.tiles = tiles; |
| 1503 | } |
| 1504 | } |
| 1505 | |
| 1506 | /** |
| 1507 | * Send an idle Central Exchange clerk to the staff-side tile of a counter. |
| 1508 | * message: { stationTileX, stationTileY } |
| 1509 | */ |
| 1510 | #stationExchangeClerk (message) |
| 1511 | { |
| 1512 | const stationTileX = message.stationTileX | 0; |
| 1513 | const stationTileY = message.stationTileY | 0; |
| 1514 | if (!this.isEnterable(stationTileX, stationTileY)) |
| 1515 | { return { ok: false, reason: "blocked" }; } |
| 1516 | |
| 1517 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) |
| 1518 | { |
| 1519 | if (!entity.spawnOrigin?.centralExchange) |
| 1520 | { continue; } |
| 1521 | if ( |
| 1522 | Number.isInteger(entity.spawnOrigin.stationTileX) |
| 1523 | && entity.spawnOrigin.stationTileX === stationTileX |
| 1524 | && entity.spawnOrigin.stationTileY === stationTileY |
| 1525 | ) |
| 1526 | { return { ok: true, entityId: entity.entityId, already: true }; } |
| 1527 | } |
| 1528 | |
| 1529 | let best = null; |
| 1530 | let bestDist = Infinity; |
| 1531 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) |
| 1532 | { |
| 1533 | if (!entity.spawnOrigin?.centralExchange) |
| 1534 | { continue; } |
| 1535 | if (Number.isInteger(entity.spawnOrigin.stationTileX)) |
| 1536 | { continue; } |
| 1537 | const dist = Math.max( |
| 1538 | Math.abs(entity.position.tileX - stationTileX), |
| 1539 | Math.abs(entity.position.tileY - stationTileY) |
| 1540 | ); |
| 1541 | if (dist < bestDist) |
| 1542 | { |
| 1543 | bestDist = dist; |
| 1544 | best = entity; |
| 1545 | } |
| 1546 | } |
| 1547 | if (!best) |
| 1548 | { return { ok: false, reason: "none-available" }; } |
| 1549 | |
| 1550 | const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1551 | const tiles = findPath( |
| 1552 | best.position.tileX, |
| 1553 | best.position.tileY, |
| 1554 | stationTileX, |
| 1555 | stationTileY, |
| 1556 | (x, y) => this.walkableFor(best.entityId, x, y), |
| 1557 | bounds.minX, |
| 1558 | bounds.minY, |
| 1559 | bounds.maxX, |
| 1560 | bounds.maxY |
| 1561 | ); |
| 1562 | best.spawnOrigin.stationTileX = stationTileX; |
| 1563 | best.spawnOrigin.stationTileY = stationTileY; |
| 1564 | if (tiles?.length) |
| 1565 | { best.path.tiles = tiles; } |
| 1566 | else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY) |
| 1567 | { best.path.tiles = []; } |
| 1568 | else |
| 1569 | { return { ok: false, reason: "no-path" }; } |
| 1570 | return { ok: true, entityId: best.entityId }; |
| 1571 | } |
| 1572 | |
| 1573 | /** |
| 1574 | * Clear a CE clerk's station assignment so wander can resume. |
| 1575 | * message: { stationTileX, stationTileY } |
| 1576 | */ |
| 1577 | #releaseExchangeClerk (message) |
| 1578 | { |
| 1579 | const stationTileX = message.stationTileX | 0; |
| 1580 | const stationTileY = message.stationTileY | 0; |
| 1581 | let released = 0; |
| 1582 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.path)) |
| 1583 | { |
| 1584 | if (!entity.spawnOrigin?.centralExchange) |
| 1585 | { continue; } |
| 1586 | if ( |
| 1587 | entity.spawnOrigin.stationTileX !== stationTileX |
| 1588 | || entity.spawnOrigin.stationTileY !== stationTileY |
| 1589 | ) |
| 1590 | { continue; } |
| 1591 | entity.spawnOrigin.stationTileX = null; |
| 1592 | entity.spawnOrigin.stationTileY = null; |
| 1593 | entity.path.tiles = []; |
| 1594 | released += 1; |
| 1595 | } |
| 1596 | return { ok: true, released }; |
| 1597 | } |
| 1598 | |
| 1599 | #pinDialogue (entityId, characterId) |
| 1600 | { |
| 1601 | const handle = this.ecs.handleOf(entityId | 0); |
| 1602 | if (handle == null) |
| 1603 | { return { ok: false }; } |
| 1604 | const origin = this.ecs.get(handle, Component.spawnOrigin); |
| 1605 | if (!origin) |
| 1606 | { return { ok: false }; } |
| 1607 | if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object") |
| 1608 | { origin.dialogueBrowsers = Object.create(null); } |
| 1609 | origin.dialogueBrowsers[characterId | 0] = true; |
| 1610 | const path = this.ecs.get(handle, Component.path); |
| 1611 | if (path) |
| 1612 | { path.tiles = []; } |
| 1613 | return { ok: true }; |
| 1614 | } |
| 1615 | |
| 1616 | #unpinDialogue (entityId, characterId) |
| 1617 | { |
| 1618 | const handle = this.ecs.handleOf(entityId | 0); |
| 1619 | if (handle == null) |
| 1620 | { return { ok: false }; } |
| 1621 | const origin = this.ecs.get(handle, Component.spawnOrigin); |
| 1622 | if (!origin?.dialogueBrowsers) |
| 1623 | { return { ok: true }; } |
| 1624 | delete origin.dialogueBrowsers[characterId | 0]; |
| 1625 | return { ok: true }; |
| 1626 | } |
| 1627 | |
| 1628 | #pruneDialogueBrowsers () |
| 1629 | { |
| 1630 | const events = []; |
| 1631 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) |
| 1632 | { |
| 1633 | const browsers = entity.spawnOrigin?.dialogueBrowsers; |
| 1634 | if (!browsers || typeof browsers !== "object") |
| 1635 | { continue; } |
| 1636 | const ids = Object.keys(browsers).map((id) => Number(id)); |
| 1637 | if (!ids.length) |
| 1638 | { continue; } |
| 1639 | const path = this.ecs.get(entity.handle, Component.path); |
| 1640 | if (path) |
| 1641 | { path.tiles = []; } |
| 1642 | for (const characterId of ids) |
| 1643 | { |
| 1644 | const playerEntityId = this.characterEntities.get(characterId); |
| 1645 | if (playerEntityId == null) |
| 1646 | { |
| 1647 | delete browsers[characterId]; |
| 1648 | continue; |
| 1649 | } |
| 1650 | const playerHandle = this.ecs.handleOf(playerEntityId); |
| 1651 | const playerPos = this.ecs.get(playerHandle, Component.position); |
| 1652 | const stillNear = playerPos |
| 1653 | && chebyshev( |
| 1654 | playerPos.tileX, |
| 1655 | playerPos.tileY, |
| 1656 | entity.position.tileX, |
| 1657 | entity.position.tileY |
| 1658 | ) <= 1; |
| 1659 | if (stillNear) |
| 1660 | { continue; } |
| 1661 | delete browsers[characterId]; |
| 1662 | const identity = this.ecs.get(playerHandle, Component.networkIdentity); |
| 1663 | events.push({ |
| 1664 | type: "dialogue-walk-away", |
| 1665 | sessionId: identity?.sessionId ?? null, |
| 1666 | characterId, |
| 1667 | npcEntityId: entity.entityId |
| 1668 | }); |
| 1669 | } |
| 1670 | } |
| 1671 | return events; |
| 1672 | } |
| 1673 | |
| 1674 | /** Keep stationed CE clerks at their counter tile. */ |
| 1675 | #queueExchangeStations () |
| 1676 | { |
| 1677 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) |
| 1678 | { |
| 1679 | if (!entity.spawnOrigin?.centralExchange) |
| 1680 | { continue; } |
| 1681 | const sx = entity.spawnOrigin.stationTileX; |
| 1682 | const sy = entity.spawnOrigin.stationTileY; |
| 1683 | if (!Number.isInteger(sx) || !Number.isInteger(sy)) |
| 1684 | { continue; } |
| 1685 | if (entity.position.tileX === sx && entity.position.tileY === sy) |
| 1686 | { |
| 1687 | entity.path.tiles = []; |
| 1688 | continue; |
| 1689 | } |
| 1690 | if (entity.path.tiles?.length) |
| 1691 | { continue; } |
| 1692 | const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1693 | const tiles = findPath( |
| 1694 | entity.position.tileX, |
| 1695 | entity.position.tileY, |
| 1696 | sx, |
| 1697 | sy, |
| 1698 | (x, y) => this.walkableFor(entity.entityId, x, y), |
| 1699 | bounds.minX, |
| 1700 | bounds.minY, |
| 1701 | bounds.maxX, |
| 1702 | bounds.maxY |
| 1703 | ); |
| 1704 | if (tiles?.length) |
| 1705 | { entity.path.tiles = tiles; } |
| 1706 | } |
| 1707 | } |
| 1708 | |
| 1709 | #applyTransfer (message) |
| 1710 | { |
| 1711 | const payload = message.payload; |
| 1712 | const entityId = payload.entityId; |
| 1713 | if (this.ecs.hasEntity(entityId)) |
| 1714 | { return { accepted: false, reason: "already-present" }; } |
| 1715 | |
| 1716 | const position = payload.components?.position; |
| 1717 | const destTileX = message.destTileX ?? position?.tileX; |
| 1718 | const destTileY = message.destTileY ?? position?.tileY; |
| 1719 | const dimensionId = normalizeDimensionId( |
| 1720 | message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID |
| 1721 | ); |
| 1722 | if (destTileX == null || destTileY == null) |
| 1723 | { return { accepted: false, reason: "missing-destination" }; } |
| 1724 | if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId)) |
| 1725 | { return { accepted: false, reason: "not-owner" }; } |
| 1726 | |
| 1727 | const creature = payload.components?.creature; |
| 1728 | const flying = !!mobDefinition(creature?.mobTypeId)?.flying; |
| 1729 | if (flying) |
| 1730 | { |
| 1731 | const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId); |
| 1732 | if (!data?.open) |
| 1733 | { return { accepted: false, reason: "blocked" }; } |
| 1734 | } |
| 1735 | else if (!this.isEnterable(destTileX, destTileY, dimensionId)) |
| 1736 | { return { accepted: false, reason: "blocked" }; } |
| 1737 | |
| 1738 | deserializeEntity(this.ecs, payload); |
| 1739 | const handle = this.ecs.handleOf(entityId); |
| 1740 | const livePosition = this.ecs.get(handle, Component.position); |
| 1741 | const path = this.ecs.get(handle, Component.path); |
| 1742 | livePosition.tileX = destTileX; |
| 1743 | livePosition.tileY = destTileY; |
| 1744 | livePosition.dimensionId = dimensionId; |
| 1745 | if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY) |
| 1746 | { path.tiles.shift(); } |
| 1747 | if (!flying) |
| 1748 | { this.#occupy(entityId, destTileX, destTileY); } |
| 1749 | const character = this.ecs.get(handle, Component.character); |
| 1750 | if (character?.characterId) |
| 1751 | { this.characterEntities.set(character.characterId, entityId); } |
| 1752 | this.frozen.delete(entityId); |
| 1753 | return { |
| 1754 | accepted: true, |
| 1755 | entity: publicEntityView(this.ecs, entityId) |
| 1756 | }; |
| 1757 | } |
| 1758 | |
| 1759 | #commitTransfer (entityId) |
| 1760 | { |
| 1761 | if (!this.ecs.hasEntity(entityId)) |
| 1762 | { return null; } |
| 1763 | return this.#destroyEntity(entityId); |
| 1764 | } |
| 1765 | |
| 1766 | #abortTransfer (entityId) |
| 1767 | { |
| 1768 | this.frozen.delete(entityId); |
| 1769 | return publicEntityView(this.ecs, entityId); |
| 1770 | } |
| 1771 | |
| 1772 | #listLoaders () |
| 1773 | { |
| 1774 | return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({ |
| 1775 | entityId: entity.entityId, |
| 1776 | tileX: entity.position.tileX, |
| 1777 | tileY: entity.position.tileY, |
| 1778 | dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID), |
| 1779 | chunkLoader: { ...entity.chunkLoader } |
| 1780 | })); |
| 1781 | } |
| 1782 | |
| 1783 | #listPublicEntities () |
| 1784 | { |
| 1785 | return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean); |
| 1786 | } |
| 1787 | |
| 1788 | #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 1789 | { |
| 1790 | const dim = normalizeDimensionId(dimensionId); |
| 1791 | const records = []; |
| 1792 | for (const entity of this.ecs.query(Component.position)) |
| 1793 | { |
| 1794 | const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID); |
| 1795 | if (entityDim !== dim) |
| 1796 | { continue; } |
| 1797 | if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY) |
| 1798 | { continue; } |
| 1799 | records.push({ |
| 1800 | ...publicEntityView(this.ecs, entity.entityId), |
| 1801 | persistent: this.ecs.has(entity.handle, Component.persistent), |
| 1802 | payload: serializeEntity(this.ecs, entity.entityId) |
| 1803 | }); |
| 1804 | } |
| 1805 | return records; |
| 1806 | } |
| 1807 | |
| 1808 | #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID) |
| 1809 | { |
| 1810 | const dim = normalizeDimensionId(dimensionId); |
| 1811 | const data = this.#chunkData(chunkX, chunkY, dim); |
| 1812 | if (staticOnly) |
| 1813 | { |
| 1814 | return { |
| 1815 | chunkX, |
| 1816 | chunkY, |
| 1817 | dimensionId: dim, |
| 1818 | open: data.open, |
| 1819 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open), |
| 1820 | grounds: data.grounds, |
| 1821 | blocks: data.blocks, |
| 1822 | light: data.light, |
| 1823 | entities: [], |
| 1824 | groundItems: [] |
| 1825 | }; |
| 1826 | } |
| 1827 | const entities = []; |
| 1828 | for (const entity of this.ecs.query(Component.position, Component.appearance)) |
| 1829 | { |
| 1830 | const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID); |
| 1831 | if (entityDim !== dim) |
| 1832 | { continue; } |
| 1833 | if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY) |
| 1834 | { continue; } |
| 1835 | entities.push(publicEntityView(this.ecs, entity.entityId)); |
| 1836 | } |
| 1837 | return { |
| 1838 | chunkX, |
| 1839 | chunkY, |
| 1840 | dimensionId: dim, |
| 1841 | open: data.open, |
| 1842 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open), |
| 1843 | grounds: data.grounds, |
| 1844 | blocks: data.blocks, |
| 1845 | light: data.light, |
| 1846 | entities, |
| 1847 | groundItems: groundItemsInChunk(this, chunkX, chunkY) |
| 1848 | }; |
| 1849 | } |
| 1850 | |
| 1851 | #moveEvent (entityId, fromTileX, fromTileY) |
| 1852 | { |
| 1853 | const view = publicEntityView(this.ecs, entityId); |
| 1854 | return { |
| 1855 | type: "entity-move", |
| 1856 | entityId, |
| 1857 | fromTileX, |
| 1858 | fromTileY, |
| 1859 | tileX: view.tileX, |
| 1860 | tileY: view.tileY, |
| 1861 | worldX: view.worldX, |
| 1862 | worldY: view.worldY, |
| 1863 | gait: view.gait, |
| 1864 | freeFlight: !!view.freeFlight |
| 1865 | }; |
| 1866 | } |
| 1867 | |
| 1868 | chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1869 | { |
| 1870 | const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)); |
| 1871 | return !!chunk && !chunk.replica && chunk.simulating; |
| 1872 | } |
| 1873 | |
| 1874 | walkableFor (entityId, tileX, tileY) |
| 1875 | { |
| 1876 | const dim = this.#entityDimensionId(entityId); |
| 1877 | const handle = this.ecs.handleOf(entityId); |
| 1878 | if (this.#isFlying(handle)) |
| 1879 | { |
| 1880 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); |
| 1881 | return !!data?.open; |
| 1882 | } |
| 1883 | // Entities pass through each other; only terrain / closed chunks block movement. |
| 1884 | return this.isEnterable(tileX, tileY, dim); |
| 1885 | } |
| 1886 | |
| 1887 | /** |
| 1888 | * Standing tile with no other mob/player (self allowed). Used for wander goals |
| 1889 | * and melee attack stance. |
| 1890 | */ |
| 1891 | isClearStanding (entityId, tileX, tileY) |
| 1892 | { |
| 1893 | const dim = this.#entityDimensionId(entityId); |
| 1894 | if (!this.isEnterable(tileX, tileY, dim)) |
| 1895 | { return false; } |
| 1896 | return !this.#hasOtherOccupant(entityId, tileX, tileY, dim); |
| 1897 | } |
| 1898 | |
| 1899 | destroyEntity (entityId) |
| 1900 | { |
| 1901 | return this.#destroyEntity(entityId); |
| 1902 | } |
| 1903 | |
| 1904 | occupied (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1905 | { |
| 1906 | return this.#anyOccupant(tileX, tileY, dimensionId); |
| 1907 | } |
| 1908 | |
| 1909 | #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1910 | { |
| 1911 | return this.chunkIsSimulating(tileX, tileY, dimensionId); |
| 1912 | } |
| 1913 | |
| 1914 | #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 1915 | { |
| 1916 | const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId)); |
| 1917 | if (loaded) |
| 1918 | { return loaded.data; } |
| 1919 | return createEmptyChunkData(this.settings.defaultGroundTypeId); |
| 1920 | } |
| 1921 | |
| 1922 | isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1923 | { |
| 1924 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 1925 | if (!data.open) |
| 1926 | { return false; } |
| 1927 | return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 1928 | } |
| 1929 | |
| 1930 | isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1931 | { |
| 1932 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 1933 | if (!data.open) |
| 1934 | { return false; } |
| 1935 | return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 1936 | } |
| 1937 | |
| 1938 | #walkableFor (entityId, tileX, tileY) |
| 1939 | { |
| 1940 | return this.walkableFor(entityId, tileX, tileY); |
| 1941 | } |
| 1942 | |
| 1943 | #isFlying (handle) |
| 1944 | { |
| 1945 | if (handle == null) |
| 1946 | { return false; } |
| 1947 | const creature = this.ecs.get(handle, Component.creature); |
| 1948 | return !!mobDefinition(creature?.mobTypeId)?.flying; |
| 1949 | } |
| 1950 | |
| 1951 | #entityDimensionId (entityId) |
| 1952 | { |
| 1953 | const handle = this.ecs.handleOf(entityId); |
| 1954 | const position = handle != null ? this.ecs.get(handle, Component.position) : null; |
| 1955 | return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID); |
| 1956 | } |
| 1957 | |
| 1958 | #occupy (entityId, tileX, tileY) |
| 1959 | { |
| 1960 | const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId)); |
| 1961 | let set = this.occupancy.get(key); |
| 1962 | if (!set) |
| 1963 | { |
| 1964 | set = new Set(); |
| 1965 | this.occupancy.set(key, set); |
| 1966 | } |
| 1967 | set.add(entityId); |
| 1968 | } |
| 1969 | |
| 1970 | #vacate (entityId, tileX, tileY) |
| 1971 | { |
| 1972 | const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId)); |
| 1973 | const set = this.occupancy.get(key); |
| 1974 | if (!set) |
| 1975 | { return; } |
| 1976 | set.delete(entityId); |
| 1977 | if (set.size === 0) |
| 1978 | { this.occupancy.delete(key); } |
| 1979 | } |
| 1980 | |
| 1981 | #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1982 | { |
| 1983 | const key = tileKey(tileX, tileY, dimensionId); |
| 1984 | const local = this.occupancy.get(key); |
| 1985 | if (local?.size) |
| 1986 | { return local.values().next().value; } |
| 1987 | const ghosts = this.ghostOccupancy.get(key); |
| 1988 | if (ghosts?.size) |
| 1989 | { return ghosts.values().next().value; } |
| 1990 | return null; |
| 1991 | } |
| 1992 | |
| 1993 | #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null) |
| 1994 | { |
| 1995 | const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId); |
| 1996 | const key = tileKey(tileX, tileY, dim); |
| 1997 | const local = this.occupancy.get(key); |
| 1998 | if (local) |
| 1999 | { |
| 2000 | for (const id of local) |
| 2001 | { |
| 2002 | if (id !== entityId) |
| 2003 | { return true; } |
| 2004 | } |
| 2005 | } |
| 2006 | const ghosts = this.ghostOccupancy.get(key); |
| 2007 | if (ghosts) |
| 2008 | { |
| 2009 | for (const id of ghosts) |
| 2010 | { |
| 2011 | if (id !== entityId) |
| 2012 | { return true; } |
| 2013 | } |
| 2014 | } |
| 2015 | return false; |
| 2016 | } |
| 2017 | |
| 2018 | /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */ |
| 2019 | #occupied (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2020 | { |
| 2021 | return this.#anyOccupant(tileX, tileY, dimensionId); |
| 2022 | } |
| 2023 | } |
| 2024 | |
| 2025 | function pickWanderGoalInRange (world, entityId, originX, originY, range) |
| 2026 | { |
| 2027 | const radius = Math.max(0, range | 0); |
| 2028 | for (let attempt = 0; attempt < 24; attempt++) |
| 2029 | { |
| 2030 | const tileX = originX + randInt(-radius, radius); |
| 2031 | const tileY = originY + randInt(-radius, radius); |
| 2032 | if (!world.isClearStanding(entityId, tileX, tileY)) |
| 2033 | { continue; } |
| 2034 | return { tileX, tileY }; |
| 2035 | } |
| 2036 | return null; |
| 2037 | } |
| 2038 | |
| 2039 | function hasDialogueBrowsers (origin) |
| 2040 | { |
| 2041 | const browsers = origin?.dialogueBrowsers; |
| 2042 | if (!browsers || typeof browsers !== "object") |
| 2043 | { return false; } |
| 2044 | return Object.keys(browsers).length > 0; |
| 2045 | } |
| 2046 | |
| 2047 | function randInt (min, max) |
| 2048 | { |
| 2049 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 2050 | } |
| 2051 | |
| 2052 | export function replicaNeededForOwnedChunks (ownedChunkKeys) |
| 2053 | { |
| 2054 | const needed = new Set(); |
| 2055 | for (const key of ownedChunkKeys) |
| 2056 | { |
| 2057 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 2058 | for (let dy = -1; dy <= 1; dy++) |
| 2059 | { |
| 2060 | for (let dx = -1; dx <= 1; dx++) |
| 2061 | { |
| 2062 | if (dx === 0 && dy === 0) |
| 2063 | { continue; } |
| 2064 | needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId)); |
| 2065 | } |
| 2066 | } |
| 2067 | } |
| 2068 | return needed; |
| 2069 | } |