BattleAI.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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 "BattleExchangeVariant.h"
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "../../lib/CStopWatch.h"
  16. #include "../../lib/CThreadHelper.h"
  17. #include "../../lib/mapObjects/CGTownInstance.h"
  18. #include "../../lib/spells/CSpellHandler.h"
  19. #include "../../lib/spells/ISpellMechanics.h"
  20. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  21. #include "../../lib/battle/CObstacleInstance.h"
  22. #include "../../lib/CStack.h" // TODO: remove
  23. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  24. // CUnitState should be private and CStack should be removed completely
  25. #define LOGL(text) print(text)
  26. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  27. enum class SpellTypes
  28. {
  29. ADVENTURE, BATTLE, OTHER
  30. };
  31. SpellTypes spellType(const CSpell * spell)
  32. {
  33. if(!spell->isCombat() || spell->isCreatureAbility())
  34. return SpellTypes::OTHER;
  35. if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
  36. return SpellTypes::BATTLE;
  37. return SpellTypes::OTHER;
  38. }
  39. std::vector<BattleHex> CBattleAI::getBrokenWallMoatHexes() const
  40. {
  41. std::vector<BattleHex> result;
  42. for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
  43. {
  44. auto state = cb->battleGetWallState(wallPart);
  45. if(state != EWallState::DESTROYED)
  46. continue;
  47. auto wallHex = cb->wallPartToBattleHex((EWallPart)wallPart);
  48. auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
  49. result.push_back(moatHex);
  50. }
  51. return result;
  52. }
  53. CBattleAI::CBattleAI()
  54. : side(-1),
  55. wasWaitingForRealize(false),
  56. wasUnlockingGs(false)
  57. {
  58. }
  59. CBattleAI::~CBattleAI()
  60. {
  61. if(cb)
  62. {
  63. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  64. cb->waitTillRealize = wasWaitingForRealize;
  65. cb->unlockGsWhenWaiting = wasUnlockingGs;
  66. }
  67. }
  68. void CBattleAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  69. {
  70. setCbc(CB);
  71. env = ENV;
  72. cb = CB;
  73. playerID = *CB->getPlayerID(); //TODO should be sth in callback
  74. wasWaitingForRealize = CB->waitTillRealize;
  75. wasUnlockingGs = CB->unlockGsWhenWaiting;
  76. CB->waitTillRealize = false;
  77. CB->unlockGsWhenWaiting = false;
  78. movesSkippedByDefense = 0;
  79. }
  80. BattleAction CBattleAI::useHealingTent(const CStack *stack)
  81. {
  82. auto healingTargets = cb->battleGetStacks(CBattleInfoEssentials::ONLY_MINE);
  83. std::map<int, const CStack*> woundHpToStack;
  84. for(const auto * stack : healingTargets)
  85. {
  86. if(auto woundHp = stack->getMaxHealth() - stack->getFirstHPleft())
  87. woundHpToStack[woundHp] = stack;
  88. }
  89. if(woundHpToStack.empty())
  90. return BattleAction::makeDefend(stack);
  91. else
  92. return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
  93. }
  94. std::optional<PossibleSpellcast> CBattleAI::findBestCreatureSpell(const CStack *stack)
  95. {
  96. //TODO: faerie dragon type spell should be selected by server
  97. SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
  98. if(stack->hasBonusOfType(BonusType::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
  99. {
  100. const CSpell * spell = creatureSpellToCast.toSpell();
  101. if(spell->canBeCast(getCbc().get(), spells::Mode::CREATURE_ACTIVE, stack))
  102. {
  103. std::vector<PossibleSpellcast> possibleCasts;
  104. spells::BattleCast temp(getCbc().get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  105. for(auto & target : temp.findPotentialTargets())
  106. {
  107. PossibleSpellcast ps;
  108. ps.dest = target;
  109. ps.spell = spell;
  110. evaluateCreatureSpellcast(stack, ps);
  111. possibleCasts.push_back(ps);
  112. }
  113. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  114. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  115. {
  116. return possibleCasts.front();
  117. }
  118. }
  119. }
  120. return std::nullopt;
  121. }
  122. BattleAction CBattleAI::selectStackAction(const CStack * stack)
  123. {
  124. //evaluate casting spell for spellcasting stack
  125. std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
  126. HypotheticBattle hb(env.get(), cb);
  127. PotentialTargets targets(stack, hb);
  128. BattleExchangeEvaluator scoreEvaluator(cb, env);
  129. auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, targets, hb);
  130. int64_t score = EvaluationResult::INEFFECTIVE_SCORE;
  131. if(targets.possibleAttacks.empty() && bestSpellcast.has_value())
  132. {
  133. movesSkippedByDefense = 0;
  134. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  135. }
  136. if(!targets.possibleAttacks.empty())
  137. {
  138. #if BATTLE_TRACE_LEVEL>=1
  139. logAi->trace("Evaluating attack for %s", stack->getDescription());
  140. #endif
  141. auto evaluationResult = scoreEvaluator.findBestTarget(stack, targets, hb);
  142. auto & bestAttack = evaluationResult.bestAttack;
  143. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  144. if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
  145. {
  146. // return because spellcast value is damage dealt and score is dps reduce
  147. movesSkippedByDefense = 0;
  148. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  149. }
  150. if(evaluationResult.score > score)
  151. {
  152. score = evaluationResult.score;
  153. logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%lld -%lld = %lld",
  154. bestAttack.attackerState->unitType()->getJsonKey(),
  155. bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
  156. (int)bestAttack.affectedUnits[0]->getCount(),
  157. (int)bestAttack.from,
  158. (int)bestAttack.attack.attacker->getPosition().hex,
  159. bestAttack.attack.chargeDistance,
  160. bestAttack.attack.attacker->speed(0, true),
  161. bestAttack.defenderDamageReduce,
  162. bestAttack.attackerDamageReduce, bestAttack.attackValue()
  163. );
  164. if (moveTarget.score <= score)
  165. {
  166. if(evaluationResult.wait)
  167. {
  168. return BattleAction::makeWait(stack);
  169. }
  170. else if(bestAttack.attack.shooting)
  171. {
  172. movesSkippedByDefense = 0;
  173. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  174. }
  175. else
  176. {
  177. movesSkippedByDefense = 0;
  178. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  179. }
  180. }
  181. }
  182. }
  183. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  184. if(moveTarget.score > score)
  185. {
  186. score = moveTarget.score;
  187. if(stack->waited())
  188. {
  189. return goTowardsNearest(stack, moveTarget.positions);
  190. }
  191. else
  192. {
  193. return BattleAction::makeWait(stack);
  194. }
  195. }
  196. if(score <= EvaluationResult::INEFFECTIVE_SCORE
  197. && !stack->hasBonusOfType(BonusType::FLYING)
  198. && stack->unitSide() == BattleSide::ATTACKER
  199. && cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  200. {
  201. auto brokenWallMoat = getBrokenWallMoatHexes();
  202. if(brokenWallMoat.size())
  203. {
  204. movesSkippedByDefense = 0;
  205. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  206. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  207. else
  208. return goTowardsNearest(stack, brokenWallMoat);
  209. }
  210. }
  211. return BattleAction::makeDefend(stack);
  212. }
  213. void CBattleAI::yourTacticPhase(int distance)
  214. {
  215. cb->battleMakeTacticAction(BattleAction::makeEndOFTacticPhase(cb->battleGetTacticsSide()));
  216. }
  217. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  218. {
  219. auto end = std::chrono::high_resolution_clock::now();
  220. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  221. }
  222. void CBattleAI::activeStack( const CStack * stack )
  223. {
  224. LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
  225. BattleAction result = BattleAction::makeDefend(stack);
  226. setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
  227. auto start = std::chrono::high_resolution_clock::now();
  228. try
  229. {
  230. if(stack->creatureId() == CreatureID::CATAPULT)
  231. {
  232. cb->battleMakeUnitAction(useCatapult(stack));
  233. return;
  234. }
  235. if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON) && stack->hasBonusOfType(BonusType::HEALER))
  236. {
  237. cb->battleMakeUnitAction(useHealingTent(stack));
  238. return;
  239. }
  240. attemptCastingSpell();
  241. logAi->trace("Spellcast attempt completed in %lld", timeElapsed(start));
  242. if(cb->battleIsFinished() || !stack->alive())
  243. {
  244. //spellcast may finish battle or kill active stack
  245. //send special preudo-action
  246. BattleAction cancel;
  247. cancel.actionType = EActionType::CANCEL;
  248. cb->battleMakeUnitAction(cancel);
  249. return;
  250. }
  251. if(auto action = considerFleeingOrSurrendering())
  252. {
  253. cb->battleMakeUnitAction(*action);
  254. return;
  255. }
  256. result = selectStackAction(stack);
  257. }
  258. catch(boost::thread_interrupted &)
  259. {
  260. throw;
  261. }
  262. catch(std::exception &e)
  263. {
  264. logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what());
  265. }
  266. if(result.actionType == EActionType::DEFEND)
  267. {
  268. movesSkippedByDefense++;
  269. }
  270. else if(result.actionType != EActionType::WAIT)
  271. {
  272. movesSkippedByDefense = 0;
  273. }
  274. logAi->trace("BattleAI decission made in %lld", timeElapsed(start));
  275. cb->battleMakeUnitAction(result);
  276. }
  277. BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes) const
  278. {
  279. auto reachability = cb->getReachability(stack);
  280. auto avHexes = cb->battleGetAvailableHexes(reachability, stack, false);
  281. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  282. {
  283. return BattleAction::makeDefend(stack);
  284. }
  285. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  286. {
  287. return reachability.distances[h1] < reachability.distances[h2];
  288. });
  289. for(auto hex : hexes)
  290. {
  291. if(vstd::contains(avHexes, hex))
  292. {
  293. return BattleAction::makeMove(stack, hex);
  294. }
  295. if(stack->coversPos(hex))
  296. {
  297. logAi->warn("Warning: already standing on neighbouring tile!");
  298. //We shouldn't even be here...
  299. return BattleAction::makeDefend(stack);
  300. }
  301. }
  302. BattleHex bestNeighbor = hexes.front();
  303. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  304. {
  305. return BattleAction::makeDefend(stack);
  306. }
  307. BattleExchangeEvaluator scoreEvaluator(cb, env);
  308. HypotheticBattle hb(env.get(), cb);
  309. scoreEvaluator.updateReachabilityMap(hb);
  310. if(stack->hasBonusOfType(BonusType::FLYING))
  311. {
  312. std::set<BattleHex> obstacleHexes;
  313. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  314. auto affectedHexes = spellObst.getAffectedTiles();
  315. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  316. };
  317. const auto & obstacles = hb.battleGetAllObstacles();
  318. for (const auto & obst: obstacles) {
  319. if(obst->triggersEffects())
  320. {
  321. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  322. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  323. if(triggerIsNegative)
  324. insertAffected(*obst, obstacleHexes);
  325. }
  326. }
  327. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  328. // We just check all available hexes and pick the one closest to the target.
  329. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  330. {
  331. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  332. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  333. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  334. if(vstd::contains(obstacleHexes, hex))
  335. distance += NEGATIVE_OBSTACLE_PENALTY;
  336. return scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  337. });
  338. return BattleAction::makeMove(stack, *nearestAvailableHex);
  339. }
  340. else
  341. {
  342. BattleHex currentDest = bestNeighbor;
  343. while(1)
  344. {
  345. if(!currentDest.isValid())
  346. {
  347. return BattleAction::makeDefend(stack);
  348. }
  349. if(vstd::contains(avHexes, currentDest)
  350. && !scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, currentDest))
  351. return BattleAction::makeMove(stack, currentDest);
  352. currentDest = reachability.predecessors[currentDest];
  353. }
  354. }
  355. }
  356. BattleAction CBattleAI::useCatapult(const CStack * stack)
  357. {
  358. BattleAction attack;
  359. BattleHex targetHex = BattleHex::INVALID;
  360. if(cb->battleGetGateState() == EGateState::CLOSED)
  361. {
  362. targetHex = cb->wallPartToBattleHex(EWallPart::GATE);
  363. }
  364. else
  365. {
  366. EWallPart wallParts[] = {
  367. EWallPart::KEEP,
  368. EWallPart::BOTTOM_TOWER,
  369. EWallPart::UPPER_TOWER,
  370. EWallPart::BELOW_GATE,
  371. EWallPart::OVER_GATE,
  372. EWallPart::BOTTOM_WALL,
  373. EWallPart::UPPER_WALL
  374. };
  375. for(auto wallPart : wallParts)
  376. {
  377. auto wallState = cb->battleGetWallState(wallPart);
  378. if(wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  379. {
  380. targetHex = cb->wallPartToBattleHex(wallPart);
  381. break;
  382. }
  383. }
  384. }
  385. if(!targetHex.isValid())
  386. {
  387. return BattleAction::makeDefend(stack);
  388. }
  389. attack.aimToHex(targetHex);
  390. attack.actionType = EActionType::CATAPULT;
  391. attack.side = side;
  392. attack.stackNumber = stack->unitId();
  393. movesSkippedByDefense = 0;
  394. return attack;
  395. }
  396. void CBattleAI::attemptCastingSpell()
  397. {
  398. auto hero = cb->battleGetMyHero();
  399. if(!hero)
  400. return;
  401. if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
  402. return;
  403. LOGL("Casting spells sounds like fun. Let's see...");
  404. //Get all spells we can cast
  405. std::vector<const CSpell*> possibleSpells;
  406. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
  407. {
  408. return s->canBeCast(cb.get(), spells::Mode::HERO, hero);
  409. });
  410. LOGFL("I can cast %d spells.", possibleSpells.size());
  411. vstd::erase_if(possibleSpells, [](const CSpell *s)
  412. {
  413. return spellType(s) != SpellTypes::BATTLE;
  414. });
  415. LOGFL("I know how %d of them works.", possibleSpells.size());
  416. //Get possible spell-target pairs
  417. std::vector<PossibleSpellcast> possibleCasts;
  418. for(auto spell : possibleSpells)
  419. {
  420. spells::BattleCast temp(cb.get(), hero, spells::Mode::HERO, spell);
  421. if(!spell->isDamage() && spell->getTargetType() == spells::AimType::LOCATION)
  422. continue;
  423. const bool FAST = true;
  424. for(auto & target : temp.findPotentialTargets(FAST))
  425. {
  426. PossibleSpellcast ps;
  427. ps.dest = target;
  428. ps.spell = spell;
  429. possibleCasts.push_back(ps);
  430. }
  431. }
  432. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  433. if(possibleCasts.empty())
  434. return;
  435. using ValueMap = PossibleSpellcast::ValueMap;
  436. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle & state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  437. {
  438. bool firstRound = true;
  439. bool enemyHadTurn = false;
  440. size_t ourTurnSpan = 0;
  441. bool stop = false;
  442. for(auto & round : queue)
  443. {
  444. if(!firstRound)
  445. state.nextRound(0);//todo: set actual value?
  446. for(auto unit : round)
  447. {
  448. if(!vstd::contains(values, unit->unitId()))
  449. values[unit->unitId()] = 0;
  450. if(!unit->alive())
  451. continue;
  452. if(state.battleGetOwner(unit) != playerID)
  453. {
  454. enemyHadTurn = true;
  455. if(!firstRound || state.battleCastSpells(unit->unitSide()) == 0)
  456. {
  457. //enemy could counter our spell at this point
  458. //anyway, we do not know what enemy will do
  459. //just stop evaluation
  460. stop = true;
  461. break;
  462. }
  463. }
  464. else if(!enemyHadTurn)
  465. {
  466. ourTurnSpan++;
  467. }
  468. state.nextTurn(unit->unitId());
  469. PotentialTargets pt(unit, state);
  470. if(!pt.possibleAttacks.empty())
  471. {
  472. AttackPossibility ap = pt.bestAction();
  473. auto swb = state.getForUpdate(unit->unitId());
  474. *swb = *ap.attackerState;
  475. if(ap.defenderDamageReduce > 0)
  476. swb->removeUnitBonus(Bonus::UntilAttack);
  477. if(ap.attackerDamageReduce > 0)
  478. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  479. for(auto affected : ap.affectedUnits)
  480. {
  481. swb = state.getForUpdate(affected->unitId());
  482. *swb = *affected;
  483. if(ap.defenderDamageReduce > 0)
  484. swb->removeUnitBonus(Bonus::UntilBeingAttacked);
  485. if(ap.attackerDamageReduce > 0 && ap.attack.defender->unitId() == affected->unitId())
  486. swb->removeUnitBonus(Bonus::UntilAttack);
  487. }
  488. }
  489. auto bav = pt.bestActionValue();
  490. //best action is from effective owner`s point if view, we need to convert to our point if view
  491. if(state.battleGetOwner(unit) != playerID)
  492. bav = -bav;
  493. values[unit->unitId()] += bav;
  494. }
  495. firstRound = false;
  496. if(stop)
  497. break;
  498. }
  499. if(enemyHadTurnOut)
  500. *enemyHadTurnOut = enemyHadTurn;
  501. return ourTurnSpan >= minTurnSpan;
  502. };
  503. ValueMap valueOfStack;
  504. ValueMap healthOfStack;
  505. TStacks all = cb->battleGetAllStacks(false);
  506. size_t ourRemainingTurns = 0;
  507. for(auto unit : all)
  508. {
  509. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  510. valueOfStack[unit->unitId()] = 0;
  511. if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  512. ourRemainingTurns++;
  513. }
  514. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  515. const bool castNow = ourRemainingTurns <= 1;
  516. if(castNow)
  517. print("I should try to cast a spell now");
  518. else
  519. print("I could wait better moment to cast a spell");
  520. auto amount = all.size();
  521. std::vector<battle::Units> turnOrder;
  522. cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  523. {
  524. bool enemyHadTurn = false;
  525. HypotheticBattle state(env.get(), cb);
  526. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  527. if(!enemyHadTurn)
  528. {
  529. auto battleIsFinishedOpt = state.battleIsFinished();
  530. if(battleIsFinishedOpt)
  531. {
  532. print("No need to cast a spell. Battle will finish soon.");
  533. return;
  534. }
  535. }
  536. }
  537. struct ScriptsCache
  538. {
  539. //todo: re-implement scripts context cache
  540. };
  541. auto evaluateSpellcast = [&] (PossibleSpellcast * ps, std::shared_ptr<ScriptsCache>)
  542. {
  543. HypotheticBattle state(env.get(), cb);
  544. spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
  545. cast.castEval(state.getServerCallback(), ps->dest);
  546. ValueMap newHealthOfStack;
  547. ValueMap newValueOfStack;
  548. size_t ourUnits = 0;
  549. std::set<uint32_t> unitIds;
  550. state.battleGetUnitsIf([&](const battle::Unit * u)->bool
  551. {
  552. if(!u->isGhost() && !u->isTurret())
  553. unitIds.insert(u->unitId());
  554. return false;
  555. });
  556. for(auto unitId : unitIds)
  557. {
  558. auto localUnit = state.battleGetUnitByID(unitId);
  559. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  560. newValueOfStack[unitId] = 0;
  561. if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
  562. ourUnits++;
  563. }
  564. size_t minTurnSpan = ourUnits/3; //todo: tweak this
  565. std::vector<battle::Units> newTurnOrder;
  566. state.battleGetTurnOrder(newTurnOrder, amount, 2);
  567. const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, state, minTurnSpan, nullptr);
  568. if(turnSpanOK || castNow)
  569. {
  570. int64_t totalGain = 0;
  571. for(auto unitId : unitIds)
  572. {
  573. auto localUnit = state.battleGetUnitByID(unitId);
  574. auto newValue = getValOr(newValueOfStack, unitId, 0);
  575. auto oldValue = getValOr(valueOfStack, unitId, 0);
  576. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  577. if(localUnit->unitOwner() != playerID)
  578. healthDiff = -healthDiff;
  579. if(healthDiff < 0)
  580. {
  581. ps->value = -1;
  582. return; //do not damage own units at all
  583. }
  584. totalGain += (newValue - oldValue + healthDiff);
  585. }
  586. ps->value = totalGain;
  587. }
  588. else
  589. {
  590. ps->value = -1;
  591. }
  592. };
  593. using EvalRunner = ThreadPool<ScriptsCache>;
  594. EvalRunner::Tasks tasks;
  595. for(PossibleSpellcast & psc : possibleCasts)
  596. tasks.push_back(std::bind(evaluateSpellcast, &psc, _1));
  597. uint32_t threadCount = boost::thread::hardware_concurrency();
  598. if(threadCount == 0)
  599. {
  600. logGlobal->warn("No information of CPU cores available");
  601. threadCount = 1;
  602. }
  603. CStopWatch timer;
  604. std::vector<std::shared_ptr<ScriptsCache>> scriptsPool;
  605. for(uint32_t idx = 0; idx < threadCount; idx++)
  606. {
  607. scriptsPool.emplace_back();
  608. }
  609. EvalRunner runner(&tasks, scriptsPool);
  610. runner.run();
  611. LOGFL("Evaluation took %d ms", timer.getDiff());
  612. auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
  613. {
  614. return ps.value;
  615. };
  616. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  617. if(castToPerform.value > 0)
  618. {
  619. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  620. BattleAction spellcast;
  621. spellcast.actionType = EActionType::HERO_SPELL;
  622. spellcast.actionSubtype = castToPerform.spell->id;
  623. spellcast.setTarget(castToPerform.dest);
  624. spellcast.side = side;
  625. spellcast.stackNumber = (!side) ? -1 : -2;
  626. cb->battleMakeSpellAction(spellcast);
  627. movesSkippedByDefense = 0;
  628. }
  629. else
  630. {
  631. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  632. }
  633. }
  634. //Below method works only for offensive spells
  635. void CBattleAI::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  636. {
  637. using ValueMap = PossibleSpellcast::ValueMap;
  638. RNGStub rngStub;
  639. HypotheticBattle state(env.get(), cb);
  640. TStacks all = cb->battleGetAllStacks(false);
  641. ValueMap healthOfStack;
  642. ValueMap newHealthOfStack;
  643. for(auto unit : all)
  644. {
  645. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  646. }
  647. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  648. cast.castEval(state.getServerCallback(), ps.dest);
  649. for(auto unit : all)
  650. {
  651. auto unitId = unit->unitId();
  652. auto localUnit = state.battleGetUnitByID(unitId);
  653. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  654. }
  655. int64_t totalGain = 0;
  656. for(auto unit : all)
  657. {
  658. auto unitId = unit->unitId();
  659. auto localUnit = state.battleGetUnitByID(unitId);
  660. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  661. if(localUnit->unitOwner() != getCbc()->getPlayerID())
  662. healthDiff = -healthDiff;
  663. if(healthDiff < 0)
  664. {
  665. ps.value = -1;
  666. return; //do not damage own units at all
  667. }
  668. totalGain += healthDiff;
  669. }
  670. ps.value = totalGain;
  671. }
  672. void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side, bool replayAllowed)
  673. {
  674. LOG_TRACE(logAi);
  675. side = Side;
  676. }
  677. void CBattleAI::print(const std::string &text) const
  678. {
  679. logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
  680. }
  681. std::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
  682. {
  683. BattleStateInfoForRetreat bs;
  684. bs.canFlee = cb->battleCanFlee();
  685. bs.canSurrender = cb->battleCanSurrender(playerID);
  686. bs.ourSide = cb->battleGetMySide();
  687. bs.ourHero = cb->battleGetMyHero();
  688. bs.enemyHero = nullptr;
  689. for(auto stack : cb->battleGetAllStacks(false))
  690. {
  691. if(stack->alive())
  692. {
  693. if(stack->unitSide() == bs.ourSide)
  694. bs.ourStacks.push_back(stack);
  695. else
  696. {
  697. bs.enemyStacks.push_back(stack);
  698. bs.enemyHero = cb->battleGetOwnerHero(stack);
  699. }
  700. }
  701. }
  702. bs.turnsSkippedByDefense = movesSkippedByDefense / bs.ourStacks.size();
  703. if(!bs.canFlee && !bs.canSurrender)
  704. {
  705. return std::nullopt;
  706. }
  707. auto result = cb->makeSurrenderRetreatDecision(bs);
  708. if(!result && bs.canFlee && bs.turnsSkippedByDefense > 30)
  709. {
  710. return BattleAction::makeRetreat(bs.ourSide);
  711. }
  712. return result;
  713. }