BattleState.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  1. #include "StdInc.h"
  2. #include "BattleState.h"
  3. #include <numeric>
  4. #include <boost/random/linear_congruential.hpp>
  5. #include "VCMI_Lib.h"
  6. #include "CObjectHandler.h"
  7. #include "CHeroHandler.h"
  8. #include "CCreatureHandler.h"
  9. #include "CSpellHandler.h"
  10. #include "CTownHandler.h"
  11. #include "NetPacks.h"
  12. #include "../lib/JsonNode.h"
  13. /*
  14. * BattleState.h, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. extern boost::rand48 ran;
  23. const CStack * BattleInfo::getNextStack() const
  24. {
  25. std::vector<const CStack *> hlp;
  26. getStackQueue(hlp, 1, -1);
  27. if(hlp.size())
  28. return hlp[0];
  29. else
  30. return NULL;
  31. }
  32. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  33. {
  34. const CStack *ret = NULL;
  35. unsigned i, //fastest stack
  36. j; //fastest stack of the other side
  37. for(i = 0; i < st.size(); i++)
  38. if(st[i])
  39. break;
  40. //no stacks left
  41. if(i == st.size())
  42. return NULL;
  43. const CStack *fastest = st[i], *other = NULL;
  44. int bestSpeed = fastest->Speed(turn);
  45. if(fastest->attackerOwned != curside)
  46. {
  47. ret = fastest;
  48. }
  49. else
  50. {
  51. for(j = i + 1; j < st.size(); j++)
  52. {
  53. if(!st[j]) continue;
  54. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  55. break;
  56. }
  57. if(j >= st.size())
  58. {
  59. ret = fastest;
  60. }
  61. else
  62. {
  63. other = st[j];
  64. if(other->Speed(turn) != bestSpeed)
  65. ret = fastest;
  66. else
  67. ret = other;
  68. }
  69. }
  70. assert(ret);
  71. if(ret == fastest)
  72. st[i] = NULL;
  73. else
  74. st[j] = NULL;
  75. curside = ret->attackerOwned;
  76. return ret;
  77. }
  78. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  79. {
  80. for(ui32 g=0; g<stacks.size(); ++g)
  81. {
  82. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  83. return stacks[g];
  84. }
  85. return NULL;
  86. }
  87. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  88. {
  89. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  90. }
  91. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive)
  92. {
  93. for(ui32 g=0; g<stacks.size(); ++g)
  94. {
  95. if(stacks[g]->position == tileID
  96. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  97. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  98. {
  99. if(!onlyAlive || stacks[g]->alive())
  100. {
  101. return stacks[g];
  102. }
  103. }
  104. }
  105. return NULL;
  106. }
  107. const CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive) const
  108. {
  109. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  110. }
  111. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<BattleHex> & occupyable, bool flying, const CStack * stackToOmmit) const
  112. {
  113. memset(accessibility, 1, GameConstants::BFIELD_SIZE); //initialize array with trues
  114. //removing accessibility for side columns of hexes
  115. for(int v = 0; v < GameConstants::BFIELD_SIZE; ++v)
  116. {
  117. if( v % GameConstants::BFIELD_WIDTH == 0 || v % GameConstants::BFIELD_WIDTH == (GameConstants::BFIELD_WIDTH - 1) )
  118. accessibility[v] = false;
  119. }
  120. for(ui32 g=0; g<stacks.size(); ++g)
  121. {
  122. if(!stacks[g]->alive() || (stackToOmmit && stacks[g]->ID==stackToOmmit->ID) || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  123. continue;
  124. accessibility[stacks[g]->position] = false;
  125. if(stacks[g]->doubleWide()) //if it's a double hex creature
  126. {
  127. if(stacks[g]->attackerOwned)
  128. accessibility[stacks[g]->position-1] = false;
  129. else
  130. accessibility[stacks[g]->position+1] = false;
  131. }
  132. }
  133. //obstacles
  134. for(ui32 b=0; b<obstacles.size(); ++b)
  135. {
  136. std::vector<BattleHex> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  137. for(ui32 c=0; c<blocked.size(); ++c)
  138. {
  139. if(blocked[c] >=0 && blocked[c] < GameConstants::BFIELD_SIZE)
  140. accessibility[blocked[c]] = false;
  141. }
  142. }
  143. //walls
  144. if(siege > 0)
  145. {
  146. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  147. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  148. {
  149. accessibility[permanentlyLocked[b]] = false;
  150. }
  151. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  152. {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
  153. std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
  154. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  155. {
  156. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  157. {
  158. accessibility[lockedIfNotDestroyed[b].second] = false;
  159. }
  160. }
  161. //gate
  162. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  163. {
  164. accessibility[95] = accessibility[96] = false; //block gate's hexes
  165. }
  166. }
  167. //occupyability
  168. if(addOccupiable && twoHex)
  169. {
  170. std::set<BattleHex> rem; //tiles to unlock
  171. for(int h=0; h<GameConstants::BFIELD_HEIGHT; ++h)
  172. {
  173. for(int w=1; w<GameConstants::BFIELD_WIDTH-1; ++w)
  174. {
  175. BattleHex hex(w, h);
  176. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  177. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  178. )
  179. rem.insert(hex);
  180. }
  181. }
  182. occupyable = rem;
  183. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  184. {
  185. accessibility[*it] = true;
  186. }*/
  187. }
  188. }
  189. bool BattleInfo::isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  190. {
  191. if(flying && !lastPos)
  192. return true;
  193. if(twoHex)
  194. {
  195. //if given hex is accessible and appropriate adjacent one is free too
  196. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  197. }
  198. else
  199. {
  200. return accessibility[hex];
  201. }
  202. }
  203. void BattleInfo::makeBFS(BattleHex start, bool *accessibility, BattleHex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  204. {
  205. //inits
  206. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  207. predecessor[b] = -1;
  208. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  209. dists[g] = 100000000;
  210. std::queue< std::pair<BattleHex, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  211. hexq.push(std::make_pair(start, true));
  212. dists[hexq.front().first] = 0;
  213. int curNext = -1; //for bfs loop only (helper var)
  214. while(!hexq.empty()) //bfs loop
  215. {
  216. std::pair<BattleHex, bool> curHex = hexq.front();
  217. std::vector<BattleHex> neighbours = curHex.first.neighbouringTiles();
  218. hexq.pop();
  219. for(ui32 nr=0; nr<neighbours.size(); nr++)
  220. {
  221. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  222. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  223. if( dists[curHex.first]+1 >= dists[curNext] )
  224. continue;
  225. if(accessible && curHex.second)
  226. {
  227. hexq.push(std::make_pair(curNext, true));
  228. dists[curNext] = dists[curHex.first] + 1;
  229. }
  230. else if(fillPredecessors && !(accessible && !curHex.second))
  231. {
  232. hexq.push(std::make_pair(curNext, false));
  233. dists[curNext] = dists[curHex.first] + 1;
  234. }
  235. predecessor[curNext] = curHex.first;
  236. }
  237. }
  238. };
  239. std::vector<BattleHex> BattleInfo::getAccessibility( const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable ) const
  240. {
  241. std::vector<BattleHex> ret;
  242. bool ac[GameConstants::BFIELD_SIZE];
  243. if(stack->position < 0) //turrets
  244. return std::vector<BattleHex>();
  245. std::set<BattleHex> occupyable;
  246. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, addOccupiable, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  247. BattleHex pr[GameConstants::BFIELD_SIZE];
  248. int dist[GameConstants::BFIELD_SIZE];
  249. makeBFS(stack->position, ac, pr, dist, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), false);
  250. if(stack->doubleWide())
  251. {
  252. if(!addOccupiable)
  253. {
  254. std::vector<BattleHex> rem;
  255. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  256. {
  257. //don't take into account most left and most right columns of hexes
  258. if( b % GameConstants::BFIELD_WIDTH == 0 || b % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1 )
  259. continue;
  260. if( ac[b] && !(stack->attackerOwned ? ac[b-1] : ac[b+1]) )
  261. {
  262. rem.push_back(b);
  263. }
  264. }
  265. for(ui32 g=0; g<rem.size(); ++g)
  266. {
  267. ac[rem[g]] = false;
  268. }
  269. //removing accessibility for side hexes
  270. for(int v=0; v<GameConstants::BFIELD_SIZE; ++v)
  271. if(stack->attackerOwned ? (v%GameConstants::BFIELD_WIDTH)==1 : (v%GameConstants::BFIELD_WIDTH)==(GameConstants::BFIELD_WIDTH - 2))
  272. ac[v] = false;
  273. }
  274. }
  275. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  276. {
  277. bool rangeFits;
  278. if (tacticDistance)
  279. rangeFits = isInTacticRange(i);
  280. else
  281. rangeFits = dist[i] <= stack->Speed(0, true); //we can reach the stack
  282. if( ( !addOccupiable && rangeFits && ac[i] )
  283. || ( addOccupiable && rangeFits && isAccessible(i, ac, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), true) )//we can reach it
  284. || (vstd::contains(occupyable, i) && (!tacticDistance && dist[ i + (stack->attackerOwned ? 1 : -1 ) ] <= stack->Speed(0, true) ) && ac[i + (stack->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  285. )
  286. {
  287. ret.push_back(i);
  288. }
  289. }
  290. if(attackable)
  291. {
  292. struct HLP
  293. {
  294. static bool meleeAttackable(BattleHex hex, const std::vector<BattleHex> & baseRng)
  295. {
  296. BOOST_FOREACH(BattleHex h, baseRng)
  297. {
  298. if(BattleHex::mutualPosition(h, hex) > 0)
  299. return true;
  300. }
  301. return false;
  302. }
  303. };
  304. BOOST_FOREACH(const CStack * otherSt, stacks)
  305. {
  306. if(otherSt->owner == stack->owner)
  307. continue;
  308. std::vector<BattleHex> occupiedBySecond;
  309. occupiedBySecond.push_back(otherSt->position);
  310. if(otherSt->doubleWide())
  311. occupiedBySecond.push_back(otherSt->occupiedHex());
  312. if(battleCanShoot(stack, otherSt->position))
  313. {
  314. attackable->insert(attackable->end(), occupiedBySecond.begin(), occupiedBySecond.end());
  315. continue;
  316. }
  317. BOOST_FOREACH(BattleHex he, occupiedBySecond)
  318. {
  319. if(HLP::meleeAttackable(he, ret))
  320. attackable->push_back(he);
  321. }
  322. }
  323. }
  324. return ret;
  325. }
  326. int BattleInfo::getAvaliableHex(TCreature creID, bool attackerOwned, int initialPos) const
  327. {
  328. int pos;
  329. if (initialPos > -1)
  330. pos = initialPos;
  331. else
  332. {
  333. if (attackerOwned)
  334. pos = 0; //top left
  335. else
  336. pos = GameConstants::BFIELD_WIDTH; //top right
  337. }
  338. bool ac[GameConstants::BFIELD_SIZE];
  339. std::set<BattleHex> occupyable;
  340. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  341. bool flying = VLC->creh->creatures[creID]->isFlying();// vstd::contains(VLC->creh->creatures[creID]->bonuses, Bonus::FLYING);
  342. getAccessibilityMap(ac, twoHex, attackerOwned, true, occupyable, flying);
  343. for (int g = pos; (-1 < g) && (g < GameConstants::BFIELD_SIZE); )
  344. {
  345. if ((g % GameConstants::BFIELD_WIDTH != 0) && (g % GameConstants::BFIELD_WIDTH != GameConstants::BFIELD_WIDTH-1) && BattleInfo::isAccessible (g, ac, twoHex, attackerOwned, flying, true))
  346. {
  347. pos = g;
  348. break;
  349. }
  350. if (attackerOwned)
  351. ++g; //probably some more sophisticated range-based iteration is needed
  352. else
  353. --g;
  354. }
  355. return pos;
  356. }
  357. bool BattleInfo::isStackBlocked(const CStack * stack) const
  358. {
  359. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  360. return false;
  361. BOOST_FOREACH(CStack * s, getAdjacentCreatures(stack))
  362. {
  363. if (s->owner != stack->owner) //blocked by enemy stack
  364. return true;
  365. }
  366. return false;
  367. }
  368. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  369. {
  370. BattleHex predecessor[GameConstants::BFIELD_SIZE]; //for getting the Path
  371. int dist[GameConstants::BFIELD_SIZE]; //calculated distances
  372. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  373. if(predecessor[dest] == -1) //cannot reach destination
  374. {
  375. return std::make_pair(std::vector<BattleHex>(), 0);
  376. }
  377. //making the Path
  378. std::vector<BattleHex> path;
  379. BattleHex curElem = dest;
  380. while(curElem != start)
  381. {
  382. path.push_back(curElem);
  383. curElem = predecessor[curElem];
  384. }
  385. return std::make_pair(path, dist[dest]);
  386. }
  387. TDmgRange BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount, TQuantity defenderCount, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  388. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg ) const
  389. {
  390. double additiveBonus = 1.0, multBonus = 1.0,
  391. minDmg = attacker->getMinDamage() * attackerCount,
  392. maxDmg = attacker->getMaxDamage() * attackerCount;
  393. if(attacker->getCreature()->idNumber == 149) //arrow turret
  394. {
  395. switch(attacker->position)
  396. {
  397. case -2: //keep
  398. minDmg = 15;
  399. maxDmg = 15;
  400. break;
  401. case -3: case -4: //turrets
  402. minDmg = 7.5;
  403. maxDmg = 7.5;
  404. break;
  405. }
  406. }
  407. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  408. { //minDmg and maxDmg are multiplied by hero attack + 1
  409. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  410. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  411. }
  412. int attackDefenceDifference = 0;
  413. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  414. {
  415. double multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0;
  416. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  417. }
  418. else
  419. {
  420. attackDefenceDifference = attacker->Attack();
  421. }
  422. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  423. {
  424. double multDefenceReduction = (100 - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0;
  425. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  426. }
  427. else
  428. {
  429. attackDefenceDifference -= defender->Defense();
  430. }
  431. //calculating total attack/defense skills modifier
  432. if(shooting) //precision handling (etc.)
  433. attackDefenceDifference += attacker->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT))->totalValue();
  434. else //bloodlust handling (etc.)
  435. attackDefenceDifference += attacker->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))->totalValue();
  436. if(attacker->getEffect(55)) //slayer handling
  437. {
  438. std::vector<int> affectedIds;
  439. int spLevel = attacker->getEffect(55)->val;
  440. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  441. {
  442. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->getBonusList())
  443. {
  444. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  445. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  446. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  447. {
  448. affectedIds.push_back(g);
  449. break;
  450. }
  451. }
  452. }
  453. for(ui32 g=0; g<affectedIds.size(); ++g)
  454. {
  455. if(defender->getCreature()->idNumber == affectedIds[g])
  456. {
  457. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  458. break;
  459. }
  460. }
  461. }
  462. //bonus from attack/defense skills
  463. if(attackDefenceDifference < 0) //decreasing dmg
  464. {
  465. double dec = 0.025 * (-attackDefenceDifference);
  466. if(dec > 0.7)
  467. {
  468. multBonus *= 0.3; //1.0 - 0.7
  469. }
  470. else
  471. {
  472. multBonus *= 1.0 - dec;
  473. }
  474. }
  475. else //increasing dmg
  476. {
  477. double inc = 0.05 * attackDefenceDifference;
  478. if(inc > 4.0)
  479. {
  480. additiveBonus += 4.0;
  481. }
  482. else
  483. {
  484. additiveBonus += inc;
  485. }
  486. }
  487. //applying jousting bonus
  488. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  489. additiveBonus += charge * 0.05;
  490. //handling secondary abilities and artifacts giving premies to them
  491. if(attackerHero)
  492. {
  493. if(shooting)
  494. {
  495. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARCHERY) / 100.0;
  496. }
  497. else
  498. {
  499. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::OFFENCE) / 100.0;
  500. }
  501. }
  502. if(defendingHero)
  503. {
  504. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARMORER))) / 100.0;
  505. }
  506. //handling hate effect
  507. additiveBonus += attacker->valOfBonuses(Bonus::HATE, defender->getCreature()->idNumber) / 100.;
  508. //luck bonus
  509. if (lucky)
  510. {
  511. additiveBonus += 1.0;
  512. }
  513. //ballista double dmg
  514. if(ballistaDoubleDmg)
  515. {
  516. additiveBonus += 1.0;
  517. }
  518. if (deathBlow) //Dread Knight and many WoGified creatures
  519. {
  520. additiveBonus += 1.0;
  521. }
  522. //handling spell effects
  523. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  524. {
  525. multBonus *= defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0) / 100.0;
  526. }
  527. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  528. {
  529. multBonus *= defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1) / 100.0;
  530. }
  531. TBonusListPtr curseEffects = attacker->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE)); //attacker->getEffect(42);
  532. TBonusListPtr blessEffects = attacker->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE)); //attacker->getEffect(43);
  533. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  534. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
  535. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  536. {
  537. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  538. }
  539. class HLP
  540. {
  541. public:
  542. static bool hasAdvancedAirShield(const CStack * stack)
  543. {
  544. BOOST_FOREACH(const Bonus *it, stack->getBonusList())
  545. {
  546. if (it->source == Bonus::SPELL_EFFECT && it->sid == 28 && it->val >= 2)
  547. {
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. };
  554. //wall / distance penalty + advanced air shield
  555. bool distPenalty = !NBonus::hasOfType(attackerHero, Bonus::NO_DISTANCE_PENALTY) &&
  556. hasDistancePenalty(attacker, defender->position);
  557. bool obstaclePenalty = hasWallPenalty(attacker, defender->position);
  558. if (shooting)
  559. {
  560. if (distPenalty || HLP::hasAdvancedAirShield(defender))
  561. {
  562. multBonus *= 0.5;
  563. }
  564. if (obstaclePenalty)
  565. {
  566. multBonus *= 0.5; //cumulative
  567. }
  568. }
  569. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  570. {
  571. multBonus *= 0.5;
  572. }
  573. minDmg *= additiveBonus * multBonus;
  574. maxDmg *= additiveBonus * multBonus;
  575. TDmgRange returnedVal;
  576. if(curseEffects->size()) //curse handling (rest)
  577. {
  578. minDmg += curseBlessAdditiveModifier;
  579. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  580. }
  581. else if(blessEffects->size()) //bless handling
  582. {
  583. maxDmg += curseBlessAdditiveModifier;
  584. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  585. }
  586. else
  587. {
  588. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  589. }
  590. //damage cannot be less than 1
  591. vstd::amax(returnedVal.first, 1);
  592. vstd::amax(returnedVal.second, 1);
  593. return returnedVal;
  594. }
  595. TDmgRange BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  596. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg) const
  597. {
  598. return calculateDmgRange(attacker, defender, attacker->count, defender->count, attackerHero, defendingHero, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  599. }
  600. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  601. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg )
  602. {
  603. TDmgRange range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  604. if(range.first != range.second)
  605. {
  606. int valuesToAverage[10];
  607. int howManyToAv = std::min<ui32>(10, attacker->count);
  608. for (int g=0; g<howManyToAv; ++g)
  609. {
  610. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  611. }
  612. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  613. }
  614. else
  615. return range.first;
  616. }
  617. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  618. {
  619. for(ui32 i=0; i<stacks.size();i++)//setting casualties
  620. {
  621. const CStack * const st = stacks[i];
  622. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  623. vstd::amax(killed, 0);
  624. if(killed)
  625. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  626. }
  627. }
  628. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, BattleHex destinationTile )
  629. {
  630. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  631. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  632. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  633. if(s->id == Spells::DEATH_RIPPLE || s->id == Spells::DESTROY_UNDEAD || s->id == Spells::ARMAGEDDON)
  634. {
  635. for(int it=0; it<stacks.size(); ++it)
  636. {
  637. if((s->id == Spells::DEATH_RIPPLE && !stacks[it]->getCreature()->isUndead()) //death ripple
  638. || (s->id == Spells::DESTROY_UNDEAD && stacks[it]->getCreature()->isUndead()) //destroy undead
  639. || (s->id == Spells::ARMAGEDDON) //Armageddon
  640. )
  641. {
  642. if(stacks[it]->isValidTarget())
  643. attackedCres.insert(stacks[it]);
  644. }
  645. }
  646. }
  647. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  648. {
  649. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  650. {
  651. CStack * st = getStackT(*it, onlyAlive);
  652. if(st)
  653. {
  654. if (s->id == 76) //Death Cloud //TODO: fireball and fire immunity
  655. {
  656. if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
  657. {
  658. attackedCres.insert(st);
  659. }
  660. }
  661. else
  662. attackedCres.insert(st);
  663. }
  664. }
  665. }
  666. else if(s->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  667. {
  668. if(skillLevel < 3) /*not expert */
  669. {
  670. CStack * st = getStackT(destinationTile, onlyAlive);
  671. if(st)
  672. attackedCres.insert(st);
  673. }
  674. else
  675. {
  676. for(int it=0; it<stacks.size(); ++it)
  677. {
  678. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  679. if((!s->isNegative() && stacks[it]->owner == attackerOwner)
  680. ||(!s->isPositive() && stacks[it]->owner != attackerOwner )
  681. )
  682. {
  683. if(stacks[it]->isValidTarget(!onlyAlive))
  684. attackedCres.insert(stacks[it]);
  685. }
  686. }
  687. } //if(caster->getSpellSchoolLevel(s) < 3)
  688. }
  689. else if(s->getTargetType() == CSpell::CREATURE)
  690. {
  691. CStack * st = getStackT(destinationTile, onlyAlive);
  692. if(st)
  693. attackedCres.insert(st);
  694. }
  695. else //custom range from attackedHexes
  696. {
  697. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  698. {
  699. CStack * st = getStackT(*it, onlyAlive);
  700. if(st)
  701. attackedCres.insert(st);
  702. }
  703. }
  704. return attackedCres;
  705. }
  706. void BattleInfo::getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  707. {
  708. const int WN = GameConstants::BFIELD_WIDTH;
  709. ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  710. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  711. {
  712. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  713. BOOST_FOREACH (BattleHex tile, hexes)
  714. {
  715. at.hostileCreaturePositions.insert(tile);
  716. }
  717. }
  718. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  719. {
  720. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  721. BOOST_FOREACH (BattleHex tile, hexes)
  722. {
  723. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1) //adjacent both to attacker's head and attacked tile
  724. || tile == destinationTile) //or simply attacked directly
  725. {
  726. CStack * st = getStackT(tile, true);
  727. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  728. {
  729. at.hostileCreaturePositions.insert(tile);
  730. }
  731. }
  732. }
  733. }
  734. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  735. {
  736. std::vector<BattleHex> hexes; //only one, in fact
  737. int pseudoVector = destinationTile.hex - hex;
  738. switch (pseudoVector)
  739. {
  740. case 1:
  741. case -1:
  742. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  743. break;
  744. case WN: //17
  745. case WN + 1: //18
  746. case -WN: //-17
  747. case -WN + 1: //-16
  748. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : -1 ), hexes);
  749. break;
  750. case WN-1: //16
  751. case -WN-1: //-18
  752. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : 0), hexes);
  753. break;
  754. }
  755. BOOST_FOREACH (BattleHex tile, hexes)
  756. {
  757. CStack * st = getStackT(tile, true);
  758. if(st) //friendly stacks can also be damaged by Dragon Breath
  759. {
  760. at.friendlyCreaturePositions.insert(tile);
  761. }
  762. }
  763. }
  764. }
  765. std::set<CStack*> BattleInfo::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  766. { //TODO: caching?
  767. AttackableTiles at;
  768. getPotentiallyAttackableHexes(at, attacker, destinationTile, attackerPos);
  769. std::set<CStack*> attackedCres;
  770. BOOST_FOREACH (BattleHex tile, at.hostileCreaturePositions) //all around & three-headed attack
  771. {
  772. CStack * st = getStackT(tile, true);
  773. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  774. {
  775. attackedCres.insert(st);
  776. }
  777. }
  778. BOOST_FOREACH (BattleHex tile, at.friendlyCreaturePositions)
  779. {
  780. CStack * st = getStackT(tile, true);
  781. if(st) //friendly stacks can also be damaged by Dragon Breath
  782. {
  783. attackedCres.insert(st);
  784. }
  785. }
  786. return attackedCres;
  787. }
  788. std::set<BattleHex> BattleInfo::getAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  789. {
  790. AttackableTiles at;
  791. getPotentiallyAttackableHexes(at, attacker, destinationTile, attackerPos);
  792. std::set<BattleHex> attackedHexes;
  793. BOOST_FOREACH (BattleHex tile, at.hostileCreaturePositions)
  794. {
  795. CStack * st = getStackT(tile, true);
  796. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  797. {
  798. attackedHexes.insert(tile);
  799. }
  800. }
  801. BOOST_FOREACH (BattleHex tile, at.friendlyCreaturePositions)
  802. {
  803. CStack * st = getStackT(tile, true);
  804. if(st) //friendly stacks can also be damaged by Dragon Breath
  805. {
  806. attackedHexes.insert(tile);
  807. }
  808. }
  809. return attackedHexes;
  810. }
  811. std::set<CStack*> BattleInfo::getAdjacentCreatures (const CStack * stack) const
  812. {
  813. std::set<CStack*> stacks;
  814. CStack * localStack;
  815. BOOST_FOREACH (BattleHex hex, stack->getSurroundingHexes())
  816. {
  817. localStack = const_cast<CStack*>(getStackT(hex, true)); //only alive?
  818. if (localStack)
  819. stacks.insert(localStack);
  820. }
  821. return stacks;
  822. }
  823. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower)
  824. {
  825. if(!caster)
  826. {
  827. if (!usedSpellPower)
  828. return 3; //default duration of all creature spells
  829. else
  830. return usedSpellPower; //use creature spell power
  831. }
  832. switch(spell->id)
  833. {
  834. case 56: //frenzy
  835. return 1;
  836. default: //other spells
  837. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  838. }
  839. }
  840. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, BattleHex position) const
  841. {
  842. int owner = attackerOwned ? sides[0] : sides[1];
  843. assert((owner >= GameConstants::PLAYER_LIMIT) ||
  844. (base.armyObj && base.armyObj->tempOwner == owner));
  845. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  846. ret->position = position;
  847. return ret;
  848. }
  849. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, int stackID, bool attackerOwned, int slot, BattleHex position) const
  850. {
  851. int owner = attackerOwned ? sides[0] : sides[1];
  852. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  853. ret->position = position;
  854. return ret;
  855. }
  856. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  857. {
  858. ui32 ret = caster->getSpellCost(sp);
  859. //checking for friendly stacks reducing cost of the spell and
  860. //enemy stacks increasing it
  861. si32 manaReduction = 0;
  862. si32 manaIncrease = 0;
  863. for(int g=0; g<stacks.size(); ++g)
  864. {
  865. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  866. {
  867. vstd::amax(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  868. }
  869. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  870. {
  871. vstd::amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  872. }
  873. }
  874. return ret - manaReduction + manaIncrease;
  875. }
  876. int BattleInfo::hexToWallPart(BattleHex hex) const
  877. {
  878. if(siege == 0) //there is no battle!
  879. return -1;
  880. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  881. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  882. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7),
  883. std::make_pair(45, -2), std::make_pair(78, -2), std::make_pair(112, -2), std::make_pair(147, -2)}; // -2 - indestructible walls
  884. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  885. {
  886. if(attackable[g].first == hex)
  887. return attackable[g].second;
  888. }
  889. return -1; //not found!
  890. }
  891. int BattleInfo::lineToWallHex( int line ) const
  892. {
  893. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  894. return lineToHex[line];
  895. }
  896. std::pair<const CStack *, BattleHex> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  897. {
  898. bool ac[GameConstants::BFIELD_SIZE];
  899. std::set<BattleHex> occupyable;
  900. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest);
  901. BattleHex predecessor[GameConstants::BFIELD_SIZE];
  902. int dist[GameConstants::BFIELD_SIZE];
  903. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  904. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  905. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  906. {
  907. const CStack * atG = getStackT(g);
  908. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  909. continue;
  910. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  911. {
  912. if(predecessor[g] == -1) //TODO: is it really the best solution?
  913. continue;
  914. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  915. }
  916. }
  917. if(stackPairs.size() > 0)
  918. {
  919. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  920. minimalPairs.push_back(stackPairs[0]);
  921. for(int b=1; b<stackPairs.size(); ++b)
  922. {
  923. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  924. {
  925. minimalPairs.clear();
  926. minimalPairs.push_back(stackPairs[b]);
  927. }
  928. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  929. {
  930. minimalPairs.push_back(stackPairs[b]);
  931. }
  932. }
  933. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  934. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  935. }
  936. return std::make_pair<const CStack * , BattleHex>(NULL, BattleHex::INVALID);
  937. }
  938. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  939. {
  940. ui32 ret = baseDamage;
  941. //applying sorcery secondary skill
  942. if(caster)
  943. {
  944. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0;
  945. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0;
  946. if(sp->air)
  947. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  948. else if(sp->fire) //only one type of bonus for Magic Arrow
  949. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  950. else if(sp->water)
  951. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  952. else if(sp->earth)
  953. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  954. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  955. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  956. }
  957. return ret;
  958. }
  959. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  960. {
  961. ui32 ret = 0; //value to return
  962. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  963. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  964. //check if spell really does damage - if not, return 0
  965. if(VLC->spellh->damageSpells.find(sp->id) == VLC->spellh->damageSpells.end())
  966. return 0;
  967. ret = usedSpellPower * sp->power;
  968. ret += sp->powers[spellSchoolLevel];
  969. //affected creature-specific part
  970. if(affectedCreature)
  971. {
  972. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  973. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  974. {
  975. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  976. ret /= 100;
  977. }
  978. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  979. {
  980. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  981. ret /= 100;
  982. }
  983. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  984. {
  985. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  986. ret /= 100;
  987. }
  988. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  989. {
  990. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  991. ret /= 100;
  992. }
  993. //general spell dmg reduction
  994. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  995. {
  996. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  997. ret /= 100;
  998. }
  999. //dmg increasing
  1000. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  1001. {
  1002. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  1003. ret /= 100;
  1004. }
  1005. }
  1006. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  1007. return ret;
  1008. }
  1009. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  1010. {
  1011. bool resurrect = resurrects(spell->id);
  1012. int healedHealth = caster->getPrimSkillLevel(2) * spell->power + spell->powers[caster->getSpellSchoolLevel(spell)];
  1013. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  1014. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1015. }
  1016. ui32 BattleInfo::calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const
  1017. {
  1018. bool resurrect = resurrects(spell->id);
  1019. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1020. }
  1021. ui32 BattleInfo::calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const
  1022. {
  1023. bool resurrect = resurrects(spell->id);
  1024. int healedHealth = usedSpellPower * spell->power + spell->powers[spellSchoolLevel];
  1025. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1026. }
  1027. bool BattleInfo::resurrects(TSpell spellid) const
  1028. {
  1029. return vstd::contains(VLC->spellh->risingSpells, spellid);
  1030. }
  1031. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  1032. {
  1033. //we'll split creatures with remaining movement to 4 parts
  1034. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  1035. int toMove = 0; //how many stacks still has move
  1036. const CStack *active = getStack(activeStack);
  1037. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  1038. if(!turn && active && active->willMove() && !vstd::contains(active->state, EBattleStackState::WAITING))
  1039. {
  1040. out.push_back(active);
  1041. if(out.size() == howMany)
  1042. return;
  1043. }
  1044. for(ui32 i=0; i<stacks.size(); ++i)
  1045. {
  1046. const CStack * const s = stacks[i];
  1047. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  1048. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  1049. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  1050. {
  1051. continue;
  1052. }
  1053. int p = -1; //in which phase this tack will move?
  1054. if(turn <= 0 && vstd::contains(s->state, EBattleStackState::WAITING)) //consider waiting state only for ongoing round
  1055. {
  1056. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  1057. p = 2;
  1058. else
  1059. p = 3;
  1060. }
  1061. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  1062. {
  1063. p = 0;
  1064. }
  1065. else
  1066. {
  1067. p = 1;
  1068. }
  1069. phase[p].push_back(s);
  1070. toMove++;
  1071. }
  1072. for(int i = 0; i < 4; i++)
  1073. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  1074. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  1075. out.push_back(phase[0][i]);
  1076. if(out.size() == howMany)
  1077. return;
  1078. if(lastMoved == -1)
  1079. {
  1080. if(active)
  1081. {
  1082. if(out.size() && out.front() == active)
  1083. lastMoved = active->attackerOwned;
  1084. else
  1085. lastMoved = active->attackerOwned;
  1086. }
  1087. else
  1088. {
  1089. lastMoved = 0;
  1090. }
  1091. }
  1092. int pi = 1;
  1093. while(out.size() < howMany)
  1094. {
  1095. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  1096. if(!hlp)
  1097. {
  1098. pi++;
  1099. if(pi > 3)
  1100. {
  1101. //if(turn != 2)
  1102. getStackQueue(out, howMany, turn + 1, lastMoved);
  1103. return;
  1104. }
  1105. }
  1106. else
  1107. {
  1108. out.push_back(hlp);
  1109. }
  1110. }
  1111. }
  1112. si8 BattleInfo::hasDistancePenalty( const CStack * stack, BattleHex destHex ) const
  1113. {
  1114. struct HLP
  1115. {
  1116. static bool lowerAnalyze(const CStack * stack, BattleHex hex)
  1117. {
  1118. int distance = BattleHex::getDistance(hex, stack->position);
  1119. //I hope it's approximately correct
  1120. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  1121. }
  1122. };
  1123. const CStack * dstStack = getStackT(destHex, false);
  1124. if (dstStack->doubleWide())
  1125. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  1126. else
  1127. return HLP::lowerAnalyze(stack, destHex);
  1128. }
  1129. si8 BattleInfo::sameSideOfWall(int pos1, int pos2) const
  1130. {
  1131. int wallInStackLine = lineToWallHex(pos1/GameConstants::BFIELD_WIDTH);
  1132. int wallInDestLine = lineToWallHex(pos2/GameConstants::BFIELD_WIDTH);
  1133. bool stackLeft = pos1 < wallInStackLine;
  1134. bool destLeft = pos2 < wallInDestLine;
  1135. return stackLeft != destLeft;
  1136. }
  1137. si8 BattleInfo::hasWallPenalty( const CStack* stack, BattleHex destHex ) const
  1138. {
  1139. if (!siege || stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  1140. {
  1141. return false;
  1142. }
  1143. int wallInStackLine = lineToWallHex(stack->position/GameConstants::BFIELD_WIDTH);
  1144. int wallInDestLine = lineToWallHex(destHex/GameConstants::BFIELD_WIDTH);
  1145. bool stackLeft = stack->position < wallInStackLine;
  1146. bool destRight = destHex > wallInDestLine;
  1147. if (stackLeft && destRight) //shooting from outside to inside
  1148. {
  1149. int row = (stack->position + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  1150. if (stack->position > destHex && ((destHex % GameConstants::BFIELD_WIDTH - stack->position % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  1151. row -= 2;
  1152. int wallPos = lineToWallHex(row);
  1153. if (hexToWallPart(wallPos) != -1) //wall still exists or is indestructible
  1154. return true;
  1155. }
  1156. return false;
  1157. }
  1158. si8 BattleInfo::canTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  1159. {
  1160. bool ac[GameConstants::BFIELD_SIZE];
  1161. std::set<BattleHex> occupyable;
  1162. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, false, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  1163. if (siege && telportLevel < 2) //check for wall
  1164. {
  1165. return ac[destHex] && sameSideOfWall(stack->position, destHex);
  1166. }
  1167. else
  1168. {
  1169. return ac[destHex];
  1170. }
  1171. }
  1172. bool BattleInfo::battleCanShoot(const CStack * stack, BattleHex dest) const
  1173. {
  1174. const CStack *dst = getStackT(dest);
  1175. if(!stack || !dst) return false;
  1176. const CGHeroInstance * stackHero = battleGetOwner(stack);
  1177. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  1178. return false;
  1179. if(stack->getCreature()->idNumber == 145 && dst) //catapult cannot attack creatures
  1180. return false;
  1181. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  1182. && stack->owner != dst->owner
  1183. && dst->alive()
  1184. && (!isStackBlocked(stack) || NBonus::hasOfType(stackHero, Bonus::FREE_SHOOTING))
  1185. && stack->shots
  1186. )
  1187. return true;
  1188. return false;
  1189. }
  1190. bool BattleInfo::battleCanFlee(int player) const
  1191. {
  1192. if (player == sides[0])
  1193. {
  1194. if (!heroes[0])
  1195. return false;//current player have no hero
  1196. }
  1197. else
  1198. {
  1199. if (!heroes[1])
  1200. return false;
  1201. }
  1202. if( ( heroes[0] && heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  1203. || ( heroes[1] && heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  1204. return false;
  1205. if (player == sides[1] && siege //defender in siege
  1206. && !(town->subID == 6 && vstd::contains(town->builtBuildings, 17)))//without escape tunnel
  1207. return false;
  1208. return true;
  1209. }
  1210. const CStack * BattleInfo::battleGetStack(BattleHex pos, bool onlyAlive)
  1211. {
  1212. CStack * stack = NULL;
  1213. for(ui32 g=0; g<stacks.size(); ++g)
  1214. {
  1215. if(stacks[g]->position == pos
  1216. || (stacks[g]->doubleWide()
  1217. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  1218. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  1219. ) )
  1220. {
  1221. if (stacks[g]->alive())
  1222. return stacks[g]; //we prefer living stacks - there cna be only one stack on te tile, so return it imediately
  1223. else if (!onlyAlive)
  1224. stack = stacks[g]; //dead stacks are only accessible when there's no alive stack on this tile
  1225. }
  1226. }
  1227. return stack;
  1228. }
  1229. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  1230. {
  1231. return heroes[!stack->attackerOwned];
  1232. }
  1233. si8 BattleInfo::battleMinSpellLevel() const
  1234. {
  1235. si8 levelLimit = 0;
  1236. if(const CGHeroInstance *h1 = heroes[0])
  1237. {
  1238. vstd::amax(levelLimit, h1->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1239. }
  1240. if(const CGHeroInstance *h2 = heroes[1])
  1241. {
  1242. vstd::amax(levelLimit, h2->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1243. }
  1244. return levelLimit;
  1245. }
  1246. void BattleInfo::localInit()
  1247. {
  1248. belligerents[0]->battle = belligerents[1]->battle = this;
  1249. BOOST_FOREACH(CArmedInstance *b, belligerents)
  1250. b->attachTo(this);
  1251. BOOST_FOREACH(CStack *s, stacks)
  1252. {
  1253. s->exportBonuses();
  1254. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  1255. {
  1256. s->attachTo(const_cast<CStackInstance*>(s->base));
  1257. }
  1258. else //attach directly to obj to which stack belongs and creature type
  1259. {
  1260. CArmedInstance *army = belligerents[!s->attackerOwned];
  1261. s->attachTo(army);
  1262. assert(s->type);
  1263. s->attachTo(const_cast<CCreature*>(s->type));
  1264. }
  1265. s->postInit();
  1266. }
  1267. exportBonuses();
  1268. }
  1269. namespace CGH
  1270. {
  1271. using namespace std;
  1272. static void readBattlePositions(const JsonNode &node, vector< vector<int> > & dest)
  1273. {
  1274. BOOST_FOREACH(const JsonNode &level, node.Vector())
  1275. {
  1276. std::vector<int> pom;
  1277. BOOST_FOREACH(const JsonNode &value, level.Vector())
  1278. {
  1279. pom.push_back(value.Float());
  1280. }
  1281. dest.push_back(pom);
  1282. }
  1283. }
  1284. }
  1285. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1286. {
  1287. CMP_stack cmpst;
  1288. BattleInfo *curB = new BattleInfo;
  1289. curB->sides[0] = armies[0]->tempOwner;
  1290. curB->sides[1] = armies[1]->tempOwner;
  1291. if(curB->sides[1] == 254)
  1292. curB->sides[1] = 255;
  1293. std::vector<CStack*> & stacks = (curB->stacks);
  1294. curB->tile = tile;
  1295. curB->battlefieldType = terType;
  1296. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1297. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1298. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1299. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1300. curB->round = -2;
  1301. curB->activeStack = -1;
  1302. curB->enchanterCounter[0] = curB->enchanterCounter[1] = 0; //ready to cast
  1303. if(town)
  1304. {
  1305. curB->town = town;
  1306. curB->siege = town->fortLevel();
  1307. }
  1308. else
  1309. {
  1310. curB->town = NULL;
  1311. curB->siege = 0;
  1312. }
  1313. //reading battleStartpos
  1314. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1315. const JsonNode config(GameConstants::DATA_DIR + "/config/battleStartpos.json");
  1316. const JsonVector &positions = config["battle_positions"].Vector();
  1317. CGH::readBattlePositions(positions[0]["levels"], attackerLoose);
  1318. CGH::readBattlePositions(positions[1]["levels"], defenderLoose);
  1319. CGH::readBattlePositions(positions[2]["levels"], attackerTight);
  1320. CGH::readBattlePositions(positions[3]["levels"], defenderTight);
  1321. CGH::readBattlePositions(positions[4]["levels"], attackerCreBank);
  1322. CGH::readBattlePositions(positions[5]["levels"], defenderCreBank);
  1323. //battleStartpos read
  1324. int k = 0; //stack serial
  1325. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1326. {
  1327. int pos;
  1328. if(creatureBank)
  1329. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1330. else if(armies[0]->formation)
  1331. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1332. else
  1333. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1334. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), true, i->first, pos);
  1335. stacks.push_back(stack);
  1336. }
  1337. k = 0;
  1338. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1339. {
  1340. int pos;
  1341. if(creatureBank)
  1342. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1343. else if(armies[1]->formation)
  1344. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1345. else
  1346. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1347. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), false, i->first, pos);
  1348. stacks.push_back(stack);
  1349. }
  1350. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1351. {
  1352. //we should do that for creature bank too
  1353. if(stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1354. {
  1355. stacks[g]->position += BattleHex::RIGHT;
  1356. }
  1357. else if(stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1358. {
  1359. if (stacks[g]->position.getX() > 1)
  1360. stacks[g]->position += BattleHex::LEFT;
  1361. }
  1362. }
  1363. //adding war machines
  1364. if(!creatureBank)
  1365. {
  1366. if(heroes[0])
  1367. {
  1368. if(heroes[0]->getArt(13)) //ballista
  1369. {
  1370. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), true, 255, 52);
  1371. stacks.push_back(stack);
  1372. }
  1373. if(heroes[0]->getArt(14)) //ammo cart
  1374. {
  1375. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), true, 255, 18);
  1376. stacks.push_back(stack);
  1377. }
  1378. if(heroes[0]->getArt(15)) //first aid tent
  1379. {
  1380. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), true, 255, 154);
  1381. stacks.push_back(stack);
  1382. }
  1383. }
  1384. if(heroes[1])
  1385. {
  1386. //defending hero shouldn't receive ballista (bug #551)
  1387. if(heroes[1]->getArt(13) && !town) //ballista
  1388. {
  1389. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), false, 255, 66);
  1390. stacks.push_back(stack);
  1391. }
  1392. if(heroes[1]->getArt(14)) //ammo cart
  1393. {
  1394. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), false, 255, 32);
  1395. stacks.push_back(stack);
  1396. }
  1397. if(heroes[1]->getArt(15)) //first aid tent
  1398. {
  1399. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), false, 255, 168);
  1400. stacks.push_back(stack);
  1401. }
  1402. }
  1403. if(town && heroes[0] && town->hasFort()) //catapult
  1404. {
  1405. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), stacks.size(), true, 255, 120);
  1406. stacks.push_back(stack);
  1407. }
  1408. }
  1409. //war machines added
  1410. if (curB->siege == 2 || curB->siege == 3)
  1411. {
  1412. // keep tower
  1413. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -2);
  1414. stacks.push_back(stack);
  1415. if (curB->siege == 3)
  1416. {
  1417. // lower tower + upper tower
  1418. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -4);
  1419. stacks.push_back(stack);
  1420. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -3);
  1421. stacks.push_back(stack);
  1422. }
  1423. }
  1424. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1425. //setting up siege
  1426. if(town && town->hasFort())
  1427. {
  1428. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1429. {
  1430. curB->si.wallState[b] = 1;
  1431. }
  1432. }
  1433. //randomize obstacles
  1434. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1435. {
  1436. bool obAv[GameConstants::BFIELD_SIZE]; //availability of hexes for obstacles;
  1437. std::vector<int> possibleObstacles;
  1438. for(int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  1439. {
  1440. if(i%17 < 4 || i%17 > 12)
  1441. {
  1442. obAv[i] = false;
  1443. }
  1444. else
  1445. {
  1446. obAv[i] = true;
  1447. }
  1448. }
  1449. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1450. {
  1451. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1452. {
  1453. possibleObstacles.push_back(g->first);
  1454. }
  1455. }
  1456. srand(time(NULL));
  1457. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1458. {
  1459. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1460. while(toBlock>0)
  1461. {
  1462. CObstacleInstance coi;
  1463. coi.uniqueID = curB->obstacles.size();
  1464. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1465. coi.pos = rand()%GameConstants::BFIELD_SIZE;
  1466. std::vector<BattleHex> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1467. bool badObstacle = false;
  1468. for(int b=0; b<block.size(); ++b)
  1469. {
  1470. if(block[b] < 0 || block[b] >= GameConstants::BFIELD_SIZE || !obAv[block[b]])
  1471. {
  1472. badObstacle = true;
  1473. break;
  1474. }
  1475. }
  1476. if(badObstacle) continue;
  1477. //obstacle can be placed
  1478. curB->obstacles.push_back(coi);
  1479. for(int b=0; b<block.size(); ++b)
  1480. {
  1481. if(block[b] >= 0 && block[b] < GameConstants::BFIELD_SIZE)
  1482. obAv[block[b]] = false;
  1483. }
  1484. toBlock -= block.size();
  1485. }
  1486. }
  1487. }
  1488. //spell level limiting bonus
  1489. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  1490. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  1491. //giving terrain overalay premies
  1492. int bonusSubtype = -1;
  1493. switch(terType)
  1494. {
  1495. case 9: //magic plains
  1496. {
  1497. bonusSubtype = 0;
  1498. }
  1499. case 14: //fiery fields
  1500. {
  1501. if(bonusSubtype == -1) bonusSubtype = 1;
  1502. }
  1503. case 15: //rock lands
  1504. {
  1505. if(bonusSubtype == -1) bonusSubtype = 8;
  1506. }
  1507. case 16: //magic clouds
  1508. {
  1509. if(bonusSubtype == -1) bonusSubtype = 2;
  1510. }
  1511. case 17: //lucid pools
  1512. {
  1513. if(bonusSubtype == -1) bonusSubtype = 4;
  1514. }
  1515. { //common part for cases 9, 14, 15, 16, 17
  1516. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1517. break;
  1518. }
  1519. case 18: //holy ground
  1520. {
  1521. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::GOOD)));
  1522. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::EVIL)));
  1523. break;
  1524. }
  1525. case 19: //clover field
  1526. { //+2 luck bonus for neutral creatures
  1527. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureFactionLimiter(-1)));
  1528. break;
  1529. }
  1530. case 20: //evil fog
  1531. {
  1532. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::GOOD)));
  1533. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EAlignment::EVIL)));
  1534. break;
  1535. }
  1536. case 22: //cursed ground
  1537. {
  1538. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1539. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1540. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  1541. b->valType = Bonus::INDEPENDENT_MAX;
  1542. curB->addNewBonus(b);
  1543. break;
  1544. }
  1545. }
  1546. //overlay premies given
  1547. //native terrain bonuses
  1548. if(town) //during siege always take premies for native terrain of faction
  1549. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1550. boost::shared_ptr<ILimiter> nativeTerrain(new CreatureNativeTerrainLimiter(terrain));
  1551. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1552. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1553. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1554. //////////////////////////////////////////////////////////////////////////
  1555. //tactics
  1556. int tacticLvls[2] = {0};
  1557. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  1558. {
  1559. if(heroes[i])
  1560. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  1561. }
  1562. if(int diff = tacticLvls[0] - tacticLvls[1])
  1563. {
  1564. curB->tacticsSide = diff < 0;
  1565. curB->tacticDistance = std::abs(diff)*2 + 1;
  1566. }
  1567. else
  1568. curB->tacticDistance = 0;
  1569. // workaround — bonuses affecting only enemy
  1570. for(int i = 0; i < 2; i++)
  1571. {
  1572. TNodes nodes;
  1573. curB->belligerents[i]->getRedAncestors(nodes);
  1574. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  1575. {
  1576. BOOST_FOREACH(Bonus *b, n->getExportedBonusList())
  1577. {
  1578. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  1579. {
  1580. Bonus *bCopy = new Bonus(*b);
  1581. bCopy->effectRange = Bonus::NO_LIMIT;
  1582. bCopy->propagator.reset();
  1583. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  1584. curB->addNewBonus(bCopy);
  1585. }
  1586. }
  1587. }
  1588. }
  1589. return curB;
  1590. }
  1591. bool BattleInfo::isInTacticRange( BattleHex dest ) const
  1592. {
  1593. return ((!tacticsSide && dest.getX() > 0 && dest.getX() <= tacticDistance)
  1594. || (tacticsSide && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - tacticDistance - 1));
  1595. }
  1596. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastSpell(int player, ECastingMode::ECastingMode mode) const
  1597. {
  1598. int side = sides[0] == player ? 0 : 1;
  1599. switch (mode)
  1600. {
  1601. case ECastingMode::HERO_CASTING:
  1602. {
  1603. if(castSpells[side] > 0)
  1604. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  1605. if(!heroes[side])
  1606. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  1607. if(!heroes[side]->getArt(17))
  1608. return ESpellCastProblem::NO_SPELLBOOK;
  1609. }
  1610. break;
  1611. }
  1612. return ESpellCastProblem::OK;
  1613. }
  1614. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastThisSpell( int player, const CSpell * spell, ECastingMode::ECastingMode mode ) const
  1615. {
  1616. ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
  1617. if(genProblem != ESpellCastProblem::OK)
  1618. return genProblem;
  1619. int cside = sides[0] == player ? 0 : 1; //caster's side
  1620. switch(mode)
  1621. {
  1622. case ECastingMode::HERO_CASTING:
  1623. {
  1624. const CGHeroInstance * caster = heroes[cside];
  1625. if(!caster->canCastThisSpell(spell))
  1626. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  1627. if(caster->mana < getSpellCost(spell, caster)) //not enough mana
  1628. return ESpellCastProblem::NOT_ENOUGH_MANA;
  1629. }
  1630. break;
  1631. }
  1632. if(spell->id < 10) //it's adventure spell (not combat))
  1633. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1634. if(NBonus::hasOfType(heroes[1-cside], Bonus::SPELL_IMMUNITY, spell->id)) //non - casting hero provides immunity for this spell
  1635. return ESpellCastProblem::SECOND_HEROS_SPELL_IMMUNITY;
  1636. if(battleMinSpellLevel() > spell->level) //non - casting hero stops caster from casting this spell
  1637. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  1638. int spellIDs[] = {66, 67, 68, 69}; //IDs of summon elemental spells (fire, earth, water, air)
  1639. int creIDs[] = {114, 113, 115, 112}; //(fire, earth, water, air)
  1640. int * idp = std::find(spellIDs, spellIDs + ARRAY_COUNT(spellIDs), spell->id);
  1641. int arpos = idp - spellIDs;
  1642. if(arpos < ARRAY_COUNT(spellIDs))
  1643. {
  1644. //check if there are summoned elementals of other type
  1645. BOOST_FOREACH ( const CStack * st, stacks)
  1646. {
  1647. if (vstd::contains(st->state, EBattleStackState::SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
  1648. {
  1649. return ESpellCastProblem::ANOTHER_ELEMENTAL_SUMMONED;
  1650. }
  1651. }
  1652. }
  1653. //checking if there exists an appropriate target
  1654. switch(spell->getTargetType())
  1655. {
  1656. case CSpell::CREATURE:
  1657. case CSpell::CREATURE_EXPERT_MASSIVE:
  1658. if(mode == ECastingMode::HERO_CASTING)
  1659. {
  1660. const CGHeroInstance * caster = getHero(player);
  1661. bool targetExists = false;
  1662. BOOST_FOREACH(const CStack * stack, stacks)
  1663. {
  1664. switch (spell->positiveness)
  1665. {
  1666. case CSpell::POSITIVE:
  1667. if(stack->owner == caster->getOwner())
  1668. {
  1669. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1670. {
  1671. targetExists = true;
  1672. break;
  1673. }
  1674. }
  1675. break;
  1676. case CSpell::NEUTRAL:
  1677. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1678. {
  1679. targetExists = true;
  1680. break;
  1681. }
  1682. break;
  1683. case CSpell::NEGATIVE:
  1684. if(stack->owner != caster->getOwner())
  1685. {
  1686. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1687. {
  1688. targetExists = true;
  1689. break;
  1690. }
  1691. }
  1692. break;
  1693. }
  1694. }
  1695. if(!targetExists)
  1696. {
  1697. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1698. }
  1699. }
  1700. break;
  1701. case CSpell::OBSTACLE:
  1702. break;
  1703. }
  1704. return ESpellCastProblem::OK;
  1705. }
  1706. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastThisSpellHere( int player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest ) const
  1707. {
  1708. ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
  1709. if(moreGeneralProblem != ESpellCastProblem::OK)
  1710. return moreGeneralProblem;
  1711. if (mode != ECastingMode::CREATURE_ACTIVE_CASTING && mode != ECastingMode::ENCHANTER_CASTING)
  1712. return battleIsImmune(getHero(player), spell, mode, dest);
  1713. else
  1714. return battleIsImmune(NULL, spell, mode, dest);
  1715. }
  1716. TSpell BattleInfo::getRandomBeneficialSpell(const CStack * subject) const
  1717. {
  1718. std::vector<TSpell> possibleSpells;
  1719. CSpell * spell;
  1720. for (int i = 0; i < GameConstants::SPELLS_QUANTITY; ++i) //should not use future spells added by mods
  1721. {
  1722. spell = VLC->spellh->spells[i];
  1723. if (spell->isPositive()) //only positive
  1724. {
  1725. if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, i) ||
  1726. battleCanCastThisSpellHere(subject->owner, spell, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1727. continue;
  1728. switch (i)
  1729. {
  1730. case Spells::SHIELD:
  1731. case Spells::FIRE_SHIELD: // not if all enemy units are shooters
  1732. {
  1733. bool walkerPresent = false;
  1734. BOOST_FOREACH (CStack * stack, stacks)
  1735. {
  1736. if ((stack->owner != subject->owner) && !stack->shots)
  1737. {
  1738. walkerPresent = true;
  1739. break;
  1740. }
  1741. }
  1742. if (!walkerPresent)
  1743. continue;
  1744. }
  1745. break;
  1746. case Spells::AIR_SHIELD: //only against active shooters
  1747. {
  1748. bool shooterPresent = false;
  1749. BOOST_FOREACH (CStack * stack, stacks)
  1750. {
  1751. if ((stack->owner != subject->owner) && stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots)
  1752. {
  1753. shooterPresent = true;
  1754. break;
  1755. }
  1756. }
  1757. if (!shooterPresent)
  1758. continue;
  1759. break;
  1760. }
  1761. case Spells::ANTI_MAGIC:
  1762. case Spells::MAGIC_MIRROR:
  1763. {
  1764. if (!heroes[whatSide(theOtherPlayer(subject->owner))]) //only if there is enemy hero
  1765. continue;
  1766. }
  1767. break;
  1768. case Spells::CURE: //only damaged units - what about affected by curse?
  1769. {
  1770. if (subject->firstHPleft >= subject->MaxHealth())
  1771. continue;
  1772. }
  1773. break;
  1774. case Spells::BLOODLUST:
  1775. {
  1776. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1777. continue;
  1778. }
  1779. break;
  1780. case Spells::PRECISION:
  1781. {
  1782. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1783. continue;
  1784. }
  1785. break;
  1786. case Spells::SLAYER://only if monsters are present
  1787. {
  1788. bool monsterPresent = false;
  1789. BOOST_FOREACH (CStack * stack, stacks)
  1790. {
  1791. if ((stack->owner != subject->owner) &&
  1792. (stack->hasBonus(Selector::type(Bonus::KING1) || Selector::type(Bonus::KING2) || Selector::type(Bonus::KING3))))
  1793. {
  1794. monsterPresent = true;
  1795. break;
  1796. }
  1797. }
  1798. if (!monsterPresent)
  1799. continue;
  1800. }
  1801. break;
  1802. case Spells::CLONE: //not allowed
  1803. continue;
  1804. break;
  1805. }
  1806. possibleSpells.push_back(i);
  1807. }
  1808. }
  1809. if (possibleSpells.size())
  1810. return possibleSpells[ran() % possibleSpells.size()];
  1811. else
  1812. return -1;
  1813. }
  1814. TSpell BattleInfo::getRandomCastedSpell(const CStack * caster) const
  1815. {
  1816. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1817. if (!bl->size())
  1818. return -1;
  1819. int totalWeight = 0;
  1820. BOOST_FOREACH(Bonus * b, *bl)
  1821. {
  1822. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1823. }
  1824. int randomPos = ran() % totalWeight;
  1825. BOOST_FOREACH(Bonus * b, *bl)
  1826. {
  1827. randomPos -= std::max(b->additionalInfo, 1);
  1828. if(randomPos < 0)
  1829. {
  1830. return b->subtype;
  1831. }
  1832. }
  1833. return -1;
  1834. }
  1835. const CGHeroInstance * BattleInfo::getHero( int player ) const
  1836. {
  1837. assert(sides[0] == player || sides[1] == player);
  1838. if(heroes[0] && heroes[0]->getOwner() == player)
  1839. return heroes[0];
  1840. return heroes[1];
  1841. }
  1842. bool NegateRemover(const Bonus* b)
  1843. {
  1844. return b->source == Bonus::CREATURE_ABILITY;
  1845. }
  1846. bool BattleInfo::battleTestElementalImmunity(const CStack * subject, const CSpell * spell, Bonus::BonusType element, bool damageSpell) const //helper for battleisImmune
  1847. {
  1848. if (!spell->isPositive()) //negative or indifferent
  1849. {
  1850. if ((damageSpell && subject->hasBonusOfType(element, 2)) || subject->hasBonusOfType(element, 1))
  1851. return true;
  1852. }
  1853. else if (spell->isPositive()) //positive
  1854. {
  1855. if (subject->hasBonusOfType(element, 0)) //must be immune to all spells
  1856. return true;
  1857. }
  1858. return false;
  1859. }
  1860. ESpellCastProblem::ESpellCastProblem BattleInfo::battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
  1861. {
  1862. const CStack * subject = getStackT(dest, false);
  1863. if(subject)
  1864. {
  1865. if (spell->isPositive() && subject->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  1866. return ESpellCastProblem::OK;
  1867. switch (spell->id) //TODO: more general logic for new spells?
  1868. {
  1869. case Spells::DESTROY_UNDEAD:
  1870. if (!subject->hasBonusOfType(Bonus::UNDEAD))
  1871. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1872. break;
  1873. case Spells::DEATH_RIPPLE:
  1874. if (subject->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1875. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //don't break here - undeads and war machines are immune, non-living are not
  1876. case Spells::BLESS:
  1877. case Spells::CURSE: //undeads are immune to bless & curse
  1878. if (subject->hasBonusOfType(Bonus::UNDEAD))
  1879. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1880. break;
  1881. case Spells::HASTE:
  1882. case Spells::SLOW:
  1883. case Spells::TELEPORT:
  1884. case Spells::CLONE:
  1885. if (subject->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1886. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //war machines are mmune to some spells than involve movement
  1887. if (spell->id == Spells::CLONE)
  1888. {
  1889. int maxLevel = (std::max(caster->getSpellSchoolLevel(spell), (ui8)1) + 4);
  1890. int creLevel = subject->getCreature()->level;
  1891. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, 1-7 for expert
  1892. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1893. }
  1894. break;
  1895. case Spells::FORGETFULNESS:
  1896. if (!subject->hasBonusOfType(Bonus::SHOOTER))
  1897. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1898. break;
  1899. case Spells::DISPEL_HELPFUL_SPELLS:
  1900. {
  1901. TBonusListPtr spellBon = subject->getSpellBonuses();
  1902. bool hasPositiveSpell = false;
  1903. BOOST_FOREACH(const Bonus * b, *spellBon)
  1904. {
  1905. if(VLC->spellh->spells[b->sid]->isPositive())
  1906. {
  1907. hasPositiveSpell = true;
  1908. break;
  1909. }
  1910. }
  1911. if(!hasPositiveSpell)
  1912. {
  1913. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  1914. }
  1915. }
  1916. break;
  1917. }
  1918. bool damageSpell = (vstd::contains(VLC->spellh->damageSpells, spell->id));
  1919. if (damageSpell && subject->hasBonusOfType(Bonus::DIRECT_DAMAGE_IMMUNITY))
  1920. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1921. if (spell->fire)
  1922. {
  1923. if (battleTestElementalImmunity(subject, spell, Bonus::FIRE_IMMUNITY, damageSpell))
  1924. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1925. }
  1926. if (spell->water)
  1927. {
  1928. if (battleTestElementalImmunity(subject, spell, Bonus::WATER_IMMUNITY, damageSpell))
  1929. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1930. }
  1931. if (spell->earth)
  1932. {
  1933. if (battleTestElementalImmunity(subject, spell, Bonus::EARTH_IMMUNITY, damageSpell))
  1934. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1935. }
  1936. if (spell->air)
  1937. {
  1938. if (battleTestElementalImmunity(subject, spell, Bonus::AIR_IMMUNITY, damageSpell))
  1939. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1940. }
  1941. if (vstd::contains(VLC->spellh->mindSpells, spell->id))
  1942. {
  1943. if (subject->hasBonusOfType(Bonus::MIND_IMMUNITY))
  1944. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1945. }
  1946. if (vstd::contains(VLC->spellh->risingSpells, spell->id))
  1947. {
  1948. if (subject->count >= subject->baseAmount) //TODO: calculate potential hp raised
  1949. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1950. }
  1951. TBonusListPtr immunities = subject->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  1952. if(subject->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  1953. {
  1954. //std::remove_if(immunities->begin(), immunities->end(), NegateRemover);
  1955. immunities->remove_if(NegateRemover);
  1956. }
  1957. if(subject->hasBonusOfType(Bonus::SPELL_IMMUNITY, spell->id) ||
  1958. ( immunities->size() > 0 && immunities->totalValue() >= spell->level && spell->level))
  1959. {
  1960. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1961. }
  1962. }
  1963. else
  1964. {
  1965. if(spell->getTargetType() == CSpell::CREATURE ||
  1966. (spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE && mode == ECastingMode::HERO_CASTING && caster && caster->getSpellSchoolLevel(spell) < 3))
  1967. {
  1968. return ESpellCastProblem::WRONG_SPELL_TARGET;
  1969. }
  1970. }
  1971. return ESpellCastProblem::OK;
  1972. }
  1973. std::vector<ui32> BattleInfo::calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures, int casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const
  1974. {
  1975. std::vector<ui32> ret;
  1976. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  1977. {
  1978. if(battleIsImmune(caster, sp, mode, (*it)->position) != ESpellCastProblem::OK)
  1979. {
  1980. ret.push_back((*it)->ID);
  1981. continue;
  1982. }
  1983. //non-negative spells on friendly stacks should always succeed, unless immune
  1984. if(!sp->isNegative() && (*it)->owner == casterSideOwner)
  1985. continue;
  1986. /*
  1987. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  1988. if((*it)->owner == casterSideOwner)
  1989. bonusHero = caster;
  1990. else
  1991. bonusHero = hero2;*/
  1992. int prob = (*it)->magicResistance(); //probability of resistance in %
  1993. if(prob > 100) prob = 100;
  1994. if(rand()%100 < prob) //immunity from resistance
  1995. ret.push_back((*it)->ID);
  1996. }
  1997. if(sp->id == 60) //hypnotize
  1998. {
  1999. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2000. {
  2001. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2002. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2003. >
  2004. usedSpellPower * 25 + sp->powers[spellLevel]
  2005. )
  2006. {
  2007. ret.push_back((*it)->ID);
  2008. }
  2009. }
  2010. }
  2011. return ret;
  2012. }
  2013. int BattleInfo::getSurrenderingCost(int player) const
  2014. {
  2015. if(!battleCanFlee(player)) //to surrender, conditions of fleeing must be fulfilled
  2016. return -1;
  2017. if(!getHero(theOtherPlayer(player))) //additionally, there must be an enemy hero
  2018. return -2;
  2019. int ret = 0;
  2020. double discount = 0;
  2021. BOOST_FOREACH(const CStack *s, stacks)
  2022. if(s->owner == player && s->base) //we pay for our stack that comes from our army (the last condition eliminates summoned cres and war machines)
  2023. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  2024. if(const CGHeroInstance *h = getHero(player))
  2025. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  2026. ret *= (100.0 - discount) / 100.0;
  2027. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  2028. return ret;
  2029. }
  2030. int BattleInfo::theOtherPlayer(int player) const
  2031. {
  2032. return sides[!whatSide(player)];
  2033. }
  2034. ui8 BattleInfo::whatSide(int player) const
  2035. {
  2036. for(int i = 0; i < ARRAY_COUNT(sides); i++)
  2037. if(sides[i] == player)
  2038. return i;
  2039. tlog1 << "BattleInfo::whatSide: Player " << player << " is not in battle!\n";
  2040. return -1;
  2041. }
  2042. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  2043. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  2044. counterAttacks(1)
  2045. {
  2046. assert(base);
  2047. type = base->type;
  2048. count = baseAmount = base->count;
  2049. setNodeType(STACK_BATTLE);
  2050. }
  2051. CStack::CStack()
  2052. {
  2053. init();
  2054. setNodeType(STACK_BATTLE);
  2055. }
  2056. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  2057. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  2058. {
  2059. type = stack->type;
  2060. count = baseAmount = stack->count;
  2061. setNodeType(STACK_BATTLE);
  2062. }
  2063. void CStack::init()
  2064. {
  2065. base = NULL;
  2066. type = NULL;
  2067. ID = -1;
  2068. count = baseAmount = -1;
  2069. firstHPleft = -1;
  2070. owner = 255;
  2071. slot = 255;
  2072. attackerOwned = false;
  2073. position = BattleHex();
  2074. counterAttacks = -1;
  2075. }
  2076. void CStack::postInit()
  2077. {
  2078. assert(type);
  2079. assert(getParentNodes().size());
  2080. firstHPleft = MaxHealth();
  2081. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  2082. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  2083. casts = valOfBonuses(Bonus::CASTS); //TODO: set them in cr_abils.txt
  2084. state.insert(EBattleStackState::ALIVE); //alive state indication
  2085. }
  2086. ui32 CStack::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  2087. {
  2088. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  2089. return 0;
  2090. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  2091. int percentBonus = 0;
  2092. BOOST_FOREACH(const Bonus *b, getBonusList())
  2093. {
  2094. if(b->type == Bonus::STACKS_SPEED)
  2095. {
  2096. percentBonus += b->additionalInfo;
  2097. }
  2098. }
  2099. speed = ((100 + percentBonus) * speed)/100;
  2100. //bind effect check - doesn't influence stack initiative
  2101. if (useBind && getEffect(72))
  2102. {
  2103. return 0;
  2104. }
  2105. return speed;
  2106. }
  2107. si32 CStack::magicResistance() const
  2108. {
  2109. si32 magicResistance;
  2110. if (base) //TODO: make war machines receive aura of magic resistance
  2111. {
  2112. magicResistance = base->magicResistance();
  2113. int auraBonus = 0;
  2114. BOOST_FOREACH (CStack * stack, base->armyObj->battle->getAdjacentCreatures(this))
  2115. {
  2116. if (stack->owner == owner)
  2117. {
  2118. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  2119. }
  2120. }
  2121. magicResistance += auraBonus;
  2122. vstd::amin (magicResistance, 100);
  2123. }
  2124. else
  2125. magicResistance = type->magicResistance();
  2126. return magicResistance;
  2127. }
  2128. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  2129. {
  2130. BOOST_FOREACH(Bonus *it, getBonusList())
  2131. {
  2132. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  2133. {
  2134. if(!turn || it->turnsRemain > turn)
  2135. return &(*it);
  2136. }
  2137. }
  2138. return NULL;
  2139. }
  2140. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  2141. {
  2142. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  2143. switch(sse.sid)
  2144. {
  2145. case 27: //shield
  2146. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  2147. sf.back().sid = sse.sid;
  2148. break;
  2149. case 28: //air shield
  2150. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  2151. sf.back().sid = sse.sid;
  2152. break;
  2153. case 29: //fire shield
  2154. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  2155. sf.back().sid = sse.sid;
  2156. break;
  2157. case 30: //protection from air
  2158. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  2159. sf.back().sid = sse.sid;
  2160. break;
  2161. case 31: //protection from fire
  2162. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  2163. sf.back().sid = sse.sid;
  2164. break;
  2165. case 32: //protection from water
  2166. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  2167. sf.back().sid = sse.sid;
  2168. break;
  2169. case 33: //protection from earth
  2170. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  2171. sf.back().sid = sse.sid;
  2172. break;
  2173. case 34: //anti-magic
  2174. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, sse.turnsRemain));
  2175. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2176. sf.back().sid = sse.sid;
  2177. break;
  2178. case 36: //magic mirror
  2179. sf.push_back(featureGenerator(Bonus::MAGIC_MIRROR, -1, power, sse.turnsRemain));
  2180. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2181. sf.back().sid = sse.sid;
  2182. case 41: //bless
  2183. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  2184. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2185. sf.back().sid = sse.sid;
  2186. break;
  2187. case 42: //curse
  2188. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  2189. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2190. sf.back().sid = sse.sid;
  2191. break;
  2192. case 43: //bloodlust
  2193. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  2194. sf.back().sid = sse.sid;
  2195. break;
  2196. case 44: //precision
  2197. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  2198. sf.back().sid = sse.sid;
  2199. break;
  2200. case 45: //weakness
  2201. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  2202. sf.back().sid = sse.sid;
  2203. break;
  2204. case 46: //stone skin
  2205. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  2206. sf.back().sid = sse.sid;
  2207. break;
  2208. case 47: //disrupting ray
  2209. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  2210. sf.back().sid = sse.sid;
  2211. sf.back().valType = Bonus::ADDITIVE_VALUE;
  2212. break;
  2213. case 48: //prayer
  2214. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  2215. sf.back().sid = sse.sid;
  2216. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  2217. sf.back().sid = sse.sid;
  2218. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  2219. sf.back().sid = sse.sid;
  2220. break;
  2221. case 49: //mirth
  2222. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  2223. sf.back().sid = sse.sid;
  2224. break;
  2225. case 50: //sorrow
  2226. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  2227. sf.back().sid = sse.sid;
  2228. break;
  2229. case 51: //fortune
  2230. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  2231. sf.back().sid = sse.sid;
  2232. break;
  2233. case 52: //misfortune
  2234. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  2235. sf.back().sid = sse.sid;
  2236. break;
  2237. case 53: //haste
  2238. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  2239. sf.back().sid = sse.sid;
  2240. break;
  2241. case 54: //slow
  2242. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2243. sf.back().sid = sse.sid;
  2244. break;
  2245. case 55: //slayer
  2246. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  2247. sf.back().sid = sse.sid;
  2248. break;
  2249. case 56: //frenzy
  2250. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  2251. sf.back().sid = sse.sid;
  2252. break;
  2253. case 58: //counterstrike
  2254. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  2255. sf.back().sid = sse.sid;
  2256. break;
  2257. case 59: //bersek
  2258. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  2259. sf.back().sid = sse.sid;
  2260. break;
  2261. case 60: //hypnotize
  2262. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  2263. sf.back().sid = sse.sid;
  2264. break;
  2265. case 61: //forgetfulness
  2266. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  2267. sf.back().sid = sse.sid;
  2268. break;
  2269. case 62: //blind
  2270. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, 0, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2271. sf.back().sid = sse.sid;
  2272. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2273. sf.back().sid = sse.sid;
  2274. break;
  2275. case 70: //Stone Gaze
  2276. case 74: //Paralyze
  2277. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, 0, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2278. sf.back().sid = sse.sid;
  2279. break;
  2280. case 71: //Poison
  2281. sf.push_back(featureGeneratorVT(Bonus::POISON, 0, 30, sse.turnsRemain, Bonus::INDEPENDENT_MAX)); //max hp penalty from this source
  2282. sf.back().sid = sse.sid;
  2283. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -10, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2284. sf.back().sid = sse.sid;
  2285. break;
  2286. case 72: //Bind
  2287. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  2288. sf.back().duration = Bonus::PERMANENT;
  2289. sf.back().sid = sse.sid;
  2290. break;
  2291. case 73: //Disease
  2292. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2 , sse.turnsRemain));
  2293. sf.back().sid = sse.sid;
  2294. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2 , sse.turnsRemain));
  2295. sf.back().sid = sse.sid;
  2296. break;
  2297. case 75: //Age
  2298. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -50, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2299. sf.back().sid = sse.sid;
  2300. break;
  2301. case 80: //Acid Breath
  2302. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  2303. sf.back().sid = sse.sid;
  2304. sf.back().duration = Bonus::PERMANENT;
  2305. sf.back().valType = Bonus::ADDITIVE_VALUE;
  2306. break;
  2307. }
  2308. }
  2309. ui8 CStack::howManyEffectsSet(ui16 id) const
  2310. {
  2311. ui8 ret = 0;
  2312. BOOST_FOREACH(const Bonus *it, getBonusList())
  2313. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  2314. {
  2315. ++ret;
  2316. }
  2317. return ret;
  2318. }
  2319. bool CStack::willMove(int turn /*= 0*/) const
  2320. {
  2321. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  2322. && !moved(turn)
  2323. && canMove(turn);
  2324. }
  2325. bool CStack::canMove( int turn /*= 0*/ ) const
  2326. {
  2327. return alive()
  2328. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  2329. }
  2330. bool CStack::moved( int turn /*= 0*/ ) const
  2331. {
  2332. if(!turn)
  2333. return vstd::contains(state, EBattleStackState::MOVED);
  2334. else
  2335. return false;
  2336. }
  2337. bool CStack::doubleWide() const
  2338. {
  2339. return getCreature()->doubleWide;
  2340. }
  2341. BattleHex CStack::occupiedHex() const
  2342. {
  2343. if (doubleWide())
  2344. {
  2345. if (attackerOwned)
  2346. return position - 1;
  2347. else
  2348. return position + 1;
  2349. }
  2350. else
  2351. {
  2352. return BattleHex::INVALID;
  2353. }
  2354. }
  2355. std::vector<BattleHex> CStack::getHexes() const
  2356. {
  2357. std::vector<BattleHex> hexes;
  2358. hexes.push_back(BattleHex(position));
  2359. BattleHex occupied = occupiedHex();
  2360. if(occupied.isValid())
  2361. hexes.push_back(occupied);
  2362. return hexes;
  2363. }
  2364. bool CStack::coversPos(BattleHex pos) const
  2365. {
  2366. return vstd::contains(getHexes(), pos);
  2367. }
  2368. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  2369. {
  2370. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  2371. std::vector<BattleHex> hexes;
  2372. if (doubleWide())
  2373. {
  2374. const int WN = GameConstants::BFIELD_WIDTH;
  2375. if(attackerOwned)
  2376. { //position is equal to front hex
  2377. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  2378. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  2379. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  2380. BattleHex::checkAndPush(hex - 2, hexes);
  2381. BattleHex::checkAndPush(hex + 1, hexes);
  2382. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  2383. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  2384. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  2385. }
  2386. else
  2387. {
  2388. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  2389. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  2390. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  2391. BattleHex::checkAndPush(hex + 2, hexes);
  2392. BattleHex::checkAndPush(hex - 1, hexes);
  2393. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  2394. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  2395. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  2396. }
  2397. return hexes;
  2398. }
  2399. else
  2400. {
  2401. return hex.neighbouringTiles();
  2402. }
  2403. }
  2404. std::vector<si32> CStack::activeSpells() const
  2405. {
  2406. std::vector<si32> ret;
  2407. TBonusListPtr spellEffects = getSpellBonuses();
  2408. BOOST_FOREACH(const Bonus *it, *spellEffects)
  2409. {
  2410. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  2411. ret.push_back(it->sid);
  2412. }
  2413. return ret;
  2414. }
  2415. CStack::~CStack()
  2416. {
  2417. detachFromAll();
  2418. }
  2419. const CGHeroInstance * CStack::getMyHero() const
  2420. {
  2421. if(base)
  2422. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  2423. else //we are attached directly?
  2424. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  2425. if(n->getNodeType() == HERO)
  2426. dynamic_cast<const CGHeroInstance *>(n);
  2427. return NULL;
  2428. }
  2429. std::string CStack::nodeName() const
  2430. {
  2431. std::ostringstream oss;
  2432. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  2433. if(type)
  2434. oss << type->namePl;
  2435. else
  2436. oss << "[UNDEFINED TYPE]";
  2437. oss << " from slot " << (int)slot;
  2438. if(base && base->armyObj)
  2439. oss << " of armyobj=" << base->armyObj->id;
  2440. return oss.str();
  2441. }
  2442. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  2443. {
  2444. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  2445. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  2446. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  2447. {
  2448. bsa.killedAmount = count;
  2449. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  2450. return; // no rebirth I believe
  2451. }
  2452. if( firstHPleft <= damageFirst )
  2453. {
  2454. bsa.killedAmount++;
  2455. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  2456. }
  2457. else
  2458. {
  2459. bsa.newHP = firstHPleft - damageFirst;
  2460. }
  2461. if(count <= bsa.killedAmount) //stack killed
  2462. {
  2463. bsa.newAmount = 0;
  2464. bsa.flags |= BattleStackAttacked::KILLED;
  2465. bsa.killedAmount = count; //we cannot kill more creatures than we have
  2466. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  2467. if (resurrectFactor > 0 && casts) //there must be casts left
  2468. {
  2469. int resurrectedCount = base->count * resurrectFactor / 100;
  2470. if (resurrectedCount)
  2471. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  2472. else //only one unit
  2473. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  2474. if (hasBonusOfType(Bonus::REBIRTH, 1))
  2475. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  2476. if (resurrectedCount)
  2477. {
  2478. bsa.flags |= BattleStackAttacked::REBIRTH;
  2479. bsa.newAmount = resurrectedCount; //risky?
  2480. bsa.newHP = MaxHealth(); //resore full health
  2481. }
  2482. }
  2483. }
  2484. else
  2485. {
  2486. bsa.newAmount = count - bsa.killedAmount;
  2487. }
  2488. }
  2489. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  2490. {
  2491. if (!attackerPos.isValid())
  2492. {
  2493. attackerPos = attacker->position;
  2494. }
  2495. if (!defenderPos.isValid())
  2496. {
  2497. defenderPos = defender->position;
  2498. }
  2499. return
  2500. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  2501. || (attacker->doubleWide() //back <=> front
  2502. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  2503. || (defender->doubleWide() //front <=> back
  2504. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  2505. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  2506. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  2507. }
  2508. bool CStack::ableToRetaliate() const
  2509. {
  2510. return alive()
  2511. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  2512. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  2513. && !hasBonusOfType(Bonus::HYPNOTIZED);
  2514. }
  2515. std::string CStack::getName() const
  2516. {
  2517. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  2518. }
  2519. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  2520. {
  2521. return (alive() || allowDead) && position.isValid();
  2522. }
  2523. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2524. {
  2525. switch(phase)
  2526. {
  2527. case 0: //catapult moves after turrets
  2528. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  2529. case 1: //fastest first, upper slot first
  2530. {
  2531. int as = a->Speed(turn), bs = b->Speed(turn);
  2532. if(as != bs)
  2533. return as > bs;
  2534. else
  2535. return a->slot < b->slot;
  2536. }
  2537. case 2: //fastest last, upper slot first
  2538. //TODO: should be replaced with order of receiving morale!
  2539. case 3: //fastest last, upper slot first
  2540. {
  2541. int as = a->Speed(turn), bs = b->Speed(turn);
  2542. if(as != bs)
  2543. return as < bs;
  2544. else
  2545. return a->slot < b->slot;
  2546. }
  2547. default:
  2548. assert(0);
  2549. return false;
  2550. }
  2551. }
  2552. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2553. {
  2554. phase = Phase;
  2555. turn = Turn;
  2556. }