CBattleInfoCallback.cpp 54 KB

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