BattleState.cpp 78 KB

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