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->getSurroundingHexes();
  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. for(BattleHex enemyHex : enemy->getAttackableHexes(activeStack))
  344. {
  345. while(!flying && dists.distances[enemyHex.toInt()] > speed && dists.predecessors.at(enemyHex.toInt()).isValid())
  346. {
  347. enemyHex = dists.predecessors.at(enemyHex.toInt());
  348. if(dists.accessibility[enemyHex.toInt()] == EAccessibility::ALIVE_STACK)
  349. {
  350. auto defenderToBypass = hb->battleGetUnitByPos(enemyHex);
  351. if(defenderToBypass)
  352. {
  353. #if BATTLE_TRACE_LEVEL >= 1
  354. logAi->trace("Found target to bypass at %d", enemyHex.toInt());
  355. #endif
  356. auto attackHex = dists.predecessors[enemyHex.toInt()];
  357. auto baiBypass = BattleAttackInfo(activeStack, defenderToBypass, 0, cb->battleCanShoot(activeStack));
  358. auto attackBypass = AttackPossibility::evaluate(baiBypass, attackHex, damageCache, hb);
  359. auto adjacentStacks = getAdjacentUnits(enemy);
  360. adjacentStacks.push_back(defenderToBypass);
  361. vstd::removeDuplicates(adjacentStacks);
  362. auto bypassScore = calculateExchange(
  363. attackBypass,
  364. dists.distances[attackHex.toInt()],
  365. targets,
  366. damageCache,
  367. hb,
  368. adjacentStacks);
  369. if(scoreValue(bypassScore) > result.score)
  370. {
  371. result.score = scoreValue(bypassScore);
  372. #if BATTLE_TRACE_LEVEL >= 1
  373. logAi->trace("New high score after bypass %f", scoreValue(bypassScore));
  374. #endif
  375. }
  376. }
  377. }
  378. }
  379. result.positions.insert(enemyHex);
  380. }
  381. result.cachedAttack = attack;
  382. result.turnsToReach = turnsToReach;
  383. }
  384. }
  385. }
  386. return result;
  387. }
  388. battle::Units BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit) const
  389. {
  390. std::queue<const battle::Unit *> queue;
  391. battle::Units checkedStacks;
  392. queue.push(blockerUnit);
  393. while(!queue.empty())
  394. {
  395. auto stack = queue.front();
  396. queue.pop();
  397. checkedStacks.push_back(stack);
  398. auto const & hexes = stack->getSurroundingHexes();
  399. for(const auto & hex : hexes)
  400. {
  401. auto neighbour = cb->battleGetUnitByPos(hex);
  402. if(neighbour && neighbour->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbour))
  403. {
  404. queue.push(neighbour);
  405. checkedStacks.push_back(neighbour);
  406. }
  407. }
  408. }
  409. return checkedStacks;
  410. }
  411. ReachabilityData BattleExchangeEvaluator::getExchangeUnits(
  412. const AttackPossibility & ap,
  413. uint8_t turn,
  414. PotentialTargets & targets,
  415. std::shared_ptr<HypotheticBattle> hb,
  416. const battle::Units & additionalUnits) const
  417. {
  418. ReachabilityData result;
  419. auto hexes = ap.attack.defender->getSurroundingHexes();
  420. if(!ap.attack.shooting)
  421. hexes.insert(ap.from);
  422. battle::Units allReachableUnits = additionalUnits;
  423. for(const auto & hex : hexes)
  424. {
  425. vstd::concatenate(allReachableUnits, getOneTurnReachableUnits(turn, hex));
  426. }
  427. if(!ap.attack.attacker->isTurret())
  428. {
  429. for(const auto & hex : ap.attack.attacker->getHexes())
  430. {
  431. auto unitsReachingAttacker = getOneTurnReachableUnits(turn, hex);
  432. for(auto unit : unitsReachingAttacker)
  433. {
  434. if(unit->unitSide() != ap.attack.attacker->unitSide())
  435. {
  436. allReachableUnits.push_back(unit);
  437. result.enemyUnitsReachingAttacker.insert(unit->unitId());
  438. }
  439. }
  440. }
  441. }
  442. vstd::removeDuplicates(allReachableUnits);
  443. auto copy = allReachableUnits;
  444. for(auto unit : copy)
  445. {
  446. for(auto adjacentUnit : getAdjacentUnits(unit))
  447. {
  448. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  449. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  450. && !vstd::contains(allReachableUnits, unitWithBonuses))
  451. {
  452. allReachableUnits.push_back(unitWithBonuses);
  453. }
  454. }
  455. }
  456. vstd::removeDuplicates(allReachableUnits);
  457. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  458. {
  459. allReachableUnits.push_back(ap.attack.attacker);
  460. }
  461. if(allReachableUnits.size() < 2)
  462. {
  463. #if BATTLE_TRACE_LEVEL>=1
  464. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  465. #endif
  466. return result;
  467. }
  468. for(auto unit : allReachableUnits)
  469. {
  470. auto accessible = !unit->canShoot() || vstd::contains(additionalUnits, unit);
  471. if(!accessible)
  472. {
  473. for(const auto & hex : unit->getSurroundingHexes())
  474. {
  475. if(ap.attack.defender->coversPos(hex))
  476. {
  477. accessible = true;
  478. }
  479. }
  480. }
  481. if(accessible)
  482. result.melleeAccessible.push_back(unit);
  483. else
  484. result.shooters.push_back(unit);
  485. }
  486. for(int turn = 0; turn < turnOrder.size(); turn++)
  487. {
  488. for(auto unit : turnOrder[turn])
  489. {
  490. if(vstd::contains(allReachableUnits, unit))
  491. result.units[turn].push_back(unit);
  492. }
  493. vstd::erase_if(result.units[turn], [&](const battle::Unit * u) -> bool
  494. {
  495. return !hb->battleGetUnitByID(u->unitId())->alive();
  496. });
  497. }
  498. return result;
  499. }
  500. float BattleExchangeEvaluator::evaluateExchange(
  501. const AttackPossibility & ap,
  502. uint8_t turn,
  503. PotentialTargets & targets,
  504. DamageCache & damageCache,
  505. std::shared_ptr<HypotheticBattle> hb) const
  506. {
  507. BattleScore score = calculateExchange(ap, turn, targets, damageCache, hb);
  508. #if BATTLE_TRACE_LEVEL >= 1
  509. logAi->trace(
  510. "calculateExchange score +%2f -%2fx%2f = %2f",
  511. score.enemyDamageReduce,
  512. score.ourDamageReduce,
  513. getNegativeEffectMultiplier(),
  514. scoreValue(score));
  515. #endif
  516. return scoreValue(score);
  517. }
  518. BattleScore BattleExchangeEvaluator::calculateExchange(
  519. const AttackPossibility & ap,
  520. uint8_t turn,
  521. PotentialTargets & targets,
  522. DamageCache & damageCache,
  523. std::shared_ptr<HypotheticBattle> hb,
  524. const battle::Units & additionalUnits) const
  525. {
  526. #if BATTLE_TRACE_LEVEL>=1
  527. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.toInt() : ap.from.toInt());
  528. #endif
  529. if(cb->battleGetMySide() == BattleSide::LEFT_SIDE
  530. && cb->battleGetGateState() == EGateState::BLOCKED
  531. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  532. {
  533. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  534. }
  535. battle::Units ourStacks;
  536. battle::Units enemyStacks;
  537. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  538. enemyStacks.push_back(ap.attack.defender);
  539. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb, additionalUnits);
  540. if(exchangeUnits.units.empty())
  541. {
  542. return BattleScore();
  543. }
  544. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  545. BattleExchangeVariant v;
  546. for(int exchangeTurn = 0; exchangeTurn < exchangeUnits.units.size(); exchangeTurn++)
  547. {
  548. for(auto unit : exchangeUnits.units.at(exchangeTurn))
  549. {
  550. if(unit->isTurret())
  551. continue;
  552. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  553. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  554. auto u = exchangeBattle->getForUpdate(unit->unitId());
  555. if(u->alive() && !vstd::contains(attackerQueue, unit))
  556. {
  557. attackerQueue.push_back(unit);
  558. #if BATTLE_TRACE_LEVEL
  559. logAi->trace("Exchanging: %s", u->getDescription());
  560. #endif
  561. }
  562. }
  563. }
  564. auto melleeAttackers = ourStacks;
  565. vstd::removeDuplicates(melleeAttackers);
  566. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  567. {
  568. return cb->battleCanShoot(u);
  569. });
  570. bool canUseAp = true;
  571. std::set<uint32_t> blockedShooters;
  572. int totalTurnsCount = simulationTurnsCount >= turn + turnOrder.size()
  573. ? simulationTurnsCount
  574. : turn + turnOrder.size();
  575. for(int exchangeTurn = 0; exchangeTurn < simulationTurnsCount; exchangeTurn++)
  576. {
  577. bool isMovingTurm = exchangeTurn < turn;
  578. int queueTurn = exchangeTurn >= exchangeUnits.units.size()
  579. ? exchangeUnits.units.size() - 1
  580. : exchangeTurn;
  581. for(auto activeUnit : exchangeUnits.units.at(queueTurn))
  582. {
  583. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  584. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  585. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  586. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  587. auto shooting = exchangeBattle->battleCanShoot(attacker.get())
  588. && !vstd::contains(blockedShooters, attacker->unitId());
  589. if(!attacker->alive())
  590. {
  591. #if BATTLE_TRACE_LEVEL>=1
  592. logAi->trace("Attacker is dead");
  593. #endif
  594. continue;
  595. }
  596. if(isMovingTurm && !shooting
  597. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  598. {
  599. #if BATTLE_TRACE_LEVEL>=1
  600. logAi->trace("Attacker is moving");
  601. #endif
  602. continue;
  603. }
  604. auto targetUnit = ap.attack.defender;
  605. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  606. {
  607. #if BATTLE_TRACE_LEVEL>=2
  608. logAi->trace("Best target selector for %s", attacker->getDescription());
  609. #endif
  610. auto estimateAttack = [&](const battle::Unit * u) -> float
  611. {
  612. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  613. auto score = v.trackAttack(
  614. attacker,
  615. stackWithBonuses,
  616. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  617. isOur,
  618. damageCache,
  619. hb,
  620. true);
  621. #if BATTLE_TRACE_LEVEL>=2
  622. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), stackWithBonuses->getDescription(), score);
  623. #endif
  624. return score;
  625. };
  626. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  627. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  628. {
  629. return vstd::contains(exchangeUnits.shooters, u);
  630. });
  631. if(!isOur
  632. && exchangeTurn == 0
  633. && exchangeUnits.units.at(exchangeTurn).at(0)->unitId() != ap.attack.attacker->unitId()
  634. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  635. {
  636. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u) -> bool
  637. {
  638. return u->unitId() == ap.attack.attacker->unitId();
  639. });
  640. }
  641. if(!unitsInOppositeQueueExceptInaccessible.empty())
  642. {
  643. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  644. }
  645. else
  646. {
  647. auto reachable = exchangeBattle->battleGetUnitsIf([this, &exchangeBattle, &attacker](const battle::Unit * u) -> bool
  648. {
  649. if(u->unitSide() == attacker->unitSide())
  650. return false;
  651. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  652. return false;
  653. if(!u->getPosition().isValid())
  654. return false; // e.g. tower shooters
  655. const auto & reachableUnits = getOneTurnReachableUnits(0, u->getPosition());
  656. return vstd::contains_if(reachableUnits, [&attacker](const battle::Unit * other) -> bool
  657. {
  658. return attacker->unitId() == other->unitId();
  659. });
  660. });
  661. if(!reachable.empty())
  662. {
  663. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  664. }
  665. else
  666. {
  667. #if BATTLE_TRACE_LEVEL>=1
  668. logAi->trace("Battle queue is empty and no reachable enemy.");
  669. #endif
  670. continue;
  671. }
  672. }
  673. }
  674. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  675. const int totalAttacks = attacker->getTotalAttacks(shooting);
  676. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  677. && targetUnit->unitId() == ap.attack.defender->unitId())
  678. {
  679. v.trackAttack(ap, exchangeBattle, damageCache);
  680. }
  681. else
  682. {
  683. for(int i = 0; i < totalAttacks; i++)
  684. {
  685. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  686. if(!attacker->alive() || !defender->alive())
  687. break;
  688. }
  689. }
  690. if(!shooting)
  691. blockedShooters.insert(defender->unitId());
  692. canUseAp = false;
  693. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  694. {
  695. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  696. });
  697. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  698. {
  699. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  700. });
  701. }
  702. exchangeBattle->nextRound();
  703. }
  704. auto score = v.getScore();
  705. if(simulationTurnsCount < totalTurnsCount)
  706. {
  707. float scalingRatio = simulationTurnsCount / static_cast<float>(totalTurnsCount);
  708. score.enemyDamageReduce *= scalingRatio;
  709. score.ourDamageReduce *= scalingRatio;
  710. }
  711. if(turn > 0)
  712. {
  713. auto turnMultiplier = 1 - std::min(0.2, 0.05 * turn);
  714. score.enemyDamageReduce *= turnMultiplier;
  715. }
  716. #if BATTLE_TRACE_LEVEL>=1
  717. logAi->trace("Exchange score: enemy: %2f, our -%2f", score.enemyDamageReduce, score.ourDamageReduce);
  718. #endif
  719. return score;
  720. }
  721. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  722. {
  723. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  724. {
  725. for(auto u : getOneTurnReachableUnits(0, pos))
  726. {
  727. if(u->unitSide() != ap.attack.attacker->unitSide())
  728. {
  729. return true;
  730. }
  731. }
  732. }
  733. return false;
  734. }
  735. void ReachabilityMapCache::update(const std::vector<battle::Units> & turnOrder, std::shared_ptr<HypotheticBattle> hb)
  736. {
  737. for(auto turn : turnOrder)
  738. {
  739. for(auto u : turn)
  740. {
  741. if(!vstd::contains(unitReachabilityMap, u->unitId()))
  742. {
  743. unitReachabilityMap[u->unitId()] = hb->getReachability(u);
  744. }
  745. }
  746. }
  747. hexReachabilityPerTurn.clear();
  748. }
  749. void BattleExchangeEvaluator::updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb)
  750. {
  751. const int TURN_DEPTH = 2;
  752. turnOrder.clear();
  753. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  754. reachabilityMap.update(turnOrder, hb);
  755. }
  756. 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)
  757. {
  758. auto & turnData = hexReachabilityPerTurn[turn];
  759. if (!turnData.isValid[hex.toInt()])
  760. {
  761. turnData.hexes[hex.toInt()] = computeOneTurnReachableUnits(cb, env, turnOrder, turn, hex);
  762. turnData.isValid.set(hex.toInt());
  763. }
  764. return turnData.hexes[hex.toInt()];
  765. }
  766. 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)
  767. {
  768. battle::Units result;
  769. for(int i = 0; i < turnOrder.size(); i++, turn++)
  770. {
  771. auto & turnQueue = turnOrder[i];
  772. HypotheticBattle turnBattle(env.get(), cb);
  773. for(const battle::Unit * unit : turnQueue)
  774. {
  775. if(unit->isTurret())
  776. continue;
  777. if(turnBattle.battleCanShoot(unit))
  778. {
  779. result.push_back(unit);
  780. continue;
  781. }
  782. auto unitSpeed = unit->getMovementRange(turn);
  783. auto radius = unitSpeed * (turn + 1);
  784. auto reachabilityIter = unitReachabilityMap.find(unit->unitId());
  785. assert(reachabilityIter != unitReachabilityMap.end()); // missing updateReachabilityMap call?
  786. ReachabilityInfo unitReachability = reachabilityIter != unitReachabilityMap.end() ? reachabilityIter->second : turnBattle.getReachability(unit);
  787. bool reachable = unitReachability.distances.at(hex.toInt()) <= radius;
  788. if(!reachable && unitReachability.accessibility[hex.toInt()] == EAccessibility::ALIVE_STACK)
  789. {
  790. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  791. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  792. {
  793. for(const BattleHex & neighbour : hex.getNeighbouringTiles())
  794. {
  795. reachable = unitReachability.distances.at(neighbour.toInt()) <= radius;
  796. if(reachable) break;
  797. }
  798. }
  799. }
  800. if(reachable)
  801. {
  802. result.push_back(unit);
  803. }
  804. }
  805. }
  806. return result;
  807. }
  808. const battle::Units & BattleExchangeEvaluator::getOneTurnReachableUnits(uint8_t turn, const BattleHex & hex) const
  809. {
  810. return reachabilityMap.getOneTurnReachableUnits(cb, env, turnOrder, turn, hex);
  811. }
  812. // avoid blocking path for stronger stack by weaker stack
  813. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(const HypotheticBattle & hb, const battle::Unit * activeUnit, const BattleHex & position)
  814. {
  815. const int BLOCKING_THRESHOLD = 70;
  816. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  817. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  818. float blockingScore = 0;
  819. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  820. for(int turn = 0; turn < turnOrder.size(); turn++)
  821. {
  822. auto & turnQueue = turnOrder[turn];
  823. HypotheticBattle turnBattle(env.get(), cb);
  824. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  825. unitToUpdate->setPosition(position);
  826. for(const battle::Unit * unit : turnQueue)
  827. {
  828. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  829. continue;
  830. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  831. float ratio = blockedUnitDamage / (float)(blockedUnitDamage + activeUnitDamage + 0.01);
  832. auto unitReachability = turnBattle.getReachability(unit);
  833. auto unitSpeed = unit->getMovementRange(turn); // Cached value, to avoid performance hit
  834. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); ++hex)
  835. {
  836. bool enemyUnit = false;
  837. bool reachable = unitReachability.distances.at(hex.toInt()) <= unitSpeed;
  838. if(!reachable && unitReachability.accessibility[hex.toInt()] == EAccessibility::ALIVE_STACK)
  839. {
  840. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  841. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  842. {
  843. enemyUnit = true;
  844. for(const BattleHex & neighbour : hex.getNeighbouringTiles())
  845. {
  846. reachable = unitReachability.distances.at(neighbour.toInt()) <= unitSpeed;
  847. if(reachable) break;
  848. }
  849. }
  850. }
  851. if(!reachable)
  852. {
  853. auto reachableUnits = getOneTurnReachableUnits(0, hex);
  854. if (std::count(reachableUnits.begin(), reachableUnits.end(), unit) > 1)
  855. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  856. }
  857. }
  858. }
  859. }
  860. #if BATTLE_TRACE_LEVEL>=1
  861. logAi->trace("Position %d, blocking score %f", position.toInt(), blockingScore);
  862. #endif
  863. return blockingScore > BLOCKING_THRESHOLD;
  864. }