| 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 } from "../../../shared/definitions/mobs.js"; |
| 5 | import |
| 6 | { |
| 7 | mobCanFightType, |
| 8 | mobCanFight, |
| 9 | mobMeleeAttackProfile, |
| 10 | mobSkillLevels, |
| 11 | mobIsAggressive, |
| 12 | mobAggroRangeTiles |
| 13 | } from "../../../shared/definitions/mobCombat.js"; |
| 14 | import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js"; |
| 15 | import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; |
| 16 | import { mobDamageAffinities } from "../../../shared/combat/magic.js"; |
| 17 | import { AttackType } from "../../../shared/definitions/attackTypes.js"; |
| 18 | import |
| 19 | { |
| 20 | effectiveHitSkillInDarkness, |
| 21 | aggroDistanceMultiplier |
| 22 | } from "../../../shared/combat/darkness.js"; |
| 23 | import |
| 24 | { |
| 25 | bakedTileLight01, |
| 26 | entityLightAtTile, |
| 27 | tileCombatLight01, |
| 28 | tileIndexLocal |
| 29 | } from "../../../shared/lighting/combatLight.js"; |
| 30 | import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js"; |
| 31 | import { LightOcclusion } from "../../../shared/definitions/tiles.js"; |
| 32 | import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js"; |
| 33 | import { spellLightsForDynamicLighting } from "../spells/lights.js"; |
| 34 | import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js"; |
| 35 | import |
| 36 | { |
| 37 | effectiveSkillLevel, |
| 38 | equipmentBonusesFromSlots |
| 39 | } from "../../../shared/equipment/stats.js"; |
| 40 | import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; |
| 41 | import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js"; |
| 42 | import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; |
| 43 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 44 | import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js"; |
| 45 | import { CHUNK_SIZE, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; |
| 46 | import { tileToChunk } from "../world/coordinates.js"; |
| 47 | import { stackQuantity } from "../../../shared/items/inventory.js"; |
| 48 | import { addGroundItem, publicGroundItem } from "../items/bags.js"; |
| 49 | import { resolveItemDualTint } from "../../../shared/render/tint.js"; |
| 50 | import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js"; |
| 51 | import { castMobAttackSpell } from "../spells/mobCast.js"; |
| 52 | import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; |
| 53 | import { scheduleSpawnerRespawn } from "../simulation/spawners.js"; |
| 54 | |
| 55 | export function chebyshev (ax, ay, bx, by) |
| 56 | { |
| 57 | return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); |
| 58 | } |
| 59 | |
| 60 | export function attackProfileOf (ecs, handle) |
| 61 | { |
| 62 | const creature = ecs.get(handle, Component.creature); |
| 63 | const level = creatureLevel(ecs, handle); |
| 64 | const equipment = ecs.get(handle, Component.equipment); |
| 65 | const weapon = equipment?.slots?.weapon; |
| 66 | if (weapon?.itemId != null) |
| 67 | { |
| 68 | const attack = itemDefinition(weapon.itemId)?.equipment?.attack; |
| 69 | if (attack) |
| 70 | { |
| 71 | const profile = { ...attack }; |
| 72 | if (creature) |
| 73 | { profile.mobAttackSkill = level; } |
| 74 | return profile; |
| 75 | } |
| 76 | } |
| 77 | if (creature) |
| 78 | { |
| 79 | const def = mobDefinition(creature.mobTypeId); |
| 80 | if (mobCanFightType(creature.mobTypeId)) |
| 81 | { return mobMeleeAttackProfile(def, level); } |
| 82 | } |
| 83 | return { ...UNARMED_ATTACK }; |
| 84 | } |
| 85 | |
| 86 | function creatureLevel (ecs, handle) |
| 87 | { |
| 88 | const creature = ecs.get(handle, Component.creature); |
| 89 | if (!creature) |
| 90 | { return 1; } |
| 91 | if (creature.level != null) |
| 92 | { return Math.max(1, creature.level | 0 || 1); } |
| 93 | const origin = ecs.get(handle, Component.spawnOrigin); |
| 94 | if (origin?.level != null) |
| 95 | { return Math.max(1, origin.level | 0 || 1); } |
| 96 | const def = mobDefinition(creature.mobTypeId); |
| 97 | return Math.max(1, def?.attackSkill | 0 || 1); |
| 98 | } |
| 99 | |
| 100 | export function weaponEquipmentKind (ecs, handle) |
| 101 | { |
| 102 | const equipment = ecs.get(handle, Component.equipment); |
| 103 | const weapon = equipment?.slots?.weapon; |
| 104 | if (!weapon?.itemId) |
| 105 | { return null; } |
| 106 | return itemDefinition(weapon.itemId)?.equipment?.kind ?? null; |
| 107 | } |
| 108 | |
| 109 | export function ensureMobCombat (ecs, entityId) |
| 110 | { |
| 111 | const handle = ecs.handleOf(entityId); |
| 112 | if (handle == null) |
| 113 | { return false; } |
| 114 | const creature = ecs.get(handle, Component.creature); |
| 115 | if (!creature || !mobCanFightType(creature.mobTypeId)) |
| 116 | { return false; } |
| 117 | const def = mobDefinition(creature.mobTypeId); |
| 118 | const level = creatureLevel(ecs, handle); |
| 119 | if (!ecs.get(handle, Component.combat)) |
| 120 | { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } |
| 121 | if (!ecs.get(handle, Component.skills)) |
| 122 | { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); } |
| 123 | return true; |
| 124 | } |
| 125 | |
| 126 | function attackerSkillLevel (skills, profile, skillId) |
| 127 | { |
| 128 | if (profile.mobAttackSkill != null) |
| 129 | { return profile.mobAttackSkill; } |
| 130 | return skillLevel(skills, skillId); |
| 131 | } |
| 132 | |
| 133 | function defenderSkillLevel (skills, skillId, equipment = null, settings = null) |
| 134 | { |
| 135 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 136 | return effectiveSkillLevel(skills, skillId, bonuses); |
| 137 | } |
| 138 | |
| 139 | function playerCombatLevels (ecs, handle, profile, settings = null) |
| 140 | { |
| 141 | const skills = ecs.get(handle, Component.skills); |
| 142 | const equipment = ecs.get(handle, Component.equipment); |
| 143 | const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); |
| 144 | const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); |
| 145 | bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); |
| 146 | bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); |
| 147 | |
| 148 | return { |
| 149 | hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses), |
| 150 | damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses), |
| 151 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 152 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 153 | }; |
| 154 | } |
| 155 | |
| 156 | export function isUntargetable (ecs, handle) |
| 157 | { |
| 158 | const creature = ecs.get(handle, Component.creature); |
| 159 | if (!creature) |
| 160 | { return false; } |
| 161 | return !!mobDefinition(creature.mobTypeId)?.untargetable; |
| 162 | } |
| 163 | |
| 164 | export function engageTarget (ecs, attackerId, targetId, now = Date.now()) |
| 165 | { |
| 166 | const handle = ecs.handleOf(attackerId); |
| 167 | if (handle == null) |
| 168 | { return false; } |
| 169 | // Spell auto-cast / pending cast is already the active combat form. |
| 170 | if (isSpellCombatBusy(ecs, handle)) |
| 171 | { return false; } |
| 172 | let combat = ecs.get(handle, Component.combat); |
| 173 | if (!combat) |
| 174 | { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } |
| 175 | const targetChanged = combat.targetEntityId !== targetId; |
| 176 | combat.targetEntityId = targetId; |
| 177 | if (targetChanged) |
| 178 | { |
| 179 | // New engage (or switch): allow an immediate swing; keep cadence if already on this target. |
| 180 | combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now); |
| 181 | const path = ecs.get(handle, Component.path); |
| 182 | if (path) |
| 183 | { path.tiles = []; } |
| 184 | } |
| 185 | return true; |
| 186 | } |
| 187 | |
| 188 | /** Pending cast or entity-spell auto-repeat — physical combat must not run. */ |
| 189 | export function isSpellCombatBusy (ecs, handle) |
| 190 | { |
| 191 | const casting = ecs.get(handle, Component.spellcasting); |
| 192 | if (!casting) |
| 193 | { return false; } |
| 194 | if (casting.pendingCast) |
| 195 | { return true; } |
| 196 | const spells = ecs.get(handle, Component.spells); |
| 197 | if (!spells?.autoCast || !casting.repeatSpellId) |
| 198 | { return false; } |
| 199 | const def = spellDefinition(casting.repeatSpellId); |
| 200 | return def?.target === "entity"; |
| 201 | } |
| 202 | |
| 203 | function clearSpellCombatState (ecs, handle) |
| 204 | { |
| 205 | const casting = ecs.get(handle, Component.spellcasting); |
| 206 | if (!casting) |
| 207 | { return; } |
| 208 | casting.repeatSpellId = null; |
| 209 | casting.repeatTargetEntityId = null; |
| 210 | casting.repeatTileX = null; |
| 211 | casting.repeatTileY = null; |
| 212 | casting.pendingCast = null; |
| 213 | } |
| 214 | |
| 215 | export function clearEngage (ecs, entityId) |
| 216 | { |
| 217 | const handle = ecs.handleOf(entityId); |
| 218 | const combat = handle != null ? ecs.get(handle, Component.combat) : null; |
| 219 | if (combat) |
| 220 | { combat.targetEntityId = null; } |
| 221 | } |
| 222 | |
| 223 | export function hasCombatLineOfSight (world, fromX, fromY, toX, toY) |
| 224 | { |
| 225 | const isClear = world.isClearForRangedAttack |
| 226 | ? (x, y) => world.isClearForRangedAttack(x, y) |
| 227 | : (x, y) => world.isEnterable(x, y); |
| 228 | return rayReaches(fromX, fromY, toX, toY, isClear); |
| 229 | } |
| 230 | |
| 231 | function lightOcclusionAtWorld (world, x, y) |
| 232 | { |
| 233 | const data = world.chunkData?.(tileToChunk(x), tileToChunk(y)); |
| 234 | if (!data) |
| 235 | { return LightOcclusion.clear; } |
| 236 | const index = tileIndexLocal(x, y); |
| 237 | if (Array.isArray(data.occlusion) && data.occlusion.length > index) |
| 238 | { return data.occlusion[index] | 0; } |
| 239 | const localX = ((x % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 240 | const localY = ((y % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; |
| 241 | return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY); |
| 242 | } |
| 243 | |
| 244 | /** Target-tile lighting 0–1 (baked + entity/spell lights − spell dark + time of day). */ |
| 245 | export function tileLightAt (world, tileX, tileY, now = Date.now()) |
| 246 | { |
| 247 | const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY)); |
| 248 | const index = tileIndexLocal(tileX, tileY); |
| 249 | const baked = bakedTileLight01(data?.light, index); |
| 250 | const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now); |
| 251 | const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now); |
| 252 | const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y); |
| 253 | const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt); |
| 254 | const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt); |
| 255 | const worldTime = world.worldTime?.(now); |
| 256 | return tileCombatLight01({ |
| 257 | bakedLight01: baked, |
| 258 | entityLight01: entity, |
| 259 | spellLight01: spellLight, |
| 260 | spellDark01: spellDark, |
| 261 | worldHour: worldTime?.hour ?? 12, |
| 262 | nightDarkness: world.settings?.nightDarkness ?? 0.72 |
| 263 | }); |
| 264 | } |
| 265 | |
| 266 | function arrowStackInOffhand (equipment) |
| 267 | { |
| 268 | const stack = equipment?.slots?.offhand; |
| 269 | if (!stack) |
| 270 | { return null; } |
| 271 | const def = itemDefinition(stack.itemId); |
| 272 | if (def?.equipment?.kind !== EquipmentKind.arrowAmmo) |
| 273 | { return null; } |
| 274 | return stack; |
| 275 | } |
| 276 | |
| 277 | /** Physical attack type, or tipped-arrow magic element when present. */ |
| 278 | function resolveAttackDamageType (ecs, attackerHandle, profile) |
| 279 | { |
| 280 | if (attackerHandle != null && profile?.mode === "ranged") |
| 281 | { |
| 282 | const stack = arrowStackInOffhand(ecs.get(attackerHandle, Component.equipment)); |
| 283 | if (stack?.instance?.kind === "tipped-arrow" && stack.instance.element) |
| 284 | { return stack.instance.element; } |
| 285 | } |
| 286 | return profile?.attackType ?? AttackType.blunt; |
| 287 | } |
| 288 | |
| 289 | function consumeArrow (ecs, handle) |
| 290 | { |
| 291 | const equipment = ecs.get(handle, Component.equipment); |
| 292 | const stack = arrowStackInOffhand(equipment); |
| 293 | if (!stack || stackQuantity(stack.quantity) <= 0) |
| 294 | { return false; } |
| 295 | if (stackQuantity(stack.quantity) <= 1) |
| 296 | { equipment.slots.offhand = null; } |
| 297 | else |
| 298 | { stack.quantity = stackQuantity(stack.quantity) - 1; } |
| 299 | return true; |
| 300 | } |
| 301 | |
| 302 | /** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */ |
| 303 | function rollDropQuantity (drop) |
| 304 | { |
| 305 | if (drop.quantityMin != null || drop.quantityMax != null) |
| 306 | { |
| 307 | const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1))); |
| 308 | const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min))); |
| 309 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 310 | } |
| 311 | return Math.max(1, Math.floor(Number(drop.quantity ?? 1))); |
| 312 | } |
| 313 | |
| 314 | function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null) |
| 315 | { |
| 316 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 317 | if (!creature) |
| 318 | { return []; } |
| 319 | const def = mobDefinition(creature.mobTypeId); |
| 320 | const mobName = entityCombatDisplayName(world.ecs, targetHandle) |
| 321 | || def?.displayName |
| 322 | || "a creature"; |
| 323 | let killerName = "someone"; |
| 324 | if (attackerId != null) |
| 325 | { |
| 326 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 327 | if (attackerHandle != null) |
| 328 | { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; } |
| 329 | } |
| 330 | const origin = lootOrigin(mobName, killerName); |
| 331 | const events = []; |
| 332 | const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin); |
| 333 | const dropTable = [ |
| 334 | ...(def?.drops ?? []), |
| 335 | ...(Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : []) |
| 336 | ]; |
| 337 | if (creature.element && (def?.essenceDropChance ?? 0) > 0) |
| 338 | { |
| 339 | const essenceId = essenceItemIdForElement(creature.element); |
| 340 | if (essenceId) |
| 341 | { dropTable.push({ itemId: essenceId, chance: def.essenceDropChance }); } |
| 342 | } |
| 343 | for (const drop of dropTable) |
| 344 | { |
| 345 | if (Math.random() > (drop.chance ?? 1)) |
| 346 | { continue; } |
| 347 | const quantity = rollDropQuantity(drop); |
| 348 | if (quantity <= 0) |
| 349 | { continue; } |
| 350 | const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); |
| 351 | const stack = attachOrigins({ |
| 352 | itemId: drop.itemId, |
| 353 | quantity, |
| 354 | origins: [{ origin, quantity }] |
| 355 | }); |
| 356 | const item = { |
| 357 | groundItemId, |
| 358 | tileX, |
| 359 | tileY, |
| 360 | stack, |
| 361 | droppedAt: now, |
| 362 | expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), |
| 363 | source: "mob-drop" |
| 364 | }; |
| 365 | addGroundItem(world, item); |
| 366 | events.push({ |
| 367 | type: "ground-item-appear", |
| 368 | ...publicGroundItem(item), |
| 369 | stack: item.stack, |
| 370 | droppedAt: item.droppedAt, |
| 371 | source: item.source, |
| 372 | expiresAt: item.expiresAt |
| 373 | }); |
| 374 | } |
| 375 | return events; |
| 376 | } |
| 377 | |
| 378 | function entityCombatDisplayName (ecs, handle) |
| 379 | { |
| 380 | const appearance = ecs.get(handle, Component.appearance); |
| 381 | const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); |
| 382 | if (fromAppearance) |
| 383 | { return fromAppearance; } |
| 384 | const creature = ecs.get(handle, Component.creature); |
| 385 | if (creature?.mobTypeId) |
| 386 | { |
| 387 | const def = mobDefinition(creature.mobTypeId); |
| 388 | if (def?.displayName) |
| 389 | { return def.displayName; } |
| 390 | } |
| 391 | return null; |
| 392 | } |
| 393 | |
| 394 | function projectileDualTintFromAttacker (ecs, handle) |
| 395 | { |
| 396 | const equipment = ecs.get(handle, Component.equipment); |
| 397 | const stack = arrowStackInOffhand(equipment); |
| 398 | if (!stack) |
| 399 | { return null; } |
| 400 | return resolveItemDualTint(stack, itemDefinition(stack.itemId)); |
| 401 | } |
| 402 | |
| 403 | function projectileSpriteFromAttacker (ecs, handle) |
| 404 | { |
| 405 | const equipment = ecs.get(handle, Component.equipment); |
| 406 | const stack = arrowStackInOffhand(equipment); |
| 407 | if (stack?.instance?.kind === "tipped-arrow") |
| 408 | { return "fx:projectile:arrow-tipped"; } |
| 409 | return "fx:projectile:arrow"; |
| 410 | } |
| 411 | |
| 412 | function publicDualTint (dualTint) |
| 413 | { |
| 414 | if (!dualTint) |
| 415 | { return null; } |
| 416 | return { |
| 417 | shaftTint: dualTint.shaft, |
| 418 | tipTint: dualTint.tip, |
| 419 | ...(dualTint.coat ? { coatTint: dualTint.coat } : {}) |
| 420 | }; |
| 421 | } |
| 422 | |
| 423 | function missProjectileTile (targetTileX, targetTileY, rng = Math.random) |
| 424 | { |
| 425 | const angle = rng() * Math.PI * 2; |
| 426 | const dist = rng(); |
| 427 | return { |
| 428 | tileX: Math.round(targetTileX + Math.cos(angle) * dist), |
| 429 | tileY: Math.round(targetTileY + Math.sin(angle) * dist) |
| 430 | }; |
| 431 | } |
| 432 | |
| 433 | /** |
| 434 | * Aggressive mobs auto-engage the nearest player character within aggro range |
| 435 | * when they have line of sight. Does nothing while already engaged. |
| 436 | */ |
| 437 | export function stepAggression (world, now = Date.now()) |
| 438 | { |
| 439 | for (const entity of world.ecs.query(Component.creature, Component.position)) |
| 440 | { |
| 441 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 442 | { continue; } |
| 443 | const def = mobDefinition(entity.creature.mobTypeId); |
| 444 | const origin = world.ecs.get(entity.handle, Component.spawnOrigin); |
| 445 | const aggressive = origin |
| 446 | ? !!origin.aggressive |
| 447 | : mobIsAggressive(def); |
| 448 | if (!aggressive || !mobCanFight(def)) |
| 449 | { continue; } |
| 450 | if (world.ecs.has(entity.handle, Component.dead)) |
| 451 | { continue; } |
| 452 | const health = world.ecs.get(entity.handle, Component.health); |
| 453 | if (health && health.current <= 0) |
| 454 | { continue; } |
| 455 | const combat = world.ecs.get(entity.handle, Component.combat); |
| 456 | if (combat?.targetEntityId != null) |
| 457 | { continue; } |
| 458 | |
| 459 | const range = mobAggroRangeTiles(def); |
| 460 | let bestId = null; |
| 461 | let bestDist = Infinity; |
| 462 | for (const player of world.ecs.query(Component.character, Component.position)) |
| 463 | { |
| 464 | if (world.ecs.has(player.handle, Component.dead)) |
| 465 | { continue; } |
| 466 | const playerHealth = world.ecs.get(player.handle, Component.health); |
| 467 | if (playerHealth && playerHealth.current <= 0) |
| 468 | { continue; } |
| 469 | const dist = chebyshev( |
| 470 | entity.position.tileX, |
| 471 | entity.position.tileY, |
| 472 | player.position.tileX, |
| 473 | player.position.tileY |
| 474 | ); |
| 475 | if (dist < 1 || dist > range) |
| 476 | { continue; } |
| 477 | let effectiveDist = dist; |
| 478 | if (dist > 1) |
| 479 | { |
| 480 | const light = tileLightAt(world, player.position.tileX, player.position.tileY); |
| 481 | effectiveDist = dist * aggroDistanceMultiplier(light); |
| 482 | } |
| 483 | if (effectiveDist > range) |
| 484 | { continue; } |
| 485 | if (!hasCombatLineOfSight( |
| 486 | world, |
| 487 | entity.position.tileX, |
| 488 | entity.position.tileY, |
| 489 | player.position.tileX, |
| 490 | player.position.tileY |
| 491 | )) |
| 492 | { continue; } |
| 493 | if (dist < bestDist) |
| 494 | { |
| 495 | bestDist = dist; |
| 496 | bestId = player.entityId; |
| 497 | } |
| 498 | } |
| 499 | if (bestId == null) |
| 500 | { continue; } |
| 501 | if (!ensureMobCombat(world.ecs, entity.entityId)) |
| 502 | { continue; } |
| 503 | engageTarget(world.ecs, entity.entityId, bestId, now); |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */ |
| 508 | export function resolveCombatTarget (world, targetId) |
| 509 | { |
| 510 | const handle = world.ecs.handleOf(targetId); |
| 511 | if (handle != null) |
| 512 | { |
| 513 | const pos = world.ecs.get(handle, Component.position); |
| 514 | if (!pos) |
| 515 | { return null; } |
| 516 | if (isUntargetable(world.ecs, handle)) |
| 517 | { return null; } |
| 518 | return { |
| 519 | local: true, |
| 520 | handle, |
| 521 | pos, |
| 522 | health: world.ecs.get(handle, Component.health) |
| 523 | }; |
| 524 | } |
| 525 | const ghost = world.ghosts?.get?.(targetId); |
| 526 | if (!ghost || ghost.untargetable) |
| 527 | { return null; } |
| 528 | const health = ghost.health != null |
| 529 | ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health } |
| 530 | : null; |
| 531 | return { |
| 532 | local: false, |
| 533 | handle: null, |
| 534 | pos: { tileX: ghost.tileX, tileY: ghost.tileY }, |
| 535 | health |
| 536 | }; |
| 537 | } |
| 538 | |
| 539 | function attackerCombatLevels (ecs, attackerHandle, profile, settings = null) |
| 540 | { |
| 541 | const attackerCharacter = ecs.get(attackerHandle, Component.character); |
| 542 | if (attackerCharacter) |
| 543 | { return playerCombatLevels(ecs, attackerHandle, profile, settings); } |
| 544 | const skills = ecs.get(attackerHandle, Component.skills); |
| 545 | const equipment = ecs.get(attackerHandle, Component.equipment); |
| 546 | const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; |
| 547 | const hitSkillId = profile.hitSkillId ?? SkillId.unarmed; |
| 548 | const damageSkillId = profile.damageSkillId ?? SkillId.strength; |
| 549 | const baseHit = attackerSkillLevel(skills, profile, hitSkillId); |
| 550 | const baseDamage = attackerSkillLevel(skills, profile, damageSkillId); |
| 551 | return { |
| 552 | hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)), |
| 553 | damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)), |
| 554 | agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), |
| 555 | defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) |
| 556 | }; |
| 557 | } |
| 558 | |
| 559 | export function stepCombat (world, now = Date.now()) |
| 560 | { |
| 561 | const events = []; |
| 562 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 563 | { |
| 564 | if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) |
| 565 | { continue; } |
| 566 | const combat = entity.combat; |
| 567 | const targetId = combat.targetEntityId; |
| 568 | if (targetId == null) |
| 569 | { continue; } |
| 570 | const target = resolveCombatTarget(world, targetId); |
| 571 | if (!target) |
| 572 | { |
| 573 | combat.targetEntityId = null; |
| 574 | continue; |
| 575 | } |
| 576 | if (target.health && target.health.current <= 0) |
| 577 | { |
| 578 | combat.targetEntityId = null; |
| 579 | continue; |
| 580 | } |
| 581 | |
| 582 | // One combat form at a time: spell cast / auto-cast wins over melee & archery. |
| 583 | if (isSpellCombatBusy(world.ecs, entity.handle)) |
| 584 | { continue; } |
| 585 | |
| 586 | const profile = attackProfileOf(world.ecs, entity.handle); |
| 587 | const targetPos = target.pos; |
| 588 | const isCreature = !!world.ecs.get(entity.handle, Component.creature) |
| 589 | && !world.ecs.get(entity.handle, Component.character); |
| 590 | |
| 591 | if (profile.mode === "ranged") |
| 592 | { |
| 593 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 594 | const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES; |
| 595 | const equipment = world.ecs.get(entity.handle, Component.equipment); |
| 596 | const hasArrows = isCreature |
| 597 | || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0); |
| 598 | const inRange = dist >= 1 && dist <= maxRange |
| 599 | && hasCombatLineOfSight( |
| 600 | world, |
| 601 | entity.position.tileX, |
| 602 | entity.position.tileY, |
| 603 | targetPos.tileX, |
| 604 | targetPos.tileY |
| 605 | ); |
| 606 | if (!inRange || !hasArrows) |
| 607 | { |
| 608 | if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0) |
| 609 | && world.ecs.get(entity.handle, Component.character)) |
| 610 | { |
| 611 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 612 | events.push({ |
| 613 | type: "combat-no-arrows", |
| 614 | attackerId: entity.entityId, |
| 615 | sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null |
| 616 | }); |
| 617 | } |
| 618 | queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange); |
| 619 | continue; |
| 620 | } |
| 621 | clearCombatApproachPath(world.ecs, entity.handle); |
| 622 | if (now < (combat.nextSwingAt || 0)) |
| 623 | { continue; } |
| 624 | combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); |
| 625 | clearSpellCombatState(world.ecs, entity.handle); |
| 626 | events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); |
| 627 | continue; |
| 628 | } |
| 629 | |
| 630 | if (profile.mode !== "melee") |
| 631 | { continue; } |
| 632 | |
| 633 | const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); |
| 634 | const canSwing = dist === 1 |
| 635 | && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); |
| 636 | const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; |
| 637 | const preferSpell = isCreature |
| 638 | && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack; |
| 639 | const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell); |
| 640 | |
| 641 | if (shouldCast) |
| 642 | { |
| 643 | const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES |
| 644 | && hasCombatLineOfSight( |
| 645 | world, |
| 646 | entity.position.tileX, |
| 647 | entity.position.tileY, |
| 648 | targetPos.tileX, |
| 649 | targetPos.tileY |
| 650 | ); |
| 651 | if (!inSpellRange) |
| 652 | { |
| 653 | queueStandInRangeApproach( |
| 654 | world, |
| 655 | entity.entityId, |
| 656 | entity.handle, |
| 657 | entity.position, |
| 658 | targetPos.tileX, |
| 659 | targetPos.tileY, |
| 660 | COMBAT_RANGE_TILES, |
| 661 | 1 |
| 662 | ); |
| 663 | continue; |
| 664 | } |
| 665 | clearCombatApproachPath(world.ecs, entity.handle); |
| 666 | if (now < (combat.nextSwingAt || 0)) |
| 667 | { continue; } |
| 668 | const picked = pickMobAttackSpell(attackSpells); |
| 669 | if (!picked) |
| 670 | { |
| 671 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 672 | continue; |
| 673 | } |
| 674 | combat.nextSwingAt = now + SPELL_COOLDOWN_MS; |
| 675 | events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now)); |
| 676 | continue; |
| 677 | } |
| 678 | |
| 679 | if (!canSwing) |
| 680 | { |
| 681 | queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); |
| 682 | continue; |
| 683 | } |
| 684 | clearCombatApproachPath(world.ecs, entity.handle); |
| 685 | const attackerHealth = world.ecs.get(entity.handle, Component.health); |
| 686 | if (attackerHealth && attackerHealth.current <= 0) |
| 687 | { continue; } |
| 688 | if ((combat.nextSwingAt || 0) > now) |
| 689 | { continue; } |
| 690 | |
| 691 | combat.nextSwingAt = now + (profile.cooldownMs || 800); |
| 692 | clearSpellCombatState(world.ecs, entity.handle); |
| 693 | events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); |
| 694 | } |
| 695 | return events; |
| 696 | } |
| 697 | |
| 698 | function eligibleMobAttackSpells (ecs, handle) |
| 699 | { |
| 700 | const spells = ecs.get(handle, Component.spells); |
| 701 | if (!spells?.known?.length) |
| 702 | { return []; } |
| 703 | const level = creatureLevel(ecs, handle); |
| 704 | const chances = spells.castChances ?? {}; |
| 705 | const out = []; |
| 706 | for (const spellId of spells.known) |
| 707 | { |
| 708 | const def = spellDefinition(spellId); |
| 709 | if (!def || def.target !== "entity") |
| 710 | { continue; } |
| 711 | const minLevel = spellMinMagicLevel(def); |
| 712 | if (level < minLevel) |
| 713 | { continue; } |
| 714 | const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0; |
| 715 | if (chance <= 0) |
| 716 | { continue; } |
| 717 | out.push({ spellId, chance }); |
| 718 | } |
| 719 | return out; |
| 720 | } |
| 721 | |
| 722 | function pickMobAttackSpell (spells) |
| 723 | { |
| 724 | if (!spells.length) |
| 725 | { return null; } |
| 726 | const pick = spells[Math.floor(Math.random() * spells.length)]; |
| 727 | if ((Math.random() * 100) >= pick.chance) |
| 728 | { return null; } |
| 729 | return pick; |
| 730 | } |
| 731 | |
| 732 | function clearCombatApproachPath (ecs, handle) |
| 733 | { |
| 734 | const path = ecs.get(handle, Component.path); |
| 735 | if (path?.tiles?.length) |
| 736 | { path.tiles = []; } |
| 737 | } |
| 738 | |
| 739 | function combatTileKey (tileX, tileY) |
| 740 | { |
| 741 | return `${tileX},${tileY}`; |
| 742 | } |
| 743 | |
| 744 | /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */ |
| 745 | function collectCombatAllyReservations (world, entityId, targetEntityId) |
| 746 | { |
| 747 | const reserved = new Set(); |
| 748 | if (targetEntityId == null) |
| 749 | { return reserved; } |
| 750 | for (const entity of world.ecs.query(Component.combat, Component.position)) |
| 751 | { |
| 752 | if (entity.entityId === entityId) |
| 753 | { continue; } |
| 754 | if (entity.combat.targetEntityId !== targetEntityId) |
| 755 | { continue; } |
| 756 | reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); |
| 757 | const allyPath = world.ecs.get(entity.handle, Component.path); |
| 758 | if (!allyPath?.tiles?.length) |
| 759 | { continue; } |
| 760 | const next = allyPath.tiles[0]; |
| 761 | if (next) |
| 762 | { reserved.add(combatTileKey(next.x, next.y)); } |
| 763 | const dest = allyPath.tiles[allyPath.tiles.length - 1]; |
| 764 | if (dest) |
| 765 | { reserved.add(combatTileKey(dest.x, dest.y)); } |
| 766 | } |
| 767 | return reserved; |
| 768 | } |
| 769 | |
| 770 | function combatGoalPreference (entityId, tileX, tileY) |
| 771 | { |
| 772 | return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0; |
| 773 | } |
| 774 | |
| 775 | export function queueMeleeApproach (world, entityId, handle, position, targetPos) |
| 776 | { |
| 777 | if (world.frozen?.has?.(entityId)) |
| 778 | { return; } |
| 779 | let path = world.ecs.get(handle, Component.path); |
| 780 | if (!path) |
| 781 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 782 | |
| 783 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) |
| 784 | ?? true; |
| 785 | if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere) |
| 786 | { |
| 787 | path.tiles = []; |
| 788 | return; |
| 789 | } |
| 790 | |
| 791 | const combat = world.ecs.get(handle, Component.combat); |
| 792 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 793 | const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); |
| 794 | if (!goal) |
| 795 | { |
| 796 | path.tiles = []; |
| 797 | return; |
| 798 | } |
| 799 | |
| 800 | if (goal.x === position.tileX && goal.y === position.tileY) |
| 801 | { |
| 802 | path.tiles = []; |
| 803 | return; |
| 804 | } |
| 805 | |
| 806 | if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) |
| 807 | { return; } |
| 808 | |
| 809 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 810 | const preferVertical = !!world.ecs.get(handle, Component.character); |
| 811 | const tiles = findPath( |
| 812 | position.tileX, |
| 813 | position.tileY, |
| 814 | goal.x, |
| 815 | goal.y, |
| 816 | (x, y) => |
| 817 | { |
| 818 | if (x === goal.x && y === goal.y) |
| 819 | { |
| 820 | return world.isClearStanding?.(entityId, x, y) |
| 821 | ?? world.walkableFor(entityId, x, y); |
| 822 | } |
| 823 | return world.walkableFor(entityId, x, y); |
| 824 | }, |
| 825 | bounds.minX, |
| 826 | bounds.minY, |
| 827 | bounds.maxX, |
| 828 | bounds.maxY, |
| 829 | { preferVertical } |
| 830 | ); |
| 831 | if (!tiles.length) |
| 832 | { |
| 833 | path.tiles = []; |
| 834 | return; |
| 835 | } |
| 836 | path.tiles = tiles; |
| 837 | const movement = world.ecs.get(handle, Component.movement); |
| 838 | if (movement) |
| 839 | { movement.walkCarry = 0; } |
| 840 | } |
| 841 | |
| 842 | /** |
| 843 | * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. |
| 844 | * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). |
| 845 | * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile). |
| 846 | */ |
| 847 | export function queueStandInRangeApproach ( |
| 848 | world, |
| 849 | entityId, |
| 850 | handle, |
| 851 | position, |
| 852 | targetTileX, |
| 853 | targetTileY, |
| 854 | maxRange, |
| 855 | minStandDist = 1 |
| 856 | ) |
| 857 | { |
| 858 | if (world.frozen?.has?.(entityId)) |
| 859 | { return; } |
| 860 | let path = world.ecs.get(handle, Component.path); |
| 861 | if (!path) |
| 862 | { path = world.ecs.add(handle, Component.path, { tiles: [] }); } |
| 863 | |
| 864 | const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); |
| 865 | const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; |
| 866 | if ( |
| 867 | distToTarget <= maxRange |
| 868 | && distToTarget >= minStandDist |
| 869 | && aloneHere |
| 870 | && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) |
| 871 | ) |
| 872 | { |
| 873 | path.tiles = []; |
| 874 | return; |
| 875 | } |
| 876 | |
| 877 | const combat = world.ecs.get(handle, Component.combat); |
| 878 | const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); |
| 879 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 880 | const isWalkable = (x, y) => world.walkableFor(entityId, x, y); |
| 881 | const isGoal = (x, y) => |
| 882 | { |
| 883 | const standOff = chebyshev(x, y, targetTileX, targetTileY); |
| 884 | if (standOff < minStandDist || standOff > maxRange) |
| 885 | { return false; } |
| 886 | if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) |
| 887 | { return false; } |
| 888 | const key = combatTileKey(x, y); |
| 889 | if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) |
| 890 | { return false; } |
| 891 | return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); |
| 892 | }; |
| 893 | |
| 894 | const tiles = findPathToNearestGoal( |
| 895 | position.tileX, |
| 896 | position.tileY, |
| 897 | isGoal, |
| 898 | isWalkable, |
| 899 | bounds.minX, |
| 900 | bounds.minY, |
| 901 | bounds.maxX, |
| 902 | bounds.maxY |
| 903 | ); |
| 904 | if (!tiles.length) |
| 905 | { |
| 906 | path.tiles = []; |
| 907 | return; |
| 908 | } |
| 909 | const bestGoal = tiles[tiles.length - 1]; |
| 910 | if (path.tiles?.length && !standInRangePathStale( |
| 911 | world, |
| 912 | entityId, |
| 913 | path, |
| 914 | bestGoal, |
| 915 | targetTileX, |
| 916 | targetTileY, |
| 917 | maxRange, |
| 918 | minStandDist, |
| 919 | reserved, |
| 920 | position |
| 921 | )) |
| 922 | { return; } |
| 923 | path.tiles = tiles; |
| 924 | const movement = world.ecs.get(handle, Component.movement); |
| 925 | if (movement) |
| 926 | { movement.walkCarry = 0; } |
| 927 | } |
| 928 | |
| 929 | function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange) |
| 930 | { |
| 931 | queueStandInRangeApproach( |
| 932 | world, |
| 933 | entityId, |
| 934 | handle, |
| 935 | position, |
| 936 | targetPos.tileX, |
| 937 | targetPos.tileY, |
| 938 | maxRange, |
| 939 | 1 |
| 940 | ); |
| 941 | } |
| 942 | |
| 943 | export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos) |
| 944 | { |
| 945 | const events = []; |
| 946 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 947 | if (attackerHandle == null) |
| 948 | { return events; } |
| 949 | const from = world.ecs.get(attackerHandle, Component.position); |
| 950 | if (!from || !targetPos) |
| 951 | { return events; } |
| 952 | const isCreature = !!world.ecs.get(attackerHandle, Component.creature) |
| 953 | && !world.ecs.get(attackerHandle, Component.character); |
| 954 | const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle); |
| 955 | const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle); |
| 956 | const tipElement = (() => |
| 957 | { |
| 958 | const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment)); |
| 959 | return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null; |
| 960 | })(); |
| 961 | if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) |
| 962 | { return events; } |
| 963 | |
| 964 | const shotProfile = tipElement |
| 965 | ? { ...profile, attackType: tipElement } |
| 966 | : profile; |
| 967 | |
| 968 | const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY }; |
| 969 | const target = resolveCombatTarget(world, targetId); |
| 970 | if (!target) |
| 971 | { return events; } |
| 972 | |
| 973 | if (!target.local) |
| 974 | { |
| 975 | events.push({ |
| 976 | type: "remote-ranged-resolve", |
| 977 | attackerId, |
| 978 | targetId, |
| 979 | profile: shotProfile, |
| 980 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings), |
| 981 | attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), |
| 982 | now, |
| 983 | tileX: snapshot.tileX, |
| 984 | tileY: snapshot.tileY, |
| 985 | fromTileX: from.tileX, |
| 986 | fromTileY: from.tileY, |
| 987 | sprite: arrowSprite, |
| 988 | ...(publicDualTint(arrowTint) ?? {}) |
| 989 | }); |
| 990 | return events; |
| 991 | } |
| 992 | |
| 993 | const hitEvents = applyLocalMeleeHit( |
| 994 | world, |
| 995 | attackerId, |
| 996 | targetId, |
| 997 | attackerHandle, |
| 998 | target.handle, |
| 999 | shotProfile, |
| 1000 | now, |
| 1001 | snapshot |
| 1002 | ); |
| 1003 | const outcome = hitEvents.find((e) => |
| 1004 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1005 | let endX = snapshot.tileX; |
| 1006 | let endY = snapshot.tileY; |
| 1007 | if (outcome?.type === "combat-miss") |
| 1008 | { |
| 1009 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1010 | endX = miss.tileX; |
| 1011 | endY = miss.tileY; |
| 1012 | } |
| 1013 | else |
| 1014 | { |
| 1015 | const currentPos = world.ecs.get(target.handle, Component.position); |
| 1016 | if (currentPos) |
| 1017 | { |
| 1018 | endX = currentPos.tileX; |
| 1019 | endY = currentPos.tileY; |
| 1020 | } |
| 1021 | } |
| 1022 | events.push({ |
| 1023 | type: "combat-projectile", |
| 1024 | attackerId, |
| 1025 | targetId, |
| 1026 | fromTileX: from.tileX, |
| 1027 | fromTileY: from.tileY, |
| 1028 | tileX: endX, |
| 1029 | tileY: endY, |
| 1030 | durationMs: RANGED_PROJECTILE_MS, |
| 1031 | trackTarget: outcome?.type !== "combat-miss", |
| 1032 | sprite: arrowSprite, |
| 1033 | ...(publicDualTint(arrowTint) ?? {}) |
| 1034 | }); |
| 1035 | return events.concat(hitEvents); |
| 1036 | } |
| 1037 | |
| 1038 | function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position) |
| 1039 | { |
| 1040 | const dest = path.tiles[path.tiles.length - 1]; |
| 1041 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 1042 | { return true; } |
| 1043 | const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); |
| 1044 | if (standOff < minStandDist || standOff > maxRange) |
| 1045 | { return true; } |
| 1046 | if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) |
| 1047 | { return true; } |
| 1048 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 1049 | { return true; } |
| 1050 | const destKey = combatTileKey(dest.x, dest.y); |
| 1051 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 1052 | { return true; } |
| 1053 | const next = path.tiles[0]; |
| 1054 | if (!next) |
| 1055 | { return true; } |
| 1056 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 1057 | { return true; } |
| 1058 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 1059 | } |
| 1060 | |
| 1061 | function meleePathStale (world, entityId, position, targetPos, path, goal, reserved) |
| 1062 | { |
| 1063 | const dest = path.tiles[path.tiles.length - 1]; |
| 1064 | if (dest.x !== goal.x || dest.y !== goal.y) |
| 1065 | { return true; } |
| 1066 | if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1) |
| 1067 | { return true; } |
| 1068 | if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) |
| 1069 | { return true; } |
| 1070 | const destKey = combatTileKey(dest.x, dest.y); |
| 1071 | if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) |
| 1072 | { return true; } |
| 1073 | const next = path.tiles[0]; |
| 1074 | if (!next) |
| 1075 | { return true; } |
| 1076 | if (!world.walkableFor(entityId, next.x, next.y)) |
| 1077 | { return true; } |
| 1078 | return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); |
| 1079 | } |
| 1080 | |
| 1081 | function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null) |
| 1082 | { |
| 1083 | const dirs = [ |
| 1084 | { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, |
| 1085 | { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } |
| 1086 | ]; |
| 1087 | let best = null; |
| 1088 | let bestDist = Infinity; |
| 1089 | let bestPref = Infinity; |
| 1090 | for (const dir of dirs) |
| 1091 | { |
| 1092 | const x = targetPos.tileX + dir.x; |
| 1093 | const y = targetPos.tileY + dir.y; |
| 1094 | const isHere = x === position.tileX && y === position.tileY; |
| 1095 | const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; |
| 1096 | const key = combatTileKey(x, y); |
| 1097 | if (reserved?.has(key) && !(isHere && aloneHere)) |
| 1098 | { continue; } |
| 1099 | const clear = world.isClearStanding?.(entityId, x, y) |
| 1100 | ?? world.walkableFor(entityId, x, y); |
| 1101 | if (!clear && !isHere) |
| 1102 | { continue; } |
| 1103 | if (isHere && !aloneHere) |
| 1104 | { continue; } |
| 1105 | const dist = chebyshev(position.tileX, position.tileY, x, y); |
| 1106 | const pref = combatGoalPreference(entityId, x, y); |
| 1107 | if (dist < bestDist || (dist === bestDist && pref < bestPref)) |
| 1108 | { |
| 1109 | bestDist = dist; |
| 1110 | bestPref = pref; |
| 1111 | best = { x, y }; |
| 1112 | } |
| 1113 | } |
| 1114 | return best; |
| 1115 | } |
| 1116 | |
| 1117 | export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now()) |
| 1118 | { |
| 1119 | const events = []; |
| 1120 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1121 | if (attackerHandle == null) |
| 1122 | { return events; } |
| 1123 | const target = resolveCombatTarget(world, targetId); |
| 1124 | if (!target) |
| 1125 | { return events; } |
| 1126 | const from = world.ecs.get(attackerHandle, Component.position); |
| 1127 | const to = target.pos; |
| 1128 | if (!from || !to) |
| 1129 | { return events; } |
| 1130 | if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1) |
| 1131 | { return events; } |
| 1132 | if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY)) |
| 1133 | { return events; } |
| 1134 | |
| 1135 | events.push({ |
| 1136 | type: "combat-swing", |
| 1137 | attackerId, |
| 1138 | targetId, |
| 1139 | tileX: to.tileX, |
| 1140 | tileY: to.tileY, |
| 1141 | fromTileX: from.tileX, |
| 1142 | fromTileY: from.tileY |
| 1143 | }); |
| 1144 | |
| 1145 | if (!target.local) |
| 1146 | { |
| 1147 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 1148 | events.push({ |
| 1149 | type: "remote-melee-resolve", |
| 1150 | attackerId, |
| 1151 | targetId, |
| 1152 | profile, |
| 1153 | attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), |
| 1154 | attackerIsPlayer: !!attackerCharacter, |
| 1155 | now, |
| 1156 | tileX: to.tileX, |
| 1157 | tileY: to.tileY |
| 1158 | }); |
| 1159 | return events; |
| 1160 | } |
| 1161 | |
| 1162 | return events.concat(applyLocalMeleeHit( |
| 1163 | world, |
| 1164 | attackerId, |
| 1165 | targetId, |
| 1166 | attackerHandle, |
| 1167 | target.handle, |
| 1168 | profile, |
| 1169 | now, |
| 1170 | to |
| 1171 | )); |
| 1172 | } |
| 1173 | |
| 1174 | /** Authoritative ranged hit when the defender lives on this worker. */ |
| 1175 | export function applyRemoteRangedShot (world, payload) |
| 1176 | { |
| 1177 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1178 | if (targetHandle == null) |
| 1179 | { return { events: [], forwards: [] }; } |
| 1180 | const snapshot = { |
| 1181 | tileX: payload.tileX, |
| 1182 | tileY: payload.tileY |
| 1183 | }; |
| 1184 | |
| 1185 | const hitEvents = applyLocalMeleeHit( |
| 1186 | world, |
| 1187 | payload.attackerId, |
| 1188 | payload.targetId, |
| 1189 | null, |
| 1190 | targetHandle, |
| 1191 | payload.profile, |
| 1192 | payload.now ?? Date.now(), |
| 1193 | snapshot, |
| 1194 | payload.attackerLevels, |
| 1195 | payload.attackerIsPlayer |
| 1196 | ); |
| 1197 | |
| 1198 | const outcome = hitEvents.find((e) => |
| 1199 | e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); |
| 1200 | let endX = snapshot.tileX; |
| 1201 | let endY = snapshot.tileY; |
| 1202 | if (outcome?.type === "combat-miss") |
| 1203 | { |
| 1204 | const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); |
| 1205 | endX = miss.tileX; |
| 1206 | endY = miss.tileY; |
| 1207 | } |
| 1208 | else |
| 1209 | { |
| 1210 | const currentPos = world.ecs.get(targetHandle, Component.position); |
| 1211 | if (currentPos) |
| 1212 | { |
| 1213 | endX = currentPos.tileX; |
| 1214 | endY = currentPos.tileY; |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | const events = [{ |
| 1219 | type: "combat-projectile", |
| 1220 | attackerId: payload.attackerId, |
| 1221 | targetId: payload.targetId, |
| 1222 | fromTileX: payload.fromTileX, |
| 1223 | fromTileY: payload.fromTileY, |
| 1224 | tileX: endX, |
| 1225 | tileY: endY, |
| 1226 | durationMs: RANGED_PROJECTILE_MS, |
| 1227 | trackTarget: outcome?.type !== "combat-miss", |
| 1228 | sprite: payload.sprite ?? "fx:projectile:arrow", |
| 1229 | shaftTint: payload.shaftTint ?? null, |
| 1230 | tipTint: payload.tipTint ?? null, |
| 1231 | coatTint: payload.coatTint ?? null |
| 1232 | }, ...hitEvents]; |
| 1233 | |
| 1234 | const forwards = []; |
| 1235 | const hitEvent = hitEvents.find((event) => event.type === "combat-hit"); |
| 1236 | if (hitEvent && payload.attackerIsPlayer) |
| 1237 | { |
| 1238 | forwards.push({ |
| 1239 | type: "forward-combat-xp", |
| 1240 | entityId: payload.attackerId, |
| 1241 | profile: payload.profile, |
| 1242 | damage: hitEvent.damage |
| 1243 | }); |
| 1244 | } |
| 1245 | return { events, forwards }; |
| 1246 | } |
| 1247 | |
| 1248 | /** Authoritative hit resolution when the defender lives on this worker. */ |
| 1249 | export function applyRemoteMeleeSwing (world, payload) |
| 1250 | { |
| 1251 | const targetHandle = world.ecs.handleOf(payload.targetId); |
| 1252 | if (targetHandle == null) |
| 1253 | { return { events: [], forwards: [] }; } |
| 1254 | const to = world.ecs.get(targetHandle, Component.position); |
| 1255 | if (!to) |
| 1256 | { return { events: [], forwards: [] }; } |
| 1257 | |
| 1258 | const events = applyLocalMeleeHit( |
| 1259 | world, |
| 1260 | payload.attackerId, |
| 1261 | payload.targetId, |
| 1262 | null, |
| 1263 | targetHandle, |
| 1264 | payload.profile, |
| 1265 | payload.now ?? Date.now(), |
| 1266 | to, |
| 1267 | payload.attackerLevels, |
| 1268 | payload.attackerIsPlayer |
| 1269 | ); |
| 1270 | |
| 1271 | const forwards = []; |
| 1272 | const hitEvent = events.find((event) => event.type === "combat-hit"); |
| 1273 | if (hitEvent && payload.attackerIsPlayer) |
| 1274 | { |
| 1275 | forwards.push({ |
| 1276 | type: "forward-combat-xp", |
| 1277 | entityId: payload.attackerId, |
| 1278 | profile: payload.profile, |
| 1279 | damage: hitEvent.damage |
| 1280 | }); |
| 1281 | } |
| 1282 | return { events, forwards }; |
| 1283 | } |
| 1284 | |
| 1285 | function applyLocalMeleeHit ( |
| 1286 | world, |
| 1287 | attackerId, |
| 1288 | targetId, |
| 1289 | attackerHandle, |
| 1290 | targetHandle, |
| 1291 | profile, |
| 1292 | now, |
| 1293 | to, |
| 1294 | attackerLevelsOverride = null, |
| 1295 | attackerIsPlayerOverride = null |
| 1296 | ) |
| 1297 | { |
| 1298 | const events = []; |
| 1299 | if (targetHandle == null) |
| 1300 | { return events; } |
| 1301 | |
| 1302 | const attackerIsPlayer = attackerIsPlayerOverride != null |
| 1303 | ? !!attackerIsPlayerOverride |
| 1304 | : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null); |
| 1305 | |
| 1306 | // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage. |
| 1307 | if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId)) |
| 1308 | { engageTarget(world.ecs, targetId, attackerId, now); } |
| 1309 | if (attackerIsPlayer === false) |
| 1310 | { |
| 1311 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1312 | if (targetCharacter) |
| 1313 | { |
| 1314 | engageTarget(world.ecs, targetId, attackerId, now); |
| 1315 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 1316 | if (follow) |
| 1317 | { |
| 1318 | follow.targetEntityId = null; |
| 1319 | follow.trail = []; |
| 1320 | } |
| 1321 | if (world.ecs.has(targetHandle, Component.gather)) |
| 1322 | { world.ecs.remove(targetHandle, Component.gather); } |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | const defenderSkills = world.ecs.get(targetHandle, Component.skills); |
| 1327 | const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); |
| 1328 | const attackerLevels = attackerLevelsOverride |
| 1329 | ?? (attackerHandle != null |
| 1330 | ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings) |
| 1331 | : null); |
| 1332 | if (!attackerLevels) |
| 1333 | { return events; } |
| 1334 | |
| 1335 | const agilityLevel = defenderSkillLevel( |
| 1336 | defenderSkills, |
| 1337 | SkillId.agility, |
| 1338 | defenderEquipment, |
| 1339 | world.settings |
| 1340 | ); |
| 1341 | const defenceLevel = defenderSkillLevel( |
| 1342 | defenderSkills, |
| 1343 | SkillId.defence, |
| 1344 | defenderEquipment, |
| 1345 | world.settings |
| 1346 | ); |
| 1347 | |
| 1348 | const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile); |
| 1349 | const targetCreature = world.ecs.get(targetHandle, Component.creature); |
| 1350 | const targetAffinities = targetCreature |
| 1351 | ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId)) |
| 1352 | : {}; |
| 1353 | const resolved = resolvePhysicalAttack({ |
| 1354 | hitSkillLevel: effectiveHitSkillInDarkness( |
| 1355 | attackerLevels.hitLevel, |
| 1356 | tileLightAt(world, to.tileX, to.tileY) |
| 1357 | ), |
| 1358 | agilitySkillLevel: agilityLevel, |
| 1359 | damageSkillLevel: attackerLevels.damageLevel, |
| 1360 | defenceSkillLevel: defenceLevel, |
| 1361 | attackType, |
| 1362 | targetAffinities |
| 1363 | }); |
| 1364 | |
| 1365 | if (resolved.outcome === "miss") |
| 1366 | { |
| 1367 | events.push({ |
| 1368 | type: "combat-miss", |
| 1369 | attackerId, |
| 1370 | targetId, |
| 1371 | tileX: to.tileX, |
| 1372 | tileY: to.tileY |
| 1373 | }); |
| 1374 | const dodgeXp = awardCombatAvoidanceXp( |
| 1375 | world.ecs, |
| 1376 | targetHandle, |
| 1377 | SkillId.agility, |
| 1378 | resolved.damageRoll |
| 1379 | ); |
| 1380 | if (dodgeXp) |
| 1381 | { |
| 1382 | events.push({ |
| 1383 | type: "skills-updated", |
| 1384 | entityId: targetId, |
| 1385 | characterId: dodgeXp.characterId, |
| 1386 | skills: dodgeXp.view, |
| 1387 | stored: dodgeXp.stored, |
| 1388 | levelUps: dodgeXp.levelUps ?? [] |
| 1389 | }); |
| 1390 | } |
| 1391 | return events; |
| 1392 | } |
| 1393 | |
| 1394 | if (resolved.outcome === "block") |
| 1395 | { |
| 1396 | events.push({ |
| 1397 | type: "combat-block", |
| 1398 | attackerId, |
| 1399 | targetId, |
| 1400 | tileX: to.tileX, |
| 1401 | tileY: to.tileY |
| 1402 | }); |
| 1403 | const blockXp = awardCombatAvoidanceXp( |
| 1404 | world.ecs, |
| 1405 | targetHandle, |
| 1406 | SkillId.defence, |
| 1407 | resolved.damageRoll |
| 1408 | ); |
| 1409 | if (blockXp) |
| 1410 | { |
| 1411 | events.push({ |
| 1412 | type: "skills-updated", |
| 1413 | entityId: targetId, |
| 1414 | characterId: blockXp.characterId, |
| 1415 | skills: blockXp.view, |
| 1416 | stored: blockXp.stored, |
| 1417 | levelUps: blockXp.levelUps ?? [] |
| 1418 | }); |
| 1419 | } |
| 1420 | return events; |
| 1421 | } |
| 1422 | |
| 1423 | const damage = resolved.damage; |
| 1424 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1425 | if (targetCharacter) |
| 1426 | { syncPlayerHealth(world.ecs, targetHandle); } |
| 1427 | const health = world.ecs.get(targetHandle, Component.health); |
| 1428 | if (health) |
| 1429 | { |
| 1430 | health.current = Math.max(0, (health.current | 0) - damage); |
| 1431 | } |
| 1432 | events.push({ |
| 1433 | type: "combat-hit", |
| 1434 | attackerId, |
| 1435 | targetId, |
| 1436 | damage, |
| 1437 | tileX: to.tileX, |
| 1438 | tileY: to.tileY, |
| 1439 | health: health?.current ?? 0, |
| 1440 | maxHealth: health?.max ?? 0 |
| 1441 | }); |
| 1442 | |
| 1443 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 1444 | if (healthXp) |
| 1445 | { |
| 1446 | events.push({ |
| 1447 | type: "skills-updated", |
| 1448 | entityId: targetId, |
| 1449 | characterId: healthXp.characterId, |
| 1450 | skills: healthXp.view, |
| 1451 | stored: healthXp.stored, |
| 1452 | levelUps: healthXp.levelUps ?? [] |
| 1453 | }); |
| 1454 | if (health) |
| 1455 | { |
| 1456 | const hitEvent = events[events.length - 2]; |
| 1457 | if (hitEvent?.type === "combat-hit") |
| 1458 | { |
| 1459 | hitEvent.health = health.current; |
| 1460 | hitEvent.maxHealth = health.max; |
| 1461 | } |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | if (attackerHandle != null) |
| 1466 | { |
| 1467 | const attackerCharacter = world.ecs.get(attackerHandle, Component.character); |
| 1468 | if (attackerCharacter) |
| 1469 | { |
| 1470 | const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage); |
| 1471 | if (xpAward) |
| 1472 | { |
| 1473 | events.push({ |
| 1474 | type: "skills-updated", |
| 1475 | entityId: attackerId, |
| 1476 | characterId: attackerCharacter.characterId, |
| 1477 | skills: xpAward.view, |
| 1478 | stored: xpAward.stored, |
| 1479 | levelUps: xpAward.levelUps ?? [] |
| 1480 | }); |
| 1481 | } |
| 1482 | } |
| 1483 | } |
| 1484 | |
| 1485 | if (health && health.current <= 0) |
| 1486 | { |
| 1487 | clearEngage(world.ecs, attackerId); |
| 1488 | clearEngage(world.ecs, targetId); |
| 1489 | for (const entity of world.ecs.query(Component.combat)) |
| 1490 | { |
| 1491 | if (entity.combat.targetEntityId === targetId) |
| 1492 | { entity.combat.targetEntityId = null; } |
| 1493 | } |
| 1494 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 1495 | { |
| 1496 | const path = world.ecs.get(targetHandle, Component.path); |
| 1497 | if (path) |
| 1498 | { path.tiles = []; } |
| 1499 | const follow = world.ecs.get(targetHandle, Component.follow); |
| 1500 | if (follow) |
| 1501 | { |
| 1502 | follow.targetEntityId = null; |
| 1503 | follow.trail = []; |
| 1504 | } |
| 1505 | world.ecs.add(targetHandle, Component.dead, {}); |
| 1506 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 1507 | events.push({ |
| 1508 | type: "player-died", |
| 1509 | entityId: targetId, |
| 1510 | attackerId, |
| 1511 | characterId: targetCharacter.characterId, |
| 1512 | sessionId: identity?.sessionId ?? null, |
| 1513 | tileX: to.tileX, |
| 1514 | tileY: to.tileY, |
| 1515 | health: 0, |
| 1516 | maxHealth: health.max |
| 1517 | }); |
| 1518 | } |
| 1519 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 1520 | if (creature && !world.ecs.get(targetHandle, Component.character)) |
| 1521 | { |
| 1522 | events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); |
| 1523 | } |
| 1524 | } |
| 1525 | return events; |
| 1526 | } |
| 1527 | |
| 1528 | /** |
| 1529 | * Drops, despawn, and `mob-killed` for bounty / town-guard reaction. |
| 1530 | * Shared by melee and spell kill paths. |
| 1531 | */ |
| 1532 | export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now) |
| 1533 | { |
| 1534 | const events = []; |
| 1535 | const handle = targetHandle ?? world.ecs.handleOf(targetId); |
| 1536 | if (handle == null) |
| 1537 | { return events; } |
| 1538 | const creature = world.ecs.get(handle, Component.creature); |
| 1539 | const origin = world.ecs.get(handle, Component.spawnOrigin); |
| 1540 | const appearance = world.ecs.get(handle, Component.appearance); |
| 1541 | events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId)); |
| 1542 | events.push({ |
| 1543 | type: "mob-killed", |
| 1544 | entityId: targetId, |
| 1545 | attackerId, |
| 1546 | mobTypeId: creature?.mobTypeId ?? null, |
| 1547 | level: creature?.level ?? origin?.level ?? 1, |
| 1548 | bounty: Math.max(0, origin?.bounty | 0 || 0), |
| 1549 | spawnerId: origin?.spawnerId ?? null, |
| 1550 | originTileX: origin?.originTileX ?? tileX, |
| 1551 | originTileY: origin?.originTileY ?? tileY, |
| 1552 | wanderRangeTiles: origin?.wanderRangeTiles ?? 0, |
| 1553 | townGuard: !!origin?.townGuard, |
| 1554 | displayName: appearance?.firstName ?? null, |
| 1555 | tileX, |
| 1556 | tileY |
| 1557 | }); |
| 1558 | if (origin?.spawnerId) |
| 1559 | { |
| 1560 | scheduleSpawnerRespawn( |
| 1561 | world, |
| 1562 | origin.spawnerId, |
| 1563 | origin.respawnDelaySeconds ?? 25, |
| 1564 | now |
| 1565 | ); |
| 1566 | } |
| 1567 | const view = world.destroyEntity?.(targetId) ?? null; |
| 1568 | if (view) |
| 1569 | { |
| 1570 | events.push({ |
| 1571 | type: "entity-despawn", |
| 1572 | entityId: targetId, |
| 1573 | tileX: view.tileX, |
| 1574 | tileY: view.tileY |
| 1575 | }); |
| 1576 | } |
| 1577 | return events; |
| 1578 | } |
| 1579 | |
| 1580 | /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */ |
| 1581 | export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now()) |
| 1582 | { |
| 1583 | const events = []; |
| 1584 | const targetHandle = world.ecs.handleOf(targetId); |
| 1585 | if (targetHandle == null) |
| 1586 | { return events; } |
| 1587 | const to = world.ecs.get(targetHandle, Component.position); |
| 1588 | if (!to) |
| 1589 | { return events; } |
| 1590 | const health = world.ecs.get(targetHandle, Component.health); |
| 1591 | if (health) |
| 1592 | { health.current = Math.max(0, (health.current | 0) - damage); } |
| 1593 | events.push({ |
| 1594 | type: "combat-hit", |
| 1595 | attackerId, |
| 1596 | targetId, |
| 1597 | damage, |
| 1598 | tileX: to.tileX, |
| 1599 | tileY: to.tileY, |
| 1600 | health: health?.current ?? 0, |
| 1601 | maxHealth: health?.max ?? 0 |
| 1602 | }); |
| 1603 | |
| 1604 | const attackerHandle = world.ecs.handleOf(attackerId); |
| 1605 | if (attackerHandle != null && ensureMobCombat(world.ecs, targetId)) |
| 1606 | { |
| 1607 | const targetCombat = world.ecs.get(targetHandle, Component.combat); |
| 1608 | if (targetCombat && targetCombat.targetEntityId == null) |
| 1609 | { engageTarget(world.ecs, targetId, attackerId, now); } |
| 1610 | } |
| 1611 | if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) |
| 1612 | { |
| 1613 | const attackerCreature = world.ecs.get(attackerHandle, Component.creature); |
| 1614 | if (attackerCreature) |
| 1615 | { |
| 1616 | engageTarget(world.ecs, targetId, attackerId, now); |
| 1617 | } |
| 1618 | } |
| 1619 | |
| 1620 | const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); |
| 1621 | if (healthXp) |
| 1622 | { |
| 1623 | events.push({ |
| 1624 | type: "skills-updated", |
| 1625 | entityId: targetId, |
| 1626 | characterId: healthXp.characterId, |
| 1627 | skills: healthXp.view, |
| 1628 | stored: healthXp.stored, |
| 1629 | levelUps: healthXp.levelUps ?? [] |
| 1630 | }); |
| 1631 | } |
| 1632 | |
| 1633 | if (health && health.current <= 0) |
| 1634 | { |
| 1635 | clearEngage(world.ecs, attackerId); |
| 1636 | clearEngage(world.ecs, targetId); |
| 1637 | for (const entity of world.ecs.query(Component.combat)) |
| 1638 | { |
| 1639 | if (entity.combat.targetEntityId === targetId) |
| 1640 | { entity.combat.targetEntityId = null; } |
| 1641 | } |
| 1642 | const targetCharacter = world.ecs.get(targetHandle, Component.character); |
| 1643 | if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) |
| 1644 | { |
| 1645 | const path = world.ecs.get(targetHandle, Component.path); |
| 1646 | if (path) |
| 1647 | { path.tiles = []; } |
| 1648 | world.ecs.add(targetHandle, Component.dead, {}); |
| 1649 | const identity = world.ecs.get(targetHandle, Component.networkIdentity); |
| 1650 | events.push({ |
| 1651 | type: "player-died", |
| 1652 | entityId: targetId, |
| 1653 | attackerId, |
| 1654 | characterId: targetCharacter.characterId, |
| 1655 | sessionId: identity?.sessionId ?? null, |
| 1656 | tileX: to.tileX, |
| 1657 | tileY: to.tileY, |
| 1658 | health: 0, |
| 1659 | maxHealth: health.max |
| 1660 | }); |
| 1661 | } |
| 1662 | const creature = world.ecs.get(targetHandle, Component.creature); |
| 1663 | if (creature && !targetCharacter) |
| 1664 | { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } |
| 1665 | } |
| 1666 | return events; |
| 1667 | } |