BattleState.cpp 97 KB

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