BattleAI.cpp 23 KB

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