CBattleCallback.cpp 60 KB

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