BattleExchangeVariant.cpp 27 KB

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