CBattleInfoCallback.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011
  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 "IGameSettings.h"
  19. #include "PossiblePlayerBattleAction.h"
  20. #include "../entities/building/TownFortifications.h"
  21. #include "../spells/ObstacleCasterProxy.h"
  22. #include "../spells/ISpellMechanics.h"
  23. #include "../spells/Problem.h"
  24. #include "../spells/CSpellHandler.h"
  25. #include "../mapObjects/CGTownInstance.h"
  26. #include "../networkPacks/PacksForClientBattle.h"
  27. #include "../BattleFieldHandler.h"
  28. #include "../Rect.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  31. {
  32. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  33. {
  34. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 96, 112, 130, 147, 165, 182};
  35. return lineToHex[line];
  36. }
  37. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  38. {
  39. const bool stackLeft = pos1 < lineToWallHex(pos1.getY());
  40. const bool destLeft = pos2 < lineToWallHex(pos2.getY());
  41. return stackLeft == destLeft;
  42. }
  43. static bool isInsideWalls(BattleHex pos)
  44. {
  45. return lineToWallHex(pos.getY()) < pos;
  46. }
  47. // parts of wall
  48. static const std::pair<int, EWallPart> wallParts[] =
  49. {
  50. std::make_pair(50, EWallPart::KEEP),
  51. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  52. std::make_pair(182, EWallPart::BOTTOM_WALL),
  53. std::make_pair(130, EWallPart::BELOW_GATE),
  54. std::make_pair(78, EWallPart::OVER_GATE),
  55. std::make_pair(29, EWallPart::UPPER_WALL),
  56. std::make_pair(12, EWallPart::UPPER_TOWER),
  57. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  58. std::make_pair(96, EWallPart::GATE),
  59. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  60. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  61. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  62. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  63. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  64. };
  65. static EWallPart hexToWallPart(BattleHex hex)
  66. {
  67. si16 hexValue = hex.toInt();
  68. for(const auto & elem : wallParts)
  69. {
  70. if(elem.first == hexValue)
  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 == BattleSide::NONE)
  97. return ESpellCastProblem::INVALID;
  98. if(!battleDoWeKnowAbout(side))
  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) > 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< BattleHexArray, int > CBattleInfoCallback::getPath(BattleHex start, BattleHex dest, const battle::Unit * stack) const
  126. {
  127. auto reachability = getReachability(stack);
  128. if(reachability.predecessors[dest.toInt()] == -1) //cannot reach destination
  129. {
  130. return std::make_pair(BattleHexArray(), 0);
  131. }
  132. //making the Path
  133. BattleHexArray path;
  134. BattleHex curElem = dest;
  135. while(curElem != start)
  136. {
  137. path.insert(curElem);
  138. curElem = reachability.predecessors[curElem.toInt()];
  139. }
  140. return std::make_pair(path, reachability.distances[dest.toInt()]);
  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. if (!from.isAvailable() || !dest.isAvailable())
  149. throw std::runtime_error("Invalid hex (" + std::to_string(from.toInt()) + " and " + std::to_string(dest.toInt()) + ") received in battleHasPenaltyOnLine!" );
  150. auto isTileBlocked = [&](BattleHex tile)
  151. {
  152. EWallPart wallPart = battleHexToWallPart(tile);
  153. if (wallPart == EWallPart::INVALID)
  154. return false; // there is no wall here
  155. if (wallPart == EWallPart::INDESTRUCTIBLE_PART_OF_GATE)
  156. return false; // does not blocks ranged attacks
  157. if (wallPart == EWallPart::INDESTRUCTIBLE_PART)
  158. return true; // always blocks ranged attacks
  159. return isWallPartAttackable(wallPart);
  160. };
  161. // Count wall penalty requirement by shortest path, not by arbitrary line, to avoid various OH3 bugs
  162. auto getShortestPath = [](BattleHex from, BattleHex dest) -> BattleHexArray
  163. {
  164. //Out early
  165. if(from == dest)
  166. return {};
  167. BattleHexArray ret;
  168. auto next = from;
  169. //Not a real direction, only to indicate to which side we should search closest tile
  170. auto direction = from.getX() > dest.getX() ? BattleSide::DEFENDER : BattleSide::ATTACKER;
  171. while (next != dest)
  172. {
  173. next = BattleHex::getClosestTile(direction, dest, next.getNeighbouringTiles());
  174. ret.insert(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.toInt() != 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(battleGetFortifications().wallsHealth == 0)
  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->fortificationsLevel().wallsHealth > 0 && 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. BattleHexArray CBattleInfoCallback::battleGetAttackedHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  266. {
  267. BattleHexArray 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(s->getHexes().contains(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(BattleSide 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, BattleSide & 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 == BattleSide::NONE && 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 != BattleSide::NONE && 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 != BattleSide::NONE && 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, BattleSide 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 == BattleSide::NONE)
  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 == BattleSide::NONE)
  471. sideThatLastMoved = BattleSide::ATTACKER;
  472. if(!turnsIsFull() && (maxTurns == 0 || turns.size() < maxTurns))
  473. battleGetTurnOrder(turns, maxUnits, maxTurns, actualTurn + 1, sideThatLastMoved);
  474. }
  475. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange) const
  476. {
  477. RETURN_IF_NOT_BATTLE(BattleHexArray());
  478. if(!unit->getPosition().isValid()) //turrets
  479. return BattleHexArray();
  480. auto reachability = getReachability(unit);
  481. return battleGetAvailableHexes(reachability, unit, obtainMovementRange);
  482. }
  483. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit, bool obtainMovementRange) const
  484. {
  485. BattleHexArray 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.insert(i);
  509. }
  510. return ret;
  511. }
  512. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange, bool addOccupiable, BattleHexArray * attackable) const
  513. {
  514. BattleHexArray ret = battleGetAvailableHexes(unit, obtainMovementRange);
  515. if(ret.empty())
  516. return ret;
  517. if(addOccupiable && unit->doubleWide())
  518. {
  519. BattleHexArray occupiable;
  520. for(auto hex : ret)
  521. occupiable.insert(unit->occupiedHex(hex));
  522. ret.insert(occupiable);
  523. }
  524. if(attackable)
  525. {
  526. auto meleeAttackable = [&](BattleHex hex) -> bool
  527. {
  528. // Return true if given hex has at least one available neighbour.
  529. // Available hexes are already present in ret vector.
  530. auto availableNeighbour = boost::find_if(ret, [=] (BattleHex availableHex)
  531. {
  532. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  533. });
  534. return availableNeighbour != ret.end();
  535. };
  536. for(const auto * otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  537. {
  538. if(!otherSt->isValidTarget(false))
  539. continue;
  540. const BattleHexArray & occupied = otherSt->getHexes();
  541. if(battleCanShoot(unit, otherSt->getPosition()))
  542. {
  543. attackable->insert(occupied);
  544. continue;
  545. }
  546. for(BattleHex he : occupied)
  547. {
  548. if(meleeAttackable(he))
  549. attackable->insert(he);
  550. }
  551. }
  552. }
  553. return ret;
  554. }
  555. bool CBattleInfoCallback::battleCanAttack(const battle::Unit * stack, const battle::Unit * target, BattleHex dest) const
  556. {
  557. RETURN_IF_NOT_BATTLE(false);
  558. if(battleTacticDist())
  559. return false;
  560. if (!stack || !target)
  561. return false;
  562. if(target->hasBonusOfType(BonusType::INVINCIBLE))
  563. return false;
  564. if(!battleMatchOwner(stack, target))
  565. return false;
  566. auto id = stack->unitType()->getId();
  567. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  568. return false;
  569. return target->alive();
  570. }
  571. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  572. {
  573. RETURN_IF_NOT_BATTLE(false);
  574. if(battleTacticDist()) //no shooting during tactics
  575. return false;
  576. if (!attacker)
  577. return false;
  578. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  579. return false;
  580. if (!attacker->canShoot())
  581. return false;
  582. return attacker->canShootBlocked() || !battleIsUnitBlocked(attacker);
  583. }
  584. bool CBattleInfoCallback::battleCanTargetEmptyHex(const battle::Unit * attacker) const
  585. {
  586. RETURN_IF_NOT_BATTLE(false);
  587. if(!VLC->engineSettings()->getBoolean(EGameSettings::COMBAT_AREA_SHOT_CAN_TARGET_EMPTY_HEX))
  588. return false;
  589. if(attacker->hasBonusOfType(BonusType::SPELL_LIKE_ATTACK))
  590. {
  591. auto bonus = attacker->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  592. const CSpell * spell = bonus->subtype.as<SpellID>().toSpell();
  593. spells::BattleCast cast(this, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  594. BattleHex dummySpellTarget = BattleHex(50); //check arbitrary hex for general spell range since currently there is no general way to access amount of hexes
  595. if(spell->battleMechanics(&cast)->rangeInHexes(dummySpellTarget).size() > 1)
  596. {
  597. return true;
  598. }
  599. }
  600. return false;
  601. }
  602. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  603. {
  604. RETURN_IF_NOT_BATTLE(false);
  605. const battle::Unit * defender = battleGetUnitByPos(dest);
  606. if(!attacker)
  607. return false;
  608. bool emptyHexAreaAttack = battleCanTargetEmptyHex(attacker);
  609. if(!emptyHexAreaAttack)
  610. {
  611. if(!defender)
  612. return false;
  613. if(defender->hasBonusOfType(BonusType::INVINCIBLE))
  614. return false;
  615. }
  616. if(emptyHexAreaAttack || (battleMatchOwner(attacker, defender) && defender->alive()))
  617. {
  618. if(battleCanShoot(attacker))
  619. {
  620. auto limitedRangeBonus = attacker->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  621. if(limitedRangeBonus == nullptr)
  622. {
  623. return true;
  624. }
  625. int shootingRange = limitedRangeBonus->val;
  626. if(defender)
  627. return isEnemyUnitWithinSpecifiedRange(attacker->getPosition(), defender, shootingRange);
  628. else
  629. return isHexWithinSpecifiedRange(attacker->getPosition(), dest, shootingRange);
  630. }
  631. }
  632. return false;
  633. }
  634. DamageEstimation CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  635. {
  636. DamageCalculator calculator(*this, info);
  637. return calculator.calculateDmgRange();
  638. }
  639. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPosition, DamageEstimation * retaliationDmg) const
  640. {
  641. RETURN_IF_NOT_BATTLE({});
  642. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  643. int movementRange = attackerPosition.isValid() ? reachability[attackerPosition.toInt()] : 0;
  644. return battleEstimateDamage(attacker, defender, movementRange, retaliationDmg);
  645. }
  646. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementRange, DamageEstimation * retaliationDmg) const
  647. {
  648. RETURN_IF_NOT_BATTLE({});
  649. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  650. const BattleAttackInfo bai(attacker, defender, movementRange, shooting);
  651. return battleEstimateDamage(bai, retaliationDmg);
  652. }
  653. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, DamageEstimation * retaliationDmg) const
  654. {
  655. RETURN_IF_NOT_BATTLE({});
  656. DamageEstimation ret = calculateDmgRange(bai);
  657. if(retaliationDmg == nullptr)
  658. return ret;
  659. *retaliationDmg = DamageEstimation();
  660. if(bai.shooting) //FIXME: handle RANGED_RETALIATION
  661. return ret;
  662. if (!bai.defender->ableToRetaliate())
  663. return ret;
  664. if (bai.attacker->hasBonusOfType(BonusType::BLOCKS_RETALIATION) || bai.attacker->hasBonusOfType(BonusType::INVINCIBLE))
  665. return ret;
  666. //TODO: rewrite using boost::numeric::interval
  667. //TODO: rewire once more using interval-based fuzzy arithmetic
  668. const auto & estimateRetaliation = [&](int64_t damage)
  669. {
  670. auto retaliationAttack = bai.reverse();
  671. auto state = retaliationAttack.attacker->acquireState();
  672. state->damage(damage);
  673. retaliationAttack.attacker = state.get();
  674. if (state->alive())
  675. return calculateDmgRange(retaliationAttack);
  676. else
  677. return DamageEstimation();
  678. };
  679. DamageEstimation retaliationMin = estimateRetaliation(ret.damage.min);
  680. DamageEstimation retaliationMax = estimateRetaliation(ret.damage.max);
  681. retaliationDmg->damage.min = std::min(retaliationMin.damage.min, retaliationMax.damage.min);
  682. retaliationDmg->damage.max = std::max(retaliationMin.damage.max, retaliationMax.damage.max);
  683. retaliationDmg->kills.min = std::min(retaliationMin.kills.min, retaliationMax.kills.min);
  684. retaliationDmg->kills.max = std::max(retaliationMin.kills.max, retaliationMax.kills.max);
  685. return ret;
  686. }
  687. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  688. {
  689. auto obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  690. RETURN_IF_NOT_BATTLE(obstacles);
  691. for(auto & obs : battleGetAllObstacles())
  692. {
  693. if(obs->getBlockedTiles().contains(tile)
  694. || (!onlyBlocking && obs->getAffectedTiles().contains(tile)))
  695. {
  696. obstacles.push_back(obs);
  697. }
  698. }
  699. return obstacles;
  700. }
  701. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit, const BattleHexArray & passed) const
  702. {
  703. auto affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  704. RETURN_IF_NOT_BATTLE(affectedObstacles);
  705. if(unit->alive())
  706. {
  707. if(!passed.contains(unit->getPosition()))
  708. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  709. if(unit->doubleWide())
  710. {
  711. BattleHex otherHex = unit->occupiedHex();
  712. if(otherHex.isValid() && !passed.contains(otherHex))
  713. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  714. if(!vstd::contains(affectedObstacles, i))
  715. affectedObstacles.push_back(i);
  716. }
  717. for(auto hex : unit->getHexes())
  718. if(hex == BattleHex::GATE_BRIDGE && battleIsGatePassable())
  719. for(int i=0; i<affectedObstacles.size(); i++)
  720. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  721. affectedObstacles.erase(affectedObstacles.begin()+i);
  722. }
  723. return affectedObstacles;
  724. }
  725. bool CBattleInfoCallback::handleObstacleTriggersForUnit(SpellCastEnvironment & spellEnv, const battle::Unit & unit, const BattleHexArray & passed) const
  726. {
  727. if(!unit.alive())
  728. return false;
  729. bool movementStopped = false;
  730. for(auto & obstacle : getAllAffectedObstaclesByStack(&unit, passed))
  731. {
  732. //helper info
  733. const SpellCreatedObstacle * spellObstacle = dynamic_cast<const SpellCreatedObstacle *>(obstacle.get());
  734. if(spellObstacle)
  735. {
  736. auto revealObstacles = [&](const SpellCreatedObstacle & spellObstacle) -> void
  737. {
  738. // For the hidden spell created obstacles, e.g. QuickSand, it should be revealed after taking damage
  739. auto operation = ObstacleChanges::EOperation::UPDATE;
  740. if (spellObstacle.removeOnTrigger)
  741. operation = ObstacleChanges::EOperation::REMOVE;
  742. SpellCreatedObstacle changedObstacle;
  743. changedObstacle.uniqueID = spellObstacle.uniqueID;
  744. changedObstacle.revealed = true;
  745. BattleObstaclesChanged bocp;
  746. bocp.battleID = getBattle()->getBattleID();
  747. bocp.changes.emplace_back(spellObstacle.uniqueID, operation);
  748. changedObstacle.toInfo(bocp.changes.back(), operation);
  749. spellEnv.apply(bocp);
  750. };
  751. const auto side = unit.unitSide();
  752. auto shouldReveal = !spellObstacle->hidden || !battleIsObstacleVisibleForSide(*obstacle, side);
  753. const auto * hero = battleGetFightingHero(spellObstacle->casterSide);
  754. auto caster = spells::ObstacleCasterProxy(getBattle()->getSidePlayer(spellObstacle->casterSide), hero, *spellObstacle);
  755. if(obstacle->triggersEffects() && obstacle->getTrigger().hasValue())
  756. {
  757. const auto * sp = obstacle->getTrigger().toSpell();
  758. auto cast = spells::BattleCast(this, &caster, spells::Mode::PASSIVE, sp);
  759. spells::detail::ProblemImpl ignored;
  760. auto target = spells::Target(1, spells::Destination(&unit));
  761. if(sp->battleMechanics(&cast)->canBeCastAt(target, ignored)) // Obstacles should not be revealed by immune creatures
  762. {
  763. if(shouldReveal) { //hidden obstacle triggers effects after revealed
  764. revealObstacles(*spellObstacle);
  765. cast.cast(&spellEnv, target);
  766. }
  767. }
  768. }
  769. else if(shouldReveal)
  770. revealObstacles(*spellObstacle);
  771. }
  772. if(!unit.alive())
  773. return false;
  774. if(obstacle->stopsMovement())
  775. movementStopped = true;
  776. }
  777. return unit.alive() && !movementStopped;
  778. }
  779. AccessibilityInfo CBattleInfoCallback::getAccessibility() const
  780. {
  781. AccessibilityInfo ret;
  782. ret.fill(EAccessibility::ACCESSIBLE);
  783. //removing accessibility for side columns of hexes
  784. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  785. {
  786. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y).toInt()] = EAccessibility::SIDE_COLUMN;
  787. ret[BattleHex(0, y).toInt()] = EAccessibility::SIDE_COLUMN;
  788. }
  789. //special battlefields with logically unavailable tiles
  790. auto bFieldType = battleGetBattlefieldType();
  791. if(bFieldType != BattleField::NONE)
  792. {
  793. for(auto hex : bFieldType.getInfo()->impassableHexes)
  794. ret[hex.toInt()] = EAccessibility::UNAVAILABLE;
  795. }
  796. //gate -> should be before stacks
  797. if(battleGetFortifications().wallsHealth > 0)
  798. {
  799. EAccessibility accessibility = EAccessibility::ACCESSIBLE;
  800. switch(battleGetGateState())
  801. {
  802. case EGateState::CLOSED:
  803. accessibility = EAccessibility::GATE;
  804. break;
  805. case EGateState::BLOCKED:
  806. accessibility = EAccessibility::UNAVAILABLE;
  807. break;
  808. }
  809. ret[BattleHex::GATE_OUTER] = ret[BattleHex::GATE_INNER] = accessibility;
  810. }
  811. //tiles occupied by standing stacks
  812. for(const auto * unit : battleAliveUnits())
  813. {
  814. for(auto hex : unit->getHexes())
  815. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  816. ret[hex.toInt()] = EAccessibility::ALIVE_STACK;
  817. }
  818. //obstacles
  819. for(const auto &obst : battleGetAllObstacles())
  820. {
  821. for(auto hex : obst->getBlockedTiles())
  822. ret[hex.toInt()] = EAccessibility::OBSTACLE;
  823. }
  824. //walls
  825. if(battleGetFortifications().wallsHealth > 0)
  826. {
  827. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  828. for(auto hex : permanentlyLocked)
  829. ret[hex] = EAccessibility::UNAVAILABLE;
  830. //TODO likely duplicated logic
  831. static const std::pair<EWallPart, BattleHex> lockedIfNotDestroyed[] =
  832. {
  833. //which part of wall, which hex is blocked if this part of wall is not destroyed
  834. std::make_pair(EWallPart::BOTTOM_WALL, BattleHex(BattleHex::DESTRUCTIBLE_WALL_4)),
  835. std::make_pair(EWallPart::BELOW_GATE, BattleHex(BattleHex::DESTRUCTIBLE_WALL_3)),
  836. std::make_pair(EWallPart::OVER_GATE, BattleHex(BattleHex::DESTRUCTIBLE_WALL_2)),
  837. std::make_pair(EWallPart::UPPER_WALL, BattleHex(BattleHex::DESTRUCTIBLE_WALL_1))
  838. };
  839. for(const auto & elem : lockedIfNotDestroyed)
  840. {
  841. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  842. ret[elem.second.toInt()] = EAccessibility::DESTRUCTIBLE_WALL;
  843. }
  844. }
  845. return ret;
  846. }
  847. AccessibilityInfo CBattleInfoCallback::getAccessibility(const battle::Unit * stack) const
  848. {
  849. return getAccessibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  850. }
  851. AccessibilityInfo CBattleInfoCallback::getAccessibility(const BattleHexArray & accessibleHexes) const
  852. {
  853. auto ret = getAccessibility();
  854. for(auto hex : accessibleHexes)
  855. if(hex.isValid())
  856. ret[hex.toInt()] = EAccessibility::ACCESSIBLE;
  857. return ret;
  858. }
  859. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo & accessibility, const ReachabilityInfo::Parameters & params) const
  860. {
  861. ReachabilityInfo ret;
  862. ret.accessibility = accessibility;
  863. ret.params = params;
  864. ret.predecessors.fill(BattleHex::INVALID);
  865. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  866. if(!params.startPosition.isValid()) //if got call for arrow turrets
  867. return ret;
  868. const BattleHexArray obstacles = getStoppers(params.perspective);
  869. auto checkParams = params;
  870. checkParams.ignoreKnownAccessible = true; //Ignore starting hexes obstacles
  871. std::queue<BattleHex> hexq; //bfs queue
  872. //first element
  873. hexq.push(params.startPosition);
  874. ret.distances[params.startPosition.toInt()] = 0;
  875. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache{};
  876. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  877. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  878. while(!hexq.empty()) //bfs loop
  879. {
  880. const BattleHex curHex = hexq.front();
  881. hexq.pop();
  882. //walking stack can't step past the obstacles
  883. if(isInObstacle(curHex, obstacles, checkParams))
  884. continue;
  885. const int costToNeighbour = ret.distances.at(curHex.toInt()) + 1;
  886. for(BattleHex neighbour : curHex.getNeighbouringTiles())
  887. {
  888. auto additionalCost = 0;
  889. if(params.bypassEnemyStacks)
  890. {
  891. auto enemyToBypass = params.destructibleEnemyTurns.at(neighbour.toInt());
  892. if(enemyToBypass >= 0)
  893. {
  894. additionalCost = enemyToBypass;
  895. }
  896. }
  897. const int costFoundSoFar = ret.distances[neighbour.toInt()];
  898. if(accessibleCache[neighbour.toInt()] && costToNeighbour + additionalCost < costFoundSoFar)
  899. {
  900. hexq.push(neighbour);
  901. ret.distances[neighbour.toInt()] = costToNeighbour + additionalCost;
  902. ret.predecessors[neighbour.toInt()] = curHex;
  903. }
  904. }
  905. }
  906. return ret;
  907. }
  908. bool CBattleInfoCallback::isInObstacle(
  909. BattleHex hex,
  910. const BattleHexArray & obstacleHexes,
  911. const ReachabilityInfo::Parameters & params) const
  912. {
  913. for(auto occupiedHex : battle::Unit::getHexes(hex, params.doubleWide, params.side))
  914. {
  915. if(params.ignoreKnownAccessible && params.knownAccessible->contains(occupiedHex))
  916. continue;
  917. if(obstacleHexes.contains(occupiedHex))
  918. {
  919. if(occupiedHex == BattleHex::GATE_BRIDGE)
  920. {
  921. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  922. return true;
  923. }
  924. else
  925. return true;
  926. }
  927. }
  928. return false;
  929. }
  930. BattleHexArray CBattleInfoCallback::getStoppers(BattleSide whichSidePerspective) const
  931. {
  932. BattleHexArray ret;
  933. RETURN_IF_NOT_BATTLE(ret);
  934. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  935. {
  936. if(!battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  937. continue;
  938. for(auto hex : oi->getStoppingTile())
  939. {
  940. if(hex == BattleHex::GATE_BRIDGE && oi->obstacleType == CObstacleInstance::MOAT)
  941. {
  942. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  943. continue; // this tile is disabled by drawbridge on top of it
  944. }
  945. ret.insert(hex);
  946. }
  947. }
  948. return ret;
  949. }
  950. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  951. {
  952. auto reachability = getReachability(closest);
  953. auto avHexes = battleGetAvailableHexes(reachability, closest, false);
  954. // I hate std::pairs with their undescriptive member names first / second
  955. struct DistStack
  956. {
  957. uint32_t distanceToPred;
  958. BattleHex destination;
  959. const battle::Unit * stack;
  960. };
  961. std::vector<DistStack> stackPairs;
  962. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  963. {
  964. return unit->isValidTarget(false) && unit != closest;
  965. });
  966. for(const battle::Unit * st : possible)
  967. {
  968. for(BattleHex hex : avHexes)
  969. if(CStack::isMeleeAttackPossible(closest, st, hex))
  970. {
  971. DistStack hlp = {reachability.distances[hex.toInt()], hex, st};
  972. stackPairs.push_back(hlp);
  973. }
  974. }
  975. if(!stackPairs.empty())
  976. {
  977. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  978. auto minimal = boost::min_element(stackPairs, comparator);
  979. return std::make_pair(minimal->stack, minimal->destination);
  980. }
  981. else
  982. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  983. }
  984. BattleHex CBattleInfoCallback::getAvailableHex(const CreatureID & creID, BattleSide side, int initialPos) const
  985. {
  986. bool twoHex = VLC->creatures()->getById(creID)->isDoubleWide();
  987. int pos;
  988. if (initialPos > -1)
  989. pos = initialPos;
  990. else //summon elementals depending on player side
  991. {
  992. if(side == BattleSide::ATTACKER)
  993. pos = 0; //top left
  994. else
  995. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  996. }
  997. auto accessibility = getAccessibility();
  998. BattleHexArray occupyable;
  999. for(int i = 0; i < accessibility.size(); i++)
  1000. if(accessibility.accessible(i, twoHex, side))
  1001. occupyable.insert(i);
  1002. if(occupyable.empty())
  1003. {
  1004. return BattleHex::INVALID; //all tiles are covered
  1005. }
  1006. return BattleHex::getClosestTile(side, pos, occupyable);
  1007. }
  1008. si8 CBattleInfoCallback::battleGetTacticDist() const
  1009. {
  1010. RETURN_IF_NOT_BATTLE(0);
  1011. //TODO get rid of this method
  1012. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1013. return battleTacticDist();
  1014. return 0;
  1015. }
  1016. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  1017. {
  1018. RETURN_IF_NOT_BATTLE(false);
  1019. auto side = battleGetTacticsSide();
  1020. auto dist = battleGetTacticDist();
  1021. if (side == BattleSide::ATTACKER && dest.getX() > 0 && dest.getX() <= dist)
  1022. return true;
  1023. if (side == BattleSide::DEFENDER && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1)
  1024. return true;
  1025. return false;
  1026. }
  1027. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  1028. {
  1029. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  1030. if(!battleDoWeKnowAbout(unit->unitSide()))
  1031. {
  1032. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1033. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1034. params.perspective = battleGetMySide();
  1035. }
  1036. return getReachability(params);
  1037. }
  1038. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters & params) const
  1039. {
  1040. if(params.flying)
  1041. return getFlyingReachability(params);
  1042. else
  1043. {
  1044. auto accessibility = getAccessibility(* params.knownAccessible);
  1045. accessibility.destructibleEnemyTurns = std::shared_ptr<const TBattlefieldTurnsArray>(
  1046. & params.destructibleEnemyTurns,
  1047. [](const TBattlefieldTurnsArray *) { }
  1048. );
  1049. return makeBFS(accessibility, params);
  1050. }
  1051. }
  1052. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters & params) const
  1053. {
  1054. ReachabilityInfo ret;
  1055. ret.accessibility = getAccessibility(* params.knownAccessible);
  1056. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1057. {
  1058. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  1059. {
  1060. ret.predecessors[i] = params.startPosition;
  1061. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1062. }
  1063. }
  1064. return ret;
  1065. }
  1066. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes(
  1067. const battle::Unit * attacker,
  1068. BattleHex destinationTile,
  1069. BattleHex attackerPos) const
  1070. {
  1071. const auto * defender = battleGetUnitByPos(destinationTile, true);
  1072. if(!defender)
  1073. return AttackableTiles(); // can't attack thin air
  1074. return getPotentiallyAttackableHexes(
  1075. attacker,
  1076. defender,
  1077. destinationTile,
  1078. attackerPos,
  1079. defender->getPosition());
  1080. }
  1081. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes(
  1082. const battle::Unit* attacker,
  1083. const battle::Unit * defender,
  1084. BattleHex destinationTile,
  1085. BattleHex attackerPos,
  1086. BattleHex defenderPos) const
  1087. {
  1088. //does not return hex attacked directly
  1089. AttackableTiles at;
  1090. RETURN_IF_NOT_BATTLE(at);
  1091. BattleHex attackOriginHex = (attackerPos.toInt() != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1092. defenderPos = (defenderPos.toInt() != BattleHex::INVALID) ? defenderPos : defender->getPosition(); //real or hypothetical (cursor) position
  1093. bool reverse = isToReverse(attacker, defender, attackerPos, defenderPos);
  1094. if(reverse && attacker->doubleWide())
  1095. {
  1096. attackOriginHex = attacker->occupiedHex(attackOriginHex); //the other hex stack stands on
  1097. }
  1098. if(attacker->hasBonusOfType(BonusType::ATTACKS_ALL_ADJACENT))
  1099. {
  1100. at.hostileCreaturePositions.insert(attacker->getSurroundingHexes(attackerPos));
  1101. }
  1102. if(attacker->hasBonusOfType(BonusType::THREE_HEADED_ATTACK))
  1103. {
  1104. const BattleHexArray & hexes = attacker->getSurroundingHexes(attackerPos);
  1105. for(BattleHex tile : hexes)
  1106. {
  1107. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, attackOriginHex) > -1)) //adjacent both to attacker's head and attacked tile
  1108. {
  1109. const auto * st = battleGetUnitByPos(tile, true);
  1110. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  1111. at.hostileCreaturePositions.insert(tile);
  1112. }
  1113. }
  1114. }
  1115. if(attacker->hasBonusOfType(BonusType::WIDE_BREATH))
  1116. {
  1117. BattleHexArray hexes = destinationTile.getNeighbouringTiles();
  1118. for(int i = 0; i < hexes.size(); i++)
  1119. {
  1120. if(hexes.at(i) == attackOriginHex)
  1121. {
  1122. hexes.erase(i);
  1123. i = 0;
  1124. }
  1125. }
  1126. for(BattleHex tile : hexes)
  1127. {
  1128. //friendly stacks can also be damaged by Dragon Breath
  1129. const auto * st = battleGetUnitByPos(tile, true);
  1130. if(st && st != attacker)
  1131. at.friendlyCreaturePositions.insert(tile);
  1132. }
  1133. }
  1134. else if(attacker->hasBonusOfType(BonusType::TWO_HEX_ATTACK_BREATH) || attacker->hasBonusOfType(BonusType::PRISM_HEX_ATTACK_BREATH))
  1135. {
  1136. auto direction = BattleHex::mutualPosition(attackOriginHex, destinationTile);
  1137. if(direction == BattleHex::NONE
  1138. && defender->doubleWide()
  1139. && attacker->doubleWide()
  1140. && defenderPos == destinationTile)
  1141. {
  1142. direction = BattleHex::mutualPosition(attackOriginHex, defender->occupiedHex(defenderPos));
  1143. }
  1144. for(int i = 0; i < 3; i++)
  1145. {
  1146. if(direction != BattleHex::NONE) //only adjacent hexes are subject of dragon breath calculation
  1147. {
  1148. BattleHex nextHex = destinationTile.cloneInDirection(direction, false);
  1149. if ( defender->doubleWide() )
  1150. {
  1151. auto secondHex = destinationTile == defenderPos ? defender->occupiedHex(defenderPos) : defenderPos;
  1152. // if targeted double-wide creature is attacked from above or below ( -> second hex is also adjacent to attack origin)
  1153. // then dragon breath should target tile on the opposite side of targeted creature
  1154. if(BattleHex::mutualPosition(attackOriginHex, secondHex) != BattleHex::NONE)
  1155. nextHex = secondHex.cloneInDirection(direction, false);
  1156. }
  1157. if (nextHex.isValid())
  1158. {
  1159. //friendly stacks can also be damaged by Dragon Breath
  1160. const auto * st = battleGetUnitByPos(nextHex, true);
  1161. if(st != nullptr && st != attacker) //but not unit itself (doublewide + prism attack)
  1162. at.friendlyCreaturePositions.insert(nextHex);
  1163. }
  1164. }
  1165. if(!attacker->hasBonusOfType(BonusType::PRISM_HEX_ATTACK_BREATH))
  1166. break;
  1167. // only needed for prism
  1168. int tmpDirection = static_cast<int>(direction) + 2;
  1169. if(tmpDirection > static_cast<int>(BattleHex::EDir::LEFT))
  1170. tmpDirection -= static_cast<int>(BattleHex::EDir::TOP);
  1171. direction = static_cast<BattleHex::EDir>(tmpDirection);
  1172. }
  1173. }
  1174. return at;
  1175. }
  1176. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1177. {
  1178. //does not return hex attacked directly
  1179. AttackableTiles at;
  1180. RETURN_IF_NOT_BATTLE(at);
  1181. if(attacker->hasBonusOfType(BonusType::SHOOTS_ALL_ADJACENT) && !attackerPos.getNeighbouringTiles().contains(destinationTile))
  1182. {
  1183. at.hostileCreaturePositions.insert(destinationTile.getNeighbouringTiles());
  1184. at.hostileCreaturePositions.insert(destinationTile);
  1185. }
  1186. return at;
  1187. }
  1188. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(
  1189. const battle::Unit * attacker,
  1190. const battle::Unit * defender,
  1191. BattleHex destinationTile,
  1192. bool rangedAttack,
  1193. BattleHex attackerPos,
  1194. BattleHex defenderPos) const
  1195. {
  1196. std::vector<const battle::Unit*> units;
  1197. RETURN_IF_NOT_BATTLE(units);
  1198. if(attackerPos == BattleHex::INVALID)
  1199. attackerPos = attacker->getPosition();
  1200. if(defenderPos == BattleHex::INVALID)
  1201. defenderPos = defender->getPosition();
  1202. AttackableTiles at;
  1203. if (rangedAttack)
  1204. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1205. else
  1206. at = getPotentiallyAttackableHexes(attacker, defender, destinationTile, attackerPos, defenderPos);
  1207. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1208. {
  1209. if (unit->isGhost() || !unit->alive())
  1210. return false;
  1211. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1212. {
  1213. if (at.hostileCreaturePositions.contains(hex))
  1214. return true;
  1215. if (at.friendlyCreaturePositions.contains(hex))
  1216. return true;
  1217. }
  1218. return false;
  1219. });
  1220. return units;
  1221. }
  1222. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1223. {
  1224. std::set<const CStack*> attackedCres;
  1225. RETURN_IF_NOT_BATTLE(attackedCres);
  1226. AttackableTiles at;
  1227. if(rangedAttack)
  1228. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1229. else
  1230. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1231. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1232. {
  1233. const CStack * st = battleGetStackByPos(tile, true);
  1234. if(st && st->unitOwner() != attacker->unitOwner()) //only hostile stacks - does it work well with Berserk?
  1235. {
  1236. attackedCres.insert(st);
  1237. }
  1238. }
  1239. for (BattleHex tile : at.friendlyCreaturePositions)
  1240. {
  1241. const CStack * st = battleGetStackByPos(tile, true);
  1242. if(st) //friendly stacks can also be damaged by Dragon Breath
  1243. {
  1244. attackedCres.insert(st);
  1245. }
  1246. }
  1247. return attackedCres;
  1248. }
  1249. static bool isHexInFront(BattleHex hex, BattleHex testHex, BattleSide side )
  1250. {
  1251. static const std::set<BattleHex::EDir> rightDirs { BattleHex::BOTTOM_RIGHT, BattleHex::TOP_RIGHT, BattleHex::RIGHT };
  1252. static const std::set<BattleHex::EDir> leftDirs { BattleHex::BOTTOM_LEFT, BattleHex::TOP_LEFT, BattleHex::LEFT };
  1253. auto mutualPos = BattleHex::mutualPosition(hex, testHex);
  1254. if (side == BattleSide::ATTACKER)
  1255. return rightDirs.count(mutualPos);
  1256. else
  1257. return leftDirs.count(mutualPos);
  1258. }
  1259. //TODO: this should apply also to mechanics and cursor interface
  1260. bool CBattleInfoCallback::isToReverse(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerHex, BattleHex defenderHex) const
  1261. {
  1262. if(!defenderHex.isValid())
  1263. defenderHex = defender->getPosition();
  1264. if(!attackerHex.isValid())
  1265. attackerHex = attacker->getPosition();
  1266. if (attackerHex < 0 ) //turret
  1267. return false;
  1268. if(isHexInFront(attackerHex, defenderHex, attacker->unitSide()))
  1269. return false;
  1270. auto defenderOtherHex = defenderHex;
  1271. auto attackerOtherHex = defenderHex;
  1272. if (defender->doubleWide())
  1273. {
  1274. defenderOtherHex = battle::Unit::occupiedHex(defenderHex, true, defender->unitSide());
  1275. if(isHexInFront(attackerHex, defenderOtherHex, attacker->unitSide()))
  1276. return false;
  1277. }
  1278. if (attacker->doubleWide())
  1279. {
  1280. attackerOtherHex = battle::Unit::occupiedHex(attackerHex, true, attacker->unitSide());
  1281. if(isHexInFront(attackerOtherHex, defenderHex, attacker->unitSide()))
  1282. return false;
  1283. }
  1284. // a bit weird case since here defender is slightly behind attacker, so reversing seems preferable,
  1285. // but this is how H3 handles it which is important, e.g. for direction of dragon breath attacks
  1286. if (attacker->doubleWide() && defender->doubleWide())
  1287. {
  1288. if(isHexInFront(attackerOtherHex, defenderOtherHex, attacker->unitSide()))
  1289. return false;
  1290. }
  1291. return true;
  1292. }
  1293. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1294. {
  1295. ReachabilityInfo::TDistances ret;
  1296. ret.fill(-1);
  1297. RETURN_IF_NOT_BATTLE(ret);
  1298. auto reachability = getReachability(unit);
  1299. boost::copy(reachability.distances, ret.begin());
  1300. return ret;
  1301. }
  1302. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1303. {
  1304. RETURN_IF_NOT_BATTLE(false);
  1305. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1306. static const auto selectorNoDistancePenalty = Selector::type()(BonusType::NO_DISTANCE_PENALTY);
  1307. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1308. return false;
  1309. if(const auto * target = battleGetUnitByPos(destHex, true))
  1310. {
  1311. //If any hex of target creature is within range, there is no penalty
  1312. int range = GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE;
  1313. auto bonus = shooter->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  1314. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  1315. range = bonus->additionalInfo[0];
  1316. if(isEnemyUnitWithinSpecifiedRange(shooterPosition, target, range))
  1317. return false;
  1318. }
  1319. else
  1320. {
  1321. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE)
  1322. return false;
  1323. }
  1324. return true;
  1325. }
  1326. bool CBattleInfoCallback::isEnemyUnitWithinSpecifiedRange(BattleHex attackerPosition, const battle::Unit * defenderUnit, unsigned int range) const
  1327. {
  1328. for(auto hex : defenderUnit->getHexes())
  1329. if(BattleHex::getDistance(attackerPosition, hex) <= range)
  1330. return true;
  1331. return false;
  1332. }
  1333. bool CBattleInfoCallback::isHexWithinSpecifiedRange(BattleHex attackerPosition, BattleHex targetPosition, unsigned int range) const
  1334. {
  1335. if(BattleHex::getDistance(attackerPosition, targetPosition) <= range)
  1336. return true;
  1337. return false;
  1338. }
  1339. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart part) const
  1340. {
  1341. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1342. return WallPartToHex(part);
  1343. }
  1344. EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1345. {
  1346. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1347. return hexToWallPart(hex);
  1348. }
  1349. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart wallPart) const
  1350. {
  1351. RETURN_IF_NOT_BATTLE(false);
  1352. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1353. wallPart != EWallPart::INVALID;
  1354. }
  1355. bool CBattleInfoCallback::isWallPartAttackable(EWallPart wallPart) const
  1356. {
  1357. RETURN_IF_NOT_BATTLE(false);
  1358. if(isWallPartPotentiallyAttackable(wallPart))
  1359. {
  1360. auto wallState = battleGetWallState(wallPart);
  1361. return (wallState != EWallState::NONE && wallState != EWallState::DESTROYED);
  1362. }
  1363. return false;
  1364. }
  1365. BattleHexArray CBattleInfoCallback::getAttackableBattleHexes() const
  1366. {
  1367. BattleHexArray attackableBattleHexes;
  1368. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1369. for(const auto & wallPartPair : wallParts)
  1370. {
  1371. if(isWallPartAttackable(wallPartPair.second))
  1372. attackableBattleHexes.insert(wallPartPair.first);
  1373. }
  1374. return attackableBattleHexes;
  1375. }
  1376. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1377. {
  1378. RETURN_IF_NOT_BATTLE(-1);
  1379. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1380. int32_t ret = caster->getSpellCost(sp);
  1381. //checking for friendly stacks reducing cost of the spell and
  1382. //enemy stacks increasing it
  1383. int32_t manaReduction = 0;
  1384. int32_t manaIncrease = 0;
  1385. for(const auto * unit : battleAliveUnits())
  1386. {
  1387. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(BonusType::CHANGES_SPELL_COST_FOR_ALLY))
  1388. {
  1389. vstd::amax(manaReduction, unit->valOfBonuses(BonusType::CHANGES_SPELL_COST_FOR_ALLY));
  1390. }
  1391. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(BonusType::CHANGES_SPELL_COST_FOR_ENEMY))
  1392. {
  1393. vstd::amax(manaIncrease, unit->valOfBonuses(BonusType::CHANGES_SPELL_COST_FOR_ENEMY));
  1394. }
  1395. }
  1396. return std::max(0, ret - manaReduction + manaIncrease);
  1397. }
  1398. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1399. {
  1400. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1401. }
  1402. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1403. {
  1404. RETURN_IF_NOT_BATTLE(false);
  1405. for(const auto * adjacent : battleAdjacentUnits(unit))
  1406. {
  1407. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1408. return true;
  1409. }
  1410. return false;
  1411. }
  1412. battle::Units CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1413. {
  1414. RETURN_IF_NOT_BATTLE({});
  1415. const auto & hexes = unit->getSurroundingHexes();
  1416. const auto & units = battleGetUnitsIf([=](const battle::Unit * unit)
  1417. {
  1418. const auto & unitHexes = unit->getHexes();
  1419. for (const auto & hex : unitHexes)
  1420. if (hexes.contains(hex))
  1421. return true;
  1422. return false;
  1423. });
  1424. return units;
  1425. }
  1426. SpellID CBattleInfoCallback::getRandomBeneficialSpell(vstd::RNG & rand, const battle::Unit * caster, const battle::Unit * subject) const
  1427. {
  1428. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1429. //This is complete list. No spells from mods.
  1430. //todo: this should be Spellbook of caster Stack
  1431. static const std::set<SpellID> allPossibleSpells =
  1432. {
  1433. SpellID::AIR_SHIELD,
  1434. SpellID::ANTI_MAGIC,
  1435. SpellID::BLESS,
  1436. SpellID::BLOODLUST,
  1437. SpellID::COUNTERSTRIKE,
  1438. SpellID::CURE,
  1439. SpellID::FIRE_SHIELD,
  1440. SpellID::FORTUNE,
  1441. SpellID::HASTE,
  1442. SpellID::MAGIC_MIRROR,
  1443. SpellID::MIRTH,
  1444. SpellID::PRAYER,
  1445. SpellID::PRECISION,
  1446. SpellID::PROTECTION_FROM_AIR,
  1447. SpellID::PROTECTION_FROM_EARTH,
  1448. SpellID::PROTECTION_FROM_FIRE,
  1449. SpellID::PROTECTION_FROM_WATER,
  1450. SpellID::SHIELD,
  1451. SpellID::SLAYER,
  1452. SpellID::STONE_SKIN
  1453. };
  1454. std::vector<SpellID> beneficialSpells;
  1455. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1456. {
  1457. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1458. {
  1459. return pred(stack) && stack->unitOwner() != subject->unitOwner() && stack->isValidTarget(false);
  1460. });
  1461. if(stacks.empty())
  1462. return nullptr;
  1463. else
  1464. return stacks.front();
  1465. };
  1466. for(const SpellID& spellID : allPossibleSpells)
  1467. {
  1468. std::stringstream cachingStr;
  1469. cachingStr << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT) << "id_" << spellID.num;
  1470. if(subject->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(spellID)), Selector::all, cachingStr.str()))
  1471. continue;
  1472. auto spellPtr = spellID.toSpell();
  1473. spells::Target target;
  1474. target.emplace_back(subject);
  1475. spells::BattleCast cast(this, caster, spells::Mode::CREATURE_ACTIVE, spellPtr);
  1476. auto m = spellPtr->battleMechanics(&cast);
  1477. spells::detail::ProblemImpl problem;
  1478. if (!m->canBeCastAt(target, problem))
  1479. continue;
  1480. switch (spellID.toEnum())
  1481. {
  1482. case SpellID::SHIELD:
  1483. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1484. {
  1485. const auto * walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1486. {
  1487. return !stack->canShoot();
  1488. });
  1489. if(!walker)
  1490. continue;
  1491. }
  1492. break;
  1493. case SpellID::AIR_SHIELD: //only against active shooters
  1494. {
  1495. const auto * shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1496. {
  1497. return stack->canShoot();
  1498. });
  1499. if(!shooter)
  1500. continue;
  1501. }
  1502. break;
  1503. case SpellID::ANTI_MAGIC:
  1504. case SpellID::MAGIC_MIRROR:
  1505. case SpellID::PROTECTION_FROM_AIR:
  1506. case SpellID::PROTECTION_FROM_EARTH:
  1507. case SpellID::PROTECTION_FROM_FIRE:
  1508. case SpellID::PROTECTION_FROM_WATER:
  1509. {
  1510. const BattleSide enemySide = otherSide(subject->unitSide());
  1511. //todo: only if enemy has spellbook
  1512. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1513. continue;
  1514. }
  1515. break;
  1516. case SpellID::CURE: //only damaged units
  1517. {
  1518. //do not cast on affected by debuffs
  1519. if(subject->getFirstHPleft() == subject->getMaxHealth())
  1520. continue;
  1521. }
  1522. break;
  1523. case SpellID::BLOODLUST:
  1524. {
  1525. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1526. continue;
  1527. }
  1528. break;
  1529. case SpellID::PRECISION:
  1530. {
  1531. if(!subject->canShoot())
  1532. continue;
  1533. }
  1534. break;
  1535. case SpellID::SLAYER://only if monsters are present
  1536. {
  1537. const auto * kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1538. {
  1539. return stack->hasBonusOfType(BonusType::KING);
  1540. });
  1541. if (!kingMonster)
  1542. continue;
  1543. }
  1544. break;
  1545. }
  1546. beneficialSpells.push_back(spellID);
  1547. }
  1548. if(!beneficialSpells.empty())
  1549. {
  1550. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1551. }
  1552. else
  1553. {
  1554. return SpellID::NONE;
  1555. }
  1556. }
  1557. SpellID CBattleInfoCallback::getRandomCastedSpell(vstd::RNG & rand,const CStack * caster) const
  1558. {
  1559. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1560. TConstBonusListPtr bl = caster->getBonusesOfType(BonusType::SPELLCASTER);
  1561. if (!bl->size())
  1562. return SpellID::NONE;
  1563. if(bl->size() == 1)
  1564. return bl->front()->subtype.as<SpellID>();
  1565. int totalWeight = 0;
  1566. for(const auto & b : *bl)
  1567. {
  1568. totalWeight += std::max(b->additionalInfo[0], 0); //spells with 0 weight are non-random, exclude them
  1569. }
  1570. if (totalWeight == 0)
  1571. return SpellID::NONE;
  1572. int randomPos = rand.nextInt(totalWeight - 1);
  1573. for(const auto & b : *bl)
  1574. {
  1575. randomPos -= std::max(b->additionalInfo[0], 0);
  1576. if(randomPos < 0)
  1577. {
  1578. return b->subtype.as<SpellID>();
  1579. }
  1580. }
  1581. return SpellID::NONE;
  1582. }
  1583. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1584. {
  1585. RETURN_IF_NOT_BATTLE(-3);
  1586. if(!battleCanSurrender(Player))
  1587. return -1;
  1588. const BattleSide side = playerToSide(Player);
  1589. if(side == BattleSide::NONE)
  1590. return -1;
  1591. int ret = 0;
  1592. double discount = 0;
  1593. for(const auto * unit : battleAliveUnits(side))
  1594. ret += unit->getRawSurrenderCost();
  1595. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1596. discount += h->valOfBonuses(BonusType::SURRENDER_DISCOUNT);
  1597. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1598. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1599. return ret;
  1600. }
  1601. si8 CBattleInfoCallback::battleMinSpellLevel(BattleSide side) const
  1602. {
  1603. const IBonusBearer * node = nullptr;
  1604. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1605. node = h;
  1606. else
  1607. node = getBonusBearer();
  1608. if(!node)
  1609. return 0;
  1610. auto b = node->getBonusesOfType(BonusType::BLOCK_MAGIC_BELOW);
  1611. if(b->size())
  1612. return b->totalValue();
  1613. return 0;
  1614. }
  1615. si8 CBattleInfoCallback::battleMaxSpellLevel(BattleSide side) const
  1616. {
  1617. const IBonusBearer *node = nullptr;
  1618. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1619. node = h;
  1620. else
  1621. node = getBonusBearer();
  1622. if(!node)
  1623. return GameConstants::SPELL_LEVELS;
  1624. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1625. auto b = node->getBonusesOfType(BonusType::BLOCK_MAGIC_ABOVE);
  1626. if(b->size())
  1627. return b->totalValue();
  1628. return GameConstants::SPELL_LEVELS;
  1629. }
  1630. std::optional<BattleSide> CBattleInfoCallback::battleIsFinished() const
  1631. {
  1632. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1633. {
  1634. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(BonusType::SIEGE_WEAPON);
  1635. });
  1636. BattleSideArray<bool> hasUnit = {false, false}; //index is BattleSide
  1637. for(auto & unit : units)
  1638. {
  1639. //todo: move SIEGE_WEAPON check to Unit state
  1640. hasUnit.at(unit->unitSide()) = true;
  1641. if(hasUnit[BattleSide::ATTACKER] && hasUnit[BattleSide::DEFENDER])
  1642. return std::nullopt;
  1643. }
  1644. hasUnit = {false, false};
  1645. for(auto & unit : units)
  1646. {
  1647. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1648. {
  1649. hasUnit.at(unit->unitSide()) = true;
  1650. }
  1651. }
  1652. if(!hasUnit[BattleSide::ATTACKER] && !hasUnit[BattleSide::DEFENDER])
  1653. return BattleSide::NONE;
  1654. if(!hasUnit[BattleSide::DEFENDER])
  1655. return BattleSide::ATTACKER;
  1656. else
  1657. return BattleSide::DEFENDER;
  1658. }
  1659. VCMI_LIB_NAMESPACE_END