BattleEvaluator.cpp 23 KB

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