BattleState.cpp 81 KB

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