BattleState.cpp 99 KB

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