CBattleCallback.cpp 71 KB

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