BattleState.cpp 83 KB

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