BattleState.cpp 84 KB

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