CBattleCallback.cpp 67 KB

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