CBattleCallback.cpp 71 KB

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