CBattleInfoCallback.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. /*
  2. * CBattleInfoCallback.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 "CBattleInfoCallback.h"
  12. #include <vcmi/scripting/Service.h>
  13. #include "../CStack.h"
  14. #include "BattleInfo.h"
  15. #include "DamageCalculator.h"
  16. #include "PossiblePlayerBattleAction.h"
  17. #include "../NetPacks.h"
  18. #include "../spells/CSpellHandler.h"
  19. #include "../mapObjects/CGTownInstance.h"
  20. #include "../BattleFieldHandler.h"
  21. #include "../CModHandler.h"
  22. #include "../Rect.h"
  23. VCMI_LIB_NAMESPACE_BEGIN
  24. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  25. {
  26. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  27. {
  28. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 96, 112, 130, 147, 165, 182};
  29. return lineToHex[line];
  30. }
  31. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  32. {
  33. const int wallInStackLine = lineToWallHex(pos1.getY());
  34. const int wallInDestLine = lineToWallHex(pos2.getY());
  35. const bool stackLeft = pos1 < wallInStackLine;
  36. const bool destLeft = pos2 < wallInDestLine;
  37. return stackLeft == destLeft;
  38. }
  39. // parts of wall
  40. static const std::pair<int, EWallPart> wallParts[] =
  41. {
  42. std::make_pair(50, EWallPart::KEEP),
  43. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  44. std::make_pair(182, EWallPart::BOTTOM_WALL),
  45. std::make_pair(130, EWallPart::BELOW_GATE),
  46. std::make_pair(78, EWallPart::OVER_GATE),
  47. std::make_pair(29, EWallPart::UPPER_WALL),
  48. std::make_pair(12, EWallPart::UPPER_TOWER),
  49. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  50. std::make_pair(96, EWallPart::GATE),
  51. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  52. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  53. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  54. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  55. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  56. };
  57. static EWallPart hexToWallPart(BattleHex hex)
  58. {
  59. for(const auto & elem : wallParts)
  60. {
  61. if(elem.first == hex)
  62. return elem.second;
  63. }
  64. return EWallPart::INVALID; //not found!
  65. }
  66. static BattleHex WallPartToHex(EWallPart part)
  67. {
  68. for(const auto & elem : wallParts)
  69. {
  70. if(elem.second == part)
  71. return elem.first;
  72. }
  73. return BattleHex::INVALID; //not found!
  74. }
  75. }
  76. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  77. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  78. {
  79. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  80. if(caster == nullptr)
  81. {
  82. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  83. return ESpellCastProblem::INVALID;
  84. }
  85. const PlayerColor player = caster->getCasterOwner();
  86. const auto side = playerToSide(player);
  87. if(!side)
  88. return ESpellCastProblem::INVALID;
  89. if(!battleDoWeKnowAbout(side.get()))
  90. {
  91. logGlobal->warn("You can't check if enemy can cast given spell!");
  92. return ESpellCastProblem::INVALID;
  93. }
  94. if(battleTacticDist())
  95. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  96. switch(mode)
  97. {
  98. case spells::Mode::HERO:
  99. {
  100. if(battleCastSpells(side.get()) > 0)
  101. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  102. const auto * hero = dynamic_cast<const CGHeroInstance *>(caster);
  103. if(!hero)
  104. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  105. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  106. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  107. }
  108. break;
  109. default:
  110. break;
  111. }
  112. return ESpellCastProblem::OK;
  113. }
  114. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  115. {
  116. auto isTileBlocked = [&](BattleHex tile)
  117. {
  118. EWallPart wallPart = battleHexToWallPart(tile);
  119. if (wallPart == EWallPart::INDESTRUCTIBLE_PART_OF_GATE)
  120. return false; // does not blocks ranged attacks
  121. if (wallPart == EWallPart::INDESTRUCTIBLE_PART)
  122. return true; // always blocks ranged attacks
  123. return isWallPartAttackable(wallPart);
  124. };
  125. auto needWallPenalty = [&](BattleHex from, BattleHex dest)
  126. {
  127. // arbitrary selected cell size for virtual grid
  128. // any even number can be selected (for division by two)
  129. static const int cellSize = 10;
  130. // create line that goes from center of shooter cell to center of target cell
  131. Point line1{ from.getX()*cellSize+cellSize/2, from.getY()*cellSize+cellSize/2};
  132. Point line2{ dest.getX()*cellSize+cellSize/2, dest.getY()*cellSize+cellSize/2};
  133. for (int y = 0; y < GameConstants::BFIELD_HEIGHT; ++y)
  134. {
  135. BattleHex obstacle = lineToWallHex(y);
  136. if (!isTileBlocked(obstacle))
  137. continue;
  138. // create rect around cell with an obstacle
  139. Rect rect {
  140. Point(obstacle.getX(), obstacle.getY()) * cellSize,
  141. Point( cellSize, cellSize)
  142. };
  143. if ( rect.intersectionTest(line1, line2))
  144. return true;
  145. }
  146. return false;
  147. };
  148. RETURN_IF_NOT_BATTLE(false);
  149. if(!battleGetSiegeLevel())
  150. return false;
  151. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  152. static const auto selectorNoWallPenalty = Selector::type()(Bonus::NO_WALL_PENALTY);
  153. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  154. return false;
  155. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  156. const bool shooterOutsideWalls = shooterPosition < wallInStackLine;
  157. return shooterOutsideWalls && needWallPenalty(shooterPosition, destHex);
  158. }
  159. si8 CBattleInfoCallback::battleCanTeleportTo(const battle::Unit * stack, BattleHex destHex, int telportLevel) const
  160. {
  161. RETURN_IF_NOT_BATTLE(false);
  162. if (!getAccesibility(stack).accessible(destHex, stack))
  163. return false;
  164. const ui8 siegeLevel = battleGetSiegeLevel();
  165. //check for wall
  166. //advanced teleport can pass wall of fort|citadel, expert - of castle
  167. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  168. return sameSideOfWall(stack->getPosition(), destHex);
  169. return true;
  170. }
  171. std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsForStack(const CStack * stack, const BattleClientInterfaceData & data)
  172. {
  173. RETURN_IF_NOT_BATTLE(std::vector<PossiblePlayerBattleAction>());
  174. std::vector<PossiblePlayerBattleAction> allowedActionList;
  175. if(data.tacticsMode) //would "if(battleGetTacticDist() > 0)" work?
  176. {
  177. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_TACTICS);
  178. allowedActionList.push_back(PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK);
  179. }
  180. else
  181. {
  182. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  183. {
  184. if(stack->hasBonusOfType(Bonus::SPELLCASTER))
  185. {
  186. for (auto const & spellID : data.creatureSpellsToCast)
  187. {
  188. const CSpell *spell = spellID.toSpell();
  189. PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
  190. allowedActionList.push_back(act);
  191. }
  192. }
  193. if(stack->hasBonusOfType(Bonus::RANDOM_SPELLCASTER))
  194. allowedActionList.push_back(PossiblePlayerBattleAction::RANDOM_GENIE_SPELL);
  195. }
  196. if(stack->canShoot())
  197. allowedActionList.push_back(PossiblePlayerBattleAction::SHOOT);
  198. if(stack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE))
  199. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK_AND_RETURN);
  200. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK); //all active stacks can attack
  201. allowedActionList.push_back(PossiblePlayerBattleAction::WALK_AND_ATTACK); //not all stacks can always walk, but we will check this elsewhere
  202. if(stack->canMove() && stack->Speed(0, true)) //probably no reason to try move war machines or bound stacks
  203. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_STACK);
  204. const auto * siegedTown = battleGetDefendedTown();
  205. if(siegedTown && siegedTown->hasFort() && stack->hasBonusOfType(Bonus::CATAPULT)) //TODO: check shots
  206. allowedActionList.push_back(PossiblePlayerBattleAction::CATAPULT);
  207. if(stack->hasBonusOfType(Bonus::HEALER))
  208. allowedActionList.push_back(PossiblePlayerBattleAction::HEAL);
  209. }
  210. return allowedActionList;
  211. }
  212. PossiblePlayerBattleAction CBattleInfoCallback::getCasterAction(const CSpell * spell, const spells::Caster * caster, spells::Mode mode) const
  213. {
  214. RETURN_IF_NOT_BATTLE(PossiblePlayerBattleAction::INVALID);
  215. auto spellSelMode = PossiblePlayerBattleAction::ANY_LOCATION;
  216. const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell), mode);
  217. if(ti.massive || ti.type == spells::AimType::NO_TARGET)
  218. spellSelMode = PossiblePlayerBattleAction::NO_LOCATION;
  219. else if(ti.type == spells::AimType::LOCATION && ti.clearAffected)
  220. spellSelMode = PossiblePlayerBattleAction::FREE_LOCATION;
  221. else if(ti.type == spells::AimType::CREATURE)
  222. spellSelMode = PossiblePlayerBattleAction::AIMED_SPELL_CREATURE;
  223. else if(ti.type == spells::AimType::OBSTACLE)
  224. spellSelMode = PossiblePlayerBattleAction::OBSTACLE;
  225. return PossiblePlayerBattleAction(spellSelMode, spell->id);
  226. }
  227. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  228. {
  229. std::set<BattleHex> attackedHexes;
  230. RETURN_IF_NOT_BATTLE(attackedHexes);
  231. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  232. for (BattleHex tile : at.hostileCreaturePositions)
  233. {
  234. const auto * st = battleGetUnitByPos(tile, true);
  235. if(st && st->unitOwner() != attacker->unitOwner()) //only hostile stacks - does it work well with Berserk?
  236. {
  237. attackedHexes.insert(tile);
  238. }
  239. }
  240. for (BattleHex tile : at.friendlyCreaturePositions)
  241. {
  242. if(battleGetUnitByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  243. {
  244. attackedHexes.insert(tile);
  245. }
  246. }
  247. return attackedHexes;
  248. }
  249. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  250. {
  251. switch (mode)
  252. {
  253. case RANDOM_GENIE:
  254. return getRandomBeneficialSpell(rand, stack); //target
  255. break;
  256. case RANDOM_AIMED:
  257. return getRandomCastedSpell(rand, stack); //caster
  258. break;
  259. default:
  260. logGlobal->error("Incorrect mode of battleGetRandomSpell (%d)", static_cast<int>(mode));
  261. return SpellID::NONE;
  262. }
  263. }
  264. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  265. {
  266. RETURN_IF_NOT_BATTLE(nullptr);
  267. for(const auto * s : battleGetAllStacks(true))
  268. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  269. return s;
  270. return nullptr;
  271. }
  272. const battle::Unit * CBattleInfoCallback::battleGetUnitByPos(BattleHex pos, bool onlyAlive) const
  273. {
  274. RETURN_IF_NOT_BATTLE(nullptr);
  275. auto ret = battleGetUnitsIf([=](const battle::Unit * unit)
  276. {
  277. return !unit->isGhost()
  278. && vstd::contains(battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()), pos)
  279. && (!onlyAlive || unit->alive());
  280. });
  281. if(!ret.empty())
  282. return ret.front();
  283. else
  284. return nullptr;
  285. }
  286. battle::Units CBattleInfoCallback::battleAliveUnits() const
  287. {
  288. return battleGetUnitsIf([](const battle::Unit * unit)
  289. {
  290. return unit->isValidTarget(false);
  291. });
  292. }
  293. battle::Units CBattleInfoCallback::battleAliveUnits(ui8 side) const
  294. {
  295. return battleGetUnitsIf([=](const battle::Unit * unit)
  296. {
  297. return unit->isValidTarget(false) && unit->unitSide() == side;
  298. });
  299. }
  300. using namespace battle;
  301. //T is battle::Unit descendant
  302. template <typename T>
  303. const T * takeOneUnit(std::vector<const T*> & allUnits, const int turn, int8_t & sideThatLastMoved, int phase)
  304. {
  305. const T * returnedUnit = nullptr;
  306. size_t currentUnitIndex = 0;
  307. for(size_t i = 0; i < allUnits.size(); i++)
  308. {
  309. int32_t currentUnitInitiative = -1;
  310. int32_t returnedUnitInitiative = -1;
  311. if(returnedUnit)
  312. returnedUnitInitiative = returnedUnit->getInitiative(turn);
  313. if(!allUnits[i])
  314. continue;
  315. auto currentUnit = allUnits[i];
  316. currentUnitInitiative = currentUnit->getInitiative(turn);
  317. switch(phase)
  318. {
  319. case BattlePhases::NORMAL: // Faster first, attacker priority, higher slot first
  320. if(returnedUnit == nullptr || currentUnitInitiative > returnedUnitInitiative)
  321. {
  322. returnedUnit = currentUnit;
  323. currentUnitIndex = i;
  324. }
  325. else if(currentUnitInitiative == returnedUnitInitiative)
  326. {
  327. if(sideThatLastMoved == -1 && turn <= 0 && currentUnit->unitSide() == BattleSide::ATTACKER
  328. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Turn 0 attacker priority
  329. {
  330. returnedUnit = currentUnit;
  331. currentUnitIndex = i;
  332. }
  333. else if(sideThatLastMoved != -1 && currentUnit->unitSide() != sideThatLastMoved
  334. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  335. {
  336. returnedUnit = currentUnit;
  337. currentUnitIndex = i;
  338. }
  339. }
  340. break;
  341. case BattlePhases::WAIT_MORALE: // Slower first, higher slot first
  342. case BattlePhases::WAIT:
  343. if(returnedUnit == nullptr || currentUnitInitiative < returnedUnitInitiative)
  344. {
  345. returnedUnit = currentUnit;
  346. currentUnitIndex = i;
  347. }
  348. else if(currentUnitInitiative == returnedUnitInitiative && sideThatLastMoved != -1 && currentUnit->unitSide() != sideThatLastMoved
  349. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  350. {
  351. returnedUnit = currentUnit;
  352. currentUnitIndex = i;
  353. }
  354. break;
  355. default:
  356. break;
  357. }
  358. }
  359. if(!returnedUnit)
  360. return nullptr;
  361. allUnits[currentUnitIndex] = nullptr;
  362. return returnedUnit;
  363. }
  364. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & turns, const size_t maxUnits, const int maxTurns, const int turn, int8_t sideThatLastMoved) const
  365. {
  366. RETURN_IF_NOT_BATTLE();
  367. if(maxUnits == 0 && maxTurns == 0)
  368. {
  369. logGlobal->error("Attempt to get infinite battle queue");
  370. return;
  371. }
  372. auto actualTurn = turn > 0 ? turn : 0;
  373. auto turnsIsFull = [&]() -> bool
  374. {
  375. if(maxUnits == 0)
  376. return false;//no limit
  377. size_t turnsSize = 0;
  378. for(const auto & oneTurn : turns)
  379. turnsSize += oneTurn.size();
  380. return turnsSize >= maxUnits;
  381. };
  382. turns.emplace_back();
  383. // We'll split creatures with remaining movement to 4 buckets (SIEGE, NORMAL, WAIT_MORALE, WAIT)
  384. std::array<battle::Units, BattlePhases::NUMBER_OF_PHASES> phases; // Access using BattlePhases enum
  385. const battle::Unit * activeUnit = battleActiveUnit();
  386. if(activeUnit)
  387. {
  388. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  389. if(turn == 0 && activeUnit->willMove() && !activeUnit->waited())
  390. {
  391. turns.back().push_back(activeUnit);
  392. if(turnsIsFull())
  393. return;
  394. }
  395. //its first or current turn, turn priority for active stack side
  396. //TODO: what if active stack mind-controlled?
  397. if(turn <= 0 && sideThatLastMoved < 0)
  398. sideThatLastMoved = activeUnit->unitSide();
  399. }
  400. auto allUnits = battleGetUnitsIf([](const battle::Unit * unit)
  401. {
  402. return !unit->isGhost();
  403. });
  404. // If no unit will be EVER! able to move, battle is over.
  405. if(!vstd::contains_if(allUnits, [](const battle::Unit * unit) { return unit->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  406. {
  407. turns.clear();
  408. return;
  409. }
  410. for(const auto * unit : allUnits)
  411. {
  412. if((actualTurn == 0 && !unit->willMove()) //we are considering current round and unit won't move
  413. || (actualTurn > 0 && !unit->canMove(turn)) //unit won't be able to move in later rounds
  414. || (actualTurn == 0 && unit == activeUnit && !turns.at(0).empty() && unit == turns.front().front())) //it's active unit already added at the beginning of queue
  415. {
  416. continue;
  417. }
  418. int unitPhase = unit->battleQueuePhase(turn);
  419. phases[unitPhase].push_back(unit);
  420. }
  421. boost::sort(phases[BattlePhases::SIEGE], CMP_stack(BattlePhases::SIEGE, actualTurn, sideThatLastMoved));
  422. std::copy(phases[BattlePhases::SIEGE].begin(), phases[BattlePhases::SIEGE].end(), std::back_inserter(turns.back()));
  423. if(turnsIsFull())
  424. return;
  425. for(uint8_t phase = BattlePhases::NORMAL; phase < BattlePhases::NUMBER_OF_PHASES; phase++)
  426. boost::sort(phases[phase], CMP_stack(phase, actualTurn, sideThatLastMoved));
  427. uint8_t phase = BattlePhases::NORMAL;
  428. while(!turnsIsFull() && phase < BattlePhases::NUMBER_OF_PHASES)
  429. {
  430. const battle::Unit * currentUnit = nullptr;
  431. if(phases[phase].empty())
  432. phase++;
  433. else
  434. {
  435. currentUnit = takeOneUnit(phases[phase], actualTurn, sideThatLastMoved, phase);
  436. if(!currentUnit)
  437. {
  438. phase++;
  439. }
  440. else
  441. {
  442. turns.back().push_back(currentUnit);
  443. sideThatLastMoved = currentUnit->unitSide();
  444. }
  445. }
  446. }
  447. if(sideThatLastMoved < 0)
  448. sideThatLastMoved = BattleSide::ATTACKER;
  449. if(!turnsIsFull() && (maxTurns == 0 || turns.size() < maxTurns))
  450. battleGetTurnOrder(turns, maxUnits, maxTurns, actualTurn + 1, sideThatLastMoved);
  451. }
  452. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit) const
  453. {
  454. RETURN_IF_NOT_BATTLE(std::vector<BattleHex>());
  455. if(!unit->getPosition().isValid()) //turrets
  456. return std::vector<BattleHex>();
  457. auto reachability = getReachability(unit);
  458. return battleGetAvailableHexes(reachability, unit);
  459. }
  460. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit) const
  461. {
  462. std::vector<BattleHex> ret;
  463. RETURN_IF_NOT_BATTLE(ret);
  464. if(!unit->getPosition().isValid()) //turrets
  465. return ret;
  466. auto unitSpeed = unit->Speed(0, true);
  467. const bool tacticPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  468. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  469. {
  470. // If obstacles or other stacks makes movement impossible, it can't be helped.
  471. if(!cache.isReachable(i))
  472. continue;
  473. if(tacticPhase)
  474. {
  475. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  476. if(!isInTacticRange(i))
  477. continue;
  478. }
  479. else
  480. {
  481. //Not tactics phase -> destination must be reachable and within unit range.
  482. if(cache.distances[i] > static_cast<int>(unitSpeed))
  483. continue;
  484. }
  485. ret.emplace_back(i);
  486. }
  487. return ret;
  488. }
  489. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool addOccupiable, std::vector<BattleHex> * attackable) const
  490. {
  491. std::vector<BattleHex> ret = battleGetAvailableHexes(unit);
  492. if(ret.empty())
  493. return ret;
  494. if(addOccupiable && unit->doubleWide())
  495. {
  496. std::vector<BattleHex> occupiable;
  497. occupiable.reserve(ret.size());
  498. for(auto hex : ret)
  499. occupiable.push_back(unit->occupiedHex(hex));
  500. vstd::concatenate(ret, occupiable);
  501. }
  502. if(attackable)
  503. {
  504. auto meleeAttackable = [&](BattleHex hex) -> bool
  505. {
  506. // Return true if given hex has at least one available neighbour.
  507. // Available hexes are already present in ret vector.
  508. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  509. {
  510. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  511. });
  512. return availableNeighbor != ret.end();
  513. };
  514. for(const auto * otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  515. {
  516. if(!otherSt->isValidTarget(false))
  517. continue;
  518. std::vector<BattleHex> occupied = otherSt->getHexes();
  519. if(battleCanShoot(unit, otherSt->getPosition()))
  520. {
  521. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  522. continue;
  523. }
  524. for(BattleHex he : occupied)
  525. {
  526. if(meleeAttackable(he))
  527. attackable->push_back(he);
  528. }
  529. }
  530. }
  531. //adding occupiable likely adds duplicates to ret -> clean it up
  532. boost::sort(ret);
  533. ret.erase(boost::unique(ret).end(), ret.end());
  534. return ret;
  535. }
  536. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  537. {
  538. RETURN_IF_NOT_BATTLE(false);
  539. if(battleTacticDist())
  540. return false;
  541. if (!stack || !target)
  542. return false;
  543. if(!battleMatchOwner(stack, target))
  544. return false;
  545. auto id = stack->getCreature()->getId();
  546. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  547. return false;
  548. return target->alive();
  549. }
  550. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  551. {
  552. RETURN_IF_NOT_BATTLE(false);
  553. if(battleTacticDist()) //no shooting during tactics
  554. return false;
  555. if (!attacker)
  556. return false;
  557. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  558. return false;
  559. //forgetfulness
  560. TConstBonusListPtr forgetfulList = attacker->getBonuses(Selector::type()(Bonus::FORGETFULL));
  561. if(!forgetfulList->empty())
  562. {
  563. int forgetful = forgetfulList->valOfBonuses(Selector::type()(Bonus::FORGETFULL));
  564. //advanced+ level
  565. if(forgetful > 1)
  566. return false;
  567. }
  568. return attacker->canShoot() && (!battleIsUnitBlocked(attacker)
  569. || attacker->hasBonusOfType(Bonus::FREE_SHOOTING));
  570. }
  571. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  572. {
  573. RETURN_IF_NOT_BATTLE(false);
  574. const battle::Unit * defender = battleGetUnitByPos(dest);
  575. if(!attacker || !defender)
  576. return false;
  577. if(battleMatchOwner(attacker, defender) && defender->alive())
  578. {
  579. if(battleCanShoot(attacker))
  580. {
  581. auto limitedRangeBonus = attacker->getBonus(Selector::type()(Bonus::LIMITED_SHOOTING_RANGE));
  582. if(limitedRangeBonus == nullptr)
  583. {
  584. return true;
  585. }
  586. int shootingRange = limitedRangeBonus->val;
  587. return isEnemyUnitWithinSpecifiedRange(attacker->getPosition(), defender, shootingRange);
  588. }
  589. }
  590. return false;
  591. }
  592. DamageEstimation CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  593. {
  594. DamageCalculator calculator(*this, info);
  595. return calculator.calculateDmgRange();
  596. }
  597. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPosition, DamageEstimation * retaliationDmg) const
  598. {
  599. RETURN_IF_NOT_BATTLE({});
  600. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  601. int movementDistance = reachability[attackerPosition];
  602. return battleEstimateDamage(attacker, defender, movementDistance, retaliationDmg);
  603. }
  604. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementDistance, DamageEstimation * retaliationDmg) const
  605. {
  606. RETURN_IF_NOT_BATTLE({});
  607. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  608. const BattleAttackInfo bai(attacker, defender, movementDistance, shooting);
  609. return battleEstimateDamage(bai, retaliationDmg);
  610. }
  611. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, DamageEstimation * retaliationDmg) const
  612. {
  613. RETURN_IF_NOT_BATTLE({});
  614. DamageEstimation ret = calculateDmgRange(bai);
  615. if(retaliationDmg)
  616. {
  617. if(bai.shooting)
  618. {
  619. //FIXME: handle RANGED_RETALIATION
  620. *retaliationDmg = DamageEstimation();
  621. }
  622. else
  623. {
  624. //TODO: rewrite using boost::numeric::interval
  625. //TODO: rewire once more using interval-based fuzzy arithmetic
  626. auto const & estimateRetaliation = [&]( int64_t damage)
  627. {
  628. auto retaliationAttack = bai.reverse();
  629. auto state = retaliationAttack.attacker->acquireState();
  630. state->damage(damage);
  631. retaliationAttack.attacker = state.get();
  632. return calculateDmgRange(retaliationAttack);
  633. };
  634. DamageEstimation retaliationMin = estimateRetaliation(ret.damage.min);
  635. DamageEstimation retaliationMax = estimateRetaliation(ret.damage.min);
  636. retaliationDmg->damage.min = std::min(retaliationMin.damage.min, retaliationMax.damage.min);
  637. retaliationDmg->damage.max = std::max(retaliationMin.damage.max, retaliationMax.damage.max);
  638. retaliationDmg->kills.min = std::min(retaliationMin.kills.min, retaliationMax.kills.min);
  639. retaliationDmg->kills.max = std::max(retaliationMin.kills.max, retaliationMax.kills.max);
  640. }
  641. }
  642. return ret;
  643. }
  644. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  645. {
  646. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  647. RETURN_IF_NOT_BATTLE(obstacles);
  648. for(auto & obs : battleGetAllObstacles())
  649. {
  650. if(vstd::contains(obs->getBlockedTiles(), tile)
  651. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  652. {
  653. obstacles.push_back(obs);
  654. }
  655. }
  656. return obstacles;
  657. }
  658. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit, const std::set<BattleHex> & passed) const
  659. {
  660. auto affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  661. RETURN_IF_NOT_BATTLE(affectedObstacles);
  662. if(unit->alive())
  663. {
  664. if(!passed.count(unit->getPosition()))
  665. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  666. if(unit->doubleWide())
  667. {
  668. BattleHex otherHex = unit->occupiedHex();
  669. if(otherHex.isValid() && !passed.count(otherHex))
  670. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  671. if(!vstd::contains(affectedObstacles, i))
  672. affectedObstacles.push_back(i);
  673. }
  674. for(auto hex : unit->getHexes())
  675. if(hex == ESiegeHex::GATE_BRIDGE)
  676. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  677. for(int i=0; i<affectedObstacles.size(); i++)
  678. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  679. affectedObstacles.erase(affectedObstacles.begin()+i);
  680. }
  681. return affectedObstacles;
  682. }
  683. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  684. {
  685. AccessibilityInfo ret;
  686. ret.fill(EAccessibility::ACCESSIBLE);
  687. //removing accessibility for side columns of hexes
  688. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  689. {
  690. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  691. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  692. }
  693. //special battlefields with logically unavailable tiles
  694. auto bFieldType = battleGetBattlefieldType();
  695. if(bFieldType != BattleField::NONE)
  696. {
  697. std::vector<BattleHex> impassableHexes = bFieldType.getInfo()->impassableHexes;
  698. for(auto hex : impassableHexes)
  699. ret[hex] = EAccessibility::UNAVAILABLE;
  700. }
  701. //gate -> should be before stacks
  702. if(battleGetSiegeLevel() > 0)
  703. {
  704. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  705. switch(battleGetGateState())
  706. {
  707. case EGateState::CLOSED:
  708. accessability = EAccessibility::GATE;
  709. break;
  710. case EGateState::BLOCKED:
  711. accessability = EAccessibility::UNAVAILABLE;
  712. break;
  713. }
  714. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  715. }
  716. //tiles occupied by standing stacks
  717. for(const auto * unit : battleAliveUnits())
  718. {
  719. for(auto hex : unit->getHexes())
  720. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  721. ret[hex] = EAccessibility::ALIVE_STACK;
  722. }
  723. //obstacles
  724. for(const auto &obst : battleGetAllObstacles())
  725. {
  726. for(auto hex : obst->getBlockedTiles())
  727. ret[hex] = EAccessibility::OBSTACLE;
  728. }
  729. //walls
  730. if(battleGetSiegeLevel() > 0)
  731. {
  732. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  733. for(auto hex : permanentlyLocked)
  734. ret[hex] = EAccessibility::UNAVAILABLE;
  735. //TODO likely duplicated logic
  736. static const std::pair<EWallPart, BattleHex> lockedIfNotDestroyed[] =
  737. {
  738. //which part of wall, which hex is blocked if this part of wall is not destroyed
  739. std::make_pair(EWallPart::BOTTOM_WALL, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  740. std::make_pair(EWallPart::BELOW_GATE, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  741. std::make_pair(EWallPart::OVER_GATE, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  742. std::make_pair(EWallPart::UPPER_WALL, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  743. };
  744. for(const auto & elem : lockedIfNotDestroyed)
  745. {
  746. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  747. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  748. }
  749. }
  750. return ret;
  751. }
  752. AccessibilityInfo CBattleInfoCallback::getAccesibility(const battle::Unit * stack) const
  753. {
  754. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  755. }
  756. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  757. {
  758. auto ret = getAccesibility();
  759. for(auto hex : accessibleHexes)
  760. if(hex.isValid())
  761. ret[hex] = EAccessibility::ACCESSIBLE;
  762. return ret;
  763. }
  764. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  765. {
  766. ReachabilityInfo ret;
  767. ret.accessibility = accessibility;
  768. ret.params = params;
  769. ret.predecessors.fill(BattleHex::INVALID);
  770. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  771. if(!params.startPosition.isValid()) //if got call for arrow turrets
  772. return ret;
  773. const std::set<BattleHex> obstacles = getStoppers(params.perspective);
  774. auto checkParams = params;
  775. checkParams.ignoreKnownAccessible = true; //Ignore starting hexes obstacles
  776. std::queue<BattleHex> hexq; //bfs queue
  777. //first element
  778. hexq.push(params.startPosition);
  779. ret.distances[params.startPosition] = 0;
  780. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache{};
  781. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  782. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  783. while(!hexq.empty()) //bfs loop
  784. {
  785. const BattleHex curHex = hexq.front();
  786. hexq.pop();
  787. //walking stack can't step past the obstacles
  788. if(isInObstacle(curHex, obstacles, checkParams))
  789. continue;
  790. const int costToNeighbour = ret.distances[curHex.hex] + 1;
  791. for(BattleHex neighbour : BattleHex::neighbouringTilesCache[curHex.hex])
  792. {
  793. if(neighbour.isValid())
  794. {
  795. const int costFoundSoFar = ret.distances[neighbour.hex];
  796. if(accessibleCache[neighbour.hex] && costToNeighbour < costFoundSoFar)
  797. {
  798. hexq.push(neighbour);
  799. ret.distances[neighbour.hex] = costToNeighbour;
  800. ret.predecessors[neighbour.hex] = curHex;
  801. }
  802. }
  803. }
  804. }
  805. return ret;
  806. }
  807. bool CBattleInfoCallback::isInObstacle(
  808. BattleHex hex,
  809. const std::set<BattleHex> & obstacles,
  810. const ReachabilityInfo::Parameters & params) const
  811. {
  812. auto occupiedHexes = battle::Unit::getHexes(hex, params.doubleWide, params.side);
  813. for(auto occupiedHex : occupiedHexes)
  814. {
  815. if(params.ignoreKnownAccessible && vstd::contains(params.knownAccessible, occupiedHex))
  816. continue;
  817. if(vstd::contains(obstacles, occupiedHex))
  818. {
  819. if(occupiedHex == ESiegeHex::GATE_BRIDGE)
  820. {
  821. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  822. return true;
  823. }
  824. else
  825. return true;
  826. }
  827. }
  828. return false;
  829. }
  830. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  831. {
  832. std::set<BattleHex> ret;
  833. RETURN_IF_NOT_BATTLE(ret);
  834. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  835. {
  836. if(!battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  837. continue;
  838. for(const auto & hex : oi->getStoppingTile())
  839. {
  840. if(hex == ESiegeHex::GATE_BRIDGE && oi->obstacleType == CObstacleInstance::MOAT)
  841. {
  842. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  843. continue; // this tile is disabled by drawbridge on top of it
  844. }
  845. ret.insert(hex);
  846. }
  847. }
  848. return ret;
  849. }
  850. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  851. {
  852. auto reachability = getReachability(closest);
  853. auto avHexes = battleGetAvailableHexes(reachability, closest);
  854. // I hate std::pairs with their undescriptive member names first / second
  855. struct DistStack
  856. {
  857. uint32_t distanceToPred;
  858. BattleHex destination;
  859. const battle::Unit * stack;
  860. };
  861. std::vector<DistStack> stackPairs;
  862. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  863. {
  864. return unit->isValidTarget(false) && unit != closest;
  865. });
  866. for(const battle::Unit * st : possible)
  867. {
  868. for(BattleHex hex : avHexes)
  869. if(CStack::isMeleeAttackPossible(closest, st, hex))
  870. {
  871. DistStack hlp = {reachability.distances[hex], hex, st};
  872. stackPairs.push_back(hlp);
  873. }
  874. }
  875. if(!stackPairs.empty())
  876. {
  877. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  878. auto minimal = boost::min_element(stackPairs, comparator);
  879. return std::make_pair(minimal->stack, minimal->destination);
  880. }
  881. else
  882. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  883. }
  884. BattleHex CBattleInfoCallback::getAvaliableHex(const CreatureID & creID, ui8 side, int initialPos) const
  885. {
  886. bool twoHex = VLC->creh->objects[creID]->isDoubleWide();
  887. int pos;
  888. if (initialPos > -1)
  889. pos = initialPos;
  890. else //summon elementals depending on player side
  891. {
  892. if(side == BattleSide::ATTACKER)
  893. pos = 0; //top left
  894. else
  895. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  896. }
  897. auto accessibility = getAccesibility();
  898. std::set<BattleHex> occupyable;
  899. for(int i = 0; i < accessibility.size(); i++)
  900. if(accessibility.accessible(i, twoHex, side))
  901. occupyable.insert(i);
  902. if(occupyable.empty())
  903. {
  904. return BattleHex::INVALID; //all tiles are covered
  905. }
  906. return BattleHex::getClosestTile(side, pos, occupyable);
  907. }
  908. si8 CBattleInfoCallback::battleGetTacticDist() const
  909. {
  910. RETURN_IF_NOT_BATTLE(0);
  911. //TODO get rid of this method
  912. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  913. return battleTacticDist();
  914. return 0;
  915. }
  916. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  917. {
  918. RETURN_IF_NOT_BATTLE(false);
  919. auto side = battleGetTacticsSide();
  920. auto dist = battleGetTacticDist();
  921. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  922. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  923. }
  924. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  925. {
  926. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  927. if(!battleDoWeKnowAbout(unit->unitSide()))
  928. {
  929. //Stack is held by enemy, we can't use his perspective to check for reachability.
  930. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  931. params.perspective = battleGetMySide();
  932. }
  933. return getReachability(params);
  934. }
  935. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  936. {
  937. if(params.flying)
  938. return getFlyingReachability(params);
  939. else
  940. return makeBFS(getAccesibility(params.knownAccessible), params);
  941. }
  942. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  943. {
  944. ReachabilityInfo ret;
  945. ret.accessibility = getAccesibility(params.knownAccessible);
  946. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  947. {
  948. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  949. {
  950. ret.predecessors[i] = params.startPosition;
  951. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  952. }
  953. }
  954. return ret;
  955. }
  956. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const battle::Unit* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  957. {
  958. //does not return hex attacked directly
  959. AttackableTiles at;
  960. RETURN_IF_NOT_BATTLE(at);
  961. BattleHex attackOriginHex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  962. const auto * defender = battleGetUnitByPos(destinationTile, true);
  963. if (!defender)
  964. return at; // can't attack thin air
  965. bool reverse = isToReverse(attacker, defender);
  966. if(reverse && attacker->doubleWide())
  967. {
  968. attackOriginHex = attacker->occupiedHex(attackOriginHex); //the other hex stack stands on
  969. }
  970. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  971. {
  972. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  973. }
  974. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  975. {
  976. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  977. for(BattleHex tile : hexes)
  978. {
  979. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, attackOriginHex) > -1)) //adjacent both to attacker's head and attacked tile
  980. {
  981. const auto * st = battleGetUnitByPos(tile, true);
  982. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  983. at.hostileCreaturePositions.insert(tile);
  984. }
  985. }
  986. }
  987. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  988. {
  989. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  990. for(int i = 0; i<hexes.size(); i++)
  991. {
  992. if(hexes.at(i) == attackOriginHex)
  993. {
  994. hexes.erase(hexes.begin() + i);
  995. i = 0;
  996. }
  997. }
  998. for(BattleHex tile : hexes)
  999. {
  1000. //friendly stacks can also be damaged by Dragon Breath
  1001. const auto * st = battleGetUnitByPos(tile, true);
  1002. if(st && st != attacker)
  1003. at.friendlyCreaturePositions.insert(tile);
  1004. }
  1005. }
  1006. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  1007. {
  1008. auto direction = BattleHex::mutualPosition(attackOriginHex, destinationTile);
  1009. if(direction != BattleHex::NONE) //only adjacent hexes are subject of dragon breath calculation
  1010. {
  1011. BattleHex nextHex = destinationTile.cloneInDirection(direction, false);
  1012. if ( defender->doubleWide() )
  1013. {
  1014. auto secondHex = destinationTile == defender->getPosition() ?
  1015. defender->occupiedHex():
  1016. defender->getPosition();
  1017. // if targeted double-wide creature is attacked from above or below ( -> second hex is also adjacent to attack origin)
  1018. // then dragon breath should target tile on the opposite side of targeted creature
  1019. if (BattleHex::mutualPosition(attackOriginHex, secondHex) != BattleHex::NONE)
  1020. nextHex = secondHex.cloneInDirection(direction, false);
  1021. }
  1022. if (nextHex.isValid())
  1023. {
  1024. //friendly stacks can also be damaged by Dragon Breath
  1025. const auto * st = battleGetUnitByPos(nextHex, true);
  1026. if(st != nullptr)
  1027. at.friendlyCreaturePositions.insert(nextHex);
  1028. }
  1029. }
  1030. }
  1031. return at;
  1032. }
  1033. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1034. {
  1035. //does not return hex attacked directly
  1036. AttackableTiles at;
  1037. RETURN_IF_NOT_BATTLE(at);
  1038. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1039. {
  1040. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1041. targetHexes.push_back(destinationTile);
  1042. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1043. }
  1044. return at;
  1045. }
  1046. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(const battle::Unit* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1047. {
  1048. std::vector<const battle::Unit*> units;
  1049. RETURN_IF_NOT_BATTLE(units);
  1050. AttackableTiles at;
  1051. if (rangedAttack)
  1052. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1053. else
  1054. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1055. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1056. {
  1057. if (unit->isGhost() || !unit->alive())
  1058. return false;
  1059. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1060. {
  1061. if (vstd::contains(at.hostileCreaturePositions, hex))
  1062. return true;
  1063. if (vstd::contains(at.friendlyCreaturePositions, hex))
  1064. return true;
  1065. }
  1066. return false;
  1067. });
  1068. return units;
  1069. }
  1070. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1071. {
  1072. std::set<const CStack*> attackedCres;
  1073. RETURN_IF_NOT_BATTLE(attackedCres);
  1074. AttackableTiles at;
  1075. if(rangedAttack)
  1076. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1077. else
  1078. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1079. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1080. {
  1081. const CStack * st = battleGetStackByPos(tile, true);
  1082. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1083. {
  1084. attackedCres.insert(st);
  1085. }
  1086. }
  1087. for (BattleHex tile : at.friendlyCreaturePositions)
  1088. {
  1089. const CStack * st = battleGetStackByPos(tile, true);
  1090. if(st) //friendly stacks can also be damaged by Dragon Breath
  1091. {
  1092. attackedCres.insert(st);
  1093. }
  1094. }
  1095. return attackedCres;
  1096. }
  1097. static bool isHexInFront(BattleHex hex, BattleHex testHex, BattleSide::Type side )
  1098. {
  1099. static const std::set<BattleHex::EDir> rightDirs { BattleHex::BOTTOM_RIGHT, BattleHex::TOP_RIGHT, BattleHex::RIGHT };
  1100. static const std::set<BattleHex::EDir> leftDirs { BattleHex::BOTTOM_LEFT, BattleHex::TOP_LEFT, BattleHex::LEFT };
  1101. auto mutualPos = BattleHex::mutualPosition(hex, testHex);
  1102. if (side == BattleSide::ATTACKER)
  1103. return rightDirs.count(mutualPos);
  1104. else
  1105. return leftDirs.count(mutualPos);
  1106. }
  1107. //TODO: this should apply also to mechanics and cursor interface
  1108. bool CBattleInfoCallback::isToReverse(const battle::Unit * attacker, const battle::Unit * defender) const
  1109. {
  1110. BattleHex attackerHex = attacker->getPosition();
  1111. BattleHex defenderHex = defender->getPosition();
  1112. if (attackerHex < 0 ) //turret
  1113. return false;
  1114. if(isHexInFront(attackerHex, defenderHex, static_cast<BattleSide::Type>(attacker->unitSide())))
  1115. return false;
  1116. if (defender->doubleWide())
  1117. {
  1118. if(isHexInFront(attackerHex, defender->occupiedHex(), static_cast<BattleSide::Type>(attacker->unitSide())))
  1119. return false;
  1120. }
  1121. if (attacker->doubleWide())
  1122. {
  1123. if(isHexInFront(attacker->occupiedHex(), defenderHex, static_cast<BattleSide::Type>(attacker->unitSide())))
  1124. return false;
  1125. }
  1126. // a bit weird case since here defender is slightly behind attacker, so reversing seems preferable,
  1127. // but this is how H3 handles it which is important, e.g. for direction of dragon breath attacks
  1128. if (attacker->doubleWide() && defender->doubleWide())
  1129. {
  1130. if(isHexInFront(attacker->occupiedHex(), defender->occupiedHex(), static_cast<BattleSide::Type>(attacker->unitSide())))
  1131. return false;
  1132. }
  1133. return true;
  1134. }
  1135. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1136. {
  1137. ReachabilityInfo::TDistances ret;
  1138. ret.fill(-1);
  1139. RETURN_IF_NOT_BATTLE(ret);
  1140. auto reachability = getReachability(unit);
  1141. boost::copy(reachability.distances, ret.begin());
  1142. return ret;
  1143. }
  1144. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1145. {
  1146. RETURN_IF_NOT_BATTLE(false);
  1147. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1148. static const auto selectorNoDistancePenalty = Selector::type()(Bonus::NO_DISTANCE_PENALTY);
  1149. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1150. return false;
  1151. if(const auto * target = battleGetUnitByPos(destHex, true))
  1152. {
  1153. //If any hex of target creature is within range, there is no penalty
  1154. int range = GameConstants::BATTLE_PENALTY_DISTANCE;
  1155. auto bonus = shooter->getBonus(Selector::type()(Bonus::LIMITED_SHOOTING_RANGE));
  1156. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  1157. range = bonus->additionalInfo[0];
  1158. if(isEnemyUnitWithinSpecifiedRange(shooterPosition, target, range))
  1159. return false;
  1160. }
  1161. else
  1162. {
  1163. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1164. return false;
  1165. }
  1166. return true;
  1167. }
  1168. bool CBattleInfoCallback::isEnemyUnitWithinSpecifiedRange(BattleHex attackerPosition, const battle::Unit * defenderUnit, unsigned int range) const
  1169. {
  1170. for(auto hex : defenderUnit->getHexes())
  1171. if(BattleHex::getDistance(attackerPosition, hex) <= range)
  1172. return true;
  1173. return false;
  1174. }
  1175. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart part) const
  1176. {
  1177. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1178. return WallPartToHex(part);
  1179. }
  1180. EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1181. {
  1182. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1183. return hexToWallPart(hex);
  1184. }
  1185. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart wallPart) const
  1186. {
  1187. RETURN_IF_NOT_BATTLE(false);
  1188. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1189. wallPart != EWallPart::INVALID;
  1190. }
  1191. bool CBattleInfoCallback::isWallPartAttackable(EWallPart wallPart) const
  1192. {
  1193. RETURN_IF_NOT_BATTLE(false);
  1194. if(isWallPartPotentiallyAttackable(wallPart))
  1195. {
  1196. auto wallState = battleGetWallState(wallPart);
  1197. return (wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED);
  1198. }
  1199. return false;
  1200. }
  1201. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1202. {
  1203. std::vector<BattleHex> attackableBattleHexes;
  1204. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1205. for(const auto & wallPartPair : wallParts)
  1206. {
  1207. if(isWallPartAttackable(wallPartPair.second))
  1208. attackableBattleHexes.emplace_back(wallPartPair.first);
  1209. }
  1210. return attackableBattleHexes;
  1211. }
  1212. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1213. {
  1214. RETURN_IF_NOT_BATTLE(-1);
  1215. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1216. int32_t ret = caster->getSpellCost(sp);
  1217. //checking for friendly stacks reducing cost of the spell and
  1218. //enemy stacks increasing it
  1219. int32_t manaReduction = 0;
  1220. int32_t manaIncrease = 0;
  1221. for(const auto * unit : battleAliveUnits())
  1222. {
  1223. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1224. {
  1225. vstd::amax(manaReduction, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1226. }
  1227. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1228. {
  1229. vstd::amax(manaIncrease, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1230. }
  1231. }
  1232. return ret - manaReduction + manaIncrease;
  1233. }
  1234. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1235. {
  1236. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1237. }
  1238. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1239. {
  1240. RETURN_IF_NOT_BATTLE(false);
  1241. if(unit->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1242. return false;
  1243. for(const auto * adjacent : battleAdjacentUnits(unit))
  1244. {
  1245. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1251. {
  1252. std::set<const battle::Unit *> ret;
  1253. RETURN_IF_NOT_BATTLE(ret);
  1254. for(auto hex : unit->getSurroundingHexes())
  1255. {
  1256. if(const auto * neighbour = battleGetUnitByPos(hex, true))
  1257. ret.insert(neighbour);
  1258. }
  1259. return ret;
  1260. }
  1261. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1262. {
  1263. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1264. //This is complete list. No spells from mods.
  1265. //todo: this should be Spellbook of caster Stack
  1266. static const std::set<SpellID> allPossibleSpells =
  1267. {
  1268. SpellID::AIR_SHIELD,
  1269. SpellID::ANTI_MAGIC,
  1270. SpellID::BLESS,
  1271. SpellID::BLOODLUST,
  1272. SpellID::COUNTERSTRIKE,
  1273. SpellID::CURE,
  1274. SpellID::FIRE_SHIELD,
  1275. SpellID::FORTUNE,
  1276. SpellID::HASTE,
  1277. SpellID::MAGIC_MIRROR,
  1278. SpellID::MIRTH,
  1279. SpellID::PRAYER,
  1280. SpellID::PRECISION,
  1281. SpellID::PROTECTION_FROM_AIR,
  1282. SpellID::PROTECTION_FROM_EARTH,
  1283. SpellID::PROTECTION_FROM_FIRE,
  1284. SpellID::PROTECTION_FROM_WATER,
  1285. SpellID::SHIELD,
  1286. SpellID::SLAYER,
  1287. SpellID::STONE_SKIN
  1288. };
  1289. std::vector<SpellID> beneficialSpells;
  1290. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1291. {
  1292. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1293. {
  1294. return pred(stack) && stack->owner != subject->owner && stack->isValidTarget(false);
  1295. });
  1296. if(stacks.empty())
  1297. return nullptr;
  1298. else
  1299. return stacks.front();
  1300. };
  1301. for(const SpellID& spellID : allPossibleSpells)
  1302. {
  1303. std::stringstream cachingStr;
  1304. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1305. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1306. //TODO: this ability has special limitations
  1307. || !(spellID.toSpell()->canBeCast(this, spells::Mode::CREATURE_ACTIVE, subject)))
  1308. continue;
  1309. switch (spellID)
  1310. {
  1311. case SpellID::SHIELD:
  1312. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1313. {
  1314. const auto * walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1315. {
  1316. return !stack->canShoot();
  1317. });
  1318. if(!walker)
  1319. continue;
  1320. }
  1321. break;
  1322. case SpellID::AIR_SHIELD: //only against active shooters
  1323. {
  1324. const auto * shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1325. {
  1326. return stack->canShoot();
  1327. });
  1328. if(!shooter)
  1329. continue;
  1330. }
  1331. break;
  1332. case SpellID::ANTI_MAGIC:
  1333. case SpellID::MAGIC_MIRROR:
  1334. case SpellID::PROTECTION_FROM_AIR:
  1335. case SpellID::PROTECTION_FROM_EARTH:
  1336. case SpellID::PROTECTION_FROM_FIRE:
  1337. case SpellID::PROTECTION_FROM_WATER:
  1338. {
  1339. const ui8 enemySide = 1 - subject->side;
  1340. //todo: only if enemy has spellbook
  1341. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1342. continue;
  1343. }
  1344. break;
  1345. case SpellID::CURE: //only damaged units
  1346. {
  1347. //do not cast on affected by debuffs
  1348. if(!subject->canBeHealed())
  1349. continue;
  1350. }
  1351. break;
  1352. case SpellID::BLOODLUST:
  1353. {
  1354. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1355. continue;
  1356. }
  1357. break;
  1358. case SpellID::PRECISION:
  1359. {
  1360. if(!subject->canShoot())
  1361. continue;
  1362. }
  1363. break;
  1364. case SpellID::SLAYER://only if monsters are present
  1365. {
  1366. const auto * kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1367. {
  1368. const auto isKing = Selector::type()(Bonus::KING);
  1369. return stack->hasBonus(isKing);
  1370. });
  1371. if (!kingMonster)
  1372. continue;
  1373. }
  1374. break;
  1375. }
  1376. beneficialSpells.push_back(spellID);
  1377. }
  1378. if(!beneficialSpells.empty())
  1379. {
  1380. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1381. }
  1382. else
  1383. {
  1384. return SpellID::NONE;
  1385. }
  1386. }
  1387. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1388. {
  1389. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1390. TConstBonusListPtr bl = caster->getBonuses(Selector::type()(Bonus::SPELLCASTER));
  1391. if (!bl->size())
  1392. return SpellID::NONE;
  1393. int totalWeight = 0;
  1394. for(const auto & b : *bl)
  1395. {
  1396. totalWeight += std::max(b->additionalInfo[0], 0); //spells with 0 weight are non-random, exclude them
  1397. }
  1398. if (totalWeight == 0)
  1399. return SpellID::NONE;
  1400. int randomPos = rand.nextInt(totalWeight - 1);
  1401. for(const auto & b : *bl)
  1402. {
  1403. randomPos -= std::max(b->additionalInfo[0], 0);
  1404. if(randomPos < 0)
  1405. {
  1406. return SpellID(b->subtype);
  1407. }
  1408. }
  1409. return SpellID::NONE;
  1410. }
  1411. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1412. {
  1413. RETURN_IF_NOT_BATTLE(-3);
  1414. if(!battleCanSurrender(Player))
  1415. return -1;
  1416. const auto sideOpt = playerToSide(Player);
  1417. if(!sideOpt)
  1418. return -1;
  1419. const auto side = sideOpt.get();
  1420. int ret = 0;
  1421. double discount = 0;
  1422. for(const auto * unit : battleAliveUnits(side))
  1423. ret += unit->getRawSurrenderCost();
  1424. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1425. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1426. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1427. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1428. return ret;
  1429. }
  1430. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1431. {
  1432. const IBonusBearer * node = nullptr;
  1433. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1434. node = h;
  1435. else
  1436. node = getBattleNode();
  1437. if(!node)
  1438. return 0;
  1439. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_BELOW));
  1440. if(b->size())
  1441. return b->totalValue();
  1442. return 0;
  1443. }
  1444. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1445. {
  1446. const IBonusBearer *node = nullptr;
  1447. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1448. node = h;
  1449. else
  1450. node = getBattleNode();
  1451. if(!node)
  1452. return GameConstants::SPELL_LEVELS;
  1453. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1454. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_ABOVE));
  1455. if(b->size())
  1456. return b->totalValue();
  1457. return GameConstants::SPELL_LEVELS;
  1458. }
  1459. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1460. {
  1461. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1462. {
  1463. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1464. });
  1465. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1466. for(auto & unit : units)
  1467. {
  1468. //todo: move SIEGE_WEAPON check to Unit state
  1469. hasUnit.at(unit->unitSide()) = true;
  1470. if(hasUnit[0] && hasUnit[1])
  1471. return boost::none;
  1472. }
  1473. hasUnit = {false, false};
  1474. for(auto & unit : units)
  1475. {
  1476. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1477. {
  1478. hasUnit.at(unit->unitSide()) = true;
  1479. }
  1480. }
  1481. if(!hasUnit[0] && !hasUnit[1])
  1482. return 2;
  1483. if(!hasUnit[1])
  1484. return 0;
  1485. else
  1486. return 1;
  1487. }
  1488. VCMI_LIB_NAMESPACE_END