CBattleInfoCallback.cpp 60 KB

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