CBattleCallback.cpp 66 KB

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