BattleState.cpp 97 KB

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