BattleEvaluator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 usefull 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::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  221. {
  222. return reachability.distances[h1] < reachability.distances[h2];
  223. });
  224. for(auto hex : hexes)
  225. {
  226. if(vstd::contains(avHexes, hex))
  227. {
  228. return BattleAction::makeMove(stack, hex);
  229. }
  230. if(stack->coversPos(hex))
  231. {
  232. logAi->warn("Warning: already standing on neighbouring tile!");
  233. //We shouldn't even be here...
  234. return BattleAction::makeDefend(stack);
  235. }
  236. }
  237. BattleHex bestNeighbor = hexes.front();
  238. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  239. {
  240. return BattleAction::makeDefend(stack);
  241. }
  242. scoreEvaluator.updateReachabilityMap(hb);
  243. if(stack->hasBonusOfType(BonusType::FLYING))
  244. {
  245. std::set<BattleHex> obstacleHexes;
  246. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  247. auto affectedHexes = spellObst.getAffectedTiles();
  248. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  249. };
  250. const auto & obstacles = hb->battleGetAllObstacles();
  251. for (const auto & obst: obstacles) {
  252. if(obst->triggersEffects())
  253. {
  254. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  255. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  256. if(triggerIsNegative)
  257. insertAffected(*obst, obstacleHexes);
  258. }
  259. }
  260. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  261. // We just check all available hexes and pick the one closest to the target.
  262. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  263. {
  264. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  265. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  266. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  267. if(vstd::contains(obstacleHexes, hex))
  268. distance += NEGATIVE_OBSTACLE_PENALTY;
  269. return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  270. });
  271. return BattleAction::makeMove(stack, *nearestAvailableHex);
  272. }
  273. else
  274. {
  275. BattleHex currentDest = bestNeighbor;
  276. while(true)
  277. {
  278. if(!currentDest.isValid())
  279. {
  280. return BattleAction::makeDefend(stack);
  281. }
  282. if(vstd::contains(avHexes, currentDest)
  283. && !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
  284. return BattleAction::makeMove(stack, currentDest);
  285. currentDest = reachability.predecessors[currentDest];
  286. }
  287. }
  288. }
  289. bool BattleEvaluator::canCastSpell()
  290. {
  291. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  292. if(!hero)
  293. return false;
  294. return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
  295. }
  296. bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
  297. {
  298. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  299. if(!hero)
  300. return false;
  301. LOGL("Casting spells sounds like fun. Let's see...");
  302. //Get all spells we can cast
  303. std::vector<const CSpell*> possibleSpells;
  304. for (auto const & s : VLC->spellh->objects)
  305. if (s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero))
  306. possibleSpells.push_back(s.get());
  307. LOGFL("I can cast %d spells.", possibleSpells.size());
  308. vstd::erase_if(possibleSpells, [](const CSpell *s)
  309. {
  310. return spellType(s) != SpellTypes::BATTLE || s->getTargetType() == spells::AimType::LOCATION;
  311. });
  312. LOGFL("I know how %d of them works.", possibleSpells.size());
  313. //Get possible spell-target pairs
  314. std::vector<PossibleSpellcast> possibleCasts;
  315. for(auto spell : possibleSpells)
  316. {
  317. spells::BattleCast temp(cb->getBattle(battleID).get(), hero, spells::Mode::HERO, spell);
  318. if(spell->getTargetType() == spells::AimType::LOCATION)
  319. continue;
  320. const bool FAST = true;
  321. for(auto & target : temp.findPotentialTargets(FAST))
  322. {
  323. PossibleSpellcast ps;
  324. ps.dest = target;
  325. ps.spell = spell;
  326. possibleCasts.push_back(ps);
  327. }
  328. }
  329. LOGFL("Found %d spell-target combinations.", possibleCasts.size());
  330. if(possibleCasts.empty())
  331. return false;
  332. using ValueMap = PossibleSpellcast::ValueMap;
  333. auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
  334. {
  335. bool firstRound = true;
  336. bool enemyHadTurn = false;
  337. size_t ourTurnSpan = 0;
  338. bool stop = false;
  339. for(auto & round : queue)
  340. {
  341. if(!firstRound)
  342. state->nextRound();
  343. for(auto unit : round)
  344. {
  345. if(!vstd::contains(values, unit->unitId()))
  346. values[unit->unitId()] = 0;
  347. if(!unit->alive())
  348. continue;
  349. if(state->battleGetOwner(unit) != playerID)
  350. {
  351. enemyHadTurn = true;
  352. if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
  353. {
  354. //enemy could counter our spell at this point
  355. //anyway, we do not know what enemy will do
  356. //just stop evaluation
  357. stop = true;
  358. break;
  359. }
  360. }
  361. else if(!enemyHadTurn)
  362. {
  363. ourTurnSpan++;
  364. }
  365. state->nextTurn(unit->unitId());
  366. PotentialTargets potentialTargets(unit, damageCache, state);
  367. if(!potentialTargets.possibleAttacks.empty())
  368. {
  369. AttackPossibility attackPossibility = potentialTargets.bestAction();
  370. auto stackWithBonuses = state->getForUpdate(unit->unitId());
  371. *stackWithBonuses = *attackPossibility.attackerState;
  372. if(attackPossibility.defenderDamageReduce > 0)
  373. {
  374. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  375. stackWithBonuses->removeUnitBonus(Bonus::UntilOwnAttack);
  376. }
  377. if(attackPossibility.attackerDamageReduce > 0)
  378. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  379. for(auto affected : attackPossibility.affectedUnits)
  380. {
  381. stackWithBonuses = state->getForUpdate(affected->unitId());
  382. *stackWithBonuses = *affected;
  383. if(attackPossibility.defenderDamageReduce > 0)
  384. stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
  385. if(attackPossibility.attackerDamageReduce > 0 && attackPossibility.attack.defender->unitId() == affected->unitId())
  386. stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
  387. }
  388. }
  389. auto bav = potentialTargets.bestActionValue();
  390. //best action is from effective owner`s point if view, we need to convert to our point if view
  391. if(state->battleGetOwner(unit) != playerID)
  392. bav = -bav;
  393. values[unit->unitId()] += bav;
  394. }
  395. firstRound = false;
  396. if(stop)
  397. break;
  398. }
  399. if(enemyHadTurnOut)
  400. *enemyHadTurnOut = enemyHadTurn;
  401. return ourTurnSpan >= minTurnSpan;
  402. };
  403. ValueMap valueOfStack;
  404. ValueMap healthOfStack;
  405. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  406. size_t ourRemainingTurns = 0;
  407. for(auto unit : all)
  408. {
  409. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  410. valueOfStack[unit->unitId()] = 0;
  411. if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
  412. ourRemainingTurns++;
  413. }
  414. LOGFL("I have %d turns left in this round", ourRemainingTurns);
  415. const bool castNow = ourRemainingTurns <= 1;
  416. if(castNow)
  417. print("I should try to cast a spell now");
  418. else
  419. print("I could wait better moment to cast a spell");
  420. auto amount = all.size();
  421. std::vector<battle::Units> turnOrder;
  422. cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
  423. {
  424. bool enemyHadTurn = false;
  425. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  426. evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
  427. if(!enemyHadTurn)
  428. {
  429. auto battleIsFinishedOpt = state->battleIsFinished();
  430. if(battleIsFinishedOpt)
  431. {
  432. print("No need to cast a spell. Battle will finish soon.");
  433. return false;
  434. }
  435. }
  436. }
  437. CStopWatch timer;
  438. #if BATTLE_TRACE_LEVEL >= 1
  439. tbb::blocked_range<size_t> r(0, possibleCasts.size());
  440. #else
  441. tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
  442. {
  443. #endif
  444. for(auto i = r.begin(); i != r.end(); i++)
  445. {
  446. auto & ps = possibleCasts[i];
  447. #if BATTLE_TRACE_LEVEL >= 1
  448. logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
  449. #endif
  450. auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
  451. spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
  452. cast.castEval(state->getServerCallback(), ps.dest);
  453. auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return true; });
  454. auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
  455. {
  456. auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
  457. return !original || u->getMovementRange() != original->getMovementRange();
  458. });
  459. DamageCache safeCopy = damageCache;
  460. DamageCache innerCache(&safeCopy);
  461. innerCache.buildDamageCache(state, side);
  462. if(needFullEval || !cachedAttack)
  463. {
  464. #if BATTLE_TRACE_LEVEL >= 1
  465. logAi->trace("Full evaluation is started due to stack speed affected.");
  466. #endif
  467. PotentialTargets innerTargets(activeStack, innerCache, state);
  468. BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio);
  469. if(!innerTargets.possibleAttacks.empty())
  470. {
  471. innerEvaluator.updateReachabilityMap(state);
  472. auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
  473. ps.value = newStackAction.score;
  474. }
  475. else
  476. {
  477. ps.value = 0;
  478. }
  479. }
  480. else
  481. {
  482. ps.value = scoreEvaluator.evaluateExchange(*cachedAttack, 0, *targets, innerCache, state);
  483. }
  484. for(const auto & unit : allUnits)
  485. {
  486. auto newHealth = unit->getAvailableHealth();
  487. auto oldHealth = vstd::find_or(healthOfStack, unit->unitId(), 0); // old health value may not exist for newly summoned units
  488. if(oldHealth != newHealth)
  489. {
  490. auto damage = std::abs(oldHealth - newHealth);
  491. auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
  492. auto dpsReduce = AttackPossibility::calculateDamageReduce(
  493. nullptr,
  494. originalDefender && originalDefender->alive() ? originalDefender : unit,
  495. damage,
  496. innerCache,
  497. state);
  498. auto ourUnit = unit->unitSide() == side ? 1 : -1;
  499. auto goodEffect = newHealth > oldHealth ? 1 : -1;
  500. if(ourUnit * goodEffect == 1)
  501. {
  502. if(ourUnit && goodEffect && (unit->isClone() || unit->isGhost()))
  503. continue;
  504. ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
  505. }
  506. else
  507. ps.value -= dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
  508. #if BATTLE_TRACE_LEVEL >= 1
  509. logAi->trace(
  510. "Spell affects %s (%d), dps: %2f",
  511. unit->creatureId().toCreature()->getNameSingularTranslated(),
  512. unit->getCount(),
  513. dpsReduce);
  514. #endif
  515. }
  516. }
  517. #if BATTLE_TRACE_LEVEL >= 1
  518. logAi->trace("Total score: %2f", ps.value);
  519. #endif
  520. }
  521. #if BATTLE_TRACE_LEVEL == 0
  522. });
  523. #endif
  524. LOGFL("Evaluation took %d ms", timer.getDiff());
  525. auto pscValue = [](const PossibleSpellcast &ps) -> float
  526. {
  527. return ps.value;
  528. };
  529. auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
  530. if(castToPerform.value > cachedScore)
  531. {
  532. LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
  533. BattleAction spellcast;
  534. spellcast.actionType = EActionType::HERO_SPELL;
  535. spellcast.spell = castToPerform.spell->id;
  536. spellcast.setTarget(castToPerform.dest);
  537. spellcast.side = side;
  538. spellcast.stackNumber = (!side) ? -1 : -2;
  539. cb->battleMakeSpellAction(battleID, spellcast);
  540. activeActionMade = true;
  541. return true;
  542. }
  543. LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
  544. return false;
  545. }
  546. //Below method works only for offensive spells
  547. void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
  548. {
  549. using ValueMap = PossibleSpellcast::ValueMap;
  550. RNGStub rngStub;
  551. HypotheticBattle state(env.get(), cb->getBattle(battleID));
  552. TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
  553. ValueMap healthOfStack;
  554. ValueMap newHealthOfStack;
  555. for(auto unit : all)
  556. {
  557. healthOfStack[unit->unitId()] = unit->getAvailableHealth();
  558. }
  559. spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
  560. cast.castEval(state.getServerCallback(), ps.dest);
  561. for(auto unit : all)
  562. {
  563. auto unitId = unit->unitId();
  564. auto localUnit = state.battleGetUnitByID(unitId);
  565. newHealthOfStack[unitId] = localUnit->getAvailableHealth();
  566. }
  567. int64_t totalGain = 0;
  568. for(auto unit : all)
  569. {
  570. auto unitId = unit->unitId();
  571. auto localUnit = state.battleGetUnitByID(unitId);
  572. auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
  573. if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
  574. healthDiff = -healthDiff;
  575. if(healthDiff < 0)
  576. {
  577. ps.value = -1;
  578. return; //do not damage own units at all
  579. }
  580. totalGain += healthDiff;
  581. }
  582. ps.value = totalGain;
  583. }
  584. void BattleEvaluator::print(const std::string & text) const
  585. {
  586. logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
  587. }