CBattleCallback.cpp 72 KB

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