CBattleCallback.cpp 73 KB

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