CBattleCallback.cpp 62 KB

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