2
0

CBattleCallback.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  1. #include "StdInc.h"
  2. #include "CBattleCallback.h"
  3. #include "BattleState.h"
  4. #include "CGameState.h"
  5. #include "NetPacks.h"
  6. #include "spells/CSpellHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "CTownHandler.h"
  9. #include "mapObjects/CGTownInstance.h"
  10. /*
  11. * CBattleCallback.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. #define RETURN_IF_NOT_BATTLE(X) if(!duringBattle()) {logGlobal->errorStream() << __FUNCTION__ << " called when no battle!"; return X; }
  20. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  21. {
  22. static void retreiveTurretDamageRange(const CGTownInstance * town, const CStack *turret, double &outMinDmg, double &outMaxDmg)
  23. {
  24. assert(turret->getCreature()->idNumber == CreatureID::ARROW_TOWERS);
  25. assert(town);
  26. assert(turret->position >= -4 && turret->position <= -2);
  27. float multiplier = (turret->position == -2) ? 1 : 0.5;
  28. int baseMin = 6;
  29. int baseMax = 10;
  30. outMinDmg = multiplier * (baseMin + town->getTownLevel() * 2);
  31. outMaxDmg = multiplier * (baseMax + town->getTownLevel() * 3);
  32. }
  33. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  34. {
  35. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  36. return lineToHex[line];
  37. }
  38. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  39. {
  40. const int wallInStackLine = lineToWallHex(pos1.getY());
  41. const int wallInDestLine = lineToWallHex(pos2.getY());
  42. const bool stackLeft = pos1 < wallInStackLine;
  43. const bool destLeft = pos2 < wallInDestLine;
  44. return stackLeft == destLeft;
  45. }
  46. // parts of wall
  47. static const std::pair<int, EWallPart::EWallPart> wallParts[] =
  48. {
  49. std::make_pair(50, EWallPart::KEEP),
  50. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  51. std::make_pair(182, EWallPart::BOTTOM_WALL),
  52. std::make_pair(130, EWallPart::BELOW_GATE),
  53. std::make_pair(78, EWallPart::OVER_GATE),
  54. std::make_pair(29, EWallPart::UPPER_WALL),
  55. std::make_pair(12, EWallPart::UPPER_TOWER),
  56. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  57. std::make_pair(96, EWallPart::GATE),
  58. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  59. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  60. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  61. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  62. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  63. };
  64. static EWallPart::EWallPart hexToWallPart(BattleHex hex)
  65. {
  66. for(auto & elem : wallParts)
  67. {
  68. if(elem.first == hex)
  69. return elem.second;
  70. }
  71. return EWallPart::INVALID; //not found!
  72. }
  73. static BattleHex WallPartToHex(EWallPart::EWallPart part)
  74. {
  75. for(auto & elem : wallParts)
  76. {
  77. if(elem.second == part)
  78. return elem.first;
  79. }
  80. return BattleHex::INVALID; //not found!
  81. }
  82. }
  83. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  84. boost::shared_mutex& CCallbackBase::getGsMutex()
  85. {
  86. return *gs->mx;
  87. }
  88. bool CCallbackBase::duringBattle() const
  89. {
  90. return getBattle() != nullptr;
  91. }
  92. void CCallbackBase::setBattle(const BattleInfo *B)
  93. {
  94. battle = B;
  95. }
  96. boost::optional<PlayerColor> CCallbackBase::getPlayerID() const
  97. {
  98. return player;
  99. }
  100. ETerrainType CBattleInfoEssentials::battleTerrainType() const
  101. {
  102. RETURN_IF_NOT_BATTLE(ETerrainType::WRONG);
  103. return getBattle()->terrainType;
  104. }
  105. BFieldType CBattleInfoEssentials::battleGetBattlefieldType() const
  106. {
  107. RETURN_IF_NOT_BATTLE(BFieldType::NONE);
  108. return getBattle()->battlefieldType;
  109. }
  110. std::vector<std::shared_ptr<const CObstacleInstance> > CBattleInfoEssentials::battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective /*= boost::none*/) const
  111. {
  112. std::vector<std::shared_ptr<const CObstacleInstance> > ret;
  113. RETURN_IF_NOT_BATTLE(ret);
  114. if(!perspective)
  115. {
  116. //if no particular perspective request, use default one
  117. perspective = battleGetMySide();
  118. }
  119. else
  120. {
  121. if(!!player && *perspective != battleGetMySide())
  122. {
  123. logGlobal->errorStream() << "Unauthorized access attempt!";
  124. assert(0); //I want to notice if that happens
  125. //perspective = battleGetMySide();
  126. }
  127. }
  128. for(auto oi : getBattle()->obstacles)
  129. {
  130. if(getBattle()->battleIsObstacleVisibleForSide(*oi, *perspective))
  131. ret.push_back(oi);
  132. }
  133. return ret;
  134. }
  135. bool CBattleInfoEssentials::battleIsObstacleVisibleForSide(const CObstacleInstance & coi, BattlePerspective::BattlePerspective side) const
  136. {
  137. RETURN_IF_NOT_BATTLE(false);
  138. return side == BattlePerspective::ALL_KNOWING || coi.visibleForSide(side, battleHasNativeStack(side));
  139. }
  140. bool CBattleInfoEssentials::battleHasNativeStack(ui8 side) const
  141. {
  142. RETURN_IF_NOT_BATTLE(false);
  143. for(const CStack *s : battleGetAllStacks())
  144. {
  145. if(s->attackerOwned == !side && s->getCreature()->isItNativeTerrain(getBattle()->terrainType))
  146. return true;
  147. }
  148. return false;
  149. }
  150. TStacks CBattleInfoEssentials::battleGetAllStacks(bool includeTurrets /*= false*/) const
  151. {
  152. return battleGetStacksIf([=](const CStack * s)
  153. {
  154. return !s->isGhost() && (includeTurrets || !s->isTurret());
  155. });
  156. }
  157. TStacks CBattleInfoEssentials::battleGetStacksIf(TStackFilter predicate) const
  158. {
  159. TStacks ret;
  160. RETURN_IF_NOT_BATTLE(ret);
  161. vstd::copy_if(getBattle()->stacks, std::back_inserter(ret), predicate);
  162. return ret;
  163. }
  164. TStacks CBattleInfoEssentials::battleAliveStacks() const
  165. {
  166. return battleGetStacksIf([](const CStack * s){
  167. return s->isValidTarget(false);
  168. });
  169. }
  170. TStacks CBattleInfoEssentials::battleAliveStacks(ui8 side) const
  171. {
  172. return battleGetStacksIf([=](const CStack * s){
  173. return s->isValidTarget(false) && s->attackerOwned == !side;
  174. });
  175. }
  176. int CBattleInfoEssentials::battleGetMoatDmg() const
  177. {
  178. RETURN_IF_NOT_BATTLE(0);
  179. auto town = getBattle()->town;
  180. if(!town)
  181. return 0;
  182. return town->town->moatDamage;
  183. }
  184. const CGTownInstance * CBattleInfoEssentials::battleGetDefendedTown() const
  185. {
  186. RETURN_IF_NOT_BATTLE(nullptr);
  187. if(!getBattle() || getBattle()->town == nullptr)
  188. return nullptr;
  189. return getBattle()->town;
  190. }
  191. BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const
  192. {
  193. RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID);
  194. if(!player)
  195. return BattlePerspective::ALL_KNOWING;
  196. if(*player == getBattle()->sides[0].color)
  197. return BattlePerspective::LEFT_SIDE;
  198. if(*player == getBattle()->sides[1].color)
  199. return BattlePerspective::RIGHT_SIDE;
  200. logGlobal->errorStream() << "Cannot find player " << *player << " in battle!";
  201. return BattlePerspective::INVALID;
  202. }
  203. const CStack * CBattleInfoEssentials::battleActiveStack() const
  204. {
  205. RETURN_IF_NOT_BATTLE(nullptr);
  206. return battleGetStackByID(getBattle()->activeStack);
  207. }
  208. const CStack* CBattleInfoEssentials::battleGetStackByID(int ID, bool onlyAlive) const
  209. {
  210. RETURN_IF_NOT_BATTLE(nullptr);
  211. auto stacks = battleGetStacksIf([=](const CStack * s)
  212. {
  213. return s->ID == ID && (!onlyAlive || s->alive());
  214. });
  215. if(stacks.empty())
  216. return nullptr;
  217. else
  218. return stacks[0];
  219. }
  220. bool CBattleInfoEssentials::battleDoWeKnowAbout(ui8 side) const
  221. {
  222. RETURN_IF_NOT_BATTLE(false);
  223. auto p = battleGetMySide();
  224. return p == BattlePerspective::ALL_KNOWING || p == side;
  225. }
  226. si8 CBattleInfoEssentials::battleTacticDist() const
  227. {
  228. RETURN_IF_NOT_BATTLE(0);
  229. return getBattle()->tacticDistance;
  230. }
  231. si8 CBattleInfoEssentials::battleGetTacticsSide() const
  232. {
  233. RETURN_IF_NOT_BATTLE(-1);
  234. return getBattle()->tacticsSide;
  235. }
  236. const CGHeroInstance * CBattleInfoEssentials::battleGetFightingHero(ui8 side) const
  237. {
  238. RETURN_IF_NOT_BATTLE(nullptr);
  239. if(side > 1)
  240. {
  241. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
  242. return nullptr;
  243. }
  244. if(!battleDoWeKnowAbout(side))
  245. {
  246. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
  247. return nullptr;
  248. }
  249. return getBattle()->sides[side].hero;
  250. }
  251. const CArmedInstance * CBattleInfoEssentials::battleGetArmyObject(ui8 side) const
  252. {
  253. RETURN_IF_NOT_BATTLE(nullptr);
  254. if(side > 1)
  255. {
  256. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
  257. return nullptr;
  258. }
  259. if(!battleDoWeKnowAbout(side))
  260. {
  261. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
  262. return nullptr;
  263. }
  264. return getBattle()->sides[side].armyObject;
  265. }
  266. InfoAboutHero CBattleInfoEssentials::battleGetHeroInfo( ui8 side ) const
  267. {
  268. auto hero = getBattle()->sides[side].hero;
  269. if(!hero)
  270. {
  271. logGlobal->warnStream() << __FUNCTION__ << ": side " << (int)side << " does not have hero!";
  272. return InfoAboutHero();
  273. }
  274. InfoAboutHero::EInfoLevel infoLevel = battleDoWeKnowAbout(side) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC;
  275. return InfoAboutHero(hero, infoLevel);
  276. }
  277. int CBattleInfoEssentials::battleCastSpells(ui8 side) const
  278. {
  279. RETURN_IF_NOT_BATTLE(-1);
  280. return getBattle()->sides[side].castSpellsCount;
  281. }
  282. const IBonusBearer * CBattleInfoEssentials::getBattleNode() const
  283. {
  284. return getBattle();
  285. }
  286. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const ISpellCaster * caster, ECastingMode::ECastingMode mode) const
  287. {
  288. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  289. if(caster == nullptr)
  290. {
  291. logGlobal->errorStream() << "CBattleInfoCallback::battleCanCastSpell: no spellcaster.";
  292. return ESpellCastProblem::INVALID;
  293. }
  294. const PlayerColor player = caster->getOwner();
  295. const ui8 side = playerToSide(player);
  296. if(!battleDoWeKnowAbout(side))
  297. {
  298. logGlobal->warnStream() << "You can't check if enemy can cast given spell!";
  299. return ESpellCastProblem::INVALID;
  300. }
  301. if(battleTacticDist())
  302. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  303. switch (mode)
  304. {
  305. case ECastingMode::HERO_CASTING:
  306. {
  307. if(battleCastSpells(side) > 0)
  308. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  309. auto hero = dynamic_cast<const CGHeroInstance *>(caster);
  310. if(!hero)
  311. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  312. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  313. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  314. }
  315. break;
  316. default:
  317. break;
  318. }
  319. return ESpellCastProblem::OK;
  320. }
  321. bool CBattleInfoEssentials::battleCanFlee(PlayerColor player) const
  322. {
  323. RETURN_IF_NOT_BATTLE(false);
  324. ui8 mySide = playerToSide(player);
  325. const CGHeroInstance *myHero = battleGetFightingHero(mySide);
  326. //current player have no hero
  327. if(!myHero)
  328. return false;
  329. //eg. one of heroes is wearing shakles of war
  330. if(myHero->hasBonusOfType(Bonus::BATTLE_NO_FLEEING))
  331. return false;
  332. //we are besieged defender
  333. if(mySide == BattleSide::DEFENDER && battleGetSiegeLevel())
  334. {
  335. auto town = battleGetDefendedTown();
  336. if(!town->hasBuilt(BuildingID::ESCAPE_TUNNEL, ETownType::STRONGHOLD))
  337. return false;
  338. }
  339. return true;
  340. }
  341. ui8 CBattleInfoEssentials::playerToSide(PlayerColor player) const
  342. {
  343. RETURN_IF_NOT_BATTLE(-1);
  344. int ret = vstd::find_pos_if(getBattle()->sides, [=](const SideInBattle &side){ return side.color == player; });
  345. if(ret < 0)
  346. logGlobal->warnStream() << "Cannot find side for player " << player;
  347. return ret;
  348. }
  349. bool CBattleInfoEssentials::playerHasAccessToHeroInfo(PlayerColor player, const CGHeroInstance * h) const
  350. {
  351. RETURN_IF_NOT_BATTLE(false);
  352. ui8 playerSide = playerToSide(player);
  353. if (playerSide != (ui8)-1)
  354. {
  355. if (getBattle()->sides[!playerSide].hero == h)
  356. return true;
  357. }
  358. return false;
  359. }
  360. ui8 CBattleInfoEssentials::battleGetSiegeLevel() const
  361. {
  362. RETURN_IF_NOT_BATTLE(0);
  363. return getBattle()->town ? getBattle()->town->fortLevel() : CGTownInstance::NONE;
  364. }
  365. bool CBattleInfoEssentials::battleCanSurrender(PlayerColor player) const
  366. {
  367. RETURN_IF_NOT_BATTLE(false);
  368. ui8 mySide = playerToSide(player);
  369. bool iAmSiegeDefender = ( mySide == BattleSide::DEFENDER && battleGetSiegeLevel() );
  370. //conditions like for fleeing (except escape tunnel presence) + enemy must have a hero
  371. return battleCanFlee(player) && !iAmSiegeDefender && battleHasHero(!mySide);
  372. }
  373. bool CBattleInfoEssentials::battleHasHero(ui8 side) const
  374. {
  375. RETURN_IF_NOT_BATTLE(false);
  376. assert(side < 2);
  377. return getBattle()->sides[side].hero;
  378. }
  379. si8 CBattleInfoEssentials::battleGetWallState(int partOfWall) const
  380. {
  381. RETURN_IF_NOT_BATTLE(0);
  382. if(getBattle()->town == nullptr || getBattle()->town->fortLevel() == CGTownInstance::NONE)
  383. return EWallState::NONE;
  384. assert(partOfWall >= 0 && partOfWall < EWallPart::PARTS_COUNT);
  385. return getBattle()->si.wallState[partOfWall];
  386. }
  387. EGateState CBattleInfoEssentials::battleGetGateState() const
  388. {
  389. RETURN_IF_NOT_BATTLE(EGateState::NONE);
  390. if(getBattle()->town == nullptr || getBattle()->town->fortLevel() == CGTownInstance::NONE)
  391. return EGateState::NONE;
  392. return getBattle()->si.gateState;
  393. }
  394. PlayerColor CBattleInfoEssentials::battleGetOwner(const CStack * stack) const
  395. {
  396. RETURN_IF_NOT_BATTLE(PlayerColor::CANNOT_DETERMINE);
  397. if(stack->hasBonusOfType(Bonus::HYPNOTIZED))
  398. return getBattle()->theOtherPlayer(stack->owner);
  399. else
  400. return stack->owner;
  401. }
  402. const CGHeroInstance * CBattleInfoEssentials::battleGetOwnerHero(const CStack * stack) const
  403. {
  404. RETURN_IF_NOT_BATTLE(nullptr);
  405. return getBattle()->sides.at(playerToSide(battleGetOwner(stack))).hero;
  406. }
  407. bool CBattleInfoEssentials::battleMatchOwner(const CStack * attacker, const CStack * defender, const boost::logic::tribool positivness /* = false*/) const
  408. {
  409. RETURN_IF_NOT_BATTLE(false);
  410. if(boost::logic::indeterminate(positivness))
  411. return true;
  412. else if(defender->owner != battleGetOwner(defender))
  413. return true;//mind controlled unit is attackable for both sides
  414. else
  415. return (battleGetOwner(attacker) == battleGetOwner(defender)) == positivness;
  416. }
  417. si8 CBattleInfoCallback::battleHasWallPenalty( const CStack * stack, BattleHex destHex ) const
  418. {
  419. return battleHasWallPenalty(stack, stack->position, destHex);
  420. }
  421. si8 CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  422. {
  423. RETURN_IF_NOT_BATTLE(false);
  424. if (!battleGetSiegeLevel() || bonusBearer->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  425. return false;
  426. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  427. const int wallInDestLine = lineToWallHex(destHex.getY());
  428. const bool stackLeft = shooterPosition < wallInStackLine;
  429. const bool destRight = destHex > wallInDestLine;
  430. if (stackLeft && destRight) //shooting from outside to inside
  431. {
  432. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  433. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  434. row -= 2;
  435. const int wallPos = lineToWallHex(row);
  436. if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
  437. }
  438. return false;
  439. }
  440. si8 CBattleInfoCallback::battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  441. {
  442. RETURN_IF_NOT_BATTLE(false);
  443. if (!getAccesibility(stack).accessible(destHex, stack))
  444. return false;
  445. const ui8 siegeLevel = battleGetSiegeLevel();
  446. //check for wall
  447. //advanced teleport can pass wall of fort|citadel, expert - of castle
  448. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  449. return sameSideOfWall(stack->position, destHex);
  450. return true;
  451. }
  452. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  453. {
  454. std::set<BattleHex> attackedHexes;
  455. RETURN_IF_NOT_BATTLE(attackedHexes);
  456. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  457. for (BattleHex tile : at.hostileCreaturePositions)
  458. {
  459. const CStack * st = battleGetStackByPos(tile, true);
  460. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  461. {
  462. attackedHexes.insert(tile);
  463. }
  464. }
  465. for (BattleHex tile : at.friendlyCreaturePositions)
  466. {
  467. if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  468. {
  469. attackedHexes.insert(tile);
  470. }
  471. }
  472. return attackedHexes;
  473. }
  474. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  475. {
  476. switch (mode)
  477. {
  478. case RANDOM_GENIE:
  479. return getRandomBeneficialSpell(rand, stack); //target
  480. break;
  481. case RANDOM_AIMED:
  482. return getRandomCastedSpell(rand, stack); //caster
  483. break;
  484. default:
  485. logGlobal->errorStream() << "Incorrect mode of battleGetRandomSpell (" << mode <<")";
  486. return SpellID::NONE;
  487. }
  488. }
  489. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  490. {
  491. RETURN_IF_NOT_BATTLE(nullptr);
  492. for(auto s : battleGetAllStacks(true))
  493. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  494. return s;
  495. return nullptr;
  496. }
  497. void CBattleInfoCallback::battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn /*= 0*/, int lastMoved /*= -1*/) const
  498. {
  499. RETURN_IF_NOT_BATTLE();
  500. //let's define a huge lambda
  501. auto takeStack = [&](std::vector<const CStack *> &st) -> const CStack*
  502. {
  503. const CStack *ret = nullptr;
  504. unsigned i, //fastest stack
  505. j=0; //fastest stack of the other side
  506. for(i = 0; i < st.size(); i++)
  507. if(st[i])
  508. break;
  509. //no stacks left
  510. if(i == st.size())
  511. return nullptr;
  512. const CStack *fastest = st[i], *other = nullptr;
  513. int bestSpeed = fastest->Speed(turn);
  514. //FIXME: comparison between bool and integer. Logic does not makes sense either
  515. if(fastest->attackerOwned != lastMoved)
  516. {
  517. ret = fastest;
  518. }
  519. else
  520. {
  521. for(j = i + 1; j < st.size(); j++)
  522. {
  523. if(!st[j]) continue;
  524. if(st[j]->attackerOwned != lastMoved || st[j]->Speed(turn) != bestSpeed)
  525. break;
  526. }
  527. if(j >= st.size())
  528. {
  529. ret = fastest;
  530. }
  531. else
  532. {
  533. other = st[j];
  534. if(other->Speed(turn) != bestSpeed)
  535. ret = fastest;
  536. else
  537. ret = other;
  538. }
  539. }
  540. assert(ret);
  541. if(ret == fastest)
  542. st[i] = nullptr;
  543. else
  544. st[j] = nullptr;
  545. lastMoved = ret->attackerOwned;
  546. return ret;
  547. };
  548. //We'll split creatures with remaining movement to 4 buckets
  549. // [0] - turrets/catapult,
  550. // [1] - normal (unmoved) creatures, other war machines,
  551. // [2] - waited cres that had morale,
  552. // [3] - rest of waited cres
  553. std::vector<const CStack *> phase[4];
  554. int toMove = 0; //how many stacks still has move
  555. const CStack *active = battleActiveStack();
  556. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  557. if(!turn && active && active->willMove() && !active->waited())
  558. {
  559. out.push_back(active);
  560. if(out.size() == howMany)
  561. return;
  562. }
  563. auto allStacks = battleGetAllStacks(true);
  564. if(!vstd::contains_if(allStacks, [](const CStack *stack) { return stack->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  565. {
  566. //No stack will be able to move, battle is over.
  567. out.clear();
  568. return;
  569. }
  570. for(auto s : battleGetAllStacks(true))
  571. {
  572. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  573. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  574. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  575. {
  576. continue;
  577. }
  578. int p = -1; //in which phase this tack will move?
  579. if(turn <= 0 && s->waited()) //consider waiting state only for ongoing round
  580. {
  581. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  582. p = 2;
  583. else
  584. p = 3;
  585. }
  586. else if(s->getCreature()->idNumber == CreatureID::CATAPULT || s->getCreature()->idNumber == CreatureID::ARROW_TOWERS) //catapult and turrets are first
  587. {
  588. p = 0;
  589. }
  590. else
  591. {
  592. p = 1;
  593. }
  594. phase[p].push_back(s);
  595. toMove++;
  596. }
  597. for(int i = 0; i < 4; i++)
  598. boost::sort(phase[i], CMP_stack(i, turn > 0 ? turn : 0));
  599. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  600. out.push_back(phase[0][i]);
  601. if(out.size() == howMany)
  602. return;
  603. if(lastMoved == -1)
  604. {
  605. if(active)
  606. {
  607. //FIXME: both branches contain same code!!!
  608. if(out.size() && out.front() == active)
  609. lastMoved = active->attackerOwned;
  610. else
  611. lastMoved = active->attackerOwned;
  612. }
  613. else
  614. {
  615. lastMoved = 0;
  616. }
  617. }
  618. int pi = 1;
  619. while(out.size() < howMany)
  620. {
  621. const CStack *hlp = takeStack(phase[pi]);
  622. if(!hlp)
  623. {
  624. pi++;
  625. if(pi > 3)
  626. {
  627. //if(turn != 2)
  628. battleGetStackQueue(out, howMany, turn + 1, lastMoved);
  629. return;
  630. }
  631. }
  632. else
  633. {
  634. out.push_back(hlp);
  635. }
  636. }
  637. }
  638. void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
  639. {
  640. RETURN_IF_NOT_BATTLE();
  641. auto accessibility = getAccesibility();
  642. for(int i = 0; i < accessibility.size(); i++)
  643. ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  644. }
  645. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable) const
  646. {
  647. std::vector<BattleHex> ret;
  648. RETURN_IF_NOT_BATTLE(ret);
  649. if(!stack->position.isValid()) //turrets
  650. return ret;
  651. auto reachability = getReachability(stack);
  652. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  653. {
  654. // If obstacles or other stacks makes movement impossible, it can't be helped.
  655. if(!reachability.isReachable(i))
  656. continue;
  657. if(battleTacticDist() && battleGetTacticsSide() == !stack->attackerOwned)
  658. {
  659. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  660. if(!isInTacticRange(i))
  661. continue;
  662. }
  663. else
  664. {
  665. //Not tactics phase -> destination must be reachable and within stack range.
  666. if(reachability.distances[i] > stack->Speed(0, true))
  667. continue;
  668. }
  669. ret.push_back(i);
  670. if(addOccupiable && stack->doubleWide())
  671. {
  672. //If two-hex stack can stand on hex i then obviously it can occupy its second hex from that position
  673. ret.push_back(stack->occupiedHex(i));
  674. }
  675. }
  676. if(attackable)
  677. {
  678. auto meleeAttackable = [&](BattleHex hex) -> bool
  679. {
  680. // Return true if given hex has at least one available neighbour.
  681. // Available hexes are already present in ret vector.
  682. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  683. { return BattleHex::mutualPosition(hex, availableHex) >= 0; });
  684. return availableNeighbor != ret.end();
  685. };
  686. for(const CStack * otherSt : battleAliveStacks(stack->attackerOwned))
  687. {
  688. if(!otherSt->isValidTarget(false))
  689. continue;
  690. std::vector<BattleHex> occupied = otherSt->getHexes();
  691. if(battleCanShoot(stack, otherSt->position))
  692. {
  693. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  694. continue;
  695. }
  696. for(BattleHex he : occupied)
  697. {
  698. if(meleeAttackable(he))
  699. attackable->push_back(he);
  700. }
  701. }
  702. }
  703. //adding occupiable likely adds duplicates to ret -> clean it up
  704. boost::sort(ret);
  705. ret.erase(boost::unique(ret).end(), ret.end());
  706. return ret;
  707. }
  708. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  709. {
  710. RETURN_IF_NOT_BATTLE(false);
  711. if(battleTacticDist())
  712. return false;
  713. if (!stack || !target)
  714. return false;
  715. if(!battleMatchOwner(stack, target))
  716. return false;
  717. auto &id = stack->getCreature()->idNumber;
  718. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  719. return false;
  720. if (!target->alive())
  721. return false;
  722. return true;
  723. }
  724. bool CBattleInfoCallback::battleCanShoot(const CStack * stack, BattleHex dest) const
  725. {
  726. RETURN_IF_NOT_BATTLE(false);
  727. if(battleTacticDist()) //no shooting during tactics
  728. return false;
  729. const CStack *dst = battleGetStackByPos(dest);
  730. if(!stack || !dst)
  731. return false;
  732. //forgetfulness
  733. TBonusListPtr forgetfulList = stack->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  734. if(!forgetfulList->empty())
  735. {
  736. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  737. //advanced+ level
  738. if(forgetful > 1)
  739. return false;
  740. }
  741. if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
  742. return false;
  743. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  744. && battleMatchOwner(stack, dst)
  745. && dst->alive()
  746. && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
  747. && stack->shots
  748. )
  749. return true;
  750. return false;
  751. }
  752. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
  753. ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  754. {
  755. return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  756. }
  757. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo &info) const
  758. {
  759. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  760. {
  761. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  762. auto limitMatches = info.shooting
  763. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  764. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  765. //any regular bonuses or just ones for melee/ranged
  766. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  767. };
  768. double additiveBonus = 1.0, multBonus = 1.0,
  769. minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
  770. maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
  771. const CCreature *attackerType = info.attacker->getCreature(),
  772. *defenderType = info.defender->getCreature();
  773. if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
  774. {
  775. SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  776. }
  777. if(info.attackerBonuses->hasBonusOfType(Bonus::SIEGE_WEAPON) && attackerType->idNumber != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  778. { //minDmg and maxDmg are multiplied by hero attack + 1
  779. auto retreiveHeroPrimSkill = [&](int skill) -> int
  780. {
  781. const std::shared_ptr<Bonus> b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  782. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  783. };
  784. minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  785. maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  786. }
  787. int attackDefenceDifference = 0;
  788. double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
  789. attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
  790. double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
  791. attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
  792. if(const std::shared_ptr<Bonus> slayerEffect = info.attackerBonuses->getBonus(Selector::type(Bonus::SLAYER))) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  793. {
  794. std::vector<int> affectedIds;
  795. int spLevel = slayerEffect->val;
  796. //FIXME: do not check all creatures
  797. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  798. {
  799. for(const std::shared_ptr<Bonus> b : VLC->creh->creatures[g]->getBonusList())
  800. {
  801. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  802. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  803. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  804. {
  805. affectedIds.push_back(g);
  806. break;
  807. }
  808. }
  809. }
  810. for(auto & affectedId : affectedIds)
  811. {
  812. if(defenderType->idNumber == affectedId)
  813. {
  814. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
  815. break;
  816. }
  817. }
  818. }
  819. //bonus from attack/defense skills
  820. if(attackDefenceDifference < 0) //decreasing dmg
  821. {
  822. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  823. multBonus *= 1.0 - dec;
  824. }
  825. else //increasing dmg
  826. {
  827. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  828. additiveBonus += inc;
  829. }
  830. //applying jousting bonus
  831. if( info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  832. additiveBonus += info.chargedFields * 0.05;
  833. //handling secondary abilities and artifacts giving premies to them
  834. if(info.shooting)
  835. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
  836. else
  837. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
  838. if(info.defenderBonuses)
  839. multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
  840. //handling hate effect
  841. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
  842. //luck bonus
  843. if (info.luckyHit)
  844. {
  845. additiveBonus += 1.0;
  846. }
  847. //unlucky hit, used only if negative luck is enabled
  848. if (info.unluckyHit)
  849. {
  850. additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
  851. }
  852. //ballista double dmg
  853. if(info.ballistaDoubleDamage)
  854. {
  855. additiveBonus += 1.0;
  856. }
  857. if (info.deathBlow) //Dread Knight and many WoGified creatures
  858. {
  859. additiveBonus += 1.0;
  860. }
  861. //handling spell effects
  862. if(!info.shooting) //eg. shield
  863. {
  864. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
  865. }
  866. else if(info.shooting) //eg. air shield
  867. {
  868. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
  869. }
  870. if(info.shooting)
  871. {
  872. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  873. //get list first, total value of 0 also counts
  874. TBonusListPtr forgetfulList = info.attackerBonuses->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  875. if(!forgetfulList->empty())
  876. {
  877. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  878. //none of basic level
  879. if(forgetful == 0 || forgetful == 1)
  880. multBonus *= 0.5;
  881. else
  882. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  883. }
  884. }
  885. TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
  886. TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
  887. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  888. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo : 0;
  889. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  890. {
  891. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  892. }
  893. auto isAdvancedAirShield = [](const Bonus* bonus)
  894. {
  895. return bonus->source == Bonus::SPELL_EFFECT
  896. && bonus->sid == SpellID::AIR_SHIELD
  897. && bonus->val >= SecSkillLevel::ADVANCED;
  898. };
  899. //wall / distance penalty + advanced air shield
  900. const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  901. const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  902. if(info.shooting)
  903. {
  904. if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
  905. {
  906. multBonus *= 0.5;
  907. }
  908. if (obstaclePenalty)
  909. {
  910. multBonus *= 0.5; //cumulative
  911. }
  912. }
  913. if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  914. {
  915. multBonus *= 0.5;
  916. }
  917. // psychic elementals versus mind immune units 50%
  918. if(attackerType->idNumber == CreatureID::PSYCHIC_ELEMENTAL
  919. && info.defenderBonuses->hasBonusOfType(Bonus::MIND_IMMUNITY))
  920. {
  921. multBonus *= 0.5;
  922. }
  923. // TODO attack on petrified unit 50%
  924. // blinded unit retaliates
  925. minDmg *= additiveBonus * multBonus;
  926. maxDmg *= additiveBonus * multBonus;
  927. TDmgRange returnedVal;
  928. if(curseEffects->size()) //curse handling (rest)
  929. {
  930. minDmg += curseBlessAdditiveModifier;
  931. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  932. }
  933. else if(blessEffects->size()) //bless handling
  934. {
  935. maxDmg += curseBlessAdditiveModifier;
  936. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  937. }
  938. else
  939. {
  940. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  941. }
  942. //damage cannot be less than 1
  943. vstd::amax(returnedVal.first, 1);
  944. vstd::amax(returnedVal.second, 1);
  945. return returnedVal;
  946. }
  947. TDmgRange CBattleInfoCallback::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount,
  948. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg ) const
  949. {
  950. BattleAttackInfo bai(attacker, defender, shooting);
  951. bai.attackerCount = attackerCount;
  952. bai.chargedFields = charge;
  953. bai.luckyHit = lucky;
  954. bai.unluckyHit = unlucky;
  955. bai.deathBlow = deathBlow;
  956. bai.ballistaDoubleDamage = ballistaDoubleDmg;
  957. return calculateDmgRange(bai);
  958. }
  959. TDmgRange CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  960. {
  961. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  962. const bool shooting = battleCanShoot(attacker, defender->position);
  963. const BattleAttackInfo bai(attacker, defender, shooting);
  964. return battleEstimateDamage(rand, bai, retaliationDmg);
  965. }
  966. std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const BattleAttackInfo &bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
  967. {
  968. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  969. //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
  970. //const ui8 mySide = !attacker->attackerOwned;
  971. TDmgRange ret = calculateDmgRange(bai);
  972. if(retaliationDmg)
  973. {
  974. if(bai.shooting)
  975. {
  976. retaliationDmg->first = retaliationDmg->second = 0;
  977. }
  978. else
  979. {
  980. ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  981. for (int i=0; i<2; ++i)
  982. {
  983. BattleStackAttacked bsa;
  984. bsa.damageAmount = ret.*pairElems[i];
  985. bai.defender->prepareAttacked(bsa, rand, bai.defenderCount);
  986. auto retaliationAttack = bai.reverse();
  987. retaliationAttack.attackerCount = bsa.newAmount;
  988. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  989. }
  990. }
  991. }
  992. return ret;
  993. }
  994. std::shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
  995. {
  996. RETURN_IF_NOT_BATTLE(std::shared_ptr<const CObstacleInstance>());
  997. for(auto &obs : battleGetAllObstacles())
  998. {
  999. if(vstd::contains(obs->getBlockedTiles(), tile)
  1000. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  1001. {
  1002. return obs;
  1003. }
  1004. }
  1005. return std::shared_ptr<const CObstacleInstance>();
  1006. }
  1007. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  1008. {
  1009. AccessibilityInfo ret;
  1010. ret.fill(EAccessibility::ACCESSIBLE);
  1011. //removing accessibility for side columns of hexes
  1012. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  1013. {
  1014. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  1015. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  1016. }
  1017. //gate -> should be before stacks
  1018. if(battleGetSiegeLevel() > 0)
  1019. {
  1020. EAccessibility::EAccessibility accessability = EAccessibility::ACCESSIBLE;
  1021. switch(battleGetGateState())
  1022. {
  1023. case EGateState::CLOSED:
  1024. accessability = EAccessibility::GATE;
  1025. break;
  1026. case EGateState::BLOCKED:
  1027. accessability = EAccessibility::UNAVAILABLE;
  1028. break;
  1029. }
  1030. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  1031. }
  1032. //tiles occupied by standing stacks
  1033. for(auto stack : battleAliveStacks())
  1034. {
  1035. for(auto hex : stack->getHexes())
  1036. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  1037. ret[hex] = EAccessibility::ALIVE_STACK;
  1038. }
  1039. //obstacles
  1040. for(const auto &obst : battleGetAllObstacles())
  1041. {
  1042. for(auto hex : obst->getBlockedTiles())
  1043. ret[hex] = EAccessibility::OBSTACLE;
  1044. }
  1045. //walls
  1046. if(battleGetSiegeLevel() > 0)
  1047. {
  1048. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  1049. for(auto hex : permanentlyLocked)
  1050. ret[hex] = EAccessibility::UNAVAILABLE;
  1051. //TODO likely duplicated logic
  1052. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  1053. {
  1054. //which part of wall, which hex is blocked if this part of wall is not destroyed
  1055. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  1056. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  1057. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  1058. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  1059. };
  1060. for(auto & elem : lockedIfNotDestroyed)
  1061. {
  1062. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  1063. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  1064. }
  1065. }
  1066. return ret;
  1067. }
  1068. AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack *stack) const
  1069. {
  1070. return getAccesibility(stack->getHexes());
  1071. }
  1072. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> &accessibleHexes) const
  1073. {
  1074. auto ret = getAccesibility();
  1075. for(auto hex : accessibleHexes)
  1076. if(hex.isValid())
  1077. ret[hex] = EAccessibility::ACCESSIBLE;
  1078. return ret;
  1079. }
  1080. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters &params) const
  1081. {
  1082. ReachabilityInfo ret;
  1083. ret.accessibility = accessibility;
  1084. ret.params = params;
  1085. ret.predecessors.fill(BattleHex::INVALID);
  1086. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  1087. if(!params.startPosition.isValid()) //if got call for arrow turrets
  1088. return ret;
  1089. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  1090. //const bool twoHexCreature = params.doubleWide;
  1091. std::queue<BattleHex> hexq; //bfs queue
  1092. //first element
  1093. hexq.push(params.startPosition);
  1094. ret.distances[params.startPosition] = 0;
  1095. while(!hexq.empty()) //bfs loop
  1096. {
  1097. const BattleHex curHex = hexq.front();
  1098. hexq.pop();
  1099. //walking stack can't step past the quicksands
  1100. //TODO what if second hex of two-hex creature enters quicksand
  1101. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  1102. continue;
  1103. const int costToNeighbour = ret.distances[curHex] + 1;
  1104. for(BattleHex neighbour : curHex.neighbouringTiles())
  1105. {
  1106. const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.attackerOwned);
  1107. const int costFoundSoFar = ret.distances[neighbour];
  1108. if(accessible && costToNeighbour < costFoundSoFar)
  1109. {
  1110. hexq.push(neighbour);
  1111. ret.distances[neighbour] = costToNeighbour;
  1112. ret.predecessors[neighbour] = curHex;
  1113. }
  1114. }
  1115. }
  1116. return ret;
  1117. }
  1118. ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack *stack) const
  1119. {
  1120. return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
  1121. }
  1122. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  1123. {
  1124. std::set<BattleHex> ret;
  1125. RETURN_IF_NOT_BATTLE(ret);
  1126. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  1127. {
  1128. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  1129. {
  1130. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  1131. }
  1132. }
  1133. return ret;
  1134. }
  1135. std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  1136. {
  1137. auto reachability = getReachability(closest);
  1138. auto avHexes = battleGetAvailableHexes(closest, false);
  1139. // I hate std::pairs with their undescriptive member names first / second
  1140. struct DistStack
  1141. {
  1142. int distanceToPred;
  1143. BattleHex destination;
  1144. const CStack *stack;
  1145. };
  1146. std::vector<DistStack> stackPairs;
  1147. std::vector<const CStack *> possibleStacks = battleGetStacksIf([=](const CStack * s)
  1148. {
  1149. return s->isValidTarget(false) && s != closest && (boost::logic::indeterminate(attackerOwned) || s->attackerOwned == attackerOwned);
  1150. });
  1151. for(const CStack * st : possibleStacks)
  1152. for(BattleHex hex : avHexes)
  1153. if(CStack::isMeleeAttackPossible(closest, st, hex))
  1154. {
  1155. DistStack hlp = {reachability.distances[hex], hex, st};
  1156. stackPairs.push_back(hlp);
  1157. }
  1158. if (stackPairs.size())
  1159. {
  1160. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  1161. auto minimal = boost::min_element(stackPairs, comparator);
  1162. return std::make_pair(minimal->stack, minimal->destination);
  1163. }
  1164. else
  1165. return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
  1166. }
  1167. si8 CBattleInfoCallback::battleGetTacticDist() const
  1168. {
  1169. RETURN_IF_NOT_BATTLE(0);
  1170. //TODO get rid of this method
  1171. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1172. return battleTacticDist();
  1173. return 0;
  1174. }
  1175. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  1176. {
  1177. RETURN_IF_NOT_BATTLE(false);
  1178. auto side = battleGetTacticsSide();
  1179. auto dist = battleGetTacticDist();
  1180. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  1181. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  1182. }
  1183. ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
  1184. {
  1185. ReachabilityInfo::Parameters params(stack);
  1186. if(!battleDoWeKnowAbout(!stack->attackerOwned))
  1187. {
  1188. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1189. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1190. params.perspective = battleGetMySide();
  1191. }
  1192. return getReachability(params);
  1193. }
  1194. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1195. {
  1196. if(params.flying)
  1197. return getFlyingReachability(params);
  1198. else
  1199. return makeBFS(getAccesibility(params.knownAccessible), params);
  1200. }
  1201. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  1202. {
  1203. ReachabilityInfo ret;
  1204. ret.accessibility = getAccesibility(params.knownAccessible);
  1205. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1206. {
  1207. if(ret.accessibility.accessible(i, params.doubleWide, params.attackerOwned))
  1208. {
  1209. ret.predecessors[i] = params.startPosition;
  1210. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1211. }
  1212. }
  1213. return ret;
  1214. }
  1215. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1216. {
  1217. //does not return hex attacked directly
  1218. //TODO: apply rotation to two-hex attackers
  1219. bool isAttacker = attacker->attackerOwned;
  1220. AttackableTiles at;
  1221. RETURN_IF_NOT_BATTLE(at);
  1222. const int WN = GameConstants::BFIELD_WIDTH;
  1223. ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  1224. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  1225. bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  1226. if (reverse)
  1227. {
  1228. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  1229. }
  1230. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  1231. {
  1232. boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
  1233. }
  1234. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  1235. {
  1236. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1237. for (BattleHex tile : hexes)
  1238. {
  1239. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  1240. {
  1241. const CStack * st = battleGetStackByPos(tile, true);
  1242. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1243. {
  1244. at.hostileCreaturePositions.insert(tile);
  1245. }
  1246. }
  1247. }
  1248. }
  1249. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  1250. {
  1251. std::vector<BattleHex> hexes; //only one, in fact
  1252. int pseudoVector = destinationTile.hex - hex;
  1253. switch (pseudoVector)
  1254. {
  1255. case 1:
  1256. case -1:
  1257. BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
  1258. break;
  1259. case WN: //17 //left-down or right-down
  1260. case -WN: //-17 //left-up or right-up
  1261. case WN + 1: //18 //right-down
  1262. case -WN + 1: //-16 //right-up
  1263. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : -1 ), hexes);
  1264. break;
  1265. case WN-1: //16 //left-down
  1266. case -WN-1: //-18 //left-up
  1267. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : 0), hexes);
  1268. break;
  1269. }
  1270. for (BattleHex tile : hexes)
  1271. {
  1272. //friendly stacks can also be damaged by Dragon Breath
  1273. if (battleGetStackByPos (tile, true))
  1274. at.friendlyCreaturePositions.insert (tile);
  1275. }
  1276. }
  1277. return at;
  1278. }
  1279. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  1280. {
  1281. std::set<const CStack*> attackedCres;
  1282. RETURN_IF_NOT_BATTLE(attackedCres);
  1283. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1284. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1285. {
  1286. const CStack * st = battleGetStackByPos(tile, true);
  1287. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1288. {
  1289. attackedCres.insert(st);
  1290. }
  1291. }
  1292. for (BattleHex tile : at.friendlyCreaturePositions)
  1293. {
  1294. const CStack * st = battleGetStackByPos(tile, true);
  1295. if(st) //friendly stacks can also be damaged by Dragon Breath
  1296. {
  1297. attackedCres.insert(st);
  1298. }
  1299. }
  1300. return attackedCres;
  1301. }
  1302. //TODO: this should apply also to mechanics and cursor interface
  1303. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1304. {
  1305. int fromX = hexFrom.getX();
  1306. int fromY = hexFrom.getY();
  1307. int toX = hexTo.getX();
  1308. int toY = hexTo.getY();
  1309. if (curDir) // attacker, facing right
  1310. {
  1311. if (fromX < toX)
  1312. return false;
  1313. if (fromX > toX)
  1314. return true;
  1315. if (fromY % 2 == 0 && toY % 2 == 1)
  1316. return true;
  1317. return false;
  1318. }
  1319. else // defender, facing left
  1320. {
  1321. if(fromX < toX)
  1322. return true;
  1323. if(fromX > toX)
  1324. return false;
  1325. if (fromY % 2 == 1 && toY % 2 == 0)
  1326. return true;
  1327. return false;
  1328. }
  1329. }
  1330. //TODO: this should apply also to mechanics and cursor interface
  1331. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1332. {
  1333. if (hexTo < 0 || hexFrom < 0) //turret
  1334. return false;
  1335. if (toDoubleWide)
  1336. {
  1337. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1338. {
  1339. if (toDir)
  1340. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1341. else
  1342. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1343. }
  1344. return false;
  1345. }
  1346. else
  1347. {
  1348. return isToReverseHlp(hexFrom, hexTo, curDir);
  1349. }
  1350. }
  1351. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
  1352. {
  1353. ReachabilityInfo::TDistances ret;
  1354. ret.fill(-1);
  1355. RETURN_IF_NOT_BATTLE(ret);
  1356. ReachabilityInfo::Parameters params(stack);
  1357. params.perspective = battleGetMySide();
  1358. params.startPosition = hex.isValid() ? hex : stack->position;
  1359. auto reachability = getReachability(params);
  1360. boost::copy(reachability.distances, ret.begin());
  1361. if(predecessors)
  1362. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1363. predecessors[i] = reachability.predecessors[i];
  1364. return ret;
  1365. }
  1366. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1367. {
  1368. return battleHasDistancePenalty(stack, stack->position, destHex);
  1369. }
  1370. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1371. {
  1372. RETURN_IF_NOT_BATTLE(false);
  1373. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1374. return false;
  1375. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1376. {
  1377. //If any hex of target creature is within range, there is no penalty
  1378. for(auto hex : dstStack->getHexes())
  1379. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1380. return false;
  1381. //TODO what about two-hex shooters?
  1382. }
  1383. else
  1384. {
  1385. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1386. return false;
  1387. }
  1388. return true;
  1389. }
  1390. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1391. {
  1392. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1393. return WallPartToHex(part);
  1394. }
  1395. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1396. {
  1397. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1398. return hexToWallPart(hex);
  1399. }
  1400. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1401. {
  1402. RETURN_IF_NOT_BATTLE(false);
  1403. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1404. wallPart != EWallPart::INVALID;
  1405. }
  1406. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1407. {
  1408. std::vector<BattleHex> attackableBattleHexes;
  1409. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1410. for(auto & wallPartPair : wallParts)
  1411. {
  1412. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1413. {
  1414. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1415. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1416. {
  1417. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1418. }
  1419. }
  1420. }
  1421. return attackableBattleHexes;
  1422. }
  1423. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpell(const ISpellCaster * caster, const CSpell * spell, ECastingMode::ECastingMode mode) const
  1424. {
  1425. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1426. if(caster == nullptr)
  1427. {
  1428. logGlobal->errorStream() << "CBattleInfoCallback::battleCanCastThisSpell: no spellcaster.";
  1429. return ESpellCastProblem::INVALID;
  1430. }
  1431. const PlayerColor player = caster->getOwner();
  1432. const ui8 side = playerToSide(player);
  1433. if((si8)side < 0)
  1434. return ESpellCastProblem::INVALID;
  1435. if(!battleDoWeKnowAbout(side))
  1436. return ESpellCastProblem::INVALID;
  1437. ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(caster, mode);
  1438. if(genProblem != ESpellCastProblem::OK)
  1439. return genProblem;
  1440. switch(mode)
  1441. {
  1442. case ECastingMode::HERO_CASTING:
  1443. {
  1444. const CGHeroInstance * castingHero = dynamic_cast<const CGHeroInstance *>(caster);//todo: unify hero|creature spell cost
  1445. if(!castingHero)
  1446. {
  1447. logGlobal->error("battleCanCastThisSpell: invalid caster");
  1448. return ESpellCastProblem::INVALID;
  1449. }
  1450. if(!castingHero->getArt(ArtifactPosition::SPELLBOOK))
  1451. return ESpellCastProblem::NO_SPELLBOOK;
  1452. if(!castingHero->canCastThisSpell(spell))
  1453. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  1454. if(castingHero->mana < battleGetSpellCost(spell, castingHero)) //not enough mana
  1455. return ESpellCastProblem::NOT_ENOUGH_MANA;
  1456. }
  1457. break;
  1458. }
  1459. if(!spell->combatSpell)
  1460. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1461. //effect like Recanter's Cloak. Blocks also passive casting.
  1462. //TODO: check creature abilities to block
  1463. if(battleMaxSpellLevel(side) < spell->level)
  1464. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  1465. return spell->canBeCast(this, mode, caster);
  1466. }
  1467. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1468. {
  1469. RETURN_IF_NOT_BATTLE(-1);
  1470. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1471. ui32 ret = caster->getSpellCost(sp);
  1472. //checking for friendly stacks reducing cost of the spell and
  1473. //enemy stacks increasing it
  1474. si32 manaReduction = 0;
  1475. si32 manaIncrease = 0;
  1476. for(auto stack : battleAliveStacks())
  1477. {
  1478. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  1479. {
  1480. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1481. }
  1482. if( stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  1483. {
  1484. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1485. }
  1486. }
  1487. return ret - manaReduction + manaIncrease;
  1488. }
  1489. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpellHere(const ISpellCaster * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
  1490. {
  1491. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1492. if(caster == nullptr)
  1493. {
  1494. logGlobal->errorStream() << "CBattleInfoCallback::battleCanCastThisSpellHere: no spellcaster.";
  1495. return ESpellCastProblem::INVALID;
  1496. }
  1497. ESpellCastProblem::ESpellCastProblem problem = battleCanCastThisSpell(caster, spell, mode);
  1498. if(problem != ESpellCastProblem::OK)
  1499. return problem;
  1500. return spell->canBeCastAt(this, caster, mode, dest);
  1501. }
  1502. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1503. {
  1504. RETURN_IF_NOT_BATTLE(nullptr);
  1505. auto stacks = battleGetAllStacks();
  1506. auto stackItr = range::find_if(stacks, pred);
  1507. return stackItr == stacks.end()
  1508. ? nullptr
  1509. : *stackItr;
  1510. }
  1511. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1512. {
  1513. RETURN_IF_NOT_BATTLE(false);
  1514. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1515. return false;
  1516. for(const CStack * s : batteAdjacentCreatures(stack))
  1517. {
  1518. if (s->owner != stack->owner) //blocked by enemy stack
  1519. return true;
  1520. }
  1521. return false;
  1522. }
  1523. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1524. {
  1525. std::set<const CStack*> stacks;
  1526. RETURN_IF_NOT_BATTLE(stacks);
  1527. for (BattleHex hex : stack->getSurroundingHexes())
  1528. if(const CStack *neighbour = battleGetStackByPos(hex, true))
  1529. stacks.insert(neighbour);
  1530. return stacks;
  1531. }
  1532. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1533. {
  1534. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1535. //This is complete list. No spells from mods.
  1536. //todo: this should be Spellbook of caster Stack
  1537. static const std::set<SpellID> allPossibleSpells =
  1538. {
  1539. SpellID::AIR_SHIELD,
  1540. SpellID::ANTI_MAGIC,
  1541. SpellID::BLESS,
  1542. SpellID::BLOODLUST,
  1543. SpellID::COUNTERSTRIKE,
  1544. SpellID::CURE,
  1545. SpellID::FIRE_SHIELD,
  1546. SpellID::FORTUNE,
  1547. SpellID::HASTE,
  1548. SpellID::MAGIC_MIRROR,
  1549. SpellID::MIRTH,
  1550. SpellID::PRAYER,
  1551. SpellID::PRECISION,
  1552. SpellID::PROTECTION_FROM_AIR,
  1553. SpellID::PROTECTION_FROM_EARTH,
  1554. SpellID::PROTECTION_FROM_FIRE,
  1555. SpellID::PROTECTION_FROM_WATER,
  1556. SpellID::SHIELD,
  1557. SpellID::SLAYER,
  1558. SpellID::STONE_SKIN
  1559. };
  1560. std::vector<SpellID> beneficialSpells;
  1561. auto getAliveEnemy = [=](const std::function<bool(const CStack * )> & pred)
  1562. {
  1563. return getStackIf([=](const CStack * stack)
  1564. {
  1565. return pred(stack) && stack->owner != subject->owner && stack->alive();
  1566. });
  1567. };
  1568. for(const SpellID spellID : allPossibleSpells)
  1569. {
  1570. std::stringstream cachingStr;
  1571. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1572. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1573. //TODO: this ability has special limitations
  1574. || battleCanCastThisSpellHere(subject, spellID.toSpell(), ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1575. continue;
  1576. switch (spellID)
  1577. {
  1578. case SpellID::SHIELD:
  1579. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1580. {
  1581. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1582. {
  1583. return !stack->shots;
  1584. });
  1585. if (!walker)
  1586. continue;
  1587. }
  1588. break;
  1589. case SpellID::AIR_SHIELD: //only against active shooters
  1590. {
  1591. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1592. {
  1593. return stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
  1594. });
  1595. if (!shooter)
  1596. continue;
  1597. }
  1598. break;
  1599. case SpellID::ANTI_MAGIC:
  1600. case SpellID::MAGIC_MIRROR:
  1601. case SpellID::PROTECTION_FROM_AIR:
  1602. case SpellID::PROTECTION_FROM_EARTH:
  1603. case SpellID::PROTECTION_FROM_FIRE:
  1604. case SpellID::PROTECTION_FROM_WATER:
  1605. {
  1606. const ui8 enemySide = (ui8)subject->attackerOwned;
  1607. //todo: only if enemy has spellbook
  1608. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1609. continue;
  1610. }
  1611. break;
  1612. case SpellID::CURE: //only damaged units
  1613. {
  1614. //do not cast on affected by debuffs
  1615. if (subject->firstHPleft >= subject->MaxHealth())
  1616. continue;
  1617. }
  1618. break;
  1619. case SpellID::BLOODLUST:
  1620. {
  1621. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1622. continue;
  1623. }
  1624. break;
  1625. case SpellID::PRECISION:
  1626. {
  1627. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1628. continue;
  1629. }
  1630. break;
  1631. case SpellID::SLAYER://only if monsters are present
  1632. {
  1633. auto kingMonster = getAliveEnemy([&](const CStack *stack) -> bool //look for enemy, non-shooting stack
  1634. {
  1635. const auto isKing = Selector::type(Bonus::KING1)
  1636. .Or(Selector::type(Bonus::KING2))
  1637. .Or(Selector::type(Bonus::KING3));
  1638. return stack->hasBonus(isKing);
  1639. });
  1640. if (!kingMonster)
  1641. continue;
  1642. }
  1643. break;
  1644. }
  1645. beneficialSpells.push_back(spellID);
  1646. }
  1647. if(!beneficialSpells.empty())
  1648. {
  1649. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1650. }
  1651. else
  1652. {
  1653. return SpellID::NONE;
  1654. }
  1655. }
  1656. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1657. {
  1658. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1659. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1660. if (!bl->size())
  1661. return SpellID::NONE;
  1662. int totalWeight = 0;
  1663. for(auto b : *bl)
  1664. {
  1665. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1666. }
  1667. int randomPos = rand.nextInt(totalWeight - 1);
  1668. for(auto b : *bl)
  1669. {
  1670. randomPos -= std::max(b->additionalInfo, 1);
  1671. if(randomPos < 0)
  1672. {
  1673. return SpellID(b->subtype);
  1674. }
  1675. }
  1676. return SpellID::NONE;
  1677. }
  1678. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1679. {
  1680. RETURN_IF_NOT_BATTLE(-3);
  1681. if(!battleCanSurrender(Player))
  1682. return -1;
  1683. int ret = 0;
  1684. double discount = 0;
  1685. for(const CStack *s : battleAliveStacks(playerToSide(Player)))
  1686. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1687. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  1688. if(const CGHeroInstance *h = battleGetFightingHero(playerToSide(Player)))
  1689. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1690. ret *= (100.0 - discount) / 100.0;
  1691. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1692. return ret;
  1693. }
  1694. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1695. {
  1696. const IBonusBearer *node = nullptr;
  1697. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1698. node = h;
  1699. else
  1700. node = getBattleNode();
  1701. if(!node)
  1702. return GameConstants::SPELL_LEVELS;
  1703. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1704. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1705. if(b->size())
  1706. return b->totalValue();
  1707. return GameConstants::SPELL_LEVELS;
  1708. }
  1709. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1710. {
  1711. auto stacks = battleGetAllStacks();
  1712. //checking winning condition
  1713. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
  1714. hasStack[0] = hasStack[1] = false;
  1715. for(auto & stack : stacks)
  1716. {
  1717. if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1718. {
  1719. hasStack[1-stack->attackerOwned] = true;
  1720. }
  1721. }
  1722. if(!hasStack[0] && !hasStack[1])
  1723. return 2;
  1724. if(!hasStack[1])
  1725. return 0;
  1726. if(!hasStack[0])
  1727. return 1;
  1728. return boost::none;
  1729. }
  1730. bool AccessibilityInfo::accessible(BattleHex tile, const CStack *stack) const
  1731. {
  1732. return accessible(tile, stack->doubleWide(), stack->attackerOwned);
  1733. }
  1734. bool AccessibilityInfo::accessible(BattleHex tile, bool doubleWide, bool attackerOwned) const
  1735. {
  1736. // All hexes that stack would cover if standing on tile have to be accessible.
  1737. for(auto hex : CStack::getHexes(tile, doubleWide, attackerOwned))
  1738. {
  1739. // If the hex is out of range then the tile isn't accessible
  1740. if(!hex.isValid())
  1741. return false;
  1742. // If we're no defender which step on gate and the hex isn't accessible, then the tile
  1743. // isn't accessible
  1744. else if(at(hex) != EAccessibility::ACCESSIBLE &&
  1745. !(at(hex) == EAccessibility::GATE && !attackerOwned))
  1746. {
  1747. return false;
  1748. }
  1749. }
  1750. return true;
  1751. }
  1752. bool AccessibilityInfo::occupiable(const CStack *stack, BattleHex tile) const
  1753. {
  1754. //obviously, we can occupy tile by standing on it
  1755. if(accessible(tile, stack))
  1756. return true;
  1757. if(stack->doubleWide())
  1758. {
  1759. //Check the tile next to -> if stack stands there, it'll also occupy considered hex
  1760. const BattleHex anotherTile = tile + (stack->attackerOwned ? BattleHex::RIGHT : BattleHex::LEFT);
  1761. if(accessible(anotherTile, stack))
  1762. return true;
  1763. }
  1764. return false;
  1765. }
  1766. ReachabilityInfo::Parameters::Parameters()
  1767. {
  1768. stack = nullptr;
  1769. perspective = BattlePerspective::ALL_KNOWING;
  1770. attackerOwned = doubleWide = flying = false;
  1771. }
  1772. ReachabilityInfo::Parameters::Parameters(const CStack *Stack)
  1773. {
  1774. stack = Stack;
  1775. perspective = (BattlePerspective::BattlePerspective)(!Stack->attackerOwned);
  1776. startPosition = Stack->position;
  1777. doubleWide = stack->doubleWide();
  1778. attackerOwned = stack->attackerOwned;
  1779. flying = stack->hasBonusOfType(Bonus::FLYING);
  1780. knownAccessible = stack->getHexes();
  1781. }
  1782. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell) const
  1783. {
  1784. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1785. ASSERT_IF_CALLED_WITH_PLAYER
  1786. const ISpellCaster * hero = battleGetMyHero();
  1787. if(hero == nullptr)
  1788. return ESpellCastProblem::INVALID;
  1789. else
  1790. return CBattleInfoCallback::battleCanCastThisSpell(hero, spell, ECastingMode::HERO_CASTING);
  1791. }
  1792. bool CPlayerBattleCallback::battleCanFlee() const
  1793. {
  1794. RETURN_IF_NOT_BATTLE(false);
  1795. ASSERT_IF_CALLED_WITH_PLAYER
  1796. return CBattleInfoEssentials::battleCanFlee(*player);
  1797. }
  1798. TStacks CPlayerBattleCallback::battleGetStacks(EStackOwnership whose /*= MINE_AND_ENEMY*/, bool onlyAlive /*= true*/) const
  1799. {
  1800. if(whose != MINE_AND_ENEMY)
  1801. {
  1802. ASSERT_IF_CALLED_WITH_PLAYER
  1803. }
  1804. return battleGetStacksIf([=](const CStack * s){
  1805. const bool ownerMatches = (whose == MINE_AND_ENEMY)
  1806. || (whose == ONLY_MINE && s->owner == player)
  1807. || (whose == ONLY_ENEMY && s->owner != player);
  1808. return ownerMatches && s->isValidTarget(!onlyAlive);
  1809. });
  1810. }
  1811. int CPlayerBattleCallback::battleGetSurrenderCost() const
  1812. {
  1813. RETURN_IF_NOT_BATTLE(-3)
  1814. ASSERT_IF_CALLED_WITH_PLAYER
  1815. return CBattleInfoCallback::battleGetSurrenderCost(*player);
  1816. }
  1817. bool CPlayerBattleCallback::battleCanCastSpell(ESpellCastProblem::ESpellCastProblem *outProblem /*= nullptr*/) const
  1818. {
  1819. RETURN_IF_NOT_BATTLE(false);
  1820. ASSERT_IF_CALLED_WITH_PLAYER
  1821. const CGHeroInstance * hero = battleGetMyHero();
  1822. if(!hero)
  1823. {
  1824. if(outProblem)
  1825. *outProblem = ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  1826. return false;
  1827. }
  1828. auto problem = CBattleInfoCallback::battleCanCastSpell(hero, ECastingMode::HERO_CASTING);
  1829. if(outProblem)
  1830. *outProblem = problem;
  1831. return problem == ESpellCastProblem::OK;
  1832. }
  1833. const CGHeroInstance * CPlayerBattleCallback::battleGetMyHero() const
  1834. {
  1835. return CBattleInfoEssentials::battleGetFightingHero(battleGetMySide());
  1836. }
  1837. InfoAboutHero CPlayerBattleCallback::battleGetEnemyHero() const
  1838. {
  1839. return battleGetHeroInfo(!battleGetMySide());
  1840. }
  1841. BattleAttackInfo::BattleAttackInfo(const CStack *Attacker, const CStack *Defender, bool Shooting)
  1842. {
  1843. attacker = Attacker;
  1844. defender = Defender;
  1845. attackerBonuses = Attacker;
  1846. defenderBonuses = Defender;
  1847. attackerPosition = Attacker->position;
  1848. defenderPosition = Defender->position;
  1849. attackerCount = Attacker->count;
  1850. defenderCount = Defender->count;
  1851. shooting = Shooting;
  1852. chargedFields = 0;
  1853. luckyHit = false;
  1854. unluckyHit = false;
  1855. deathBlow = false;
  1856. ballistaDoubleDamage = false;
  1857. }
  1858. BattleAttackInfo BattleAttackInfo::reverse() const
  1859. {
  1860. BattleAttackInfo ret = *this;
  1861. std::swap(ret.attacker, ret.defender);
  1862. std::swap(ret.attackerBonuses, ret.defenderBonuses);
  1863. std::swap(ret.attackerPosition, ret.defenderPosition);
  1864. std::swap(ret.attackerCount, ret.defenderCount);
  1865. ret.shooting = false;
  1866. ret.chargedFields = 0;
  1867. ret.luckyHit = ret.ballistaDoubleDamage = ret.deathBlow = false;
  1868. return ret;
  1869. }