2
0

CBattleCallback.cpp 73 KB

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