2
0

AttackPossibility.cpp 12 KB

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