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