BattleEvaluator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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 || s->getTargetType() == spells::AimType::LOCATION;
  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. if(spell->getTargetType() == spells::AimType::LOCATION)
  333. continue;
  334. const bool FAST = true;
  335. for(auto & target : temp.findPotentialTargets(FAST))
  336. {
  337. PossibleSpellcast ps;
  338. ps.dest = target;
  339. ps.spell = spell;
  340. possibleCasts.push_back(ps);
  341. }
  342. }
  343. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  344. if(possibleCasts.empty())
  345. return false;
  346. using ValueMap = PossibleSpellcast::ValueMap;
  347. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  348. {
  349. bool firstRound = true;
  350. bool enemyHadTurn = false;
  351. size_t ourTurnSpan = 0;
  352. bool stop = false;
  353. for(auto & round : queue)
  354. {
  355. if(!firstRound)
  356. state->nextRound();
  357. for(auto unit : round)
  358. {
  359. if(!vstd::contains(values, unit->unitId()))
  360. values[unit->unitId()] = 0;
  361. if(!unit->alive())
  362. continue;
  363. if(state->battleGetOwner(unit) != playerID)
  364. {
  365. enemyHadTurn = true;
  366. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  367. {
  368. //enemy could counter our spell at this point
  369. //anyway, we do not know what enemy will do
  370. //just stop evaluation
  371. stop = true;
  372. break;
  373. }
  374. }
  375. else if(!enemyHadTurn)
  376. {
  377. ourTurnSpan++;
  378. }
  379. state->nextTurn(unit->unitId());
  380. PotentialTargets potentialTargets(unit, damageCache, state);
  381. if(!potentialTargets.possibleAttacks.empty())
  382. {
  383. AttackPossibility attackPossibility = potentialTargets.bestAction();
  384. auto stackWithBonuses = state->getForUpdate(unit->unitId());
  385. *stackWithBonuses = *attackPossibility.attackerState;
  386. if(attackPossibility.defenderDamageReduce > 0)
  387. {
  388. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  389. stackWithBonuses->removeUnitBonus(Bonus::UntilOwnAttack);
  390. }
  391. if(attackPossibility.attackerDamageReduce > 0)
  392. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  393. for(auto affected : attackPossibility.affectedUnits)
  394. {
  395. stackWithBonuses = state->getForUpdate(affected->unitId());
  396. *stackWithBonuses = *affected;
  397. if(attackPossibility.defenderDamageReduce > 0)
  398. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  399. if(attackPossibility.attackerDamageReduce > 0 && attackPossibility.attack.defender->unitId() == affected->unitId())
  400. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  401. }
  402. }
  403. auto bav = potentialTargets.bestActionValue();
  404. //best action is from effective owner`s point if view, we need to convert to our point if view
  405. if(state->battleGetOwner(unit) != playerID)
  406. bav = -bav;
  407. values[unit->unitId()] += bav;
  408. }
  409. firstRound = false;
  410. if(stop)
  411. break;
  412. }
  413. if(enemyHadTurnOut)
  414. *enemyHadTurnOut = enemyHadTurn;
  415. return ourTurnSpan >= minTurnSpan;
  416. };
  417. ValueMap valueOfStack;
  418. ValueMap healthOfStack;
  419. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  420. size_t ourRemainingTurns = 0;
  421. for(auto unit : all)
  422. {
  423. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  424. valueOfStack[unit->unitId()] = 0;
  425. if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  426. ourRemainingTurns++;
  427. }
  428. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  429. const bool castNow = ourRemainingTurns <= 1;
  430. if(castNow)
  431. print("I should try to cast a spell now");
  432. else
  433. print("I could wait better moment to cast a spell");
  434. auto amount = all.size();
  435. std::vector<battle::Units> turnOrder;
  436. cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  437. {
  438. bool enemyHadTurn = false;
  439. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  440. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  441. if(!enemyHadTurn)
  442. {
  443. auto battleIsFinishedOpt = state->battleIsFinished();
  444. if(battleIsFinishedOpt)
  445. {
  446. print("No need to cast a spell. Battle will finish soon.");
  447. return false;
  448. }
  449. }
  450. }
  451. CStopWatch timer;
  452. #if BATTLE_TRACE_LEVEL >= 1
  453. tbb::blocked_range<size_t> r(0, possibleCasts.size());
  454. #else
  455. tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
  456. {
  457. #endif
  458. for(auto i = r.begin(); i != r.end(); i++)
  459. {
  460. auto & ps = possibleCasts[i];
  461. #if BATTLE_TRACE_LEVEL >= 1
  462. logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
  463. #endif
  464. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  465. spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
  466. cast.castEval(state->getServerCallback(), ps.dest);
  467. auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return true; });
  468. auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
  469. {
  470. auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
  471. return !original || u->getMovementRange() != original->getMovementRange();
  472. });
  473. DamageCache safeCopy = damageCache;
  474. DamageCache innerCache(&safeCopy);
  475. innerCache.buildDamageCache(state, side);
  476. if(needFullEval || !cachedAttack)
  477. {
  478. #if BATTLE_TRACE_LEVEL >= 1
  479. logAi->trace("Full evaluation is started due to stack speed affected.");
  480. #endif
  481. PotentialTargets innerTargets(activeStack, innerCache, state);
  482. BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio);
  483. if(!innerTargets.possibleAttacks.empty())
  484. {
  485. innerEvaluator.updateReachabilityMap(state);
  486. auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
  487. ps.value = newStackAction.score;
  488. }
  489. else
  490. {
  491. ps.value = 0;
  492. }
  493. }
  494. else
  495. {
  496. ps.value = scoreEvaluator.evaluateExchange(*cachedAttack, 0, *targets, innerCache, state);
  497. }
  498. for(const auto & unit : allUnits)
  499. {
  500. if (!unit->isValidTarget())
  501. continue;
  502. auto newHealth = unit->getAvailableHealth();
  503. auto oldHealth = vstd::find_or(healthOfStack, unit->unitId(), 0); // old health value may not exist for newly summoned units
  504. if(oldHealth != newHealth)
  505. {
  506. auto damage = std::abs(oldHealth - newHealth);
  507. auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
  508. auto dpsReduce = AttackPossibility::calculateDamageReduce(
  509. nullptr,
  510. originalDefender && originalDefender->alive() ? originalDefender : unit,
  511. damage,
  512. innerCache,
  513. state);
  514. auto ourUnit = unit->unitSide() == side ? 1 : -1;
  515. auto goodEffect = newHealth > oldHealth ? 1 : -1;
  516. if(ourUnit * goodEffect == 1)
  517. {
  518. if(ourUnit && goodEffect && (unit->isClone() || unit->isGhost()))
  519. continue;
  520. ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
  521. }
  522. else
  523. ps.value -= dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
  524. #if BATTLE_TRACE_LEVEL >= 1
  525. logAi->trace(
  526. "Spell affects %s (%d), dps: %2f",
  527. unit->creatureId().toCreature()->getNameSingularTranslated(),
  528. unit->getCount(),
  529. dpsReduce);
  530. #endif
  531. }
  532. }
  533. #if BATTLE_TRACE_LEVEL >= 1
  534. logAi->trace("Total score: %2f", ps.value);
  535. #endif
  536. }
  537. #if BATTLE_TRACE_LEVEL == 0
  538. });
  539. #endif
  540. LOGFL("Evaluation took %d ms", timer.getDiff());
  541. auto pscValue = [](const PossibleSpellcast &ps) -> float
  542. {
  543. return ps.value;
  544. };
  545. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  546. if(castToPerform.value > cachedScore)
  547. {
  548. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  549. BattleAction spellcast;
  550. spellcast.actionType = EActionType::HERO_SPELL;
  551. spellcast.spell = castToPerform.spell->id;
  552. spellcast.setTarget(castToPerform.dest);
  553. spellcast.side = side;
  554. spellcast.stackNumber = (!side) ? -1 : -2;
  555. cb->battleMakeSpellAction(battleID, spellcast);
  556. activeActionMade = true;
  557. return true;
  558. }
  559. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  560. return false;
  561. }
  562. //Below method works only for offensive spells
  563. void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  564. {
  565. using ValueMap = PossibleSpellcast::ValueMap;
  566. RNGStub rngStub;
  567. HypotheticBattle state(env.get(), cb->getBattle(battleID));
  568. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  569. ValueMap healthOfStack;
  570. ValueMap newHealthOfStack;
  571. for(auto unit : all)
  572. {
  573. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  574. }
  575. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  576. cast.castEval(state.getServerCallback(), ps.dest);
  577. for(auto unit : all)
  578. {
  579. auto unitId = unit->unitId();
  580. auto localUnit = state.battleGetUnitByID(unitId);
  581. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  582. }
  583. int64_t totalGain = 0;
  584. for(auto unit : all)
  585. {
  586. auto unitId = unit->unitId();
  587. auto localUnit = state.battleGetUnitByID(unitId);
  588. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  589. if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
  590. healthDiff = -healthDiff;
  591. if(healthDiff < 0)
  592. {
  593. ps.value = -1;
  594. return; //do not damage own units at all
  595. }
  596. totalGain += healthDiff;
  597. }
  598. ps.value = totalGain;
  599. }
  600. void BattleEvaluator::print(const std::string & text) const
  601. {
  602. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  603. }