| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { itemDefinition } from "../../../shared/definitions/items.js"; |
| 3 | import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; |
| 4 | import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js"; |
| 5 | import |
| 6 | { |
| 7 | mobCanFightType, |
| 8 | mobCanFight, |
| 9 | mobMeleeAttackProfile, |
| 10 | mobSkillLevels, |
| 11 | mobIsAggressive, |
| 12 | mobAggroRangeTiles, |
| 13 | mobIsBoss |
| 14 | } from "../../../shared/definitions/mobCombat.js"; |
| 15 | import { |
| 16 | combatLevelFromSkills, |
| 17 | mobAggressionLevel, |
| 18 | playerOutlevelsMobAggression |
| 19 | } from "../../../shared/combat/combatLevel.js"; |
| 20 | import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js"; |
| 21 | import { OVERWORLD_ID } from "../../../shared/world/dimensions.js"; |
| 22 | import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js"; |
| 23 | import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; |
| 24 | import { mobDamageAffinities } from "../../../shared/combat/magic.js"; |
| 25 | import { AttackType } from "../../../shared/definitions/attackTypes.js"; |
| 26 | import |
| 27 | { |
| 28 | effectiveHitSkillInDarkness, |
| 29 | aggroDistanceMultiplier |
| 30 | } from "../../../shared/combat/darkness.js"; |
| 31 | import |
| 32 | { |
| 33 | bakedTileLight01, |
| 34 | entityLightAtTile, |
| 35 | tileCombatLight01, |
| 36 | tileIndexLocal |
| 37 | } from "../../../shared/lighting/combatLight.js"; |
| 38 | import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js"; |
| 39 | import { LightOcclusion } from "../../../shared/definitions/tiles.js"; |
| 40 | import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js"; |
| 41 | import { spellLightsForDynamicLighting } from "../spells/lights.js"; |
| 42 | import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js"; |
| 43 | import |
| 44 | { |
| 45 | effectiveSkillLevel, |
| 46 | equipmentBonusesFromSlots |
| 47 | } from "../../../shared/equipment/stats.js"; |
| 48 | import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; |
| 49 | import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js"; |
| 50 | import |
| 51 | { |
| 52 | markHealthDamaged, |
| 53 | PASSIVE_HP_REGEN_DELAY_MS, |
| 54 | PASSIVE_HP_REGEN_PER_SECOND |
| 55 | } from "../../../shared/combat/passiveRegen.js"; |
| 56 | import { publicEntityView } from "../ecs/serialize.js"; |
| 57 | import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; |
| 58 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 59 | import { tileToChunk } from "../world/coordinates.js"; |
| 60 | import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js"; |
| 61 | import { CHUNK_SIZE, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; |
| 62 | import { stackQuantity } from "../../../shared/items/inventory.js"; |
| 63 | import { addGroundItem, publicGroundItem } from "../items/bags.js"; |
| 64 | import { resolveItemDualTint } from "../../../shared/render/tint.js"; |
| 65 | import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js"; |
| 66 | import { castMobAttackSpell } from "../spells/mobCast.js"; |
| 67 | import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; |
| 68 | import { scheduleSpawnerRespawn } from "../simulation/spawners.js"; |
| 69 | |
| 70 | export function chebyshev (ax, ay, bx, by) |
| 71 | { |
| 72 | return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); |
| 73 | } |
| 74 | |
| 75 | export function attackProfileOf (ecs, handle) |
| 76 | { |
| 77 | const creature = ecs.get(handle, Component.creature); |
| 78 | const level = creatureLevel(ecs, handle); |
| 79 | const equipment = ecs.get(handle, Component.equipment); |
| 80 | const weapon = equipment?.slots?.weapon; |
| 81 | if (weapon?.itemId != null) |
| 82 | { |
| 83 | const attack = itemDefinition(weapon.itemId)?.equipment?.attack; |
| 84 | if (attack) |
| 85 | { |
| 86 | const profile = { ...attack }; |
| 87 | if (creature) |
| 88 | { profile.mobAttackSkill = level; } |
| 89 | return profile; |
| 90 | } |
| 91 | } |
| 92 | if (creature) |
| 93 | { |
| 94 | const def = mobDefinition(creature.mobTypeId); |
| 95 | if (mobCanFightType(creature.mobTypeId)) |
| 96 | { return mobMeleeAttackProfile(def, level); } |
| 97 | } |
| 98 | return { ...UNARMED_ATTACK }; |
| 99 | } |
| 100 | |
| 101 | function creatureLevel (ecs, handle) |
| 102 | { |
| 103 | const creature = ecs.get(handle, Component.creature); |
| 104 | if (!creature) |
| 105 | { return 1; } |
| 106 | if (creature.level != null) |
| 107 | { return Math.max(1, creature.level | 0 || 1); } |
| 108 | const origin = ecs.get(handle, Component.spawnOrigin); |
| 109 | if (origin?.level != null) |
| 110 | { return Math.max(1, origin.level | 0 || 1); } |
| 111 | const def = mobDefinition(creature.mobTypeId); |
| 112 | return Math.max(1, def?.attackSkill | 0 || 1); |
| 113 | } |
| 114 | |
| 115 | export function weaponEquipmentKind (ecs, handle) |
| 116 | { |
| 117 | const equipment = ecs.get(handle, Component.equipment); |
| 118 | const weapon = equipment?.slots?.weapon; |
| 119 | if (!weapon?.itemId) |
| 120 | { return null; } |
| 121 | return itemDefinition(weapon.itemId)?.equipment?.kind ?? null; |
| 122 | } |
| 123 | |
| 124 | export function ensureMobCombat (ecs, entityId) |
| 125 | { |
| 126 | const handle = ecs.handleOf(entityId); |
| 127 | if (handle == null) |
| 128 | { return false; } |
| 129 | const creature = ecs.get(handle, Component.creature); |
| 130 | if (!creature || !mobCanFightType(creature.mobTypeId)) |
| 131 | { return false; } |
| 132 | const def = mobDefinition(creature.mobTypeId); |
| 133 | const level = creatureLevel(ecs, handle); |
| 134 | if (!ecs.get(handle, Component.combat)) |
| 135 | { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } |
| 136 | if (!ecs.get(handle, Component.skills)) |
| 137 | { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); } |
| 138 | return true; |
| 139 | } |
| 140 | |
| 141 | function attackerSkillLevel (skills, profile, skillId) |
| 142 | { |
| 143 | if (profile.mobAttackSkill != null) |
| 144 | { return profile.mobAttackSkill; } |
| 145 | return skillLevel(skills, skillId); |
| 146 | } |
| 147 | |
| 148 | function defenderSkillLevel (skills, skillId, equipment = null, settings = null) |
| 149 | { |
| 150 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 151 | return effectiveSkillLevel(skills, skillId, bonuses); |
| 152 | } |
| 153 | |
| 154 | function playerCombatLevels (ecs, handle, profile, settings = null) |
| 155 | { |
| 156 | const skills = ecs.get(handle, Component.skills); |
| 157 | const equipment = ecs.get(handle, Component.equipment); |
| 158 | const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); |
| 159 | const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); |
| 160 | bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); |
| 161 | bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); |
| 162 | |
| 163 | return { |
| 164 | hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses), |
| 165 | damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses), |
| 166 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 167 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 168 | }; |
| 169 | } |
| 170 | |
| 171 | export function isUntargetable (ecs, handle) |
| 172 | { |
| 173 | if (ecs.has(handle, Component.dead)) |
| 174 | { return true; } |
| 175 | const creature = ecs.get(handle, Component.creature); |
| 176 | if (!creature) |
| 177 | { return false; } |
| 178 | return !!mobDefinition(creature.mobTypeId)?.untargetable; |
| 179 | } |
| 180 | |
| 181 | /** Stop active combat / cast / path activity when a player dies. |
| 182 | * Auto-cast preference is kept so respawn + re-cast can resume repeating. */ |
| 183 | export function silenceDeadPlayer (ecs, handle) |
| 184 | { |
| 185 | if (handle == null) |
| 186 | { return; } |
| 187 | const entityId = ecs.entityIdOf(handle); |
| 188 | if (entityId != null) |
| 189 | { clearEngage(ecs, entityId); } |
| 190 | const path = ecs.get(handle, Component.path); |
| 191 | if (path) |
| 192 | { path.tiles = []; } |
| 193 | const follow = ecs.get(handle, Component.follow); |
| 194 | if (follow) |
| 195 | { |
| 196 | follow.targetEntityId = null; |
| 197 | follow.trail = []; |
| 198 | } |
| 199 | const casting = ecs.get(handle, Component.spellcasting); |
| 200 | if (casting) |
| 201 | { |
| 202 | casting.armedSpellId = null; |
| 203 | casting.repeatSpellId = null; |
| 204 | casting.repeatTargetEntityId = null; |
| 205 | casting.repeatTileX = null; |
| 206 | casting.repeatTileY = null; |
| 207 | casting.pendingCast = null; |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | export function engageTarget (ecs, attackerId, targetId, now = Date.now()) |
| 212 | { |
| 213 | const handle = ecs.handleOf(attackerId); |
| 214 | if (handle == null) |
| 215 | { return false; } |
| 216 | if (ecs.has(handle, Component.dead)) |
| 217 | { return false; } |
| 218 | const targetHandle = ecs.handleOf(targetId); |
| 219 | if (targetHandle != null && ecs.has(targetHandle, Component.dead)) |
| 220 | { return false; } |
| 221 | // Spell auto-cast / pending cast is already the active combat form. |
| 222 | if (isSpellCombatBusy(ecs, handle)) |
| 223 | { return false; } |
| 224 | let combat = ecs.get(handle, Component.combat); |
| 225 | if (!combat) |
| 226 | { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } |
| 227 | const targetChanged = combat.targetEntityId !== targetId; |
| 228 | combat.targetEntityId = targetId; |
| 229 | if (targetChanged) |
| 230 | { |
| 231 | // New engage (or switch): allow an immediate swing; keep cadence if already on this target. |
| 232 | combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now); |
| 233 | const path = ecs.get(handle, Component.path); |
| 234 | if (path) |
| 235 | { path.tiles = []; } |
| 236 | } |
| 237 | return true; |
| 238 | } |
| 239 | |
| 240 | /** Melee mobs shot by player ranged/spells prefer cover while closing. */ |
| 241 | export function markSeekCover (ecs, entityId) |
| 242 | { |
| 243 | const handle = ecs.handleOf(entityId); |
| 244 | const combat = handle != null ? ecs.get(handle, Component.combat) : null; |
| 245 | if (combat) |
| 246 | { combat.seekCover = true; } |
| 247 | } |
| 248 | |
| 249 | /** |
| 250 | * Flee-on-hit mobs (fairies) path away from the hit source until far enough, |
| 251 | * then stop fleeing until the next successful hit. |
| 252 | */ |
| 253 | export function markFleeOnHit (world, targetId, attackerId) |
| 254 | { |
| 255 | const ecs = world.ecs; |
| 256 | const targetHandle = ecs.handleOf(targetId); |
| 257 | if (targetHandle == null) |
| 258 | { return; } |
| 259 | const creature = ecs.get(targetHandle, Component.creature); |
| 260 | if (!creature || ecs.get(targetHandle, Component.character)) |
| 261 | { return; } |
| 262 | const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0; |
| 263 | if (fleeDist <= 0) |
| 264 | { return; } |
| 265 | if (!ensureMobCombat(ecs, targetId)) |
| 266 | { return; } |
| 267 | const combat = ecs.get(targetHandle, Component.combat); |
| 268 | const targetPos = ecs.get(targetHandle, Component.position); |
| 269 | const attackerHandle = ecs.handleOf(attackerId); |
| 270 | const attackerPos = attackerHandle != null ? ecs.get(attackerHandle, Component.position) : null; |
| 271 | if (!combat || !targetPos || !attackerPos) |
| 272 | { return; } |
| 273 | if (chebyshev(targetPos.tileX, targetPos.tileY, attackerPos.tileX, attackerPos.tileY) >= fleeDist) |
| 274 | { |
| 275 | combat.fleeFrom = null; |
| 276 | return; |
| 277 | } |
| 278 | combat.fleeFrom = { |
| 279 | tileX: attackerPos.tileX, |
| 280 | tileY: attackerPos.tileY, |
| 281 | minDist: fleeDist |
| 282 | }; |
| 283 | const path = ecs.get(targetHandle, Component.path); |
| 284 | if (path) |
| 285 | { path.tiles = []; } |
| 286 | } |
| 287 | |
| 288 | /** Pending cast or entity-spell auto-repeat — physical combat must not run. */ |
| 289 | export function isSpellCombatBusy (ecs, handle) |
| 290 | { |
| 291 | const casting = ecs.get(handle, Component.spellcasting); |
| 292 | if (!casting) |
| 293 | { return false; } |
| 294 | if (casting.pendingCast) |
| 295 | { return true; } |
| 296 | const spells = ecs.get(handle, Component.spells); |
| 297 | if (!spells?.autoCast || !casting.repeatSpellId) |
| 298 | { return false; } |
| 299 | const def = spellDefinition(casting.repeatSpellId); |
| 300 | return def?.target === "entity"; |
| 301 | } |
| 302 | |
| 303 | function clearSpellCombatState (ecs, handle) |
| 304 | { |
| 305 | const casting = ecs.get(handle, Component.spellcasting); |
| 306 | if (!casting) |
| 307 | { return; } |
| 308 | casting.repeatSpellId = null; |
| 309 | casting.repeatTargetEntityId = null; |
| 310 | casting.repeatTileX = null; |
| 311 | casting.repeatTileY = null; |
| 312 | casting.pendingCast = null; |
| 313 | } |
| 314 | |
| 315 | export function clearEngage (ecs, entityId) |
| 316 | { |
| 317 | const handle = ecs.handleOf(entityId); |
| 318 | const combat = handle != null ? ecs.get(handle, Component.combat) : null; |
| 319 | if (combat) |
| 320 | { |
| 321 | combat.targetEntityId = null; |
| 322 | combat.seekCover = false; |
| 323 | combat.fleeFrom = null; |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | export function hasCombatLineOfSight (world, fromX, fromY, toX, toY) |
| 328 | { |
| 329 | const isClear = world.isClearForRangedAttack |
| 330 | ? (x, y) => world.isClearForRangedAttack(x, y) |
| 331 | : (x, y) => world.isEnterable(x, y); |
| 332 | return rayReaches(fromX, fromY, toX, toY, isClear); |
| 333 | } |
| 334 | |
| 335 | function lightOcclusionAtWorld (world, x, y) |
| 336 | { |
| 337 | const data = world.chunkData?.(tileToChunk(x), tileToChunk(y)); |
| 338 | if (!data) |
| 339 | { return LightOcclusion.clear; } |
| 340 | const index = tileIndexLocal(x, y); |
| 341 | if (Array.isArray(data.occlusion) && data.occlusion.length > index) |
| 342 | { return data.occlusion[index] | 0; } |
| 343 | const localX = ((x % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 344 | const localY = ((y % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 345 | return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY); |
| 346 | } |
| 347 | |
| 348 | /** Target-tile lighting 0–1 (baked + entity/spell lights − spell dark + time of day). */ |
| 349 | export function tileLightAt (world, tileX, tileY, now = Date.now()) |
| 350 | { |
| 351 | const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY)); |
| 352 | const index = tileIndexLocal(tileX, tileY); |
| 353 | const baked = bakedTileLight01(data?.light, index); |
| 354 | const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now); |
| 355 | const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now); |
| 356 | const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y); |
| 357 | const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt); |
| 358 | const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt); |
| 359 | const worldTime = world.worldTime?.(now); |
| 360 | return tileCombatLight01({ |
| 361 | bakedLight01: baked, |
| 362 | entityLight01: entity, |
| 363 | spellLight01: spellLight, |
| 364 | spellDark01: spellDark, |
| 365 | worldHour: worldTime?.hour ?? 12, |
| 366 | nightDarkness: world.settings?.nightDarkness ?? 0.72 |
| 367 | }); |
| 368 | } |
| 369 | |
| 370 | function arrowStackInOffhand (equipment) |
| 371 | { |
| 372 | const stack = equipment?.slots?.offhand; |
| 373 | if (!stack) |
| 374 | { return null; } |
| 375 | const def = itemDefinition(stack.itemId); |
| 376 | if (def?.equipment?.kind !== EquipmentKind.arrowAmmo) |
| 377 | { return null; } |
| 378 | return stack; |
| 379 | } |
| 380 | |
| 381 | /** Physical attack type, or tipped-arrow element for ranged shots. */ |
| 382 | function resolveAttackDamageType (ecs, attackerHandle, profile) |
| 383 | { |
| 384 | if (attackerHandle != null && profile?.mode === "ranged") |
| 385 | { |
| 386 | const stack = arrowStackInOffhand(ecs.get(attackerHandle, Component.equipment)); |
| 387 | if (stack?.instance?.kind === "tipped-arrow" && stack.instance.element) |
| 388 | { return stack.instance.element; } |
| 389 | } |
| 390 | return profile?.attackType ?? AttackType.blunt; |
| 391 | } |
| 392 | |
| 393 | function consumeArrow (ecs, handle) |
| 394 | { |
| 395 | const equipment = ecs.get(handle, Component.equipment); |
| 396 | const stack = arrowStackInOffhand(equipment); |
| 397 | if (!stack || stackQuantity(stack.quantity) <= 0) |
| 398 | { return false; } |
| 399 | if (stackQuantity(stack.quantity) <= 1) |
| 400 | { equipment.slots.offhand = null; } |
| 401 | else |
| 402 | { stack.quantity = stackQuantity(stack.quantity) - 1; } |
| 403 | return true; |
| 404 | } |
| 405 | |
| 406 | /** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */ |
| 407 | function rollDropQuantity (drop) |
| 408 | { |
| 409 | if (drop.quantityMin != null || drop.quantityMax != null) |
| 410 | { |
| 411 | const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1))); |
| 412 | const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min))); |
| 413 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 414 | } |
| 415 | return Math.max(1, Math.floor(Number(drop.quantity ?? 1))); |
| 416 | } |
| 417 | |
| 418 | function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null) |
| 419 | { |
| 420 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 421 | if (!creature) |
| 422 | { return []; } |
| 423 | // Summons (e.g. Shade spell) never drop loot — only wild / spawner mobs. |
| 424 | if (world.ecs.get(targetHandle, Component.summon)) |
| 425 | { return []; } |
| 426 | const def = mobDefinition(creature.mobTypeId); |
| 427 | const mobName = entityCombatDisplayName(world.ecs, targetHandle) |
| 428 | || def?.displayName |
| 429 | || "a creature"; |
| 430 | let killerName = "someone"; |
| 431 | if (attackerId != null) |
| 432 | { |
| 433 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 434 | if (attackerHandle != null) |
| 435 | { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; } |
| 436 | } |
| 437 | const origin = lootOrigin(mobName, killerName); |
| 438 | const events = []; |
| 439 | const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin); |
| 440 | const dropTable = [ |
| 441 | ...(def?.drops ?? []), |
| 442 | ...(Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : []) |
| 443 | ]; |
| 444 | if (creature.element && (def?.essenceDropChance ?? 0) > 0) |
| 445 | { |
| 446 | const essenceId = essenceItemIdForElement(creature.element); |
| 447 | if (essenceId) |
| 448 | { dropTable.push({ itemId: essenceId, chance: def.essenceDropChance }); } |
| 449 | } |
| 450 | for (const drop of dropTable) |
| 451 | { |
| 452 | if (Math.random() > (drop.chance ?? 1)) |
| 453 | { continue; } |
| 454 | const quantity = rollDropQuantity(drop); |
| 455 | if (quantity <= 0) |
| 456 | { continue; } |
| 457 | const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); |
| 458 | const stack = attachOrigins({ |
| 459 | itemId: drop.itemId, |
| 460 | quantity, |
| 461 | origins: [{ origin, quantity }] |
| 462 | }); |
| 463 | const item = { |
| 464 | groundItemId, |
| 465 | tileX, |
| 466 | tileY, |
| 467 | stack, |
| 468 | droppedAt: now, |
| 469 | expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), |
| 470 | source: "mob-drop" |
| 471 | }; |
| 472 | addGroundItem(world, item); |
| 473 | events.push({ |
| 474 | type: "ground-item-appear", |
| 475 | ...publicGroundItem(item), |
| 476 | stack: item.stack, |
| 477 | droppedAt: item.droppedAt, |
| 478 | source: item.source, |
| 479 | expiresAt: item.expiresAt |
| 480 | }); |
| 481 | } |
| 482 | return events; |
| 483 | } |
| 484 | |
| 485 | function entityCombatDisplayName (ecs, handle) |
| 486 | { |
| 487 | const appearance = ecs.get(handle, Component.appearance); |
| 488 | const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); |
| 489 | if (fromAppearance) |
| 490 | { return fromAppearance; } |
| 491 | const creature = ecs.get(handle, Component.creature); |
| 492 | if (creature?.mobTypeId) |
| 493 | { |
| 494 | const def = mobDefinition(creature.mobTypeId); |
| 495 | if (def?.displayName) |
| 496 | { return def.displayName; } |
| 497 | } |
| 498 | return null; |
| 499 | } |
| 500 | |
| 501 | function projectileDualTintFromAttacker (ecs, handle) |
| 502 | { |
| 503 | const equipment = ecs.get(handle, Component.equipment); |
| 504 | const stack = arrowStackInOffhand(equipment); |
| 505 | if (!stack) |
| 506 | { return null; } |
| 507 | return resolveItemDualTint(stack, itemDefinition(stack.itemId)); |
| 508 | } |
| 509 | |
| 510 | function projectileSpriteFromAttacker (ecs, handle) |
| 511 | { |
| 512 | const equipment = ecs.get(handle, Component.equipment); |
| 513 | const stack = arrowStackInOffhand(equipment); |
| 514 | if (stack?.instance?.kind === "tipped-arrow") |
| 515 | { return "fx:projectile:arrow-tipped"; } |
| 516 | return "fx:projectile:arrow"; |
| 517 | } |
| 518 | |
| 519 | function publicDualTint (dualTint) |
| 520 | { |
| 521 | if (!dualTint) |
| 522 | { return null; } |
| 523 | return { |
| 524 | shaftTint: dualTint.shaft, |
| 525 | tipTint: dualTint.tip, |
| 526 | ...(dualTint.coat ? { coatTint: dualTint.coat } : {}) |
| 527 | }; |
| 528 | } |
| 529 | |
| 530 | function missProjectileTile (targetTileX, targetTileY, rng = Math.random) |
| 531 | { |
| 532 | const angle = rng() * Math.PI * 2; |
| 533 | const dist = rng(); |
| 534 | return { |
| 535 | tileX: Math.round(targetTileX + Math.cos(angle) * dist), |
| 536 | tileY: Math.round(targetTileY + Math.sin(angle) * dist) |
| 537 | }; |
| 538 | } |
| 539 | |
| 540 | /** |
| 541 | * Aggressive mobs auto-engage the nearest player or town guard within aggro range |
| 542 | * when they have line of sight. Town guards auto-engage aggressive creatures. |
| 543 | * Does nothing while already engaged. |
| 544 | */ |
| 545 | export function stepAggression (world, now = Date.now()) |
| 546 | { |
| 547 | for (const entity of world.ecs.query(Component.creature, Component.position)) |
| 548 | { |
| 549 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 550 | { continue; } |
| 551 | const def = mobDefinition(entity.creature.mobTypeId); |
| 552 | if (world.ecs.get(entity.handle, Component.summon)) |
| 553 | { continue; } |
| 554 | const origin = world.ecs.get(entity.handle, Component.spawnOrigin); |
| 555 | const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId); |
| 556 | const aggressive = origin |
| 557 | ? !!origin.aggressive |
| 558 | : mobIsAggressive(def); |
| 559 | if ((!aggressive && !townGuard) || !mobCanFight(def)) |
| 560 | { continue; } |
| 561 | if (world.ecs.has(entity.handle, Component.dead)) |
| 562 | { continue; } |
| 563 | const health = world.ecs.get(entity.handle, Component.health); |
| 564 | if (health && health.current <= 0) |
| 565 | { continue; } |
| 566 | const combat = world.ecs.get(entity.handle, Component.combat); |
| 567 | if (combat?.targetEntityId != null) |
| 568 | { continue; } |
| 569 | |
| 570 | const range = mobAggroRangeTiles(def); |
| 571 | const bestId = townGuard |
| 572 | ? pickAggressionTargetAggressiveMob(world, entity, range) |
| 573 | : pickAggressionTargetPlayerOrGuard(world, entity, range, now); |
| 574 | if (bestId == null) |
| 575 | { continue; } |
| 576 | if (!ensureMobCombat(world.ecs, entity.entityId)) |
| 577 | { continue; } |
| 578 | engageTarget(world.ecs, entity.entityId, bestId, now); |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | function creatureIsAggressiveHostile (world, handle, creature) |
| 583 | { |
| 584 | if (!creature || world.ecs.get(handle, Component.character)) |
| 585 | { return false; } |
| 586 | if (world.ecs.get(handle, Component.summon)) |
| 587 | { return false; } |
| 588 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 589 | if (origin?.townGuard || isTownGuardMob(creature.mobTypeId)) |
| 590 | { return false; } |
| 591 | if (origin) |
| 592 | { return !!origin.aggressive; } |
| 593 | return mobIsAggressive(mobDefinition(creature.mobTypeId)); |
| 594 | } |
| 595 | |
| 596 | function entityIsTownGuard (world, handle, creature) |
| 597 | { |
| 598 | if (!creature || world.ecs.get(handle, Component.character)) |
| 599 | { return false; } |
| 600 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 601 | return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId); |
| 602 | } |
| 603 | |
| 604 | /** Nearest living player or town guard in range with LOS. */ |
| 605 | function pickAggressionTargetPlayerOrGuard (world, entity, range, now = Date.now()) |
| 606 | { |
| 607 | let bestId = null; |
| 608 | let bestDist = Infinity; |
| 609 | for (const player of world.ecs.query(Component.character, Component.position)) |
| 610 | { |
| 611 | if (playerIgnoresAggressiveMob(world, entity, player.handle, now)) |
| 612 | { continue; } |
| 613 | const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range); |
| 614 | if (dist != null && dist < bestDist) |
| 615 | { |
| 616 | bestDist = dist; |
| 617 | bestId = player.entityId; |
| 618 | } |
| 619 | } |
| 620 | for (const other of world.ecs.query(Component.creature, Component.position)) |
| 621 | { |
| 622 | if (other.entityId === entity.entityId) |
| 623 | { continue; } |
| 624 | if (!entityIsTownGuard(world, other.handle, other.creature)) |
| 625 | { continue; } |
| 626 | const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); |
| 627 | if (dist != null && dist < bestDist) |
| 628 | { |
| 629 | bestDist = dist; |
| 630 | bestId = other.entityId; |
| 631 | } |
| 632 | } |
| 633 | return bestId; |
| 634 | } |
| 635 | |
| 636 | /** Non-boss aggressive mobs skip players who outlevel them or have chunk peace. */ |
| 637 | function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now) |
| 638 | { |
| 639 | const def = mobDefinition(mobEntity.creature.mobTypeId); |
| 640 | if (mobIsBoss(def)) |
| 641 | { return false; } |
| 642 | const skills = world.ecs.get(playerHandle, Component.skills); |
| 643 | if (!skills) |
| 644 | { return false; } |
| 645 | const playerLevel = combatLevelFromSkills(skills); |
| 646 | const origin = world.ecs.get(mobEntity.handle, Component.spawnOrigin); |
| 647 | const mobLevel = mobAggressionLevel(mobEntity.creature, origin, def); |
| 648 | if (playerOutlevelsMobAggression(playerLevel, mobLevel)) |
| 649 | { return true; } |
| 650 | const presence = world.ecs.get(playerHandle, Component.chunkPresence); |
| 651 | const pos = world.ecs.get(playerHandle, Component.position); |
| 652 | if (!presence || !pos) |
| 653 | { return false; } |
| 654 | return chunkPeaceAggressionImmunity( |
| 655 | presence, |
| 656 | pos.tileX, |
| 657 | pos.tileY, |
| 658 | pos.dimensionId ?? OVERWORLD_ID, |
| 659 | now, |
| 660 | tileToChunk |
| 661 | ); |
| 662 | } |
| 663 | |
| 664 | /** Nearest aggressive hostile creature in range with LOS (for town guards). */ |
| 665 | function pickAggressionTargetAggressiveMob (world, entity, range) |
| 666 | { |
| 667 | let bestId = null; |
| 668 | let bestDist = Infinity; |
| 669 | for (const other of world.ecs.query(Component.creature, Component.position)) |
| 670 | { |
| 671 | if (other.entityId === entity.entityId) |
| 672 | { continue; } |
| 673 | if (!creatureIsAggressiveHostile(world, other.handle, other.creature)) |
| 674 | { continue; } |
| 675 | if (!mobCanFight(mobDefinition(other.creature.mobTypeId))) |
| 676 | { continue; } |
| 677 | const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); |
| 678 | if (dist != null && dist < bestDist) |
| 679 | { |
| 680 | bestDist = dist; |
| 681 | bestId = other.entityId; |
| 682 | } |
| 683 | } |
| 684 | return bestId; |
| 685 | } |
| 686 | |
| 687 | /** |
| 688 | * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null. |
| 689 | */ |
| 690 | function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range) |
| 691 | { |
| 692 | if (world.ecs.has(targetHandle, Component.dead)) |
| 693 | { return null; } |
| 694 | const health = world.ecs.get(targetHandle, Component.health); |
| 695 | if (health && health.current <= 0) |
| 696 | { return null; } |
| 697 | const dist = chebyshev( |
| 698 | attacker.position.tileX, |
| 699 | attacker.position.tileY, |
| 700 | targetPos.tileX, |
| 701 | targetPos.tileY |
| 702 | ); |
| 703 | if (dist < 1 || dist > range) |
| 704 | { return null; } |
| 705 | let effectiveDist = dist; |
| 706 | if (dist > 1) |
| 707 | { |
| 708 | const light = tileLightAt(world, targetPos.tileX, targetPos.tileY); |
| 709 | effectiveDist = dist * aggroDistanceMultiplier(light); |
| 710 | } |
| 711 | if (effectiveDist > range) |
| 712 | { return null; } |
| 713 | if (!hasCombatLineOfSight( |
| 714 | world, |
| 715 | attacker.position.tileX, |
| 716 | attacker.position.tileY, |
| 717 | targetPos.tileX, |
| 718 | targetPos.tileY |
| 719 | )) |
| 720 | { return null; } |
| 721 | return dist; |
| 722 | } |
| 723 | |
| 724 | /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */ |
| 725 | export function resolveCombatTarget (world, targetId) |
| 726 | { |
| 727 | const handle = world.ecs.handleOf(targetId); |
| 728 | if (handle != null) |
| 729 | { |
| 730 | const pos = world.ecs.get(handle, Component.position); |
| 731 | if (!pos) |
| 732 | { return null; } |
| 733 | if (isUntargetable(world.ecs, handle)) |
| 734 | { return null; } |
| 735 | return { |
| 736 | local: true, |
| 737 | handle, |
| 738 | pos, |
| 739 | health: world.ecs.get(handle, Component.health) |
| 740 | }; |
| 741 | } |
| 742 | const ghost = world.ghosts?.get?.(targetId); |
| 743 | if (!ghost || ghost.untargetable) |
| 744 | { return null; } |
| 745 | const health = ghost.health != null |
| 746 | ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health } |
| 747 | : null; |
| 748 | return { |
| 749 | local: false, |
| 750 | handle: null, |
| 751 | pos: { tileX: ghost.tileX, tileY: ghost.tileY }, |
| 752 | health |
| 753 | }; |
| 754 | } |
| 755 | |
| 756 | function attackerCombatLevels (ecs, attackerHandle, profile, settings = null) |
| 757 | { |
| 758 | const attackerCharacter = ecs.get(attackerHandle, Component.character); |
| 759 | if (attackerCharacter) |
| 760 | { return playerCombatLevels(ecs, attackerHandle, profile, settings); } |
| 761 | const skills = ecs.get(attackerHandle, Component.skills); |
| 762 | const equipment = ecs.get(attackerHandle, Component.equipment); |
| 763 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 764 | const hitSkillId = profile.hitSkillId ?? SkillId.unarmed; |
| 765 | const damageSkillId = profile.damageSkillId ?? SkillId.strength; |
| 766 | const baseHit = attackerSkillLevel(skills, profile, hitSkillId); |
| 767 | const baseDamage = attackerSkillLevel(skills, profile, damageSkillId); |
| 768 | return { |
| 769 | hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)), |
| 770 | damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)), |
| 771 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 772 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 773 | }; |
| 774 | } |
| 775 | |
| 776 | export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20) |
| 777 | { |
| 778 | const events = []; |
| 779 | for (const entity of world.ecs.query(Component.health, Component.position)) |
| 780 | { |
| 781 | const { handle, entityId, health, position, character } = entity; |
| 782 | if (world.ecs.has(handle, Component.dead)) |
| 783 | { continue; } |
| 784 | if (!world.chunkIsSimulating?.(position.tileX, position.tileY)) |
| 785 | { continue; } |
| 786 | if ((health.current | 0) >= (health.max | 0)) |
| 787 | { continue; } |
| 788 | const lastDamageAt = health.lastDamageAt ?? 0; |
| 789 | if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS) |
| 790 | { continue; } |
| 791 | const beforeInt = health.current | 0; |
| 792 | health.current = Math.min( |
| 793 | health.max | 0, |
| 794 | (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * dt |
| 795 | ); |
| 796 | if ((health.current | 0) === beforeInt) |
| 797 | { continue; } |
| 798 | if (character) |
| 799 | { syncPlayerHealth(world.ecs, handle); } |
| 800 | const view = publicEntityView(world.ecs, entityId); |
| 801 | if (!view) |
| 802 | { continue; } |
| 803 | events.push({ |
| 804 | type: "entity-health", |
| 805 | entityId, |
| 806 | ...(character ? { characterId: character.characterId } : {}), |
| 807 | health: view.health, |
| 808 | maxHealth: view.maxHealth, |
| 809 | tileX: view.tileX, |
| 810 | tileY: view.tileY |
| 811 | }); |
| 812 | } |
| 813 | return events; |
| 814 | } |
| 815 | |
| 816 | export function stepCombat (world, now = Date.now()) |
| 817 | { |
| 818 | const events = []; |
| 819 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 820 | { |
| 821 | if (world.ecs.has(entity.handle, Component.dead)) |
| 822 | { |
| 823 | entity.combat.targetEntityId = null; |
| 824 | continue; |
| 825 | } |
| 826 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 827 | { continue; } |
| 828 | const combat = entity.combat; |
| 829 | const targetId = combat.targetEntityId; |
| 830 | if (targetId == null) |
| 831 | { continue; } |
| 832 | const target = resolveCombatTarget(world, targetId); |
| 833 | if (!target) |
| 834 | { |
| 835 | combat.targetEntityId = null; |
| 836 | continue; |
| 837 | } |
| 838 | if (target.health && target.health.current <= 0) |
| 839 | { |
| 840 | combat.targetEntityId = null; |
| 841 | continue; |
| 842 | } |
| 843 | |
| 844 | // One combat form at a time: spell cast / auto-cast wins over melee & archery. |
| 845 | if (isSpellCombatBusy(world.ecs, entity.handle)) |
| 846 | { continue; } |
| 847 | |
| 848 | if (combat.fleeFrom) |
| 849 | { |
| 850 | const flee = combat.fleeFrom; |
| 851 | const minDist = Math.max(1, flee.minDist | 0 || 2); |
| 852 | const fleeDist = chebyshev( |
| 853 | entity.position.tileX, |
| 854 | entity.position.tileY, |
| 855 | flee.tileX, |
| 856 | flee.tileY |
| 857 | ); |
| 858 | if (fleeDist >= minDist) |
| 859 | { |
| 860 | combat.fleeFrom = null; |
| 861 | clearCombatApproachPath(world.ecs, entity.handle); |
| 862 | } |
| 863 | else |
| 864 | { |
| 865 | queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist); |
| 866 | continue; |
| 867 | } |
| 868 | } |
| 869 | |
| 870 | const profile = attackProfileOf(world.ecs, entity.handle); |
| 871 | const targetPos = target.pos; |
| 872 | const isCreature = !!world.ecs.get(entity.handle, Component.creature) |
| 873 | && !world.ecs.get(entity.handle, Component.character); |
| 874 | |
| 875 | if (profile.mode === "ranged") |
| 876 | { |
| 877 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 878 | const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES; |
| 879 | const equipment = world.ecs.get(entity.handle, Component.equipment); |
| 880 | const hasArrows = isCreature |
| 881 | || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0); |
| 882 | const inRange = dist >= 1 && dist <= maxRange |
| 883 | && hasCombatLineOfSight( |
| 884 | world, |
| 885 | entity.position.tileX, |
| 886 | entity.position.tileY, |
| 887 | targetPos.tileX, |
| 888 | targetPos.tileY |
| 889 | ); |
| 890 | if (!inRange || !hasArrows) |
| 891 | { |
| 892 | if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0) |
| 893 | && world.ecs.get(entity.handle, Component.character)) |
| 894 | { |
| 895 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 896 | events.push({ |
| 897 | type: "combat-no-arrows", |
| 898 | attackerId: entity.entityId, |
| 899 | sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null |
| 900 | }); |
| 901 | } |
| 902 | queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange); |
| 903 | continue; |
| 904 | } |
| 905 | clearCombatApproachPath(world.ecs, entity.handle); |
| 906 | if (now < (combat.nextSwingAt || 0)) |
| 907 | { continue; } |
| 908 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 909 | clearSpellCombatState(world.ecs, entity.handle); |
| 910 | events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); |
| 911 | continue; |
| 912 | } |
| 913 | |
| 914 | if (profile.mode !== "melee") |
| 915 | { continue; } |
| 916 | |
| 917 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 918 | const canSwing = dist === 1 |
| 919 | && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); |
| 920 | const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; |
| 921 | const preferSpell = isCreature |
| 922 | && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack; |
| 923 | const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell); |
| 924 | |
| 925 | if (shouldCast) |
| 926 | { |
| 927 | const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES |
| 928 | && hasCombatLineOfSight( |
| 929 | world, |
| 930 | entity.position.tileX, |
| 931 | entity.position.tileY, |
| 932 | targetPos.tileX, |
| 933 | targetPos.tileY |
| 934 | ); |
| 935 | if (!inSpellRange) |
| 936 | { |
| 937 | queueStandInRangeApproach( |
| 938 | world, |
| 939 | entity.entityId, |
| 940 | entity.handle, |
| 941 | entity.position, |
| 942 | targetPos.tileX, |
| 943 | targetPos.tileY, |
| 944 | COMBAT_RANGE_TILES, |
| 945 | 1 |
| 946 | ); |
| 947 | continue; |
| 948 | } |
| 949 | clearCombatApproachPath(world.ecs, entity.handle); |
| 950 | if (now < (combat.nextSwingAt || 0)) |
| 951 | { continue; } |
| 952 | const picked = pickMobAttackSpell(attackSpells); |
| 953 | if (!picked) |
| 954 | { |
| 955 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 956 | continue; |
| 957 | } |
| 958 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 959 | events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now)); |
| 960 | continue; |
| 961 | } |
| 962 | |
| 963 | if (!canSwing) |
| 964 | { |
| 965 | queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); |
| 966 | continue; |
| 967 | } |
| 968 | clearCombatApproachPath(world.ecs, entity.handle); |
| 969 | const attackerHealth = world.ecs.get(entity.handle, Component.health); |
| 970 | if (attackerHealth && attackerHealth.current <= 0) |
| 971 | { continue; } |
| 972 | if ((combat.nextSwingAt || 0) > now) |
| 973 | { continue; } |
| 974 | |
| 975 | combat.nextSwingAt = now + (profile.cooldownMs || 800); |
| 976 | clearSpellCombatState(world.ecs, entity.handle); |
| 977 | events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); |
| 978 | } |
| 979 | return events; |
| 980 | } |
| 981 | |
| 982 | function eligibleMobAttackSpells (ecs, handle) |
| 983 | { |
| 984 | const spells = ecs.get(handle, Component.spells); |
| 985 | if (!spells?.known?.length) |
| 986 | { return []; } |
| 987 | const level = creatureLevel(ecs, handle); |
| 988 | const chances = spells.castChances ?? {}; |
| 989 | const out = []; |
| 990 | for (const spellId of spells.known) |
| 991 | { |
| 992 | const def = spellDefinition(spellId); |
| 993 | if (!def || def.target !== "entity") |
| 994 | { continue; } |
| 995 | const minLevel = spellMinMagicLevel(def); |
| 996 | if (level < minLevel) |
| 997 | { continue; } |
| 998 | const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0; |
| 999 | if (chance <= 0) |
| 1000 | { continue; } |
| 1001 | out.push({ spellId, chance }); |
| 1002 | } |
| 1003 | return out; |
| 1004 | } |
| 1005 | |
| 1006 | function pickMobAttackSpell (spells) |
| 1007 | { |
| 1008 | if (!spells.length) |
| 1009 | { return null; } |
| 1010 | const pick = spells[Math.floor(Math.random() * spells.length)]; |
| 1011 | if ((Math.random() * 100) >= pick.chance) |
| 1012 | { return null; } |
| 1013 | return pick; |
| 1014 | } |
| 1015 | |
| 1016 | function clearCombatApproachPath (ecs, handle) |
| 1017 | { |
| 1018 | const path = ecs.get(handle, Component.path); |
| 1019 | if (path?.tiles?.length) |
| 1020 | { path.tiles = []; } |
| 1021 | } |
| 1022 | |
| 1023 | function combatTileKey (tileX, tileY) |
| 1024 | { |
| 1025 | return `${tileX},${tileY}`; |
| 1026 | } |
| 1027 | |
| 1028 | /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */ |
| 1029 | function collectCombatAllyReservations (world, entityId, targetEntityId) |
| 1030 | { |
| 1031 | const reserved = new Set(); |
| 1032 | if (targetEntityId == null) |
| 1033 | { return reserved; } |
| 1034 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 1035 | { |
| 1036 | if (entity.entityId === entityId) |
| 1037 | { continue; } |
| 1038 | if (entity.combat.targetEntityId !== targetEntityId) |
| 1039 | { continue; } |
| 1040 | reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); |
| 1041 | const allyPath = world.ecs.get(entity.handle, Component.path); |
| 1042 | if (!allyPath?.tiles?.length) |
| 1043 | { continue; } |
| 1044 | const next = allyPath.tiles[0]; |
| 1045 | if (next) |
| 1046 | { reserved.add(combatTileKey(next.x, next.y)); } |
| 1047 | const dest = allyPath.tiles[allyPath.tiles.length - 1]; |
| 1048 | if (dest) |
| 1049 | { reserved.add(combatTileKey(dest.x, dest.y)); } |
| 1050 | } |
| 1051 | return reserved; |
| 1052 | } |
| 1053 | |
| 1054 | function combatGoalPreference (entityId, tileX, tileY) |
| 1055 | { |
| 1056 | return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0; |
| 1057 | } |
| 1058 | |
| 1059 | /** Cost multiplier for tiles the threat can currently shoot. */ |
| 1060 | const COVER_EXPOSED_STEP_COST = 5; |
| 1061 | |
| 1062 | function mobHasRangedRetaliation (world, handle) |
| 1063 | { |
| 1064 | const profile = attackProfileOf(world.ecs, handle); |
| 1065 | if (profile?.mode === "ranged") |
| 1066 | { return true; } |
| 1067 | return eligibleMobAttackSpells(world.ecs, handle).length > 0; |
| 1068 | } |
| 1069 | |
| 1070 | /** Melee-only creatures closing after a player ranged/spell hit. */ |
| 1071 | function shouldSeekCoverApproach (world, handle) |
| 1072 | { |
| 1073 | if (world.ecs.get(handle, Component.character)) |
| 1074 | { return false; } |
| 1075 | if (!world.ecs.get(handle, Component.creature)) |
| 1076 | { return false; } |
| 1077 | const combat = world.ecs.get(handle, Component.combat); |
| 1078 | if (!combat?.seekCover) |
| 1079 | { return false; } |
| 1080 | return !mobHasRangedRetaliation(world, handle); |
| 1081 | } |
| 1082 | |
| 1083 | function coverStepCost (world, threatPos, goalX, goalY, x, y) |
| 1084 | { |
| 1085 | // Final adjacent step is always in LOS — don't punish the last lunge. |
| 1086 | if (x === goalX && y === goalY) |
| 1087 | { return 1; } |
| 1088 | if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y)) |
| 1089 | { return COVER_EXPOSED_STEP_COST; } |
| 1090 | return 1; |
| 1091 | } |
| 1092 | |
| 1093 | function pathCoverScore (world, threatPos, tiles) |
| 1094 | { |
| 1095 | let score = 0; |
| 1096 | for (const step of tiles) |
| 1097 | { |
| 1098 | score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y) |
| 1099 | ? COVER_EXPOSED_STEP_COST |
| 1100 | : 1; |
| 1101 | } |
| 1102 | return score; |
| 1103 | } |
| 1104 | |
| 1105 | function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved) |
| 1106 | { |
| 1107 | const dirs = [ |
| 1108 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1109 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1110 | ]; |
| 1111 | const goals = []; |
| 1112 | for (const dir of dirs) |
| 1113 | { |
| 1114 | const x = targetPos.tileX + dir.x; |
| 1115 | const y = targetPos.tileY + dir.y; |
| 1116 | const isHere = x === position.tileX && y === position.tileY; |
| 1117 | const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; |
| 1118 | const key = combatTileKey(x, y); |
| 1119 | if (reserved?.has(key) && !(isHere && aloneHere)) |
| 1120 | { continue; } |
| 1121 | const clear = world.isClearStanding?.(entityId, x, y) |
| 1122 | ?? world.walkableFor(entityId, x, y); |
| 1123 | if (!clear && !isHere) |
| 1124 | { continue; } |
| 1125 | if (isHere && !aloneHere) |
| 1126 | { continue; } |
| 1127 | goals.push({ x, y }); |
| 1128 | } |
| 1129 | return goals; |
| 1130 | } |
| 1131 | |
| 1132 | function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved) |
| 1133 | { |
| 1134 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1135 | const preferVertical = !!world.ecs.get(handle, Component.character); |
| 1136 | const isWalkable = (x, y, goal) => |
| 1137 | { |
| 1138 | if (x === goal.x && y === goal.y) |
| 1139 | { |
| 1140 | return world.isClearStanding?.(entityId, x, y) |
| 1141 | ?? world.walkableFor(entityId, x, y); |
| 1142 | } |
| 1143 | return world.walkableFor(entityId, x, y); |
| 1144 | }; |
| 1145 | let bestTiles = null; |
| 1146 | let bestScore = Infinity; |
| 1147 | let bestPref = Infinity; |
| 1148 | for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved)) |
| 1149 | { |
| 1150 | if (goal.x === position.tileX && goal.y === position.tileY) |
| 1151 | { return []; } |
| 1152 | const tiles = findPath( |
| 1153 | position.tileX, |
| 1154 | position.tileY, |
| 1155 | goal.x, |
| 1156 | goal.y, |
| 1157 | (x, y) => isWalkable(x, y, goal), |
| 1158 | bounds.minX, |
| 1159 | bounds.minY, |
| 1160 | bounds.maxX, |
| 1161 | bounds.maxY, |
| 1162 | { |
| 1163 | preferVertical, |
| 1164 | stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y) |
| 1165 | } |
| 1166 | ); |
| 1167 | if (!tiles.length) |
| 1168 | { continue; } |
| 1169 | const score = pathCoverScore(world, targetPos, tiles); |
| 1170 | const pref = combatGoalPreference(entityId, goal.x, goal.y); |
| 1171 | if (score < bestScore || (score === bestScore && pref < bestPref)) |
| 1172 | { |
| 1173 | bestScore = score; |
| 1174 | bestPref = pref; |
| 1175 | bestTiles = tiles; |
| 1176 | } |
| 1177 | } |
| 1178 | return bestTiles; |
| 1179 | } |
| 1180 | |
| 1181 | /** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */ |
| 1182 | function queueFleeToCover (world, entityId, handle, position, threatPos) |
| 1183 | { |
| 1184 | let path = world.ecs.get(handle, Component.path); |
| 1185 | if (!path) |
| 1186 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1187 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1188 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 1189 | const isGoal = (x, y) => |
| 1190 | { |
| 1191 | if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) |
| 1192 | { return false; } |
| 1193 | if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1) |
| 1194 | { return false; } |
| 1195 | return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y); |
| 1196 | }; |
| 1197 | if (isGoal(position.tileX, position.tileY)) |
| 1198 | { |
| 1199 | path.tiles = []; |
| 1200 | return; |
| 1201 | } |
| 1202 | const tiles = findPathToNearestGoal( |
| 1203 | position.tileX, |
| 1204 | position.tileY, |
| 1205 | isGoal, |
| 1206 | isWalkable, |
| 1207 | bounds.minX, |
| 1208 | bounds.minY, |
| 1209 | bounds.maxX, |
| 1210 | bounds.maxY |
| 1211 | ); |
| 1212 | if (!tiles.length) |
| 1213 | { |
| 1214 | path.tiles = []; |
| 1215 | return; |
| 1216 | } |
| 1217 | path.tiles = tiles; |
| 1218 | const movement = world.ecs.get(handle, Component.movement); |
| 1219 | if (movement) |
| 1220 | { movement.walkCarry = 0; } |
| 1221 | } |
| 1222 | |
| 1223 | /** Path to the nearest standable tile at least `minDist` from the hit source. */ |
| 1224 | function queueFleeFromHitSource (world, entityId, handle, position, source, minDist) |
| 1225 | { |
| 1226 | if (world.frozen?.has?.(entityId)) |
| 1227 | { return; } |
| 1228 | let path = world.ecs.get(handle, Component.path); |
| 1229 | if (!path) |
| 1230 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1231 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; |
| 1232 | if ( |
| 1233 | aloneHere |
| 1234 | && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist |
| 1235 | ) |
| 1236 | { |
| 1237 | path.tiles = []; |
| 1238 | return; |
| 1239 | } |
| 1240 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1241 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 1242 | const isGoal = (x, y) => |
| 1243 | { |
| 1244 | if (chebyshev(x, y, source.tileX, source.tileY) < minDist) |
| 1245 | { return false; } |
| 1246 | return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); |
| 1247 | }; |
| 1248 | if (isGoal(position.tileX, position.tileY) && aloneHere) |
| 1249 | { |
| 1250 | path.tiles = []; |
| 1251 | return; |
| 1252 | } |
| 1253 | const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null; |
| 1254 | if ( |
| 1255 | dest |
| 1256 | && isGoal(dest.x, dest.y) |
| 1257 | && path.tiles.every((step) => isWalkable(step.x, step.y)) |
| 1258 | ) |
| 1259 | { return; } |
| 1260 | const tiles = findPathToNearestGoal( |
| 1261 | position.tileX, |
| 1262 | position.tileY, |
| 1263 | isGoal, |
| 1264 | isWalkable, |
| 1265 | bounds.minX, |
| 1266 | bounds.minY, |
| 1267 | bounds.maxX, |
| 1268 | bounds.maxY |
| 1269 | ); |
| 1270 | if (!tiles.length) |
| 1271 | { |
| 1272 | path.tiles = []; |
| 1273 | return; |
| 1274 | } |
| 1275 | path.tiles = tiles; |
| 1276 | const movement = world.ecs.get(handle, Component.movement); |
| 1277 | if (movement) |
| 1278 | { movement.walkCarry = 0; } |
| 1279 | } |
| 1280 | |
| 1281 | export function queueMeleeApproach (world, entityId, handle, position, targetPos) |
| 1282 | { |
| 1283 | if (world.frozen?.has?.(entityId)) |
| 1284 | { return; } |
| 1285 | let path = world.ecs.get(handle, Component.path); |
| 1286 | if (!path) |
| 1287 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1288 | |
| 1289 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) |
| 1290 | ?? true; |
| 1291 | if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere) |
| 1292 | { |
| 1293 | path.tiles = []; |
| 1294 | return; |
| 1295 | } |
| 1296 | |
| 1297 | const combat = world.ecs.get(handle, Component.combat); |
| 1298 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 1299 | const seekCover = shouldSeekCoverApproach(world, handle); |
| 1300 | |
| 1301 | if (seekCover) |
| 1302 | { |
| 1303 | const coverTiles = findCoverMeleeApproachPath( |
| 1304 | world, |
| 1305 | entityId, |
| 1306 | handle, |
| 1307 | position, |
| 1308 | targetPos, |
| 1309 | reserved |
| 1310 | ); |
| 1311 | if (coverTiles) |
| 1312 | { |
| 1313 | if (!coverTiles.length) |
| 1314 | { |
| 1315 | path.tiles = []; |
| 1316 | return; |
| 1317 | } |
| 1318 | const goal = coverTiles[coverTiles.length - 1]; |
| 1319 | if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) |
| 1320 | { return; } |
| 1321 | path.tiles = coverTiles; |
| 1322 | const movement = world.ecs.get(handle, Component.movement); |
| 1323 | if (movement) |
| 1324 | { movement.walkCarry = 0; } |
| 1325 | return; |
| 1326 | } |
| 1327 | queueFleeToCover(world, entityId, handle, position, targetPos); |
| 1328 | return; |
| 1329 | } |
| 1330 | |
| 1331 | const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); |
| 1332 | if (!goal) |
| 1333 | { |
| 1334 | path.tiles = []; |
| 1335 | return; |
| 1336 | } |
| 1337 | |
| 1338 | if (goal.x === position.tileX && goal.y === position.tileY) |
| 1339 | { |
| 1340 | path.tiles = []; |
| 1341 | return; |
| 1342 | } |
| 1343 | |
| 1344 | if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) |
| 1345 | { return; } |
| 1346 | |
| 1347 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1348 | const preferVertical = !!world.ecs.get(handle, Component.character); |
| 1349 | const tiles = findPath( |
| 1350 | position.tileX, |
| 1351 | position.tileY, |
| 1352 | goal.x, |
| 1353 | goal.y, |
| 1354 | (x, y) => |
| 1355 | { |
| 1356 | if (x === goal.x && y === goal.y) |
| 1357 | { |
| 1358 | return world.isClearStanding?.(entityId, x, y) |
| 1359 | ?? world.walkableFor(entityId, x, y); |
| 1360 | } |
| 1361 | return world.walkableFor(entityId, x, y); |
| 1362 | }, |
| 1363 | bounds.minX, |
| 1364 | bounds.minY, |
| 1365 | bounds.maxX, |
| 1366 | bounds.maxY, |
| 1367 | { preferVertical } |
| 1368 | ); |
| 1369 | if (!tiles.length) |
| 1370 | { |
| 1371 | path.tiles = []; |
| 1372 | return; |
| 1373 | } |
| 1374 | path.tiles = tiles; |
| 1375 | const movement = world.ecs.get(handle, Component.movement); |
| 1376 | if (movement) |
| 1377 | { movement.walkCarry = 0; } |
| 1378 | } |
| 1379 | |
| 1380 | /** |
| 1381 | * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. |
| 1382 | * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). |
| 1383 | * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile). |
| 1384 | */ |
| 1385 | export function queueStandInRangeApproach ( |
| 1386 | world, |
| 1387 | entityId, |
| 1388 | handle, |
| 1389 | position, |
| 1390 | targetTileX, |
| 1391 | targetTileY, |
| 1392 | maxRange, |
| 1393 | minStandDist = 1 |
| 1394 | ) |
| 1395 | { |
| 1396 | if (world.frozen?.has?.(entityId)) |
| 1397 | { return; } |
| 1398 | let path = world.ecs.get(handle, Component.path); |
| 1399 | if (!path) |
| 1400 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 1401 | |
| 1402 | const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); |
| 1403 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; |
| 1404 | if ( |
| 1405 | distToTarget <= maxRange |
| 1406 | && distToTarget >= minStandDist |
| 1407 | && aloneHere |
| 1408 | && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) |
| 1409 | ) |
| 1410 | { |
| 1411 | path.tiles = []; |
| 1412 | return; |
| 1413 | } |
| 1414 | |
| 1415 | const combat = world.ecs.get(handle, Component.combat); |
| 1416 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 1417 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 1418 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 1419 | const isGoal = (x, y) => |
| 1420 | { |
| 1421 | const standOff = chebyshev(x, y, targetTileX, targetTileY); |
| 1422 | if (standOff < minStandDist || standOff > maxRange) |
| 1423 | { return false; } |
| 1424 | if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) |
| 1425 | { return false; } |
| 1426 | const key = combatTileKey(x, y); |
| 1427 | if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) |
| 1428 | { return false; } |
| 1429 | return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); |
| 1430 | }; |
| 1431 | |
| 1432 | const tiles = findPathToNearestGoal( |
| 1433 | position.tileX, |
| 1434 | position.tileY, |
| 1435 | isGoal, |
| 1436 | isWalkable, |
| 1437 | bounds.minX, |
| 1438 | bounds.minY, |
| 1439 | bounds.maxX, |
| 1440 | bounds.maxY |
| 1441 | ); |
| 1442 | if (!tiles.length) |
| 1443 | { |
| 1444 | path.tiles = []; |
| 1445 | return; |
| 1446 | } |
| 1447 | const bestGoal = tiles[tiles.length - 1]; |
| 1448 | if (path.tiles?.length && !standInRangePathStale( |
| 1449 | world, |
| 1450 | entityId, |
| 1451 | path, |
| 1452 | bestGoal, |
| 1453 | targetTileX, |
| 1454 | targetTileY, |
| 1455 | maxRange, |
| 1456 | minStandDist, |
| 1457 | reserved, |
| 1458 | position |
| 1459 | )) |
| 1460 | { return; } |
| 1461 | path.tiles = tiles; |
| 1462 | const movement = world.ecs.get(handle, Component.movement); |
| 1463 | if (movement) |
| 1464 | { movement.walkCarry = 0; } |
| 1465 | } |
| 1466 | |
| 1467 | function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange) |
| 1468 | { |
| 1469 | queueStandInRangeApproach( |
| 1470 | world, |
| 1471 | entityId, |
| 1472 | handle, |
| 1473 | position, |
| 1474 | targetPos.tileX, |
| 1475 | targetPos.tileY, |
| 1476 | maxRange, |
| 1477 | 1 |
| 1478 | ); |
| 1479 | } |
| 1480 | |
| 1481 | export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos) |
| 1482 | { |
| 1483 | const events = []; |
| 1484 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1485 | if (attackerHandle == null) |
| 1486 | { return events; } |
| 1487 | const from = world.ecs.get(attackerHandle, Component.position); |
| 1488 | if (!from || !targetPos) |
| 1489 | { return events; } |
| 1490 | const isCreature = !!world.ecs.get(attackerHandle, Component.creature) |
| 1491 | && !world.ecs.get(attackerHandle, Component.character); |
| 1492 | const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle); |
| 1493 | const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle); |
| 1494 | const tipElement = (() => |
| 1495 | { |
| 1496 | const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment)); |
| 1497 | return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null; |
| 1498 | })(); |
| 1499 | if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) |
| 1500 | { return events; } |
| 1501 | |
| 1502 | const shotProfile = tipElement |
| 1503 | ? { ...profile, attackType: tipElement } |
| 1504 | : profile; |
| 1505 | |
| 1506 | const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY }; |
| 1507 | const target = resolveCombatTarget(world, targetId); |
| 1508 | if (!target) |
| 1509 | { return events; } |
| 1510 | |
| 1511 | if (!target.local) |
| 1512 | { |
| 1513 | events.push({ |
| 1514 | type: "remote-ranged-resolve", |
| 1515 | attackerId, |
| 1516 | targetId, |
| 1517 | profile: shotProfile, |
| 1518 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings), |
| 1519 | attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), |
| 1520 | now, |
| 1521 | tileX: snapshot.tileX, |
| 1522 | tileY: snapshot.tileY, |
| 1523 | fromTileX: from.tileX, |
| 1524 | fromTileY: from.tileY, |
| 1525 | sprite: arrowSprite, |
| 1526 | ...(publicDualTint(arrowTint) ?? {}) |
| 1527 | }); |
| 1528 | return events; |
| 1529 | } |
| 1530 | |
| 1531 | const hitEvents = applyLocalMeleeHit( |
| 1532 | world, |
| 1533 | attackerId, |
| 1534 | targetId, |
| 1535 | attackerHandle, |
| 1536 | target.handle, |
| 1537 | shotProfile, |
| 1538 | now, |
| 1539 | snapshot |
| 1540 | ); |
| 1541 | const outcome = hitEvents.find((e) => |
| 1542 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1543 | let endX = snapshot.tileX; |
| 1544 | let endY = snapshot.tileY; |
| 1545 | if (outcome?.type === "combat-miss") |
| 1546 | { |
| 1547 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1548 | endX = miss.tileX; |
| 1549 | endY = miss.tileY; |
| 1550 | } |
| 1551 | else |
| 1552 | { |
| 1553 | const currentPos = world.ecs.get(target.handle, Component.position); |
| 1554 | if (currentPos) |
| 1555 | { |
| 1556 | endX = currentPos.tileX; |
| 1557 | endY = currentPos.tileY; |
| 1558 | } |
| 1559 | } |
| 1560 | events.push({ |
| 1561 | type: "combat-projectile", |
| 1562 | attackerId, |
| 1563 | targetId, |
| 1564 | fromTileX: from.tileX, |
| 1565 | fromTileY: from.tileY, |
| 1566 | tileX: endX, |
| 1567 | tileY: endY, |
| 1568 | durationMs: RANGED_PROJECTILE_MS, |
| 1569 | trackTarget: outcome?.type !== "combat-miss", |
| 1570 | sprite: arrowSprite, |
| 1571 | ...(publicDualTint(arrowTint) ?? {}) |
| 1572 | }); |
| 1573 | return events.concat(hitEvents); |
| 1574 | } |
| 1575 | |
| 1576 | function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position) |
| 1577 | { |
| 1578 | const dest = path.tiles[path.tiles.length - 1]; |
| 1579 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 1580 | { return true; } |
| 1581 | const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); |
| 1582 | if (standOff < minStandDist || standOff > maxRange) |
| 1583 | { return true; } |
| 1584 | if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) |
| 1585 | { return true; } |
| 1586 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 1587 | { return true; } |
| 1588 | const destKey = combatTileKey(dest.x, dest.y); |
| 1589 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 1590 | { return true; } |
| 1591 | const next = path.tiles[0]; |
| 1592 | if (!next) |
| 1593 | { return true; } |
| 1594 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 1595 | { return true; } |
| 1596 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 1597 | } |
| 1598 | |
| 1599 | function meleePathStale (world, entityId, position, targetPos, path, goal, reserved) |
| 1600 | { |
| 1601 | const dest = path.tiles[path.tiles.length - 1]; |
| 1602 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 1603 | { return true; } |
| 1604 | if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1) |
| 1605 | { return true; } |
| 1606 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 1607 | { return true; } |
| 1608 | const destKey = combatTileKey(dest.x, dest.y); |
| 1609 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 1610 | { return true; } |
| 1611 | const next = path.tiles[0]; |
| 1612 | if (!next) |
| 1613 | { return true; } |
| 1614 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 1615 | { return true; } |
| 1616 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 1617 | } |
| 1618 | |
| 1619 | function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null) |
| 1620 | { |
| 1621 | const dirs = [ |
| 1622 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1623 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1624 | ]; |
| 1625 | let best = null; |
| 1626 | let bestDist = Infinity; |
| 1627 | let bestPref = Infinity; |
| 1628 | for (const dir of dirs) |
| 1629 | { |
| 1630 | const x = targetPos.tileX + dir.x; |
| 1631 | const y = targetPos.tileY + dir.y; |
| 1632 | const isHere = x === position.tileX && y === position.tileY; |
| 1633 | const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; |
| 1634 | const key = combatTileKey(x, y); |
| 1635 | if (reserved?.has(key) && !(isHere && aloneHere)) |
| 1636 | { continue; } |
| 1637 | const clear = world.isClearStanding?.(entityId, x, y) |
| 1638 | ?? world.walkableFor(entityId, x, y); |
| 1639 | if (!clear && !isHere) |
| 1640 | { continue; } |
| 1641 | if (isHere && !aloneHere) |
| 1642 | { continue; } |
| 1643 | const dist = chebyshev(position.tileX, position.tileY, x, y); |
| 1644 | const pref = combatGoalPreference(entityId, x, y); |
| 1645 | if (dist < bestDist || (dist === bestDist && pref < bestPref)) |
| 1646 | { |
| 1647 | bestDist = dist; |
| 1648 | bestPref = pref; |
| 1649 | best = { x, y }; |
| 1650 | } |
| 1651 | } |
| 1652 | return best; |
| 1653 | } |
| 1654 | |
| 1655 | export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now()) |
| 1656 | { |
| 1657 | const events = []; |
| 1658 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1659 | if (attackerHandle == null) |
| 1660 | { return events; } |
| 1661 | const target = resolveCombatTarget(world, targetId); |
| 1662 | if (!target) |
| 1663 | { return events; } |
| 1664 | const from = world.ecs.get(attackerHandle, Component.position); |
| 1665 | const to = target.pos; |
| 1666 | if (!from || !to) |
| 1667 | { return events; } |
| 1668 | if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1) |
| 1669 | { return events; } |
| 1670 | if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY)) |
| 1671 | { return events; } |
| 1672 | |
| 1673 | events.push({ |
| 1674 | type: "combat-swing", |
| 1675 | attackerId, |
| 1676 | targetId, |
| 1677 | tileX: to.tileX, |
| 1678 | tileY: to.tileY, |
| 1679 | fromTileX: from.tileX, |
| 1680 | fromTileY: from.tileY |
| 1681 | }); |
| 1682 | |
| 1683 | if (!target.local) |
| 1684 | { |
| 1685 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 1686 | events.push({ |
| 1687 | type: "remote-melee-resolve", |
| 1688 | attackerId, |
| 1689 | targetId, |
| 1690 | profile, |
| 1691 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), |
| 1692 | attackerIsPlayer: !!attackerCharacter, |
| 1693 | now, |
| 1694 | tileX: to.tileX, |
| 1695 | tileY: to.tileY |
| 1696 | }); |
| 1697 | return events; |
| 1698 | } |
| 1699 | |
| 1700 | return events.concat(applyLocalMeleeHit( |
| 1701 | world, |
| 1702 | attackerId, |
| 1703 | targetId, |
| 1704 | attackerHandle, |
| 1705 | target.handle, |
| 1706 | profile, |
| 1707 | now, |
| 1708 | to |
| 1709 | )); |
| 1710 | } |
| 1711 | |
| 1712 | /** Authoritative ranged hit when the defender lives on this worker. */ |
| 1713 | export function applyRemoteRangedShot (world, payload) |
| 1714 | { |
| 1715 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1716 | if (targetHandle == null) |
| 1717 | { return { events: [], forwards: [] }; } |
| 1718 | const snapshot = { |
| 1719 | tileX: payload.tileX, |
| 1720 | tileY: payload.tileY |
| 1721 | }; |
| 1722 | |
| 1723 | const hitEvents = applyLocalMeleeHit( |
| 1724 | world, |
| 1725 | payload.attackerId, |
| 1726 | payload.targetId, |
| 1727 | null, |
| 1728 | targetHandle, |
| 1729 | payload.profile, |
| 1730 | payload.now ?? Date.now(), |
| 1731 | snapshot, |
| 1732 | payload.attackerLevels, |
| 1733 | payload.attackerIsPlayer |
| 1734 | ); |
| 1735 | |
| 1736 | const outcome = hitEvents.find((e) => |
| 1737 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1738 | let endX = snapshot.tileX; |
| 1739 | let endY = snapshot.tileY; |
| 1740 | if (outcome?.type === "combat-miss") |
| 1741 | { |
| 1742 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1743 | endX = miss.tileX; |
| 1744 | endY = miss.tileY; |
| 1745 | } |
| 1746 | else |
| 1747 | { |
| 1748 | const currentPos = world.ecs.get(targetHandle, Component.position); |
| 1749 | if (currentPos) |
| 1750 | { |
| 1751 | endX = currentPos.tileX; |
| 1752 | endY = currentPos.tileY; |
| 1753 | } |
| 1754 | } |
| 1755 | |
| 1756 | const events = [{ |
| 1757 | type: "combat-projectile", |
| 1758 | attackerId: payload.attackerId, |
| 1759 | targetId: payload.targetId, |
| 1760 | fromTileX: payload.fromTileX, |
| 1761 | fromTileY: payload.fromTileY, |
| 1762 | tileX: endX, |
| 1763 | tileY: endY, |
| 1764 | durationMs: RANGED_PROJECTILE_MS, |
| 1765 | trackTarget: outcome?.type !== "combat-miss", |
| 1766 | sprite: payload.sprite ?? "fx:projectile:arrow", |
| 1767 | shaftTint: payload.shaftTint ?? null, |
| 1768 | tipTint: payload.tipTint ?? null, |
| 1769 | coatTint: payload.coatTint ?? null |
| 1770 | }, ...hitEvents]; |
| 1771 | |
| 1772 | const forwards = []; |
| 1773 | const hitEvent = hitEvents.find((event) => event.type === "combat-hit"); |
| 1774 | if (hitEvent && payload.attackerIsPlayer) |
| 1775 | { |
| 1776 | forwards.push({ |
| 1777 | type: "forward-combat-xp", |
| 1778 | entityId: payload.attackerId, |
| 1779 | profile: payload.profile, |
| 1780 | damage: hitEvent.damage |
| 1781 | }); |
| 1782 | } |
| 1783 | return { events, forwards }; |
| 1784 | } |
| 1785 | |
| 1786 | /** Authoritative hit resolution when the defender lives on this worker. */ |
| 1787 | export function applyRemoteMeleeSwing (world, payload) |
| 1788 | { |
| 1789 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1790 | if (targetHandle == null) |
| 1791 | { return { events: [], forwards: [] }; } |
| 1792 | const to = world.ecs.get(targetHandle, Component.position); |
| 1793 | if (!to) |
| 1794 | { return { events: [], forwards: [] }; } |
| 1795 | |
| 1796 | const events = applyLocalMeleeHit( |
| 1797 | world, |
| 1798 | payload.attackerId, |
| 1799 | payload.targetId, |
| 1800 | null, |
| 1801 | targetHandle, |
| 1802 | payload.profile, |
| 1803 | payload.now ?? Date.now(), |
| 1804 | to, |
| 1805 | payload.attackerLevels, |
| 1806 | payload.attackerIsPlayer |
| 1807 | ); |
| 1808 | |
| 1809 | const forwards = []; |
| 1810 | const hitEvent = events.find((event) => event.type === "combat-hit"); |
| 1811 | if (hitEvent && payload.attackerIsPlayer) |
| 1812 | { |
| 1813 | forwards.push({ |
| 1814 | type: "forward-combat-xp", |
| 1815 | entityId: payload.attackerId, |
| 1816 | profile: payload.profile, |
| 1817 | damage: hitEvent.damage |
| 1818 | }); |
| 1819 | } |
| 1820 | return { events, forwards }; |
| 1821 | } |
| 1822 | |
| 1823 | function applyLocalMeleeHit ( |
| 1824 | world, |
| 1825 | attackerId, |
| 1826 | targetId, |
| 1827 | attackerHandle, |
| 1828 | targetHandle, |
| 1829 | profile, |
| 1830 | now, |
| 1831 | to, |
| 1832 | attackerLevelsOverride = null, |
| 1833 | attackerIsPlayerOverride = null |
| 1834 | ) |
| 1835 | { |
| 1836 | const events = []; |
| 1837 | if (targetHandle == null) |
| 1838 | { return events; } |
| 1839 | |
| 1840 | const attackerIsPlayer = attackerIsPlayerOverride != null |
| 1841 | ? !!attackerIsPlayerOverride |
| 1842 | : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null); |
| 1843 | |
| 1844 | // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage. |
| 1845 | if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId)) |
| 1846 | { |
| 1847 | engageTarget(world.ecs, targetId, attackerId, now); |
| 1848 | if (profile?.mode === "ranged") |
| 1849 | { markSeekCover(world.ecs, targetId); } |
| 1850 | } |
| 1851 | if (attackerIsPlayer === false) |
| 1852 | { |
| 1853 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1854 | if (targetCharacter) |
| 1855 | { |
| 1856 | engageTarget(world.ecs, targetId, attackerId, now); |
| 1857 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 1858 | if (follow) |
| 1859 | { |
| 1860 | follow.targetEntityId = null; |
| 1861 | follow.trail = []; |
| 1862 | } |
| 1863 | if (world.ecs.has(targetHandle, Component.gather)) |
| 1864 | { world.ecs.remove(targetHandle, Component.gather); } |
| 1865 | } |
| 1866 | } |
| 1867 | |
| 1868 | const defenderSkills = world.ecs.get(targetHandle, Component.skills); |
| 1869 | const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); |
| 1870 | const attackerLevels = attackerLevelsOverride |
| 1871 | ?? (attackerHandle != null |
| 1872 | ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings) |
| 1873 | : null); |
| 1874 | if (!attackerLevels) |
| 1875 | { return events; } |
| 1876 | |
| 1877 | const agilityLevel = defenderSkillLevel( |
| 1878 | defenderSkills, |
| 1879 | SkillId.agility, |
| 1880 | defenderEquipment, |
| 1881 | world.settings |
| 1882 | ); |
| 1883 | const defenceLevel = defenderSkillLevel( |
| 1884 | defenderSkills, |
| 1885 | SkillId.defence, |
| 1886 | defenderEquipment, |
| 1887 | world.settings |
| 1888 | ); |
| 1889 | |
| 1890 | const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile); |
| 1891 | const targetCreature = world.ecs.get(targetHandle, Component.creature); |
| 1892 | const targetAffinities = targetCreature |
| 1893 | ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId)) |
| 1894 | : {}; |
| 1895 | const resolved = resolvePhysicalAttack({ |
| 1896 | hitSkillLevel: effectiveHitSkillInDarkness( |
| 1897 | attackerLevels.hitLevel, |
| 1898 | tileLightAt(world, to.tileX, to.tileY) |
| 1899 | ), |
| 1900 | agilitySkillLevel: agilityLevel, |
| 1901 | damageSkillLevel: attackerLevels.damageLevel, |
| 1902 | defenceSkillLevel: defenceLevel, |
| 1903 | attackType, |
| 1904 | targetAffinities |
| 1905 | }); |
| 1906 | |
| 1907 | if (resolved.outcome === "miss") |
| 1908 | { |
| 1909 | events.push({ |
| 1910 | type: "combat-miss", |
| 1911 | attackerId, |
| 1912 | targetId, |
| 1913 | tileX: to.tileX, |
| 1914 | tileY: to.tileY |
| 1915 | }); |
| 1916 | const dodgeXp = awardCombatAvoidanceXp( |
| 1917 | world.ecs, |
| 1918 | targetHandle, |
| 1919 | SkillId.agility, |
| 1920 | resolved.damageRoll |
| 1921 | ); |
| 1922 | if (dodgeXp) |
| 1923 | { |
| 1924 | events.push({ |
| 1925 | type: "skills-updated", |
| 1926 | entityId: targetId, |
| 1927 | characterId: dodgeXp.characterId, |
| 1928 | skills: dodgeXp.skills, |
| 1929 | combatLevel: dodgeXp.combatLevel, |
| 1930 | stored: dodgeXp.stored, |
| 1931 | levelUps: dodgeXp.levelUps ?? [] |
| 1932 | }); |
| 1933 | } |
| 1934 | return events; |
| 1935 | } |
| 1936 | |
| 1937 | if (resolved.outcome === "block") |
| 1938 | { |
| 1939 | events.push({ |
| 1940 | type: "combat-block", |
| 1941 | attackerId, |
| 1942 | targetId, |
| 1943 | tileX: to.tileX, |
| 1944 | tileY: to.tileY |
| 1945 | }); |
| 1946 | const blockXp = awardCombatAvoidanceXp( |
| 1947 | world.ecs, |
| 1948 | targetHandle, |
| 1949 | SkillId.defence, |
| 1950 | resolved.damageRoll |
| 1951 | ); |
| 1952 | if (blockXp) |
| 1953 | { |
| 1954 | events.push({ |
| 1955 | type: "skills-updated", |
| 1956 | entityId: targetId, |
| 1957 | characterId: blockXp.characterId, |
| 1958 | skills: blockXp.skills, |
| 1959 | combatLevel: blockXp.combatLevel, |
| 1960 | stored: blockXp.stored, |
| 1961 | levelUps: blockXp.levelUps ?? [] |
| 1962 | }); |
| 1963 | } |
| 1964 | return events; |
| 1965 | } |
| 1966 | |
| 1967 | const damage = resolved.damage; |
| 1968 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1969 | if (targetCharacter) |
| 1970 | { syncPlayerHealth(world.ecs, targetHandle); } |
| 1971 | const health = world.ecs.get(targetHandle, Component.health); |
| 1972 | if (health) |
| 1973 | { |
| 1974 | health.current = Math.max(0, (health.current | 0) - damage); |
| 1975 | markHealthDamaged(health, now); |
| 1976 | } |
| 1977 | events.push({ |
| 1978 | type: "combat-hit", |
| 1979 | attackerId, |
| 1980 | targetId, |
| 1981 | damage, |
| 1982 | tileX: to.tileX, |
| 1983 | tileY: to.tileY, |
| 1984 | health: health?.current ?? 0, |
| 1985 | maxHealth: health?.max ?? 0 |
| 1986 | }); |
| 1987 | |
| 1988 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 1989 | if (healthXp) |
| 1990 | { |
| 1991 | events.push({ |
| 1992 | type: "skills-updated", |
| 1993 | entityId: targetId, |
| 1994 | characterId: healthXp.characterId, |
| 1995 | skills: healthXp.skills, |
| 1996 | combatLevel: healthXp.combatLevel, |
| 1997 | stored: healthXp.stored, |
| 1998 | levelUps: healthXp.levelUps ?? [] |
| 1999 | }); |
| 2000 | if (health) |
| 2001 | { |
| 2002 | const hitEvent = events[events.length - 2]; |
| 2003 | if (hitEvent?.type === "combat-hit") |
| 2004 | { |
| 2005 | hitEvent.health = health.current; |
| 2006 | hitEvent.maxHealth = health.max; |
| 2007 | } |
| 2008 | } |
| 2009 | } |
| 2010 | |
| 2011 | if (attackerHandle != null) |
| 2012 | { markFleeOnHit(world, targetId, attackerId); } |
| 2013 | |
| 2014 | if (attackerHandle != null) |
| 2015 | { |
| 2016 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 2017 | if (attackerCharacter) |
| 2018 | { |
| 2019 | const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage); |
| 2020 | if (xpAward) |
| 2021 | { |
| 2022 | events.push({ |
| 2023 | type: "skills-updated", |
| 2024 | entityId: attackerId, |
| 2025 | characterId: attackerCharacter.characterId, |
| 2026 | skills: xpAward.skills, |
| 2027 | combatLevel: xpAward.combatLevel, |
| 2028 | stored: xpAward.stored, |
| 2029 | levelUps: xpAward.levelUps ?? [] |
| 2030 | }); |
| 2031 | } |
| 2032 | } |
| 2033 | } |
| 2034 | |
| 2035 | if (health && health.current <= 0) |
| 2036 | { |
| 2037 | clearEngage(world.ecs, attackerId); |
| 2038 | clearEngage(world.ecs, targetId); |
| 2039 | for (const entity of world.ecs.query(Component.combat)) |
| 2040 | { |
| 2041 | if (entity.combat.targetEntityId === targetId) |
| 2042 | { entity.combat.targetEntityId = null; } |
| 2043 | } |
| 2044 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 2045 | { |
| 2046 | const path = world.ecs.get(targetHandle, Component.path); |
| 2047 | if (path) |
| 2048 | { path.tiles = []; } |
| 2049 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 2050 | if (follow) |
| 2051 | { |
| 2052 | follow.targetEntityId = null; |
| 2053 | follow.trail = []; |
| 2054 | } |
| 2055 | world.ecs.add(targetHandle, Component.dead, {}); |
| 2056 | silenceDeadPlayer(world.ecs, targetHandle); |
| 2057 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 2058 | events.push({ |
| 2059 | type: "player-died", |
| 2060 | entityId: targetId, |
| 2061 | attackerId, |
| 2062 | characterId: targetCharacter.characterId, |
| 2063 | sessionId: identity?.sessionId ?? null, |
| 2064 | tileX: to.tileX, |
| 2065 | tileY: to.tileY, |
| 2066 | health: 0, |
| 2067 | maxHealth: health.max |
| 2068 | }); |
| 2069 | } |
| 2070 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 2071 | if (creature && !world.ecs.get(targetHandle, Component.character)) |
| 2072 | { |
| 2073 | events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); |
| 2074 | } |
| 2075 | } |
| 2076 | return events; |
| 2077 | } |
| 2078 | |
| 2079 | /** |
| 2080 | * Drops, despawn, and `mob-killed` for bounty / town-guard reaction. |
| 2081 | * Shared by melee and spell kill paths. |
| 2082 | */ |
| 2083 | export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now) |
| 2084 | { |
| 2085 | const events = []; |
| 2086 | const handle = targetHandle ?? world.ecs.handleOf(targetId); |
| 2087 | if (handle == null) |
| 2088 | { return events; } |
| 2089 | const creature = world.ecs.get(handle, Component.creature); |
| 2090 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 2091 | const appearance = world.ecs.get(handle, Component.appearance); |
| 2092 | events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId)); |
| 2093 | events.push({ |
| 2094 | type: "mob-killed", |
| 2095 | entityId: targetId, |
| 2096 | attackerId, |
| 2097 | mobTypeId: creature?.mobTypeId ?? null, |
| 2098 | level: creature?.level ?? origin?.level ?? 1, |
| 2099 | bounty: Math.max(0, origin?.bounty | 0 || 0), |
| 2100 | spawnerId: origin?.spawnerId ?? null, |
| 2101 | originTileX: origin?.originTileX ?? tileX, |
| 2102 | originTileY: origin?.originTileY ?? tileY, |
| 2103 | wanderRangeTiles: origin?.wanderRangeTiles ?? 0, |
| 2104 | townGuard: !!origin?.townGuard, |
| 2105 | displayName: appearance?.firstName ?? null, |
| 2106 | tileX, |
| 2107 | tileY |
| 2108 | }); |
| 2109 | if (origin?.spawnerId) |
| 2110 | { |
| 2111 | scheduleSpawnerRespawn( |
| 2112 | world, |
| 2113 | origin.spawnerId, |
| 2114 | origin.respawnDelaySeconds ?? 25, |
| 2115 | now |
| 2116 | ); |
| 2117 | } |
| 2118 | const view = world.destroyEntity?.(targetId) ?? null; |
| 2119 | if (view) |
| 2120 | { |
| 2121 | events.push({ |
| 2122 | type: "entity-despawn", |
| 2123 | entityId: targetId, |
| 2124 | tileX: view.tileX, |
| 2125 | tileY: view.tileY |
| 2126 | }); |
| 2127 | } |
| 2128 | return events; |
| 2129 | } |
| 2130 | |
| 2131 | /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */ |
| 2132 | export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now()) |
| 2133 | { |
| 2134 | const events = []; |
| 2135 | const targetHandle = world.ecs.handleOf(targetId); |
| 2136 | if (targetHandle == null) |
| 2137 | { return events; } |
| 2138 | const to = world.ecs.get(targetHandle, Component.position); |
| 2139 | if (!to) |
| 2140 | { return events; } |
| 2141 | const health = world.ecs.get(targetHandle, Component.health); |
| 2142 | if (health) |
| 2143 | { |
| 2144 | health.current = Math.max(0, (health.current | 0) - damage); |
| 2145 | markHealthDamaged(health, now); |
| 2146 | } |
| 2147 | events.push({ |
| 2148 | type: "combat-hit", |
| 2149 | attackerId, |
| 2150 | targetId, |
| 2151 | damage, |
| 2152 | tileX: to.tileX, |
| 2153 | tileY: to.tileY, |
| 2154 | health: health?.current ?? 0, |
| 2155 | maxHealth: health?.max ?? 0 |
| 2156 | }); |
| 2157 | |
| 2158 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 2159 | if (attackerHandle != null && ensureMobCombat(world.ecs, targetId)) |
| 2160 | { |
| 2161 | const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character); |
| 2162 | const targetCombat = world.ecs.get(targetHandle, Component.combat); |
| 2163 | if (targetCombat && targetCombat.targetEntityId == null) |
| 2164 | { engageTarget(world.ecs, targetId, attackerId, now); } |
| 2165 | if (attackerIsPlayer) |
| 2166 | { markSeekCover(world.ecs, targetId); } |
| 2167 | } |
| 2168 | if (attackerHandle != null) |
| 2169 | { markFleeOnHit(world, targetId, attackerId); } |
| 2170 | if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) |
| 2171 | { |
| 2172 | const attackerCreature = world.ecs.get(attackerHandle, Component.creature); |
| 2173 | if (attackerCreature) |
| 2174 | { |
| 2175 | engageTarget(world.ecs, targetId, attackerId, now); |
| 2176 | } |
| 2177 | } |
| 2178 | |
| 2179 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 2180 | if (healthXp) |
| 2181 | { |
| 2182 | events.push({ |
| 2183 | type: "skills-updated", |
| 2184 | entityId: targetId, |
| 2185 | characterId: healthXp.characterId, |
| 2186 | skills: healthXp.skills, |
| 2187 | combatLevel: healthXp.combatLevel, |
| 2188 | stored: healthXp.stored, |
| 2189 | levelUps: healthXp.levelUps ?? [] |
| 2190 | }); |
| 2191 | } |
| 2192 | |
| 2193 | if (health && health.current <= 0) |
| 2194 | { |
| 2195 | clearEngage(world.ecs, attackerId); |
| 2196 | clearEngage(world.ecs, targetId); |
| 2197 | for (const entity of world.ecs.query(Component.combat)) |
| 2198 | { |
| 2199 | if (entity.combat.targetEntityId === targetId) |
| 2200 | { entity.combat.targetEntityId = null; } |
| 2201 | } |
| 2202 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 2203 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 2204 | { |
| 2205 | const path = world.ecs.get(targetHandle, Component.path); |
| 2206 | if (path) |
| 2207 | { path.tiles = []; } |
| 2208 | world.ecs.add(targetHandle, Component.dead, {}); |
| 2209 | silenceDeadPlayer(world.ecs, targetHandle); |
| 2210 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 2211 | events.push({ |
| 2212 | type: "player-died", |
| 2213 | entityId: targetId, |
| 2214 | attackerId, |
| 2215 | characterId: targetCharacter.characterId, |
| 2216 | sessionId: identity?.sessionId ?? null, |
| 2217 | tileX: to.tileX, |
| 2218 | tileY: to.tileY, |
| 2219 | health: 0, |
| 2220 | maxHealth: health.max |
| 2221 | }); |
| 2222 | } |
| 2223 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 2224 | if (creature && !targetCharacter) |
| 2225 | { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } |
| 2226 | } |
| 2227 | return events; |
| 2228 | } |