CBattleInfoCallback.cpp 57 KB

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