BattleAI.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 <vstd/RNG.h>
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "PossibleSpellcast.h"
  16. #include "../../lib/CStopWatch.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/spells/CSpellHandler.h"
  19. #include "../../lib/spells/ISpellMechanics.h"
  20. #include "../../lib/CStack.h"//todo: remove
  21. #define LOGL(text) print(text)
  22. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  23. class RNGStub : public vstd::RNG
  24. {
  25. public:
  26. vstd::TRandI64 getInt64Range(int64_t lower, int64_t upper) override
  27. {
  28. return [=]()->int64_t
  29. {
  30. return (lower + upper)/2;
  31. };
  32. }
  33. vstd::TRand getDoubleRange(double lower, double upper) override
  34. {
  35. return [=]()->double
  36. {
  37. return (lower + upper)/2;
  38. };
  39. }
  40. };
  41. enum class SpellTypes
  42. {
  43. ADVENTURE, BATTLE, OTHER
  44. };
  45. SpellTypes spellType(const CSpell * spell)
  46. {
  47. if(!spell->isCombatSpell() || spell->isCreatureAbility())
  48. return SpellTypes::OTHER;
  49. if(spell->isOffensiveSpell() || spell->hasEffects() || spell->hasBattleEffects())
  50. return SpellTypes::BATTLE;
  51. return SpellTypes::OTHER;
  52. }
  53. CBattleAI::CBattleAI()
  54. : side(-1), wasWaitingForRealize(false), wasUnlockingGs(false)
  55. {
  56. }
  57. CBattleAI::~CBattleAI()
  58. {
  59. if(cb)
  60. {
  61. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  62. cb->waitTillRealize = wasWaitingForRealize;
  63. cb->unlockGsWhenWaiting = wasUnlockingGs;
  64. }
  65. }
  66. void CBattleAI::init(std::shared_ptr<CBattleCallback> CB)
  67. {
  68. setCbc(CB);
  69. cb = CB;
  70. playerID = *CB->getPlayerID(); //TODO should be sth in callback
  71. wasWaitingForRealize = cb->waitTillRealize;
  72. wasUnlockingGs = CB->unlockGsWhenWaiting;
  73. CB->waitTillRealize = true;
  74. CB->unlockGsWhenWaiting = false;
  75. }
  76. BattleAction CBattleAI::activeStack( const CStack * stack )
  77. {
  78. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName()) ;
  79. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  80. try
  81. {
  82. if(stack->type->idNumber == CreatureID::CATAPULT)
  83. return useCatapult(stack);
  84. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->hasBonusOfType(Bonus::HEALER))
  85. {
  86. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  87. std::map<int, const CStack*> woundHpToStack;
  88. for(auto stack : healingTargets)
  89. if(auto woundHp = stack->MaxHealth() - stack->getFirstHPleft())
  90. woundHpToStack[woundHp] = stack;
  91. if(woundHpToStack.empty())
  92. return BattleAction::makeDefend(stack);
  93. else
  94. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  95. }
  96. attemptCastingSpell();
  97. if(auto ret = getCbc()->battleIsFinished())
  98. {
  99. //spellcast may finish battle
  100. //send special preudo-action
  101. BattleAction cancel;
  102. cancel.actionType = EActionType::CANCEL;
  103. return cancel;
  104. }
  105. if(auto action = considerFleeingOrSurrendering())
  106. return *action;
  107. //best action is from effective owner point if view, we are effective owner as we received "activeStack"
  108. HypotheticBattle hb(getCbc());
  109. PotentialTargets targets(stack, &hb);
  110. if(targets.possibleAttacks.size())
  111. {
  112. auto hlp = targets.bestAction();
  113. if(hlp.attack.shooting)
  114. return BattleAction::makeShotAttack(stack, hlp.attack.defender);
  115. else
  116. return BattleAction::makeMeleeAttack(stack, hlp.attack.defender->getPosition(), hlp.tile);
  117. }
  118. else
  119. {
  120. if(stack->waited())
  121. {
  122. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  123. auto dists = getCbc()->battleGetDistances(stack, stack->getPosition());
  124. if(!targets.unreachableEnemies.empty())
  125. {
  126. const EnemyInfo &ei= *range::min_element(targets.unreachableEnemies, std::bind(isCloser, _1, _2, std::ref(dists)));
  127. if(distToNearestNeighbour(ei.s->getPosition(), dists) < GameConstants::BFIELD_SIZE)
  128. {
  129. return goTowards(stack, ei.s->getPosition());
  130. }
  131. }
  132. }
  133. else
  134. {
  135. return BattleAction::makeWait(stack);
  136. }
  137. }
  138. }
  139. catch(boost::thread_interrupted &)
  140. {
  141. throw;
  142. }
  143. catch(std::exception &e)
  144. {
  145. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  146. }
  147. return BattleAction::makeDefend(stack);
  148. }
  149. BattleAction CBattleAI::goTowards(const CStack * stack, BattleHex destination)
  150. {
  151. if(!destination.isValid())
  152. {
  153. logAi->error("CBattleAI::goTowards: invalid destination");
  154. return BattleAction::makeDefend(stack);
  155. }
  156. auto reachability = cb->getReachability(stack);
  157. auto avHexes = cb->battleGetAvailableHexes(reachability, stack);
  158. if(vstd::contains(avHexes, destination))
  159. return BattleAction::makeMove(stack, destination);
  160. auto destNeighbours = destination.neighbouringTiles();
  161. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  162. {
  163. logAi->warn("Warning: already standing on neighbouring tile!");
  164. //We shouldn't even be here...
  165. return BattleAction::makeDefend(stack);
  166. }
  167. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  168. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  169. {
  170. return BattleAction::makeDefend(stack);
  171. }
  172. if(stack->hasBonusOfType(Bonus::FLYING))
  173. {
  174. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  175. // We just check all available hexes and pick the one closest to the target.
  176. auto distToDestNeighbour = [&](BattleHex hex) -> int
  177. {
  178. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  179. {return BattleHex::getDistance(a, hex);});
  180. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  181. };
  182. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  183. return BattleAction::makeMove(stack, *nearestAvailableHex);
  184. }
  185. else
  186. {
  187. BattleHex bestNeighbor = destination;
  188. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  189. {
  190. return BattleAction::makeDefend(stack);
  191. }
  192. BattleHex currentDest = bestNeighbor;
  193. while(1)
  194. {
  195. if(!currentDest.isValid())
  196. {
  197. logAi->error("CBattleAI::goTowards: internal error");
  198. return BattleAction::makeDefend(stack);
  199. }
  200. if(vstd::contains(avHexes, currentDest))
  201. return BattleAction::makeMove(stack, currentDest);
  202. currentDest = reachability.predecessors[currentDest];
  203. }
  204. }
  205. }
  206. BattleAction CBattleAI::useCatapult(const CStack * stack)
  207. {
  208. throw std::runtime_error("CBattleAI::useCatapult is not implemented.");
  209. }
  210. void CBattleAI::attemptCastingSpell()
  211. {
  212. auto hero = cb->battleGetMyHero();
  213. if(!hero)
  214. return;
  215. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  216. return;
  217. LOGL("Casting spells sounds like fun. Let's see...");
  218. //Get all spells we can cast
  219. std::vector<const CSpell*> possibleSpells;
  220. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero](const CSpell *s) -> bool
  221. {
  222. return s->canBeCast(getCbc().get(), spells::Mode::HERO, hero);
  223. });
  224. LOGFL("I can cast %d spells.", possibleSpells.size());
  225. vstd::erase_if(possibleSpells, [](const CSpell *s)
  226. {
  227. return spellType(s) != SpellTypes::BATTLE;
  228. });
  229. LOGFL("I know how %d of them works.", possibleSpells.size());
  230. //Get possible spell-target pairs
  231. std::vector<PossibleSpellcast> possibleCasts;
  232. for(auto spell : possibleSpells)
  233. {
  234. spells::BattleCast temp(getCbc().get(), hero, spells::Mode::HERO, spell);
  235. for(auto & target : temp.findPotentialTargets())
  236. {
  237. PossibleSpellcast ps;
  238. ps.dest = target;
  239. ps.spell = spell;
  240. possibleCasts.push_back(ps);
  241. }
  242. }
  243. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  244. if(possibleCasts.empty())
  245. return;
  246. using ValueMap = PossibleSpellcast::ValueMap;
  247. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle * state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  248. {
  249. bool firstRound = true;
  250. bool enemyHadTurn = false;
  251. size_t ourTurnSpan = 0;
  252. bool stop = false;
  253. for(auto & round : queue)
  254. {
  255. if(!firstRound)
  256. state->nextRound(0);//todo: set actual value?
  257. for(auto unit : round)
  258. {
  259. if(!vstd::contains(values, unit->unitId()))
  260. values[unit->unitId()] = 0;
  261. if(!unit->alive())
  262. continue;
  263. if(state->battleGetOwner(unit) != playerID)
  264. {
  265. enemyHadTurn = true;
  266. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  267. {
  268. //enemy could counter our spell at this point
  269. //anyway, we do not know what enemy will do
  270. //just stop evaluation
  271. stop = true;
  272. break;
  273. }
  274. }
  275. else if(!enemyHadTurn)
  276. {
  277. ourTurnSpan++;
  278. }
  279. state->nextTurn(unit->unitId());
  280. PotentialTargets pt(unit, state);
  281. if(!pt.possibleAttacks.empty())
  282. {
  283. AttackPossibility ap = pt.bestAction();
  284. auto swb = state->getForUpdate(unit->unitId());
  285. *swb = *ap.attackerState;
  286. if(ap.damageDealt > 0)
  287. swb->removeUnitBonus(Bonus::UntilAttack);
  288. if(ap.damageReceived > 0)
  289. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  290. for(auto affected : ap.affectedUnits)
  291. {
  292. swb = state->getForUpdate(affected->unitId());
  293. *swb = *affected;
  294. if(ap.damageDealt > 0)
  295. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  296. if(ap.damageReceived > 0 && ap.attack.defender->unitId() == affected->unitId())
  297. swb->removeUnitBonus(Bonus::UntilAttack);
  298. }
  299. }
  300. auto bav = pt.bestActionValue();
  301. //best action is from effective owner`s point if view, we need to convert to our point if view
  302. if(state->battleGetOwner(unit) != playerID)
  303. bav = -bav;
  304. values[unit->unitId()] += bav;
  305. }
  306. firstRound = false;
  307. if(stop)
  308. break;
  309. }
  310. if(enemyHadTurnOut)
  311. *enemyHadTurnOut = enemyHadTurn;
  312. return ourTurnSpan >= minTurnSpan;
  313. };
  314. RNGStub rngStub;
  315. ValueMap valueOfStack;
  316. ValueMap healthOfStack;
  317. TStacks all = cb->battleGetAllStacks(false);
  318. size_t ourRemainingTurns = 0;
  319. for(auto unit : all)
  320. {
  321. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  322. valueOfStack[unit->unitId()] = 0;
  323. if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  324. ourRemainingTurns++;
  325. }
  326. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  327. const bool castNow = ourRemainingTurns <= 1;
  328. if(castNow)
  329. print("I should try to cast a spell now");
  330. else
  331. print("I could wait better moment to cast a spell");
  332. auto amount = all.size();
  333. std::vector<battle::Units> turnOrder;
  334. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  335. {
  336. bool enemyHadTurn = false;
  337. HypotheticBattle state(cb);
  338. evaluateQueue(valueOfStack, turnOrder, &state, 0, &enemyHadTurn);
  339. if(!enemyHadTurn)
  340. {
  341. auto battleIsFinishedOpt = state.battleIsFinished();
  342. if(battleIsFinishedOpt)
  343. {
  344. print("No need to cast a spell. Battle will finish soon.");
  345. return;
  346. }
  347. }
  348. }
  349. auto evaluateSpellcast = [&] (PossibleSpellcast * ps)
  350. {
  351. HypotheticBattle state(cb);
  352. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  353. cast.target = ps->dest;
  354. cast.cast(&state, rngStub);
  355. ValueMap newHealthOfStack;
  356. ValueMap newValueOfStack;
  357. size_t ourUnits = 0;
  358. for(auto unit : all)
  359. {
  360. auto unitId = unit->unitId();
  361. auto localUnit = state.battleGetUnitByID(unitId);
  362. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  363. newValueOfStack[unitId] = 0;
  364. if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
  365. ourUnits++;
  366. }
  367. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  368. std::vector<battle::Units> newTurnOrder;
  369. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  370. const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, &state, minTurnSpan, nullptr);
  371. if(turnSpanOK || castNow)
  372. {
  373. int64_t totalGain = 0;
  374. for(auto unit : all)
  375. {
  376. auto unitId = unit->unitId();
  377. auto localUnit = state.battleGetUnitByID(unitId);
  378. auto newValue = getValOr(newValueOfStack, unitId, 0);
  379. auto oldValue = getValOr(valueOfStack, unitId, 0);
  380. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  381. if(localUnit->unitOwner() != playerID)
  382. healthDiff = -healthDiff;
  383. if(healthDiff < 0)
  384. {
  385. ps->value = -1;
  386. return; //do not damage own units at all
  387. }
  388. totalGain += (newValue - oldValue + healthDiff);
  389. }
  390. ps->value = totalGain;
  391. }
  392. else
  393. {
  394. ps->value = -1;
  395. }
  396. };
  397. std::vector<std::function<void()>> tasks;
  398. for(PossibleSpellcast & psc : possibleCasts)
  399. tasks.push_back(std::bind(evaluateSpellcast, &psc));
  400. uint32_t threadCount = boost::thread::hardware_concurrency();
  401. if(threadCount == 0)
  402. {
  403. logGlobal->warn("No information of CPU cores available");
  404. threadCount = 1;
  405. }
  406. CStopWatch timer;
  407. CThreadHelper threadHelper(&tasks, threadCount);
  408. threadHelper.run();
  409. LOGFL("Evaluation took %d ms", timer.getDiff());
  410. auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
  411. {
  412. return ps.value;
  413. };
  414. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  415. if(castToPerform.value > 0)
  416. {
  417. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->name % castToPerform.value);
  418. BattleAction spellcast;
  419. spellcast.actionType = EActionType::HERO_SPELL;
  420. spellcast.actionSubtype = castToPerform.spell->id;
  421. spellcast.setTarget(castToPerform.dest);
  422. spellcast.side = side;
  423. spellcast.stackNumber = (!side) ? -1 : -2;
  424. cb->battleMakeAction(&spellcast);
  425. }
  426. else
  427. {
  428. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->name % castToPerform.value);
  429. }
  430. }
  431. int CBattleAI::distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances &dists, BattleHex *chosenHex)
  432. {
  433. int ret = 1000000;
  434. for(BattleHex n : hex.neighbouringTiles())
  435. {
  436. if(dists[n] >= 0 && dists[n] < ret)
  437. {
  438. ret = dists[n];
  439. if(chosenHex)
  440. *chosenHex = n;
  441. }
  442. }
  443. return ret;
  444. }
  445. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  446. {
  447. LOG_TRACE(logAi);
  448. side = Side;
  449. }
  450. bool CBattleAI::isCloser(const EnemyInfo &ei1, const EnemyInfo &ei2, const ReachabilityInfo::TDistances &dists)
  451. {
  452. return distToNearestNeighbour(ei1.s->getPosition(), dists) < distToNearestNeighbour(ei2.s->getPosition(), dists);
  453. }
  454. void CBattleAI::print(const std::string &text) const
  455. {
  456. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  457. }
  458. boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  459. {
  460. if(cb->battleCanSurrender(playerID))
  461. {
  462. }
  463. if(cb->battleCanFlee())
  464. {
  465. }
  466. return boost::none;
  467. }