2
0

BattleExchangeVariant.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. /*
  2. * BattleAI.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 "BattleExchangeVariant.h"
  12. #include "BattleEvaluator.h"
  13. #include "../../lib/CStack.h"
  14. #include "../../lib/GameLibrary.h"
  15. #include <tbb/parallel_for.h>
  16. AttackerValue::AttackerValue()
  17. : value(0),
  18. isRetaliated(false)
  19. {
  20. }
  21. MoveTarget::MoveTarget()
  22. : positions(), cachedAttack(), score(EvaluationResult::INEFFECTIVE_SCORE)
  23. {
  24. turnsToReach = 1;
  25. }
  26. float BattleExchangeVariant::trackAttack(
  27. const AttackPossibility & ap,
  28. std::shared_ptr<HypotheticBattle> hb,
  29. DamageCache & damageCache)
  30. {
  31. if(!ap.attackerState)
  32. {
  33. logAi->trace("Skipping fake ap attack");
  34. return 0;
  35. }
  36. auto attacker = hb->getForUpdate(ap.attack.attacker->unitId());
  37. float attackValue = ap.attackValue();
  38. auto affectedUnits = ap.affectedUnits;
  39. dpsScore.ourDamageReduce += ap.attackerDamageReduce + ap.collateralDamageReduce;
  40. dpsScore.enemyDamageReduce += ap.defenderDamageReduce + ap.shootersBlockedDmg;
  41. attackerValue[attacker->unitId()].value = attackValue;
  42. affectedUnits.push_back(ap.attackerState);
  43. for(auto affectedUnit : affectedUnits)
  44. {
  45. auto unitToUpdate = hb->getForUpdate(affectedUnit->unitId());
  46. auto damageDealt = unitToUpdate->getAvailableHealth() - affectedUnit->getAvailableHealth();
  47. if(damageDealt > 0)
  48. {
  49. unitToUpdate->damage(damageDealt);
  50. }
  51. if(unitToUpdate->unitSide() == attacker->unitSide())
  52. {
  53. if(unitToUpdate->unitId() == attacker->unitId())
  54. {
  55. unitToUpdate->afterAttack(ap.attack.shooting, false);
  56. #if BATTLE_TRACE_LEVEL>=1
  57. logAi->trace(
  58. "%s -> %s, ap retaliation, %s, dps: %lld",
  59. hb->getForUpdate(ap.attack.defender->unitId())->getDescription(),
  60. ap.attack.attacker->getDescription(),
  61. ap.attack.shooting ? "shot" : "mellee",
  62. damageDealt);
  63. #endif
  64. }
  65. else
  66. {
  67. #if BATTLE_TRACE_LEVEL>=1
  68. logAi->trace(
  69. "%s, ap collateral, dps: %lld",
  70. unitToUpdate->getDescription(),
  71. damageDealt);
  72. #endif
  73. }
  74. }
  75. else
  76. {
  77. if(unitToUpdate->unitId() == ap.attack.defender->unitId())
  78. {
  79. if(unitToUpdate->ableToRetaliate() && !affectedUnit->ableToRetaliate())
  80. {
  81. unitToUpdate->afterAttack(ap.attack.shooting, true);
  82. }
  83. #if BATTLE_TRACE_LEVEL>=1
  84. logAi->trace(
  85. "%s -> %s, ap attack, %s, dps: %lld",
  86. attacker->getDescription(),
  87. ap.attack.defender->getDescription(),
  88. ap.attack.shooting ? "shot" : "mellee",
  89. damageDealt);
  90. #endif
  91. }
  92. else
  93. {
  94. #if BATTLE_TRACE_LEVEL>=1
  95. logAi->trace(
  96. "%s, ap enemy collateral, dps: %lld",
  97. unitToUpdate->getDescription(),
  98. damageDealt);
  99. #endif
  100. }
  101. }
  102. }
  103. #if BATTLE_TRACE_LEVEL >= 1
  104. logAi->trace(
  105. "ap score: our: %2f, enemy: %2f, collateral: %2f, blocked: %2f",
  106. ap.attackerDamageReduce,
  107. ap.defenderDamageReduce,
  108. ap.collateralDamageReduce,
  109. ap.shootersBlockedDmg);
  110. #endif
  111. return attackValue;
  112. }
  113. float BattleExchangeVariant::trackAttack(
  114. std::shared_ptr<StackWithBonuses> attacker,
  115. std::shared_ptr<StackWithBonuses> defender,
  116. bool shooting,
  117. bool isOurAttack,
  118. DamageCache & damageCache,
  119. std::shared_ptr<HypotheticBattle> hb,
  120. bool evaluateOnly)
  121. {
  122. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  123. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  124. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  125. int64_t attackDamage = damageCache.getDamage(attacker.get(), defender.get(), hb);
  126. float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), defender.get(), attackDamage, damageCache, hb);
  127. float attackerDamageReduce = 0;
  128. if(!evaluateOnly)
  129. {
  130. #if BATTLE_TRACE_LEVEL>=1
  131. logAi->trace(
  132. "%s -> %s, normal attack, %s, dps: %lld, %2f",
  133. attacker->getDescription(),
  134. defender->getDescription(),
  135. shooting ? "shot" : "mellee",
  136. attackDamage,
  137. defenderDamageReduce);
  138. #endif
  139. if(isOurAttack)
  140. {
  141. dpsScore.enemyDamageReduce += defenderDamageReduce;
  142. attackerValue[attacker->unitId()].value += defenderDamageReduce;
  143. }
  144. else
  145. dpsScore.ourDamageReduce += defenderDamageReduce;
  146. defender->damage(attackDamage);
  147. attacker->afterAttack(shooting, false);
  148. }
  149. if(!evaluateOnly && defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
  150. {
  151. auto retaliationDamage = damageCache.getDamage(defender.get(), attacker.get(), hb);
  152. attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), attacker.get(), retaliationDamage, damageCache, hb);
  153. #if BATTLE_TRACE_LEVEL>=1
  154. logAi->trace(
  155. "%s -> %s, retaliation, dps: %lld, %2f",
  156. defender->getDescription(),
  157. attacker->getDescription(),
  158. retaliationDamage,
  159. attackerDamageReduce);
  160. #endif
  161. if(isOurAttack)
  162. {
  163. dpsScore.ourDamageReduce += attackerDamageReduce;
  164. attackerValue[attacker->unitId()].isRetaliated = true;
  165. }
  166. else
  167. {
  168. dpsScore.enemyDamageReduce += attackerDamageReduce;
  169. attackerValue[defender->unitId()].value += attackerDamageReduce;
  170. }
  171. attacker->damage(retaliationDamage);
  172. defender->afterAttack(false, true);
  173. }
  174. auto score = defenderDamageReduce - attackerDamageReduce;
  175. #if BATTLE_TRACE_LEVEL>=1
  176. if(!score)
  177. {
  178. logAi->trace("Attack has zero score def:%2f att:%2f", defenderDamageReduce, attackerDamageReduce);
  179. }
  180. #endif
  181. return score;
  182. }
  183. float BattleExchangeEvaluator::scoreValue(const BattleScore & score) const
  184. {
  185. return score.enemyDamageReduce * getPositiveEffectMultiplier() - score.ourDamageReduce * getNegativeEffectMultiplier();
  186. }
  187. EvaluationResult BattleExchangeEvaluator::findBestTarget(
  188. const battle::Unit * activeStack,
  189. PotentialTargets & targets,
  190. DamageCache & damageCache,
  191. std::shared_ptr<HypotheticBattle> hb,
  192. bool siegeDefense)
  193. {
  194. EvaluationResult result(targets.bestAction());
  195. if(!activeStack->waited() && !activeStack->acquireState()->hadMorale)
  196. {
  197. #if BATTLE_TRACE_LEVEL>=1
  198. logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
  199. #endif
  200. auto hbWaited = std::make_shared<HypotheticBattle>(env.get(), hb);
  201. hbWaited->makeWait(activeStack);
  202. updateReachabilityMap(hbWaited);
  203. for(auto & ap : targets.possibleAttacks)
  204. {
  205. if (siegeDefense && !hb->battleIsInsideWalls(ap.from))
  206. continue;
  207. float score = evaluateExchange(ap, 0, targets, damageCache, hbWaited);
  208. if(score > result.score)
  209. {
  210. result.score = score;
  211. result.bestAttack = ap;
  212. result.wait = true;
  213. #if BATTLE_TRACE_LEVEL >= 1
  214. logAi->trace("New high score %2f", result.score);
  215. #endif
  216. }
  217. }
  218. }
  219. #if BATTLE_TRACE_LEVEL>=1
  220. logAi->trace("Evaluating normal attack for %s", activeStack->getDescription());
  221. #endif
  222. updateReachabilityMap(hb);
  223. if(result.bestAttack.attack.shooting
  224. && !result.bestAttack.defenderDead
  225. && !activeStack->waited()
  226. && hb->battleHasShootingPenalty(activeStack, result.bestAttack.dest))
  227. {
  228. if(!canBeHitThisTurn(result.bestAttack))
  229. return result; // lets wait
  230. }
  231. for(auto & ap : targets.possibleAttacks)
  232. {
  233. if (siegeDefense && !hb->battleIsInsideWalls(ap.from))
  234. continue;
  235. float score = evaluateExchange(ap, 0, targets, damageCache, hb);
  236. bool sameScoreButWaited = vstd::isAlmostEqual(score, result.score) && result.wait;
  237. if(score > result.score || sameScoreButWaited)
  238. {
  239. result.score = score;
  240. result.bestAttack = ap;
  241. result.wait = false;
  242. #if BATTLE_TRACE_LEVEL >= 1
  243. logAi->trace("New high score %2f", result.score);
  244. #endif
  245. }
  246. }
  247. return result;
  248. }
  249. ReachabilityInfo getReachabilityWithEnemyBypass(
  250. const battle::Unit * activeStack,
  251. DamageCache & damageCache,
  252. std::shared_ptr<HypotheticBattle> state)
  253. {
  254. ReachabilityInfo::Parameters params(activeStack, activeStack->getPosition());
  255. if(!params.flying)
  256. {
  257. for(const auto * unit : state->battleAliveUnits())
  258. {
  259. if(unit->unitSide() == activeStack->unitSide())
  260. continue;
  261. auto dmg = damageCache.getOriginalDamage(activeStack, unit, state);
  262. auto turnsToKill = unit->getAvailableHealth() / std::max(dmg, (int64_t)1);
  263. vstd::amin(turnsToKill, 100);
  264. for(auto & hex : unit->getHexes())
  265. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  266. params.destructibleEnemyTurns[hex.toInt()] = turnsToKill * unit->getMovementRange();
  267. }
  268. params.bypassEnemyStacks = true;
  269. }
  270. return state->getReachability(params);
  271. }
  272. MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
  273. const battle::Unit * activeStack,
  274. PotentialTargets & targets,
  275. DamageCache & damageCache,
  276. std::shared_ptr<HypotheticBattle> hb)
  277. {
  278. MoveTarget result;
  279. BattleExchangeVariant ev;
  280. logAi->trace("Find move towards unreachable. Enemies count %d", targets.unreachableEnemies.size());
  281. if(targets.unreachableEnemies.empty())
  282. return result;
  283. auto speed = activeStack->getMovementRange();
  284. if(speed == 0)
  285. return result;
  286. updateReachabilityMap(hb);
  287. auto dists = getReachabilityWithEnemyBypass(activeStack, damageCache, hb);
  288. auto flying = activeStack->hasBonusOfType(BonusType::FLYING);
  289. for(const battle::Unit * enemy : targets.unreachableEnemies)
  290. {
  291. logAi->trace(
  292. "Checking movement towards %d of %s",
  293. enemy->getCount(),
  294. LIBRARY->creatures()->getById(enemy->creatureId())->getJsonKey());
  295. auto distance = dists.distToNearestNeighbour(activeStack, enemy);
  296. if(distance >= GameConstants::BFIELD_SIZE)
  297. continue;
  298. if(distance <= speed)
  299. continue;
  300. float penaltyMultiplier = 1.0f; // Default multiplier, no penalty
  301. float closestAllyDistance = std::numeric_limits<float>::max();
  302. for (const battle::Unit* ally : hb->battleAliveUnits())
  303. {
  304. if (ally == activeStack)
  305. continue;
  306. if (ally->unitSide() != activeStack->unitSide())
  307. continue;
  308. float allyDistance = dists.distToNearestNeighbour(ally, enemy);
  309. if (allyDistance < closestAllyDistance)
  310. {
  311. closestAllyDistance = allyDistance;
  312. }
  313. }
  314. // If an ally is closer to the enemy, compute the penaltyMultiplier
  315. if (closestAllyDistance < distance)
  316. {
  317. penaltyMultiplier = closestAllyDistance / distance; // Ratio of distances
  318. }
  319. auto turnsToReach = (distance - 1) / speed + 1;
  320. const BattleHexArray & hexes = enemy->getAttackableHexes(activeStack);
  321. auto enemySpeed = enemy->getMovementRange();
  322. auto speedRatio = speed / static_cast<float>(enemySpeed);
  323. auto multiplier = (speedRatio > 1 ? 1 : speedRatio) * penaltyMultiplier;
  324. for(auto & hex : hexes)
  325. {
  326. // FIXME: provide distance info for Jousting bonus
  327. auto bai = BattleAttackInfo(activeStack, enemy, 0, cb->battleCanShoot(activeStack));
  328. auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
  329. attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
  330. auto score = calculateExchange(attack, turnsToReach, targets, damageCache, hb);
  331. score.enemyDamageReduce *= multiplier;
  332. #if BATTLE_TRACE_LEVEL >= 1
  333. logAi->trace("Multiplier: %f, turns: %d, current score %f, new score %f", multiplier, turnsToReach, result.score, scoreValue(score));
  334. #endif
  335. if(result.score < scoreValue(score)
  336. || (result.turnsToReach > turnsToReach && vstd::isAlmostEqual(result.score, scoreValue(score))))
  337. {
  338. result.score = scoreValue(score);
  339. result.positions.clear();
  340. #if BATTLE_TRACE_LEVEL >= 1
  341. logAi->trace("New high score");
  342. #endif
  343. BattleHex enemyHex = hex;
  344. while(!flying && dists.distances[enemyHex.toInt()] > speed && dists.predecessors.at(enemyHex.toInt()).isValid())
  345. {
  346. enemyHex = dists.predecessors.at(enemyHex.toInt());
  347. if(dists.accessibility[enemyHex.toInt()] == EAccessibility::ALIVE_STACK)
  348. {
  349. auto defenderToBypass = hb->battleGetUnitByPos(enemyHex);
  350. assert(defenderToBypass != nullptr);
  351. auto attackHex = dists.predecessors[enemyHex.toInt()];
  352. if(defenderToBypass &&
  353. defenderToBypass != enemy &&
  354. vstd::contains(defenderToBypass->getAttackableHexes(activeStack), attackHex))
  355. {
  356. #if BATTLE_TRACE_LEVEL >= 1
  357. logAi->trace("Found target to bypass at %d", enemyHex.toInt());
  358. #endif
  359. auto baiBypass = BattleAttackInfo(activeStack, defenderToBypass, 0, cb->battleCanShoot(activeStack));
  360. auto attackBypass = AttackPossibility::evaluate(baiBypass, attackHex, damageCache, hb);
  361. auto adjacentStacks = getAdjacentUnits(enemy);
  362. adjacentStacks.push_back(defenderToBypass);
  363. vstd::removeDuplicates(adjacentStacks);
  364. auto bypassScore = calculateExchange(
  365. attackBypass,
  366. dists.distances[attackHex.toInt()],
  367. targets,
  368. damageCache,
  369. hb,
  370. adjacentStacks);
  371. if(scoreValue(bypassScore) > result.score)
  372. {
  373. result.score = scoreValue(bypassScore);
  374. #if BATTLE_TRACE_LEVEL >= 1
  375. logAi->trace("New high score after bypass %f", scoreValue(bypassScore));
  376. #endif
  377. }
  378. }
  379. }
  380. }
  381. result.positions.insert(enemyHex);
  382. result.cachedAttack = attack;
  383. result.turnsToReach = turnsToReach;
  384. }
  385. }
  386. }
  387. return result;
  388. }
  389. battle::Units BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit) const
  390. {
  391. std::queue<const battle::Unit *> queue;
  392. battle::Units checkedStacks;
  393. queue.push(blockerUnit);
  394. while(!queue.empty())
  395. {
  396. auto stack = queue.front();
  397. queue.pop();
  398. checkedStacks.push_back(stack);
  399. auto const & hexes = stack->getSurroundingHexes();
  400. for(const auto & hex : hexes)
  401. {
  402. auto neighbour = cb->battleGetUnitByPos(hex);
  403. if(neighbour && neighbour->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbour))
  404. {
  405. queue.push(neighbour);
  406. checkedStacks.push_back(neighbour);
  407. }
  408. }
  409. }
  410. return checkedStacks;
  411. }
  412. ReachabilityData BattleExchangeEvaluator::getExchangeUnits(
  413. const AttackPossibility & ap,
  414. uint8_t turn,
  415. PotentialTargets & targets,
  416. std::shared_ptr<HypotheticBattle> hb,
  417. const battle::Units & additionalUnits) const
  418. {
  419. ReachabilityData result;
  420. auto hexes = ap.attack.defender->getSurroundingHexes();
  421. if(!ap.attack.shooting)
  422. hexes.insert(ap.from);
  423. battle::Units allReachableUnits = additionalUnits;
  424. for(const auto & hex : hexes)
  425. {
  426. vstd::concatenate(allReachableUnits, getOneTurnReachableUnits(turn, hex));
  427. }
  428. if(!ap.attack.attacker->isTurret())
  429. {
  430. for(const auto & hex : ap.attack.attacker->getHexes())
  431. {
  432. auto unitsReachingAttacker = getOneTurnReachableUnits(turn, hex);
  433. for(auto unit : unitsReachingAttacker)
  434. {
  435. if(unit->unitSide() != ap.attack.attacker->unitSide())
  436. {
  437. allReachableUnits.push_back(unit);
  438. result.enemyUnitsReachingAttacker.insert(unit->unitId());
  439. }
  440. }
  441. }
  442. }
  443. vstd::removeDuplicates(allReachableUnits);
  444. auto copy = allReachableUnits;
  445. for(auto unit : copy)
  446. {
  447. for(auto adjacentUnit : getAdjacentUnits(unit))
  448. {
  449. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  450. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  451. && !vstd::contains(allReachableUnits, unitWithBonuses))
  452. {
  453. allReachableUnits.push_back(unitWithBonuses);
  454. }
  455. }
  456. }
  457. vstd::removeDuplicates(allReachableUnits);
  458. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  459. {
  460. allReachableUnits.push_back(ap.attack.attacker);
  461. }
  462. if(allReachableUnits.size() < 2)
  463. {
  464. #if BATTLE_TRACE_LEVEL>=1
  465. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  466. #endif
  467. return result;
  468. }
  469. for(auto unit : allReachableUnits)
  470. {
  471. auto accessible = !unit->canShoot() || vstd::contains(additionalUnits, unit);
  472. if(!accessible)
  473. {
  474. for(const auto & hex : unit->getSurroundingHexes())
  475. {
  476. if(ap.attack.defender->coversPos(hex))
  477. {
  478. accessible = true;
  479. }
  480. }
  481. }
  482. if(accessible)
  483. result.melleeAccessible.push_back(unit);
  484. else
  485. result.shooters.push_back(unit);
  486. }
  487. for(int turn = 0; turn < turnOrder.size(); turn++)
  488. {
  489. for(auto unit : turnOrder[turn])
  490. {
  491. if(vstd::contains(allReachableUnits, unit))
  492. result.units[turn].push_back(unit);
  493. }
  494. vstd::erase_if(result.units[turn], [&](const battle::Unit * u) -> bool
  495. {
  496. return !hb->battleGetUnitByID(u->unitId())->alive();
  497. });
  498. }
  499. return result;
  500. }
  501. float BattleExchangeEvaluator::evaluateExchange(
  502. const AttackPossibility & ap,
  503. uint8_t turn,
  504. PotentialTargets & targets,
  505. DamageCache & damageCache,
  506. std::shared_ptr<HypotheticBattle> hb) const
  507. {
  508. BattleScore score = calculateExchange(ap, turn, targets, damageCache, hb);
  509. #if BATTLE_TRACE_LEVEL >= 1
  510. logAi->trace(
  511. "calculateExchange score +%2f -%2fx%2f = %2f",
  512. score.enemyDamageReduce,
  513. score.ourDamageReduce,
  514. getNegativeEffectMultiplier(),
  515. scoreValue(score));
  516. #endif
  517. return scoreValue(score);
  518. }
  519. BattleScore BattleExchangeEvaluator::calculateExchange(
  520. const AttackPossibility & ap,
  521. uint8_t turn,
  522. PotentialTargets & targets,
  523. DamageCache & damageCache,
  524. std::shared_ptr<HypotheticBattle> hb,
  525. const battle::Units & additionalUnits) const
  526. {
  527. #if BATTLE_TRACE_LEVEL>=1
  528. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.toInt() : ap.from.toInt());
  529. #endif
  530. if(cb->battleGetMySide() == BattleSide::LEFT_SIDE
  531. && cb->battleGetGateState() == EGateState::BLOCKED
  532. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  533. {
  534. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  535. }
  536. battle::Units ourStacks;
  537. battle::Units enemyStacks;
  538. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  539. enemyStacks.push_back(ap.attack.defender);
  540. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb, additionalUnits);
  541. if(exchangeUnits.units.empty())
  542. {
  543. return BattleScore();
  544. }
  545. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  546. BattleExchangeVariant v;
  547. for(int exchangeTurn = 0; exchangeTurn < exchangeUnits.units.size(); exchangeTurn++)
  548. {
  549. for(auto unit : exchangeUnits.units.at(exchangeTurn))
  550. {
  551. if(unit->isTurret())
  552. continue;
  553. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  554. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  555. auto u = exchangeBattle->getForUpdate(unit->unitId());
  556. if(u->alive() && !vstd::contains(attackerQueue, unit))
  557. {
  558. attackerQueue.push_back(unit);
  559. #if BATTLE_TRACE_LEVEL
  560. logAi->trace("Exchanging: %s", u->getDescription());
  561. #endif
  562. }
  563. }
  564. }
  565. auto melleeAttackers = ourStacks;
  566. vstd::removeDuplicates(melleeAttackers);
  567. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  568. {
  569. return cb->battleCanShoot(u);
  570. });
  571. bool canUseAp = true;
  572. std::set<uint32_t> blockedShooters;
  573. int totalTurnsCount = simulationTurnsCount >= turn + turnOrder.size()
  574. ? simulationTurnsCount
  575. : turn + turnOrder.size();
  576. for(int exchangeTurn = 0; exchangeTurn < simulationTurnsCount; exchangeTurn++)
  577. {
  578. bool isMovingTurm = exchangeTurn < turn;
  579. int queueTurn = exchangeTurn >= exchangeUnits.units.size()
  580. ? exchangeUnits.units.size() - 1
  581. : exchangeTurn;
  582. for(auto activeUnit : exchangeUnits.units.at(queueTurn))
  583. {
  584. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  585. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  586. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  587. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  588. auto shooting = exchangeBattle->battleCanShoot(attacker.get())
  589. && !vstd::contains(blockedShooters, attacker->unitId());
  590. if(!attacker->alive())
  591. {
  592. #if BATTLE_TRACE_LEVEL>=1
  593. logAi->trace("Attacker is dead");
  594. #endif
  595. continue;
  596. }
  597. if(isMovingTurm && !shooting
  598. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  599. {
  600. #if BATTLE_TRACE_LEVEL>=1
  601. logAi->trace("Attacker is moving");
  602. #endif
  603. continue;
  604. }
  605. auto targetUnit = ap.attack.defender;
  606. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  607. {
  608. #if BATTLE_TRACE_LEVEL>=2
  609. logAi->trace("Best target selector for %s", attacker->getDescription());
  610. #endif
  611. auto estimateAttack = [&](const battle::Unit * u) -> float
  612. {
  613. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  614. auto score = v.trackAttack(
  615. attacker,
  616. stackWithBonuses,
  617. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  618. isOur,
  619. damageCache,
  620. hb,
  621. true);
  622. #if BATTLE_TRACE_LEVEL>=2
  623. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), stackWithBonuses->getDescription(), score);
  624. #endif
  625. return score;
  626. };
  627. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  628. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  629. {
  630. return vstd::contains(exchangeUnits.shooters, u);
  631. });
  632. if(!isOur
  633. && exchangeTurn == 0
  634. && exchangeUnits.units.at(exchangeTurn).at(0)->unitId() != ap.attack.attacker->unitId()
  635. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  636. {
  637. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u) -> bool
  638. {
  639. return u->unitId() == ap.attack.attacker->unitId();
  640. });
  641. }
  642. if(!unitsInOppositeQueueExceptInaccessible.empty())
  643. {
  644. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  645. }
  646. else
  647. {
  648. auto reachable = exchangeBattle->battleGetUnitsIf([this, &exchangeBattle, &attacker](const battle::Unit * u) -> bool
  649. {
  650. if(u->unitSide() == attacker->unitSide())
  651. return false;
  652. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  653. return false;
  654. if(!u->getPosition().isValid())
  655. return false; // e.g. tower shooters
  656. const auto & reachableUnits = getOneTurnReachableUnits(0, u->getPosition());
  657. return vstd::contains_if(reachableUnits, [&attacker](const battle::Unit * other) -> bool
  658. {
  659. return attacker->unitId() == other->unitId();
  660. });
  661. });
  662. if(!reachable.empty())
  663. {
  664. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  665. }
  666. else
  667. {
  668. #if BATTLE_TRACE_LEVEL>=1
  669. logAi->trace("Battle queue is empty and no reachable enemy.");
  670. #endif
  671. continue;
  672. }
  673. }
  674. }
  675. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  676. const int totalAttacks = attacker->getTotalAttacks(shooting);
  677. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  678. && targetUnit->unitId() == ap.attack.defender->unitId())
  679. {
  680. v.trackAttack(ap, exchangeBattle, damageCache);
  681. }
  682. else
  683. {
  684. for(int i = 0; i < totalAttacks; i++)
  685. {
  686. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  687. if(!attacker->alive() || !defender->alive())
  688. break;
  689. }
  690. }
  691. if(!shooting)
  692. blockedShooters.insert(defender->unitId());
  693. canUseAp = false;
  694. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  695. {
  696. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  697. });
  698. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  699. {
  700. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  701. });
  702. }
  703. exchangeBattle->nextRound();
  704. }
  705. auto score = v.getScore();
  706. if(simulationTurnsCount < totalTurnsCount)
  707. {
  708. float scalingRatio = simulationTurnsCount / static_cast<float>(totalTurnsCount);
  709. score.enemyDamageReduce *= scalingRatio;
  710. score.ourDamageReduce *= scalingRatio;
  711. }
  712. if(turn > 0)
  713. {
  714. auto turnMultiplier = 1 - std::min(0.2, 0.05 * turn);
  715. score.enemyDamageReduce *= turnMultiplier;
  716. }
  717. #if BATTLE_TRACE_LEVEL>=1
  718. logAi->trace("Exchange score: enemy: %2f, our -%2f", score.enemyDamageReduce, score.ourDamageReduce);
  719. #endif
  720. return score;
  721. }
  722. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  723. {
  724. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  725. {
  726. for(auto u : getOneTurnReachableUnits(0, pos))
  727. {
  728. if(u->unitSide() != ap.attack.attacker->unitSide())
  729. {
  730. return true;
  731. }
  732. }
  733. }
  734. return false;
  735. }
  736. void ReachabilityMapCache::update(const std::vector<battle::Units> & turnOrder, std::shared_ptr<HypotheticBattle> hb)
  737. {
  738. for(auto turn : turnOrder)
  739. {
  740. for(auto u : turn)
  741. {
  742. if(!vstd::contains(unitReachabilityMap, u->unitId()))
  743. {
  744. unitReachabilityMap[u->unitId()] = hb->getReachability(u);
  745. }
  746. }
  747. }
  748. hexReachabilityPerTurn.clear();
  749. }
  750. void BattleExchangeEvaluator::updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb)
  751. {
  752. const int TURN_DEPTH = 2;
  753. turnOrder.clear();
  754. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  755. reachabilityMap.update(turnOrder, hb);
  756. }
  757. const battle::Units & ReachabilityMapCache::getOneTurnReachableUnits(std::shared_ptr<CBattleInfoCallback> cb, std::shared_ptr<Environment> env, const std::vector<battle::Units> & turnOrder, uint8_t turn, const BattleHex & hex)
  758. {
  759. auto & turnData = hexReachabilityPerTurn[turn];
  760. if (!turnData.isValid[hex.toInt()])
  761. {
  762. turnData.hexes[hex.toInt()] = computeOneTurnReachableUnits(cb, env, turnOrder, turn, hex);
  763. turnData.isValid.set(hex.toInt());
  764. }
  765. return turnData.hexes[hex.toInt()];
  766. }
  767. battle::Units ReachabilityMapCache::computeOneTurnReachableUnits(std::shared_ptr<CBattleInfoCallback> cb, std::shared_ptr<Environment> env, const std::vector<battle::Units> & turnOrder, uint8_t turn, const BattleHex & hex)
  768. {
  769. battle::Units result;
  770. for(int i = 0; i < turnOrder.size(); i++, turn++)
  771. {
  772. auto & turnQueue = turnOrder[i];
  773. HypotheticBattle turnBattle(env.get(), cb);
  774. for(const battle::Unit * unit : turnQueue)
  775. {
  776. if(unit->isTurret())
  777. continue;
  778. if(turnBattle.battleCanShoot(unit))
  779. {
  780. result.push_back(unit);
  781. continue;
  782. }
  783. auto unitSpeed = unit->getMovementRange(turn);
  784. auto radius = unitSpeed * (turn + 1);
  785. auto reachabilityIter = unitReachabilityMap.find(unit->unitId());
  786. assert(reachabilityIter != unitReachabilityMap.end()); // missing updateReachabilityMap call?
  787. ReachabilityInfo unitReachability = reachabilityIter != unitReachabilityMap.end() ? reachabilityIter->second : turnBattle.getReachability(unit);
  788. bool reachable = unitReachability.distances.at(hex.toInt()) <= radius;
  789. if(!reachable && unitReachability.accessibility[hex.toInt()] == EAccessibility::ALIVE_STACK)
  790. {
  791. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  792. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  793. {
  794. for(const BattleHex & neighbour : hex.getNeighbouringTiles())
  795. {
  796. reachable = unitReachability.distances.at(neighbour.toInt()) <= radius;
  797. if(reachable) break;
  798. }
  799. }
  800. }
  801. if(reachable)
  802. {
  803. result.push_back(unit);
  804. }
  805. }
  806. }
  807. return result;
  808. }
  809. const battle::Units & BattleExchangeEvaluator::getOneTurnReachableUnits(uint8_t turn, const BattleHex & hex) const
  810. {
  811. return reachabilityMap.getOneTurnReachableUnits(cb, env, turnOrder, turn, hex);
  812. }
  813. // avoid blocking path for stronger stack by weaker stack
  814. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(const HypotheticBattle & hb, const battle::Unit * activeUnit, const BattleHex & position)
  815. {
  816. const int BLOCKING_THRESHOLD = 70;
  817. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  818. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  819. float blockingScore = 0;
  820. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  821. for(int turn = 0; turn < turnOrder.size(); turn++)
  822. {
  823. auto & turnQueue = turnOrder[turn];
  824. HypotheticBattle turnBattle(env.get(), cb);
  825. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  826. unitToUpdate->setPosition(position);
  827. for(const battle::Unit * unit : turnQueue)
  828. {
  829. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  830. continue;
  831. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  832. float ratio = blockedUnitDamage / (float)(blockedUnitDamage + activeUnitDamage + 0.01);
  833. auto unitReachability = turnBattle.getReachability(unit);
  834. auto unitSpeed = unit->getMovementRange(turn); // Cached value, to avoid performance hit
  835. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); ++hex)
  836. {
  837. bool enemyUnit = false;
  838. bool reachable = unitReachability.distances.at(hex.toInt()) <= unitSpeed;
  839. if(!reachable && unitReachability.accessibility[hex.toInt()] == EAccessibility::ALIVE_STACK)
  840. {
  841. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  842. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  843. {
  844. enemyUnit = true;
  845. for(const BattleHex & neighbour : hex.getNeighbouringTiles())
  846. {
  847. reachable = unitReachability.distances.at(neighbour.toInt()) <= unitSpeed;
  848. if(reachable) break;
  849. }
  850. }
  851. }
  852. if(!reachable)
  853. {
  854. auto reachableUnits = getOneTurnReachableUnits(0, hex);
  855. if (std::count(reachableUnits.begin(), reachableUnits.end(), unit) > 1)
  856. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  857. }
  858. }
  859. }
  860. }
  861. #if BATTLE_TRACE_LEVEL>=1
  862. logAi->trace("Position %d, blocking score %f", position.toInt(), blockingScore);
  863. #endif
  864. return blockingScore > BLOCKING_THRESHOLD;
  865. }