CBattleInfoCallback.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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 "../CStack.h"
  13. #include "BattleInfo.h"
  14. #include "../NetPacks.h"
  15. #include "../spells/CSpellHandler.h"
  16. #include "../mapObjects/CGTownInstance.h"
  17. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  18. {
  19. /*
  20. *Here are 2 explanations how below algorithm should work in H3, looks like they are not 100% accurate as it results in one damage number, not min/max range:
  21. *
  22. *1. http://heroes.thelazy.net/wiki/Arrow_tower
  23. *
  24. *2. All towns' turrets do the same damage. If Fort, Citadel or Castle is built damage of the Middle turret is 15, and 7,5 for others.
  25. *Buildings increase turrets' damage, but only those buildings that are new in town view, not upgrades to the existing. So, every building save:
  26. *- dwellings' upgrades
  27. *- Mage Guild upgrades
  28. *- Horde buildings
  29. *- income upgrades
  30. *- some special ones
  31. *increases middle Turret damage by 3, and 1,5 for the other two.
  32. *Damage is almost always the maximum one (right click on the Turret), sometimes +1/2 points, and it does not depend on the target. Nothing can influence it, except the mentioned above (but it will be roughly double if the defender has Armorer or Air Shield).
  33. *Maximum damage for Castle, Conflux is 120, Necropolis, Inferno, Fortress 125, Stronghold, Turret, and Dungeon 130 (for all three Turrets).
  34. *Artillery allows the player to control the Turrets.
  35. */
  36. static void retrieveTurretDamageRange(const CGTownInstance * town, const battle::Unit * turret, double & outMinDmg, double & outMaxDmg)//does not match OH3 yet, but damage is somewhat close
  37. {
  38. assert(turret->creatureIndex() == CreatureID::ARROW_TOWERS);
  39. assert(town);
  40. assert(turret->getPosition() >= -4 && turret->getPosition() <= -2);
  41. const float multiplier = (turret->getPosition() == -2) ? 1 : 0.5;
  42. //Revised - Where do below values come from?
  43. /*int baseMin = 6;
  44. int baseMax = 10;*/
  45. const int baseDamage = 15;
  46. outMinDmg = multiplier * (baseDamage + town->getTownLevel() * 3);
  47. outMaxDmg = multiplier * (baseDamage + town->getTownLevel() * 3);
  48. }
  49. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  50. {
  51. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  52. return lineToHex[line];
  53. }
  54. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  55. {
  56. const int wallInStackLine = lineToWallHex(pos1.getY());
  57. const int wallInDestLine = lineToWallHex(pos2.getY());
  58. const bool stackLeft = pos1 < wallInStackLine;
  59. const bool destLeft = pos2 < wallInDestLine;
  60. return stackLeft == destLeft;
  61. }
  62. // parts of wall
  63. static const std::pair<int, EWallPart::EWallPart> wallParts[] =
  64. {
  65. std::make_pair(50, EWallPart::KEEP),
  66. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  67. std::make_pair(182, EWallPart::BOTTOM_WALL),
  68. std::make_pair(130, EWallPart::BELOW_GATE),
  69. std::make_pair(78, EWallPart::OVER_GATE),
  70. std::make_pair(29, EWallPart::UPPER_WALL),
  71. std::make_pair(12, EWallPart::UPPER_TOWER),
  72. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  73. std::make_pair(96, EWallPart::GATE),
  74. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  75. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  76. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  77. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  78. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  79. };
  80. static EWallPart::EWallPart hexToWallPart(BattleHex hex)
  81. {
  82. for(auto & elem : wallParts)
  83. {
  84. if(elem.first == hex)
  85. return elem.second;
  86. }
  87. return EWallPart::INVALID; //not found!
  88. }
  89. static BattleHex WallPartToHex(EWallPart::EWallPart part)
  90. {
  91. for(auto & elem : wallParts)
  92. {
  93. if(elem.second == part)
  94. return elem.first;
  95. }
  96. return BattleHex::INVALID; //not found!
  97. }
  98. }
  99. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  100. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  101. {
  102. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  103. if(caster == nullptr)
  104. {
  105. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  106. return ESpellCastProblem::INVALID;
  107. }
  108. const PlayerColor player = caster->getOwner();
  109. const auto side = playerToSide(player);
  110. if(!side)
  111. return ESpellCastProblem::INVALID;
  112. if(!battleDoWeKnowAbout(side.get()))
  113. {
  114. logGlobal->warn("You can't check if enemy can cast given spell!");
  115. return ESpellCastProblem::INVALID;
  116. }
  117. if(battleTacticDist())
  118. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  119. switch(mode)
  120. {
  121. case spells::Mode::HERO:
  122. {
  123. if(battleCastSpells(side.get()) > 0)
  124. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  125. auto hero = dynamic_cast<const CGHeroInstance *>(caster);
  126. if(!hero)
  127. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  128. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  129. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  130. }
  131. break;
  132. default:
  133. break;
  134. }
  135. return ESpellCastProblem::OK;
  136. }
  137. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  138. {
  139. RETURN_IF_NOT_BATTLE(false);
  140. if(!battleGetSiegeLevel())
  141. return false;
  142. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  143. static const auto selectorNoWallPenalty = Selector::type(Bonus::NO_WALL_PENALTY);
  144. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  145. return false;
  146. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  147. const int wallInDestLine = lineToWallHex(destHex.getY());
  148. const bool stackLeft = shooterPosition < wallInStackLine;
  149. const bool destRight = destHex > wallInDestLine;
  150. if (stackLeft && destRight) //shooting from outside to inside
  151. {
  152. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  153. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  154. row -= 2;
  155. const int wallPos = lineToWallHex(row);
  156. if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
  157. }
  158. return false;
  159. }
  160. si8 CBattleInfoCallback::battleCanTeleportTo(const battle::Unit * stack, BattleHex destHex, int telportLevel) const
  161. {
  162. RETURN_IF_NOT_BATTLE(false);
  163. if (!getAccesibility(stack).accessible(destHex, stack))
  164. return false;
  165. const ui8 siegeLevel = battleGetSiegeLevel();
  166. //check for wall
  167. //advanced teleport can pass wall of fort|citadel, expert - of castle
  168. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  169. return sameSideOfWall(stack->getPosition(), destHex);
  170. return true;
  171. }
  172. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  173. {
  174. std::set<BattleHex> attackedHexes;
  175. RETURN_IF_NOT_BATTLE(attackedHexes);
  176. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  177. for (BattleHex tile : at.hostileCreaturePositions)
  178. {
  179. const CStack * st = battleGetStackByPos(tile, true);
  180. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  181. {
  182. attackedHexes.insert(tile);
  183. }
  184. }
  185. for (BattleHex tile : at.friendlyCreaturePositions)
  186. {
  187. if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  188. {
  189. attackedHexes.insert(tile);
  190. }
  191. }
  192. return attackedHexes;
  193. }
  194. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  195. {
  196. switch (mode)
  197. {
  198. case RANDOM_GENIE:
  199. return getRandomBeneficialSpell(rand, stack); //target
  200. break;
  201. case RANDOM_AIMED:
  202. return getRandomCastedSpell(rand, stack); //caster
  203. break;
  204. default:
  205. logGlobal->error("Incorrect mode of battleGetRandomSpell (%d)", static_cast<int>(mode));
  206. return SpellID::NONE;
  207. }
  208. }
  209. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  210. {
  211. RETURN_IF_NOT_BATTLE(nullptr);
  212. for(auto s : battleGetAllStacks(true))
  213. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  214. return s;
  215. return nullptr;
  216. }
  217. const battle::Unit * CBattleInfoCallback::battleGetUnitByPos(BattleHex pos, bool onlyAlive) const
  218. {
  219. RETURN_IF_NOT_BATTLE(nullptr);
  220. auto ret = battleGetUnitsIf([=](const battle::Unit * unit)
  221. {
  222. return !unit->isGhost()
  223. && vstd::contains(battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()), pos)
  224. && (!onlyAlive || unit->alive());
  225. });
  226. if(!ret.empty())
  227. return ret.front();
  228. else
  229. return nullptr;
  230. }
  231. battle::Units CBattleInfoCallback::battleAliveUnits() const
  232. {
  233. return battleGetUnitsIf([](const battle::Unit * unit)
  234. {
  235. return unit->isValidTarget(false);
  236. });
  237. }
  238. battle::Units CBattleInfoCallback::battleAliveUnits(ui8 side) const
  239. {
  240. return battleGetUnitsIf([=](const battle::Unit * unit)
  241. {
  242. return unit->isValidTarget(false) && unit->unitSide() == side;
  243. });
  244. }
  245. //T is battle::Unit descendant
  246. template <typename T>
  247. const T * takeOneUnit(std::vector<const T *> & all, const int turn, int8_t & lastMoved)
  248. {
  249. const T * ret = nullptr;
  250. size_t i, //fastest stack
  251. j=0; //fastest stack of the other side
  252. for(i = 0; i < all.size(); i++)
  253. if(all[i])
  254. break;
  255. //no stacks left
  256. if(i == all.size())
  257. return nullptr;
  258. const T * fastest = all[i], *other = nullptr;
  259. int bestSpeed = fastest->getInitiative(turn);
  260. if(fastest->unitSide() == lastMoved)
  261. {
  262. ret = fastest;
  263. }
  264. else
  265. {
  266. for(j = i + 1; j < all.size(); j++)
  267. {
  268. if(!all[j]) continue;
  269. if(all[j]->unitSide() != lastMoved || all[j]->getInitiative(turn) != bestSpeed)
  270. break;
  271. }
  272. if(j >= all.size())
  273. {
  274. ret = fastest;
  275. }
  276. else
  277. {
  278. other = all[j];
  279. if(other->getInitiative(turn) != bestSpeed)
  280. ret = fastest;
  281. else
  282. ret = other;
  283. }
  284. }
  285. assert(ret);
  286. if(ret == fastest)
  287. all[i] = nullptr;
  288. else
  289. all[j] = nullptr;
  290. lastMoved = ret->unitSide();
  291. return ret;
  292. }
  293. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & out, const size_t maxUnits, const int maxTurns, const int turn, int8_t lastMoved) const
  294. {
  295. RETURN_IF_NOT_BATTLE();
  296. if(maxUnits == 0 && maxTurns == 0)
  297. {
  298. logGlobal->error("Attempt to get infinite battle queue");
  299. return;
  300. }
  301. auto actualTurn = turn > 0 ? turn : 0;
  302. auto outputFull = [&]() -> bool
  303. {
  304. if(maxUnits == 0)
  305. return false;//no limit
  306. size_t outSize = 0;
  307. for(const auto & oneTurn : out)
  308. outSize += oneTurn.size();
  309. return outSize >= maxUnits;
  310. };
  311. out.emplace_back();
  312. //We'll split creatures with remaining movement to 4 buckets
  313. // [0] - turrets/catapult,
  314. // [1] - normal (unmoved) creatures, other war machines,
  315. // [2] - waited cres that had morale,
  316. // [3] - rest of waited cres
  317. std::array<battle::Units, 4> phase;
  318. const battle::Unit * active = battleActiveUnit();
  319. if(active)
  320. {
  321. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  322. if(turn == 0 && active->willMove() && !active->waited())
  323. {
  324. out.back().push_back(active);
  325. if(outputFull())
  326. return;
  327. }
  328. //its first or current turn, turn priority for active stack side
  329. //TODO: what if active stack mind-controlled?
  330. if(turn <= 0 && lastMoved < 0)
  331. lastMoved = active->unitSide();
  332. }
  333. auto all = battleGetUnitsIf([](const battle::Unit * unit)
  334. {
  335. return !unit->isGhost();
  336. });
  337. if(!vstd::contains_if(all, [](const battle::Unit * unit) { return unit->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  338. {
  339. //No unit will be able to move, battle is over.
  340. out.clear();
  341. return;
  342. }
  343. for(auto one : all)
  344. {
  345. if((actualTurn == 0 && !one->willMove()) //we are considering current round and unit won't move
  346. || (actualTurn > 0 && !one->canMove(turn)) //unit won't be able to move in later rounds
  347. || (actualTurn == 0 && one == active && !out.at(0).empty() && one == out.front().front())) //it's active unit already added at the beginning of queue
  348. {
  349. continue;
  350. }
  351. int p = one->battleQueuePhase(turn);
  352. phase[p].push_back(one);
  353. }
  354. boost::sort(phase[0], CMP_stack(0, actualTurn));
  355. std::copy(phase[0].begin(), phase[0].end(), std::back_inserter(out.back()));
  356. if(outputFull())
  357. return;
  358. for(int i = 1; i < 4; i++)
  359. boost::sort(phase[i], CMP_stack(i, actualTurn));
  360. if(lastMoved < 0)
  361. lastMoved = BattleSide::ATTACKER;
  362. int pi = 1;
  363. while(!outputFull() && pi < 4)
  364. {
  365. auto current = takeOneUnit(phase[pi], actualTurn, lastMoved);
  366. if(!current)
  367. pi++;
  368. else
  369. out.back().push_back(current);
  370. }
  371. if(!outputFull() && (maxTurns == 0 || out.size() < maxTurns))
  372. battleGetTurnOrder(out, maxUnits, maxTurns, actualTurn + 1, lastMoved);
  373. }
  374. void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
  375. {
  376. RETURN_IF_NOT_BATTLE();
  377. auto accessibility = getAccesibility();
  378. for(int i = 0; i < accessibility.size(); i++)
  379. ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  380. }
  381. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit) const
  382. {
  383. RETURN_IF_NOT_BATTLE(std::vector<BattleHex>());
  384. if(!unit->getPosition().isValid()) //turrets
  385. return std::vector<BattleHex>();
  386. auto reachability = getReachability(unit);
  387. return battleGetAvailableHexes(reachability, unit);
  388. }
  389. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit) const
  390. {
  391. std::vector<BattleHex> ret;
  392. RETURN_IF_NOT_BATTLE(ret);
  393. if(!unit->getPosition().isValid()) //turrets
  394. return ret;
  395. auto unitSpeed = unit->Speed(0, true);
  396. const bool tacticPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  397. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  398. {
  399. // If obstacles or other stacks makes movement impossible, it can't be helped.
  400. if(!cache.isReachable(i))
  401. continue;
  402. if(tacticPhase)
  403. {
  404. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  405. if(!isInTacticRange(i))
  406. continue;
  407. }
  408. else
  409. {
  410. //Not tactics phase -> destination must be reachable and within unit range.
  411. if(cache.distances[i] > unitSpeed)
  412. continue;
  413. }
  414. ret.push_back(i);
  415. }
  416. return ret;
  417. }
  418. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool addOccupiable, std::vector<BattleHex> * attackable) const
  419. {
  420. std::vector<BattleHex> ret = battleGetAvailableHexes(unit);
  421. if(ret.empty())
  422. return ret;
  423. if(addOccupiable && unit->doubleWide())
  424. {
  425. std::vector<BattleHex> occupiable;
  426. for(auto hex : ret)
  427. occupiable.push_back(unit->occupiedHex(hex));
  428. vstd::concatenate(ret, occupiable);
  429. }
  430. if(attackable)
  431. {
  432. auto meleeAttackable = [&](BattleHex hex) -> bool
  433. {
  434. // Return true if given hex has at least one available neighbour.
  435. // Available hexes are already present in ret vector.
  436. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  437. {
  438. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  439. });
  440. return availableNeighbor != ret.end();
  441. };
  442. for(auto otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  443. {
  444. if(!otherSt->isValidTarget(false))
  445. continue;
  446. std::vector<BattleHex> occupied = otherSt->getHexes();
  447. if(battleCanShoot(unit, otherSt->getPosition()))
  448. {
  449. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  450. continue;
  451. }
  452. for(BattleHex he : occupied)
  453. {
  454. if(meleeAttackable(he))
  455. attackable->push_back(he);
  456. }
  457. }
  458. }
  459. //adding occupiable likely adds duplicates to ret -> clean it up
  460. boost::sort(ret);
  461. ret.erase(boost::unique(ret).end(), ret.end());
  462. return ret;
  463. }
  464. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  465. {
  466. RETURN_IF_NOT_BATTLE(false);
  467. if(battleTacticDist())
  468. return false;
  469. if (!stack || !target)
  470. return false;
  471. if(!battleMatchOwner(stack, target))
  472. return false;
  473. auto &id = stack->getCreature()->idNumber;
  474. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  475. return false;
  476. if (!target->alive())
  477. return false;
  478. return true;
  479. }
  480. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  481. {
  482. RETURN_IF_NOT_BATTLE(false);
  483. if(battleTacticDist()) //no shooting during tactics
  484. return false;
  485. const battle::Unit * defender = battleGetUnitByPos(dest);
  486. if(!attacker || !defender)
  487. return false;
  488. //forgetfulness
  489. TBonusListPtr forgetfulList = attacker->getBonuses(Selector::type(Bonus::FORGETFULL));
  490. if(!forgetfulList->empty())
  491. {
  492. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  493. //advanced+ level
  494. if(forgetful > 1)
  495. return false;
  496. }
  497. if(attacker->creatureIndex() == CreatureID::CATAPULT && defender) //catapult cannot attack creatures
  498. return false;
  499. if(attacker->canShoot()
  500. && battleMatchOwner(attacker, defender)
  501. && defender->alive()
  502. && (!battleIsUnitBlocked(attacker) || attacker->hasBonusOfType(Bonus::FREE_SHOOTING)))
  503. return true;
  504. return false;
  505. }
  506. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  507. {
  508. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  509. {
  510. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  511. auto limitMatches = info.shooting
  512. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  513. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  514. //any regular bonuses or just ones for melee/ranged
  515. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  516. };
  517. const IBonusBearer * attackerBonuses = info.attacker;
  518. const IBonusBearer * defenderBonuses = info.defender;
  519. double additiveBonus = 1.0 + info.additiveBonus;
  520. double multBonus = 1.0 * info.multBonus;
  521. double minDmg = 0.0;
  522. double maxDmg = 0.0;
  523. minDmg = info.attacker->getMinDamage(info.shooting);
  524. maxDmg = info.attacker->getMaxDamage(info.shooting);
  525. minDmg *= info.attacker->getCount(),
  526. maxDmg *= info.attacker->getCount();
  527. if(info.attacker->creatureIndex() == CreatureID::ARROW_TOWERS)
  528. {
  529. SiegeStuffThatShouldBeMovedToHandlers::retrieveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  530. TDmgRange unmodifiableTowerDamage = std::make_pair(int64_t(minDmg), int64_t(maxDmg));
  531. return unmodifiableTowerDamage;
  532. }
  533. const std::string cachingStrSiedgeWeapon = "type_SIEGE_WEAPON";
  534. static const auto selectorSiedgeWeapon = Selector::type(Bonus::SIEGE_WEAPON);
  535. if(attackerBonuses->hasBonus(selectorSiedgeWeapon, cachingStrSiedgeWeapon) && info.attacker->creatureIndex() != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  536. { //minDmg and maxDmg are multiplied by hero attack + 1
  537. auto retrieveHeroPrimSkill = [&](int skill) -> int
  538. {
  539. const std::shared_ptr<Bonus> b = attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  540. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  541. };
  542. minDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  543. maxDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  544. }
  545. double attackDefenceDifference = 0.0;
  546. double multAttackReduction = 1.0 - battleBonusValue(attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION)) / 100.0;
  547. attackDefenceDifference += info.attacker->getAttack(info.shooting) * multAttackReduction;
  548. double multDefenceReduction = 1.0 - battleBonusValue(attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION)) / 100.0;
  549. attackDefenceDifference -= info.defender->getDefence(info.shooting) * multDefenceReduction;
  550. const std::string cachingStrSlayer = "type_SLAYER";
  551. static const auto selectorSlayer = Selector::type(Bonus::SLAYER);
  552. //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  553. auto slayerEffects = attackerBonuses->getBonuses(selectorSlayer, cachingStrSlayer);
  554. if(const std::shared_ptr<Bonus> slayerEffect = slayerEffects->getFirst(Selector::all))
  555. {
  556. std::vector<int32_t> affectedIds;
  557. const auto spLevel = slayerEffect->val;
  558. const CCreature * defenderType = info.defender->unitType();
  559. bool isAffected = false;
  560. for(const auto & b : defenderType->getBonusList())
  561. {
  562. if((b->type == Bonus::KING3 && spLevel >= 3) || //expert
  563. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  564. (b->type == Bonus::KING1 && spLevel >= 0)) //none or basic +
  565. {
  566. isAffected = true;
  567. break;
  568. }
  569. }
  570. if(isAffected)
  571. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
  572. }
  573. //bonus from attack/defense skills
  574. if(attackDefenceDifference < 0) //decreasing dmg
  575. {
  576. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  577. multBonus *= 1.0 - dec;
  578. }
  579. else //increasing dmg
  580. {
  581. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  582. additiveBonus += inc;
  583. }
  584. const std::string cachingStrJousting = "type_JOUSTING";
  585. static const auto selectorJousting = Selector::type(Bonus::JOUSTING);
  586. const std::string cachingStrChargeImmunity = "type_CHARGE_IMMUNITY";
  587. static const auto selectorChargeImmunity = Selector::type(Bonus::CHARGE_IMMUNITY);
  588. //applying jousting bonus
  589. if(info.chargedFields > 0 && attackerBonuses->hasBonus(selectorJousting, cachingStrJousting) && !defenderBonuses->hasBonus(selectorChargeImmunity, cachingStrChargeImmunity))
  590. additiveBonus += info.chargedFields * 0.05;
  591. //handling secondary abilities and artifacts giving premies to them
  592. const std::string cachingStrArchery = "type_SECONDARY_SKILL_PREMYs_ARCHERY";
  593. static const auto selectorArchery = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY);
  594. const std::string cachingStrOffence = "type_SECONDARY_SKILL_PREMYs_OFFENCE";
  595. static const auto selectorOffence = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE);
  596. const std::string cachingStrArmorer = "type_SECONDARY_SKILL_PREMYs_ARMORER";
  597. static const auto selectorArmorer = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER);
  598. if(info.shooting)
  599. additiveBonus += attackerBonuses->valOfBonuses(selectorArchery, cachingStrArchery) / 100.0;
  600. else
  601. additiveBonus += attackerBonuses->valOfBonuses(selectorOffence, cachingStrOffence) / 100.0;
  602. multBonus *= (std::max(0, 100 - defenderBonuses->valOfBonuses(selectorArmorer, cachingStrArmorer))) / 100.0;
  603. //handling hate effect
  604. //assume that unit have only few HATE features and cache them all
  605. const std::string cachingStrHate = "type_HATE";
  606. static const auto selectorHate = Selector::type(Bonus::HATE);
  607. auto allHateEffects = attackerBonuses->getBonuses(selectorHate, cachingStrHate);
  608. additiveBonus += allHateEffects->valOfBonuses(Selector::subtype(info.defender->creatureIndex())) / 100.0;
  609. const std::string cachingStrMeleeReduction = "type_GENERAL_DAMAGE_REDUCTIONs_0";
  610. static const auto selectorMeleeReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 0);
  611. const std::string cachingStrRangedReduction = "type_GENERAL_DAMAGE_REDUCTIONs_1";
  612. static const auto selectorRangedReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 1);
  613. //handling spell effects
  614. if(!info.shooting) //eg. shield
  615. {
  616. multBonus *= (100 - defenderBonuses->valOfBonuses(selectorMeleeReduction, cachingStrMeleeReduction)) / 100.0;
  617. }
  618. else //eg. air shield
  619. {
  620. multBonus *= (100 - defenderBonuses->valOfBonuses(selectorRangedReduction, cachingStrRangedReduction)) / 100.0;
  621. }
  622. if(info.shooting)
  623. {
  624. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  625. //get list first, total value of 0 also counts
  626. TBonusListPtr forgetfulList = attackerBonuses->getBonuses(Selector::type(Bonus::FORGETFULL),"type_FORGETFULL");
  627. if(!forgetfulList->empty())
  628. {
  629. int forgetful = forgetfulList->valOfBonuses(Selector::all);
  630. //none of basic level
  631. if(forgetful == 0 || forgetful == 1)
  632. multBonus *= 0.5;
  633. else
  634. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  635. }
  636. }
  637. const std::string cachingStrForcedMinDamage = "type_ALWAYS_MINIMUM_DAMAGE";
  638. static const auto selectorForcedMinDamage = Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE);
  639. const std::string cachingStrForcedMaxDamage = "type_ALWAYS_MAXIMUM_DAMAGE";
  640. static const auto selectorForcedMaxDamage = Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE);
  641. TBonusListPtr curseEffects = attackerBonuses->getBonuses(selectorForcedMinDamage, cachingStrForcedMinDamage);
  642. TBonusListPtr blessEffects = attackerBonuses->getBonuses(selectorForcedMaxDamage, cachingStrForcedMaxDamage);
  643. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  644. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo : 0;
  645. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  646. {
  647. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  648. }
  649. const std::string cachingStrAdvAirShield = "isAdvancedAirShield";
  650. auto isAdvancedAirShield = [](const Bonus* bonus)
  651. {
  652. return bonus->source == Bonus::SPELL_EFFECT
  653. && bonus->sid == SpellID::AIR_SHIELD
  654. && bonus->val >= SecSkillLevel::ADVANCED;
  655. };
  656. if(info.shooting)
  657. {
  658. //wall / distance penalty + advanced air shield
  659. const bool distPenalty = battleHasDistancePenalty(attackerBonuses, info.attacker->getPosition(), info.defender->getPosition());
  660. const bool obstaclePenalty = battleHasWallPenalty(attackerBonuses, info.attacker->getPosition(), info.defender->getPosition());
  661. if(distPenalty || defenderBonuses->hasBonus(isAdvancedAirShield, cachingStrAdvAirShield))
  662. multBonus *= 0.5;
  663. if(obstaclePenalty)
  664. multBonus *= 0.5; //cumulative
  665. }
  666. else
  667. {
  668. const std::string cachingStrNoMeleePenalty = "type_NO_MELEE_PENALTY";
  669. static const auto selectorNoMeleePenalty = Selector::type(Bonus::NO_MELEE_PENALTY);
  670. if(info.attacker->isShooter() && !attackerBonuses->hasBonus(selectorNoMeleePenalty, cachingStrNoMeleePenalty))
  671. multBonus *= 0.5;
  672. }
  673. // psychic elementals versus mind immune units 50%
  674. if(info.attacker->creatureIndex() == CreatureID::PSYCHIC_ELEMENTAL)
  675. {
  676. const std::string cachingStrMindImmunity = "type_MIND_IMMUNITY";
  677. static const auto selectorMindImmunity = Selector::type(Bonus::MIND_IMMUNITY);
  678. if(defenderBonuses->hasBonus(selectorMindImmunity, cachingStrMindImmunity))
  679. multBonus *= 0.5;
  680. }
  681. // TODO attack on petrified unit 50%
  682. // blinded unit retaliates
  683. minDmg *= additiveBonus * multBonus;
  684. maxDmg *= additiveBonus * multBonus;
  685. if(curseEffects->size()) //curse handling (rest)
  686. {
  687. minDmg += curseBlessAdditiveModifier;
  688. maxDmg = minDmg;
  689. }
  690. else if(blessEffects->size()) //bless handling
  691. {
  692. maxDmg += curseBlessAdditiveModifier;
  693. minDmg = maxDmg;
  694. }
  695. TDmgRange returnedVal = std::make_pair(int64_t(minDmg), int64_t(maxDmg));
  696. //damage cannot be less than 1
  697. vstd::amax(returnedVal.first, 1);
  698. vstd::amax(returnedVal.second, 1);
  699. return returnedVal;
  700. }
  701. TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  702. {
  703. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  704. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  705. const BattleAttackInfo bai(attacker, defender, shooting);
  706. return battleEstimateDamage(bai, retaliationDmg);
  707. }
  708. TDmgRange CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, TDmgRange * retaliationDmg) const
  709. {
  710. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  711. TDmgRange ret = calculateDmgRange(bai);
  712. if(retaliationDmg)
  713. {
  714. if(bai.shooting)
  715. {
  716. //FIXME: handle RANGED_RETALIATION
  717. retaliationDmg->first = retaliationDmg->second = 0;
  718. }
  719. else
  720. {
  721. //TODO: rewrite using boost::numeric::interval
  722. //TODO: rewire once more using interval-based fuzzy arithmetic
  723. int64_t TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  724. for (int i=0; i<2; ++i)
  725. {
  726. auto retaliationAttack = bai.reverse();
  727. int64_t dmg = ret.*pairElems[i];
  728. auto state = retaliationAttack.attacker->acquireState();
  729. state->damage(dmg);
  730. retaliationAttack.attacker = state.get();
  731. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  732. }
  733. }
  734. }
  735. return ret;
  736. }
  737. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  738. {
  739. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  740. RETURN_IF_NOT_BATTLE(obstacles);
  741. for(auto & obs : battleGetAllObstacles())
  742. {
  743. if(vstd::contains(obs->getBlockedTiles(), tile)
  744. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  745. {
  746. obstacles.push_back(obs);
  747. }
  748. }
  749. return obstacles;
  750. }
  751. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const CStack * stack) const
  752. {
  753. std::vector<std::shared_ptr<const CObstacleInstance>> affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  754. RETURN_IF_NOT_BATTLE(affectedObstacles);
  755. if(stack->alive())
  756. {
  757. affectedObstacles = battleGetAllObstaclesOnPos(stack->getPosition(), false);
  758. if(stack->doubleWide())
  759. {
  760. BattleHex otherHex = stack->occupiedHex(stack->getPosition());
  761. if(otherHex.isValid())
  762. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  763. affectedObstacles.push_back(i);
  764. }
  765. for(auto hex : stack->getHexes())
  766. if(hex == ESiegeHex::GATE_BRIDGE)
  767. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  768. for(int i=0; i<affectedObstacles.size(); i++)
  769. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  770. affectedObstacles.erase(affectedObstacles.begin()+i);
  771. }
  772. return affectedObstacles;
  773. }
  774. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  775. {
  776. AccessibilityInfo ret;
  777. ret.fill(EAccessibility::ACCESSIBLE);
  778. //removing accessibility for side columns of hexes
  779. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  780. {
  781. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  782. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  783. }
  784. //special battlefields with logically unavailable tiles
  785. std::vector<BattleHex> impassableHexes;
  786. if(battleGetBattlefieldType().num == BFieldType::SHIP_TO_SHIP)
  787. {
  788. impassableHexes =
  789. {
  790. 6, 7, 8, 9,
  791. 24, 25, 26,
  792. 58, 59, 60,
  793. 75, 76, 77,
  794. 92, 93, 94,
  795. 109, 110, 111,
  796. 126, 127, 128,
  797. 159, 160, 161, 162, 163,
  798. 176, 177, 178, 179, 180
  799. };
  800. }
  801. for(auto hex : impassableHexes)
  802. ret[hex] = EAccessibility::UNAVAILABLE;
  803. //gate -> should be before stacks
  804. if(battleGetSiegeLevel() > 0)
  805. {
  806. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  807. switch(battleGetGateState())
  808. {
  809. case EGateState::CLOSED:
  810. accessability = EAccessibility::GATE;
  811. break;
  812. case EGateState::BLOCKED:
  813. accessability = EAccessibility::UNAVAILABLE;
  814. break;
  815. }
  816. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  817. }
  818. //tiles occupied by standing stacks
  819. for(auto unit : battleAliveUnits())
  820. {
  821. for(auto hex : unit->getHexes())
  822. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  823. ret[hex] = EAccessibility::ALIVE_STACK;
  824. }
  825. //obstacles
  826. for(const auto &obst : battleGetAllObstacles())
  827. {
  828. for(auto hex : obst->getBlockedTiles())
  829. ret[hex] = EAccessibility::OBSTACLE;
  830. }
  831. //walls
  832. if(battleGetSiegeLevel() > 0)
  833. {
  834. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  835. for(auto hex : permanentlyLocked)
  836. ret[hex] = EAccessibility::UNAVAILABLE;
  837. //TODO likely duplicated logic
  838. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  839. {
  840. //which part of wall, which hex is blocked if this part of wall is not destroyed
  841. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  842. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  843. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  844. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  845. };
  846. for(auto & elem : lockedIfNotDestroyed)
  847. {
  848. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  849. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  850. }
  851. }
  852. return ret;
  853. }
  854. AccessibilityInfo CBattleInfoCallback::getAccesibility(const battle::Unit * stack) const
  855. {
  856. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  857. }
  858. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  859. {
  860. auto ret = getAccesibility();
  861. for(auto hex : accessibleHexes)
  862. if(hex.isValid())
  863. ret[hex] = EAccessibility::ACCESSIBLE;
  864. return ret;
  865. }
  866. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  867. {
  868. ReachabilityInfo ret;
  869. ret.accessibility = accessibility;
  870. ret.params = params;
  871. ret.predecessors.fill(BattleHex::INVALID);
  872. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  873. if(!params.startPosition.isValid()) //if got call for arrow turrets
  874. return ret;
  875. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  876. std::queue<BattleHex> hexq; //bfs queue
  877. //first element
  878. hexq.push(params.startPosition);
  879. ret.distances[params.startPosition] = 0;
  880. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache;
  881. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  882. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  883. while(!hexq.empty()) //bfs loop
  884. {
  885. const BattleHex curHex = hexq.front();
  886. hexq.pop();
  887. //walking stack can't step past the quicksands
  888. //TODO what if second hex of two-hex creature enters quicksand
  889. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  890. continue;
  891. const int costToNeighbour = ret.distances[curHex.hex] + 1;
  892. for(BattleHex neighbour : BattleHex::neighbouringTilesCache[curHex.hex])
  893. {
  894. if(neighbour.isValid())
  895. {
  896. const int costFoundSoFar = ret.distances[neighbour.hex];
  897. if(accessibleCache[neighbour.hex] && costToNeighbour < costFoundSoFar)
  898. {
  899. hexq.push(neighbour);
  900. ret.distances[neighbour.hex] = costToNeighbour;
  901. ret.predecessors[neighbour.hex] = curHex;
  902. }
  903. }
  904. }
  905. }
  906. return ret;
  907. }
  908. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  909. {
  910. std::set<BattleHex> ret;
  911. RETURN_IF_NOT_BATTLE(ret);
  912. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  913. {
  914. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  915. {
  916. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  917. }
  918. }
  919. return ret;
  920. }
  921. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  922. {
  923. auto reachability = getReachability(closest);
  924. auto avHexes = battleGetAvailableHexes(reachability, closest);
  925. // I hate std::pairs with their undescriptive member names first / second
  926. struct DistStack
  927. {
  928. int distanceToPred;
  929. BattleHex destination;
  930. const battle::Unit * stack;
  931. };
  932. std::vector<DistStack> stackPairs;
  933. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  934. {
  935. return unit->isValidTarget(false) && unit != closest;
  936. });
  937. for(const battle::Unit * st : possible)
  938. {
  939. for(BattleHex hex : avHexes)
  940. if(CStack::isMeleeAttackPossible(closest, st, hex))
  941. {
  942. DistStack hlp = {reachability.distances[hex], hex, st};
  943. stackPairs.push_back(hlp);
  944. }
  945. }
  946. if (stackPairs.size())
  947. {
  948. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  949. auto minimal = boost::min_element(stackPairs, comparator);
  950. return std::make_pair(minimal->stack, minimal->destination);
  951. }
  952. else
  953. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  954. }
  955. BattleHex CBattleInfoCallback::getAvaliableHex(CreatureID creID, ui8 side, int initialPos) const
  956. {
  957. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  958. //bool flying = VLC->creh->creatures[creID]->isFlying();
  959. int pos;
  960. if (initialPos > -1)
  961. pos = initialPos;
  962. else //summon elementals depending on player side
  963. {
  964. if(side == BattleSide::ATTACKER)
  965. pos = 0; //top left
  966. else
  967. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  968. }
  969. auto accessibility = getAccesibility();
  970. std::set<BattleHex> occupyable;
  971. for(int i = 0; i < accessibility.size(); i++)
  972. if(accessibility.accessible(i, twoHex, side))
  973. occupyable.insert(i);
  974. if(occupyable.empty())
  975. {
  976. return BattleHex::INVALID; //all tiles are covered
  977. }
  978. return BattleHex::getClosestTile(side, pos, occupyable);
  979. }
  980. si8 CBattleInfoCallback::battleGetTacticDist() const
  981. {
  982. RETURN_IF_NOT_BATTLE(0);
  983. //TODO get rid of this method
  984. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  985. return battleTacticDist();
  986. return 0;
  987. }
  988. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  989. {
  990. RETURN_IF_NOT_BATTLE(false);
  991. auto side = battleGetTacticsSide();
  992. auto dist = battleGetTacticDist();
  993. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  994. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  995. }
  996. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  997. {
  998. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  999. if(!battleDoWeKnowAbout(unit->unitSide()))
  1000. {
  1001. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1002. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1003. params.perspective = battleGetMySide();
  1004. }
  1005. return getReachability(params);
  1006. }
  1007. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1008. {
  1009. if(params.flying)
  1010. return getFlyingReachability(params);
  1011. else
  1012. return makeBFS(getAccesibility(params.knownAccessible), params);
  1013. }
  1014. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  1015. {
  1016. ReachabilityInfo ret;
  1017. ret.accessibility = getAccesibility(params.knownAccessible);
  1018. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1019. {
  1020. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  1021. {
  1022. ret.predecessors[i] = params.startPosition;
  1023. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1024. }
  1025. }
  1026. return ret;
  1027. }
  1028. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1029. {
  1030. //does not return hex attacked directly
  1031. //TODO: apply rotation to two-hex attackers
  1032. bool isAttacker = attacker->side == BattleSide::ATTACKER;
  1033. AttackableTiles at;
  1034. RETURN_IF_NOT_BATTLE(at);
  1035. const int WN = GameConstants::BFIELD_WIDTH;
  1036. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1037. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  1038. bool reverse = isToReverse(hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  1039. if(reverse && attacker->doubleWide())
  1040. {
  1041. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  1042. }
  1043. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  1044. {
  1045. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  1046. }
  1047. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  1048. {
  1049. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1050. for(BattleHex tile : hexes)
  1051. {
  1052. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  1053. {
  1054. const CStack * st = battleGetStackByPos(tile, true);
  1055. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1056. {
  1057. at.hostileCreaturePositions.insert(tile);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  1063. {
  1064. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  1065. for(int i = 0; i<hexes.size(); i++)
  1066. {
  1067. if(hexes.at(i) == hex)
  1068. {
  1069. hexes.erase(hexes.begin() + i);
  1070. i = 0;
  1071. }
  1072. }
  1073. for(BattleHex tile : hexes)
  1074. {
  1075. //friendly stacks can also be damaged by Dragon Breath
  1076. if(battleGetStackByPos(tile, true))
  1077. {
  1078. if(battleGetStackByPos(tile, true) != attacker)
  1079. at.friendlyCreaturePositions.insert(tile);
  1080. }
  1081. }
  1082. }
  1083. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition(destinationTile, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  1084. {
  1085. std::vector<BattleHex> hexes; //only one, in fact
  1086. int pseudoVector = destinationTile.hex - hex;
  1087. switch(pseudoVector)
  1088. {
  1089. case 1:
  1090. case -1:
  1091. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  1092. break;
  1093. case WN: //17 //left-down or right-down
  1094. case -WN: //-17 //left-up or right-up
  1095. case WN + 1: //18 //right-down
  1096. case -WN + 1: //-16 //right-up
  1097. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : -1), hexes);
  1098. break;
  1099. case WN - 1: //16 //left-down
  1100. case -WN - 1: //-18 //left-up
  1101. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : 0), hexes);
  1102. break;
  1103. }
  1104. for(BattleHex tile : hexes)
  1105. {
  1106. //friendly stacks can also be damaged by Dragon Breath
  1107. if(battleGetStackByPos(tile, true))
  1108. at.friendlyCreaturePositions.insert(tile);
  1109. }
  1110. }
  1111. return at;
  1112. }
  1113. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const CStack * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1114. {
  1115. //does not return hex attacked directly
  1116. AttackableTiles at;
  1117. RETURN_IF_NOT_BATTLE(at);
  1118. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1119. {
  1120. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1121. targetHexes.push_back(destinationTile);
  1122. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1123. }
  1124. return at;
  1125. }
  1126. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1127. {
  1128. std::set<const CStack*> attackedCres;
  1129. RETURN_IF_NOT_BATTLE(attackedCres);
  1130. AttackableTiles at;
  1131. if(rangedAttack)
  1132. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1133. else
  1134. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1135. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1136. {
  1137. const CStack * st = battleGetStackByPos(tile, true);
  1138. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1139. {
  1140. attackedCres.insert(st);
  1141. }
  1142. }
  1143. for (BattleHex tile : at.friendlyCreaturePositions)
  1144. {
  1145. const CStack * st = battleGetStackByPos(tile, true);
  1146. if(st) //friendly stacks can also be damaged by Dragon Breath
  1147. {
  1148. attackedCres.insert(st);
  1149. }
  1150. }
  1151. return attackedCres;
  1152. }
  1153. //TODO: this should apply also to mechanics and cursor interface
  1154. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1155. {
  1156. int fromX = hexFrom.getX();
  1157. int fromY = hexFrom.getY();
  1158. int toX = hexTo.getX();
  1159. int toY = hexTo.getY();
  1160. if (curDir) // attacker, facing right
  1161. {
  1162. if (fromX < toX)
  1163. return false;
  1164. if (fromX > toX)
  1165. return true;
  1166. if (fromY % 2 == 0 && toY % 2 == 1)
  1167. return true;
  1168. return false;
  1169. }
  1170. else // defender, facing left
  1171. {
  1172. if(fromX < toX)
  1173. return true;
  1174. if(fromX > toX)
  1175. return false;
  1176. if (fromY % 2 == 1 && toY % 2 == 0)
  1177. return true;
  1178. return false;
  1179. }
  1180. }
  1181. //TODO: this should apply also to mechanics and cursor interface
  1182. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1183. {
  1184. if (hexTo < 0 || hexFrom < 0) //turret
  1185. return false;
  1186. if (toDoubleWide)
  1187. {
  1188. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1189. {
  1190. if (toDir)
  1191. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1192. else
  1193. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1194. }
  1195. return false;
  1196. }
  1197. else
  1198. {
  1199. return isToReverseHlp(hexFrom, hexTo, curDir);
  1200. }
  1201. }
  1202. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1203. {
  1204. ReachabilityInfo::TDistances ret;
  1205. ret.fill(-1);
  1206. RETURN_IF_NOT_BATTLE(ret);
  1207. auto reachability = getReachability(unit);
  1208. boost::copy(reachability.distances, ret.begin());
  1209. return ret;
  1210. }
  1211. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1212. {
  1213. RETURN_IF_NOT_BATTLE(false);
  1214. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1215. static const auto selectorNoDistancePenalty = Selector::type(Bonus::NO_DISTANCE_PENALTY);
  1216. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1217. return false;
  1218. if(auto target = battleGetUnitByPos(destHex, true))
  1219. {
  1220. //If any hex of target creature is within range, there is no penalty
  1221. for(auto hex : target->getHexes())
  1222. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1223. return false;
  1224. //TODO what about two-hex shooters?
  1225. }
  1226. else
  1227. {
  1228. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1229. return false;
  1230. }
  1231. return true;
  1232. }
  1233. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1234. {
  1235. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1236. return WallPartToHex(part);
  1237. }
  1238. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1239. {
  1240. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1241. return hexToWallPart(hex);
  1242. }
  1243. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1244. {
  1245. RETURN_IF_NOT_BATTLE(false);
  1246. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1247. wallPart != EWallPart::INVALID;
  1248. }
  1249. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1250. {
  1251. std::vector<BattleHex> attackableBattleHexes;
  1252. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1253. for(auto & wallPartPair : wallParts)
  1254. {
  1255. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1256. {
  1257. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1258. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1259. {
  1260. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1261. }
  1262. }
  1263. }
  1264. return attackableBattleHexes;
  1265. }
  1266. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1267. {
  1268. RETURN_IF_NOT_BATTLE(-1);
  1269. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1270. ui32 ret = caster->getSpellCost(sp);
  1271. //checking for friendly stacks reducing cost of the spell and
  1272. //enemy stacks increasing it
  1273. si32 manaReduction = 0;
  1274. si32 manaIncrease = 0;
  1275. for(auto unit : battleAliveUnits())
  1276. {
  1277. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1278. {
  1279. vstd::amax(manaReduction, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1280. }
  1281. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1282. {
  1283. vstd::amax(manaIncrease, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1284. }
  1285. }
  1286. return ret - manaReduction + manaIncrease;
  1287. }
  1288. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1289. {
  1290. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1291. }
  1292. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1293. {
  1294. RETURN_IF_NOT_BATTLE(false);
  1295. if(unit->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1296. return false;
  1297. for(auto adjacent : battleAdjacentUnits(unit))
  1298. {
  1299. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1300. return true;
  1301. }
  1302. return false;
  1303. }
  1304. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1305. {
  1306. std::set<const battle::Unit *> ret;
  1307. RETURN_IF_NOT_BATTLE(ret);
  1308. for(auto hex : unit->getSurroundingHexes())
  1309. {
  1310. if(auto neighbour = battleGetUnitByPos(hex, true))
  1311. ret.insert(neighbour);
  1312. }
  1313. return ret;
  1314. }
  1315. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1316. {
  1317. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1318. //This is complete list. No spells from mods.
  1319. //todo: this should be Spellbook of caster Stack
  1320. static const std::set<SpellID> allPossibleSpells =
  1321. {
  1322. SpellID::AIR_SHIELD,
  1323. SpellID::ANTI_MAGIC,
  1324. SpellID::BLESS,
  1325. SpellID::BLOODLUST,
  1326. SpellID::COUNTERSTRIKE,
  1327. SpellID::CURE,
  1328. SpellID::FIRE_SHIELD,
  1329. SpellID::FORTUNE,
  1330. SpellID::HASTE,
  1331. SpellID::MAGIC_MIRROR,
  1332. SpellID::MIRTH,
  1333. SpellID::PRAYER,
  1334. SpellID::PRECISION,
  1335. SpellID::PROTECTION_FROM_AIR,
  1336. SpellID::PROTECTION_FROM_EARTH,
  1337. SpellID::PROTECTION_FROM_FIRE,
  1338. SpellID::PROTECTION_FROM_WATER,
  1339. SpellID::SHIELD,
  1340. SpellID::SLAYER,
  1341. SpellID::STONE_SKIN
  1342. };
  1343. std::vector<SpellID> beneficialSpells;
  1344. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1345. {
  1346. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1347. {
  1348. return pred(stack) && stack->owner != subject->owner && stack->isValidTarget(false);
  1349. });
  1350. if(stacks.empty())
  1351. return nullptr;
  1352. else
  1353. return stacks.front();
  1354. };
  1355. for(const SpellID spellID : allPossibleSpells)
  1356. {
  1357. std::stringstream cachingStr;
  1358. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1359. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1360. //TODO: this ability has special limitations
  1361. || !(spellID.toSpell()->canBeCast(this, spells::Mode::CREATURE_ACTIVE, subject)))
  1362. continue;
  1363. switch (spellID)
  1364. {
  1365. case SpellID::SHIELD:
  1366. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1367. {
  1368. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1369. {
  1370. return !stack->canShoot();
  1371. });
  1372. if (!walker)
  1373. continue;
  1374. }
  1375. break;
  1376. case SpellID::AIR_SHIELD: //only against active shooters
  1377. {
  1378. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1379. {
  1380. return stack->canShoot();
  1381. });
  1382. if (!shooter)
  1383. continue;
  1384. }
  1385. break;
  1386. case SpellID::ANTI_MAGIC:
  1387. case SpellID::MAGIC_MIRROR:
  1388. case SpellID::PROTECTION_FROM_AIR:
  1389. case SpellID::PROTECTION_FROM_EARTH:
  1390. case SpellID::PROTECTION_FROM_FIRE:
  1391. case SpellID::PROTECTION_FROM_WATER:
  1392. {
  1393. const ui8 enemySide = 1 - subject->side;
  1394. //todo: only if enemy has spellbook
  1395. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1396. continue;
  1397. }
  1398. break;
  1399. case SpellID::CURE: //only damaged units
  1400. {
  1401. //do not cast on affected by debuffs
  1402. if(!subject->canBeHealed())
  1403. continue;
  1404. }
  1405. break;
  1406. case SpellID::BLOODLUST:
  1407. {
  1408. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1409. continue;
  1410. }
  1411. break;
  1412. case SpellID::PRECISION:
  1413. {
  1414. if(!subject->canShoot())
  1415. continue;
  1416. }
  1417. break;
  1418. case SpellID::SLAYER://only if monsters are present
  1419. {
  1420. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1421. {
  1422. const auto isKing = Selector::type(Bonus::KING1)
  1423. .Or(Selector::type(Bonus::KING2))
  1424. .Or(Selector::type(Bonus::KING3));
  1425. return stack->hasBonus(isKing);
  1426. });
  1427. if (!kingMonster)
  1428. continue;
  1429. }
  1430. break;
  1431. }
  1432. beneficialSpells.push_back(spellID);
  1433. }
  1434. if(!beneficialSpells.empty())
  1435. {
  1436. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1437. }
  1438. else
  1439. {
  1440. return SpellID::NONE;
  1441. }
  1442. }
  1443. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1444. {
  1445. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1446. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1447. if (!bl->size())
  1448. return SpellID::NONE;
  1449. int totalWeight = 0;
  1450. for(auto b : *bl)
  1451. {
  1452. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1453. }
  1454. int randomPos = rand.nextInt(totalWeight - 1);
  1455. for(auto b : *bl)
  1456. {
  1457. randomPos -= std::max(b->additionalInfo, 1);
  1458. if(randomPos < 0)
  1459. {
  1460. return SpellID(b->subtype);
  1461. }
  1462. }
  1463. return SpellID::NONE;
  1464. }
  1465. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1466. {
  1467. RETURN_IF_NOT_BATTLE(-3);
  1468. if(!battleCanSurrender(Player))
  1469. return -1;
  1470. const auto sideOpt = playerToSide(Player);
  1471. if(!sideOpt)
  1472. return -1;
  1473. const auto side = sideOpt.get();
  1474. int ret = 0;
  1475. double discount = 0;
  1476. for(auto unit : battleAliveUnits(side))
  1477. ret += unit->getRawSurrenderCost();
  1478. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1479. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1480. ret *= (100.0 - discount) / 100.0;
  1481. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1482. return ret;
  1483. }
  1484. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1485. {
  1486. const IBonusBearer * node = nullptr;
  1487. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1488. node = h;
  1489. else
  1490. node = getBattleNode();
  1491. if(!node)
  1492. return 0;
  1493. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_BELOW));
  1494. if(b->size())
  1495. return b->totalValue();
  1496. return 0;
  1497. }
  1498. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1499. {
  1500. const IBonusBearer *node = nullptr;
  1501. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1502. node = h;
  1503. else
  1504. node = getBattleNode();
  1505. if(!node)
  1506. return GameConstants::SPELL_LEVELS;
  1507. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1508. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1509. if(b->size())
  1510. return b->totalValue();
  1511. return GameConstants::SPELL_LEVELS;
  1512. }
  1513. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1514. {
  1515. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1516. {
  1517. return unit->alive() && !unit->isTurret() && unit->alive();
  1518. });
  1519. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1520. for(auto & unit : units)
  1521. {
  1522. //todo: move SIEGE_WEAPON check to Unit state
  1523. if(!unit->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1524. {
  1525. hasUnit.at(unit->unitSide()) = true;
  1526. }
  1527. if(hasUnit[0] && hasUnit[1])
  1528. break;
  1529. }
  1530. if(!hasUnit[0] && !hasUnit[1])
  1531. return 2;
  1532. if(!hasUnit[1])
  1533. return 0;
  1534. if(!hasUnit[0])
  1535. return 1;
  1536. return boost::none;
  1537. }