CBattleCallback.cpp 61 KB

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