CBattleCallback.cpp 76 KB

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