CBattleInfoCallback.cpp 53 KB

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