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