CBattleCallback.cpp 64 KB

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