CBattleCallback.cpp 67 KB

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