BattleState.cpp 96 KB

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