CBattleCallback.cpp 76 KB

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