CBattleInfoCallback.cpp 57 KB

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