BattleState.cpp 93 KB

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