CBattleInfoCallback.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  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(Bonus::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()(Bonus::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(Bonus::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(Bonus::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(Bonus::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(Bonus::CATAPULT)) //TODO: check shots
  216. allowedActionList.push_back(PossiblePlayerBattleAction::CATAPULT);
  217. if(stack->hasBonusOfType(Bonus::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 isActiveStack) 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, isActiveStack);
  469. }
  470. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit, bool isActiveStack) 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 showTacticsRange = battleTacticDist() && battleGetTacticsSide() == unit->unitSide() && isActiveStack;
  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(showTacticsRange)
  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 isActiveStack, bool addOccupiable, std::vector<BattleHex> * attackable) const
  500. {
  501. std::vector<BattleHex> ret = battleGetAvailableHexes(unit, isActiveStack);
  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()(Bonus::FORGETFULL));
  571. if(!forgetfulList->empty())
  572. {
  573. int forgetful = forgetfulList->valOfBonuses(Selector::type()(Bonus::FORGETFULL));
  574. //advanced+ level
  575. if(forgetful > 1)
  576. return false;
  577. }
  578. return attacker->canShoot() && (!battleIsUnitBlocked(attacker)
  579. || attacker->hasBonusOfType(Bonus::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()(Bonus::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(Bonus::ATTACKS_ALL_ADJACENT))
  1033. {
  1034. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  1035. }
  1036. if(attacker->hasBonusOfType(Bonus::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(Bonus::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(Bonus::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(Bonus::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->owner != attacker->owner) //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()(Bonus::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_PENALTY_DISTANCE;
  1217. auto bonus = shooter->getBonus(Selector::type()(Bonus::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_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(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1286. {
  1287. vstd::amax(manaReduction, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1288. }
  1289. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1290. {
  1291. vstd::amax(manaIncrease, unit->valOfBonuses(Bonus::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(Bonus::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->owner != subject->owner && 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_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1367. if(subject->hasBonus(Selector::source(Bonus::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->side;
  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()(Bonus::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()(Bonus::SPELLCASTER));
  1453. if (!bl->size())
  1454. return SpellID::NONE;
  1455. int totalWeight = 0;
  1456. for(const auto & b : *bl)
  1457. {
  1458. totalWeight += std::max(b->additionalInfo[0], 0); //spells with 0 weight are non-random, exclude them
  1459. }
  1460. if (totalWeight == 0)
  1461. return SpellID::NONE;
  1462. int randomPos = rand.nextInt(totalWeight - 1);
  1463. for(const auto & b : *bl)
  1464. {
  1465. randomPos -= std::max(b->additionalInfo[0], 0);
  1466. if(randomPos < 0)
  1467. {
  1468. return SpellID(b->subtype);
  1469. }
  1470. }
  1471. return SpellID::NONE;
  1472. }
  1473. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1474. {
  1475. RETURN_IF_NOT_BATTLE(-3);
  1476. if(!battleCanSurrender(Player))
  1477. return -1;
  1478. const auto sideOpt = playerToSide(Player);
  1479. if(!sideOpt)
  1480. return -1;
  1481. const auto side = sideOpt.value();
  1482. int ret = 0;
  1483. double discount = 0;
  1484. for(const auto * unit : battleAliveUnits(side))
  1485. ret += unit->getRawSurrenderCost();
  1486. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1487. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1488. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1489. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1490. return ret;
  1491. }
  1492. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1493. {
  1494. const IBonusBearer * node = nullptr;
  1495. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1496. node = h;
  1497. else
  1498. node = getBonusBearer();
  1499. if(!node)
  1500. return 0;
  1501. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_BELOW));
  1502. if(b->size())
  1503. return b->totalValue();
  1504. return 0;
  1505. }
  1506. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1507. {
  1508. const IBonusBearer *node = nullptr;
  1509. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1510. node = h;
  1511. else
  1512. node = getBonusBearer();
  1513. if(!node)
  1514. return GameConstants::SPELL_LEVELS;
  1515. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1516. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_ABOVE));
  1517. if(b->size())
  1518. return b->totalValue();
  1519. return GameConstants::SPELL_LEVELS;
  1520. }
  1521. std::optional<int> CBattleInfoCallback::battleIsFinished() const
  1522. {
  1523. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1524. {
  1525. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1526. });
  1527. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1528. for(auto & unit : units)
  1529. {
  1530. //todo: move SIEGE_WEAPON check to Unit state
  1531. hasUnit.at(unit->unitSide()) = true;
  1532. if(hasUnit[0] && hasUnit[1])
  1533. return std::nullopt;
  1534. }
  1535. hasUnit = {false, false};
  1536. for(auto & unit : units)
  1537. {
  1538. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1539. {
  1540. hasUnit.at(unit->unitSide()) = true;
  1541. }
  1542. }
  1543. if(!hasUnit[0] && !hasUnit[1])
  1544. return 2;
  1545. if(!hasUnit[1])
  1546. return 0;
  1547. else
  1548. return 1;
  1549. }
  1550. VCMI_LIB_NAMESPACE_END