BattleEvaluator.cpp 23 KB

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