2
0

CBattleCallback.cpp 74 KB

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