BattleState.cpp 98 KB

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