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