CBattleInfoCallback.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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. DamageRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  589. {
  590. DamageCalculator calculator(*this, info);
  591. return calculator.calculateDmgRange();
  592. }
  593. DamageRange CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPosition, DamageRange * retaliationDmg) const
  594. {
  595. RETURN_IF_NOT_BATTLE({0, 0});
  596. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  597. int movementDistance = reachability[attackerPosition];
  598. return battleEstimateDamage(attacker, defender, movementDistance, retaliationDmg);
  599. }
  600. DamageRange CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementDistance, DamageRange * retaliationDmg) const
  601. {
  602. RETURN_IF_NOT_BATTLE({0, 0});
  603. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  604. const BattleAttackInfo bai(attacker, defender, movementDistance, shooting);
  605. return battleEstimateDamage(bai, retaliationDmg);
  606. }
  607. DamageRange CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, DamageRange * retaliationDmg) const
  608. {
  609. RETURN_IF_NOT_BATTLE({0, 0});
  610. DamageRange ret = calculateDmgRange(bai);
  611. if(retaliationDmg)
  612. {
  613. if(bai.shooting)
  614. {
  615. //FIXME: handle RANGED_RETALIATION
  616. retaliationDmg->min = 0;
  617. retaliationDmg->max = 0;
  618. }
  619. else
  620. {
  621. //TODO: rewrite using boost::numeric::interval
  622. //TODO: rewire once more using interval-based fuzzy arithmetic
  623. int64_t DamageRange::* pairElems[] = {&DamageRange::min, &DamageRange::max};
  624. for (int i=0; i<2; ++i)
  625. {
  626. auto retaliationAttack = bai.reverse();
  627. int64_t dmg = ret.*pairElems[i];
  628. auto state = retaliationAttack.attacker->acquireState();
  629. state->damage(dmg);
  630. retaliationAttack.attacker = state.get();
  631. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  632. }
  633. }
  634. }
  635. return ret;
  636. }
  637. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  638. {
  639. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  640. RETURN_IF_NOT_BATTLE(obstacles);
  641. for(auto & obs : battleGetAllObstacles())
  642. {
  643. if(vstd::contains(obs->getBlockedTiles(), tile)
  644. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  645. {
  646. obstacles.push_back(obs);
  647. }
  648. }
  649. return obstacles;
  650. }
  651. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit) const
  652. {
  653. std::vector<std::shared_ptr<const CObstacleInstance>> affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  654. RETURN_IF_NOT_BATTLE(affectedObstacles);
  655. if(unit->alive())
  656. {
  657. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  658. if(unit->doubleWide())
  659. {
  660. BattleHex otherHex = unit->occupiedHex(unit->getPosition());
  661. if(otherHex.isValid())
  662. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  663. affectedObstacles.push_back(i);
  664. }
  665. for(auto hex : unit->getHexes())
  666. if(hex == ESiegeHex::GATE_BRIDGE)
  667. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  668. for(int i=0; i<affectedObstacles.size(); i++)
  669. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  670. affectedObstacles.erase(affectedObstacles.begin()+i);
  671. }
  672. return affectedObstacles;
  673. }
  674. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  675. {
  676. AccessibilityInfo ret;
  677. ret.fill(EAccessibility::ACCESSIBLE);
  678. //removing accessibility for side columns of hexes
  679. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  680. {
  681. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  682. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  683. }
  684. //special battlefields with logically unavailable tiles
  685. auto bFieldType = battleGetBattlefieldType();
  686. if(bFieldType != BattleField::NONE)
  687. {
  688. std::vector<BattleHex> impassableHexes = bFieldType.getInfo()->impassableHexes;
  689. for(auto hex : impassableHexes)
  690. ret[hex] = EAccessibility::UNAVAILABLE;
  691. }
  692. //gate -> should be before stacks
  693. if(battleGetSiegeLevel() > 0)
  694. {
  695. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  696. switch(battleGetGateState())
  697. {
  698. case EGateState::CLOSED:
  699. accessability = EAccessibility::GATE;
  700. break;
  701. case EGateState::BLOCKED:
  702. accessability = EAccessibility::UNAVAILABLE;
  703. break;
  704. }
  705. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  706. }
  707. //tiles occupied by standing stacks
  708. for(const auto * unit : battleAliveUnits())
  709. {
  710. for(auto hex : unit->getHexes())
  711. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  712. ret[hex] = EAccessibility::ALIVE_STACK;
  713. }
  714. //obstacles
  715. for(const auto &obst : battleGetAllObstacles())
  716. {
  717. for(auto hex : obst->getBlockedTiles())
  718. ret[hex] = EAccessibility::OBSTACLE;
  719. }
  720. //walls
  721. if(battleGetSiegeLevel() > 0)
  722. {
  723. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  724. for(auto hex : permanentlyLocked)
  725. ret[hex] = EAccessibility::UNAVAILABLE;
  726. //TODO likely duplicated logic
  727. static const std::pair<EWallPart, BattleHex> lockedIfNotDestroyed[] =
  728. {
  729. //which part of wall, which hex is blocked if this part of wall is not destroyed
  730. std::make_pair(EWallPart::BOTTOM_WALL, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  731. std::make_pair(EWallPart::BELOW_GATE, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  732. std::make_pair(EWallPart::OVER_GATE, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  733. std::make_pair(EWallPart::UPPER_WALL, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  734. };
  735. for(const auto & elem : lockedIfNotDestroyed)
  736. {
  737. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  738. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  739. }
  740. }
  741. return ret;
  742. }
  743. AccessibilityInfo CBattleInfoCallback::getAccesibility(const battle::Unit * stack) const
  744. {
  745. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  746. }
  747. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  748. {
  749. auto ret = getAccesibility();
  750. for(auto hex : accessibleHexes)
  751. if(hex.isValid())
  752. ret[hex] = EAccessibility::ACCESSIBLE;
  753. return ret;
  754. }
  755. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  756. {
  757. ReachabilityInfo ret;
  758. ret.accessibility = accessibility;
  759. ret.params = params;
  760. ret.predecessors.fill(BattleHex::INVALID);
  761. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  762. if(!params.startPosition.isValid()) //if got call for arrow turrets
  763. return ret;
  764. const std::set<BattleHex> obstacles = getStoppers(params.perspective);
  765. std::queue<BattleHex> hexq; //bfs queue
  766. //first element
  767. hexq.push(params.startPosition);
  768. ret.distances[params.startPosition] = 0;
  769. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache{};
  770. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  771. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  772. while(!hexq.empty()) //bfs loop
  773. {
  774. const BattleHex curHex = hexq.front();
  775. hexq.pop();
  776. //walking stack can't step past the obstacles
  777. if(curHex != params.startPosition && isInObstacle(curHex, obstacles, params))
  778. continue;
  779. const int costToNeighbour = ret.distances[curHex.hex] + 1;
  780. for(BattleHex neighbour : BattleHex::neighbouringTilesCache[curHex.hex])
  781. {
  782. if(neighbour.isValid())
  783. {
  784. const int costFoundSoFar = ret.distances[neighbour.hex];
  785. if(accessibleCache[neighbour.hex] && costToNeighbour < costFoundSoFar)
  786. {
  787. hexq.push(neighbour);
  788. ret.distances[neighbour.hex] = costToNeighbour;
  789. ret.predecessors[neighbour.hex] = curHex;
  790. }
  791. }
  792. }
  793. }
  794. return ret;
  795. }
  796. bool CBattleInfoCallback::isInObstacle(
  797. BattleHex hex,
  798. const std::set<BattleHex> & obstacles,
  799. const ReachabilityInfo::Parameters & params) const
  800. {
  801. auto occupiedHexes = battle::Unit::getHexes(hex, params.doubleWide, params.side);
  802. for(auto occupiedHex : occupiedHexes)
  803. {
  804. if(vstd::contains(obstacles, occupiedHex))
  805. {
  806. if(occupiedHex == ESiegeHex::GATE_BRIDGE)
  807. {
  808. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  809. return true;
  810. }
  811. else
  812. return true;
  813. }
  814. }
  815. return false;
  816. }
  817. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  818. {
  819. std::set<BattleHex> ret;
  820. RETURN_IF_NOT_BATTLE(ret);
  821. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  822. {
  823. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  824. {
  825. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  826. }
  827. }
  828. return ret;
  829. }
  830. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  831. {
  832. auto reachability = getReachability(closest);
  833. auto avHexes = battleGetAvailableHexes(reachability, closest);
  834. // I hate std::pairs with their undescriptive member names first / second
  835. struct DistStack
  836. {
  837. uint32_t distanceToPred;
  838. BattleHex destination;
  839. const battle::Unit * stack;
  840. };
  841. std::vector<DistStack> stackPairs;
  842. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  843. {
  844. return unit->isValidTarget(false) && unit != closest;
  845. });
  846. for(const battle::Unit * st : possible)
  847. {
  848. for(BattleHex hex : avHexes)
  849. if(CStack::isMeleeAttackPossible(closest, st, hex))
  850. {
  851. DistStack hlp = {reachability.distances[hex], hex, st};
  852. stackPairs.push_back(hlp);
  853. }
  854. }
  855. if(!stackPairs.empty())
  856. {
  857. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  858. auto minimal = boost::min_element(stackPairs, comparator);
  859. return std::make_pair(minimal->stack, minimal->destination);
  860. }
  861. else
  862. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  863. }
  864. BattleHex CBattleInfoCallback::getAvaliableHex(const CreatureID & creID, ui8 side, int initialPos) const
  865. {
  866. bool twoHex = VLC->creh->objects[creID]->isDoubleWide();
  867. int pos;
  868. if (initialPos > -1)
  869. pos = initialPos;
  870. else //summon elementals depending on player side
  871. {
  872. if(side == BattleSide::ATTACKER)
  873. pos = 0; //top left
  874. else
  875. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  876. }
  877. auto accessibility = getAccesibility();
  878. std::set<BattleHex> occupyable;
  879. for(int i = 0; i < accessibility.size(); i++)
  880. if(accessibility.accessible(i, twoHex, side))
  881. occupyable.insert(i);
  882. if(occupyable.empty())
  883. {
  884. return BattleHex::INVALID; //all tiles are covered
  885. }
  886. return BattleHex::getClosestTile(side, pos, occupyable);
  887. }
  888. si8 CBattleInfoCallback::battleGetTacticDist() const
  889. {
  890. RETURN_IF_NOT_BATTLE(0);
  891. //TODO get rid of this method
  892. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  893. return battleTacticDist();
  894. return 0;
  895. }
  896. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  897. {
  898. RETURN_IF_NOT_BATTLE(false);
  899. auto side = battleGetTacticsSide();
  900. auto dist = battleGetTacticDist();
  901. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  902. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  903. }
  904. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  905. {
  906. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  907. if(!battleDoWeKnowAbout(unit->unitSide()))
  908. {
  909. //Stack is held by enemy, we can't use his perspective to check for reachability.
  910. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  911. params.perspective = battleGetMySide();
  912. }
  913. return getReachability(params);
  914. }
  915. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  916. {
  917. if(params.flying)
  918. return getFlyingReachability(params);
  919. else
  920. return makeBFS(getAccesibility(params.knownAccessible), params);
  921. }
  922. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  923. {
  924. ReachabilityInfo ret;
  925. ret.accessibility = getAccesibility(params.knownAccessible);
  926. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  927. {
  928. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  929. {
  930. ret.predecessors[i] = params.startPosition;
  931. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  932. }
  933. }
  934. return ret;
  935. }
  936. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const battle::Unit* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  937. {
  938. //does not return hex attacked directly
  939. AttackableTiles at;
  940. RETURN_IF_NOT_BATTLE(at);
  941. BattleHex attackOriginHex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  942. const auto * defender = battleGetUnitByPos(destinationTile, true);
  943. if (!defender)
  944. return at; // can't attack thin air
  945. bool reverse = isToReverse(attacker, defender);
  946. if(reverse && attacker->doubleWide())
  947. {
  948. attackOriginHex = attacker->occupiedHex(attackOriginHex); //the other hex stack stands on
  949. }
  950. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  951. {
  952. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  953. }
  954. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  955. {
  956. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  957. for(BattleHex tile : hexes)
  958. {
  959. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, attackOriginHex) > -1)) //adjacent both to attacker's head and attacked tile
  960. {
  961. const auto * st = battleGetUnitByPos(tile, true);
  962. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  963. at.hostileCreaturePositions.insert(tile);
  964. }
  965. }
  966. }
  967. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  968. {
  969. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  970. for(int i = 0; i<hexes.size(); i++)
  971. {
  972. if(hexes.at(i) == attackOriginHex)
  973. {
  974. hexes.erase(hexes.begin() + i);
  975. i = 0;
  976. }
  977. }
  978. for(BattleHex tile : hexes)
  979. {
  980. //friendly stacks can also be damaged by Dragon Breath
  981. const auto * st = battleGetUnitByPos(tile, true);
  982. if(st && st != attacker)
  983. at.friendlyCreaturePositions.insert(tile);
  984. }
  985. }
  986. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  987. {
  988. auto direction = BattleHex::mutualPosition(attackOriginHex, destinationTile);
  989. if(direction != BattleHex::NONE) //only adjacent hexes are subject of dragon breath calculation
  990. {
  991. BattleHex nextHex = destinationTile.cloneInDirection(direction, false);
  992. if ( defender->doubleWide() )
  993. {
  994. auto secondHex = destinationTile == defender->getPosition() ?
  995. defender->occupiedHex():
  996. defender->getPosition();
  997. // if targeted double-wide creature is attacked from above or below ( -> second hex is also adjacent to attack origin)
  998. // then dragon breath should target tile on the opposite side of targeted creature
  999. if (BattleHex::mutualPosition(attackOriginHex, secondHex) != BattleHex::NONE)
  1000. nextHex = secondHex.cloneInDirection(direction, false);
  1001. }
  1002. if (nextHex.isValid())
  1003. {
  1004. //friendly stacks can also be damaged by Dragon Breath
  1005. const auto * st = battleGetUnitByPos(nextHex, true);
  1006. if(st != nullptr)
  1007. at.friendlyCreaturePositions.insert(nextHex);
  1008. }
  1009. }
  1010. }
  1011. return at;
  1012. }
  1013. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1014. {
  1015. //does not return hex attacked directly
  1016. AttackableTiles at;
  1017. RETURN_IF_NOT_BATTLE(at);
  1018. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1019. {
  1020. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1021. targetHexes.push_back(destinationTile);
  1022. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1023. }
  1024. return at;
  1025. }
  1026. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(const battle::Unit* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1027. {
  1028. std::vector<const battle::Unit*> units;
  1029. RETURN_IF_NOT_BATTLE(units);
  1030. AttackableTiles at;
  1031. if (rangedAttack)
  1032. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1033. else
  1034. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1035. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1036. {
  1037. if (unit->isGhost() || !unit->alive())
  1038. return false;
  1039. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1040. {
  1041. if (vstd::contains(at.hostileCreaturePositions, hex))
  1042. return true;
  1043. if (vstd::contains(at.friendlyCreaturePositions, hex))
  1044. return true;
  1045. }
  1046. return false;
  1047. });
  1048. return units;
  1049. }
  1050. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1051. {
  1052. std::set<const CStack*> attackedCres;
  1053. RETURN_IF_NOT_BATTLE(attackedCres);
  1054. AttackableTiles at;
  1055. if(rangedAttack)
  1056. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1057. else
  1058. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1059. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1060. {
  1061. const CStack * st = battleGetStackByPos(tile, true);
  1062. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1063. {
  1064. attackedCres.insert(st);
  1065. }
  1066. }
  1067. for (BattleHex tile : at.friendlyCreaturePositions)
  1068. {
  1069. const CStack * st = battleGetStackByPos(tile, true);
  1070. if(st) //friendly stacks can also be damaged by Dragon Breath
  1071. {
  1072. attackedCres.insert(st);
  1073. }
  1074. }
  1075. return attackedCres;
  1076. }
  1077. static bool isHexInFront(BattleHex hex, BattleHex testHex, BattleSide::Type side )
  1078. {
  1079. static const std::set<BattleHex::EDir> rightDirs { BattleHex::BOTTOM_RIGHT, BattleHex::TOP_RIGHT, BattleHex::RIGHT };
  1080. static const std::set<BattleHex::EDir> leftDirs { BattleHex::BOTTOM_LEFT, BattleHex::TOP_LEFT, BattleHex::LEFT };
  1081. auto mutualPos = BattleHex::mutualPosition(hex, testHex);
  1082. if (side == BattleSide::ATTACKER)
  1083. return rightDirs.count(mutualPos);
  1084. else
  1085. return leftDirs.count(mutualPos);
  1086. }
  1087. //TODO: this should apply also to mechanics and cursor interface
  1088. bool CBattleInfoCallback::isToReverse(const battle::Unit * attacker, const battle::Unit * defender) const
  1089. {
  1090. BattleHex attackerHex = attacker->getPosition();
  1091. BattleHex defenderHex = defender->getPosition();
  1092. if (attackerHex < 0 ) //turret
  1093. return false;
  1094. if(isHexInFront(attackerHex, defenderHex, static_cast<BattleSide::Type>(attacker->unitSide())))
  1095. return false;
  1096. if (defender->doubleWide())
  1097. {
  1098. if(isHexInFront(attackerHex, defender->occupiedHex(), static_cast<BattleSide::Type>(attacker->unitSide())))
  1099. return false;
  1100. }
  1101. if (attacker->doubleWide())
  1102. {
  1103. if(isHexInFront(attacker->occupiedHex(), defenderHex, static_cast<BattleSide::Type>(attacker->unitSide())))
  1104. return false;
  1105. }
  1106. // a bit weird case since here defender is slightly behind attacker, so reversing seems preferable,
  1107. // but this is how H3 handles it which is important, e.g. for direction of dragon breath attacks
  1108. if (attacker->doubleWide() && defender->doubleWide())
  1109. {
  1110. if(isHexInFront(attacker->occupiedHex(), defender->occupiedHex(), static_cast<BattleSide::Type>(attacker->unitSide())))
  1111. return false;
  1112. }
  1113. return true;
  1114. }
  1115. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1116. {
  1117. ReachabilityInfo::TDistances ret;
  1118. ret.fill(-1);
  1119. RETURN_IF_NOT_BATTLE(ret);
  1120. auto reachability = getReachability(unit);
  1121. boost::copy(reachability.distances, ret.begin());
  1122. return ret;
  1123. }
  1124. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1125. {
  1126. RETURN_IF_NOT_BATTLE(false);
  1127. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1128. static const auto selectorNoDistancePenalty = Selector::type()(Bonus::NO_DISTANCE_PENALTY);
  1129. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1130. return false;
  1131. if(const auto * target = battleGetUnitByPos(destHex, true))
  1132. {
  1133. //If any hex of target creature is within range, there is no penalty
  1134. int range = GameConstants::BATTLE_PENALTY_DISTANCE;
  1135. auto bonus = shooter->getBonus(Selector::type()(Bonus::LIMITED_SHOOTING_RANGE));
  1136. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  1137. range = bonus->additionalInfo[0];
  1138. if(isEnemyUnitWithinSpecifiedRange(shooterPosition, target, range))
  1139. return false;
  1140. }
  1141. else
  1142. {
  1143. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1144. return false;
  1145. }
  1146. return true;
  1147. }
  1148. bool CBattleInfoCallback::isEnemyUnitWithinSpecifiedRange(BattleHex attackerPosition, const battle::Unit * defenderUnit, unsigned int range) const
  1149. {
  1150. for(auto hex : defenderUnit->getHexes())
  1151. if(BattleHex::getDistance(attackerPosition, hex) <= range)
  1152. return true;
  1153. return false;
  1154. }
  1155. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart part) const
  1156. {
  1157. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1158. return WallPartToHex(part);
  1159. }
  1160. EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1161. {
  1162. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1163. return hexToWallPart(hex);
  1164. }
  1165. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart wallPart) const
  1166. {
  1167. RETURN_IF_NOT_BATTLE(false);
  1168. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1169. wallPart != EWallPart::INVALID;
  1170. }
  1171. bool CBattleInfoCallback::isWallPartAttackable(EWallPart wallPart) const
  1172. {
  1173. RETURN_IF_NOT_BATTLE(false);
  1174. if(isWallPartPotentiallyAttackable(wallPart))
  1175. {
  1176. auto wallState = battleGetWallState(wallPart);
  1177. return (wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED);
  1178. }
  1179. return false;
  1180. }
  1181. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1182. {
  1183. std::vector<BattleHex> attackableBattleHexes;
  1184. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1185. for(const auto & wallPartPair : wallParts)
  1186. {
  1187. if(isWallPartAttackable(wallPartPair.second))
  1188. attackableBattleHexes.emplace_back(wallPartPair.first);
  1189. }
  1190. return attackableBattleHexes;
  1191. }
  1192. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1193. {
  1194. RETURN_IF_NOT_BATTLE(-1);
  1195. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1196. int32_t ret = caster->getSpellCost(sp);
  1197. //checking for friendly stacks reducing cost of the spell and
  1198. //enemy stacks increasing it
  1199. int32_t manaReduction = 0;
  1200. int32_t manaIncrease = 0;
  1201. for(const auto * unit : battleAliveUnits())
  1202. {
  1203. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1204. {
  1205. vstd::amax(manaReduction, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1206. }
  1207. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1208. {
  1209. vstd::amax(manaIncrease, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1210. }
  1211. }
  1212. return ret - manaReduction + manaIncrease;
  1213. }
  1214. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1215. {
  1216. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1217. }
  1218. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1219. {
  1220. RETURN_IF_NOT_BATTLE(false);
  1221. if(unit->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1222. return false;
  1223. for(const auto * adjacent : battleAdjacentUnits(unit))
  1224. {
  1225. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1226. return true;
  1227. }
  1228. return false;
  1229. }
  1230. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1231. {
  1232. std::set<const battle::Unit *> ret;
  1233. RETURN_IF_NOT_BATTLE(ret);
  1234. for(auto hex : unit->getSurroundingHexes())
  1235. {
  1236. if(const auto * neighbour = battleGetUnitByPos(hex, true))
  1237. ret.insert(neighbour);
  1238. }
  1239. return ret;
  1240. }
  1241. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1242. {
  1243. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1244. //This is complete list. No spells from mods.
  1245. //todo: this should be Spellbook of caster Stack
  1246. static const std::set<SpellID> allPossibleSpells =
  1247. {
  1248. SpellID::AIR_SHIELD,
  1249. SpellID::ANTI_MAGIC,
  1250. SpellID::BLESS,
  1251. SpellID::BLOODLUST,
  1252. SpellID::COUNTERSTRIKE,
  1253. SpellID::CURE,
  1254. SpellID::FIRE_SHIELD,
  1255. SpellID::FORTUNE,
  1256. SpellID::HASTE,
  1257. SpellID::MAGIC_MIRROR,
  1258. SpellID::MIRTH,
  1259. SpellID::PRAYER,
  1260. SpellID::PRECISION,
  1261. SpellID::PROTECTION_FROM_AIR,
  1262. SpellID::PROTECTION_FROM_EARTH,
  1263. SpellID::PROTECTION_FROM_FIRE,
  1264. SpellID::PROTECTION_FROM_WATER,
  1265. SpellID::SHIELD,
  1266. SpellID::SLAYER,
  1267. SpellID::STONE_SKIN
  1268. };
  1269. std::vector<SpellID> beneficialSpells;
  1270. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1271. {
  1272. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1273. {
  1274. return pred(stack) && stack->owner != subject->owner && stack->isValidTarget(false);
  1275. });
  1276. if(stacks.empty())
  1277. return nullptr;
  1278. else
  1279. return stacks.front();
  1280. };
  1281. for(const SpellID& spellID : allPossibleSpells)
  1282. {
  1283. std::stringstream cachingStr;
  1284. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1285. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1286. //TODO: this ability has special limitations
  1287. || !(spellID.toSpell()->canBeCast(this, spells::Mode::CREATURE_ACTIVE, subject)))
  1288. continue;
  1289. switch (spellID)
  1290. {
  1291. case SpellID::SHIELD:
  1292. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1293. {
  1294. const auto * walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1295. {
  1296. return !stack->canShoot();
  1297. });
  1298. if(!walker)
  1299. continue;
  1300. }
  1301. break;
  1302. case SpellID::AIR_SHIELD: //only against active shooters
  1303. {
  1304. const auto * shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1305. {
  1306. return stack->canShoot();
  1307. });
  1308. if(!shooter)
  1309. continue;
  1310. }
  1311. break;
  1312. case SpellID::ANTI_MAGIC:
  1313. case SpellID::MAGIC_MIRROR:
  1314. case SpellID::PROTECTION_FROM_AIR:
  1315. case SpellID::PROTECTION_FROM_EARTH:
  1316. case SpellID::PROTECTION_FROM_FIRE:
  1317. case SpellID::PROTECTION_FROM_WATER:
  1318. {
  1319. const ui8 enemySide = 1 - subject->side;
  1320. //todo: only if enemy has spellbook
  1321. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1322. continue;
  1323. }
  1324. break;
  1325. case SpellID::CURE: //only damaged units
  1326. {
  1327. //do not cast on affected by debuffs
  1328. if(!subject->canBeHealed())
  1329. continue;
  1330. }
  1331. break;
  1332. case SpellID::BLOODLUST:
  1333. {
  1334. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1335. continue;
  1336. }
  1337. break;
  1338. case SpellID::PRECISION:
  1339. {
  1340. if(!subject->canShoot())
  1341. continue;
  1342. }
  1343. break;
  1344. case SpellID::SLAYER://only if monsters are present
  1345. {
  1346. const auto * kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1347. {
  1348. const auto isKing = Selector::type()(Bonus::KING);
  1349. return stack->hasBonus(isKing);
  1350. });
  1351. if (!kingMonster)
  1352. continue;
  1353. }
  1354. break;
  1355. }
  1356. beneficialSpells.push_back(spellID);
  1357. }
  1358. if(!beneficialSpells.empty())
  1359. {
  1360. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1361. }
  1362. else
  1363. {
  1364. return SpellID::NONE;
  1365. }
  1366. }
  1367. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1368. {
  1369. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1370. TConstBonusListPtr bl = caster->getBonuses(Selector::type()(Bonus::SPELLCASTER));
  1371. if (!bl->size())
  1372. return SpellID::NONE;
  1373. int totalWeight = 0;
  1374. for(const auto & b : *bl)
  1375. {
  1376. totalWeight += std::max(b->additionalInfo[0], 1); //minimal chance to cast is 1
  1377. }
  1378. int randomPos = rand.nextInt(totalWeight - 1);
  1379. for(const auto & b : *bl)
  1380. {
  1381. randomPos -= std::max(b->additionalInfo[0], 1);
  1382. if(randomPos < 0)
  1383. {
  1384. return SpellID(b->subtype);
  1385. }
  1386. }
  1387. return SpellID::NONE;
  1388. }
  1389. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1390. {
  1391. RETURN_IF_NOT_BATTLE(-3);
  1392. if(!battleCanSurrender(Player))
  1393. return -1;
  1394. const auto sideOpt = playerToSide(Player);
  1395. if(!sideOpt)
  1396. return -1;
  1397. const auto side = sideOpt.get();
  1398. int ret = 0;
  1399. double discount = 0;
  1400. for(const auto * unit : battleAliveUnits(side))
  1401. ret += unit->getRawSurrenderCost();
  1402. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1403. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1404. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1405. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1406. return ret;
  1407. }
  1408. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1409. {
  1410. const IBonusBearer * node = nullptr;
  1411. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1412. node = h;
  1413. else
  1414. node = getBattleNode();
  1415. if(!node)
  1416. return 0;
  1417. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_BELOW));
  1418. if(b->size())
  1419. return b->totalValue();
  1420. return 0;
  1421. }
  1422. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1423. {
  1424. const IBonusBearer *node = nullptr;
  1425. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1426. node = h;
  1427. else
  1428. node = getBattleNode();
  1429. if(!node)
  1430. return GameConstants::SPELL_LEVELS;
  1431. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1432. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_ABOVE));
  1433. if(b->size())
  1434. return b->totalValue();
  1435. return GameConstants::SPELL_LEVELS;
  1436. }
  1437. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1438. {
  1439. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1440. {
  1441. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1442. });
  1443. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1444. for(auto & unit : units)
  1445. {
  1446. //todo: move SIEGE_WEAPON check to Unit state
  1447. hasUnit.at(unit->unitSide()) = true;
  1448. if(hasUnit[0] && hasUnit[1])
  1449. return boost::none;
  1450. }
  1451. hasUnit = {false, false};
  1452. for(auto & unit : units)
  1453. {
  1454. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1455. {
  1456. hasUnit.at(unit->unitSide()) = true;
  1457. }
  1458. }
  1459. if(!hasUnit[0] && !hasUnit[1])
  1460. return 2;
  1461. if(!hasUnit[1])
  1462. return 0;
  1463. else
  1464. return 1;
  1465. }
  1466. VCMI_LIB_NAMESPACE_END