BattleEvaluator.cpp 28 KB

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