CBattleInfoCallback.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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(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(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. 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. 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(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. //T is battle::Unit descendant
  299. template <typename T>
  300. const T * takeOneUnit(std::vector<const T*> & all, const int turn, int8_t & lastMoved, int phase)
  301. {
  302. const T * returnedUnit = nullptr;
  303. size_t currentUnitIndex = 0;
  304. for(size_t i = 0; i < all.size(); i++)
  305. {
  306. int32_t currentUnitSpeed = -1;
  307. int32_t returnedUnitSpeed = -1;
  308. if(returnedUnit)
  309. returnedUnitSpeed = returnedUnit->getInitiative(turn);
  310. if(all[i])
  311. {
  312. currentUnitSpeed = all[i]->getInitiative(turn);
  313. switch(phase)
  314. {
  315. case 1: // Faster first, attacker priority, higher slot first
  316. if(returnedUnit == nullptr || currentUnitSpeed > returnedUnitSpeed)
  317. {
  318. returnedUnit = all[i];
  319. currentUnitIndex = i;
  320. }
  321. else if(currentUnitSpeed == returnedUnitSpeed)
  322. {
  323. if(lastMoved == -1 && turn <= 0 && all[i]->unitSide() == BattleSide::ATTACKER
  324. && !(returnedUnit->unitSide() == all[i]->unitSide() && returnedUnit->unitSlot() < all[i]->unitSlot())) // Turn 0 attacker priority
  325. {
  326. returnedUnit = all[i];
  327. currentUnitIndex = i;
  328. }
  329. else if(lastMoved != -1 && all[i]->unitSide() != lastMoved
  330. && !(returnedUnit->unitSide() == all[i]->unitSide() && returnedUnit->unitSlot() < all[i]->unitSlot())) // Alternate equal speeds units
  331. {
  332. returnedUnit = all[i];
  333. currentUnitIndex = i;
  334. }
  335. }
  336. break;
  337. case 2: // Slower first, higher slot first
  338. case 3:
  339. if(returnedUnit == nullptr || currentUnitSpeed < returnedUnitSpeed)
  340. {
  341. returnedUnit = all[i];
  342. currentUnitIndex = i;
  343. }
  344. else if(currentUnitSpeed == returnedUnitSpeed && lastMoved != -1 && all[i]->unitSide() != lastMoved
  345. && !(returnedUnit->unitSide() == all[i]->unitSide() && returnedUnit->unitSlot() < all[i]->unitSlot())) // Alternate equal speeds units
  346. {
  347. returnedUnit = all[i];
  348. currentUnitIndex = i;
  349. }
  350. break;
  351. default:
  352. break;
  353. }
  354. }
  355. }
  356. if(!returnedUnit)
  357. return nullptr;
  358. all[currentUnitIndex] = nullptr;
  359. return returnedUnit;
  360. }
  361. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & out, const size_t maxUnits, const int maxTurns, const int turn, int8_t lastMoved) const
  362. {
  363. RETURN_IF_NOT_BATTLE();
  364. if(maxUnits == 0 && maxTurns == 0)
  365. {
  366. logGlobal->error("Attempt to get infinite battle queue");
  367. return;
  368. }
  369. auto actualTurn = turn > 0 ? turn : 0;
  370. auto outputFull = [&]() -> bool
  371. {
  372. if(maxUnits == 0)
  373. return false;//no limit
  374. size_t outSize = 0;
  375. for(const auto & oneTurn : out)
  376. outSize += oneTurn.size();
  377. return outSize >= maxUnits;
  378. };
  379. out.emplace_back();
  380. //We'll split creatures with remaining movement to 4 buckets
  381. // [0] - turrets/catapult,
  382. // [1] - normal (unmoved) creatures, other war machines,
  383. // [2] - waited cres that had morale,
  384. // [3] - rest of waited cres
  385. std::array<battle::Units, 4> phase;
  386. const battle::Unit * active = battleActiveUnit();
  387. if(active)
  388. {
  389. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  390. if(turn == 0 && active->willMove() && !active->waited())
  391. {
  392. out.back().push_back(active);
  393. if(outputFull())
  394. return;
  395. }
  396. //its first or current turn, turn priority for active stack side
  397. //TODO: what if active stack mind-controlled?
  398. if(turn <= 0 && lastMoved < 0)
  399. lastMoved = active->unitSide();
  400. }
  401. auto all = battleGetUnitsIf([](const battle::Unit * unit)
  402. {
  403. return !unit->isGhost();
  404. });
  405. if(!vstd::contains_if(all, [](const battle::Unit * unit) { return unit->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  406. {
  407. //No unit will be able to move, battle is over.
  408. out.clear();
  409. return;
  410. }
  411. for(auto one : all)
  412. {
  413. if((actualTurn == 0 && !one->willMove()) //we are considering current round and unit won't move
  414. || (actualTurn > 0 && !one->canMove(turn)) //unit won't be able to move in later rounds
  415. || (actualTurn == 0 && one == active && !out.at(0).empty() && one == out.front().front())) //it's active unit already added at the beginning of queue
  416. {
  417. continue;
  418. }
  419. int p = one->battleQueuePhase(turn);
  420. phase[p].push_back(one);
  421. }
  422. boost::sort(phase[0], CMP_stack(0, actualTurn, lastMoved));
  423. std::copy(phase[0].begin(), phase[0].end(), std::back_inserter(out.back()));
  424. if(outputFull())
  425. return;
  426. for(int i = 1; i < 4; i++)
  427. boost::sort(phase[i], CMP_stack(i, actualTurn, lastMoved));
  428. int pi = 1;
  429. while(!outputFull() && pi < 4)
  430. {
  431. const battle::Unit * current = nullptr;
  432. if(phase[pi].empty())
  433. pi++;
  434. else
  435. {
  436. current = takeOneUnit(phase[pi], actualTurn, lastMoved, pi);
  437. if(!current)
  438. {
  439. pi++;
  440. }
  441. else
  442. {
  443. out.back().push_back(current);
  444. lastMoved = current->unitSide();
  445. }
  446. }
  447. }
  448. if(lastMoved < 0)
  449. lastMoved = BattleSide::ATTACKER;
  450. if(!outputFull() && (maxTurns == 0 || out.size() < maxTurns))
  451. battleGetTurnOrder(out, maxUnits, maxTurns, actualTurn + 1, lastMoved);
  452. }
  453. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit) const
  454. {
  455. RETURN_IF_NOT_BATTLE(std::vector<BattleHex>());
  456. if(!unit->getPosition().isValid()) //turrets
  457. return std::vector<BattleHex>();
  458. auto reachability = getReachability(unit);
  459. return battleGetAvailableHexes(reachability, unit);
  460. }
  461. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit) const
  462. {
  463. std::vector<BattleHex> ret;
  464. RETURN_IF_NOT_BATTLE(ret);
  465. if(!unit->getPosition().isValid()) //turrets
  466. return ret;
  467. auto unitSpeed = unit->Speed(0, true);
  468. const bool tacticPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  469. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  470. {
  471. // If obstacles or other stacks makes movement impossible, it can't be helped.
  472. if(!cache.isReachable(i))
  473. continue;
  474. if(tacticPhase)
  475. {
  476. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  477. if(!isInTacticRange(i))
  478. continue;
  479. }
  480. else
  481. {
  482. //Not tactics phase -> destination must be reachable and within unit range.
  483. if(cache.distances[i] > (int)unitSpeed)
  484. continue;
  485. }
  486. ret.push_back(i);
  487. }
  488. return ret;
  489. }
  490. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool addOccupiable, std::vector<BattleHex> * attackable) const
  491. {
  492. std::vector<BattleHex> ret = battleGetAvailableHexes(unit);
  493. if(ret.empty())
  494. return ret;
  495. if(addOccupiable && unit->doubleWide())
  496. {
  497. std::vector<BattleHex> occupiable;
  498. for(auto hex : ret)
  499. occupiable.push_back(unit->occupiedHex(hex));
  500. vstd::concatenate(ret, occupiable);
  501. }
  502. if(attackable)
  503. {
  504. auto meleeAttackable = [&](BattleHex hex) -> bool
  505. {
  506. // Return true if given hex has at least one available neighbour.
  507. // Available hexes are already present in ret vector.
  508. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  509. {
  510. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  511. });
  512. return availableNeighbor != ret.end();
  513. };
  514. for(auto otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  515. {
  516. if(!otherSt->isValidTarget(false))
  517. continue;
  518. std::vector<BattleHex> occupied = otherSt->getHexes();
  519. if(battleCanShoot(unit, otherSt->getPosition()))
  520. {
  521. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  522. continue;
  523. }
  524. for(BattleHex he : occupied)
  525. {
  526. if(meleeAttackable(he))
  527. attackable->push_back(he);
  528. }
  529. }
  530. }
  531. //adding occupiable likely adds duplicates to ret -> clean it up
  532. boost::sort(ret);
  533. ret.erase(boost::unique(ret).end(), ret.end());
  534. return ret;
  535. }
  536. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  537. {
  538. RETURN_IF_NOT_BATTLE(false);
  539. if(battleTacticDist())
  540. return false;
  541. if (!stack || !target)
  542. return false;
  543. if(!battleMatchOwner(stack, target))
  544. return false;
  545. auto id = stack->getCreature()->getId();
  546. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  547. return false;
  548. return target->alive();
  549. }
  550. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  551. {
  552. RETURN_IF_NOT_BATTLE(false);
  553. if(battleTacticDist()) //no shooting during tactics
  554. return false;
  555. if (!attacker)
  556. return false;
  557. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  558. return false;
  559. //forgetfulness
  560. TConstBonusListPtr forgetfulList = attacker->getBonuses(Selector::type()(Bonus::FORGETFULL));
  561. if(!forgetfulList->empty())
  562. {
  563. int forgetful = forgetfulList->valOfBonuses(Selector::type()(Bonus::FORGETFULL));
  564. //advanced+ level
  565. if(forgetful > 1)
  566. return false;
  567. }
  568. return attacker->canShoot() && (!battleIsUnitBlocked(attacker)
  569. || attacker->hasBonusOfType(Bonus::FREE_SHOOTING));
  570. }
  571. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  572. {
  573. RETURN_IF_NOT_BATTLE(false);
  574. const battle::Unit * defender = battleGetUnitByPos(dest);
  575. if(!attacker || !defender)
  576. return false;
  577. if(battleMatchOwner(attacker, defender) && defender->alive())
  578. {
  579. if(battleCanShoot(attacker))
  580. {
  581. auto limitedRangeBonus = attacker->getBonus(Selector::type()(Bonus::LIMITED_SHOOTING_RANGE));
  582. if(limitedRangeBonus == nullptr)
  583. {
  584. return true;
  585. }
  586. int shootingRange = limitedRangeBonus->val;
  587. return isEnemyUnitWithinSpecifiedRange(attacker->getPosition(), defender, shootingRange);
  588. }
  589. }
  590. return false;
  591. }
  592. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  593. {
  594. DamageCalculator calculator(*this, info);
  595. return calculator.calculateDmgRange();
  596. }
  597. TDmgRange CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPosition, TDmgRange * retaliationDmg) const
  598. {
  599. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  600. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  601. int movementDistance = reachability[attackerPosition];
  602. return battleEstimateDamage(attacker, defender, movementDistance, retaliationDmg);
  603. }
  604. TDmgRange CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementDistance, TDmgRange * retaliationDmg) const
  605. {
  606. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  607. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  608. const BattleAttackInfo bai(attacker, defender, movementDistance, shooting);
  609. return battleEstimateDamage(bai, retaliationDmg);
  610. }
  611. TDmgRange CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, TDmgRange * retaliationDmg) const
  612. {
  613. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  614. TDmgRange ret = calculateDmgRange(bai);
  615. if(retaliationDmg)
  616. {
  617. if(bai.shooting)
  618. {
  619. //FIXME: handle RANGED_RETALIATION
  620. retaliationDmg->first = retaliationDmg->second = 0;
  621. }
  622. else
  623. {
  624. //TODO: rewrite using boost::numeric::interval
  625. //TODO: rewire once more using interval-based fuzzy arithmetic
  626. int64_t TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  627. for (int i=0; i<2; ++i)
  628. {
  629. auto retaliationAttack = bai.reverse();
  630. int64_t dmg = ret.*pairElems[i];
  631. auto state = retaliationAttack.attacker->acquireState();
  632. state->damage(dmg);
  633. retaliationAttack.attacker = state.get();
  634. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  635. }
  636. }
  637. }
  638. return ret;
  639. }
  640. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  641. {
  642. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  643. RETURN_IF_NOT_BATTLE(obstacles);
  644. for(auto & obs : battleGetAllObstacles())
  645. {
  646. if(vstd::contains(obs->getBlockedTiles(), tile)
  647. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  648. {
  649. obstacles.push_back(obs);
  650. }
  651. }
  652. return obstacles;
  653. }
  654. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit) const
  655. {
  656. std::vector<std::shared_ptr<const CObstacleInstance>> affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  657. RETURN_IF_NOT_BATTLE(affectedObstacles);
  658. if(unit->alive())
  659. {
  660. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  661. if(unit->doubleWide())
  662. {
  663. BattleHex otherHex = unit->occupiedHex(unit->getPosition());
  664. if(otherHex.isValid())
  665. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  666. affectedObstacles.push_back(i);
  667. }
  668. for(auto hex : unit->getHexes())
  669. if(hex == ESiegeHex::GATE_BRIDGE)
  670. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  671. for(int i=0; i<affectedObstacles.size(); i++)
  672. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  673. affectedObstacles.erase(affectedObstacles.begin()+i);
  674. }
  675. return affectedObstacles;
  676. }
  677. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  678. {
  679. AccessibilityInfo ret;
  680. ret.fill(EAccessibility::ACCESSIBLE);
  681. //removing accessibility for side columns of hexes
  682. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  683. {
  684. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  685. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  686. }
  687. //special battlefields with logically unavailable tiles
  688. auto bFieldType = battleGetBattlefieldType();
  689. if(bFieldType != BattleField::NONE)
  690. {
  691. std::vector<BattleHex> impassableHexes = bFieldType.getInfo()->impassableHexes;
  692. for(auto hex : impassableHexes)
  693. ret[hex] = EAccessibility::UNAVAILABLE;
  694. }
  695. //gate -> should be before stacks
  696. if(battleGetSiegeLevel() > 0)
  697. {
  698. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  699. switch(battleGetGateState())
  700. {
  701. case EGateState::CLOSED:
  702. accessability = EAccessibility::GATE;
  703. break;
  704. case EGateState::BLOCKED:
  705. accessability = EAccessibility::UNAVAILABLE;
  706. break;
  707. }
  708. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  709. }
  710. //tiles occupied by standing stacks
  711. for(auto unit : battleAliveUnits())
  712. {
  713. for(auto hex : unit->getHexes())
  714. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  715. ret[hex] = EAccessibility::ALIVE_STACK;
  716. }
  717. //obstacles
  718. for(const auto &obst : battleGetAllObstacles())
  719. {
  720. for(auto hex : obst->getBlockedTiles())
  721. ret[hex] = EAccessibility::OBSTACLE;
  722. }
  723. //walls
  724. if(battleGetSiegeLevel() > 0)
  725. {
  726. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  727. for(auto hex : permanentlyLocked)
  728. ret[hex] = EAccessibility::UNAVAILABLE;
  729. //TODO likely duplicated logic
  730. static const std::pair<EWallPart, BattleHex> lockedIfNotDestroyed[] =
  731. {
  732. //which part of wall, which hex is blocked if this part of wall is not destroyed
  733. std::make_pair(EWallPart::BOTTOM_WALL, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  734. std::make_pair(EWallPart::BELOW_GATE, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  735. std::make_pair(EWallPart::OVER_GATE, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  736. std::make_pair(EWallPart::UPPER_WALL, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  737. };
  738. for(auto & elem : lockedIfNotDestroyed)
  739. {
  740. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  741. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  742. }
  743. }
  744. return ret;
  745. }
  746. AccessibilityInfo CBattleInfoCallback::getAccesibility(const battle::Unit * stack) const
  747. {
  748. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  749. }
  750. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  751. {
  752. auto ret = getAccesibility();
  753. for(auto hex : accessibleHexes)
  754. if(hex.isValid())
  755. ret[hex] = EAccessibility::ACCESSIBLE;
  756. return ret;
  757. }
  758. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  759. {
  760. ReachabilityInfo ret;
  761. ret.accessibility = accessibility;
  762. ret.params = params;
  763. ret.predecessors.fill(BattleHex::INVALID);
  764. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  765. if(!params.startPosition.isValid()) //if got call for arrow turrets
  766. return ret;
  767. const std::set<BattleHex> obstacles = getStoppers(params.perspective);
  768. std::queue<BattleHex> hexq; //bfs queue
  769. //first element
  770. hexq.push(params.startPosition);
  771. ret.distances[params.startPosition] = 0;
  772. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache;
  773. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  774. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  775. while(!hexq.empty()) //bfs loop
  776. {
  777. const BattleHex curHex = hexq.front();
  778. hexq.pop();
  779. //walking stack can't step past the obstacles
  780. if(curHex != params.startPosition && isInObstacle(curHex, obstacles, params))
  781. continue;
  782. const int costToNeighbour = ret.distances[curHex.hex] + 1;
  783. for(BattleHex neighbour : BattleHex::neighbouringTilesCache[curHex.hex])
  784. {
  785. if(neighbour.isValid())
  786. {
  787. const int costFoundSoFar = ret.distances[neighbour.hex];
  788. if(accessibleCache[neighbour.hex] && costToNeighbour < costFoundSoFar)
  789. {
  790. hexq.push(neighbour);
  791. ret.distances[neighbour.hex] = costToNeighbour;
  792. ret.predecessors[neighbour.hex] = curHex;
  793. }
  794. }
  795. }
  796. }
  797. return ret;
  798. }
  799. bool CBattleInfoCallback::isInObstacle(
  800. BattleHex hex,
  801. const std::set<BattleHex> & obstacles,
  802. const ReachabilityInfo::Parameters & params) const
  803. {
  804. auto occupiedHexes = battle::Unit::getHexes(hex, params.doubleWide, params.side);
  805. for(auto occupiedHex : occupiedHexes)
  806. {
  807. if(vstd::contains(obstacles, occupiedHex))
  808. {
  809. if(occupiedHex == ESiegeHex::GATE_BRIDGE)
  810. {
  811. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  812. return true;
  813. }
  814. else
  815. return true;
  816. }
  817. }
  818. return false;
  819. }
  820. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  821. {
  822. std::set<BattleHex> ret;
  823. RETURN_IF_NOT_BATTLE(ret);
  824. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  825. {
  826. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  827. {
  828. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  829. }
  830. }
  831. return ret;
  832. }
  833. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  834. {
  835. auto reachability = getReachability(closest);
  836. auto avHexes = battleGetAvailableHexes(reachability, closest);
  837. // I hate std::pairs with their undescriptive member names first / second
  838. struct DistStack
  839. {
  840. uint32_t distanceToPred;
  841. BattleHex destination;
  842. const battle::Unit * stack;
  843. };
  844. std::vector<DistStack> stackPairs;
  845. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  846. {
  847. return unit->isValidTarget(false) && unit != closest;
  848. });
  849. for(const battle::Unit * st : possible)
  850. {
  851. for(BattleHex hex : avHexes)
  852. if(CStack::isMeleeAttackPossible(closest, st, hex))
  853. {
  854. DistStack hlp = {reachability.distances[hex], hex, st};
  855. stackPairs.push_back(hlp);
  856. }
  857. }
  858. if (stackPairs.size())
  859. {
  860. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  861. auto minimal = boost::min_element(stackPairs, comparator);
  862. return std::make_pair(minimal->stack, minimal->destination);
  863. }
  864. else
  865. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  866. }
  867. BattleHex CBattleInfoCallback::getAvaliableHex(CreatureID creID, ui8 side, int initialPos) const
  868. {
  869. bool twoHex = VLC->creh->objects[creID]->isDoubleWide();
  870. int pos;
  871. if (initialPos > -1)
  872. pos = initialPos;
  873. else //summon elementals depending on player side
  874. {
  875. if(side == BattleSide::ATTACKER)
  876. pos = 0; //top left
  877. else
  878. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  879. }
  880. auto accessibility = getAccesibility();
  881. std::set<BattleHex> occupyable;
  882. for(int i = 0; i < accessibility.size(); i++)
  883. if(accessibility.accessible(i, twoHex, side))
  884. occupyable.insert(i);
  885. if(occupyable.empty())
  886. {
  887. return BattleHex::INVALID; //all tiles are covered
  888. }
  889. return BattleHex::getClosestTile(side, pos, occupyable);
  890. }
  891. si8 CBattleInfoCallback::battleGetTacticDist() const
  892. {
  893. RETURN_IF_NOT_BATTLE(0);
  894. //TODO get rid of this method
  895. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  896. return battleTacticDist();
  897. return 0;
  898. }
  899. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  900. {
  901. RETURN_IF_NOT_BATTLE(false);
  902. auto side = battleGetTacticsSide();
  903. auto dist = battleGetTacticDist();
  904. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  905. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  906. }
  907. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  908. {
  909. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  910. if(!battleDoWeKnowAbout(unit->unitSide()))
  911. {
  912. //Stack is held by enemy, we can't use his perspective to check for reachability.
  913. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  914. params.perspective = battleGetMySide();
  915. }
  916. return getReachability(params);
  917. }
  918. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  919. {
  920. if(params.flying)
  921. return getFlyingReachability(params);
  922. else
  923. return makeBFS(getAccesibility(params.knownAccessible), params);
  924. }
  925. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  926. {
  927. ReachabilityInfo ret;
  928. ret.accessibility = getAccesibility(params.knownAccessible);
  929. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  930. {
  931. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  932. {
  933. ret.predecessors[i] = params.startPosition;
  934. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  935. }
  936. }
  937. return ret;
  938. }
  939. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const battle::Unit* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  940. {
  941. //does not return hex attacked directly
  942. AttackableTiles at;
  943. RETURN_IF_NOT_BATTLE(at);
  944. BattleHex attackOriginHex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  945. auto defender = battleGetUnitByPos(destinationTile, true);
  946. if (!defender)
  947. return at; // can't attack thin air
  948. bool reverse = isToReverse(attacker, defender);
  949. if(reverse && attacker->doubleWide())
  950. {
  951. attackOriginHex = attacker->occupiedHex(attackOriginHex); //the other hex stack stands on
  952. }
  953. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  954. {
  955. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  956. }
  957. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  958. {
  959. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  960. for(BattleHex tile : hexes)
  961. {
  962. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, attackOriginHex) > -1)) //adjacent both to attacker's head and attacked tile
  963. {
  964. auto st = battleGetUnitByPos(tile, true);
  965. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  966. at.hostileCreaturePositions.insert(tile);
  967. }
  968. }
  969. }
  970. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  971. {
  972. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  973. for(int i = 0; i<hexes.size(); i++)
  974. {
  975. if(hexes.at(i) == attackOriginHex)
  976. {
  977. hexes.erase(hexes.begin() + i);
  978. i = 0;
  979. }
  980. }
  981. for(BattleHex tile : hexes)
  982. {
  983. //friendly stacks can also be damaged by Dragon Breath
  984. auto st = battleGetUnitByPos(tile, true);
  985. if(st && st != attacker)
  986. at.friendlyCreaturePositions.insert(tile);
  987. }
  988. }
  989. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  990. {
  991. auto direction = BattleHex::mutualPosition(attackOriginHex, destinationTile);
  992. if(direction != BattleHex::NONE) //only adjacent hexes are subject of dragon breath calculation
  993. {
  994. BattleHex nextHex = destinationTile.cloneInDirection(direction, false);
  995. if ( defender->doubleWide() )
  996. {
  997. auto secondHex = destinationTile == defender->getPosition() ?
  998. defender->occupiedHex():
  999. defender->getPosition();
  1000. // if targeted double-wide creature is attacked from above or below ( -> second hex is also adjacent to attack origin)
  1001. // then dragon breath should target tile on the opposite side of targeted creature
  1002. if (BattleHex::mutualPosition(attackOriginHex, secondHex) != BattleHex::NONE)
  1003. nextHex = secondHex.cloneInDirection(direction, false);
  1004. }
  1005. if (nextHex.isValid())
  1006. {
  1007. //friendly stacks can also be damaged by Dragon Breath
  1008. auto st = battleGetUnitByPos(nextHex, true);
  1009. if(st != nullptr)
  1010. at.friendlyCreaturePositions.insert(nextHex);
  1011. }
  1012. }
  1013. }
  1014. return at;
  1015. }
  1016. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1017. {
  1018. //does not return hex attacked directly
  1019. AttackableTiles at;
  1020. RETURN_IF_NOT_BATTLE(at);
  1021. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1022. {
  1023. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1024. targetHexes.push_back(destinationTile);
  1025. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1026. }
  1027. return at;
  1028. }
  1029. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(const battle::Unit* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1030. {
  1031. std::vector<const battle::Unit*> units;
  1032. RETURN_IF_NOT_BATTLE(units);
  1033. AttackableTiles at;
  1034. if (rangedAttack)
  1035. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1036. else
  1037. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1038. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1039. {
  1040. if (unit->isGhost() || !unit->alive())
  1041. return false;
  1042. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1043. {
  1044. if (vstd::contains(at.hostileCreaturePositions, hex))
  1045. return true;
  1046. if (vstd::contains(at.friendlyCreaturePositions, hex))
  1047. return true;
  1048. }
  1049. return false;
  1050. });
  1051. return units;
  1052. }
  1053. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1054. {
  1055. std::set<const CStack*> attackedCres;
  1056. RETURN_IF_NOT_BATTLE(attackedCres);
  1057. AttackableTiles at;
  1058. if(rangedAttack)
  1059. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1060. else
  1061. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1062. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1063. {
  1064. const CStack * st = battleGetStackByPos(tile, true);
  1065. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1066. {
  1067. attackedCres.insert(st);
  1068. }
  1069. }
  1070. for (BattleHex tile : at.friendlyCreaturePositions)
  1071. {
  1072. const CStack * st = battleGetStackByPos(tile, true);
  1073. if(st) //friendly stacks can also be damaged by Dragon Breath
  1074. {
  1075. attackedCres.insert(st);
  1076. }
  1077. }
  1078. return attackedCres;
  1079. }
  1080. static bool isHexInFront(BattleHex hex, BattleHex testHex, BattleSide::Type side )
  1081. {
  1082. static const std::set<BattleHex::EDir> rightDirs { BattleHex::BOTTOM_RIGHT, BattleHex::TOP_RIGHT, BattleHex::RIGHT };
  1083. static const std::set<BattleHex::EDir> leftDirs { BattleHex::BOTTOM_LEFT, BattleHex::TOP_LEFT, BattleHex::LEFT };
  1084. auto mutualPos = BattleHex::mutualPosition(hex, testHex);
  1085. if (side == BattleSide::ATTACKER)
  1086. return rightDirs.count(mutualPos);
  1087. else
  1088. return leftDirs.count(mutualPos);
  1089. }
  1090. //TODO: this should apply also to mechanics and cursor interface
  1091. bool CBattleInfoCallback::isToReverse (const battle::Unit * attacker, const battle::Unit * defender) const
  1092. {
  1093. BattleHex attackerHex = attacker->getPosition();
  1094. BattleHex defenderHex = defender->getPosition();
  1095. if (attackerHex < 0 ) //turret
  1096. return false;
  1097. if (isHexInFront(attackerHex, defenderHex, BattleSide::Type(attacker->unitSide())))
  1098. return false;
  1099. if (defender->doubleWide())
  1100. {
  1101. if (isHexInFront(attackerHex,defender->occupiedHex(), BattleSide::Type(attacker->unitSide())))
  1102. return false;
  1103. }
  1104. if (attacker->doubleWide())
  1105. {
  1106. if (isHexInFront(attacker->occupiedHex(), defenderHex, BattleSide::Type(attacker->unitSide())))
  1107. return false;
  1108. }
  1109. // a bit weird case since here defender is slightly behind attacker, so reversing seems preferable,
  1110. // but this is how H3 handles it which is important, e.g. for direction of dragon breath attacks
  1111. if (attacker->doubleWide() && defender->doubleWide())
  1112. {
  1113. if (isHexInFront(attacker->occupiedHex(), defender->occupiedHex(), BattleSide::Type(attacker->unitSide())))
  1114. return false;
  1115. }
  1116. return true;
  1117. }
  1118. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1119. {
  1120. ReachabilityInfo::TDistances ret;
  1121. ret.fill(-1);
  1122. RETURN_IF_NOT_BATTLE(ret);
  1123. auto reachability = getReachability(unit);
  1124. boost::copy(reachability.distances, ret.begin());
  1125. return ret;
  1126. }
  1127. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1128. {
  1129. RETURN_IF_NOT_BATTLE(false);
  1130. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1131. static const auto selectorNoDistancePenalty = Selector::type()(Bonus::NO_DISTANCE_PENALTY);
  1132. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1133. return false;
  1134. if(auto target = battleGetUnitByPos(destHex, true))
  1135. {
  1136. //If any hex of target creature is within range, there is no penalty
  1137. int range = GameConstants::BATTLE_PENALTY_DISTANCE;
  1138. auto bonus = shooter->getBonus(Selector::type()(Bonus::LIMITED_SHOOTING_RANGE));
  1139. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  1140. range = bonus->additionalInfo[0];
  1141. if(isEnemyUnitWithinSpecifiedRange(shooterPosition, target, range))
  1142. return false;
  1143. }
  1144. else
  1145. {
  1146. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1147. return false;
  1148. }
  1149. return true;
  1150. }
  1151. bool CBattleInfoCallback::isEnemyUnitWithinSpecifiedRange(BattleHex attackerPosition, const battle::Unit * defenderUnit, unsigned int range) const
  1152. {
  1153. for(auto hex : defenderUnit->getHexes())
  1154. if(BattleHex::getDistance(attackerPosition, hex) <= range)
  1155. return true;
  1156. return false;
  1157. }
  1158. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart part) const
  1159. {
  1160. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1161. return WallPartToHex(part);
  1162. }
  1163. EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1164. {
  1165. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1166. return hexToWallPart(hex);
  1167. }
  1168. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart wallPart) const
  1169. {
  1170. RETURN_IF_NOT_BATTLE(false);
  1171. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1172. wallPart != EWallPart::INVALID;
  1173. }
  1174. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1175. {
  1176. std::vector<BattleHex> attackableBattleHexes;
  1177. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1178. for(auto & wallPartPair : wallParts)
  1179. {
  1180. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1181. {
  1182. auto wallState = battleGetWallState(wallPartPair.second);
  1183. if(wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1184. {
  1185. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1186. }
  1187. }
  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(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(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(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. 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. 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. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1346. {
  1347. const auto isKing = Selector::type()(Bonus::KING1)
  1348. .Or(Selector::type()(Bonus::KING2))
  1349. .Or(Selector::type()(Bonus::KING3));
  1350. return stack->hasBonus(isKing);
  1351. });
  1352. if (!kingMonster)
  1353. continue;
  1354. }
  1355. break;
  1356. }
  1357. beneficialSpells.push_back(spellID);
  1358. }
  1359. if(!beneficialSpells.empty())
  1360. {
  1361. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1362. }
  1363. else
  1364. {
  1365. return SpellID::NONE;
  1366. }
  1367. }
  1368. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1369. {
  1370. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1371. TConstBonusListPtr bl = caster->getBonuses(Selector::type()(Bonus::SPELLCASTER));
  1372. if (!bl->size())
  1373. return SpellID::NONE;
  1374. int totalWeight = 0;
  1375. for(auto b : *bl)
  1376. {
  1377. totalWeight += std::max(b->additionalInfo[0], 1); //minimal chance to cast is 1
  1378. }
  1379. int randomPos = rand.nextInt(totalWeight - 1);
  1380. for(auto b : *bl)
  1381. {
  1382. randomPos -= std::max(b->additionalInfo[0], 1);
  1383. if(randomPos < 0)
  1384. {
  1385. return SpellID(b->subtype);
  1386. }
  1387. }
  1388. return SpellID::NONE;
  1389. }
  1390. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1391. {
  1392. RETURN_IF_NOT_BATTLE(-3);
  1393. if(!battleCanSurrender(Player))
  1394. return -1;
  1395. const auto sideOpt = playerToSide(Player);
  1396. if(!sideOpt)
  1397. return -1;
  1398. const auto side = sideOpt.get();
  1399. int ret = 0;
  1400. double discount = 0;
  1401. for(auto unit : battleAliveUnits(side))
  1402. ret += unit->getRawSurrenderCost();
  1403. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1404. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1405. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1406. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1407. return ret;
  1408. }
  1409. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1410. {
  1411. const IBonusBearer * node = nullptr;
  1412. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1413. node = h;
  1414. else
  1415. node = getBattleNode();
  1416. if(!node)
  1417. return 0;
  1418. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_BELOW));
  1419. if(b->size())
  1420. return b->totalValue();
  1421. return 0;
  1422. }
  1423. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1424. {
  1425. const IBonusBearer *node = nullptr;
  1426. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1427. node = h;
  1428. else
  1429. node = getBattleNode();
  1430. if(!node)
  1431. return GameConstants::SPELL_LEVELS;
  1432. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1433. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_ABOVE));
  1434. if(b->size())
  1435. return b->totalValue();
  1436. return GameConstants::SPELL_LEVELS;
  1437. }
  1438. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1439. {
  1440. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1441. {
  1442. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1443. });
  1444. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1445. for(auto & unit : units)
  1446. {
  1447. //todo: move SIEGE_WEAPON check to Unit state
  1448. hasUnit.at(unit->unitSide()) = true;
  1449. if(hasUnit[0] && hasUnit[1])
  1450. return boost::none;
  1451. }
  1452. hasUnit = {false, false};
  1453. for(auto & unit : units)
  1454. {
  1455. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1456. {
  1457. hasUnit.at(unit->unitSide()) = true;
  1458. }
  1459. }
  1460. if(!hasUnit[0] && !hasUnit[1])
  1461. return 2;
  1462. if(!hasUnit[1])
  1463. return 0;
  1464. else
  1465. return 1;
  1466. }
  1467. VCMI_LIB_NAMESPACE_END