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