BattleAI.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 "BattleAI.h"
  12. #include "BattleEvaluator.h"
  13. #include "BattleExchangeVariant.h"
  14. #include "StackWithBonuses.h"
  15. #include "EnemyInfo.h"
  16. #include "tbb/parallel_for.h"
  17. #include "../../lib/CStopWatch.h"
  18. #include "../../lib/CThreadHelper.h"
  19. #include "../../lib/mapObjects/CGTownInstance.h"
  20. #include "../../lib/spells/CSpellHandler.h"
  21. #include "../../lib/spells/ISpellMechanics.h"
  22. #include "../../lib/battle/BattleAction.h"
  23. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  24. #include "../../lib/battle/CObstacleInstance.h"
  25. #include "../../lib/StartInfo.h"
  26. #include "../../lib/CStack.h" // TODO: remove
  27. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  28. // CUnitState should be private and CStack should be removed completely
  29. #include "../../lib/logging/VisualLogger.h"
  30. #define LOGL(text) print(text)
  31. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  32. CBattleAI::CBattleAI()
  33. : side(BattleSide::NONE),
  34. wasWaitingForRealize(false),
  35. wasUnlockingGs(false)
  36. {
  37. }
  38. CBattleAI::~CBattleAI()
  39. {
  40. if(cb)
  41. {
  42. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  43. cb->waitTillRealize = wasWaitingForRealize;
  44. cb->unlockGsWhenWaiting = wasUnlockingGs;
  45. }
  46. }
  47. void logHexNumbers()
  48. {
  49. #if BATTLE_TRACE_LEVEL >= 1
  50. logVisual->updateWithLock("hexes", [](IVisualLogBuilder & b)
  51. {
  52. for(BattleHex hex = BattleHex(0); hex < GameConstants::BFIELD_SIZE; ++hex)
  53. b.addText(hex, std::to_string(hex.toInt()));
  54. });
  55. #endif
  56. }
  57. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  58. {
  59. env = ENV;
  60. cb = CB;
  61. playerID = *CB->getPlayerID();
  62. wasWaitingForRealize = CB->waitTillRealize;
  63. wasUnlockingGs = CB->unlockGsWhenWaiting;
  64. CB->waitTillRealize = false;
  65. CB->unlockGsWhenWaiting = false;
  66. movesSkippedByDefense = 0;
  67. logHexNumbers();
  68. }
  69. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB, AutocombatPreferences autocombatPreferences)
  70. {
  71. initBattleInterface(ENV, CB);
  72. autobattlePreferences = autocombatPreferences;
  73. }
  74. BattleAction CBattleAI::useHealingTent(const BattleID & battleID, const CStack *stack)
  75. {
  76. auto healingTargets = cb->getBattle(battleID)->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  77. std::map<int, const CStack*> woundHpToStack;
  78. for(const auto * stack : healingTargets)
  79. {
  80. if(auto woundHp = stack->getMaxHealth() - stack->getFirstHPleft())
  81. woundHpToStack[woundHp] = stack;
  82. }
  83. if(woundHpToStack.empty())
  84. return BattleAction::makeDefend(stack);
  85. else
  86. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  87. }
  88. void CBattleAI::yourTacticPhase(const BattleID & battleID, int distance)
  89. {
  90. cb->battleMakeTacticAction(battleID, BattleAction::makeEndOFTacticPhase(cb->getBattle(battleID)->battleGetTacticsSide()));
  91. }
  92. static float getStrengthRatio(std::shared_ptr<CBattleInfoCallback> cb, BattleSide side)
  93. {
  94. auto stacks = cb->battleGetAllStacks();
  95. auto our = 0;
  96. auto enemy = 0;
  97. for(auto stack : stacks)
  98. {
  99. auto creature = stack->creatureId().toCreature();
  100. if(!creature)
  101. continue;
  102. if(stack->unitSide() == side)
  103. our += stack->getCount() * creature->getAIValue();
  104. else
  105. enemy += stack->getCount() * creature->getAIValue();
  106. }
  107. return enemy == 0 ? 1.0f : static_cast<float>(our) / enemy;
  108. }
  109. int getSimulationTurnsCount(const StartInfo * startInfo)
  110. {
  111. return startInfo->difficulty < 4 ? 2 : 10;
  112. }
  113. void CBattleAI::activeStack(const BattleID & battleID, const CStack * stack )
  114. {
  115. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
  116. auto timeElapsed = [](std::chrono::time_point<std::chrono::high_resolution_clock> start) -> uint64_t
  117. {
  118. auto end = std::chrono::high_resolution_clock::now();
  119. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  120. };
  121. BattleAction result = BattleAction::makeDefend(stack);
  122. auto start = std::chrono::high_resolution_clock::now();
  123. try
  124. {
  125. if(stack->creatureId() == CreatureID::CATAPULT)
  126. {
  127. cb->battleMakeUnitAction(battleID, useCatapult(battleID, stack));
  128. return;
  129. }
  130. if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON) && stack->hasBonusOfType(BonusType::HEALER))
  131. {
  132. cb->battleMakeUnitAction(battleID, useHealingTent(battleID, stack));
  133. return;
  134. }
  135. #if BATTLE_TRACE_LEVEL>=1
  136. logAi->trace("Build evaluator and targets");
  137. #endif
  138. BattleEvaluator evaluator(
  139. env, cb, stack, playerID, battleID, side,
  140. getStrengthRatio(cb->getBattle(battleID), side),
  141. getSimulationTurnsCount(env->game()->getStartInfo()));
  142. result = evaluator.selectStackAction(stack);
  143. if(autobattlePreferences.enableSpellsUsage && evaluator.canCastSpell())
  144. {
  145. auto spelCasted = evaluator.attemptCastingSpell(stack);
  146. if(spelCasted)
  147. return;
  148. }
  149. logAi->trace("Spellcast attempt completed in %lld", timeElapsed(start));
  150. if(auto action = considerFleeingOrSurrendering(battleID))
  151. {
  152. cb->battleMakeUnitAction(battleID, *action);
  153. return;
  154. }
  155. }
  156. catch(boost::thread_interrupted &)
  157. {
  158. throw;
  159. }
  160. if(result.actionType == EActionType::DEFEND)
  161. {
  162. movesSkippedByDefense++;
  163. }
  164. else if(result.actionType != EActionType::WAIT)
  165. {
  166. movesSkippedByDefense = 0;
  167. }
  168. logAi->trace("BattleAI decision made in %lld", timeElapsed(start));
  169. cb->battleMakeUnitAction(battleID, result);
  170. }
  171. BattleAction CBattleAI::useCatapult(const BattleID & battleID, const CStack * stack)
  172. {
  173. BattleAction attack;
  174. BattleHex targetHex = BattleHex::INVALID;
  175. if(cb->getBattle(battleID)->battleGetGateState() == EGateState::CLOSED)
  176. {
  177. targetHex = cb->getBattle(battleID)->wallPartToBattleHex(EWallPart::GATE);
  178. }
  179. else
  180. {
  181. std::array wallParts {
  182. EWallPart::KEEP,
  183. EWallPart::BOTTOM_TOWER,
  184. EWallPart::UPPER_TOWER,
  185. EWallPart::BELOW_GATE,
  186. EWallPart::OVER_GATE,
  187. EWallPart::BOTTOM_WALL,
  188. EWallPart::UPPER_WALL
  189. };
  190. for(auto wallPart : wallParts)
  191. {
  192. auto wallState = cb->getBattle(battleID)->battleGetWallState(wallPart);
  193. if(wallState != EWallState::NONE && wallState != EWallState::DESTROYED)
  194. {
  195. targetHex = cb->getBattle(battleID)->wallPartToBattleHex(wallPart);
  196. break;
  197. }
  198. }
  199. }
  200. if(!targetHex.isValid())
  201. {
  202. return BattleAction::makeDefend(stack);
  203. }
  204. attack.aimToHex(targetHex);
  205. attack.actionType = EActionType::CATAPULT;
  206. attack.side = side;
  207. attack.stackNumber = stack->unitId();
  208. movesSkippedByDefense = 0;
  209. return attack;
  210. }
  211. void CBattleAI::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, BattleSide Side, bool replayAllowed)
  212. {
  213. LOG_TRACE(logAi);
  214. side = Side;
  215. }
  216. void CBattleAI::print(const std::string &text) const
  217. {
  218. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  219. }
  220. std::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering(const BattleID & battleID)
  221. {
  222. BattleStateInfoForRetreat bs;
  223. bs.canFlee = cb->getBattle(battleID)->battleCanFlee();
  224. bs.canSurrender = cb->getBattle(battleID)->battleCanSurrender(playerID);
  225. bs.ourSide = cb->getBattle(battleID)->battleGetMySide();
  226. bs.ourHero = cb->getBattle(battleID)->battleGetMyHero();
  227. bs.enemyHero = nullptr;
  228. for(auto stack : cb->getBattle(battleID)->battleGetAllStacks(false))
  229. {
  230. if(stack->alive())
  231. {
  232. if(stack->unitSide() == bs.ourSide)
  233. bs.ourStacks.push_back(stack);
  234. else
  235. {
  236. bs.enemyStacks.push_back(stack);
  237. bs.enemyHero = cb->getBattle(battleID)->battleGetOwnerHero(stack);
  238. }
  239. }
  240. }
  241. bs.turnsSkippedByDefense = movesSkippedByDefense / bs.ourStacks.size();
  242. if(!bs.canFlee && !bs.canSurrender)
  243. {
  244. return std::nullopt;
  245. }
  246. auto result = cb->makeSurrenderRetreatDecision(battleID, bs);
  247. if(!result && bs.canFlee && bs.turnsSkippedByDefense > 30)
  248. {
  249. return BattleAction::makeRetreat(bs.ourSide);
  250. }
  251. return result;
  252. }