CBattleInfoCallback.cpp 53 KB

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