BattleEvaluator.cpp 21 KB

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