BattleEvaluator.cpp 29 KB

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