CBattleCallback.cpp 63 KB

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