CBattleCallback.cpp 67 KB

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