AttackPossibility.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * AttackPossibility.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 "AttackPossibility.h"
  12. #include "../../lib/CStack.h" // TODO: remove
  13. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  14. // CUnitState should be private and CStack should be removed completely
  15. uint64_t averageDmg(const DamageRange & range)
  16. {
  17. return (range.min + range.max) / 2;
  18. }
  19. void DamageCache::cacheDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb)
  20. {
  21. auto damage = averageDmg(hb->battleEstimateDamage(attacker, defender, 0).damage);
  22. damageCache[attacker->unitId()][defender->unitId()] = static_cast<float>(damage) / attacker->getCount();
  23. }
  24. void DamageCache::buildDamageCache(std::shared_ptr<HypotheticBattle> hb, int side)
  25. {
  26. auto stacks = hb->battleGetUnitsIf([=](const battle::Unit * u) -> bool
  27. {
  28. return u->isValidTarget();
  29. });
  30. std::vector<const battle::Unit *> ourUnits;
  31. std::vector<const battle::Unit *> enemyUnits;
  32. for(auto stack : stacks)
  33. {
  34. if(stack->unitSide() == side)
  35. ourUnits.push_back(stack);
  36. else
  37. enemyUnits.push_back(stack);
  38. }
  39. for(auto ourUnit : ourUnits)
  40. {
  41. if(!ourUnit->alive())
  42. continue;
  43. for(auto enemyUnit : enemyUnits)
  44. {
  45. if(enemyUnit->alive())
  46. {
  47. cacheDamage(ourUnit, enemyUnit, hb);
  48. cacheDamage(enemyUnit, ourUnit, hb);
  49. }
  50. }
  51. }
  52. }
  53. int64_t DamageCache::getDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb)
  54. {
  55. bool wasComputedBefore = damageCache[attacker->unitId()].count(defender->unitId());
  56. if (!wasComputedBefore)
  57. cacheDamage(attacker, defender, hb);
  58. return damageCache[attacker->unitId()][defender->unitId()] * attacker->getCount();
  59. }
  60. int64_t DamageCache::getOriginalDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb)
  61. {
  62. if(parent)
  63. {
  64. auto attackerDamageMap = parent->damageCache.find(attacker->unitId());
  65. if(attackerDamageMap != parent->damageCache.end())
  66. {
  67. auto targetDamage = attackerDamageMap->second.find(defender->unitId());
  68. if(targetDamage != attackerDamageMap->second.end())
  69. {
  70. return static_cast<int64_t>(targetDamage->second * attacker->getCount());
  71. }
  72. }
  73. }
  74. return getDamage(attacker, defender, hb);
  75. }
  76. AttackPossibility::AttackPossibility(BattleHex from, BattleHex dest, const BattleAttackInfo & attack)
  77. : from(from), dest(dest), attack(attack)
  78. {
  79. }
  80. float AttackPossibility::damageDiff() const
  81. {
  82. return defenderDamageReduce - attackerDamageReduce - collateralDamageReduce + shootersBlockedDmg;
  83. }
  84. float AttackPossibility::damageDiff(float positiveEffectMultiplier, float negativeEffectMultiplier) const
  85. {
  86. return positiveEffectMultiplier * (defenderDamageReduce + shootersBlockedDmg)
  87. - negativeEffectMultiplier * (attackerDamageReduce + collateralDamageReduce);
  88. }
  89. float AttackPossibility::attackValue() const
  90. {
  91. return damageDiff();
  92. }
  93. float hpFunction(uint64_t unitHealthStart, uint64_t unitHealthEnd, uint64_t maxHealth)
  94. {
  95. float ratioStart = static_cast<float>(unitHealthStart) / maxHealth;
  96. float ratioEnd = static_cast<float>(unitHealthEnd) / maxHealth;
  97. float base = 0.666666f;
  98. // reduce from max to 0 must be 1.
  99. // 10 hp from end costs bit more than 10 hp from start because our goal is to kill unit, not just hurt it
  100. // ********** 2 * base - ratioStart *********
  101. // * *
  102. // * height = ratioStart - ratioEnd *
  103. // * *
  104. // ******************** 2 * base - ratioEnd ******
  105. // S = (a + b) * h / 2
  106. return (base * (4 - ratioStart - ratioEnd)) * (ratioStart - ratioEnd) / 2 ;
  107. }
  108. /// <summary>
  109. /// How enemy damage will be reduced by this attack
  110. /// Half bounty for kill, half for making damage equal to enemy health
  111. /// Bounty - the killed creature average damage calculated against attacker
  112. /// </summary>
  113. float AttackPossibility::calculateDamageReduce(
  114. const battle::Unit * attacker,
  115. const battle::Unit * defender,
  116. uint64_t damageDealt,
  117. DamageCache & damageCache,
  118. std::shared_ptr<CBattleInfoCallback> state)
  119. {
  120. const float HEALTH_BOUNTY = 0.5;
  121. const float KILL_BOUNTY = 0.5;
  122. // FIXME: provide distance info for Jousting bonus
  123. auto attackerUnitForMeasurement = attacker;
  124. if(!attackerUnitForMeasurement || attackerUnitForMeasurement->isTurret())
  125. {
  126. auto ourUnits = state->battleGetUnitsIf([&](const battle::Unit * u) -> bool
  127. {
  128. return u->unitSide() != defender->unitSide()
  129. && !u->isTurret()
  130. && u->creatureId() != CreatureID::CATAPULT
  131. && u->creatureId() != CreatureID::BALLISTA
  132. && u->creatureId() != CreatureID::FIRST_AID_TENT
  133. && u->getCount();
  134. });
  135. if(ourUnits.empty())
  136. attackerUnitForMeasurement = defender;
  137. else
  138. attackerUnitForMeasurement = ourUnits.front();
  139. }
  140. auto maxHealth = defender->getMaxHealth();
  141. auto availableHealth = defender->getFirstHPleft() + ((defender->getCount() - 1) * maxHealth);
  142. vstd::amin(damageDealt, availableHealth);
  143. auto enemyDamageBeforeAttack = damageCache.getOriginalDamage(defender, attackerUnitForMeasurement, state);
  144. auto enemiesKilled = damageDealt / maxHealth + (damageDealt % maxHealth >= defender->getFirstHPleft() ? 1 : 0);
  145. auto damagePerEnemy = enemyDamageBeforeAttack / (double)defender->getCount();
  146. auto exceedingDamage = (damageDealt % maxHealth);
  147. float hpValue = (damageDealt / maxHealth);
  148. if(defender->getFirstHPleft() >= exceedingDamage)
  149. {
  150. hpValue += hpFunction(defender->getFirstHPleft(), defender->getFirstHPleft() - exceedingDamage, maxHealth);
  151. }
  152. else
  153. {
  154. hpValue += hpFunction(defender->getFirstHPleft(), 0, maxHealth);
  155. hpValue += hpFunction(maxHealth, maxHealth + defender->getFirstHPleft() - exceedingDamage, maxHealth);
  156. }
  157. return damagePerEnemy * (enemiesKilled * KILL_BOUNTY + hpValue * HEALTH_BOUNTY);
  158. }
  159. int64_t AttackPossibility::evaluateBlockedShootersDmg(
  160. const BattleAttackInfo & attackInfo,
  161. BattleHex hex,
  162. DamageCache & damageCache,
  163. std::shared_ptr<CBattleInfoCallback> state)
  164. {
  165. int64_t res = 0;
  166. if(attackInfo.shooting)
  167. return 0;
  168. auto attacker = attackInfo.attacker;
  169. auto hexes = attacker->getSurroundingHexes(hex);
  170. for(BattleHex tile : hexes)
  171. {
  172. auto st = state->battleGetUnitByPos(tile, true);
  173. if(!st || !state->battleMatchOwner(st, attacker))
  174. continue;
  175. if(!state->battleCanShoot(st))
  176. continue;
  177. // FIXME: provide distance info for Jousting bonus
  178. BattleAttackInfo rangeAttackInfo(st, attacker, 0, true);
  179. rangeAttackInfo.defenderPos = hex;
  180. BattleAttackInfo meleeAttackInfo(st, attacker, 0, false);
  181. meleeAttackInfo.defenderPos = hex;
  182. auto rangeDmg = state->battleEstimateDamage(rangeAttackInfo);
  183. auto meleeDmg = state->battleEstimateDamage(meleeAttackInfo);
  184. int64_t gain = averageDmg(rangeDmg.damage) - averageDmg(meleeDmg.damage) + 1;
  185. res += gain;
  186. }
  187. return res;
  188. }
  189. AttackPossibility AttackPossibility::evaluate(
  190. const BattleAttackInfo & attackInfo,
  191. BattleHex hex,
  192. DamageCache & damageCache,
  193. std::shared_ptr<CBattleInfoCallback> state)
  194. {
  195. auto attacker = attackInfo.attacker;
  196. auto defender = attackInfo.defender;
  197. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  198. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  199. const auto attackerSide = state->playerToSide(state->battleGetOwner(attacker));
  200. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  201. AttackPossibility bestAp(hex, BattleHex::INVALID, attackInfo);
  202. std::vector<BattleHex> defenderHex;
  203. if(attackInfo.shooting)
  204. defenderHex = defender->getHexes();
  205. else
  206. defenderHex = CStack::meleeAttackHexes(attacker, defender, hex);
  207. for(BattleHex defHex : defenderHex)
  208. {
  209. if(defHex == hex) // should be impossible but check anyway
  210. continue;
  211. AttackPossibility ap(hex, defHex, attackInfo);
  212. ap.attackerState = attacker->acquireState();
  213. ap.shootersBlockedDmg = bestAp.shootersBlockedDmg;
  214. const int totalAttacks = ap.attackerState->getTotalAttacks(attackInfo.shooting);
  215. if (!attackInfo.shooting)
  216. ap.attackerState->setPosition(hex);
  217. std::vector<const battle::Unit*> units;
  218. if (attackInfo.shooting)
  219. units = state->getAttackedBattleUnits(attacker, defHex, true, BattleHex::INVALID);
  220. else
  221. units = state->getAttackedBattleUnits(attacker, defHex, false, hex);
  222. // ensure the defender is also affected
  223. bool addDefender = true;
  224. for(auto unit : units)
  225. {
  226. if (unit->unitId() == defender->unitId())
  227. {
  228. addDefender = false;
  229. break;
  230. }
  231. }
  232. if(addDefender)
  233. units.push_back(defender);
  234. for(auto u : units)
  235. {
  236. if(!ap.attackerState->alive())
  237. break;
  238. auto defenderState = u->acquireState();
  239. ap.affectedUnits.push_back(defenderState);
  240. for(int i = 0; i < totalAttacks; i++)
  241. {
  242. int64_t damageDealt;
  243. int64_t damageReceived;
  244. float defenderDamageReduce;
  245. float attackerDamageReduce;
  246. DamageEstimation retaliation;
  247. auto attackDmg = state->battleEstimateDamage(ap.attack, &retaliation);
  248. vstd::amin(attackDmg.damage.min, defenderState->getAvailableHealth());
  249. vstd::amin(attackDmg.damage.max, defenderState->getAvailableHealth());
  250. vstd::amin(retaliation.damage.min, ap.attackerState->getAvailableHealth());
  251. vstd::amin(retaliation.damage.max, ap.attackerState->getAvailableHealth());
  252. damageDealt = averageDmg(attackDmg.damage);
  253. defenderDamageReduce = calculateDamageReduce(attacker, defender, damageDealt, damageCache, state);
  254. ap.attackerState->afterAttack(attackInfo.shooting, false);
  255. //FIXME: use ranged retaliation
  256. damageReceived = 0;
  257. attackerDamageReduce = 0;
  258. if (!attackInfo.shooting && defenderState->ableToRetaliate() && !counterAttacksBlocked)
  259. {
  260. damageReceived = averageDmg(retaliation.damage);
  261. attackerDamageReduce = calculateDamageReduce(defender, attacker, damageReceived, damageCache, state);
  262. defenderState->afterAttack(attackInfo.shooting, true);
  263. }
  264. bool isEnemy = state->battleMatchOwner(attacker, u);
  265. // this includes enemy units as well as attacker units under enemy's mind control
  266. if(isEnemy)
  267. ap.defenderDamageReduce += defenderDamageReduce;
  268. // damaging attacker's units (even those under enemy's mind control) is considered friendly fire
  269. if(attackerSide == u->unitSide())
  270. ap.collateralDamageReduce += defenderDamageReduce;
  271. if(u->unitId() == defender->unitId() ||
  272. (!attackInfo.shooting && CStack::isMeleeAttackPossible(u, attacker, hex)))
  273. {
  274. //FIXME: handle RANGED_RETALIATION ?
  275. ap.attackerDamageReduce += attackerDamageReduce;
  276. }
  277. ap.attackerState->damage(damageReceived);
  278. defenderState->damage(damageDealt);
  279. if (!ap.attackerState->alive() || !defenderState->alive())
  280. break;
  281. }
  282. }
  283. if(!bestAp.dest.isValid() || ap.attackValue() > bestAp.attackValue())
  284. bestAp = ap;
  285. }
  286. // check how much damage we gain from blocking enemy shooters on this hex
  287. bestAp.shootersBlockedDmg = evaluateBlockedShootersDmg(attackInfo, hex, damageCache, state);
  288. #if BATTLE_TRACE_LEVEL>=1
  289. logAi->trace("BattleAI best AP: %s -> %s at %d from %d, affects %d units: d:%lld a:%lld c:%lld s:%lld",
  290. attackInfo.attacker->unitType()->getJsonKey(),
  291. attackInfo.defender->unitType()->getJsonKey(),
  292. (int)bestAp.dest, (int)bestAp.from, (int)bestAp.affectedUnits.size(),
  293. bestAp.defenderDamageReduce, bestAp.attackerDamageReduce, bestAp.collateralDamageReduce, bestAp.shootersBlockedDmg);
  294. #endif
  295. //TODO other damage related to attack (eg. fire shield and other abilities)
  296. return bestAp;
  297. }