BattleExchangeVariant.cpp 28 KB

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