CBattleInfoCallback.cpp 58 KB

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