CBattleInfoCallback.cpp 56 KB

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