BattleState.cpp 71 KB

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