CBattleCallback.cpp 74 KB

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