BattleEvaluator.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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 "BattleEvaluator.h"
  12. #include "BattleExchangeVariant.h"
  13. #include "StackWithBonuses.h"
  14. #include "EnemyInfo.h"
  15. #include "tbb/parallel_for.h"
  16. #include "../../lib/CStopWatch.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/mapObjects/CGTownInstance.h"
  19. #include "../../lib/spells/CSpellHandler.h"
  20. #include "../../lib/spells/ISpellMechanics.h"
  21. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  22. #include "../../lib/battle/CObstacleInstance.h"
  23. #include "../../lib/battle/BattleAction.h"
  24. #include "../../lib/CRandomGenerator.h"
  25. // TODO: remove
  26. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  27. // CUnitState should be private and CStack should be removed completely
  28. #include "../../lib/CStack.h"
  29. #define LOGL(text) print(text)
  30. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  31. enum class SpellTypes
  32. {
  33. ADVENTURE, BATTLE, OTHER
  34. };
  35. SpellTypes spellType(const CSpell * spell)
  36. {
  37. if(!spell->isCombat() || spell->isCreatureAbility())
  38. return SpellTypes::OTHER;
  39. if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
  40. return SpellTypes::BATTLE;
  41. return SpellTypes::OTHER;
  42. }
  43. BattleEvaluator::BattleEvaluator(
  44. std::shared_ptr<Environment> env,
  45. std::shared_ptr<CBattleCallback> cb,
  46. const battle::Unit * activeStack,
  47. PlayerColor playerID,
  48. BattleID battleID,
  49. BattleSide side,
  50. float strengthRatio,
  51. int simulationTurnsCount)
  52. :scoreEvaluator(cb->getBattle(battleID), env, strengthRatio, simulationTurnsCount),
  53. cachedAttack(), playerID(playerID), side(side), env(env),
  54. cb(cb), strengthRatio(strengthRatio), battleID(battleID), simulationTurnsCount(simulationTurnsCount)
  55. {
  56. hb = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  57. damageCache.buildDamageCache(hb, side);
  58. targets = std::make_unique<PotentialTargets>(activeStack, damageCache, hb);
  59. }
  60. BattleEvaluator::BattleEvaluator(
  61. std::shared_ptr<Environment> env,
  62. std::shared_ptr<CBattleCallback> cb,
  63. std::shared_ptr<HypotheticBattle> hb,
  64. DamageCache & damageCache,
  65. const battle::Unit * activeStack,
  66. PlayerColor playerID,
  67. BattleID battleID,
  68. BattleSide side,
  69. float strengthRatio,
  70. int simulationTurnsCount)
  71. :scoreEvaluator(cb->getBattle(battleID), env, strengthRatio, simulationTurnsCount),
  72. cachedAttack(), playerID(playerID), side(side), env(env), cb(cb), hb(hb),
  73. damageCache(damageCache), strengthRatio(strengthRatio), battleID(battleID), simulationTurnsCount(simulationTurnsCount)
  74. {
  75. targets = std::make_unique<PotentialTargets>(activeStack, damageCache, hb);
  76. }
  77. std::vector<BattleHex> BattleEvaluator::getBrokenWallMoatHexes() const
  78. {
  79. std::vector<BattleHex> result;
  80. for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
  81. {
  82. auto state = cb->getBattle(battleID)->battleGetWallState(wallPart);
  83. if(state != EWallState::DESTROYED)
  84. continue;
  85. auto wallHex = cb->getBattle(battleID)->wallPartToBattleHex(wallPart);
  86. auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
  87. result.push_back(moatHex);
  88. moatHex = moatHex.cloneInDirection(BattleHex::LEFT);
  89. auto obstaclesSecondRow = cb->getBattle(battleID)->battleGetAllObstaclesOnPos(moatHex, false);
  90. for(auto obstacle : obstaclesSecondRow)
  91. {
  92. if(obstacle->obstacleType == CObstacleInstance::EObstacleType::MOAT)
  93. {
  94. result.push_back(moatHex);
  95. break;
  96. }
  97. }
  98. }
  99. return result;
  100. }
  101. std::optional<PossibleSpellcast> BattleEvaluator::findBestCreatureSpell(const CStack *stack)
  102. {
  103. //TODO: faerie dragon type spell should be selected by server
  104. SpellID creatureSpellToCast = cb->getBattle(battleID)->getRandomCastedSpell(CRandomGenerator::getDefault(), stack);
  105. if(stack->canCast() && creatureSpellToCast != SpellID::NONE)
  106. {
  107. const CSpell * spell = creatureSpellToCast.toSpell();
  108. if(spell->canBeCast(cb->getBattle(battleID).get(), spells::Mode::CREATURE_ACTIVE, stack))
  109. {
  110. std::vector<PossibleSpellcast> possibleCasts;
  111. spells::BattleCast temp(cb->getBattle(battleID).get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  112. for(auto & target : temp.findPotentialTargets())
  113. {
  114. PossibleSpellcast ps;
  115. ps.dest = target;
  116. ps.spell = spell;
  117. evaluateCreatureSpellcast(stack, ps);
  118. possibleCasts.push_back(ps);
  119. }
  120. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  121. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  122. {
  123. return possibleCasts.front();
  124. }
  125. }
  126. }
  127. return std::nullopt;
  128. }
  129. BattleAction BattleEvaluator::selectStackAction(const CStack * stack)
  130. {
  131. #if BATTLE_TRACE_LEVEL >= 1
  132. logAi->trace("Select stack action");
  133. #endif
  134. //evaluate casting spell for spellcasting stack
  135. std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
  136. auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, *targets, damageCache, hb);
  137. float score = EvaluationResult::INEFFECTIVE_SCORE;
  138. if(targets->possibleAttacks.empty() && bestSpellcast.has_value())
  139. {
  140. activeActionMade = true;
  141. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  142. }
  143. if(!targets->possibleAttacks.empty())
  144. {
  145. #if BATTLE_TRACE_LEVEL>=1
  146. logAi->trace("Evaluating attack for %s", stack->getDescription());
  147. #endif
  148. auto evaluationResult = scoreEvaluator.findBestTarget(stack, *targets, damageCache, hb);
  149. auto & bestAttack = evaluationResult.bestAttack;
  150. cachedAttack.ap = bestAttack;
  151. cachedAttack.score = evaluationResult.score;
  152. cachedAttack.turn = 0;
  153. cachedAttack.waited = evaluationResult.wait;
  154. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  155. if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
  156. {
  157. // return because spellcast value is damage dealt and score is dps reduce
  158. activeActionMade = true;
  159. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  160. }
  161. if(evaluationResult.score > score)
  162. {
  163. score = evaluationResult.score;
  164. logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%2f -%2f = %2f",
  165. bestAttack.attackerState->unitType()->getJsonKey(),
  166. bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
  167. bestAttack.affectedUnits[0]->getCount(),
  168. (int)bestAttack.from,
  169. (int)bestAttack.attack.attacker->getPosition().hex,
  170. bestAttack.attack.chargeDistance,
  171. bestAttack.attack.attacker->getMovementRange(0),
  172. bestAttack.defenderDamageReduce,
  173. bestAttack.attackerDamageReduce,
  174. score
  175. );
  176. if (moveTarget.score <= score)
  177. {
  178. if(evaluationResult.wait)
  179. {
  180. return BattleAction::makeWait(stack);
  181. }
  182. else if(bestAttack.attack.shooting)
  183. {
  184. activeActionMade = true;
  185. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  186. }
  187. else
  188. {
  189. if(bestAttack.collateralDamageReduce
  190. && bestAttack.collateralDamageReduce >= bestAttack.defenderDamageReduce / 2
  191. && score < 0)
  192. {
  193. return BattleAction::makeDefend(stack);
  194. }
  195. else
  196. {
  197. activeActionMade = true;
  198. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defenderPos, bestAttack.from);
  199. }
  200. }
  201. }
  202. }
  203. }
  204. //ThreatMap threatsToUs(stack); // These lines may be useful but they are't used in the code.
  205. if(moveTarget.score > score)
  206. {
  207. score = moveTarget.score;
  208. cachedAttack.ap = moveTarget.cachedAttack;
  209. cachedAttack.score = score;
  210. cachedAttack.turn = moveTarget.turnsToRich;
  211. if(stack->waited())
  212. {
  213. logAi->debug(
  214. "Moving %s towards hex %s[%d], score: %2f",
  215. stack->getDescription(),
  216. moveTarget.cachedAttack->attack.defender->getDescription(),
  217. moveTarget.cachedAttack->attack.defender->getPosition().hex,
  218. moveTarget.score);
  219. return goTowardsNearest(stack, moveTarget.positions, *targets);
  220. }
  221. else
  222. {
  223. cachedAttack.waited = true;
  224. return BattleAction::makeWait(stack);
  225. }
  226. }
  227. if(score <= EvaluationResult::INEFFECTIVE_SCORE
  228. && !stack->hasBonusOfType(BonusType::FLYING)
  229. && stack->unitSide() == BattleSide::ATTACKER
  230. && cb->getBattle(battleID)->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  231. {
  232. auto brokenWallMoat = getBrokenWallMoatHexes();
  233. if(brokenWallMoat.size())
  234. {
  235. activeActionMade = true;
  236. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  237. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  238. else
  239. return goTowardsNearest(stack, brokenWallMoat, *targets);
  240. }
  241. }
  242. return stack->waited() ? BattleAction::makeDefend(stack) : BattleAction::makeWait(stack);
  243. }
  244. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  245. {
  246. auto end = std::chrono::high_resolution_clock::now();
  247. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  248. }
  249. BattleAction BattleEvaluator::moveOrAttack(const CStack * stack, BattleHex hex, const PotentialTargets & targets)
  250. {
  251. auto additionalScore = 0;
  252. std::optional<AttackPossibility> attackOnTheWay;
  253. for(auto & target : targets.possibleAttacks)
  254. {
  255. if(!target.attack.shooting && target.from == hex && target.attackValue() > additionalScore)
  256. {
  257. additionalScore = target.attackValue();
  258. attackOnTheWay = target;
  259. }
  260. }
  261. if(attackOnTheWay)
  262. {
  263. activeActionMade = true;
  264. return BattleAction::makeMeleeAttack(stack, attackOnTheWay->attack.defender->getPosition(), attackOnTheWay->from);
  265. }
  266. else
  267. {
  268. return BattleAction::makeMove(stack, hex);
  269. }
  270. }
  271. BattleAction BattleEvaluator::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes, const PotentialTargets & targets)
  272. {
  273. auto reachability = cb->getBattle(battleID)->getReachability(stack);
  274. auto avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(reachability, stack, false);
  275. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  276. {
  277. return BattleAction::makeDefend(stack);
  278. }
  279. std::vector<BattleHex> targetHexes = hexes;
  280. vstd::erase_if(targetHexes, [](const BattleHex & hex) { return !hex.isValid(); });
  281. std::sort(targetHexes.begin(), targetHexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  282. {
  283. return reachability.distances[h1] < reachability.distances[h2];
  284. });
  285. BattleHex bestNeighbor = targetHexes.front();
  286. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  287. {
  288. logAi->trace("No richable hexes.");
  289. return BattleAction::makeDefend(stack);
  290. }
  291. // this turn
  292. for(auto hex : targetHexes)
  293. {
  294. if(vstd::contains(avHexes, hex))
  295. {
  296. return moveOrAttack(stack, hex, targets);
  297. }
  298. if(stack->coversPos(hex))
  299. {
  300. logAi->warn("Warning: already standing on neighbouring hex!");
  301. //We shouldn't even be here...
  302. return BattleAction::makeDefend(stack);
  303. }
  304. }
  305. // not this turn
  306. scoreEvaluator.updateReachabilityMap(hb);
  307. if(stack->hasBonusOfType(BonusType::FLYING))
  308. {
  309. std::set<BattleHex> obstacleHexes;
  310. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  311. auto affectedHexes = spellObst.getAffectedTiles();
  312. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  313. };
  314. const auto & obstacles = hb->battleGetAllObstacles();
  315. for (const auto & obst: obstacles) {
  316. if(obst->triggersEffects())
  317. {
  318. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  319. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  320. if(triggerIsNegative)
  321. insertAffected(*obst, obstacleHexes);
  322. }
  323. }
  324. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  325. // We just check all available hexes and pick the one closest to the target.
  326. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  327. {
  328. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  329. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  330. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  331. if(vstd::contains(obstacleHexes, hex))
  332. distance += NEGATIVE_OBSTACLE_PENALTY;
  333. return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  334. });
  335. return moveOrAttack(stack, *nearestAvailableHex, targets);
  336. }
  337. else
  338. {
  339. BattleHex currentDest = bestNeighbor;
  340. while(true)
  341. {
  342. if(!currentDest.isValid())
  343. {
  344. return BattleAction::makeDefend(stack);
  345. }
  346. if(vstd::contains(avHexes, currentDest)
  347. && !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
  348. {
  349. return moveOrAttack(stack, currentDest, targets);
  350. }
  351. currentDest = reachability.predecessors[currentDest];
  352. }
  353. }
  354. logAi->error("We should either detect that hexes are unreachable or make a move!");
  355. return BattleAction::makeDefend(stack);
  356. }
  357. bool BattleEvaluator::canCastSpell()
  358. {
  359. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  360. if(!hero)
  361. return false;
  362. return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
  363. }
  364. bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
  365. {
  366. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  367. if(!hero)
  368. return false;
  369. LOGL("Casting spells sounds like fun. Let's see...");
  370. //Get all spells we can cast
  371. std::vector<const CSpell*> possibleSpells;
  372. for (auto const & s : VLC->spellh->objects)
  373. if (s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero))
  374. possibleSpells.push_back(s.get());
  375. LOGFL("I can cast %d spells.", possibleSpells.size());
  376. vstd::erase_if(possibleSpells, [](const CSpell *s)
  377. {
  378. return spellType(s) != SpellTypes::BATTLE;
  379. });
  380. LOGFL("I know how %d of them works.", possibleSpells.size());
  381. //Get possible spell-target pairs
  382. std::vector<PossibleSpellcast> possibleCasts;
  383. for(auto spell : possibleSpells)
  384. {
  385. spells::BattleCast temp(cb->getBattle(battleID).get(), hero, spells::Mode::HERO, spell);
  386. const bool FAST = true;
  387. for(auto & target : temp.findPotentialTargets(FAST))
  388. {
  389. PossibleSpellcast ps;
  390. ps.dest = target;
  391. ps.spell = spell;
  392. possibleCasts.push_back(ps);
  393. }
  394. }
  395. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  396. if(possibleCasts.empty())
  397. return false;
  398. using ValueMap = PossibleSpellcast::ValueMap;
  399. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  400. {
  401. bool firstRound = true;
  402. bool enemyHadTurn = false;
  403. size_t ourTurnSpan = 0;
  404. bool stop = false;
  405. for(auto & round : queue)
  406. {
  407. if(!firstRound)
  408. state->nextRound();
  409. for(auto unit : round)
  410. {
  411. if(!vstd::contains(values, unit->unitId()))
  412. values[unit->unitId()] = 0;
  413. if(!unit->alive())
  414. continue;
  415. if(state->battleGetOwner(unit) != playerID)
  416. {
  417. enemyHadTurn = true;
  418. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  419. {
  420. //enemy could counter our spell at this point
  421. //anyway, we do not know what enemy will do
  422. //just stop evaluation
  423. stop = true;
  424. break;
  425. }
  426. }
  427. else if(!enemyHadTurn)
  428. {
  429. ourTurnSpan++;
  430. }
  431. state->nextTurn(unit->unitId());
  432. PotentialTargets potentialTargets(unit, damageCache, state);
  433. if(!potentialTargets.possibleAttacks.empty())
  434. {
  435. AttackPossibility attackPossibility = potentialTargets.bestAction();
  436. auto stackWithBonuses = state->getForUpdate(unit->unitId());
  437. *stackWithBonuses = *attackPossibility.attackerState;
  438. if(attackPossibility.defenderDamageReduce > 0)
  439. {
  440. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  441. stackWithBonuses->removeUnitBonus(Bonus::UntilOwnAttack);
  442. }
  443. if(attackPossibility.attackerDamageReduce > 0)
  444. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  445. for(auto affected : attackPossibility.affectedUnits)
  446. {
  447. stackWithBonuses = state->getForUpdate(affected->unitId());
  448. *stackWithBonuses = *affected;
  449. if(attackPossibility.defenderDamageReduce > 0)
  450. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  451. if(attackPossibility.attackerDamageReduce > 0 && attackPossibility.attack.defender->unitId() == affected->unitId())
  452. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  453. }
  454. }
  455. auto bav = potentialTargets.bestActionValue();
  456. //best action is from effective owner`s point if view, we need to convert to our point if view
  457. if(state->battleGetOwner(unit) != playerID)
  458. bav = -bav;
  459. values[unit->unitId()] += bav;
  460. }
  461. firstRound = false;
  462. if(stop)
  463. break;
  464. }
  465. if(enemyHadTurnOut)
  466. *enemyHadTurnOut = enemyHadTurn;
  467. return ourTurnSpan >= minTurnSpan;
  468. };
  469. ValueMap valueOfStack;
  470. ValueMap healthOfStack;
  471. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  472. size_t ourRemainingTurns = 0;
  473. for(auto unit : all)
  474. {
  475. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  476. valueOfStack[unit->unitId()] = 0;
  477. if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  478. ourRemainingTurns++;
  479. }
  480. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  481. const bool castNow = ourRemainingTurns <= 1;
  482. if(castNow)
  483. print("I should try to cast a spell now");
  484. else
  485. print("I could wait better moment to cast a spell");
  486. auto amount = all.size();
  487. std::vector<battle::Units> turnOrder;
  488. cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  489. {
  490. bool enemyHadTurn = false;
  491. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  492. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  493. if(!enemyHadTurn)
  494. {
  495. auto battleIsFinishedOpt = state->battleIsFinished();
  496. if(battleIsFinishedOpt)
  497. {
  498. print("No need to cast a spell. Battle will finish soon.");
  499. return false;
  500. }
  501. }
  502. }
  503. CStopWatch timer;
  504. #if BATTLE_TRACE_LEVEL >= 1
  505. tbb::blocked_range<size_t> r(0, possibleCasts.size());
  506. #else
  507. tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
  508. {
  509. #endif
  510. for(auto i = r.begin(); i != r.end(); i++)
  511. {
  512. auto & ps = possibleCasts[i];
  513. #if BATTLE_TRACE_LEVEL >= 1
  514. logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
  515. #endif
  516. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  517. spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
  518. cast.castEval(state->getServerCallback(), ps.dest);
  519. auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return true; });
  520. auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
  521. {
  522. auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
  523. return !original || u->getMovementRange() != original->getMovementRange();
  524. });
  525. DamageCache safeCopy = damageCache;
  526. DamageCache innerCache(&safeCopy);
  527. innerCache.buildDamageCache(state, side);
  528. if(cachedAttack.ap && cachedAttack.waited)
  529. {
  530. state->makeWait(activeStack);
  531. }
  532. if(needFullEval || !cachedAttack.ap)
  533. {
  534. #if BATTLE_TRACE_LEVEL >= 1
  535. logAi->trace("Full evaluation is started due to stack speed affected.");
  536. #endif
  537. PotentialTargets innerTargets(activeStack, innerCache, state);
  538. BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio, simulationTurnsCount);
  539. innerEvaluator.updateReachabilityMap(state);
  540. auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(activeStack, innerTargets, innerCache, state);
  541. if(!innerTargets.possibleAttacks.empty())
  542. {
  543. auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
  544. ps.value = std::max(moveTarget.score, newStackAction.score);
  545. }
  546. else
  547. {
  548. ps.value = moveTarget.score;
  549. }
  550. }
  551. else
  552. {
  553. ps.value = scoreEvaluator.evaluateExchange(*cachedAttack.ap, cachedAttack.turn, *targets, innerCache, state);
  554. }
  555. for(const auto & unit : allUnits)
  556. {
  557. if(!unit->isValidTarget())
  558. continue;
  559. auto newHealth = unit->getAvailableHealth();
  560. auto oldHealth = vstd::find_or(healthOfStack, unit->unitId(), 0); // old health value may not exist for newly summoned units
  561. if(oldHealth != newHealth)
  562. {
  563. auto damage = std::abs(oldHealth - newHealth);
  564. auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
  565. auto dpsReduce = AttackPossibility::calculateDamageReduce(
  566. nullptr,
  567. originalDefender && originalDefender->alive() ? originalDefender : unit,
  568. damage,
  569. innerCache,
  570. state);
  571. auto ourUnit = unit->unitSide() == side ? 1 : -1;
  572. auto goodEffect = newHealth > oldHealth ? 1 : -1;
  573. if(ourUnit * goodEffect == 1)
  574. {
  575. if(ourUnit && goodEffect && (unit->isClone() || unit->isGhost()))
  576. continue;
  577. ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
  578. }
  579. else
  580. ps.value -= dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
  581. #if BATTLE_TRACE_LEVEL >= 1
  582. logAi->trace(
  583. "Spell affects %s (%d), dps: %2f",
  584. unit->creatureId().toCreature()->getNameSingularTranslated(),
  585. unit->getCount(),
  586. dpsReduce);
  587. #endif
  588. }
  589. }
  590. #if BATTLE_TRACE_LEVEL >= 1
  591. logAi->trace("Total score: %2f", ps.value);
  592. #endif
  593. }
  594. #if BATTLE_TRACE_LEVEL == 0
  595. });
  596. #endif
  597. LOGFL("Evaluation took %d ms", timer.getDiff());
  598. auto castToPerform = *vstd::maxElementByFun(possibleCasts, [](const PossibleSpellcast & ps) -> float
  599. {
  600. return ps.value;
  601. });
  602. if(castToPerform.value > cachedAttack.score && !vstd::isAlmostEqual(castToPerform.value, cachedAttack.score))
  603. {
  604. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  605. BattleAction spellcast;
  606. spellcast.actionType = EActionType::HERO_SPELL;
  607. spellcast.spell = castToPerform.spell->id;
  608. spellcast.setTarget(castToPerform.dest);
  609. spellcast.side = side;
  610. spellcast.stackNumber = -1;
  611. cb->battleMakeSpellAction(battleID, spellcast);
  612. activeActionMade = true;
  613. return true;
  614. }
  615. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  616. return false;
  617. }
  618. //Below method works only for offensive spells
  619. void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  620. {
  621. using ValueMap = PossibleSpellcast::ValueMap;
  622. RNGStub rngStub;
  623. HypotheticBattle state(env.get(), cb->getBattle(battleID));
  624. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  625. ValueMap healthOfStack;
  626. ValueMap newHealthOfStack;
  627. for(auto unit : all)
  628. {
  629. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  630. }
  631. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  632. cast.castEval(state.getServerCallback(), ps.dest);
  633. for(auto unit : all)
  634. {
  635. auto unitId = unit->unitId();
  636. auto localUnit = state.battleGetUnitByID(unitId);
  637. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  638. }
  639. int64_t totalGain = 0;
  640. for(auto unit : all)
  641. {
  642. auto unitId = unit->unitId();
  643. auto localUnit = state.battleGetUnitByID(unitId);
  644. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  645. if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
  646. healthDiff = -healthDiff;
  647. if(healthDiff < 0)
  648. {
  649. ps.value = -1;
  650. return; //do not damage own units at all
  651. }
  652. totalGain += healthDiff;
  653. }
  654. ps.value = totalGain;
  655. }
  656. void BattleEvaluator::print(const std::string & text) const
  657. {
  658. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  659. }