BattleState.cpp 86 KB

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