CBattleCallback.cpp 67 KB

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