CBattleCallback.cpp 72 KB

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