CBattleInfoCallback.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  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 "../CStack.h"
  14. #include "BattleInfo.h"
  15. #include "CObstacleInstance.h"
  16. #include "DamageCalculator.h"
  17. #include "PossiblePlayerBattleAction.h"
  18. #include "../NetPacks.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 "../BattleFieldHandler.h"
  25. #include "../Rect.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  28. {
  29. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  30. {
  31. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 96, 112, 130, 147, 165, 182};
  32. return lineToHex[line];
  33. }
  34. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  35. {
  36. const int wallInStackLine = lineToWallHex(pos1.getY());
  37. const int wallInDestLine = lineToWallHex(pos2.getY());
  38. const bool stackLeft = pos1 < wallInStackLine;
  39. const bool destLeft = pos2 < wallInDestLine;
  40. return stackLeft == destLeft;
  41. }
  42. // parts of wall
  43. static const std::pair<int, EWallPart> wallParts[] =
  44. {
  45. std::make_pair(50, EWallPart::KEEP),
  46. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  47. std::make_pair(182, EWallPart::BOTTOM_WALL),
  48. std::make_pair(130, EWallPart::BELOW_GATE),
  49. std::make_pair(78, EWallPart::OVER_GATE),
  50. std::make_pair(29, EWallPart::UPPER_WALL),
  51. std::make_pair(12, EWallPart::UPPER_TOWER),
  52. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  53. std::make_pair(96, EWallPart::GATE),
  54. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  55. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  56. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  57. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  58. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  59. };
  60. static EWallPart hexToWallPart(BattleHex hex)
  61. {
  62. for(const auto & elem : wallParts)
  63. {
  64. if(elem.first == hex)
  65. return elem.second;
  66. }
  67. return EWallPart::INVALID; //not found!
  68. }
  69. static BattleHex WallPartToHex(EWallPart part)
  70. {
  71. for(const auto & elem : wallParts)
  72. {
  73. if(elem.second == part)
  74. return elem.first;
  75. }
  76. return BattleHex::INVALID; //not found!
  77. }
  78. }
  79. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  80. ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  81. {
  82. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  83. if(caster == nullptr)
  84. {
  85. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  86. return ESpellCastProblem::INVALID;
  87. }
  88. const PlayerColor player = caster->getCasterOwner();
  89. const auto side = playerToSide(player);
  90. if(!side)
  91. return ESpellCastProblem::INVALID;
  92. if(!battleDoWeKnowAbout(side.value()))
  93. {
  94. logGlobal->warn("You can't check if enemy can cast given spell!");
  95. return ESpellCastProblem::INVALID;
  96. }
  97. if(battleTacticDist())
  98. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  99. switch(mode)
  100. {
  101. case spells::Mode::HERO:
  102. {
  103. if(battleCastSpells(side.value()) > 0)
  104. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  105. const auto * hero = dynamic_cast<const CGHeroInstance *>(caster);
  106. if(!hero)
  107. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  108. if(hero->hasBonusOfType(BonusType::BLOCK_ALL_MAGIC))
  109. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  110. }
  111. break;
  112. default:
  113. break;
  114. }
  115. return ESpellCastProblem::OK;
  116. }
  117. std::pair< std::vector<BattleHex>, int > CBattleInfoCallback::getPath(BattleHex start, BattleHex dest, const battle::Unit * stack) const
  118. {
  119. auto reachability = getReachability(stack);
  120. if(reachability.predecessors[dest] == -1) //cannot reach destination
  121. {
  122. return std::make_pair(std::vector<BattleHex>(), 0);
  123. }
  124. //making the Path
  125. std::vector<BattleHex> path;
  126. BattleHex curElem = dest;
  127. while(curElem != start)
  128. {
  129. path.push_back(curElem);
  130. curElem = reachability.predecessors[curElem];
  131. }
  132. return std::make_pair(path, reachability.distances[dest]);
  133. }
  134. bool CBattleInfoCallback::battleHasPenaltyOnLine(BattleHex from, BattleHex dest, bool checkWall, bool checkMoat) const
  135. {
  136. auto isTileBlocked = [&](BattleHex tile)
  137. {
  138. EWallPart wallPart = battleHexToWallPart(tile);
  139. if (wallPart == EWallPart::INVALID)
  140. return false; // there is no wall here
  141. if (wallPart == EWallPart::INDESTRUCTIBLE_PART_OF_GATE)
  142. return false; // does not blocks ranged attacks
  143. if (wallPart == EWallPart::INDESTRUCTIBLE_PART)
  144. return true; // always blocks ranged attacks
  145. return isWallPartAttackable(wallPart);
  146. };
  147. // Count wall penalty requirement by shortest path, not by arbitrary line, to avoid various OH3 bugs
  148. auto getShortestPath = [](BattleHex from, BattleHex dest) -> std::vector<BattleHex>
  149. {
  150. //Out early
  151. if(from == dest)
  152. return {};
  153. std::vector<BattleHex> ret;
  154. auto next = from;
  155. //Not a real direction, only to indicate to which side we should search closest tile
  156. auto direction = from.getX() > dest.getX() ? BattleSide::DEFENDER : BattleSide::ATTACKER;
  157. while (next != dest)
  158. {
  159. auto tiles = next.neighbouringTiles();
  160. std::set<BattleHex> possibilities = {tiles.begin(), tiles.end()};
  161. next = BattleHex::getClosestTile(direction, dest, possibilities);
  162. ret.push_back(next);
  163. }
  164. assert(!ret.empty());
  165. ret.pop_back(); //Remove destination hex
  166. return ret;
  167. };
  168. RETURN_IF_NOT_BATTLE(false);
  169. auto checkNeeded = !sameSideOfWall(from, dest);
  170. bool pathHasWall = false;
  171. bool pathHasMoat = false;
  172. for(const auto & hex : getShortestPath(from, dest))
  173. {
  174. pathHasWall |= isTileBlocked(hex);
  175. if(!checkMoat)
  176. continue;
  177. auto obstacles = battleGetAllObstaclesOnPos(hex, false);
  178. if(hex != BattleHex::GATE_BRIDGE || (battleIsGatePassable()))
  179. for(const auto & obst : obstacles)
  180. if(obst->obstacleType == CObstacleInstance::MOAT)
  181. pathHasMoat |= true;
  182. }
  183. return checkNeeded && ( (checkWall && pathHasWall) || (checkMoat && pathHasMoat) );
  184. }
  185. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  186. {
  187. RETURN_IF_NOT_BATTLE(false);
  188. if(!battleGetSiegeLevel())
  189. return false;
  190. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  191. static const auto selectorNoWallPenalty = Selector::type()(BonusType::NO_WALL_PENALTY);
  192. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  193. return false;
  194. const auto shooterOutsideWalls = shooterPosition < lineToWallHex(shooterPosition.getY());
  195. return shooterOutsideWalls && battleHasPenaltyOnLine(shooterPosition, destHex, true, false);
  196. }
  197. std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsForStack(const CStack * stack, const BattleClientInterfaceData & data)
  198. {
  199. RETURN_IF_NOT_BATTLE(std::vector<PossiblePlayerBattleAction>());
  200. std::vector<PossiblePlayerBattleAction> allowedActionList;
  201. if(data.tacticsMode) //would "if(battleGetTacticDist() > 0)" work?
  202. {
  203. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_TACTICS);
  204. allowedActionList.push_back(PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK);
  205. }
  206. else
  207. {
  208. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  209. {
  210. if(stack->hasBonusOfType(BonusType::SPELLCASTER))
  211. {
  212. for(const auto & spellID : data.creatureSpellsToCast)
  213. {
  214. const CSpell *spell = spellID.toSpell();
  215. PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
  216. allowedActionList.push_back(act);
  217. }
  218. }
  219. if(stack->hasBonusOfType(BonusType::RANDOM_SPELLCASTER))
  220. allowedActionList.push_back(PossiblePlayerBattleAction::RANDOM_GENIE_SPELL);
  221. }
  222. if(stack->canShoot())
  223. allowedActionList.push_back(PossiblePlayerBattleAction::SHOOT);
  224. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE))
  225. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK_AND_RETURN);
  226. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK); //all active stacks can attack
  227. allowedActionList.push_back(PossiblePlayerBattleAction::WALK_AND_ATTACK); //not all stacks can always walk, but we will check this elsewhere
  228. if(stack->canMove() && stack->speed(0, true)) //probably no reason to try move war machines or bound stacks
  229. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_STACK);
  230. const auto * siegedTown = battleGetDefendedTown();
  231. if(siegedTown && siegedTown->hasFort() && stack->hasBonusOfType(BonusType::CATAPULT)) //TODO: check shots
  232. allowedActionList.push_back(PossiblePlayerBattleAction::CATAPULT);
  233. if(stack->hasBonusOfType(BonusType::HEALER))
  234. allowedActionList.push_back(PossiblePlayerBattleAction::HEAL);
  235. }
  236. return allowedActionList;
  237. }
  238. PossiblePlayerBattleAction CBattleInfoCallback::getCasterAction(const CSpell * spell, const spells::Caster * caster, spells::Mode mode) const
  239. {
  240. RETURN_IF_NOT_BATTLE(PossiblePlayerBattleAction::INVALID);
  241. auto spellSelMode = PossiblePlayerBattleAction::ANY_LOCATION;
  242. const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell), mode);
  243. if(ti.massive || ti.type == spells::AimType::NO_TARGET)
  244. spellSelMode = PossiblePlayerBattleAction::NO_LOCATION;
  245. else if(ti.type == spells::AimType::LOCATION && ti.clearAffected)
  246. spellSelMode = PossiblePlayerBattleAction::FREE_LOCATION;
  247. else if(ti.type == spells::AimType::CREATURE)
  248. spellSelMode = PossiblePlayerBattleAction::AIMED_SPELL_CREATURE;
  249. else if(ti.type == spells::AimType::OBSTACLE)
  250. spellSelMode = PossiblePlayerBattleAction::OBSTACLE;
  251. return PossiblePlayerBattleAction(spellSelMode, spell->id);
  252. }
  253. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  254. {
  255. std::set<BattleHex> attackedHexes;
  256. RETURN_IF_NOT_BATTLE(attackedHexes);
  257. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  258. for (BattleHex tile : at.hostileCreaturePositions)
  259. {
  260. const auto * st = battleGetUnitByPos(tile, true);
  261. if(st && st->unitOwner() != attacker->unitOwner()) //only hostile stacks - does it work well with Berserk?
  262. {
  263. attackedHexes.insert(tile);
  264. }
  265. }
  266. for (BattleHex tile : at.friendlyCreaturePositions)
  267. {
  268. if(battleGetUnitByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  269. {
  270. attackedHexes.insert(tile);
  271. }
  272. }
  273. return attackedHexes;
  274. }
  275. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  276. {
  277. switch (mode)
  278. {
  279. case RANDOM_GENIE:
  280. return getRandomBeneficialSpell(rand, stack); //target
  281. break;
  282. case RANDOM_AIMED:
  283. return getRandomCastedSpell(rand, stack); //caster
  284. break;
  285. default:
  286. logGlobal->error("Incorrect mode of battleGetRandomSpell (%d)", static_cast<int>(mode));
  287. return SpellID::NONE;
  288. }
  289. }
  290. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  291. {
  292. RETURN_IF_NOT_BATTLE(nullptr);
  293. for(const auto * s : battleGetAllStacks(true))
  294. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  295. return s;
  296. return nullptr;
  297. }
  298. const battle::Unit * CBattleInfoCallback::battleGetUnitByPos(BattleHex pos, bool onlyAlive) const
  299. {
  300. RETURN_IF_NOT_BATTLE(nullptr);
  301. auto ret = battleGetUnitsIf([=](const battle::Unit * unit)
  302. {
  303. return !unit->isGhost()
  304. && vstd::contains(battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()), pos)
  305. && (!onlyAlive || unit->alive());
  306. });
  307. if(!ret.empty())
  308. return ret.front();
  309. else
  310. return nullptr;
  311. }
  312. battle::Units CBattleInfoCallback::battleAliveUnits() const
  313. {
  314. return battleGetUnitsIf([](const battle::Unit * unit)
  315. {
  316. return unit->isValidTarget(false);
  317. });
  318. }
  319. battle::Units CBattleInfoCallback::battleAliveUnits(ui8 side) const
  320. {
  321. return battleGetUnitsIf([=](const battle::Unit * unit)
  322. {
  323. return unit->isValidTarget(false) && unit->unitSide() == side;
  324. });
  325. }
  326. using namespace battle;
  327. //T is battle::Unit descendant
  328. template <typename T>
  329. const T * takeOneUnit(std::vector<const T*> & allUnits, const int turn, int8_t & sideThatLastMoved, int phase)
  330. {
  331. const T * returnedUnit = nullptr;
  332. size_t currentUnitIndex = 0;
  333. for(size_t i = 0; i < allUnits.size(); i++)
  334. {
  335. int32_t currentUnitInitiative = -1;
  336. int32_t returnedUnitInitiative = -1;
  337. if(returnedUnit)
  338. returnedUnitInitiative = returnedUnit->getInitiative(turn);
  339. if(!allUnits[i])
  340. continue;
  341. auto currentUnit = allUnits[i];
  342. currentUnitInitiative = currentUnit->getInitiative(turn);
  343. switch(phase)
  344. {
  345. case BattlePhases::NORMAL: // Faster first, attacker priority, higher slot first
  346. if(returnedUnit == nullptr || currentUnitInitiative > returnedUnitInitiative)
  347. {
  348. returnedUnit = currentUnit;
  349. currentUnitIndex = i;
  350. }
  351. else if(currentUnitInitiative == returnedUnitInitiative)
  352. {
  353. if(sideThatLastMoved == -1 && turn <= 0 && currentUnit->unitSide() == BattleSide::ATTACKER
  354. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Turn 0 attacker priority
  355. {
  356. returnedUnit = currentUnit;
  357. currentUnitIndex = i;
  358. }
  359. else if(sideThatLastMoved != -1 && currentUnit->unitSide() != sideThatLastMoved
  360. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  361. {
  362. returnedUnit = currentUnit;
  363. currentUnitIndex = i;
  364. }
  365. }
  366. break;
  367. case BattlePhases::WAIT_MORALE: // Slower first, higher slot first
  368. case BattlePhases::WAIT:
  369. if(returnedUnit == nullptr || currentUnitInitiative < returnedUnitInitiative)
  370. {
  371. returnedUnit = currentUnit;
  372. currentUnitIndex = i;
  373. }
  374. else if(currentUnitInitiative == returnedUnitInitiative && sideThatLastMoved != -1 && currentUnit->unitSide() != sideThatLastMoved
  375. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  376. {
  377. returnedUnit = currentUnit;
  378. currentUnitIndex = i;
  379. }
  380. break;
  381. default:
  382. break;
  383. }
  384. }
  385. if(!returnedUnit)
  386. return nullptr;
  387. allUnits[currentUnitIndex] = nullptr;
  388. return returnedUnit;
  389. }
  390. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & turns, const size_t maxUnits, const int maxTurns, const int turn, int8_t sideThatLastMoved) const
  391. {
  392. RETURN_IF_NOT_BATTLE();
  393. if(maxUnits == 0 && maxTurns == 0)
  394. {
  395. logGlobal->error("Attempt to get infinite battle queue");
  396. return;
  397. }
  398. auto actualTurn = turn > 0 ? turn : 0;
  399. auto turnsIsFull = [&]() -> bool
  400. {
  401. if(maxUnits == 0)
  402. return false;//no limit
  403. size_t turnsSize = 0;
  404. for(const auto & oneTurn : turns)
  405. turnsSize += oneTurn.size();
  406. return turnsSize >= maxUnits;
  407. };
  408. turns.emplace_back();
  409. // We'll split creatures with remaining movement to 4 buckets (SIEGE, NORMAL, WAIT_MORALE, WAIT)
  410. std::array<battle::Units, BattlePhases::NUMBER_OF_PHASES> phases; // Access using BattlePhases enum
  411. const battle::Unit * activeUnit = battleActiveUnit();
  412. if(activeUnit)
  413. {
  414. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  415. if(turn == 0 && activeUnit->willMove() && !activeUnit->waited())
  416. {
  417. turns.back().push_back(activeUnit);
  418. if(turnsIsFull())
  419. return;
  420. }
  421. //its first or current turn, turn priority for active stack side
  422. //TODO: what if active stack mind-controlled?
  423. if(turn <= 0 && sideThatLastMoved < 0)
  424. sideThatLastMoved = activeUnit->unitSide();
  425. }
  426. auto allUnits = battleGetUnitsIf([](const battle::Unit * unit)
  427. {
  428. return !unit->isGhost();
  429. });
  430. // If no unit will be EVER! able to move, battle is over.
  431. 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
  432. {
  433. turns.clear();
  434. return;
  435. }
  436. for(const auto * unit : allUnits)
  437. {
  438. if((actualTurn == 0 && !unit->willMove()) //we are considering current round and unit won't move
  439. || (actualTurn > 0 && !unit->canMove(turn)) //unit won't be able to move in later rounds
  440. || (actualTurn == 0 && unit == activeUnit && !turns.at(0).empty() && unit == turns.front().front())) //it's active unit already added at the beginning of queue
  441. {
  442. continue;
  443. }
  444. int unitPhase = unit->battleQueuePhase(turn);
  445. phases[unitPhase].push_back(unit);
  446. }
  447. boost::sort(phases[BattlePhases::SIEGE], CMP_stack(BattlePhases::SIEGE, actualTurn, sideThatLastMoved));
  448. std::copy(phases[BattlePhases::SIEGE].begin(), phases[BattlePhases::SIEGE].end(), std::back_inserter(turns.back()));
  449. if(turnsIsFull())
  450. return;
  451. for(uint8_t phase = BattlePhases::NORMAL; phase < BattlePhases::NUMBER_OF_PHASES; phase++)
  452. boost::sort(phases[phase], CMP_stack(phase, actualTurn, sideThatLastMoved));
  453. uint8_t phase = BattlePhases::NORMAL;
  454. while(!turnsIsFull() && phase < BattlePhases::NUMBER_OF_PHASES)
  455. {
  456. const battle::Unit * currentUnit = nullptr;
  457. if(phases[phase].empty())
  458. phase++;
  459. else
  460. {
  461. currentUnit = takeOneUnit(phases[phase], actualTurn, sideThatLastMoved, phase);
  462. if(!currentUnit)
  463. {
  464. phase++;
  465. }
  466. else
  467. {
  468. turns.back().push_back(currentUnit);
  469. sideThatLastMoved = currentUnit->unitSide();
  470. }
  471. }
  472. }
  473. if(sideThatLastMoved < 0)
  474. sideThatLastMoved = BattleSide::ATTACKER;
  475. if(!turnsIsFull() && (maxTurns == 0 || turns.size() < maxTurns))
  476. battleGetTurnOrder(turns, maxUnits, maxTurns, actualTurn + 1, sideThatLastMoved);
  477. }
  478. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange) const
  479. {
  480. RETURN_IF_NOT_BATTLE(std::vector<BattleHex>());
  481. if(!unit->getPosition().isValid()) //turrets
  482. return std::vector<BattleHex>();
  483. auto reachability = getReachability(unit);
  484. return battleGetAvailableHexes(reachability, unit, obtainMovementRange);
  485. }
  486. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit, bool obtainMovementRange) const
  487. {
  488. std::vector<BattleHex> ret;
  489. RETURN_IF_NOT_BATTLE(ret);
  490. if(!unit->getPosition().isValid()) //turrets
  491. return ret;
  492. auto unitSpeed = unit->speed(0, true);
  493. const bool tacticsPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  494. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  495. {
  496. // If obstacles or other stacks makes movement impossible, it can't be helped.
  497. if(!cache.isReachable(i))
  498. continue;
  499. if(tacticsPhase && !obtainMovementRange) // if obtainMovementRange requested do not return tactics range
  500. {
  501. // Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  502. if(!isInTacticRange(i))
  503. continue;
  504. }
  505. else
  506. {
  507. // Not tactics phase -> destination must be reachable and within unit range.
  508. if(cache.distances[i] > static_cast<int>(unitSpeed))
  509. continue;
  510. }
  511. ret.emplace_back(i);
  512. }
  513. return ret;
  514. }
  515. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange, bool addOccupiable, std::vector<BattleHex> * attackable) const
  516. {
  517. std::vector<BattleHex> ret = battleGetAvailableHexes(unit, obtainMovementRange);
  518. if(ret.empty())
  519. return ret;
  520. if(addOccupiable && unit->doubleWide())
  521. {
  522. std::vector<BattleHex> occupiable;
  523. occupiable.reserve(ret.size());
  524. for(auto hex : ret)
  525. occupiable.push_back(unit->occupiedHex(hex));
  526. vstd::concatenate(ret, occupiable);
  527. }
  528. if(attackable)
  529. {
  530. auto meleeAttackable = [&](BattleHex hex) -> bool
  531. {
  532. // Return true if given hex has at least one available neighbour.
  533. // Available hexes are already present in ret vector.
  534. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  535. {
  536. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  537. });
  538. return availableNeighbor != ret.end();
  539. };
  540. for(const auto * otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  541. {
  542. if(!otherSt->isValidTarget(false))
  543. continue;
  544. std::vector<BattleHex> occupied = otherSt->getHexes();
  545. if(battleCanShoot(unit, otherSt->getPosition()))
  546. {
  547. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  548. continue;
  549. }
  550. for(BattleHex he : occupied)
  551. {
  552. if(meleeAttackable(he))
  553. attackable->push_back(he);
  554. }
  555. }
  556. }
  557. //adding occupiable likely adds duplicates to ret -> clean it up
  558. boost::sort(ret);
  559. ret.erase(boost::unique(ret).end(), ret.end());
  560. return ret;
  561. }
  562. bool CBattleInfoCallback::battleCanAttack(const battle::Unit * stack, const battle::Unit * target, BattleHex dest) const
  563. {
  564. RETURN_IF_NOT_BATTLE(false);
  565. if(battleTacticDist())
  566. return false;
  567. if (!stack || !target)
  568. return false;
  569. if(!battleMatchOwner(stack, target))
  570. return false;
  571. auto id = stack->unitType()->getId();
  572. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  573. return false;
  574. return target->alive();
  575. }
  576. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  577. {
  578. RETURN_IF_NOT_BATTLE(false);
  579. if(battleTacticDist()) //no shooting during tactics
  580. return false;
  581. if (!attacker)
  582. return false;
  583. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  584. return false;
  585. //forgetfulness
  586. TConstBonusListPtr forgetfulList = attacker->getBonuses(Selector::type()(BonusType::FORGETFULL));
  587. if(!forgetfulList->empty())
  588. {
  589. int forgetful = forgetfulList->valOfBonuses(Selector::type()(BonusType::FORGETFULL));
  590. //advanced+ level
  591. if(forgetful > 1)
  592. return false;
  593. }
  594. return attacker->canShoot() && (!battleIsUnitBlocked(attacker)
  595. || attacker->hasBonusOfType(BonusType::FREE_SHOOTING));
  596. }
  597. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  598. {
  599. RETURN_IF_NOT_BATTLE(false);
  600. const battle::Unit * defender = battleGetUnitByPos(dest);
  601. if(!attacker || !defender)
  602. return false;
  603. if(battleMatchOwner(attacker, defender) && defender->alive())
  604. {
  605. if(battleCanShoot(attacker))
  606. {
  607. auto limitedRangeBonus = attacker->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  608. if(limitedRangeBonus == nullptr)
  609. {
  610. return true;
  611. }
  612. int shootingRange = limitedRangeBonus->val;
  613. return isEnemyUnitWithinSpecifiedRange(attacker->getPosition(), defender, shootingRange);
  614. }
  615. }
  616. return false;
  617. }
  618. DamageEstimation CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  619. {
  620. DamageCalculator calculator(*this, info);
  621. return calculator.calculateDmgRange();
  622. }
  623. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPosition, DamageEstimation * retaliationDmg) const
  624. {
  625. RETURN_IF_NOT_BATTLE({});
  626. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  627. int movementDistance = reachability[attackerPosition];
  628. return battleEstimateDamage(attacker, defender, movementDistance, retaliationDmg);
  629. }
  630. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementDistance, DamageEstimation * retaliationDmg) const
  631. {
  632. RETURN_IF_NOT_BATTLE({});
  633. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  634. const BattleAttackInfo bai(attacker, defender, movementDistance, shooting);
  635. return battleEstimateDamage(bai, retaliationDmg);
  636. }
  637. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, DamageEstimation * retaliationDmg) const
  638. {
  639. RETURN_IF_NOT_BATTLE({});
  640. DamageEstimation ret = calculateDmgRange(bai);
  641. if(retaliationDmg)
  642. {
  643. if(bai.shooting)
  644. {
  645. //FIXME: handle RANGED_RETALIATION
  646. *retaliationDmg = DamageEstimation();
  647. }
  648. else
  649. {
  650. //TODO: rewrite using boost::numeric::interval
  651. //TODO: rewire once more using interval-based fuzzy arithmetic
  652. const auto & estimateRetaliation = [&](int64_t damage)
  653. {
  654. auto retaliationAttack = bai.reverse();
  655. auto state = retaliationAttack.attacker->acquireState();
  656. state->damage(damage);
  657. retaliationAttack.attacker = state.get();
  658. return calculateDmgRange(retaliationAttack);
  659. };
  660. DamageEstimation retaliationMin = estimateRetaliation(ret.damage.min);
  661. DamageEstimation retaliationMax = estimateRetaliation(ret.damage.min);
  662. retaliationDmg->damage.min = std::min(retaliationMin.damage.min, retaliationMax.damage.min);
  663. retaliationDmg->damage.max = std::max(retaliationMin.damage.max, retaliationMax.damage.max);
  664. retaliationDmg->kills.min = std::min(retaliationMin.kills.min, retaliationMax.kills.min);
  665. retaliationDmg->kills.max = std::max(retaliationMin.kills.max, retaliationMax.kills.max);
  666. }
  667. }
  668. return ret;
  669. }
  670. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  671. {
  672. std::vector<std::shared_ptr<const CObstacleInstance>> 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, (BattlePerspective::BattlePerspective)side);
  736. const auto * hero = battleGetFightingHero(spellObstacle->casterSide);
  737. auto caster = spells::ObstacleCasterProxy(getBattle()->getSidePlayer(spellObstacle->casterSide), hero, *spellObstacle);
  738. const auto * sp = obstacle->getTrigger().toSpell();
  739. if(obstacle->triggersEffects() && sp)
  740. {
  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::getAccesibility() 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 accessability = EAccessibility::ACCESSIBLE;
  784. switch(battleGetGateState())
  785. {
  786. case EGateState::CLOSED:
  787. accessability = EAccessibility::GATE;
  788. break;
  789. case EGateState::BLOCKED:
  790. accessability = EAccessibility::UNAVAILABLE;
  791. break;
  792. }
  793. ret[BattleHex::GATE_OUTER] = ret[BattleHex::GATE_INNER] = accessability;
  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::getAccesibility(const battle::Unit * stack) const
  832. {
  833. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  834. }
  835. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  836. {
  837. auto ret = getAccesibility();
  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(BattlePerspective::BattlePerspective 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::getAvaliableHex(const CreatureID & creID, ui8 side, int initialPos) const
  964. {
  965. bool twoHex = VLC->creh->objects[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 = getAccesibility();
  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. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  1001. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  1002. }
  1003. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  1004. {
  1005. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  1006. if(!battleDoWeKnowAbout(unit->unitSide()))
  1007. {
  1008. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1009. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1010. params.perspective = battleGetMySide();
  1011. }
  1012. return getReachability(params);
  1013. }
  1014. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1015. {
  1016. if(params.flying)
  1017. return getFlyingReachability(params);
  1018. else
  1019. return makeBFS(getAccesibility(params.knownAccessible), params);
  1020. }
  1021. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  1022. {
  1023. ReachabilityInfo ret;
  1024. ret.accessibility = getAccesibility(params.knownAccessible);
  1025. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1026. {
  1027. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  1028. {
  1029. ret.predecessors[i] = params.startPosition;
  1030. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1031. }
  1032. }
  1033. return ret;
  1034. }
  1035. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes(const battle::Unit* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1036. {
  1037. //does not return hex attacked directly
  1038. AttackableTiles at;
  1039. RETURN_IF_NOT_BATTLE(at);
  1040. BattleHex attackOriginHex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1041. const auto * defender = battleGetUnitByPos(destinationTile, true);
  1042. if (!defender)
  1043. return at; // can't attack thin air
  1044. bool reverse = isToReverse(attacker, defender);
  1045. if(reverse && attacker->doubleWide())
  1046. {
  1047. attackOriginHex = attacker->occupiedHex(attackOriginHex); //the other hex stack stands on
  1048. }
  1049. if(attacker->hasBonusOfType(BonusType::ATTACKS_ALL_ADJACENT))
  1050. {
  1051. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  1052. }
  1053. if(attacker->hasBonusOfType(BonusType::THREE_HEADED_ATTACK))
  1054. {
  1055. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1056. for(BattleHex tile : hexes)
  1057. {
  1058. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, attackOriginHex) > -1)) //adjacent both to attacker's head and attacked tile
  1059. {
  1060. const auto * st = battleGetUnitByPos(tile, true);
  1061. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  1062. at.hostileCreaturePositions.insert(tile);
  1063. }
  1064. }
  1065. }
  1066. if(attacker->hasBonusOfType(BonusType::WIDE_BREATH))
  1067. {
  1068. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  1069. for(int i = 0; i<hexes.size(); i++)
  1070. {
  1071. if(hexes.at(i) == attackOriginHex)
  1072. {
  1073. hexes.erase(hexes.begin() + i);
  1074. i = 0;
  1075. }
  1076. }
  1077. for(BattleHex tile : hexes)
  1078. {
  1079. //friendly stacks can also be damaged by Dragon Breath
  1080. const auto * st = battleGetUnitByPos(tile, true);
  1081. if(st && st != attacker)
  1082. at.friendlyCreaturePositions.insert(tile);
  1083. }
  1084. }
  1085. else if(attacker->hasBonusOfType(BonusType::TWO_HEX_ATTACK_BREATH))
  1086. {
  1087. auto direction = BattleHex::mutualPosition(attackOriginHex, destinationTile);
  1088. if(direction != BattleHex::NONE) //only adjacent hexes are subject of dragon breath calculation
  1089. {
  1090. BattleHex nextHex = destinationTile.cloneInDirection(direction, false);
  1091. if ( defender->doubleWide() )
  1092. {
  1093. auto secondHex = destinationTile == defender->getPosition() ?
  1094. defender->occupiedHex():
  1095. defender->getPosition();
  1096. // if targeted double-wide creature is attacked from above or below ( -> second hex is also adjacent to attack origin)
  1097. // then dragon breath should target tile on the opposite side of targeted creature
  1098. if (BattleHex::mutualPosition(attackOriginHex, secondHex) != BattleHex::NONE)
  1099. nextHex = secondHex.cloneInDirection(direction, false);
  1100. }
  1101. if (nextHex.isValid())
  1102. {
  1103. //friendly stacks can also be damaged by Dragon Breath
  1104. const auto * st = battleGetUnitByPos(nextHex, true);
  1105. if(st != nullptr)
  1106. at.friendlyCreaturePositions.insert(nextHex);
  1107. }
  1108. }
  1109. }
  1110. return at;
  1111. }
  1112. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1113. {
  1114. //does not return hex attacked directly
  1115. AttackableTiles at;
  1116. RETURN_IF_NOT_BATTLE(at);
  1117. if(attacker->hasBonusOfType(BonusType::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1118. {
  1119. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1120. targetHexes.push_back(destinationTile);
  1121. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1122. }
  1123. return at;
  1124. }
  1125. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(const battle::Unit* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1126. {
  1127. std::vector<const battle::Unit*> units;
  1128. RETURN_IF_NOT_BATTLE(units);
  1129. AttackableTiles at;
  1130. if (rangedAttack)
  1131. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1132. else
  1133. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1134. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1135. {
  1136. if (unit->isGhost() || !unit->alive())
  1137. return false;
  1138. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1139. {
  1140. if (vstd::contains(at.hostileCreaturePositions, hex))
  1141. return true;
  1142. if (vstd::contains(at.friendlyCreaturePositions, hex))
  1143. return true;
  1144. }
  1145. return false;
  1146. });
  1147. return units;
  1148. }
  1149. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1150. {
  1151. std::set<const CStack*> attackedCres;
  1152. RETURN_IF_NOT_BATTLE(attackedCres);
  1153. AttackableTiles at;
  1154. if(rangedAttack)
  1155. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1156. else
  1157. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1158. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1159. {
  1160. const CStack * st = battleGetStackByPos(tile, true);
  1161. if(st && st->unitOwner() != attacker->unitOwner()) //only hostile stacks - does it work well with Berserk?
  1162. {
  1163. attackedCres.insert(st);
  1164. }
  1165. }
  1166. for (BattleHex tile : at.friendlyCreaturePositions)
  1167. {
  1168. const CStack * st = battleGetStackByPos(tile, true);
  1169. if(st) //friendly stacks can also be damaged by Dragon Breath
  1170. {
  1171. attackedCres.insert(st);
  1172. }
  1173. }
  1174. return attackedCres;
  1175. }
  1176. static bool isHexInFront(BattleHex hex, BattleHex testHex, BattleSide::Type side )
  1177. {
  1178. static const std::set<BattleHex::EDir> rightDirs { BattleHex::BOTTOM_RIGHT, BattleHex::TOP_RIGHT, BattleHex::RIGHT };
  1179. static const std::set<BattleHex::EDir> leftDirs { BattleHex::BOTTOM_LEFT, BattleHex::TOP_LEFT, BattleHex::LEFT };
  1180. auto mutualPos = BattleHex::mutualPosition(hex, testHex);
  1181. if (side == BattleSide::ATTACKER)
  1182. return rightDirs.count(mutualPos);
  1183. else
  1184. return leftDirs.count(mutualPos);
  1185. }
  1186. //TODO: this should apply also to mechanics and cursor interface
  1187. bool CBattleInfoCallback::isToReverse(const battle::Unit * attacker, const battle::Unit * defender) const
  1188. {
  1189. BattleHex attackerHex = attacker->getPosition();
  1190. BattleHex defenderHex = defender->getPosition();
  1191. if (attackerHex < 0 ) //turret
  1192. return false;
  1193. if(isHexInFront(attackerHex, defenderHex, static_cast<BattleSide::Type>(attacker->unitSide())))
  1194. return false;
  1195. if (defender->doubleWide())
  1196. {
  1197. if(isHexInFront(attackerHex, defender->occupiedHex(), static_cast<BattleSide::Type>(attacker->unitSide())))
  1198. return false;
  1199. }
  1200. if (attacker->doubleWide())
  1201. {
  1202. if(isHexInFront(attacker->occupiedHex(), defenderHex, static_cast<BattleSide::Type>(attacker->unitSide())))
  1203. return false;
  1204. }
  1205. // a bit weird case since here defender is slightly behind attacker, so reversing seems preferable,
  1206. // but this is how H3 handles it which is important, e.g. for direction of dragon breath attacks
  1207. if (attacker->doubleWide() && defender->doubleWide())
  1208. {
  1209. if(isHexInFront(attacker->occupiedHex(), defender->occupiedHex(), static_cast<BattleSide::Type>(attacker->unitSide())))
  1210. return false;
  1211. }
  1212. return true;
  1213. }
  1214. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1215. {
  1216. ReachabilityInfo::TDistances ret;
  1217. ret.fill(-1);
  1218. RETURN_IF_NOT_BATTLE(ret);
  1219. auto reachability = getReachability(unit);
  1220. boost::copy(reachability.distances, ret.begin());
  1221. return ret;
  1222. }
  1223. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1224. {
  1225. RETURN_IF_NOT_BATTLE(false);
  1226. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1227. static const auto selectorNoDistancePenalty = Selector::type()(BonusType::NO_DISTANCE_PENALTY);
  1228. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1229. return false;
  1230. if(const auto * target = battleGetUnitByPos(destHex, true))
  1231. {
  1232. //If any hex of target creature is within range, there is no penalty
  1233. int range = GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE;
  1234. auto bonus = shooter->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  1235. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  1236. range = bonus->additionalInfo[0];
  1237. if(isEnemyUnitWithinSpecifiedRange(shooterPosition, target, range))
  1238. return false;
  1239. }
  1240. else
  1241. {
  1242. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE)
  1243. return false;
  1244. }
  1245. return true;
  1246. }
  1247. bool CBattleInfoCallback::isEnemyUnitWithinSpecifiedRange(BattleHex attackerPosition, const battle::Unit * defenderUnit, unsigned int range) const
  1248. {
  1249. for(auto hex : defenderUnit->getHexes())
  1250. if(BattleHex::getDistance(attackerPosition, hex) <= range)
  1251. return true;
  1252. return false;
  1253. }
  1254. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart part) const
  1255. {
  1256. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1257. return WallPartToHex(part);
  1258. }
  1259. EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1260. {
  1261. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1262. return hexToWallPart(hex);
  1263. }
  1264. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart wallPart) const
  1265. {
  1266. RETURN_IF_NOT_BATTLE(false);
  1267. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1268. wallPart != EWallPart::INVALID;
  1269. }
  1270. bool CBattleInfoCallback::isWallPartAttackable(EWallPart wallPart) const
  1271. {
  1272. RETURN_IF_NOT_BATTLE(false);
  1273. if(isWallPartPotentiallyAttackable(wallPart))
  1274. {
  1275. auto wallState = battleGetWallState(wallPart);
  1276. return (wallState == EWallState::REINFORCED || wallState == EWallState::INTACT || wallState == EWallState::DAMAGED);
  1277. }
  1278. return false;
  1279. }
  1280. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1281. {
  1282. std::vector<BattleHex> attackableBattleHexes;
  1283. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1284. for(const auto & wallPartPair : wallParts)
  1285. {
  1286. if(isWallPartAttackable(wallPartPair.second))
  1287. attackableBattleHexes.emplace_back(wallPartPair.first);
  1288. }
  1289. return attackableBattleHexes;
  1290. }
  1291. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1292. {
  1293. RETURN_IF_NOT_BATTLE(-1);
  1294. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1295. int32_t ret = caster->getSpellCost(sp);
  1296. //checking for friendly stacks reducing cost of the spell and
  1297. //enemy stacks increasing it
  1298. int32_t manaReduction = 0;
  1299. int32_t manaIncrease = 0;
  1300. for(const auto * unit : battleAliveUnits())
  1301. {
  1302. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(BonusType::CHANGES_SPELL_COST_FOR_ALLY))
  1303. {
  1304. vstd::amax(manaReduction, unit->valOfBonuses(BonusType::CHANGES_SPELL_COST_FOR_ALLY));
  1305. }
  1306. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(BonusType::CHANGES_SPELL_COST_FOR_ENEMY))
  1307. {
  1308. vstd::amax(manaIncrease, unit->valOfBonuses(BonusType::CHANGES_SPELL_COST_FOR_ENEMY));
  1309. }
  1310. }
  1311. return std::max(0, ret - manaReduction + manaIncrease);
  1312. }
  1313. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1314. {
  1315. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1316. }
  1317. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1318. {
  1319. RETURN_IF_NOT_BATTLE(false);
  1320. if(unit->hasBonusOfType(BonusType::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1321. return false;
  1322. for(const auto * adjacent : battleAdjacentUnits(unit))
  1323. {
  1324. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1325. return true;
  1326. }
  1327. return false;
  1328. }
  1329. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1330. {
  1331. std::set<const battle::Unit *> ret;
  1332. RETURN_IF_NOT_BATTLE(ret);
  1333. for(auto hex : unit->getSurroundingHexes())
  1334. {
  1335. if(const auto * neighbour = battleGetUnitByPos(hex, true))
  1336. ret.insert(neighbour);
  1337. }
  1338. return ret;
  1339. }
  1340. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1341. {
  1342. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1343. //This is complete list. No spells from mods.
  1344. //todo: this should be Spellbook of caster Stack
  1345. static const std::set<SpellID> allPossibleSpells =
  1346. {
  1347. SpellID::AIR_SHIELD,
  1348. SpellID::ANTI_MAGIC,
  1349. SpellID::BLESS,
  1350. SpellID::BLOODLUST,
  1351. SpellID::COUNTERSTRIKE,
  1352. SpellID::CURE,
  1353. SpellID::FIRE_SHIELD,
  1354. SpellID::FORTUNE,
  1355. SpellID::HASTE,
  1356. SpellID::MAGIC_MIRROR,
  1357. SpellID::MIRTH,
  1358. SpellID::PRAYER,
  1359. SpellID::PRECISION,
  1360. SpellID::PROTECTION_FROM_AIR,
  1361. SpellID::PROTECTION_FROM_EARTH,
  1362. SpellID::PROTECTION_FROM_FIRE,
  1363. SpellID::PROTECTION_FROM_WATER,
  1364. SpellID::SHIELD,
  1365. SpellID::SLAYER,
  1366. SpellID::STONE_SKIN
  1367. };
  1368. std::vector<SpellID> beneficialSpells;
  1369. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1370. {
  1371. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1372. {
  1373. return pred(stack) && stack->unitOwner() != subject->unitOwner() && stack->isValidTarget(false);
  1374. });
  1375. if(stacks.empty())
  1376. return nullptr;
  1377. else
  1378. return stacks.front();
  1379. };
  1380. for(const SpellID& spellID : allPossibleSpells)
  1381. {
  1382. std::stringstream cachingStr;
  1383. cachingStr << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT) << "id_" << spellID.num;
  1384. if(subject->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1385. //TODO: this ability has special limitations
  1386. || !(spellID.toSpell()->canBeCast(this, spells::Mode::CREATURE_ACTIVE, subject)))
  1387. continue;
  1388. switch (spellID)
  1389. {
  1390. case SpellID::SHIELD:
  1391. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1392. {
  1393. const auto * walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1394. {
  1395. return !stack->canShoot();
  1396. });
  1397. if(!walker)
  1398. continue;
  1399. }
  1400. break;
  1401. case SpellID::AIR_SHIELD: //only against active shooters
  1402. {
  1403. const auto * shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1404. {
  1405. return stack->canShoot();
  1406. });
  1407. if(!shooter)
  1408. continue;
  1409. }
  1410. break;
  1411. case SpellID::ANTI_MAGIC:
  1412. case SpellID::MAGIC_MIRROR:
  1413. case SpellID::PROTECTION_FROM_AIR:
  1414. case SpellID::PROTECTION_FROM_EARTH:
  1415. case SpellID::PROTECTION_FROM_FIRE:
  1416. case SpellID::PROTECTION_FROM_WATER:
  1417. {
  1418. const ui8 enemySide = 1 - subject->unitSide();
  1419. //todo: only if enemy has spellbook
  1420. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1421. continue;
  1422. }
  1423. break;
  1424. case SpellID::CURE: //only damaged units
  1425. {
  1426. //do not cast on affected by debuffs
  1427. if(!subject->canBeHealed())
  1428. continue;
  1429. }
  1430. break;
  1431. case SpellID::BLOODLUST:
  1432. {
  1433. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1434. continue;
  1435. }
  1436. break;
  1437. case SpellID::PRECISION:
  1438. {
  1439. if(!subject->canShoot())
  1440. continue;
  1441. }
  1442. break;
  1443. case SpellID::SLAYER://only if monsters are present
  1444. {
  1445. const auto * kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1446. {
  1447. const auto isKing = Selector::type()(BonusType::KING);
  1448. return stack->hasBonus(isKing);
  1449. });
  1450. if (!kingMonster)
  1451. continue;
  1452. }
  1453. break;
  1454. }
  1455. beneficialSpells.push_back(spellID);
  1456. }
  1457. if(!beneficialSpells.empty())
  1458. {
  1459. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1460. }
  1461. else
  1462. {
  1463. return SpellID::NONE;
  1464. }
  1465. }
  1466. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1467. {
  1468. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1469. TConstBonusListPtr bl = caster->getBonuses(Selector::type()(BonusType::SPELLCASTER));
  1470. if (!bl->size())
  1471. return SpellID::NONE;
  1472. if(bl->size() == 1)
  1473. return bl->front()->subtype.as<SpellID>();
  1474. int totalWeight = 0;
  1475. for(const auto & b : *bl)
  1476. {
  1477. totalWeight += std::max(b->additionalInfo[0], 0); //spells with 0 weight are non-random, exclude them
  1478. }
  1479. if (totalWeight == 0)
  1480. return SpellID::NONE;
  1481. int randomPos = rand.nextInt(totalWeight - 1);
  1482. for(const auto & b : *bl)
  1483. {
  1484. randomPos -= std::max(b->additionalInfo[0], 0);
  1485. if(randomPos < 0)
  1486. {
  1487. return b->subtype.as<SpellID>();
  1488. }
  1489. }
  1490. return SpellID::NONE;
  1491. }
  1492. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1493. {
  1494. RETURN_IF_NOT_BATTLE(-3);
  1495. if(!battleCanSurrender(Player))
  1496. return -1;
  1497. const auto sideOpt = playerToSide(Player);
  1498. if(!sideOpt)
  1499. return -1;
  1500. const auto side = sideOpt.value();
  1501. int ret = 0;
  1502. double discount = 0;
  1503. for(const auto * unit : battleAliveUnits(side))
  1504. ret += unit->getRawSurrenderCost();
  1505. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1506. discount += h->valOfBonuses(BonusType::SURRENDER_DISCOUNT);
  1507. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1508. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1509. return ret;
  1510. }
  1511. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1512. {
  1513. const IBonusBearer * node = nullptr;
  1514. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1515. node = h;
  1516. else
  1517. node = getBonusBearer();
  1518. if(!node)
  1519. return 0;
  1520. auto b = node->getBonuses(Selector::type()(BonusType::BLOCK_MAGIC_BELOW));
  1521. if(b->size())
  1522. return b->totalValue();
  1523. return 0;
  1524. }
  1525. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1526. {
  1527. const IBonusBearer *node = nullptr;
  1528. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1529. node = h;
  1530. else
  1531. node = getBonusBearer();
  1532. if(!node)
  1533. return GameConstants::SPELL_LEVELS;
  1534. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1535. auto b = node->getBonuses(Selector::type()(BonusType::BLOCK_MAGIC_ABOVE));
  1536. if(b->size())
  1537. return b->totalValue();
  1538. return GameConstants::SPELL_LEVELS;
  1539. }
  1540. std::optional<int> CBattleInfoCallback::battleIsFinished() const
  1541. {
  1542. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1543. {
  1544. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(BonusType::SIEGE_WEAPON);
  1545. });
  1546. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1547. for(auto & unit : units)
  1548. {
  1549. //todo: move SIEGE_WEAPON check to Unit state
  1550. hasUnit.at(unit->unitSide()) = true;
  1551. if(hasUnit[0] && hasUnit[1])
  1552. return std::nullopt;
  1553. }
  1554. hasUnit = {false, false};
  1555. for(auto & unit : units)
  1556. {
  1557. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1558. {
  1559. hasUnit.at(unit->unitSide()) = true;
  1560. }
  1561. }
  1562. if(!hasUnit[0] && !hasUnit[1])
  1563. return 2;
  1564. if(!hasUnit[1])
  1565. return 0;
  1566. else
  1567. return 1;
  1568. }
  1569. VCMI_LIB_NAMESPACE_END