DamageCalculator.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * DamageCalculator.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "DamageCalculator.h"
  12. #include "CBattleInfoCallback.h"
  13. #include "Unit.h"
  14. #include "../HeroBonus.h"
  15. #include "../mapObjects/CGTownInstance.h"
  16. #include "../spells/CSpellHandler.h"
  17. #include "../CModHandler.h"
  18. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  19. {
  20. static void retrieveTurretDamageRange(const CGTownInstance * town, const battle::Unit * turret, double & outMinDmg, double & outMaxDmg)
  21. {
  22. // http://heroes.thelazy.net/wiki/Arrow_tower
  23. assert(turret->creatureIndex() == CreatureID::ARROW_TOWERS);
  24. assert(town);
  25. assert(turret->getPosition() >= -4 && turret->getPosition() <= -2);
  26. // base damage, irregardless of town level
  27. static const int baseDamageKeep = 10;
  28. static const int baseDamageTower = 6;
  29. // extra damage, for each building in town
  30. static const int extraDamage = 2;
  31. const int townLevel = town->getTownLevel();
  32. int minDamage;
  33. if (turret->getPosition() == BattleHex::CASTLE_CENTRAL_TOWER)
  34. minDamage = baseDamageKeep + townLevel * extraDamage;
  35. else
  36. minDamage = baseDamageTower + townLevel / 2 * extraDamage;
  37. outMinDmg = minDamage;
  38. outMaxDmg = minDamage * 2;
  39. }
  40. }
  41. TDmgRange DamageCalculator::getBaseDamageSingle() const
  42. {
  43. double minDmg = 0.0;
  44. double maxDmg = 0.0;
  45. minDmg = info.attacker->getMinDamage(info.shooting);
  46. maxDmg = info.attacker->getMaxDamage(info.shooting);
  47. if(info.attacker->creatureIndex() == CreatureID::ARROW_TOWERS)
  48. SiegeStuffThatShouldBeMovedToHandlers::retrieveTurretDamageRange(callback.battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  49. const std::string cachingStrSiedgeWeapon = "type_SIEGE_WEAPON";
  50. static const auto selectorSiedgeWeapon = Selector::type()(Bonus::SIEGE_WEAPON);
  51. if(info.attacker->hasBonus(selectorSiedgeWeapon, cachingStrSiedgeWeapon) && info.attacker->creatureIndex() != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  52. { //minDmg and maxDmg are multiplied by hero attack + 1
  53. auto retrieveHeroPrimSkill = [&](int skill) -> int
  54. {
  55. std::shared_ptr<const Bonus> b = info.attacker->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  56. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  57. };
  58. minDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  59. maxDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  60. }
  61. return { minDmg, maxDmg };
  62. }
  63. TDmgRange DamageCalculator::getBaseDamageBlessCurse() const
  64. {
  65. const std::string cachingStrForcedMinDamage = "type_ALWAYS_MINIMUM_DAMAGE";
  66. static const auto selectorForcedMinDamage = Selector::type()(Bonus::ALWAYS_MINIMUM_DAMAGE);
  67. const std::string cachingStrForcedMaxDamage = "type_ALWAYS_MAXIMUM_DAMAGE";
  68. static const auto selectorForcedMaxDamage = Selector::type()(Bonus::ALWAYS_MAXIMUM_DAMAGE);
  69. TConstBonusListPtr curseEffects = info.attacker->getBonuses(selectorForcedMinDamage, cachingStrForcedMinDamage);
  70. TConstBonusListPtr blessEffects = info.attacker->getBonuses(selectorForcedMaxDamage, cachingStrForcedMaxDamage);
  71. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  72. TDmgRange baseDamage = getBaseDamageSingle();
  73. TDmgRange modifiedDamage = {
  74. std::max( int64_t(1), baseDamage.first + curseBlessAdditiveModifier),
  75. std::max( int64_t(1), baseDamage.second + curseBlessAdditiveModifier)
  76. };
  77. if ( curseEffects->size() && blessEffects->size() )
  78. {
  79. logGlobal->warn("Stack has both curse and bless! Effects will negate each other!");
  80. return modifiedDamage;
  81. }
  82. if(curseEffects->size())
  83. {
  84. return {
  85. modifiedDamage.first,
  86. modifiedDamage.first
  87. };
  88. }
  89. if(blessEffects->size())
  90. {
  91. return {
  92. modifiedDamage.second,
  93. modifiedDamage.second
  94. };
  95. }
  96. return modifiedDamage;
  97. }
  98. TDmgRange DamageCalculator::getBaseDamageStack() const
  99. {
  100. auto stackSize = info.attacker->getCount();
  101. auto baseDamage = getBaseDamageBlessCurse();
  102. return {
  103. baseDamage.first * stackSize,
  104. baseDamage.second * stackSize
  105. };
  106. }
  107. int DamageCalculator::getActorAttackBase() const
  108. {
  109. return info.attacker->getAttack(info.shooting);
  110. }
  111. int DamageCalculator::getActorAttackEffective() const
  112. {
  113. return getActorAttackBase() + getActorAttackSlayer();
  114. }
  115. int DamageCalculator::getActorAttackSlayer() const
  116. {
  117. const std::string cachingStrSlayer = "type_SLAYER";
  118. static const auto selectorSlayer = Selector::type()(Bonus::SLAYER);
  119. auto slayerEffects = info.attacker->getBonuses(selectorSlayer, cachingStrSlayer);
  120. if(std::shared_ptr<const Bonus> slayerEffect = slayerEffects->getFirst(Selector::all))
  121. {
  122. std::vector<int32_t> affectedIds;
  123. const auto spLevel = slayerEffect->val;
  124. const CCreature * defenderType = info.defender->unitType();
  125. bool isAffected = false;
  126. for(const auto & b : defenderType->getBonusList())
  127. {
  128. if((b->type == Bonus::KING3 && spLevel >= 3) || //expert
  129. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  130. (b->type == Bonus::KING1 && spLevel >= 0)) //none or basic +
  131. {
  132. isAffected = true;
  133. break;
  134. }
  135. }
  136. if(isAffected)
  137. {
  138. int attackBonus = SpellID(SpellID::SLAYER).toSpell()->getLevelPower(spLevel);
  139. if(info.attacker->hasBonusOfType(Bonus::SPECIAL_PECULIAR_ENCHANT, SpellID::SLAYER))
  140. {
  141. ui8 attackerTier = info.attacker->unitType()->level;
  142. ui8 specialtyBonus = std::max(5 - attackerTier, 0);
  143. attackBonus += specialtyBonus;
  144. }
  145. return attackBonus;
  146. }
  147. }
  148. return 0;
  149. }
  150. int DamageCalculator::getTargetDefenseBase() const
  151. {
  152. return info.defender->getDefense(info.shooting);
  153. }
  154. int DamageCalculator::getTargetDefenseEffective() const
  155. {
  156. return getTargetDefenseBase() + getTargetDefenseIgnored();
  157. }
  158. int DamageCalculator::getTargetDefenseIgnored() const
  159. {
  160. double multDefenceReduction = battleBonusValue(info.attacker, Selector::type()(Bonus::ENEMY_DEFENCE_REDUCTION)) / 100.0;
  161. if(multDefenceReduction > 0)
  162. {
  163. int reduction = std::floor(multDefenceReduction * getTargetDefenseBase()) + 1;
  164. return -std::min(reduction,getTargetDefenseBase());
  165. }
  166. return 0;
  167. }
  168. double DamageCalculator::getAttackSkillFactor() const
  169. {
  170. int attackAdvantage = getActorAttackEffective() - getTargetDefenseEffective();
  171. if (attackAdvantage > 0)
  172. {
  173. const double attackMultiplier = VLC->modh->settings.ATTACK_POINT_DMG_MULTIPLIER;
  174. const double attackMultiplierCap = VLC->modh->settings.ATTACK_POINTS_DMG_MULTIPLIER_CAP;
  175. const double attackFactor = std::min(attackMultiplier * attackAdvantage, attackMultiplierCap);
  176. return attackFactor;
  177. }
  178. return 0.f;
  179. }
  180. double DamageCalculator::getAttackBlessFactor() const
  181. {
  182. const std::string cachingStrDamage = "type_GENERAL_DAMAGE_PREMY";
  183. static const auto selectorDamage = Selector::type()(Bonus::GENERAL_DAMAGE_PREMY);
  184. return info.attacker->valOfBonuses(selectorDamage, cachingStrDamage) / 100.0;
  185. }
  186. double DamageCalculator::getAttackOffenseArcheryFactor() const
  187. {
  188. if(info.shooting)
  189. {
  190. const std::string cachingStrArchery = "type_SECONDARY_SKILL_PREMYs_ARCHERY";
  191. static const auto selectorArchery = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY);
  192. return info.attacker->valOfBonuses(selectorArchery, cachingStrArchery) / 100.0;
  193. }
  194. else
  195. {
  196. const std::string cachingStrOffence = "type_SECONDARY_SKILL_PREMYs_OFFENCE";
  197. static const auto selectorOffence = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE);
  198. return info.attacker->valOfBonuses(selectorOffence, cachingStrOffence) / 100.0;
  199. }
  200. }
  201. double DamageCalculator::getAttackLuckFactor() const
  202. {
  203. if (info.luckyStrike)
  204. return 1.0;
  205. return 0.0;
  206. }
  207. double DamageCalculator::getAttackDeathBlowFactor() const
  208. {
  209. if (info.deathBlow)
  210. return 1.0;
  211. return 0.0;
  212. }
  213. double DamageCalculator::getAttackDoubleDamageFactor() const
  214. {
  215. if (info.doubleDamage)
  216. return 1.0;
  217. return 0.0;
  218. }
  219. double DamageCalculator::getAttackJoustingFactor() const
  220. {
  221. const std::string cachingStrJousting = "type_JOUSTING";
  222. static const auto selectorJousting = Selector::type()(Bonus::JOUSTING);
  223. const std::string cachingStrChargeImmunity = "type_CHARGE_IMMUNITY";
  224. static const auto selectorChargeImmunity = Selector::type()(Bonus::CHARGE_IMMUNITY);
  225. //applying jousting bonus
  226. if(info.chargeDistance > 0 && info.attacker->hasBonus(selectorJousting, cachingStrJousting) && !info.defender->hasBonus(selectorChargeImmunity, cachingStrChargeImmunity))
  227. return info.chargeDistance * 0.05;
  228. return 0.0;
  229. }
  230. double DamageCalculator::getAttackHateFactor() const
  231. {
  232. //assume that unit have only few HATE features and cache them all
  233. const std::string cachingStrHate = "type_HATE";
  234. static const auto selectorHate = Selector::type()(Bonus::HATE);
  235. auto allHateEffects = info.attacker->getBonuses(selectorHate, cachingStrHate);
  236. return allHateEffects->valOfBonuses(Selector::subtype()(info.defender->creatureIndex())) / 100.0;
  237. }
  238. double DamageCalculator::getDefenseSkillFactor() const
  239. {
  240. int defenseAdvantage = getTargetDefenseEffective() - getActorAttackEffective();
  241. //bonus from attack/defense skills
  242. if(defenseAdvantage > 0) //decreasing dmg
  243. {
  244. const double defenseMultiplier = VLC->modh->settings.DEFENSE_POINT_DMG_MULTIPLIER;
  245. const double defenseMultiplierCap = VLC->modh->settings.DEFENSE_POINTS_DMG_MULTIPLIER_CAP;
  246. const double dec = std::min(defenseMultiplier * defenseAdvantage, defenseMultiplierCap);
  247. return dec;
  248. }
  249. return 0.0;
  250. }
  251. double DamageCalculator::getDefenseArmorerFactor() const
  252. {
  253. const std::string cachingStrArmorer = "type_SECONDARY_SKILL_PREMYs_ARMORER";
  254. static const auto selectorArmorer = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER);
  255. return info.defender->valOfBonuses(selectorArmorer, cachingStrArmorer) / 100.0;
  256. }
  257. double DamageCalculator::getDefenseMagicShieldFactor() const
  258. {
  259. const std::string cachingStrMeleeReduction = "type_GENERAL_DAMAGE_REDUCTIONs_0";
  260. static const auto selectorMeleeReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 0);
  261. const std::string cachingStrRangedReduction = "type_GENERAL_DAMAGE_REDUCTIONs_1";
  262. static const auto selectorRangedReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 1);
  263. //handling spell effects - shield and air shield
  264. if(info.shooting)
  265. return info.defender->valOfBonuses(selectorRangedReduction, cachingStrRangedReduction) / 100.0;
  266. else
  267. return info.defender->valOfBonuses(selectorMeleeReduction, cachingStrMeleeReduction) / 100.0;
  268. }
  269. double DamageCalculator::getDefenseRangePenaltiesFactor() const
  270. {
  271. if(info.shooting)
  272. {
  273. BattleHex attackerPos = info.attackerPos.isValid() ? info.attackerPos : info.attacker->getPosition();
  274. BattleHex defenderPos = info.defenderPos.isValid() ? info.defenderPos : info.defender->getPosition();
  275. const std::string cachingStrAdvAirShield = "isAdvancedAirShield";
  276. auto isAdvancedAirShield = [](const Bonus* bonus)
  277. {
  278. return bonus->source == Bonus::SPELL_EFFECT
  279. && bonus->sid == SpellID::AIR_SHIELD
  280. && bonus->val >= SecSkillLevel::ADVANCED;
  281. };
  282. const bool distPenalty = callback.battleHasDistancePenalty(info.attacker, attackerPos, defenderPos);
  283. if(distPenalty || info.defender->hasBonus(isAdvancedAirShield, cachingStrAdvAirShield))
  284. return 0.5;
  285. }
  286. else
  287. {
  288. const std::string cachingStrNoMeleePenalty = "type_NO_MELEE_PENALTY";
  289. static const auto selectorNoMeleePenalty = Selector::type()(Bonus::NO_MELEE_PENALTY);
  290. if(info.attacker->isShooter() && !info.attacker->hasBonus(selectorNoMeleePenalty, cachingStrNoMeleePenalty))
  291. return 0.5;
  292. }
  293. return 0.0;
  294. }
  295. double DamageCalculator::getDefenseObstacleFactor() const
  296. {
  297. if(info.shooting)
  298. {
  299. BattleHex attackerPos = info.attackerPos.isValid() ? info.attackerPos : info.attacker->getPosition();
  300. BattleHex defenderPos = info.defenderPos.isValid() ? info.defenderPos : info.defender->getPosition();
  301. const bool obstaclePenalty = callback.battleHasWallPenalty(info.attacker, attackerPos, defenderPos);
  302. if(obstaclePenalty)
  303. return 0.5;
  304. }
  305. return 0.0;
  306. }
  307. double DamageCalculator::getDefenseUnluckyFactor() const
  308. {
  309. if (info.unluckyStrike)
  310. return 0.5;
  311. return 0.0;
  312. }
  313. double DamageCalculator::getDefenseBlindParalysisFactor() const
  314. {
  315. double multAttackReduction = battleBonusValue(info.attacker, Selector::type()(Bonus::GENERAL_ATTACK_REDUCTION)) / 100.0;
  316. return multAttackReduction;
  317. }
  318. double DamageCalculator::getDefenseForgetfulnessFactor() const
  319. {
  320. if(info.shooting)
  321. {
  322. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  323. //get list first, total value of 0 also counts
  324. TConstBonusListPtr forgetfulList = info.attacker->getBonuses(Selector::type()(Bonus::FORGETFULL),"type_FORGETFULL");
  325. if(!forgetfulList->empty())
  326. {
  327. int forgetful = forgetfulList->valOfBonuses(Selector::all);
  328. //none of basic level
  329. if(forgetful == 0 || forgetful == 1)
  330. return 0.5;
  331. else
  332. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  333. }
  334. }
  335. return 0.0;
  336. }
  337. double DamageCalculator::getDefensePetrificationFactor() const
  338. {
  339. // Creatures that are petrified by a Basilisk's Petrifying attack or a Medusa's Stone gaze take 50% damage (R8 = 0.50) from ranged and melee attacks. Taking damage also deactivates the effect.
  340. const std::string cachingStrAllReduction = "type_GENERAL_DAMAGE_REDUCTIONs_N1";
  341. static const auto selectorAllReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, -1);
  342. return info.defender->valOfBonuses(selectorAllReduction, cachingStrAllReduction) / 100.0;
  343. }
  344. double DamageCalculator::getDefenseMagicFactor() const
  345. {
  346. // Magic Elementals deal half damage (R8 = 0.50) against Magic Elementals and Black Dragons. This is not affected by the Orb of Vulnerability, Anti-Magic, or Magic Resistance.
  347. if(info.attacker->creatureIndex() == CreatureID::MAGIC_ELEMENTAL)
  348. {
  349. const std::string cachingStrMagicImmunity = "type_LEVEL_SPELL_IMMUNITY";
  350. static const auto selectorMagicImmunity = Selector::type()(Bonus::LEVEL_SPELL_IMMUNITY);
  351. if(info.defender->valOfBonuses(selectorMagicImmunity, cachingStrMagicImmunity) >= 5)
  352. return 0.5;
  353. }
  354. return 0.0;
  355. }
  356. double DamageCalculator::getDefenseMindFactor() const
  357. {
  358. // Psychic Elementals deal half damage (R8 = 0.50) against creatures that are immune to Mind spells, such as Giants and Undead. This is not affected by the Orb of Vulnerability.
  359. if(info.attacker->creatureIndex() == CreatureID::PSYCHIC_ELEMENTAL)
  360. {
  361. const std::string cachingStrMindImmunity = "type_MIND_IMMUNITY";
  362. static const auto selectorMindImmunity = Selector::type()(Bonus::MIND_IMMUNITY);
  363. if(info.defender->hasBonus(selectorMindImmunity, cachingStrMindImmunity))
  364. return 0.5;
  365. }
  366. return 0.0;
  367. }
  368. std::vector<double> DamageCalculator::getAttackFactors() const
  369. {
  370. return {
  371. getAttackSkillFactor(),
  372. getAttackOffenseArcheryFactor(),
  373. getAttackBlessFactor(),
  374. getAttackLuckFactor(),
  375. getAttackJoustingFactor(),
  376. getAttackDeathBlowFactor(),
  377. getAttackDoubleDamageFactor(),
  378. getAttackHateFactor()
  379. };
  380. }
  381. std::vector<double> DamageCalculator::getDefenseFactors() const
  382. {
  383. return {
  384. getDefenseSkillFactor(),
  385. getDefenseArmorerFactor(),
  386. getDefenseMagicShieldFactor(),
  387. getDefenseRangePenaltiesFactor(),
  388. getDefenseObstacleFactor(),
  389. getDefenseBlindParalysisFactor(),
  390. getDefenseUnluckyFactor(),
  391. getDefenseForgetfulnessFactor(),
  392. getDefensePetrificationFactor(),
  393. getDefenseMagicFactor(),
  394. getDefenseMindFactor()
  395. };
  396. }
  397. int DamageCalculator::battleBonusValue(const IBonusBearer * bearer, const CSelector & selector) const
  398. {
  399. auto noLimit = Selector::effectRange()(Bonus::NO_LIMIT);
  400. auto limitMatches = info.shooting
  401. ? Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT)
  402. : Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT);
  403. //any regular bonuses or just ones for melee/ranged
  404. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  405. };
  406. TDmgRange DamageCalculator::calculateDmgRange() const
  407. {
  408. TDmgRange result = getBaseDamageStack();
  409. auto attackFactors = getAttackFactors();
  410. auto defenseFactors = getDefenseFactors();
  411. double attackFactorTotal = 1.0;
  412. double defenseFactorTotal = 1.0;
  413. for (auto & factor : attackFactors)
  414. {
  415. assert(factor >= 0.0);
  416. attackFactorTotal += factor;
  417. }
  418. for (auto & factor : defenseFactors)
  419. {
  420. assert(factor >= 0.0);
  421. defenseFactorTotal *= ( 1 - std::min(1.0, factor));
  422. }
  423. double resultingFactor = std::min(8.0, attackFactorTotal) * std::max( 0.01, defenseFactorTotal);
  424. return {
  425. std::max( 1.0, std::floor(result.first * resultingFactor)),
  426. std::max( 1.0, std::floor(result.second * resultingFactor))
  427. };
  428. }