BattleEvaluator.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. // TODO: remove
  25. // Eventually only IBattleInfoCallback and battle::Unit should be used,
  26. // CUnitState should be private and CStack should be removed completely
  27. #include "../../lib/CStack.h"
  28. #define LOGL(text) print(text)
  29. #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
  30. enum class SpellTypes
  31. {
  32. ADVENTURE, BATTLE, OTHER
  33. };
  34. SpellTypes spellType(const CSpell * spell)
  35. {
  36. if(!spell->isCombat() || spell->isCreatureAbility())
  37. return SpellTypes::OTHER;
  38. if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
  39. return SpellTypes::BATTLE;
  40. return SpellTypes::OTHER;
  41. }
  42. std::vector<BattleHex> BattleEvaluator::getBrokenWallMoatHexes() const
  43. {
  44. std::vector<BattleHex> result;
  45. for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
  46. {
  47. auto state = cb->getBattle(battleID)->battleGetWallState(wallPart);
  48. if(state != EWallState::DESTROYED)
  49. continue;
  50. auto wallHex = cb->getBattle(battleID)->wallPartToBattleHex(wallPart);
  51. auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
  52. result.push_back(moatHex);
  53. }
  54. return result;
  55. }
  56. std::optional<PossibleSpellcast> BattleEvaluator::findBestCreatureSpell(const CStack *stack)
  57. {
  58. //TODO: faerie dragon type spell should be selected by server
  59. SpellID creatureSpellToCast = cb->getBattle(battleID)->getRandomCastedSpell(CRandomGenerator::getDefault(), stack);
  60. if(stack->canCast() && creatureSpellToCast != SpellID::NONE)
  61. {
  62. const CSpell * spell = creatureSpellToCast.toSpell();
  63. if(spell->canBeCast(cb->getBattle(battleID).get(), spells::Mode::CREATURE_ACTIVE, stack))
  64. {
  65. std::vector<PossibleSpellcast> possibleCasts;
  66. spells::BattleCast temp(cb->getBattle(battleID).get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
  67. for(auto & target : temp.findPotentialTargets())
  68. {
  69. PossibleSpellcast ps;
  70. ps.dest = target;
  71. ps.spell = spell;
  72. evaluateCreatureSpellcast(stack, ps);
  73. possibleCasts.push_back(ps);
  74. }
  75. std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
  76. if(!possibleCasts.empty() && possibleCasts.front().value > 0)
  77. {
  78. return possibleCasts.front();
  79. }
  80. }
  81. }
  82. return std::nullopt;
  83. }
  84. BattleAction BattleEvaluator::selectStackAction(const CStack * stack)
  85. {
  86. #if BATTLE_TRACE_LEVEL >= 1
  87. logAi->trace("Select stack action");
  88. #endif
  89. //evaluate casting spell for spellcasting stack
  90. std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
  91. auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, *targets, damageCache, hb);
  92. float score = EvaluationResult::INEFFECTIVE_SCORE;
  93. if(targets->possibleAttacks.empty() && bestSpellcast.has_value())
  94. {
  95. activeActionMade = true;
  96. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  97. }
  98. if(!targets->possibleAttacks.empty())
  99. {
  100. #if BATTLE_TRACE_LEVEL>=1
  101. logAi->trace("Evaluating attack for %s", stack->getDescription());
  102. #endif
  103. auto evaluationResult = scoreEvaluator.findBestTarget(stack, *targets, damageCache, hb);
  104. auto & bestAttack = evaluationResult.bestAttack;
  105. cachedAttack = bestAttack;
  106. cachedScore = evaluationResult.score;
  107. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
  108. if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
  109. {
  110. // return because spellcast value is damage dealt and score is dps reduce
  111. activeActionMade = true;
  112. return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
  113. }
  114. if(evaluationResult.score > score)
  115. {
  116. score = evaluationResult.score;
  117. logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%2f -%2f = %2f",
  118. bestAttack.attackerState->unitType()->getJsonKey(),
  119. bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
  120. bestAttack.affectedUnits[0]->getCount(),
  121. (int)bestAttack.from,
  122. (int)bestAttack.attack.attacker->getPosition().hex,
  123. bestAttack.attack.chargeDistance,
  124. bestAttack.attack.attacker->speed(0, true),
  125. bestAttack.defenderDamageReduce,
  126. bestAttack.attackerDamageReduce,
  127. score
  128. );
  129. if (moveTarget.scorePerTurn <= score)
  130. {
  131. if(evaluationResult.wait)
  132. {
  133. return BattleAction::makeWait(stack);
  134. }
  135. else if(bestAttack.attack.shooting)
  136. {
  137. activeActionMade = true;
  138. return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
  139. }
  140. else
  141. {
  142. if(bestAttack.collateralDamageReduce
  143. && bestAttack.collateralDamageReduce >= bestAttack.defenderDamageReduce / 2
  144. && score < 0)
  145. {
  146. return BattleAction::makeDefend(stack);
  147. }
  148. else
  149. {
  150. activeActionMade = true;
  151. return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
  152. }
  153. }
  154. }
  155. }
  156. }
  157. //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
  158. if(moveTarget.scorePerTurn > score)
  159. {
  160. score = moveTarget.score;
  161. cachedAttack = moveTarget.cachedAttack;
  162. cachedScore = score;
  163. if(stack->waited())
  164. {
  165. logAi->debug(
  166. "Moving %s towards hex %s[%d], score: %2f/%2f",
  167. stack->getDescription(),
  168. moveTarget.cachedAttack->attack.defender->getDescription(),
  169. moveTarget.cachedAttack->attack.defender->getPosition().hex,
  170. moveTarget.score,
  171. moveTarget.scorePerTurn);
  172. return goTowardsNearest(stack, moveTarget.positions);
  173. }
  174. else
  175. {
  176. return BattleAction::makeWait(stack);
  177. }
  178. }
  179. if(score <= EvaluationResult::INEFFECTIVE_SCORE
  180. && !stack->hasBonusOfType(BonusType::FLYING)
  181. && stack->unitSide() == BattleSide::ATTACKER
  182. && cb->getBattle(battleID)->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
  183. {
  184. auto brokenWallMoat = getBrokenWallMoatHexes();
  185. if(brokenWallMoat.size())
  186. {
  187. activeActionMade = true;
  188. if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
  189. return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
  190. else
  191. return goTowardsNearest(stack, brokenWallMoat);
  192. }
  193. }
  194. return BattleAction::makeDefend(stack);
  195. }
  196. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  197. {
  198. auto end = std::chrono::high_resolution_clock::now();
  199. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  200. }
  201. BattleAction BattleEvaluator::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes)
  202. {
  203. auto reachability = cb->getBattle(battleID)->getReachability(stack);
  204. auto avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(reachability, stack, false);
  205. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  206. {
  207. return BattleAction::makeDefend(stack);
  208. }
  209. std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
  210. {
  211. return reachability.distances[h1] < reachability.distances[h2];
  212. });
  213. for(auto hex : hexes)
  214. {
  215. if(vstd::contains(avHexes, hex))
  216. {
  217. return BattleAction::makeMove(stack, hex);
  218. }
  219. if(stack->coversPos(hex))
  220. {
  221. logAi->warn("Warning: already standing on neighbouring tile!");
  222. //We shouldn't even be here...
  223. return BattleAction::makeDefend(stack);
  224. }
  225. }
  226. BattleHex bestNeighbor = hexes.front();
  227. if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
  228. {
  229. return BattleAction::makeDefend(stack);
  230. }
  231. scoreEvaluator.updateReachabilityMap(hb);
  232. if(stack->hasBonusOfType(BonusType::FLYING))
  233. {
  234. std::set<BattleHex> obstacleHexes;
  235. auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
  236. auto affectedHexes = spellObst.getAffectedTiles();
  237. obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
  238. };
  239. const auto & obstacles = hb->battleGetAllObstacles();
  240. for (const auto & obst: obstacles) {
  241. if(obst->triggersEffects())
  242. {
  243. auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
  244. auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
  245. if(triggerIsNegative)
  246. insertAffected(*obst, obstacleHexes);
  247. }
  248. }
  249. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  250. // We just check all available hexes and pick the one closest to the target.
  251. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  252. {
  253. const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
  254. const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
  255. auto distance = BattleHex::getDistance(bestNeighbor, hex);
  256. if(vstd::contains(obstacleHexes, hex))
  257. distance += NEGATIVE_OBSTACLE_PENALTY;
  258. return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
  259. });
  260. return BattleAction::makeMove(stack, *nearestAvailableHex);
  261. }
  262. else
  263. {
  264. BattleHex currentDest = bestNeighbor;
  265. while(true)
  266. {
  267. if(!currentDest.isValid())
  268. {
  269. return BattleAction::makeDefend(stack);
  270. }
  271. if(vstd::contains(avHexes, currentDest)
  272. && !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
  273. return BattleAction::makeMove(stack, currentDest);
  274. currentDest = reachability.predecessors[currentDest];
  275. }
  276. }
  277. }
  278. bool BattleEvaluator::canCastSpell()
  279. {
  280. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  281. if(!hero)
  282. return false;
  283. return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
  284. }
  285. bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
  286. {
  287. auto hero = cb->getBattle(battleID)->battleGetMyHero();
  288. if(!hero)
  289. return false;
  290. LOGL("Casting spells sounds like fun. Let's see...");
  291. //Get all spells we can cast
  292. std::vector<const CSpell*> possibleSpells;
  293. vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
  294. {
  295. return s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero);
  296. });
  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->speed() != original->speed();
  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() || !unit->unitSlot().validSlot()))
  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. }