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