DamageCalculator.cpp 16 KB

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