| 1 | import { GAIT, VISIBLE_CHUNK_RADIUS, STATIC_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 | tileIndex |
| 13 | } from "../world/coordinates.js"; |
| 14 | import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js"; |
| 15 | import { closedNeighborEdges } from "../world/chunkFlags.js"; |
| 16 | import { EcsWorld } from "../ecs/world.js"; |
| 17 | import { Component } from "../ecs/components.js"; |
| 18 | import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js"; |
| 19 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 20 | import { WorkerMessage } from "./protocol.js"; |
| 21 | import { collectSpawnRequests } from "./spawners.js"; |
| 22 | import { mobDefinition } from "../../../shared/definitions/mobs.js"; |
| 23 | import { |
| 24 | bagView, |
| 25 | applyBagView, |
| 26 | addGroundItem, |
| 27 | expireGroundItems, |
| 28 | groundItemsInChunk, |
| 29 | groundItemsInRegion, |
| 30 | handleItemCommand, |
| 31 | removeGroundItem, |
| 32 | publicGroundItem, |
| 33 | setGroundItemsForRegion, |
| 34 | stripCarriedCoinsForDeath |
| 35 | } from "../items/bags.js"; |
| 36 | import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js"; |
| 37 | import { stepSummons } from "../spells/summons.js"; |
| 38 | import { stepJadeiteFairies } from "../spells/jadeiteFairy.js"; |
| 39 | import { |
| 40 | handleJewelryTeleportCommand, |
| 41 | stepJewelryTeleports, |
| 42 | cancelJewelryTeleport |
| 43 | } from "../equipment/jewelryTeleport.js"; |
| 44 | import { publicSpellsView } from "../../../shared/spells/state.js"; |
| 45 | import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js"; |
| 46 | import { |
| 47 | handleGatherCommand, |
| 48 | stepGather, |
| 49 | cancelGather, |
| 50 | clearOreRespawnsForChunk, |
| 51 | clearTreeRespawnsForChunk, |
| 52 | clearPlantRespawnsForChunk |
| 53 | } from "../gathering/service.js"; |
| 54 | import { handleCraftCommand, stepCrafting } from "../crafting/service.js"; |
| 55 | import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js"; |
| 56 | import { handleFishingCommand, stepFishing } from "../fishing/service.js"; |
| 57 | import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js"; |
| 58 | import { handleAlchemyCommand } from "../alchemy/service.js"; |
| 59 | import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js"; |
| 60 | import { |
| 61 | applyRemoteMeleeSwing, |
| 62 | applyRemoteRangedShot, |
| 63 | attackProfileOf, |
| 64 | clearEngage, |
| 65 | engageTarget, |
| 66 | ensureMobCombat, |
| 67 | isUntargetable, |
| 68 | queueMeleeApproach, |
| 69 | queueStandInRangeApproach, |
| 70 | resolveCombatTarget, |
| 71 | silenceDeadPlayer, |
| 72 | stepAggression, |
| 73 | stepCombat, |
| 74 | stepPassiveHealthRegen, |
| 75 | chebyshev, |
| 76 | tryArmStaffSpellAttack |
| 77 | } from "../combat/service.js"; |
| 78 | import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js"; |
| 79 | import { SkillId } from "../../../shared/definitions/skills.js"; |
| 80 | import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js"; |
| 81 | import { passiveStaminaRegenMultiplier, dropAmuletInsteadOfCoins } from "../../../shared/equipment/jewelryEffects.js"; |
| 82 | import { JewelryItemId } from "../../../shared/definitions/jewelryItems.js"; |
| 83 | import { EQUIPMENT_SLOT } from "../../../shared/definitions/items.js"; |
| 84 | import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js"; |
| 85 | import { |
| 86 | STAMINA_REGEN_PER_SECOND, |
| 87 | STAMINA_XP_PER_POINT_SPENT, |
| 88 | staminaCostPerRunStep, |
| 89 | publicStaminaView |
| 90 | } from "../../../shared/stamina/rules.js"; |
| 91 | import { |
| 92 | stepCostForGround, |
| 93 | PATH_GROUND_STEP_COST, |
| 94 | SOFT_OCCUPIED_DWELL_MS |
| 95 | } from "../../../shared/navigation/pathGround.js"; |
| 96 | import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js"; |
| 97 | import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js"; |
| 98 | import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js"; |
| 99 | import { stepStatusEffects } from "../statusEffects/service.js"; |
| 100 | import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js"; |
| 101 | |
| 102 | export class WorkerWorld |
| 103 | { |
| 104 | constructor (workerId) |
| 105 | { |
| 106 | this.workerId = workerId; |
| 107 | this.ecs = new EcsWorld(); |
| 108 | this.chunks = new Map(); |
| 109 | this.ownedRegions = new Set(); |
| 110 | this.occupancy = new Map(); |
| 111 | this.ghosts = new Map(); |
| 112 | this.ghostOccupancy = new Map(); |
| 113 | this.characterEntities = new Map(); |
| 114 | this.frozen = new Set(); |
| 115 | this.groundItems = new Map(); |
| 116 | this.groundByTile = new Map(); |
| 117 | this.oreRespawns = new Map(); |
| 118 | this.treeRespawns = new Map(); |
| 119 | this.campfireExpires = new Map(); |
| 120 | this.fireSessions = new Map(); |
| 121 | this.fishingSpotRespawns = new Map(); |
| 122 | this.fishSessions = new Map(); |
| 123 | this.pendingSpellImpacts = []; |
| 124 | this.jadeiteFairyTimers = new Map(); |
| 125 | this.jewelryTeleportSessions = new Map(); |
| 126 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 127 | this.activeRevisionId = 1; |
| 128 | } |
| 129 | |
| 130 | handle (message) |
| 131 | { |
| 132 | switch (message.type) |
| 133 | { |
| 134 | case WorkerMessage.configure: |
| 135 | return this.#configure(message); |
| 136 | case WorkerMessage.assignRegion: |
| 137 | return this.#assignRegion(message); |
| 138 | case WorkerMessage.dropRegion: |
| 139 | return this.#dropRegion(message); |
| 140 | case WorkerMessage.replaceRegionChunks: |
| 141 | return this.#replaceRegionChunks(message); |
| 142 | case WorkerMessage.setReplicas: |
| 143 | return this.#setReplicas(message); |
| 144 | case WorkerMessage.setSimulatingChunks: |
| 145 | return this.#setSimulatingChunks(message); |
| 146 | case WorkerMessage.setGhosts: |
| 147 | return this.#setGhosts(message); |
| 148 | case WorkerMessage.spawn: |
| 149 | return this.#spawn(message); |
| 150 | case WorkerMessage.despawn: |
| 151 | return this.#despawn(message.entityId); |
| 152 | case WorkerMessage.despawnCharacter: |
| 153 | return this.#despawnCharacter(message.characterId); |
| 154 | case WorkerMessage.reattachSession: |
| 155 | return this.#reattachSession(message.characterId, message.sessionId); |
| 156 | case WorkerMessage.command: |
| 157 | return this.#command(message); |
| 158 | case WorkerMessage.stepMovement: |
| 159 | return this.#stepMovement(message.now); |
| 160 | case WorkerMessage.stepSystems: |
| 161 | return this.#stepSystems(message.now, message.dt ?? (1 / 20)); |
| 162 | case WorkerMessage.stepSpawners: |
| 163 | return { spawnRequests: collectSpawnRequests(this, Date.now()) }; |
| 164 | case WorkerMessage.setGroundItems: |
| 165 | setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion); |
| 166 | return { ok: true }; |
| 167 | case WorkerMessage.inspectBag: |
| 168 | return this.#inspectBag(message.entityId); |
| 169 | case WorkerMessage.inspectSkills: |
| 170 | return this.#inspectSkills(message.entityId); |
| 171 | case WorkerMessage.inspectSpells: |
| 172 | return this.#inspectSpells(message.entityId); |
| 173 | case WorkerMessage.inspectStamina: |
| 174 | return this.#inspectStamina(message.entityId); |
| 175 | case WorkerMessage.applyBag: |
| 176 | return this.#applyBag(message.entityId, message.bag); |
| 177 | case WorkerMessage.applyAppearance: |
| 178 | return this.#applyAppearance(message.entityId, message.appearance); |
| 179 | case WorkerMessage.applySkullValue: |
| 180 | return this.#applySkullValue(message.entityId, message.skullValue); |
| 181 | case WorkerMessage.engageTarget: |
| 182 | return this.#engageTargetMessage(message); |
| 183 | case WorkerMessage.setSpellAutoCast: |
| 184 | return this.#setSpellAutoCast(message); |
| 185 | case WorkerMessage.inspectCombatState: |
| 186 | return this.#inspectCombatState(message.entityId); |
| 187 | case WorkerMessage.listTownGuardsNear: |
| 188 | return this.#listTownGuardsNear(message); |
| 189 | case WorkerMessage.updateFlight: |
| 190 | return this.#updateFlight(message.entityId, message.flight, message.now); |
| 191 | case WorkerMessage.chunkIsSimulating: |
| 192 | return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId); |
| 193 | case WorkerMessage.applyTransfer: |
| 194 | return this.#applyTransfer(message); |
| 195 | case WorkerMessage.commitTransfer: |
| 196 | return this.#commitTransfer(message.entityId); |
| 197 | case WorkerMessage.abortTransfer: |
| 198 | return this.#abortTransfer(message.entityId); |
| 199 | case WorkerMessage.snapshotChunk: |
| 200 | return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId); |
| 201 | case WorkerMessage.listLoaders: |
| 202 | return this.#listLoaders(); |
| 203 | case WorkerMessage.listPublicEntities: |
| 204 | return this.#listPublicEntities(); |
| 205 | case WorkerMessage.entitiesInRegion: |
| 206 | return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId); |
| 207 | case WorkerMessage.inspect: |
| 208 | return publicEntityView(this.ecs, message.entityId); |
| 209 | case WorkerMessage.remoteCombatEngage: |
| 210 | return this.#remoteCombatEngage(message); |
| 211 | case WorkerMessage.applyRemoteMelee: |
| 212 | return this.#applyRemoteMelee(message); |
| 213 | case WorkerMessage.applyRemoteRanged: |
| 214 | return this.#applyRemoteRanged(message); |
| 215 | case WorkerMessage.applyCombatHitXp: |
| 216 | return this.#applyCombatHitXp(message); |
| 217 | case WorkerMessage.spawnCorpseDrops: |
| 218 | return this.#spawnCorpseDrops(message); |
| 219 | case WorkerMessage.applyRespawn: |
| 220 | return this.#applyRespawn(message); |
| 221 | case WorkerMessage.relocateEntity: |
| 222 | return this.#relocateEntity(message); |
| 223 | case WorkerMessage.clearCombat: |
| 224 | { |
| 225 | clearEngage(this.ecs, message.entityId); |
| 226 | const handle = this.ecs.handleOf(message.entityId); |
| 227 | if (handle != null) |
| 228 | { |
| 229 | silenceDeadPlayer(this.ecs, handle); |
| 230 | cancelGather(this.ecs, handle); |
| 231 | clearFollow(this.ecs, message.entityId); |
| 232 | } |
| 233 | for (const entity of this.ecs.query(Component.combat)) |
| 234 | { |
| 235 | if (entity.combat.targetEntityId === message.targetEntityId) |
| 236 | { entity.combat.targetEntityId = null; } |
| 237 | } |
| 238 | return { ok: true }; |
| 239 | } |
| 240 | case WorkerMessage.setItemLastSales: |
| 241 | { |
| 242 | this.itemLastSales = new Map(); |
| 243 | for (const [key, sale] of Object.entries(message.sales ?? {})) |
| 244 | { this.itemLastSales.set(Number(key), sale); } |
| 245 | return { ok: true }; |
| 246 | } |
| 247 | case WorkerMessage.stationExchangeClerk: |
| 248 | return this.#stationExchangeClerk(message); |
| 249 | case WorkerMessage.releaseExchangeClerk: |
| 250 | return this.#releaseExchangeClerk(message); |
| 251 | case WorkerMessage.pinDialogue: |
| 252 | return this.#pinDialogue(message.entityId, message.characterId); |
| 253 | case WorkerMessage.unpinDialogue: |
| 254 | return this.#unpinDialogue(message.entityId, message.characterId); |
| 255 | default: |
| 256 | throw new Error(`Unknown worker message ${message.type}`); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 261 | { |
| 262 | return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId)); |
| 263 | } |
| 264 | |
| 265 | requireOwnedEntity (sessionId, characterId) |
| 266 | { |
| 267 | return this.#requireOwnedEntity(sessionId, characterId); |
| 268 | } |
| 269 | |
| 270 | chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 271 | { |
| 272 | return this.#chunkData(chunkX, chunkY, dimensionId); |
| 273 | } |
| 274 | |
| 275 | #configure (message) |
| 276 | { |
| 277 | if (message.settings) |
| 278 | { this.settings = { ...this.settings, ...message.settings }; } |
| 279 | if (message.activeRevisionId != null) |
| 280 | { this.activeRevisionId = message.activeRevisionId; } |
| 281 | return { ok: true }; |
| 282 | } |
| 283 | |
| 284 | #assignRegion (message) |
| 285 | { |
| 286 | const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 287 | this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim)); |
| 288 | for (const chunk of message.chunks ?? []) |
| 289 | { |
| 290 | const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim); |
| 291 | clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 292 | clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 293 | clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 294 | this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), { |
| 295 | data: cloneChunkData(chunk.data), |
| 296 | simulating: false, |
| 297 | replica: false, |
| 298 | dimensionId: chunkDim |
| 299 | }); |
| 300 | } |
| 301 | return { ok: true }; |
| 302 | } |
| 303 | |
| 304 | #replaceRegionChunks (message) |
| 305 | { |
| 306 | const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 307 | for (const chunk of message.chunks ?? []) |
| 308 | { |
| 309 | const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim); |
| 310 | const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim); |
| 311 | const existing = this.chunks.get(key); |
| 312 | clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 313 | clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 314 | clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); |
| 315 | this.chunks.set(key, { |
| 316 | data: cloneChunkData(chunk.data), |
| 317 | simulating: existing?.simulating ?? false, |
| 318 | replica: existing?.replica ?? false, |
| 319 | dimensionId: chunkDim |
| 320 | }); |
| 321 | } |
| 322 | return { ok: true }; |
| 323 | } |
| 324 | |
| 325 | #dropRegion (message) |
| 326 | { |
| 327 | const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 328 | const dropped = []; |
| 329 | for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim)) |
| 330 | { |
| 331 | const components = record.payload?.components; |
| 332 | if (components?.creature && !components?.character && components?.health) |
| 333 | { components.health.current = components.health.max; } |
| 334 | dropped.push(record); |
| 335 | this.#destroyEntity(record.entityId); |
| 336 | } |
| 337 | const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion); |
| 338 | for (const item of groundItems) |
| 339 | { removeGroundItem(this, item.groundItemId); } |
| 340 | for (const [key, chunk] of [...this.chunks.entries()]) |
| 341 | { |
| 342 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 343 | if (chunk.replica) |
| 344 | { continue; } |
| 345 | if (dimensionId !== dim) |
| 346 | { continue; } |
| 347 | if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY) |
| 348 | { |
| 349 | clearOreRespawnsForChunk(this, chunkX, chunkY); |
| 350 | clearTreeRespawnsForChunk(this, chunkX, chunkY); |
| 351 | clearPlantRespawnsForChunk(this, chunkX, chunkY); |
| 352 | this.chunks.delete(key); |
| 353 | } |
| 354 | } |
| 355 | this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim)); |
| 356 | return { dropped, groundItems }; |
| 357 | } |
| 358 | |
| 359 | #setReplicas (message) |
| 360 | { |
| 361 | const keep = new Set(); |
| 362 | for (const chunk of message.chunks ?? []) |
| 363 | { |
| 364 | const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID); |
| 365 | const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim); |
| 366 | keep.add(key); |
| 367 | const existing = this.chunks.get(key); |
| 368 | if (existing && !existing.replica) |
| 369 | { continue; } |
| 370 | this.chunks.set(key, { |
| 371 | data: cloneChunkData(chunk.data), |
| 372 | simulating: false, |
| 373 | replica: true, |
| 374 | dimensionId: chunkDim |
| 375 | }); |
| 376 | } |
| 377 | for (const [key, chunk] of [...this.chunks.entries()]) |
| 378 | { |
| 379 | if (chunk.replica && !keep.has(key)) |
| 380 | { this.chunks.delete(key); } |
| 381 | } |
| 382 | return { ok: true }; |
| 383 | } |
| 384 | |
| 385 | #setSimulatingChunks (message) |
| 386 | { |
| 387 | const simulating = new Set(message.chunkKeys ?? []); |
| 388 | for (const [key, chunk] of this.chunks) |
| 389 | { |
| 390 | if (chunk.replica) |
| 391 | { |
| 392 | chunk.simulating = false; |
| 393 | continue; |
| 394 | } |
| 395 | chunk.simulating = simulating.has(key); |
| 396 | } |
| 397 | return { ok: true }; |
| 398 | } |
| 399 | |
| 400 | #setGhosts (message) |
| 401 | { |
| 402 | this.ghosts.clear(); |
| 403 | this.ghostOccupancy.clear(); |
| 404 | for (const ghost of message.ghosts ?? []) |
| 405 | { |
| 406 | this.ghosts.set(ghost.entityId, ghost); |
| 407 | const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID); |
| 408 | const key = tileKey(ghost.tileX, ghost.tileY, dim); |
| 409 | let set = this.ghostOccupancy.get(key); |
| 410 | if (!set) |
| 411 | { |
| 412 | set = new Set(); |
| 413 | this.ghostOccupancy.set(key, set); |
| 414 | } |
| 415 | set.add(ghost.entityId); |
| 416 | } |
| 417 | return { ok: true }; |
| 418 | } |
| 419 | |
| 420 | #spawn (message) |
| 421 | { |
| 422 | const entityId = deserializeEntity(this.ecs, message); |
| 423 | const handle = this.ecs.handleOf(entityId); |
| 424 | const position = this.ecs.get(handle, Component.position); |
| 425 | if (!position) |
| 426 | { |
| 427 | this.ecs.destroy(handle); |
| 428 | throw new Error("Spawned entity is missing position."); |
| 429 | } |
| 430 | const flying = this.#isFlying(handle); |
| 431 | if (!flying) |
| 432 | { |
| 433 | if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY)) |
| 434 | { |
| 435 | this.ecs.destroy(handle); |
| 436 | const error = new Error("That tile is occupied."); |
| 437 | error.userFacing = true; |
| 438 | throw error; |
| 439 | } |
| 440 | this.#occupy(entityId, position.tileX, position.tileY); |
| 441 | } |
| 442 | const creature = this.ecs.get(handle, Component.creature); |
| 443 | const def = creature ? mobDefinition(creature.mobTypeId) : null; |
| 444 | if (def?.freeFlight) |
| 445 | { ensureFlightComponent(this.ecs, handle, position, def); } |
| 446 | const character = this.ecs.get(handle, Component.character); |
| 447 | if (character?.characterId) |
| 448 | { |
| 449 | this.characterEntities.set(character.characterId, entityId); |
| 450 | syncCharacterChunkPresence(this.ecs, handle, Date.now()); |
| 451 | } |
| 452 | return publicEntityView(this.ecs, entityId); |
| 453 | } |
| 454 | |
| 455 | #despawn (entityId) |
| 456 | { |
| 457 | return this.#destroyEntity(entityId); |
| 458 | } |
| 459 | |
| 460 | #despawnCharacter (characterId) |
| 461 | { |
| 462 | releaseShopBrowsersForCharacter(this, characterId); |
| 463 | const entityId = this.characterEntities.get(characterId); |
| 464 | if (!entityId) |
| 465 | { return null; } |
| 466 | return this.#destroyEntity(entityId); |
| 467 | } |
| 468 | |
| 469 | #reattachSession (characterId, sessionId) |
| 470 | { |
| 471 | const entityId = this.characterEntities.get(characterId | 0); |
| 472 | if (!entityId) |
| 473 | { return { ok: false }; } |
| 474 | const handle = this.ecs.handleOf(entityId); |
| 475 | if (handle == null) |
| 476 | { return { ok: false }; } |
| 477 | this.ecs.add(handle, Component.networkIdentity, { sessionId }); |
| 478 | return { ok: true, entityId }; |
| 479 | } |
| 480 | |
| 481 | #destroyEntity (entityId) |
| 482 | { |
| 483 | const handle = this.ecs.handleOf(entityId); |
| 484 | if (handle == null) |
| 485 | { return null; } |
| 486 | const view = publicEntityView(this.ecs, entityId); |
| 487 | const position = this.ecs.get(handle, Component.position); |
| 488 | const character = this.ecs.get(handle, Component.character); |
| 489 | if (position && !this.#isFlying(handle)) |
| 490 | { this.#vacate(entityId, position.tileX, position.tileY); } |
| 491 | if (character?.characterId) |
| 492 | { this.characterEntities.delete(character.characterId); } |
| 493 | this.frozen.delete(entityId); |
| 494 | this.ecs.destroy(handle); |
| 495 | return view; |
| 496 | } |
| 497 | |
| 498 | #command (message) |
| 499 | { |
| 500 | const { sessionId, command } = message; |
| 501 | switch (command.type) |
| 502 | { |
| 503 | case "move-to": |
| 504 | return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY); |
| 505 | case "set-gait": |
| 506 | return this.#setGait(sessionId, command.characterId, command.gait); |
| 507 | case "attack": |
| 508 | return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now()); |
| 509 | case "cancel-attack": |
| 510 | return this.#cancelAttack(sessionId, command.characterId); |
| 511 | case "interact": |
| 512 | return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose); |
| 513 | case "follow": |
| 514 | return this.#follow(sessionId, command.characterId, command.targetEntityId); |
| 515 | case "cancel-follow": |
| 516 | return this.#cancelFollow(sessionId, command.characterId); |
| 517 | case "jewelry-teleport": |
| 518 | { |
| 519 | const jewelry = handleJewelryTeleportCommand(this, sessionId, command, message.now ?? Date.now()); |
| 520 | if (jewelry) |
| 521 | { return jewelry; } |
| 522 | return { events: [] }; |
| 523 | } |
| 524 | case "set-spell-favorite": |
| 525 | case "reorder-spell-favorites": |
| 526 | case "set-spell-autocast": |
| 527 | case "arm-spell": |
| 528 | case "cancel-arm-spell": |
| 529 | case "cast-spell-tile": |
| 530 | case "cast-spell-entity": |
| 531 | case "read-spellbook": |
| 532 | return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] }; |
| 533 | default: |
| 534 | { |
| 535 | const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now()); |
| 536 | if (gather) |
| 537 | { return gather; } |
| 538 | const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now()); |
| 539 | if (fire) |
| 540 | { return fire; } |
| 541 | const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now()); |
| 542 | if (fishing) |
| 543 | { return fishing; } |
| 544 | const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now()); |
| 545 | if (shearing) |
| 546 | { return shearing; } |
| 547 | const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now()); |
| 548 | if (craft) |
| 549 | { return craft; } |
| 550 | const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now()); |
| 551 | if (shop) |
| 552 | { return shop; } |
| 553 | const alchemy = handleAlchemyCommand(this, sessionId, command); |
| 554 | if (alchemy) |
| 555 | { return alchemy; } |
| 556 | const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now()); |
| 557 | return result ?? { events: [] }; |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | #spawnCorpseDrops (message) |
| 563 | { |
| 564 | const events = []; |
| 565 | const drops = [...(message.drops ?? [])]; |
| 566 | let privateBag = null; |
| 567 | if (message.dropCarriedCoins) |
| 568 | { |
| 569 | const entityId = this.characterEntities.get(message.characterId); |
| 570 | const handle = entityId != null ? this.ecs.handleOf(entityId) : null; |
| 571 | const equipment = handle != null ? this.ecs.get(handle, Component.equipment) : null; |
| 572 | if (dropAmuletInsteadOfCoins(equipment)) |
| 573 | { |
| 574 | const amulet = equipment?.slots?.[EQUIPMENT_SLOT.amulet] |
| 575 | ?? equipment?.slots?.amulet |
| 576 | ?? null; |
| 577 | if (amulet && (amulet.itemId | 0) === JewelryItemId.rubyAmulet) |
| 578 | { |
| 579 | equipment.slots[EQUIPMENT_SLOT.amulet] = null; |
| 580 | if (message.coinGroundItemId != null) |
| 581 | { |
| 582 | drops.push({ |
| 583 | groundItemId: message.coinGroundItemId, |
| 584 | stack: { |
| 585 | itemId: JewelryItemId.rubyAmulet, |
| 586 | quantity: 1, |
| 587 | origins: amulet.origins ?? [] |
| 588 | } |
| 589 | }); |
| 590 | } |
| 591 | privateBag = bagView(this.ecs, handle); |
| 592 | } |
| 593 | } |
| 594 | else |
| 595 | { |
| 596 | const stripped = stripCarriedCoinsForDeath(this, message.characterId); |
| 597 | privateBag = stripped.private; |
| 598 | if (stripped.stack && message.coinGroundItemId != null) |
| 599 | { |
| 600 | drops.push({ |
| 601 | groundItemId: message.coinGroundItemId, |
| 602 | stack: stripped.stack |
| 603 | }); |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | for (const drop of drops) |
| 608 | { |
| 609 | const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 }; |
| 610 | const item = { |
| 611 | groundItemId: drop.groundItemId, |
| 612 | tileX: message.tileX, |
| 613 | tileY: message.tileY, |
| 614 | stack, |
| 615 | droppedAt: message.now, |
| 616 | expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000), |
| 617 | source: "player-death", |
| 618 | droppedByCharacterId: message.characterId |
| 619 | }; |
| 620 | addGroundItem(this, item); |
| 621 | events.push({ |
| 622 | type: "ground-item-appear", |
| 623 | ...publicGroundItem(item), |
| 624 | stack: item.stack, |
| 625 | droppedAt: item.droppedAt, |
| 626 | source: item.source, |
| 627 | droppedByCharacterId: item.droppedByCharacterId, |
| 628 | expiresAt: item.expiresAt |
| 629 | }); |
| 630 | } |
| 631 | return { events, private: privateBag }; |
| 632 | } |
| 633 | |
| 634 | #applyRespawn (message) |
| 635 | { |
| 636 | const handle = this.ecs.handleOf(message.entityId); |
| 637 | if (handle == null || !this.ecs.has(handle, Component.dead)) |
| 638 | { return { accepted: false }; } |
| 639 | const position = this.ecs.get(handle, Component.position); |
| 640 | const fromTileX = position.tileX; |
| 641 | const fromTileY = position.tileY; |
| 642 | const health = this.ecs.get(handle, Component.health); |
| 643 | const stamina = this.ecs.get(handle, Component.stamina); |
| 644 | if (health) |
| 645 | { |
| 646 | health.max = message.maxHealth; |
| 647 | health.current = message.maxHealth; |
| 648 | } |
| 649 | if (stamina) |
| 650 | { |
| 651 | stamina.max = message.maxStamina; |
| 652 | stamina.current = message.maxStamina; |
| 653 | } |
| 654 | else |
| 655 | { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); } |
| 656 | this.ecs.remove(handle, Component.dead); |
| 657 | clearEngage(this.ecs, message.entityId); |
| 658 | const path = this.ecs.get(handle, Component.path); |
| 659 | if (path) |
| 660 | { path.tiles = []; } |
| 661 | clearFollow(this.ecs, message.entityId); |
| 662 | |
| 663 | const destRegionX = tileToRegion(message.tileX); |
| 664 | const destRegionY = tileToRegion(message.tileY); |
| 665 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 666 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 667 | { |
| 668 | this.frozen.add(message.entityId); |
| 669 | return { |
| 670 | accepted: true, |
| 671 | transferRequest: { |
| 672 | entityId: message.entityId, |
| 673 | fromTileX, |
| 674 | fromTileY, |
| 675 | destTileX: message.tileX, |
| 676 | destTileY: message.tileY, |
| 677 | toRegionX: destRegionX, |
| 678 | toRegionY: destRegionY, |
| 679 | dimensionId, |
| 680 | payload: serializeEntity(this.ecs, message.entityId) |
| 681 | } |
| 682 | }; |
| 683 | } |
| 684 | if (!this.isEnterable(message.tileX, message.tileY, dimensionId)) |
| 685 | { return { accepted: false }; } |
| 686 | this.#vacate(message.entityId, fromTileX, fromTileY); |
| 687 | position.tileX = message.tileX; |
| 688 | position.tileY = message.tileY; |
| 689 | syncCharacterChunkPresence(this.ecs, handle, Date.now()); |
| 690 | this.#occupy(message.entityId, position.tileX, position.tileY); |
| 691 | return { |
| 692 | accepted: true, |
| 693 | event: { |
| 694 | type: "entity-move", |
| 695 | entityId: message.entityId, |
| 696 | fromTileX, |
| 697 | fromTileY, |
| 698 | tileX: position.tileX, |
| 699 | tileY: position.tileY, |
| 700 | dimensionId, |
| 701 | gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk |
| 702 | } |
| 703 | }; |
| 704 | } |
| 705 | |
| 706 | /** Move an entity to a tile/dimension; clears path and updates occupancy. */ |
| 707 | #relocateEntity (message) |
| 708 | { |
| 709 | const handle = this.ecs.handleOf(message.entityId); |
| 710 | if (handle == null) |
| 711 | { return { accepted: false }; } |
| 712 | const position = this.ecs.get(handle, Component.position); |
| 713 | if (!position) |
| 714 | { return { accepted: false }; } |
| 715 | const fromTileX = position.tileX; |
| 716 | const fromTileY = position.tileY; |
| 717 | const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 718 | const destTileX = message.tileX | 0; |
| 719 | const destTileY = message.tileY | 0; |
| 720 | const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId); |
| 721 | |
| 722 | clearEngage(this.ecs, message.entityId); |
| 723 | const path = this.ecs.get(handle, Component.path); |
| 724 | if (path) |
| 725 | { path.tiles = []; } |
| 726 | clearFollow(this.ecs, message.entityId); |
| 727 | |
| 728 | const destRegionX = tileToRegion(destTileX); |
| 729 | const destRegionY = tileToRegion(destTileY); |
| 730 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 731 | { |
| 732 | this.frozen.add(message.entityId); |
| 733 | const payload = serializeEntity(this.ecs, message.entityId); |
| 734 | if (payload.components?.position) |
| 735 | { |
| 736 | payload.components.position.tileX = destTileX; |
| 737 | payload.components.position.tileY = destTileY; |
| 738 | payload.components.position.dimensionId = dimensionId; |
| 739 | } |
| 740 | return { |
| 741 | accepted: true, |
| 742 | transferRequest: { |
| 743 | entityId: message.entityId, |
| 744 | fromTileX, |
| 745 | fromTileY, |
| 746 | fromDimensionId, |
| 747 | destTileX, |
| 748 | destTileY, |
| 749 | toRegionX: destRegionX, |
| 750 | toRegionY: destRegionY, |
| 751 | dimensionId, |
| 752 | payload |
| 753 | } |
| 754 | }; |
| 755 | } |
| 756 | if (!this.isEnterable(destTileX, destTileY, dimensionId)) |
| 757 | { return { accepted: false }; } |
| 758 | if (!this.#isFlying(handle)) |
| 759 | { this.#vacate(message.entityId, fromTileX, fromTileY); } |
| 760 | position.tileX = destTileX; |
| 761 | position.tileY = destTileY; |
| 762 | position.dimensionId = dimensionId; |
| 763 | syncCharacterChunkPresence(this.ecs, handle, Date.now()); |
| 764 | if (!this.#isFlying(handle)) |
| 765 | { this.#occupy(message.entityId, destTileX, destTileY); } |
| 766 | return { |
| 767 | accepted: true, |
| 768 | event: { |
| 769 | type: "entity-move", |
| 770 | entityId: message.entityId, |
| 771 | fromTileX, |
| 772 | fromTileY, |
| 773 | fromDimensionId, |
| 774 | tileX: destTileX, |
| 775 | tileY: destTileY, |
| 776 | dimensionId, |
| 777 | gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk |
| 778 | } |
| 779 | }; |
| 780 | } |
| 781 | |
| 782 | #inspectBag (entityId) |
| 783 | { |
| 784 | const handle = this.ecs.handleOf(entityId); |
| 785 | if (handle == null) |
| 786 | { return null; } |
| 787 | return bagView(this.ecs, handle); |
| 788 | } |
| 789 | |
| 790 | #inspectSkills (entityId) |
| 791 | { |
| 792 | const handle = this.ecs.handleOf(entityId); |
| 793 | if (handle == null) |
| 794 | { return null; } |
| 795 | const skills = this.ecs.get(handle, Component.skills); |
| 796 | if (!skills?.xp) |
| 797 | { return null; } |
| 798 | return skills; |
| 799 | } |
| 800 | |
| 801 | #inspectSpells (entityId) |
| 802 | { |
| 803 | const handle = this.ecs.handleOf(entityId); |
| 804 | if (handle == null) |
| 805 | { return null; } |
| 806 | const spells = this.ecs.get(handle, Component.spells); |
| 807 | const skills = this.ecs.get(handle, Component.skills); |
| 808 | const casting = this.ecs.get(handle, Component.spellcasting); |
| 809 | if (!spells) |
| 810 | { return null; } |
| 811 | return { |
| 812 | spells: publicSpellsView(spells, skills), |
| 813 | favorites: Array.isArray(spells.favorites) ? [...spells.favorites] : [], |
| 814 | autoCast: !!spells.autoCast, |
| 815 | armedSpellId: casting?.armedSpellId ?? null |
| 816 | }; |
| 817 | } |
| 818 | |
| 819 | #setSpellAutoCast (message) |
| 820 | { |
| 821 | const entityId = message.entityId != null |
| 822 | ? message.entityId |
| 823 | : this.characterEntities.get(message.characterId | 0); |
| 824 | const handle = entityId != null ? this.ecs.handleOf(entityId) : null; |
| 825 | if (handle == null) |
| 826 | { return { ok: false }; } |
| 827 | const spells = this.ecs.get(handle, Component.spells); |
| 828 | if (!spells) |
| 829 | { return { ok: false }; } |
| 830 | const previous = !!spells.autoCast; |
| 831 | spells.autoCast = !!message.autoCast; |
| 832 | return { ok: true, previousAutoCast: previous, autoCast: !!spells.autoCast }; |
| 833 | } |
| 834 | |
| 835 | #inspectCombatState (entityId) |
| 836 | { |
| 837 | const handle = this.ecs.handleOf(entityId); |
| 838 | if (handle == null) |
| 839 | { return null; } |
| 840 | const combat = this.ecs.get(handle, Component.combat); |
| 841 | const casting = this.ecs.get(handle, Component.spellcasting); |
| 842 | const character = this.ecs.get(handle, Component.character); |
| 843 | const dead = this.ecs.has(handle, Component.dead); |
| 844 | const targetId = combat?.targetEntityId ?? null; |
| 845 | const repeatTargetId = casting?.repeatTargetEntityId ?? null; |
| 846 | const pendingTargetId = casting?.pendingCast?.targetEntityId ?? null; |
| 847 | const inCombat = !dead && !!(targetId != null |
| 848 | || repeatTargetId != null |
| 849 | || (casting?.pendingCast && (pendingTargetId != null |
| 850 | || casting.pendingCast.tileX != null))); |
| 851 | return { |
| 852 | characterId: character?.characterId ?? null, |
| 853 | inCombat, |
| 854 | dead, |
| 855 | targetEntityId: targetId, |
| 856 | repeatTargetEntityId: repeatTargetId, |
| 857 | pendingTargetEntityId: pendingTargetId |
| 858 | }; |
| 859 | } |
| 860 | |
| 861 | #inspectStamina (entityId) |
| 862 | { |
| 863 | const handle = this.ecs.handleOf(entityId); |
| 864 | if (handle == null) |
| 865 | { return null; } |
| 866 | const stamina = this.ecs.get(handle, Component.stamina); |
| 867 | const movement = this.ecs.get(handle, Component.movement); |
| 868 | if (!stamina) |
| 869 | { return null; } |
| 870 | return { |
| 871 | ...publicStaminaView(stamina), |
| 872 | gait: movement?.gait ?? GAIT.walk |
| 873 | }; |
| 874 | } |
| 875 | |
| 876 | #applyBag (entityId, bag) |
| 877 | { |
| 878 | const handle = this.ecs.handleOf(entityId); |
| 879 | if (handle == null) |
| 880 | { return null; } |
| 881 | return applyBagView(this.ecs, handle, bag); |
| 882 | } |
| 883 | |
| 884 | #applyAppearance (entityId, appearancePatch) |
| 885 | { |
| 886 | const handle = this.ecs.handleOf(entityId); |
| 887 | if (handle == null) |
| 888 | { return null; } |
| 889 | const appearance = this.ecs.get(handle, Component.appearance); |
| 890 | if (!appearance) |
| 891 | { return null; } |
| 892 | Object.assign(appearance, appearancePatch ?? {}); |
| 893 | return publicEntityView(this.ecs, entityId); |
| 894 | } |
| 895 | |
| 896 | #applySkullValue (entityId, skullValue) |
| 897 | { |
| 898 | const handle = this.ecs.handleOf(entityId); |
| 899 | if (handle == null) |
| 900 | { return null; } |
| 901 | const character = this.ecs.get(handle, Component.character); |
| 902 | if (!character) |
| 903 | { return null; } |
| 904 | character.skullValue = Math.max(0, skullValue | 0); |
| 905 | return { ok: true, skullValue: character.skullValue }; |
| 906 | } |
| 907 | |
| 908 | #updateFlight (entityId, flightPatch, now = Date.now()) |
| 909 | { |
| 910 | const handle = this.ecs.handleOf(entityId); |
| 911 | if (handle == null) |
| 912 | { return null; } |
| 913 | let flight = this.ecs.get(handle, Component.flight); |
| 914 | if (!flight) |
| 915 | { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); } |
| 916 | else |
| 917 | { Object.assign(flight, flightPatch); } |
| 918 | const position = this.ecs.get(handle, Component.position); |
| 919 | const movement = this.ecs.get(handle, Component.movement); |
| 920 | const fromTileX = position.tileX; |
| 921 | const fromTileY = position.tileY; |
| 922 | const tileX = Math.floor(flight.x); |
| 923 | const tileY = Math.floor(flight.y); |
| 924 | position.tileX = tileX; |
| 925 | position.tileY = tileY; |
| 926 | syncCharacterChunkPresence(this.ecs, handle, now); |
| 927 | const destRegionX = tileToRegion(tileX); |
| 928 | const destRegionY = tileToRegion(tileY); |
| 929 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 930 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 931 | { |
| 932 | this.frozen.add(entityId); |
| 933 | return { |
| 934 | transferRequest: { |
| 935 | type: "transfer-request", |
| 936 | entityId, |
| 937 | fromTileX, |
| 938 | fromTileY, |
| 939 | destTileX: tileX, |
| 940 | destTileY: tileY, |
| 941 | toRegionX: destRegionX, |
| 942 | toRegionY: destRegionY, |
| 943 | dimensionId |
| 944 | } |
| 945 | }; |
| 946 | } |
| 947 | const dt = flight.lastAt && now > flight.lastAt |
| 948 | ? Math.min(0.25, (now - flight.lastAt) / 1000) |
| 949 | : 1 / 20; |
| 950 | return { |
| 951 | event: { |
| 952 | type: "entity-move", |
| 953 | entityId, |
| 954 | fromTileX, |
| 955 | fromTileY, |
| 956 | tileX, |
| 957 | tileY, |
| 958 | worldX: flight.x, |
| 959 | worldY: flight.y, |
| 960 | gait: movement?.gait ?? "walk", |
| 961 | lerpMs: Math.max(50, Math.round(dt * 1000)), |
| 962 | freeFlight: true |
| 963 | } |
| 964 | }; |
| 965 | } |
| 966 | |
| 967 | #moveTo (sessionId, characterId, tileX, tileY) |
| 968 | { |
| 969 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 970 | if (this.frozen.has(entityId)) |
| 971 | { return { events: [] }; } |
| 972 | clearEngage(this.ecs, entityId); |
| 973 | clearFollow(this.ecs, entityId); |
| 974 | cancelGather(this.ecs, handle); |
| 975 | cancelJewelryTeleport(this, characterId); |
| 976 | clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting)); |
| 977 | const position = this.ecs.get(handle, Component.position); |
| 978 | const movement = this.ecs.get(handle, Component.movement); |
| 979 | let path = this.ecs.get(handle, Component.path); |
| 980 | if (!path) |
| 981 | { path = this.ecs.add(handle, Component.path, { tiles: [] }); } |
| 982 | // Match the static map ring (long vision): clicks outside the 3×3 entity view still path. |
| 983 | const bounds = chunkBoundsAround(position.tileX, position.tileY, STATIC_CHUNK_RADIUS); |
| 984 | path.tiles = findPath( |
| 985 | position.tileX, |
| 986 | position.tileY, |
| 987 | tileX, |
| 988 | tileY, |
| 989 | (x, y) => this.walkableFor(entityId, x, y), |
| 990 | bounds.minX, |
| 991 | bounds.minY, |
| 992 | bounds.maxX, |
| 993 | bounds.maxY, |
| 994 | this.pathfindOptions({ preferVertical: true, preferPaths: true, entityId }) |
| 995 | ); |
| 996 | movement.walkCarry = 0; |
| 997 | const events = []; |
| 998 | /** Open immediately when the next step is a door (player already adjacent). */ |
| 999 | const first = path.tiles[0]; |
| 1000 | if (first) |
| 1001 | { |
| 1002 | const doorDelta = maybeOpenDoorOnApproach(this, entityId, first.x, first.y); |
| 1003 | if (doorDelta) |
| 1004 | { events.push(doorDelta); } |
| 1005 | } |
| 1006 | return { events }; |
| 1007 | } |
| 1008 | |
| 1009 | #attack (sessionId, characterId, targetEntityId, now) |
| 1010 | { |
| 1011 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 1012 | if (targetEntityId === entityId) |
| 1013 | { |
| 1014 | const error = new Error("Cannot attack yourself."); |
| 1015 | error.userFacing = true; |
| 1016 | throw error; |
| 1017 | } |
| 1018 | const target = resolveCombatTarget(this, targetEntityId); |
| 1019 | if (!target) |
| 1020 | { |
| 1021 | const error = new Error("Target is not here."); |
| 1022 | error.userFacing = true; |
| 1023 | throw error; |
| 1024 | } |
| 1025 | if (target.health && target.health.current <= 0) |
| 1026 | { |
| 1027 | const error = new Error("That cannot be attacked."); |
| 1028 | error.userFacing = true; |
| 1029 | throw error; |
| 1030 | } |
| 1031 | if (!this.ecs.get(handle, Component.combat)) |
| 1032 | { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } |
| 1033 | clearFollow(this.ecs, entityId); |
| 1034 | cancelGather(this.ecs, handle); |
| 1035 | // Staff + favorite attack spell: hold spell range via auto-cast (same as retaliate). |
| 1036 | if (tryArmStaffSpellAttack(this.ecs, entityId, targetEntityId)) |
| 1037 | { return { events: [] }; } |
| 1038 | clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting)); |
| 1039 | engageTarget(this.ecs, entityId, targetEntityId, now); |
| 1040 | const position = this.ecs.get(handle, Component.position); |
| 1041 | const profile = attackProfileOf(this.ecs, handle); |
| 1042 | if (position && target.pos) |
| 1043 | { |
| 1044 | if (profile.mode === "ranged") |
| 1045 | { |
| 1046 | queueStandInRangeApproach( |
| 1047 | this, |
| 1048 | entityId, |
| 1049 | handle, |
| 1050 | position, |
| 1051 | target.pos.tileX, |
| 1052 | target.pos.tileY, |
| 1053 | profile.rangeTiles | 0 || COMBAT_RANGE_TILES, |
| 1054 | 1 |
| 1055 | ); |
| 1056 | } |
| 1057 | else if (profile.mode === "melee") |
| 1058 | { |
| 1059 | queueMeleeApproach(this, entityId, handle, position, target.pos); |
| 1060 | } |
| 1061 | } |
| 1062 | return { events: [] }; |
| 1063 | } |
| 1064 | |
| 1065 | #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() }) |
| 1066 | { |
| 1067 | // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click. |
| 1068 | void attackerEntityId; |
| 1069 | void targetEntityId; |
| 1070 | void now; |
| 1071 | return { events: [] }; |
| 1072 | } |
| 1073 | |
| 1074 | #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() }) |
| 1075 | { |
| 1076 | if (this.ecs.handleOf(attackerEntityId) == null) |
| 1077 | { return { ok: false }; } |
| 1078 | engageTarget(this.ecs, attackerEntityId, targetEntityId, now); |
| 1079 | return { ok: true }; |
| 1080 | } |
| 1081 | |
| 1082 | /** |
| 1083 | * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY). |
| 1084 | * Optionally restrict to one spawnerId. |
| 1085 | */ |
| 1086 | #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 }) |
| 1087 | { |
| 1088 | const guards = []; |
| 1089 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position)) |
| 1090 | { |
| 1091 | if (!entity.spawnOrigin?.townGuard) |
| 1092 | { continue; } |
| 1093 | if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId) |
| 1094 | { continue; } |
| 1095 | const originX = entity.spawnOrigin.originTileX; |
| 1096 | const originY = entity.spawnOrigin.originTileY; |
| 1097 | const range = entity.spawnOrigin.wanderRangeTiles | 0; |
| 1098 | const dx = Math.abs(tileX - originX); |
| 1099 | const dy = Math.abs(tileY - originY); |
| 1100 | if (Math.max(dx, dy) > range) |
| 1101 | { continue; } |
| 1102 | const health = this.ecs.get(entity.handle, Component.health); |
| 1103 | if (health && health.current <= 0) |
| 1104 | { continue; } |
| 1105 | if (this.ecs.has(entity.handle, Component.dead)) |
| 1106 | { continue; } |
| 1107 | guards.push({ |
| 1108 | entityId: entity.entityId, |
| 1109 | spawnerId: entity.spawnOrigin.spawnerId, |
| 1110 | busy: entity.combat?.targetEntityId != null |
| 1111 | }); |
| 1112 | if (guards.length >= limit) |
| 1113 | { break; } |
| 1114 | } |
| 1115 | return { guards }; |
| 1116 | } |
| 1117 | |
| 1118 | #applyRemoteMelee (payload) |
| 1119 | { |
| 1120 | return applyRemoteMeleeSwing(this, payload); |
| 1121 | } |
| 1122 | |
| 1123 | #applyRemoteRanged (payload) |
| 1124 | { |
| 1125 | return applyRemoteRangedShot(this, payload); |
| 1126 | } |
| 1127 | |
| 1128 | #applyCombatHitXp ({ entityId, profile, damage }) |
| 1129 | { |
| 1130 | const handle = this.ecs.handleOf(entityId); |
| 1131 | if (handle == null) |
| 1132 | { return { events: [] }; } |
| 1133 | const character = this.ecs.get(handle, Component.character); |
| 1134 | if (!character) |
| 1135 | { return { events: [] }; } |
| 1136 | const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage); |
| 1137 | if (!xpAward) |
| 1138 | { return { events: [] }; } |
| 1139 | return { |
| 1140 | events: [{ |
| 1141 | type: "skills-updated", |
| 1142 | entityId, |
| 1143 | characterId: character.characterId, |
| 1144 | skills: xpAward.skills, |
| 1145 | combatLevel: xpAward.combatLevel, |
| 1146 | stored: xpAward.stored, |
| 1147 | levelUps: xpAward.levelUps ?? [] |
| 1148 | }] |
| 1149 | }; |
| 1150 | } |
| 1151 | |
| 1152 | #cancelAttack (sessionId, characterId) |
| 1153 | { |
| 1154 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 1155 | clearEngage(this.ecs, entityId); |
| 1156 | clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting)); |
| 1157 | return { events: [] }; |
| 1158 | } |
| 1159 | |
| 1160 | #interact (sessionId, characterId, targetEntityId, purpose = null) |
| 1161 | { |
| 1162 | this.#requireOwnedEntity(sessionId, characterId); |
| 1163 | const targetHandle = this.ecs.handleOf(targetEntityId); |
| 1164 | if (targetHandle == null) |
| 1165 | { |
| 1166 | const error = new Error("Target is not here."); |
| 1167 | error.userFacing = true; |
| 1168 | throw error; |
| 1169 | } |
| 1170 | if (isUntargetable(this.ecs, targetHandle)) |
| 1171 | { |
| 1172 | const error = new Error("Nothing to say."); |
| 1173 | error.userFacing = true; |
| 1174 | throw error; |
| 1175 | } |
| 1176 | const creature = this.ecs.get(targetHandle, Component.creature); |
| 1177 | const def = creature ? mobDefinition(creature.mobTypeId) : null; |
| 1178 | const shop = this.ecs.get(targetHandle, Component.shop); |
| 1179 | const hasShop = shopHasInterface(shop); |
| 1180 | const origin = this.ecs.get(targetHandle, Component.spawnOrigin); |
| 1181 | const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : ""; |
| 1182 | const intent = purpose === "shop" || purpose === "talk" ? purpose : null; |
| 1183 | |
| 1184 | if (intent === "shop" && hasShop) |
| 1185 | { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } |
| 1186 | if (intent === "talk" && dialogueId) |
| 1187 | { |
| 1188 | // Pin in-worker before return so wander cannot start before the sim thread pins. |
| 1189 | this.#pinDialogue(targetEntityId, characterId); |
| 1190 | return { |
| 1191 | events: [{ |
| 1192 | type: "open-dialogue", |
| 1193 | sessionId, |
| 1194 | characterId, |
| 1195 | entityId: targetEntityId, |
| 1196 | dialogueId |
| 1197 | }] |
| 1198 | }; |
| 1199 | } |
| 1200 | if (intent === "talk" && hasShop) |
| 1201 | { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } |
| 1202 | |
| 1203 | // Default click: prefer dialogue when assigned, else shop, else talkable no-op. |
| 1204 | if (dialogueId) |
| 1205 | { |
| 1206 | this.#pinDialogue(targetEntityId, characterId); |
| 1207 | return { |
| 1208 | events: [{ |
| 1209 | type: "open-dialogue", |
| 1210 | sessionId, |
| 1211 | characterId, |
| 1212 | entityId: targetEntityId, |
| 1213 | dialogueId |
| 1214 | }] |
| 1215 | }; |
| 1216 | } |
| 1217 | if (hasShop) |
| 1218 | { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); } |
| 1219 | if (!def?.talkable) |
| 1220 | { |
| 1221 | const error = new Error("They have nothing to say."); |
| 1222 | error.userFacing = true; |
| 1223 | throw error; |
| 1224 | } |
| 1225 | return { events: [] }; |
| 1226 | } |
| 1227 | |
| 1228 | #follow (sessionId, characterId, targetEntityId) |
| 1229 | { |
| 1230 | const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 1231 | const targetHandle = this.ecs.handleOf(targetEntityId); |
| 1232 | if (targetHandle == null) |
| 1233 | { |
| 1234 | const error = new Error("Target is not here."); |
| 1235 | error.userFacing = true; |
| 1236 | throw error; |
| 1237 | } |
| 1238 | if (targetEntityId === entityId) |
| 1239 | { |
| 1240 | const error = new Error("Cannot follow yourself."); |
| 1241 | error.userFacing = true; |
| 1242 | throw error; |
| 1243 | } |
| 1244 | if (!this.ecs.get(targetHandle, Component.position)) |
| 1245 | { |
| 1246 | const error = new Error("That cannot be followed."); |
| 1247 | error.userFacing = true; |
| 1248 | throw error; |
| 1249 | } |
| 1250 | clearEngage(this.ecs, entityId); |
| 1251 | setFollow(this.ecs, entityId, targetEntityId); |
| 1252 | const path = this.ecs.get(handle, Component.path); |
| 1253 | if (path) |
| 1254 | { path.tiles = []; } |
| 1255 | return { events: [] }; |
| 1256 | } |
| 1257 | |
| 1258 | #cancelFollow (sessionId, characterId) |
| 1259 | { |
| 1260 | const { entityId } = this.#requireOwnedEntity(sessionId, characterId); |
| 1261 | clearFollow(this.ecs, entityId); |
| 1262 | return { events: [] }; |
| 1263 | } |
| 1264 | |
| 1265 | #setGait (sessionId, characterId, gait) |
| 1266 | { |
| 1267 | if (gait !== GAIT.walk && gait !== GAIT.run) |
| 1268 | { |
| 1269 | const error = new Error("Gait must be walk or run."); |
| 1270 | error.userFacing = true; |
| 1271 | throw error; |
| 1272 | } |
| 1273 | const { handle } = this.#requireOwnedEntity(sessionId, characterId); |
| 1274 | const movement = this.ecs.get(handle, Component.movement); |
| 1275 | const stamina = this.ecs.get(handle, Component.stamina); |
| 1276 | if (gait === GAIT.run && !(Number(stamina?.current) > 0)) |
| 1277 | { |
| 1278 | const error = new Error("You are too exhausted to run."); |
| 1279 | error.userFacing = true; |
| 1280 | throw error; |
| 1281 | } |
| 1282 | movement.gait = gait; |
| 1283 | const character = this.ecs.get(handle, Component.character); |
| 1284 | return { |
| 1285 | events: character |
| 1286 | ? [this.#staminaEvent(handle, character.characterId, movement.gait)] |
| 1287 | : [] |
| 1288 | }; |
| 1289 | } |
| 1290 | |
| 1291 | #staminaEvent (handle, characterId, gait = null) |
| 1292 | { |
| 1293 | const stamina = this.ecs.get(handle, Component.stamina); |
| 1294 | const movement = this.ecs.get(handle, Component.movement); |
| 1295 | return { |
| 1296 | type: "stamina", |
| 1297 | characterId, |
| 1298 | ...publicStaminaView(stamina), |
| 1299 | gait: gait ?? movement?.gait ?? GAIT.walk |
| 1300 | }; |
| 1301 | } |
| 1302 | |
| 1303 | #consumeRunStamina (handle, events) |
| 1304 | { |
| 1305 | const character = this.ecs.get(handle, Component.character); |
| 1306 | if (!character) |
| 1307 | { return; } |
| 1308 | let stamina = this.ecs.get(handle, Component.stamina); |
| 1309 | if (!stamina) |
| 1310 | { |
| 1311 | stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 }); |
| 1312 | } |
| 1313 | const skills = this.ecs.get(handle, Component.skills); |
| 1314 | syncPlayerStamina(this.ecs, handle); |
| 1315 | const position = this.ecs.get(handle, Component.position); |
| 1316 | const onPath = position |
| 1317 | ? this.groundTypeAt(position.tileX, position.tileY, position.dimensionId) === GroundType.path |
| 1318 | : false; |
| 1319 | const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond, { onPath }); |
| 1320 | stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost); |
| 1321 | stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost; |
| 1322 | let skillsChanged = false; |
| 1323 | const levelUps = []; |
| 1324 | while (stamina.xpDebt >= 1 && skills?.xp) |
| 1325 | { |
| 1326 | stamina.xpDebt -= 1; |
| 1327 | const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT); |
| 1328 | if (result.changed) |
| 1329 | { |
| 1330 | skillsChanged = true; |
| 1331 | syncPlayerStamina(this.ecs, handle); |
| 1332 | } |
| 1333 | if (result.levelUp) |
| 1334 | { levelUps.push(result.levelUp); } |
| 1335 | } |
| 1336 | const movement = this.ecs.get(handle, Component.movement); |
| 1337 | if (stamina.current <= 0 && movement) |
| 1338 | { |
| 1339 | stamina.current = 0; |
| 1340 | movement.gait = GAIT.walk; |
| 1341 | } |
| 1342 | events.push(this.#staminaEvent(handle, character.characterId)); |
| 1343 | if (skillsChanged) |
| 1344 | { |
| 1345 | events.push({ |
| 1346 | type: "skills-updated", |
| 1347 | entityId: this.ecs.entityIdOf(handle), |
| 1348 | characterId: character.characterId, |
| 1349 | ...publicSkillsPayload(skills), |
| 1350 | stored: storedSkillXp(skills), |
| 1351 | levelUps |
| 1352 | }); |
| 1353 | } |
| 1354 | } |
| 1355 | |
| 1356 | #regenStamina (dt, events) |
| 1357 | { |
| 1358 | if (!(dt > 0)) |
| 1359 | { return; } |
| 1360 | for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement)) |
| 1361 | { |
| 1362 | const { handle, character, stamina, movement } = entity; |
| 1363 | if (this.ecs.has(handle, Component.dead)) |
| 1364 | { continue; } |
| 1365 | const status = this.ecs.get(handle, Component.statusEffects); |
| 1366 | if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now())) |
| 1367 | { continue; } |
| 1368 | // Run gait only blocks regen while actually stepping along a path. |
| 1369 | const path = this.ecs.get(handle, Component.path); |
| 1370 | if (movement.gait === GAIT.run && path?.tiles?.length) |
| 1371 | { continue; } |
| 1372 | syncPlayerStamina(this.ecs, handle); |
| 1373 | const before = Number(stamina.current) || 0; |
| 1374 | if (before >= stamina.max) |
| 1375 | { continue; } |
| 1376 | stamina.current = Math.min( |
| 1377 | stamina.max, |
| 1378 | before + dt * STAMINA_REGEN_PER_SECOND * passiveStaminaRegenMultiplier( |
| 1379 | this.ecs.get(handle, Component.equipment) |
| 1380 | ) |
| 1381 | ); |
| 1382 | const after = Number(stamina.current) || 0; |
| 1383 | // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam. |
| 1384 | if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max)) |
| 1385 | { events.push(this.#staminaEvent(handle, character.characterId)); } |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | #requireOwnedEntity (sessionId, characterId) |
| 1390 | { |
| 1391 | const entityId = this.characterEntities.get(characterId); |
| 1392 | if (!entityId) |
| 1393 | { |
| 1394 | const error = new Error("Character is not in the world."); |
| 1395 | error.userFacing = true; |
| 1396 | throw error; |
| 1397 | } |
| 1398 | const handle = this.ecs.handleOf(entityId); |
| 1399 | const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null; |
| 1400 | if (!identity || identity.sessionId !== sessionId) |
| 1401 | { |
| 1402 | const error = new Error("Character is not in the world."); |
| 1403 | error.userFacing = true; |
| 1404 | throw error; |
| 1405 | } |
| 1406 | if (this.ecs.has(handle, Component.dead)) |
| 1407 | { |
| 1408 | const error = new Error("You are dead."); |
| 1409 | error.userFacing = true; |
| 1410 | throw error; |
| 1411 | } |
| 1412 | return { handle, entityId }; |
| 1413 | } |
| 1414 | |
| 1415 | #stepSystems (now = Date.now(), dt = 1 / 20) |
| 1416 | { |
| 1417 | const events = []; |
| 1418 | const transferRequests = []; |
| 1419 | this.#regenStamina(dt, events); |
| 1420 | events.push(...stepStatusEffects(this, now, dt)); |
| 1421 | events.push(...stepPassiveHealthRegen(this, now, dt)); |
| 1422 | const flight = stepFreeFlight(this, now); |
| 1423 | for (const event of flight) |
| 1424 | { |
| 1425 | if (event.type === "transfer-request") |
| 1426 | { |
| 1427 | const payload = serializeEntity(this.ecs, event.entityId); |
| 1428 | transferRequests.push({ |
| 1429 | entityId: event.entityId, |
| 1430 | fromTileX: event.fromTileX, |
| 1431 | fromTileY: event.fromTileY, |
| 1432 | destTileX: event.destTileX, |
| 1433 | destTileY: event.destTileY, |
| 1434 | toRegionX: event.toRegionX, |
| 1435 | toRegionY: event.toRegionY, |
| 1436 | dimensionId: event.dimensionId ?? OVERWORLD_ID, |
| 1437 | payload |
| 1438 | }); |
| 1439 | continue; |
| 1440 | } |
| 1441 | events.push(event); |
| 1442 | } |
| 1443 | stepAggression(this, now); |
| 1444 | events.push(...stepCombat(this, now)); |
| 1445 | events.push(...stepPendingSpellCast(this, now)); |
| 1446 | events.push(...processSpellImpacts(this, now)); |
| 1447 | events.push(...stepSpellAutoCast(this, now)); |
| 1448 | events.push(...tickSpellLights(this, now)); |
| 1449 | const summons = stepSummons(this, now); |
| 1450 | events.push(...(summons.events ?? [])); |
| 1451 | for (const entityId of summons.despawnIds ?? []) |
| 1452 | { |
| 1453 | const dropped = this.#destroyEntity(entityId); |
| 1454 | if (dropped) |
| 1455 | { events.push({ type: "entity-despawn", entityId }); } |
| 1456 | } |
| 1457 | const fairies = stepJadeiteFairies(this, now); |
| 1458 | events.push(...(fairies.events ?? [])); |
| 1459 | for (const entityId of fairies.despawnIds ?? []) |
| 1460 | { |
| 1461 | const dropped = this.#destroyEntity(entityId); |
| 1462 | if (dropped) |
| 1463 | { events.push({ type: "entity-despawn", entityId }); } |
| 1464 | } |
| 1465 | events.push(...stepJewelryTeleports(this, now).events); |
| 1466 | stepFollow(this); |
| 1467 | const gather = stepGather(this, now); |
| 1468 | events.push(...gather.events); |
| 1469 | for (const entry of gather.privates ?? []) |
| 1470 | { |
| 1471 | events.push({ |
| 1472 | type: "inventory", |
| 1473 | characterId: entry.characterId, |
| 1474 | ...entry.bag |
| 1475 | }); |
| 1476 | } |
| 1477 | const fire = stepFirestarting(this, now); |
| 1478 | events.push(...fire.events); |
| 1479 | for (const entry of fire.privates ?? []) |
| 1480 | { |
| 1481 | events.push({ |
| 1482 | type: "inventory", |
| 1483 | characterId: entry.characterId, |
| 1484 | ...entry.bag |
| 1485 | }); |
| 1486 | } |
| 1487 | const fishing = stepFishing(this, now); |
| 1488 | events.push(...fishing.events); |
| 1489 | for (const entry of fishing.privates ?? []) |
| 1490 | { |
| 1491 | events.push({ |
| 1492 | type: "inventory", |
| 1493 | characterId: entry.characterId, |
| 1494 | ...entry.bag |
| 1495 | }); |
| 1496 | } |
| 1497 | const shearing = stepShearing(this, now); |
| 1498 | events.push(...shearing.events); |
| 1499 | for (const entry of shearing.privates ?? []) |
| 1500 | { |
| 1501 | events.push({ |
| 1502 | type: "inventory", |
| 1503 | characterId: entry.characterId, |
| 1504 | ...entry.bag |
| 1505 | }); |
| 1506 | } |
| 1507 | const craft = stepCrafting(this, now); |
| 1508 | events.push(...craft.events); |
| 1509 | for (const entry of craft.privates ?? []) |
| 1510 | { |
| 1511 | events.push({ |
| 1512 | type: "inventory", |
| 1513 | characterId: entry.characterId, |
| 1514 | ...entry.bag |
| 1515 | }); |
| 1516 | } |
| 1517 | events.push(...stepDoors(this)); |
| 1518 | return { events, transferRequests }; |
| 1519 | } |
| 1520 | |
| 1521 | #stepMovement (now = Date.now()) |
| 1522 | { |
| 1523 | const events = expireGroundItems(this, now); |
| 1524 | const transferRequests = []; |
| 1525 | events.push(...pruneShopBrowsers(this)); |
| 1526 | events.push(...this.#pruneDialogueBrowsers()); |
| 1527 | this.#queueAmbientWander(); |
| 1528 | this.#queueSpawnerWander(); |
| 1529 | this.#queueExchangeStations(); |
| 1530 | for (const entity of this.ecs.query(Component.position, Component.movement)) |
| 1531 | { |
| 1532 | const { handle, entityId, position, movement } = entity; |
| 1533 | if (this.ecs.has(handle, Component.dead)) |
| 1534 | { continue; } |
| 1535 | if (this.ecs.has(handle, Component.flight)) |
| 1536 | { continue; } |
| 1537 | const path = this.ecs.get(handle, Component.path); |
| 1538 | const tiles = path?.tiles; |
| 1539 | if (this.frozen.has(entityId) || !tiles?.length) |
| 1540 | { |
| 1541 | if (path) |
| 1542 | { path.stuckSince = null; } |
| 1543 | continue; |
| 1544 | } |
| 1545 | if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID)) |
| 1546 | { continue; } |
| 1547 | |
| 1548 | this.#repathIfNavigationStuck(entityId, position, movement, path, now); |
| 1549 | |
| 1550 | const stamina = this.ecs.get(handle, Component.stamina); |
| 1551 | if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0)) |
| 1552 | { movement.gait = GAIT.walk; } |
| 1553 | const isWalk = movement.gait !== GAIT.run; |
| 1554 | if (isWalk) |
| 1555 | { |
| 1556 | movement.walkCarry = (movement.walkCarry + 1) % 2; |
| 1557 | if (movement.walkCarry !== 0) |
| 1558 | { continue; } |
| 1559 | } |
| 1560 | |
| 1561 | const next = tiles[0]; |
| 1562 | if (!next) |
| 1563 | { continue; } |
| 1564 | const destRegionX = tileToRegion(next.x); |
| 1565 | const destRegionY = tileToRegion(next.y); |
| 1566 | const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 1567 | if (!this.ownsRegion(destRegionX, destRegionY, dimensionId)) |
| 1568 | { |
| 1569 | this.frozen.add(entityId); |
| 1570 | transferRequests.push({ |
| 1571 | entityId, |
| 1572 | fromTileX: position.tileX, |
| 1573 | fromTileY: position.tileY, |
| 1574 | destTileX: next.x, |
| 1575 | destTileY: next.y, |
| 1576 | toRegionX: destRegionX, |
| 1577 | toRegionY: destRegionY, |
| 1578 | dimensionId, |
| 1579 | payload: serializeEntity(this.ecs, entityId) |
| 1580 | }); |
| 1581 | continue; |
| 1582 | } |
| 1583 | |
| 1584 | if (!this.walkableFor(entityId, next.x, next.y)) |
| 1585 | { |
| 1586 | const combat = this.ecs.get(handle, Component.combat); |
| 1587 | if (combat?.targetEntityId != null) |
| 1588 | { |
| 1589 | const targetHandle = this.ecs.handleOf(combat.targetEntityId); |
| 1590 | const targetPos = targetHandle != null |
| 1591 | ? this.ecs.get(targetHandle, Component.position) |
| 1592 | : null; |
| 1593 | const blockedByTarget = targetPos |
| 1594 | && next.x === targetPos.tileX |
| 1595 | && next.y === targetPos.tileY; |
| 1596 | if (!blockedByTarget) |
| 1597 | { path.tiles = []; } |
| 1598 | } |
| 1599 | continue; |
| 1600 | } |
| 1601 | |
| 1602 | const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y); |
| 1603 | if (doorDelta) |
| 1604 | { events.push(doorDelta); } |
| 1605 | |
| 1606 | const combat = this.ecs.get(handle, Component.combat); |
| 1607 | if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y)) |
| 1608 | { continue; } |
| 1609 | |
| 1610 | const fromTileX = position.tileX; |
| 1611 | const fromTileY = position.tileY; |
| 1612 | const flying = this.#isFlying(handle); |
| 1613 | if (!flying) |
| 1614 | { this.#vacate(entityId, fromTileX, fromTileY); } |
| 1615 | position.tileX = next.x; |
| 1616 | position.tileY = next.y; |
| 1617 | tiles.shift(); |
| 1618 | if (!flying) |
| 1619 | { this.#occupy(entityId, position.tileX, position.tileY, now); } |
| 1620 | path.stuckSince = now; |
| 1621 | path.stuckTileX = position.tileX; |
| 1622 | path.stuckTileY = position.tileY; |
| 1623 | recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY); |
| 1624 | consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY); |
| 1625 | syncCharacterChunkPresence(this.ecs, handle, now); |
| 1626 | if (!isWalk) |
| 1627 | { this.#consumeRunStamina(handle, events); } |
| 1628 | events.push(this.#moveEvent(entityId, fromTileX, fromTileY)); |
| 1629 | } |
| 1630 | return { events, transferRequests }; |
| 1631 | } |
| 1632 | |
| 1633 | /** |
| 1634 | * If we still have a destination but have not left this tile for NAV_STUCK_MS, |
| 1635 | * recompute A* to the same goal (around whoever is blocking the old route). |
| 1636 | */ |
| 1637 | #repathIfNavigationStuck (entityId, position, movement, path, now) |
| 1638 | { |
| 1639 | if (!path?.tiles?.length) |
| 1640 | { |
| 1641 | path.stuckSince = null; |
| 1642 | return; |
| 1643 | } |
| 1644 | if ( |
| 1645 | path.stuckSince == null |
| 1646 | || path.stuckTileX !== position.tileX |
| 1647 | || path.stuckTileY !== position.tileY |
| 1648 | ) |
| 1649 | { |
| 1650 | path.stuckSince = now; |
| 1651 | path.stuckTileX = position.tileX; |
| 1652 | path.stuckTileY = position.tileY; |
| 1653 | return; |
| 1654 | } |
| 1655 | if (now - path.stuckSince < NAV_STUCK_MS) |
| 1656 | { return; } |
| 1657 | |
| 1658 | const goal = path.tiles[path.tiles.length - 1]; |
| 1659 | if (!goal || (goal.x === position.tileX && goal.y === position.tileY)) |
| 1660 | { |
| 1661 | path.tiles = []; |
| 1662 | path.stuckSince = null; |
| 1663 | return; |
| 1664 | } |
| 1665 | const stuckHandle = this.ecs.handleOf(entityId); |
| 1666 | const isCharacter = stuckHandle != null && this.ecs.has(stuckHandle, Component.character); |
| 1667 | const bounds = chunkBoundsAround( |
| 1668 | position.tileX, |
| 1669 | position.tileY, |
| 1670 | isCharacter ? STATIC_CHUNK_RADIUS : VISIBLE_CHUNK_RADIUS |
| 1671 | ); |
| 1672 | const inCombat = stuckHandle != null |
| 1673 | && this.ecs.get(stuckHandle, Component.combat)?.targetEntityId != null; |
| 1674 | path.tiles = findPath( |
| 1675 | position.tileX, |
| 1676 | position.tileY, |
| 1677 | goal.x, |
| 1678 | goal.y, |
| 1679 | (x, y) => this.isClearStanding(entityId, x, y), |
| 1680 | bounds.minX, |
| 1681 | bounds.minY, |
| 1682 | bounds.maxX, |
| 1683 | bounds.maxY, |
| 1684 | this.pathfindOptions({ |
| 1685 | preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character), |
| 1686 | preferPaths: !inCombat, |
| 1687 | entityId |
| 1688 | }) |
| 1689 | ); |
| 1690 | path.stuckSince = now; |
| 1691 | path.stuckTileX = position.tileX; |
| 1692 | path.stuckTileY = position.tileY; |
| 1693 | if (movement) |
| 1694 | { movement.walkCarry = 0; } |
| 1695 | } |
| 1696 | |
| 1697 | #queueAmbientWander () |
| 1698 | { |
| 1699 | for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature)) |
| 1700 | { |
| 1701 | const def = mobDefinition(entity.creature.mobTypeId); |
| 1702 | if (!def?.ambient || def.freeFlight) |
| 1703 | { continue; } |
| 1704 | if (this.ecs.get(entity.handle, Component.spawnOrigin)) |
| 1705 | { continue; } |
| 1706 | const path = this.ecs.get(entity.handle, Component.path); |
| 1707 | if (!path) |
| 1708 | { continue; } |
| 1709 | if (path.tiles?.length) |
| 1710 | { continue; } |
| 1711 | if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID)) |
| 1712 | { continue; } |
| 1713 | if (Math.random() > 0.35) |
| 1714 | { continue; } |
| 1715 | const dirs = [ |
| 1716 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1717 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1718 | ]; |
| 1719 | const dir = dirs[Math.floor(Math.random() * dirs.length)]; |
| 1720 | const nextX = entity.position.tileX + dir.x; |
| 1721 | const nextY = entity.position.tileY + dir.y; |
| 1722 | if (!this.isClearStanding(entity.entityId, nextX, nextY)) |
| 1723 | { continue; } |
| 1724 | path.tiles = [{ x: nextX, y: nextY }]; |
| 1725 | } |
| 1726 | } |
| 1727 | |
| 1728 | /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */ |
| 1729 | #queueSpawnerWander () |
| 1730 | { |
| 1731 | for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin)) |
| 1732 | { |
| 1733 | const combat = this.ecs.get(entity.handle, Component.combat); |
| 1734 | if (combat?.targetEntityId != null) |
| 1735 | { continue; } |
| 1736 | const follow = this.ecs.get(entity.handle, Component.follow); |
| 1737 | if (follow?.targetEntityId != null) |
| 1738 | { continue; } |
| 1739 | const shop = this.ecs.get(entity.handle, Component.shop); |
| 1740 | if (shopHasActiveBrowsers(shop)) |
| 1741 | { continue; } |
| 1742 | const origin = entity.spawnOrigin; |
| 1743 | if (originIsBusyPinned(origin)) |
| 1744 | { continue; } |
| 1745 | if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY)) |
| 1746 | { continue; } |
| 1747 | const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId); |
| 1748 | if (def?.freeFlight) |
| 1749 | { continue; } |
| 1750 | const path = this.ecs.get(entity.handle, Component.path); |
| 1751 | if (!path || path.tiles?.length) |
| 1752 | { continue; } |
| 1753 | if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID)) |
| 1754 | { continue; } |
| 1755 | |
| 1756 | const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX; |
| 1757 | const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY; |
| 1758 | const range = Math.max(0, origin.wanderRangeTiles | 0); |
| 1759 | const homeDist = Math.max( |
| 1760 | Math.abs(entity.position.tileX - originX), |
| 1761 | Math.abs(entity.position.tileY - originY) |
| 1762 | ); |
| 1763 | const tooFar = homeDist > range; |
| 1764 | |
| 1765 | // Outside the leash: always try to step home. Inside: mostly idle. |
| 1766 | if (!tooFar && Math.random() > 0.1) |
| 1767 | { continue; } |
| 1768 | |
| 1769 | if (tooFar) |
| 1770 | { |
| 1771 | if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY)) |
| 1772 | { continue; } |
| 1773 | queueLocalRandomWanderStep(this, entity.entityId, entity.position, path); |
| 1774 | continue; |
| 1775 | } |
| 1776 | |
| 1777 | const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range); |
| 1778 | if (!goal) |
| 1779 | { continue; } |
| 1780 | if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY) |
| 1781 | { continue; } |
| 1782 | const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1783 | const tiles = findPath( |
| 1784 | entity.position.tileX, |
| 1785 | entity.position.tileY, |
| 1786 | goal.tileX, |
| 1787 | goal.tileY, |
| 1788 | (x, y) => this.walkableFor(entity.entityId, x, y), |
| 1789 | bounds.minX, |
| 1790 | bounds.minY, |
| 1791 | bounds.maxX, |
| 1792 | bounds.maxY, |
| 1793 | this.pathfindOptions({ preferPaths: true, entityId: entity.entityId }) |
| 1794 | ); |
| 1795 | if (!tiles?.length) |
| 1796 | { continue; } |
| 1797 | path.tiles = tiles; |
| 1798 | } |
| 1799 | } |
| 1800 | |
| 1801 | /** |
| 1802 | * Path toward the spawner within the current pathfinding window (chunk-step home). |
| 1803 | * @returns {boolean} true if a return path was queued |
| 1804 | */ |
| 1805 | #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY) |
| 1806 | { |
| 1807 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1808 | const goal = pickClearGoalToward( |
| 1809 | this, |
| 1810 | entityId, |
| 1811 | position.tileX, |
| 1812 | position.tileY, |
| 1813 | originX, |
| 1814 | originY, |
| 1815 | bounds |
| 1816 | ); |
| 1817 | if (!goal) |
| 1818 | { return false; } |
| 1819 | if (goal.tileX === position.tileX && goal.tileY === position.tileY) |
| 1820 | { return false; } |
| 1821 | const tiles = findPath( |
| 1822 | position.tileX, |
| 1823 | position.tileY, |
| 1824 | goal.tileX, |
| 1825 | goal.tileY, |
| 1826 | (x, y) => this.walkableFor(entityId, x, y), |
| 1827 | bounds.minX, |
| 1828 | bounds.minY, |
| 1829 | bounds.maxX, |
| 1830 | bounds.maxY, |
| 1831 | this.pathfindOptions({ preferPaths: true, entityId }) |
| 1832 | ); |
| 1833 | if (!tiles?.length) |
| 1834 | { return false; } |
| 1835 | path.tiles = tiles; |
| 1836 | const movement = this.ecs.get(handle, Component.movement); |
| 1837 | if (movement) |
| 1838 | { movement.walkCarry = 0; } |
| 1839 | return true; |
| 1840 | } |
| 1841 | |
| 1842 | /** |
| 1843 | * Send an idle Central Exchange clerk to the staff-side tile of a counter. |
| 1844 | * message: { stationTileX, stationTileY } |
| 1845 | */ |
| 1846 | #stationExchangeClerk (message) |
| 1847 | { |
| 1848 | const stationTileX = message.stationTileX | 0; |
| 1849 | const stationTileY = message.stationTileY | 0; |
| 1850 | if (!this.isEnterable(stationTileX, stationTileY)) |
| 1851 | { return { ok: false, reason: "blocked" }; } |
| 1852 | |
| 1853 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) |
| 1854 | { |
| 1855 | if (!entity.spawnOrigin?.centralExchange) |
| 1856 | { continue; } |
| 1857 | if ( |
| 1858 | Number.isInteger(entity.spawnOrigin.stationTileX) |
| 1859 | && entity.spawnOrigin.stationTileX === stationTileX |
| 1860 | && entity.spawnOrigin.stationTileY === stationTileY |
| 1861 | ) |
| 1862 | { return { ok: true, entityId: entity.entityId, already: true }; } |
| 1863 | } |
| 1864 | |
| 1865 | let best = null; |
| 1866 | let bestDist = Infinity; |
| 1867 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) |
| 1868 | { |
| 1869 | if (!entity.spawnOrigin?.centralExchange) |
| 1870 | { continue; } |
| 1871 | if (Number.isInteger(entity.spawnOrigin.stationTileX)) |
| 1872 | { continue; } |
| 1873 | const dist = Math.max( |
| 1874 | Math.abs(entity.position.tileX - stationTileX), |
| 1875 | Math.abs(entity.position.tileY - stationTileY) |
| 1876 | ); |
| 1877 | if (dist < bestDist) |
| 1878 | { |
| 1879 | bestDist = dist; |
| 1880 | best = entity; |
| 1881 | } |
| 1882 | } |
| 1883 | if (!best) |
| 1884 | { return { ok: false, reason: "none-available" }; } |
| 1885 | |
| 1886 | const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1887 | const tiles = findPath( |
| 1888 | best.position.tileX, |
| 1889 | best.position.tileY, |
| 1890 | stationTileX, |
| 1891 | stationTileY, |
| 1892 | (x, y) => this.walkableFor(best.entityId, x, y), |
| 1893 | bounds.minX, |
| 1894 | bounds.minY, |
| 1895 | bounds.maxX, |
| 1896 | bounds.maxY, |
| 1897 | this.pathfindOptions({ preferPaths: true, entityId: best.entityId }) |
| 1898 | ); |
| 1899 | best.spawnOrigin.stationTileX = stationTileX; |
| 1900 | best.spawnOrigin.stationTileY = stationTileY; |
| 1901 | if (tiles?.length) |
| 1902 | { best.path.tiles = tiles; } |
| 1903 | else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY) |
| 1904 | { best.path.tiles = []; } |
| 1905 | else |
| 1906 | { return { ok: false, reason: "no-path" }; } |
| 1907 | return { ok: true, entityId: best.entityId }; |
| 1908 | } |
| 1909 | |
| 1910 | /** |
| 1911 | * Clear a CE clerk's station assignment so wander can resume. |
| 1912 | * message: { stationTileX, stationTileY } |
| 1913 | */ |
| 1914 | #releaseExchangeClerk (message) |
| 1915 | { |
| 1916 | const stationTileX = message.stationTileX | 0; |
| 1917 | const stationTileY = message.stationTileY | 0; |
| 1918 | let released = 0; |
| 1919 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.path)) |
| 1920 | { |
| 1921 | if (!entity.spawnOrigin?.centralExchange) |
| 1922 | { continue; } |
| 1923 | if ( |
| 1924 | entity.spawnOrigin.stationTileX !== stationTileX |
| 1925 | || entity.spawnOrigin.stationTileY !== stationTileY |
| 1926 | ) |
| 1927 | { continue; } |
| 1928 | entity.spawnOrigin.stationTileX = null; |
| 1929 | entity.spawnOrigin.stationTileY = null; |
| 1930 | entity.path.tiles = []; |
| 1931 | released += 1; |
| 1932 | } |
| 1933 | return { ok: true, released }; |
| 1934 | } |
| 1935 | |
| 1936 | #pinDialogue (entityId, characterId) |
| 1937 | { |
| 1938 | const handle = this.ecs.handleOf(entityId | 0); |
| 1939 | if (handle == null) |
| 1940 | { return { ok: false }; } |
| 1941 | const origin = this.ecs.get(handle, Component.spawnOrigin); |
| 1942 | if (!origin) |
| 1943 | { return { ok: false }; } |
| 1944 | if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object") |
| 1945 | { origin.dialogueBrowsers = Object.create(null); } |
| 1946 | origin.dialogueBrowsers[characterId | 0] = true; |
| 1947 | const path = this.ecs.get(handle, Component.path); |
| 1948 | if (path) |
| 1949 | { path.tiles = []; } |
| 1950 | return { ok: true }; |
| 1951 | } |
| 1952 | |
| 1953 | #unpinDialogue (entityId, characterId) |
| 1954 | { |
| 1955 | const handle = this.ecs.handleOf(entityId | 0); |
| 1956 | if (handle == null) |
| 1957 | { return { ok: false }; } |
| 1958 | const origin = this.ecs.get(handle, Component.spawnOrigin); |
| 1959 | if (!origin?.dialogueBrowsers) |
| 1960 | { return { ok: true }; } |
| 1961 | delete origin.dialogueBrowsers[characterId | 0]; |
| 1962 | return { ok: true }; |
| 1963 | } |
| 1964 | |
| 1965 | #pruneDialogueBrowsers () |
| 1966 | { |
| 1967 | const events = []; |
| 1968 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) |
| 1969 | { |
| 1970 | const browsers = entity.spawnOrigin?.dialogueBrowsers; |
| 1971 | const shearBrowsers = entity.spawnOrigin?.shearBrowsers; |
| 1972 | const dialogueIds = browsers && typeof browsers === "object" |
| 1973 | ? Object.keys(browsers).map((id) => Number(id)) |
| 1974 | : []; |
| 1975 | const shearIds = shearBrowsers && typeof shearBrowsers === "object" |
| 1976 | ? Object.keys(shearBrowsers).map((id) => Number(id)) |
| 1977 | : []; |
| 1978 | if (!dialogueIds.length && !shearIds.length) |
| 1979 | { continue; } |
| 1980 | const path = this.ecs.get(entity.handle, Component.path); |
| 1981 | if (path) |
| 1982 | { path.tiles = []; } |
| 1983 | for (const characterId of dialogueIds) |
| 1984 | { |
| 1985 | const playerEntityId = this.characterEntities.get(characterId); |
| 1986 | if (playerEntityId == null) |
| 1987 | { |
| 1988 | delete browsers[characterId]; |
| 1989 | continue; |
| 1990 | } |
| 1991 | const playerHandle = this.ecs.handleOf(playerEntityId); |
| 1992 | const playerPos = this.ecs.get(playerHandle, Component.position); |
| 1993 | const stillNear = playerPos |
| 1994 | && chebyshev( |
| 1995 | playerPos.tileX, |
| 1996 | playerPos.tileY, |
| 1997 | entity.position.tileX, |
| 1998 | entity.position.tileY |
| 1999 | ) <= 1; |
| 2000 | if (stillNear) |
| 2001 | { continue; } |
| 2002 | delete browsers[characterId]; |
| 2003 | const identity = this.ecs.get(playerHandle, Component.networkIdentity); |
| 2004 | events.push({ |
| 2005 | type: "dialogue-walk-away", |
| 2006 | sessionId: identity?.sessionId ?? null, |
| 2007 | characterId, |
| 2008 | npcEntityId: entity.entityId |
| 2009 | }); |
| 2010 | } |
| 2011 | for (const characterId of shearIds) |
| 2012 | { |
| 2013 | const playerEntityId = this.characterEntities.get(characterId); |
| 2014 | if (playerEntityId == null) |
| 2015 | { |
| 2016 | delete shearBrowsers[characterId]; |
| 2017 | continue; |
| 2018 | } |
| 2019 | const playerHandle = this.ecs.handleOf(playerEntityId); |
| 2020 | const playerPos = this.ecs.get(playerHandle, Component.position); |
| 2021 | const stillNear = playerPos |
| 2022 | && chebyshev( |
| 2023 | playerPos.tileX, |
| 2024 | playerPos.tileY, |
| 2025 | entity.position.tileX, |
| 2026 | entity.position.tileY |
| 2027 | ) <= 1; |
| 2028 | if (stillNear) |
| 2029 | { continue; } |
| 2030 | delete shearBrowsers[characterId]; |
| 2031 | } |
| 2032 | } |
| 2033 | return events; |
| 2034 | } |
| 2035 | |
| 2036 | /** Keep stationed CE clerks at their counter tile. */ |
| 2037 | #queueExchangeStations () |
| 2038 | { |
| 2039 | for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) |
| 2040 | { |
| 2041 | if (!entity.spawnOrigin?.centralExchange) |
| 2042 | { continue; } |
| 2043 | const sx = entity.spawnOrigin.stationTileX; |
| 2044 | const sy = entity.spawnOrigin.stationTileY; |
| 2045 | if (!Number.isInteger(sx) || !Number.isInteger(sy)) |
| 2046 | { continue; } |
| 2047 | if (entity.position.tileX === sx && entity.position.tileY === sy) |
| 2048 | { |
| 2049 | entity.path.tiles = []; |
| 2050 | continue; |
| 2051 | } |
| 2052 | if (entity.path.tiles?.length) |
| 2053 | { continue; } |
| 2054 | const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); |
| 2055 | const tiles = findPath( |
| 2056 | entity.position.tileX, |
| 2057 | entity.position.tileY, |
| 2058 | sx, |
| 2059 | sy, |
| 2060 | (x, y) => this.walkableFor(entity.entityId, x, y), |
| 2061 | bounds.minX, |
| 2062 | bounds.minY, |
| 2063 | bounds.maxX, |
| 2064 | bounds.maxY, |
| 2065 | this.pathfindOptions({ preferPaths: true, entityId: entity.entityId }) |
| 2066 | ); |
| 2067 | if (tiles?.length) |
| 2068 | { entity.path.tiles = tiles; } |
| 2069 | } |
| 2070 | } |
| 2071 | |
| 2072 | #applyTransfer (message) |
| 2073 | { |
| 2074 | const payload = message.payload; |
| 2075 | const entityId = payload.entityId; |
| 2076 | if (this.ecs.hasEntity(entityId)) |
| 2077 | { return { accepted: false, reason: "already-present" }; } |
| 2078 | |
| 2079 | const position = payload.components?.position; |
| 2080 | const destTileX = message.destTileX ?? position?.tileX; |
| 2081 | const destTileY = message.destTileY ?? position?.tileY; |
| 2082 | const dimensionId = normalizeDimensionId( |
| 2083 | message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID |
| 2084 | ); |
| 2085 | if (destTileX == null || destTileY == null) |
| 2086 | { return { accepted: false, reason: "missing-destination" }; } |
| 2087 | if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId)) |
| 2088 | { return { accepted: false, reason: "not-owner" }; } |
| 2089 | |
| 2090 | const creature = payload.components?.creature; |
| 2091 | const flying = !!mobDefinition(creature?.mobTypeId)?.flying; |
| 2092 | if (flying) |
| 2093 | { |
| 2094 | const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId); |
| 2095 | if (!data?.open) |
| 2096 | { return { accepted: false, reason: "blocked" }; } |
| 2097 | } |
| 2098 | else if (!this.isEnterable(destTileX, destTileY, dimensionId)) |
| 2099 | { return { accepted: false, reason: "blocked" }; } |
| 2100 | |
| 2101 | deserializeEntity(this.ecs, payload); |
| 2102 | const handle = this.ecs.handleOf(entityId); |
| 2103 | const livePosition = this.ecs.get(handle, Component.position); |
| 2104 | const path = this.ecs.get(handle, Component.path); |
| 2105 | livePosition.tileX = destTileX; |
| 2106 | livePosition.tileY = destTileY; |
| 2107 | livePosition.dimensionId = dimensionId; |
| 2108 | if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY) |
| 2109 | { path.tiles.shift(); } |
| 2110 | if (!flying) |
| 2111 | { this.#occupy(entityId, destTileX, destTileY); } |
| 2112 | const character = this.ecs.get(handle, Component.character); |
| 2113 | if (character?.characterId) |
| 2114 | { this.characterEntities.set(character.characterId, entityId); } |
| 2115 | this.frozen.delete(entityId); |
| 2116 | return { |
| 2117 | accepted: true, |
| 2118 | entity: publicEntityView(this.ecs, entityId) |
| 2119 | }; |
| 2120 | } |
| 2121 | |
| 2122 | #commitTransfer (entityId) |
| 2123 | { |
| 2124 | if (!this.ecs.hasEntity(entityId)) |
| 2125 | { return null; } |
| 2126 | return this.#destroyEntity(entityId); |
| 2127 | } |
| 2128 | |
| 2129 | #abortTransfer (entityId) |
| 2130 | { |
| 2131 | this.frozen.delete(entityId); |
| 2132 | return publicEntityView(this.ecs, entityId); |
| 2133 | } |
| 2134 | |
| 2135 | #listLoaders () |
| 2136 | { |
| 2137 | return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({ |
| 2138 | entityId: entity.entityId, |
| 2139 | tileX: entity.position.tileX, |
| 2140 | tileY: entity.position.tileY, |
| 2141 | dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID), |
| 2142 | chunkLoader: { ...entity.chunkLoader } |
| 2143 | })); |
| 2144 | } |
| 2145 | |
| 2146 | #listPublicEntities () |
| 2147 | { |
| 2148 | const out = []; |
| 2149 | for (const entity of this.ecs.query(Component.position)) |
| 2150 | { |
| 2151 | if (this.ecs.has(entity.handle, Component.dead)) |
| 2152 | { continue; } |
| 2153 | const view = publicEntityView(this.ecs, entity.entityId); |
| 2154 | if (view) |
| 2155 | { out.push(view); } |
| 2156 | } |
| 2157 | return out; |
| 2158 | } |
| 2159 | |
| 2160 | #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID) |
| 2161 | { |
| 2162 | const dim = normalizeDimensionId(dimensionId); |
| 2163 | const records = []; |
| 2164 | for (const entity of this.ecs.query(Component.position)) |
| 2165 | { |
| 2166 | const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID); |
| 2167 | if (entityDim !== dim) |
| 2168 | { continue; } |
| 2169 | if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY) |
| 2170 | { continue; } |
| 2171 | records.push({ |
| 2172 | ...publicEntityView(this.ecs, entity.entityId), |
| 2173 | persistent: this.ecs.has(entity.handle, Component.persistent), |
| 2174 | payload: serializeEntity(this.ecs, entity.entityId) |
| 2175 | }); |
| 2176 | } |
| 2177 | return records; |
| 2178 | } |
| 2179 | |
| 2180 | #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID) |
| 2181 | { |
| 2182 | const dim = normalizeDimensionId(dimensionId); |
| 2183 | const data = this.#chunkData(chunkX, chunkY, dim); |
| 2184 | if (staticOnly) |
| 2185 | { |
| 2186 | return { |
| 2187 | chunkX, |
| 2188 | chunkY, |
| 2189 | dimensionId: dim, |
| 2190 | open: data.open, |
| 2191 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open), |
| 2192 | grounds: data.grounds, |
| 2193 | blocks: data.blocks, |
| 2194 | light: data.light, |
| 2195 | occlusion: data.occlusion, |
| 2196 | entities: [], |
| 2197 | groundItems: [] |
| 2198 | }; |
| 2199 | } |
| 2200 | const entities = []; |
| 2201 | for (const entity of this.ecs.query(Component.position, Component.appearance)) |
| 2202 | { |
| 2203 | if (this.ecs.has(entity.handle, Component.dead)) |
| 2204 | { continue; } |
| 2205 | const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID); |
| 2206 | if (entityDim !== dim) |
| 2207 | { continue; } |
| 2208 | if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY) |
| 2209 | { continue; } |
| 2210 | entities.push(publicEntityView(this.ecs, entity.entityId)); |
| 2211 | } |
| 2212 | return { |
| 2213 | chunkX, |
| 2214 | chunkY, |
| 2215 | dimensionId: dim, |
| 2216 | open: data.open, |
| 2217 | closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open), |
| 2218 | grounds: data.grounds, |
| 2219 | blocks: data.blocks, |
| 2220 | light: data.light, |
| 2221 | occlusion: data.occlusion, |
| 2222 | entities, |
| 2223 | groundItems: groundItemsInChunk(this, chunkX, chunkY) |
| 2224 | }; |
| 2225 | } |
| 2226 | |
| 2227 | #moveEvent (entityId, fromTileX, fromTileY) |
| 2228 | { |
| 2229 | const view = publicEntityView(this.ecs, entityId); |
| 2230 | return { |
| 2231 | type: "entity-move", |
| 2232 | entityId, |
| 2233 | fromTileX, |
| 2234 | fromTileY, |
| 2235 | tileX: view.tileX, |
| 2236 | tileY: view.tileY, |
| 2237 | worldX: view.worldX, |
| 2238 | worldY: view.worldY, |
| 2239 | gait: view.gait, |
| 2240 | freeFlight: !!view.freeFlight |
| 2241 | }; |
| 2242 | } |
| 2243 | |
| 2244 | chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2245 | { |
| 2246 | const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)); |
| 2247 | return !!chunk && !chunk.replica && chunk.simulating; |
| 2248 | } |
| 2249 | |
| 2250 | walkableFor (entityId, tileX, tileY) |
| 2251 | { |
| 2252 | const dim = this.#entityDimensionId(entityId); |
| 2253 | const handle = this.ecs.handleOf(entityId); |
| 2254 | if (this.#isFlying(handle)) |
| 2255 | { |
| 2256 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); |
| 2257 | return !!data?.open; |
| 2258 | } |
| 2259 | // Entities pass through each other; only terrain / closed chunks block movement. |
| 2260 | return this.isEnterable(tileX, tileY, dim, { |
| 2261 | canOpenDoors: entityCanOpenDoors(this.ecs, entityId) |
| 2262 | }); |
| 2263 | } |
| 2264 | |
| 2265 | /** Ground type id at a world tile (defaults to world default ground). */ |
| 2266 | groundTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2267 | { |
| 2268 | const dim = normalizeDimensionId(dimensionId) ?? OVERWORLD_ID; |
| 2269 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); |
| 2270 | const entry = normalizeGround(data.grounds[tileIndex(tileToLocal(tileX), tileToLocal(tileY))]); |
| 2271 | return entry?.typeId ?? this.settings.defaultGroundTypeId ?? GroundType.grass; |
| 2272 | } |
| 2273 | |
| 2274 | /** |
| 2275 | * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options] |
| 2276 | */ |
| 2277 | pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {}) |
| 2278 | { |
| 2279 | const options = { preferVertical: !!preferVertical }; |
| 2280 | const now = Date.now(); |
| 2281 | const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID; |
| 2282 | options.stepCost = (x, y) => stepCostForGround( |
| 2283 | this.groundTypeAt(x, y, dimensionId), |
| 2284 | { |
| 2285 | preferPaths: !!preferPaths, |
| 2286 | softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now) |
| 2287 | } |
| 2288 | ); |
| 2289 | options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1; |
| 2290 | return options; |
| 2291 | } |
| 2292 | |
| 2293 | /** |
| 2294 | * True when another living occupant has stood on this tile for SOFT_OCCUPIED_DWELL_MS+. |
| 2295 | * Soft cost only — never blocks pathing. |
| 2296 | */ |
| 2297 | #isSoftOccupiedTile (tileX, tileY, dimensionId, selfEntityId, now = Date.now()) |
| 2298 | { |
| 2299 | const key = tileKey(tileX, tileY, dimensionId); |
| 2300 | const local = this.occupancy.get(key); |
| 2301 | if (!local?.size) |
| 2302 | { return false; } |
| 2303 | for (const id of local) |
| 2304 | { |
| 2305 | if (id === selfEntityId) |
| 2306 | { continue; } |
| 2307 | const handle = this.ecs.handleOf(id); |
| 2308 | if (handle == null) |
| 2309 | { continue; } |
| 2310 | const position = this.ecs.get(handle, Component.position); |
| 2311 | const enteredAt = position?.tileEnteredAt; |
| 2312 | if (enteredAt == null) |
| 2313 | { continue; } |
| 2314 | if (now - enteredAt >= SOFT_OCCUPIED_DWELL_MS) |
| 2315 | { return true; } |
| 2316 | } |
| 2317 | return false; |
| 2318 | } |
| 2319 | |
| 2320 | /** |
| 2321 | * Standing tile with no other mob/player (self allowed). Used for wander goals |
| 2322 | * and melee attack stance. |
| 2323 | */ |
| 2324 | isClearStanding (entityId, tileX, tileY) |
| 2325 | { |
| 2326 | const dim = this.#entityDimensionId(entityId); |
| 2327 | if (!this.isEnterable(tileX, tileY, dim, { |
| 2328 | canOpenDoors: entityCanOpenDoors(this.ecs, entityId) |
| 2329 | })) |
| 2330 | { return false; } |
| 2331 | return !this.#hasOtherOccupant(entityId, tileX, tileY, dim); |
| 2332 | } |
| 2333 | |
| 2334 | destroyEntity (entityId) |
| 2335 | { |
| 2336 | return this.#destroyEntity(entityId); |
| 2337 | } |
| 2338 | |
| 2339 | occupied (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2340 | { |
| 2341 | return this.#anyOccupant(tileX, tileY, dimensionId); |
| 2342 | } |
| 2343 | |
| 2344 | #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2345 | { |
| 2346 | return this.chunkIsSimulating(tileX, tileY, dimensionId); |
| 2347 | } |
| 2348 | |
| 2349 | #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 2350 | { |
| 2351 | const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId)); |
| 2352 | if (loaded) |
| 2353 | { return loaded.data; } |
| 2354 | return createEmptyChunkData(this.settings.defaultGroundTypeId); |
| 2355 | } |
| 2356 | |
| 2357 | isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {}) |
| 2358 | { |
| 2359 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 2360 | if (!data.open) |
| 2361 | { return false; } |
| 2362 | return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors }); |
| 2363 | } |
| 2364 | |
| 2365 | isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2366 | { |
| 2367 | const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 2368 | if (!data.open) |
| 2369 | { return false; } |
| 2370 | return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 2371 | } |
| 2372 | |
| 2373 | #walkableFor (entityId, tileX, tileY) |
| 2374 | { |
| 2375 | return this.walkableFor(entityId, tileX, tileY); |
| 2376 | } |
| 2377 | |
| 2378 | #isFlying (handle) |
| 2379 | { |
| 2380 | if (handle == null) |
| 2381 | { return false; } |
| 2382 | const creature = this.ecs.get(handle, Component.creature); |
| 2383 | return !!mobDefinition(creature?.mobTypeId)?.flying; |
| 2384 | } |
| 2385 | |
| 2386 | #entityDimensionId (entityId) |
| 2387 | { |
| 2388 | const handle = this.ecs.handleOf(entityId); |
| 2389 | const position = handle != null ? this.ecs.get(handle, Component.position) : null; |
| 2390 | return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID); |
| 2391 | } |
| 2392 | |
| 2393 | #occupy (entityId, tileX, tileY, now = Date.now()) |
| 2394 | { |
| 2395 | const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId)); |
| 2396 | let set = this.occupancy.get(key); |
| 2397 | if (!set) |
| 2398 | { |
| 2399 | set = new Set(); |
| 2400 | this.occupancy.set(key, set); |
| 2401 | } |
| 2402 | set.add(entityId); |
| 2403 | const handle = this.ecs.handleOf(entityId); |
| 2404 | const position = handle != null ? this.ecs.get(handle, Component.position) : null; |
| 2405 | if (position) |
| 2406 | { position.tileEnteredAt = now; } |
| 2407 | } |
| 2408 | |
| 2409 | #vacate (entityId, tileX, tileY) |
| 2410 | { |
| 2411 | const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId)); |
| 2412 | const set = this.occupancy.get(key); |
| 2413 | if (!set) |
| 2414 | { return; } |
| 2415 | set.delete(entityId); |
| 2416 | if (set.size === 0) |
| 2417 | { this.occupancy.delete(key); } |
| 2418 | } |
| 2419 | |
| 2420 | #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2421 | { |
| 2422 | const key = tileKey(tileX, tileY, dimensionId); |
| 2423 | const local = this.occupancy.get(key); |
| 2424 | if (local?.size) |
| 2425 | { return local.values().next().value; } |
| 2426 | const ghosts = this.ghostOccupancy.get(key); |
| 2427 | if (ghosts?.size) |
| 2428 | { return ghosts.values().next().value; } |
| 2429 | return null; |
| 2430 | } |
| 2431 | |
| 2432 | #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null) |
| 2433 | { |
| 2434 | const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId); |
| 2435 | const key = tileKey(tileX, tileY, dim); |
| 2436 | const local = this.occupancy.get(key); |
| 2437 | if (local) |
| 2438 | { |
| 2439 | for (const id of local) |
| 2440 | { |
| 2441 | if (id !== entityId) |
| 2442 | { return true; } |
| 2443 | } |
| 2444 | } |
| 2445 | const ghosts = this.ghostOccupancy.get(key); |
| 2446 | if (ghosts) |
| 2447 | { |
| 2448 | for (const id of ghosts) |
| 2449 | { |
| 2450 | if (id !== entityId) |
| 2451 | { return true; } |
| 2452 | } |
| 2453 | } |
| 2454 | return false; |
| 2455 | } |
| 2456 | |
| 2457 | /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */ |
| 2458 | #occupied (tileX, tileY, dimensionId = OVERWORLD_ID) |
| 2459 | { |
| 2460 | return this.#anyOccupant(tileX, tileY, dimensionId); |
| 2461 | } |
| 2462 | } |
| 2463 | |
| 2464 | function pickWanderGoalInRange (world, entityId, originX, originY, range) |
| 2465 | { |
| 2466 | const radius = Math.max(0, range | 0); |
| 2467 | for (let attempt = 0; attempt < 24; attempt++) |
| 2468 | { |
| 2469 | const tileX = originX + randInt(-radius, radius); |
| 2470 | const tileY = originY + randInt(-radius, radius); |
| 2471 | if (!world.isClearStanding(entityId, tileX, tileY)) |
| 2472 | { continue; } |
| 2473 | return { tileX, tileY }; |
| 2474 | } |
| 2475 | return null; |
| 2476 | } |
| 2477 | |
| 2478 | /** |
| 2479 | * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY). |
| 2480 | * When the destination is outside the window this becomes a chunk-step toward home. |
| 2481 | */ |
| 2482 | function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds) |
| 2483 | { |
| 2484 | const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0)); |
| 2485 | const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0)); |
| 2486 | if (world.isClearStanding(entityId, idealX, idealY)) |
| 2487 | { return { tileX: idealX, tileY: idealY }; } |
| 2488 | for (let radius = 1; radius <= 4; radius++) |
| 2489 | { |
| 2490 | for (let dy = -radius; dy <= radius; dy++) |
| 2491 | { |
| 2492 | for (let dx = -radius; dx <= radius; dx++) |
| 2493 | { |
| 2494 | if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius) |
| 2495 | { continue; } |
| 2496 | const tileX = idealX + dx; |
| 2497 | const tileY = idealY + dy; |
| 2498 | if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY) |
| 2499 | { continue; } |
| 2500 | if (tileX === fromX && tileY === fromY) |
| 2501 | { continue; } |
| 2502 | if (!world.isClearStanding(entityId, tileX, tileY)) |
| 2503 | { continue; } |
| 2504 | return { tileX, tileY }; |
| 2505 | } |
| 2506 | } |
| 2507 | } |
| 2508 | return null; |
| 2509 | } |
| 2510 | |
| 2511 | /** One random adjacent step so a stranded mob does not freeze in place. */ |
| 2512 | function queueLocalRandomWanderStep (world, entityId, position, path) |
| 2513 | { |
| 2514 | const dirs = [ |
| 2515 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 2516 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 2517 | ]; |
| 2518 | for (let i = dirs.length - 1; i > 0; i--) |
| 2519 | { |
| 2520 | const j = Math.floor(Math.random() * (i + 1)); |
| 2521 | const tmp = dirs[i]; |
| 2522 | dirs[i] = dirs[j]; |
| 2523 | dirs[j] = tmp; |
| 2524 | } |
| 2525 | for (const dir of dirs) |
| 2526 | { |
| 2527 | const nextX = position.tileX + dir.x; |
| 2528 | const nextY = position.tileY + dir.y; |
| 2529 | if (!world.isClearStanding(entityId, nextX, nextY)) |
| 2530 | { continue; } |
| 2531 | path.tiles = [{ x: nextX, y: nextY }]; |
| 2532 | return true; |
| 2533 | } |
| 2534 | return false; |
| 2535 | } |
| 2536 | |
| 2537 | function hasDialogueBrowsers (origin) |
| 2538 | { |
| 2539 | return originIsBusyPinned(origin); |
| 2540 | } |
| 2541 | |
| 2542 | function randInt (min, max) |
| 2543 | { |
| 2544 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 2545 | } |
| 2546 | |
| 2547 | export function replicaNeededForOwnedChunks (ownedChunkKeys) |
| 2548 | { |
| 2549 | const needed = new Set(); |
| 2550 | for (const key of ownedChunkKeys) |
| 2551 | { |
| 2552 | const { chunkX, chunkY, dimensionId } = parseChunkKey(key); |
| 2553 | for (let dy = -1; dy <= 1; dy++) |
| 2554 | { |
| 2555 | for (let dx = -1; dx <= 1; dx++) |
| 2556 | { |
| 2557 | if (dx === 0 && dy === 0) |
| 2558 | { continue; } |
| 2559 | needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId)); |
| 2560 | } |
| 2561 | } |
| 2562 | } |
| 2563 | return needed; |
| 2564 | } |