CBattleInfoCallback.cpp 59 KB

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