BattleExchangeVariant.cpp 27 KB

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