CBattleInfoCallback.cpp 60 KB

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