2
0

BattleState.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332
  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 "VCMI_Lib.h"
  11. #include "CObjectHandler.h"
  12. #include "CHeroHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "CSpellHandler.h"
  15. #include "CTownHandler.h"
  16. #include "NetPacks.h"
  17. /*
  18. * BattleState.h, part of VCMI engine
  19. *
  20. * Authors: listed in file AUTHORS in main folder
  21. *
  22. * License: GNU General Public License v2.0 or later
  23. * Full text of license available in license.txt file, in main folder
  24. *
  25. */
  26. const CStack * BattleInfo::getNextStack() const
  27. {
  28. std::vector<const CStack *> hlp;
  29. getStackQueue(hlp, 1, -1);
  30. if(hlp.size())
  31. return hlp[0];
  32. else
  33. return NULL;
  34. }
  35. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  36. {
  37. const CStack *ret = NULL;
  38. unsigned i, //fastest stack
  39. j; //fastest stack of the other side
  40. for(i = 0; i < st.size(); i++)
  41. if(st[i])
  42. break;
  43. //no stacks left
  44. if(i == st.size())
  45. return NULL;
  46. const CStack *fastest = st[i], *other = NULL;
  47. int bestSpeed = fastest->Speed(turn);
  48. if(fastest->attackerOwned != curside)
  49. {
  50. ret = fastest;
  51. }
  52. else
  53. {
  54. for(j = i + 1; j < st.size(); j++)
  55. {
  56. if(!st[j]) continue;
  57. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  58. break;
  59. }
  60. if(j >= st.size())
  61. {
  62. ret = fastest;
  63. }
  64. else
  65. {
  66. other = st[j];
  67. if(other->Speed(turn) != bestSpeed)
  68. ret = fastest;
  69. else
  70. ret = other;
  71. }
  72. }
  73. assert(ret);
  74. if(ret == fastest)
  75. st[i] = NULL;
  76. else
  77. st[j] = NULL;
  78. curside = ret->attackerOwned;
  79. return ret;
  80. }
  81. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  82. {
  83. for(unsigned int g=0; g<stacks.size(); ++g)
  84. {
  85. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  86. return stacks[g];
  87. }
  88. return NULL;
  89. }
  90. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  91. {
  92. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  93. }
  94. CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive)
  95. {
  96. for(unsigned int g=0; g<stacks.size(); ++g)
  97. {
  98. if(stacks[g]->position == tileID
  99. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  100. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  101. {
  102. if(!onlyAlive || stacks[g]->alive())
  103. {
  104. return stacks[g];
  105. }
  106. }
  107. }
  108. return NULL;
  109. }
  110. const CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive) const
  111. {
  112. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  113. }
  114. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<THex> & occupyable, bool flying, const CStack * stackToOmmit) const
  115. {
  116. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  117. //removing accessibility for side columns of hexes
  118. for(int v = 0; v < BFIELD_SIZE; ++v)
  119. {
  120. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  121. accessibility[v] = false;
  122. }
  123. for(unsigned int g=0; g<stacks.size(); ++g)
  124. {
  125. 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)
  126. continue;
  127. accessibility[stacks[g]->position] = false;
  128. if(stacks[g]->doubleWide()) //if it's a double hex creature
  129. {
  130. if(stacks[g]->attackerOwned)
  131. accessibility[stacks[g]->position-1] = false;
  132. else
  133. accessibility[stacks[g]->position+1] = false;
  134. }
  135. }
  136. //obstacles
  137. for(unsigned int b=0; b<obstacles.size(); ++b)
  138. {
  139. std::vector<THex> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  140. for(unsigned int c=0; c<blocked.size(); ++c)
  141. {
  142. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  143. accessibility[blocked[c]] = false;
  144. }
  145. }
  146. //walls
  147. if(siege > 0)
  148. {
  149. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  150. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  151. {
  152. accessibility[permanentlyLocked[b]] = false;
  153. }
  154. static const std::pair<int, THex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  155. {std::make_pair(2, THex(182)), std::make_pair(3, THex(130)),
  156. std::make_pair(4, THex(62)), std::make_pair(5, THex(29))};
  157. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  158. {
  159. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  160. {
  161. accessibility[lockedIfNotDestroyed[b].second] = false;
  162. }
  163. }
  164. //gate
  165. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  166. {
  167. accessibility[95] = accessibility[96] = false; //block gate's hexes
  168. }
  169. }
  170. //occupyability
  171. if(addOccupiable && twoHex)
  172. {
  173. std::set<THex> rem; //tiles to unlock
  174. for(int h=0; h<BFIELD_HEIGHT; ++h)
  175. {
  176. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  177. {
  178. THex hex(w, h);
  179. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  180. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  181. )
  182. rem.insert(hex);
  183. }
  184. }
  185. occupyable = rem;
  186. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  187. {
  188. accessibility[*it] = true;
  189. }*/
  190. }
  191. }
  192. bool BattleInfo::isAccessible(THex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  193. {
  194. if(flying && !lastPos)
  195. return true;
  196. if(twoHex)
  197. {
  198. //if given hex is accessible and appropriate adjacent one is free too
  199. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  200. }
  201. else
  202. {
  203. return accessibility[hex];
  204. }
  205. }
  206. 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
  207. {
  208. //inits
  209. for(int b=0; b<BFIELD_SIZE; ++b)
  210. predecessor[b] = -1;
  211. for(int g=0; g<BFIELD_SIZE; ++g)
  212. dists[g] = 100000000;
  213. std::queue< std::pair<THex, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  214. hexq.push(std::make_pair(start, true));
  215. dists[hexq.front().first] = 0;
  216. int curNext = -1; //for bfs loop only (helper var)
  217. while(!hexq.empty()) //bfs loop
  218. {
  219. std::pair<THex, bool> curHex = hexq.front();
  220. std::vector<THex> neighbours = curHex.first.neighbouringTiles();
  221. hexq.pop();
  222. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  223. {
  224. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  225. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  226. if( dists[curHex.first]+1 >= dists[curNext] )
  227. continue;
  228. if(accessible && curHex.second)
  229. {
  230. hexq.push(std::make_pair(curNext, true));
  231. dists[curNext] = dists[curHex.first] + 1;
  232. }
  233. else if(fillPredecessors && !(accessible && !curHex.second))
  234. {
  235. hexq.push(std::make_pair(curNext, false));
  236. dists[curNext] = dists[curHex.first] + 1;
  237. }
  238. predecessor[curNext] = curHex.first;
  239. }
  240. }
  241. };
  242. std::vector<THex> BattleInfo::getAccessibility( const CStack * stack, bool addOccupiable, std::vector<THex> * attackable ) const
  243. {
  244. std::vector<THex> ret;
  245. bool ac[BFIELD_SIZE];
  246. if(stack->position < 0) //turrets
  247. return std::vector<THex>();
  248. std::set<THex> occupyable;
  249. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, addOccupiable, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  250. THex pr[BFIELD_SIZE];
  251. int dist[BFIELD_SIZE];
  252. makeBFS(stack->position, ac, pr, dist, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), false);
  253. if(stack->doubleWide())
  254. {
  255. if(!addOccupiable)
  256. {
  257. std::vector<THex> rem;
  258. for(int b=0; b<BFIELD_SIZE; ++b)
  259. {
  260. //don't take into account most left and most right columns of hexes
  261. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  262. continue;
  263. if( ac[b] && !(stack->attackerOwned ? ac[b-1] : ac[b+1]) )
  264. {
  265. rem.push_back(b);
  266. }
  267. }
  268. for(unsigned int g=0; g<rem.size(); ++g)
  269. {
  270. ac[rem[g]] = false;
  271. }
  272. //removing accessibility for side hexes
  273. for(int v=0; v<BFIELD_SIZE; ++v)
  274. if(stack->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  275. ac[v] = false;
  276. }
  277. }
  278. for (int i=0; i < BFIELD_SIZE ; ++i)
  279. {
  280. bool rangeFits = tacticDistance
  281. ? isInTacticRange(i)
  282. : dist[i] <= stack->Speed();
  283. if( ( !addOccupiable && rangeFits && ac[i] )
  284. || ( addOccupiable && rangeFits && isAccessible(i, ac, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), true) )//we can reach it
  285. || (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
  286. )
  287. {
  288. ret.push_back(i);
  289. }
  290. }
  291. if(attackable)
  292. {
  293. struct HLP
  294. {
  295. static bool meleeAttackable(THex hex, const std::vector<THex> & baseRng)
  296. {
  297. BOOST_FOREACH(THex h, baseRng)
  298. {
  299. if(THex::mutualPosition(h, hex) > 0)
  300. return true;
  301. }
  302. return false;
  303. }
  304. };
  305. BOOST_FOREACH(const CStack * otherSt, stacks)
  306. {
  307. if(otherSt->owner == stack->owner)
  308. continue;
  309. std::vector<THex> occupiedBySecond;
  310. occupiedBySecond.push_back(otherSt->position);
  311. if(otherSt->doubleWide())
  312. occupiedBySecond.push_back(otherSt->occupiedHex());
  313. if(battleCanShoot(stack, otherSt->position))
  314. {
  315. attackable->insert(attackable->end(), occupiedBySecond.begin(), occupiedBySecond.end());
  316. continue;
  317. }
  318. BOOST_FOREACH(THex he, occupiedBySecond)
  319. {
  320. if(HLP::meleeAttackable(he, ret))
  321. attackable->push_back(he);
  322. }
  323. }
  324. }
  325. return ret;
  326. }
  327. bool BattleInfo::isStackBlocked(const CStack * stack) const
  328. {
  329. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  330. return false;
  331. for(unsigned int i=0; i<stacks.size();i++)
  332. {
  333. if( !stacks[i]->alive()
  334. || stacks[i]->owner==stack->owner
  335. )
  336. continue; //we omit dead and allied stacks
  337. if(stacks[i]->doubleWide())
  338. {
  339. if( THex::mutualPosition(stacks[i]->position, stack->position) >= 0
  340. || THex::mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), stack->position) >= 0)
  341. return true;
  342. }
  343. else
  344. {
  345. if( THex::mutualPosition(stacks[i]->position, stack->position) >= 0 )
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. std::pair< std::vector<THex>, int > BattleInfo::getPath(THex start, THex dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  352. {
  353. THex predecessor[BFIELD_SIZE]; //for getting the Path
  354. int dist[BFIELD_SIZE]; //calculated distances
  355. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  356. if(predecessor[dest] == -1) //cannot reach destination
  357. {
  358. return std::make_pair(std::vector<THex>(), 0);
  359. }
  360. //making the Path
  361. std::vector<THex> path;
  362. THex curElem = dest;
  363. while(curElem != start)
  364. {
  365. path.push_back(curElem);
  366. curElem = predecessor[curElem];
  367. }
  368. return std::make_pair(path, dist[dest]);
  369. }
  370. TDmgRange BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount, TQuantity defenderCount, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool ballistaDoubleDmg ) const
  371. {
  372. float additiveBonus=1.0f, multBonus=1.0f,
  373. minDmg = attacker->getMinDamage() * attackerCount,
  374. maxDmg = attacker->getMaxDamage() * attackerCount;
  375. if(attacker->getCreature()->idNumber == 149) //arrow turret
  376. {
  377. switch(attacker->position)
  378. {
  379. case -2: //keep
  380. minDmg = 15;
  381. maxDmg = 15;
  382. break;
  383. case -3: case -4: //turrets
  384. minDmg = 7.5f;
  385. maxDmg = 7.5f;
  386. break;
  387. }
  388. }
  389. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  390. { //minDmg and maxDmg are multiplied by hero attack + 1
  391. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  392. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  393. }
  394. int attackDefenceDifference = 0;
  395. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  396. {
  397. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  398. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  399. }
  400. else
  401. {
  402. attackDefenceDifference = attacker->Attack();
  403. }
  404. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  405. {
  406. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  407. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  408. }
  409. else
  410. {
  411. attackDefenceDifference -= defender->Defense();
  412. }
  413. //calculating total attack/defense skills modifier
  414. if(shooting) //precision handling (etc.)
  415. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  416. else //bloodlust handling (etc.)
  417. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  418. if(attacker->getEffect(55)) //slayer handling
  419. {
  420. std::vector<int> affectedIds;
  421. int spLevel = attacker->getEffect(55)->val;
  422. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  423. {
  424. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->bonuses)
  425. {
  426. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  427. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  428. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  429. {
  430. affectedIds.push_back(g);
  431. break;
  432. }
  433. }
  434. }
  435. for(unsigned int g=0; g<affectedIds.size(); ++g)
  436. {
  437. if(defender->getCreature()->idNumber == affectedIds[g])
  438. {
  439. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  440. break;
  441. }
  442. }
  443. }
  444. //bonus from attack/defense skills
  445. if(attackDefenceDifference < 0) //decreasing dmg
  446. {
  447. float dec = 0.025f * (-attackDefenceDifference);
  448. if(dec > 0.7f)
  449. {
  450. multBonus *= 0.3f; //1.0 - 0.7
  451. }
  452. else
  453. {
  454. multBonus *= 1.0f - dec;
  455. }
  456. }
  457. else //increasing dmg
  458. {
  459. float inc = 0.05f * attackDefenceDifference;
  460. if(inc > 4.0f)
  461. {
  462. additiveBonus += 4.0f;
  463. }
  464. else
  465. {
  466. additiveBonus += inc;
  467. }
  468. }
  469. //applying jousting bonus
  470. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  471. additiveBonus += charge * 0.05f;
  472. //handling secondary abilities and artifacts giving premies to them
  473. if(attackerHero)
  474. {
  475. if(shooting)
  476. {
  477. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARCHERY) / 100.0f;
  478. }
  479. else
  480. {
  481. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::OFFENCE) / 100.0f;
  482. }
  483. }
  484. if(defendingHero)
  485. {
  486. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARMORER))) / 100.0f;
  487. }
  488. //handling hate effect
  489. if( attacker->hasBonusOfType(Bonus::HATE, defender->getCreature()->idNumber) )
  490. additiveBonus += 0.5f;
  491. //luck bonus
  492. if (lucky)
  493. {
  494. additiveBonus += 1.0f;
  495. }
  496. //ballista double dmg
  497. if(ballistaDoubleDmg)
  498. {
  499. additiveBonus += 1.0f;
  500. }
  501. //handling spell effects
  502. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  503. {
  504. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  505. }
  506. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  507. {
  508. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  509. }
  510. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  511. {
  512. multBonus *= 0.8f * float(VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val]); //the second factor is 1 or 0
  513. }
  514. class HLP
  515. {
  516. public:
  517. static bool hasAdvancedAirShield(const CStack * stack)
  518. {
  519. BOOST_FOREACH(const Bonus *it, stack->bonuses)
  520. {
  521. if (it->source == Bonus::SPELL_EFFECT && it->sid == 28 && it->val >= 2)
  522. {
  523. return true;
  524. }
  525. }
  526. return false;
  527. }
  528. };
  529. //wall / distance penalty + advanced air shield
  530. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  531. hasDistancePenalty(attacker, defender->position) || hasWallPenalty(attacker, defender->position) ||
  532. HLP::hasAdvancedAirShield(defender) )
  533. )
  534. {
  535. multBonus *= 0.5;
  536. }
  537. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  538. {
  539. multBonus *= 0.5;
  540. }
  541. minDmg *= additiveBonus * multBonus;
  542. maxDmg *= additiveBonus * multBonus;
  543. TDmgRange returnedVal;
  544. if(attacker->getEffect(42)) //curse handling (rest)
  545. {
  546. minDmg -= VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val];
  547. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  548. }
  549. else if(attacker->getEffect(41)) //bless handling
  550. {
  551. maxDmg += VLC->spellh->spells[41]->powers[attacker->getEffect(41)->val];
  552. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  553. }
  554. else
  555. {
  556. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  557. }
  558. //damage cannot be less than 1
  559. amax(returnedVal.first, 1);
  560. amax(returnedVal.second, 1);
  561. return returnedVal;
  562. }
  563. TDmgRange BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool ballistaDoubleDmg) const
  564. {
  565. return calculateDmgRange(attacker, defender, attacker->count, defender->count, attackerHero, defendingHero, shooting, charge, lucky, ballistaDoubleDmg);
  566. }
  567. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool ballistaDoubleDmg )
  568. {
  569. TDmgRange range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky, ballistaDoubleDmg);
  570. if(range.first != range.second)
  571. {
  572. int valuesToAverage[10];
  573. int howManyToAv = std::min<ui32>(10, attacker->count);
  574. for (int g=0; g<howManyToAv; ++g)
  575. {
  576. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  577. }
  578. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  579. }
  580. else
  581. return range.first;
  582. }
  583. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  584. {
  585. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  586. {
  587. const CStack * const st = stacks[i];
  588. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  589. amax(killed, 0);
  590. if(killed)
  591. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  592. }
  593. }
  594. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, THex destinationTile )
  595. {
  596. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  597. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  598. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  599. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  600. {
  601. for(int it=0; it<stacks.size(); ++it)
  602. {
  603. if((s->id == 24 && !stacks[it]->getCreature()->isUndead()) //death ripple
  604. || (s->id == 25 && stacks[it]->getCreature()->isUndead()) //destroy undead
  605. || (s->id == 26) //Armageddon
  606. )
  607. {
  608. if(stacks[it]->alive())
  609. attackedCres.insert(stacks[it]);
  610. }
  611. }
  612. }
  613. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  614. {
  615. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  616. {
  617. CStack * st = getStackT(*it, onlyAlive);
  618. if(st)
  619. attackedCres.insert(st);
  620. }
  621. }
  622. else if(s->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  623. {
  624. if(skillLevel < 3) /*not expert */
  625. {
  626. CStack * st = getStackT(destinationTile, onlyAlive);
  627. if(st)
  628. attackedCres.insert(st);
  629. }
  630. else
  631. {
  632. for(int it=0; it<stacks.size(); ++it)
  633. {
  634. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  635. if((s->positiveness >= 0 && stacks[it]->owner == attackerOwner)
  636. ||(s->positiveness <= 0 && stacks[it]->owner != attackerOwner )
  637. )
  638. {
  639. if(!onlyAlive || stacks[it]->alive())
  640. attackedCres.insert(stacks[it]);
  641. }
  642. }
  643. } //if(caster->getSpellSchoolLevel(s) < 3)
  644. }
  645. else if(s->getTargetType() == CSpell::CREATURE)
  646. {
  647. CStack * st = getStackT(destinationTile, onlyAlive);
  648. if(st)
  649. attackedCres.insert(st);
  650. }
  651. else //custom range from attackedHexes
  652. {
  653. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  654. {
  655. CStack * st = getStackT(*it, onlyAlive);
  656. if(st)
  657. attackedCres.insert(st);
  658. }
  659. }
  660. return attackedCres;
  661. }
  662. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  663. {
  664. if(!caster) //TODO: something better
  665. return std::max(5, usedSpellPower);
  666. switch(spell->id)
  667. {
  668. case 56: //frenzy
  669. return 1;
  670. default: //other spells
  671. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  672. }
  673. }
  674. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, THex position) const
  675. {
  676. int owner = attackerOwned ? sides[0] : sides[1];
  677. assert(owner >= PLAYER_LIMIT || base.armyObj && base.armyObj->tempOwner == owner);
  678. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  679. ret->position = position;
  680. return ret;
  681. }
  682. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, int stackID, bool attackerOwned, int slot, THex position) const
  683. {
  684. int owner = attackerOwned ? sides[0] : sides[1];
  685. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  686. ret->position = position;
  687. return ret;
  688. }
  689. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  690. {
  691. ui32 ret = caster->getSpellCost(sp);
  692. //checking for friendly stacks reducing cost of the spell and
  693. //enemy stacks increasing it
  694. si32 manaReduction = 0;
  695. si32 manaIncrease = 0;
  696. for(int g=0; g<stacks.size(); ++g)
  697. {
  698. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  699. {
  700. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  701. }
  702. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  703. {
  704. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  705. }
  706. }
  707. return ret + manaReduction + manaIncrease;
  708. }
  709. int BattleInfo::hexToWallPart(THex hex) const
  710. {
  711. if(siege == 0) //there is no battle!
  712. return -1;
  713. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  714. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  715. 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)};
  716. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  717. {
  718. if(attackable[g].first == hex)
  719. return attackable[g].second;
  720. }
  721. return -1; //not found!
  722. }
  723. int BattleInfo::lineToWallHex( int line ) const
  724. {
  725. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  726. return lineToHex[line];
  727. }
  728. std::pair<const CStack *, THex> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  729. {
  730. bool ac[BFIELD_SIZE];
  731. std::set<THex> occupyable;
  732. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest);
  733. THex predecessor[BFIELD_SIZE];
  734. int dist[BFIELD_SIZE];
  735. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  736. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  737. for(int g=0; g<BFIELD_SIZE; ++g)
  738. {
  739. const CStack * atG = getStackT(g);
  740. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  741. continue;
  742. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  743. {
  744. if(predecessor[g] == -1) //TODO: is it really the best solution?
  745. continue;
  746. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  747. }
  748. }
  749. if(stackPairs.size() > 0)
  750. {
  751. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  752. minimalPairs.push_back(stackPairs[0]);
  753. for(int b=1; b<stackPairs.size(); ++b)
  754. {
  755. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  756. {
  757. minimalPairs.clear();
  758. minimalPairs.push_back(stackPairs[b]);
  759. }
  760. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  761. {
  762. minimalPairs.push_back(stackPairs[b]);
  763. }
  764. }
  765. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  766. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  767. }
  768. return std::make_pair<const CStack * , THex>(NULL, THex::INVALID);
  769. }
  770. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  771. {
  772. ui32 ret = baseDamage;
  773. //applying sorcery secondary skill
  774. if(caster)
  775. {
  776. ret *= (100.f + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0f;
  777. ret *= (100.f + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0f;
  778. if(sp->air)
  779. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  780. else if(sp->fire) //only one type of bonus for Magic Arrow
  781. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  782. else if(sp->water)
  783. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  784. else if(sp->earth)
  785. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  786. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  787. ret *= (100.f + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0f;
  788. }
  789. return ret;
  790. }
  791. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  792. {
  793. ui32 ret = 0; //value to return
  794. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  795. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  796. //FIXME: what point of dmgMultipliers map? all damage multipliers are already present in CSpell::power
  797. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50)(77, 10);
  798. //check if spell really does damage - if not, return 0
  799. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  800. return 0;
  801. ret = usedSpellPower * dmgMultipliers[sp->id];
  802. ret += sp->powers[spellSchoolLevel];
  803. //affected creature-specific part
  804. if(affectedCreature)
  805. {
  806. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  807. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  808. {
  809. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  810. ret /= 100;
  811. }
  812. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  813. {
  814. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  815. ret /= 100;
  816. }
  817. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  818. {
  819. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  820. ret /= 100;
  821. }
  822. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  823. {
  824. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  825. ret /= 100;
  826. }
  827. //general spell dmg reduction
  828. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  829. {
  830. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  831. ret /= 100;
  832. }
  833. //dmg increasing
  834. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  835. {
  836. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  837. ret /= 100;
  838. }
  839. }
  840. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  841. return ret;
  842. }
  843. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  844. {
  845. int powerPerLevel;
  846. bool resurrect;
  847. switch(spell->id)
  848. {
  849. case 37: //cure
  850. {
  851. powerPerLevel = 5;
  852. resurrect = false;
  853. break;
  854. }
  855. case 38: //resurrection
  856. case 39: //animate dead
  857. {
  858. powerPerLevel = 50;
  859. resurrect = true;
  860. break;
  861. }
  862. }
  863. int healedHealth = caster->getPrimSkillLevel(2) * powerPerLevel + spell->powers[caster->getSpellSchoolLevel(spell)];
  864. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  865. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  866. }
  867. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  868. {
  869. //we'll split creatures with remaining movement to 4 parts
  870. 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
  871. int toMove = 0; //how many stacks still has move
  872. const CStack *active = getStack(activeStack);
  873. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  874. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  875. {
  876. out.push_back(active);
  877. if(out.size() == howMany)
  878. return;
  879. }
  880. for(unsigned int i=0; i<stacks.size(); ++i)
  881. {
  882. const CStack * const s = stacks[i];
  883. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  884. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  885. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  886. {
  887. continue;
  888. }
  889. int p = -1; //in which phase this tack will move?
  890. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  891. {
  892. if(vstd::contains(s->state, HAD_MORALE))
  893. p = 2;
  894. else
  895. p = 3;
  896. }
  897. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  898. {
  899. p = 0;
  900. }
  901. else
  902. {
  903. p = 1;
  904. }
  905. phase[p].push_back(s);
  906. toMove++;
  907. }
  908. for(int i = 0; i < 4; i++)
  909. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  910. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  911. out.push_back(phase[0][i]);
  912. if(out.size() == howMany)
  913. return;
  914. if(lastMoved == -1)
  915. {
  916. if(active)
  917. {
  918. if(out.size() && out.front() == active)
  919. lastMoved = active->attackerOwned;
  920. else
  921. lastMoved = active->attackerOwned;
  922. }
  923. else
  924. {
  925. lastMoved = 0;
  926. }
  927. }
  928. int pi = 1;
  929. while(out.size() < howMany)
  930. {
  931. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  932. if(!hlp)
  933. {
  934. pi++;
  935. if(pi > 3)
  936. {
  937. //if(turn != 2)
  938. getStackQueue(out, howMany, turn + 1, lastMoved);
  939. return;
  940. }
  941. }
  942. else
  943. {
  944. out.push_back(hlp);
  945. }
  946. }
  947. }
  948. si8 BattleInfo::hasDistancePenalty( const CStack * stack, THex destHex ) const
  949. {
  950. struct HLP
  951. {
  952. static bool lowerAnalyze(const CStack * stack, THex hex)
  953. {
  954. int distance = THex::getDistance(hex, stack->position);
  955. //I hope it's approximately correct
  956. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  957. }
  958. };
  959. const CStack * dstStack = getStackT(destHex, false);
  960. if (dstStack->doubleWide())
  961. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  962. else
  963. return HLP::lowerAnalyze(stack, destHex);
  964. }
  965. si8 BattleInfo::sameSideOfWall(int pos1, int pos2) const
  966. {
  967. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  968. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  969. bool stackLeft = pos1 < wallInStackLine;
  970. bool destLeft = pos2 < wallInDestLine;
  971. return stackLeft != destLeft;
  972. }
  973. si8 BattleInfo::hasWallPenalty( const CStack* stack, THex destHex ) const
  974. {
  975. if (siege == 0)
  976. {
  977. return false;
  978. }
  979. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  980. {
  981. return false;
  982. }
  983. return !sameSideOfWall(stack->position, destHex);
  984. }
  985. si8 BattleInfo::canTeleportTo(const CStack * stack, THex destHex, int telportLevel) const
  986. {
  987. bool ac[BFIELD_SIZE];
  988. std::set<THex> occupyable;
  989. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, false, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  990. if (siege && telportLevel < 2) //check for wall
  991. {
  992. return ac[destHex] && sameSideOfWall(stack->position, destHex);
  993. }
  994. else
  995. {
  996. return ac[destHex];
  997. }
  998. }
  999. bool BattleInfo::battleCanShoot(const CStack * stack, THex dest) const
  1000. {
  1001. const CStack *dst = getStackT(dest);
  1002. if(!stack || !dst) return false;
  1003. const CGHeroInstance * stackHero = battleGetOwner(stack);
  1004. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  1005. return false;
  1006. if(stack->getCreature()->idNumber == 145 && dst) //catapult cannot attack creatures
  1007. return false;
  1008. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  1009. && stack->owner != dst->owner
  1010. && dst->alive()
  1011. && (!isStackBlocked(stack) || NBonus::hasOfType(stackHero, Bonus::FREE_SHOOTING))
  1012. && stack->shots
  1013. )
  1014. return true;
  1015. return false;
  1016. }
  1017. bool BattleInfo::battleCanFlee(int player) const
  1018. {
  1019. if (player == sides[0])
  1020. {
  1021. if (!heroes[0])
  1022. return false;//current player have no hero
  1023. }
  1024. else
  1025. {
  1026. if (!heroes[1])
  1027. return false;
  1028. }
  1029. if( ( heroes[0] && heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  1030. || ( heroes[1] && heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  1031. return false;
  1032. if (player == sides[1] && siege //defender in siege
  1033. && !(town->subID == 6 && vstd::contains(town->builtBuildings, 17)))//without escape tunnel
  1034. return false;
  1035. return true;
  1036. }
  1037. const CStack * BattleInfo::battleGetStack(THex pos, bool onlyAlive)
  1038. {
  1039. for(unsigned int g=0; g<stacks.size(); ++g)
  1040. {
  1041. if((stacks[g]->position == pos
  1042. || (stacks[g]->doubleWide()
  1043. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  1044. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  1045. ))
  1046. && (!onlyAlive || stacks[g]->alive())
  1047. )
  1048. return stacks[g];
  1049. }
  1050. return NULL;
  1051. }
  1052. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  1053. {
  1054. return heroes[!stack->attackerOwned];
  1055. }
  1056. si8 BattleInfo::battleMinSpellLevel() const
  1057. {
  1058. si8 levelLimit = 0;
  1059. if(const CGHeroInstance *h1 = heroes[0])
  1060. {
  1061. amax(levelLimit, h1->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1062. }
  1063. if(const CGHeroInstance *h2 = heroes[1])
  1064. {
  1065. amax(levelLimit, h2->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1066. }
  1067. return levelLimit;
  1068. }
  1069. void BattleInfo::localInit()
  1070. {
  1071. belligerents[0]->battle = belligerents[1]->battle = this;
  1072. BOOST_FOREACH(CArmedInstance *b, belligerents)
  1073. b->attachTo(this);
  1074. BOOST_FOREACH(CStack *s, stacks)
  1075. {
  1076. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  1077. {
  1078. s->attachTo(const_cast<CStackInstance*>(s->base));
  1079. }
  1080. else //attach directly to obj to which stack belongs and creature type
  1081. {
  1082. CArmedInstance *army = belligerents[!s->attackerOwned];
  1083. s->attachTo(army);
  1084. assert(s->type);
  1085. s->attachTo(const_cast<CCreature*>(s->type));
  1086. }
  1087. s->postInit();
  1088. }
  1089. }
  1090. namespace CGH
  1091. {
  1092. using namespace std;
  1093. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1094. {
  1095. for(int j=0; j<7; ++j)
  1096. {
  1097. std::vector<int> pom;
  1098. for(int g=0; g<j+1; ++g)
  1099. {
  1100. int hlp; input>>hlp;
  1101. pom.push_back(hlp);
  1102. }
  1103. dest.push_back(pom);
  1104. }
  1105. }
  1106. }
  1107. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1108. {
  1109. CMP_stack cmpst;
  1110. BattleInfo *curB = new BattleInfo;
  1111. curB->sides[0] = armies[0]->tempOwner;
  1112. curB->sides[1] = armies[1]->tempOwner;
  1113. if(curB->sides[1] == 254)
  1114. curB->sides[1] = 255;
  1115. std::vector<CStack*> & stacks = (curB->stacks);
  1116. curB->tile = tile;
  1117. curB->battlefieldType = terType;
  1118. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1119. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1120. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1121. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1122. curB->round = -2;
  1123. curB->activeStack = -1;
  1124. if(town)
  1125. {
  1126. curB->town = town;
  1127. curB->siege = town->fortLevel();
  1128. }
  1129. else
  1130. {
  1131. curB->town = NULL;
  1132. curB->siege = 0;
  1133. }
  1134. //reading battleStartpos
  1135. std::ifstream positions;
  1136. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1137. if(!positions.is_open())
  1138. {
  1139. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1140. }
  1141. std::string dump;
  1142. positions>>dump; positions>>dump;
  1143. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1144. CGH::readItTo(positions, attackerLoose);
  1145. positions>>dump;
  1146. CGH::readItTo(positions, defenderLoose);
  1147. positions>>dump;
  1148. positions>>dump;
  1149. CGH::readItTo(positions, attackerTight);
  1150. positions>>dump;
  1151. CGH::readItTo(positions, defenderTight);
  1152. positions>>dump;
  1153. positions>>dump;
  1154. CGH::readItTo(positions, attackerCreBank);
  1155. positions>>dump;
  1156. CGH::readItTo(positions, defenderCreBank);
  1157. positions.close();
  1158. //battleStartpos read
  1159. int k = 0; //stack serial
  1160. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1161. {
  1162. int pos;
  1163. if(creatureBank)
  1164. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1165. else if(armies[0]->formation)
  1166. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1167. else
  1168. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1169. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), true, i->first, pos);
  1170. stacks.push_back(stack);
  1171. }
  1172. k = 0;
  1173. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1174. {
  1175. int pos;
  1176. if(creatureBank)
  1177. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1178. else if(armies[1]->formation)
  1179. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1180. else
  1181. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1182. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), false, i->first, pos);
  1183. stacks.push_back(stack);
  1184. }
  1185. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1186. {
  1187. //we should do that for creature bank too
  1188. if(stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1189. {
  1190. stacks[g]->position += THex::RIGHT;
  1191. }
  1192. else if(stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1193. {
  1194. stacks[g]->position += THex::LEFT;
  1195. }
  1196. }
  1197. //adding war machines
  1198. if(heroes[0])
  1199. {
  1200. if(heroes[0]->getArt(13)) //ballista
  1201. {
  1202. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), true, 255, 52);
  1203. stacks.push_back(stack);
  1204. }
  1205. if(heroes[0]->getArt(14)) //ammo cart
  1206. {
  1207. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), true, 255, 18);
  1208. stacks.push_back(stack);
  1209. }
  1210. if(heroes[0]->getArt(15)) //first aid tent
  1211. {
  1212. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), true, 255, 154);
  1213. stacks.push_back(stack);
  1214. }
  1215. }
  1216. if(heroes[1])
  1217. {
  1218. //defending hero shouldn't receive ballista (bug #551)
  1219. if(heroes[1]->getArt(13) && !town) //ballista
  1220. {
  1221. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), false, 255, 66);
  1222. stacks.push_back(stack);
  1223. }
  1224. if(heroes[1]->getArt(14)) //ammo cart
  1225. {
  1226. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), false, 255, 32);
  1227. stacks.push_back(stack);
  1228. }
  1229. if(heroes[1]->getArt(15)) //first aid tent
  1230. {
  1231. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), false, 255, 168);
  1232. stacks.push_back(stack);
  1233. }
  1234. }
  1235. if(town && heroes[0] && town->hasFort()) //catapult
  1236. {
  1237. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), stacks.size(), true, 255, 120);
  1238. stacks.push_back(stack);
  1239. }
  1240. //war machines added
  1241. switch(curB->siege) //adding towers
  1242. {
  1243. case 3: //castle
  1244. {//lower tower / upper tower
  1245. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -4);
  1246. stacks.push_back(stack);
  1247. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -3);
  1248. stacks.push_back(stack);
  1249. }
  1250. case 2: //citadel
  1251. {//main tower
  1252. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -2);
  1253. stacks.push_back(stack);
  1254. }
  1255. }
  1256. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1257. //seting up siege
  1258. if(town && town->hasFort())
  1259. {
  1260. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1261. {
  1262. curB->si.wallState[b] = 1;
  1263. }
  1264. }
  1265. //randomize obstacles
  1266. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1267. {
  1268. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1269. std::vector<int> possibleObstacles;
  1270. for(int i=0; i<BFIELD_SIZE; ++i)
  1271. {
  1272. if(i%17 < 4 || i%17 > 12)
  1273. {
  1274. obAv[i] = false;
  1275. }
  1276. else
  1277. {
  1278. obAv[i] = true;
  1279. }
  1280. }
  1281. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1282. {
  1283. 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
  1284. {
  1285. possibleObstacles.push_back(g->first);
  1286. }
  1287. }
  1288. srand(time(NULL));
  1289. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1290. {
  1291. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1292. while(toBlock>0)
  1293. {
  1294. CObstacleInstance coi;
  1295. coi.uniqueID = curB->obstacles.size();
  1296. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1297. coi.pos = rand()%BFIELD_SIZE;
  1298. std::vector<THex> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1299. bool badObstacle = false;
  1300. for(int b=0; b<block.size(); ++b)
  1301. {
  1302. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1303. {
  1304. badObstacle = true;
  1305. break;
  1306. }
  1307. }
  1308. if(badObstacle) continue;
  1309. //obstacle can be placed
  1310. curB->obstacles.push_back(coi);
  1311. for(int b=0; b<block.size(); ++b)
  1312. {
  1313. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1314. obAv[block[b]] = false;
  1315. }
  1316. toBlock -= block.size();
  1317. }
  1318. }
  1319. }
  1320. //spell level limiting bonus
  1321. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  1322. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  1323. //giving terrain overalay premies
  1324. int bonusSubtype = -1;
  1325. switch(terType)
  1326. {
  1327. case 9: //magic plains
  1328. {
  1329. bonusSubtype = 0;
  1330. }
  1331. case 14: //fiery fields
  1332. {
  1333. if(bonusSubtype == -1) bonusSubtype = 1;
  1334. }
  1335. case 15: //rock lands
  1336. {
  1337. if(bonusSubtype == -1) bonusSubtype = 8;
  1338. }
  1339. case 16: //magic clouds
  1340. {
  1341. if(bonusSubtype == -1) bonusSubtype = 2;
  1342. }
  1343. case 17: //lucid pools
  1344. {
  1345. if(bonusSubtype == -1) bonusSubtype = 4;
  1346. }
  1347. { //common part for cases 9, 14, 15, 16, 17
  1348. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1349. break;
  1350. }
  1351. case 18: //holy ground
  1352. {
  1353. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1354. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1355. break;
  1356. }
  1357. case 19: //clover field
  1358. { //+2 luck bonus for neutral creatures
  1359. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureFactionLimiter(-1)));
  1360. break;
  1361. }
  1362. case 20: //evil fog
  1363. {
  1364. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1365. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1366. break;
  1367. }
  1368. case 22: //cursed ground
  1369. {
  1370. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1371. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1372. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  1373. b->valType = Bonus::INDEPENDENT_MAX;
  1374. curB->addNewBonus(b);
  1375. break;
  1376. }
  1377. }
  1378. //overlay premies given
  1379. //native terrain bonuses
  1380. if(town) //during siege always take premies for native terrain of faction
  1381. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1382. boost::shared_ptr<ILimiter> nativeTerrain(new CreatureNativeTerrainLimiter(terrain));
  1383. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1384. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1385. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1386. //////////////////////////////////////////////////////////////////////////
  1387. //tactics
  1388. int tacticLvls[2] = {0};
  1389. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  1390. {
  1391. if(heroes[i])
  1392. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  1393. }
  1394. if(int diff = tacticLvls[0] - tacticLvls[1])
  1395. {
  1396. curB->tacticsSide = diff < 0;
  1397. curB->tacticDistance = std::abs(diff)*2 + 1;
  1398. }
  1399. else
  1400. curB->tacticDistance = 0;
  1401. // workaround — bonuses affecting only enemy
  1402. for(int i = 0; i < 2; i++)
  1403. {
  1404. TNodes nodes;
  1405. curB->belligerents[i]->getRedAncestors(nodes);
  1406. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  1407. {
  1408. BOOST_FOREACH(Bonus *b, n->exportedBonuses)
  1409. {
  1410. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  1411. {
  1412. Bonus *bCopy = new Bonus(*b);
  1413. bCopy->effectRange = Bonus::NO_LIMIT;
  1414. bCopy->propagator.reset();
  1415. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  1416. curB->addNewBonus(bCopy);
  1417. }
  1418. }
  1419. }
  1420. }
  1421. return curB;
  1422. }
  1423. bool BattleInfo::isInTacticRange( THex dest ) const
  1424. {
  1425. return ((!tacticsSide && dest.getX() > 0 && dest.getX() <= tacticDistance)
  1426. || (tacticsSide && dest.getX() < BFIELD_WIDTH - 1 && dest.getX() >= BFIELD_WIDTH - tacticDistance - 1));
  1427. }
  1428. SpellCasting::ESpellCastProblem BattleInfo::battleCanCastSpell(int player, SpellCasting::ECastingMode mode) const
  1429. {
  1430. int side = sides[0] == player ? 0 : 1;
  1431. switch (mode)
  1432. {
  1433. case SpellCasting::HERO_CASTING:
  1434. {
  1435. if(castSpells[side] > 0)
  1436. return SpellCasting::ALREADY_CASTED_THIS_TURN;
  1437. if(!heroes[side])
  1438. return SpellCasting::NO_HERO_TO_CAST_SPELL;
  1439. if(!heroes[side]->getArt(17))
  1440. return SpellCasting::NO_SPELLBOOK;
  1441. }
  1442. break;
  1443. }
  1444. return SpellCasting::OK;
  1445. }
  1446. SpellCasting::ESpellCastProblem BattleInfo::battleCanCastThisSpell( int player, const CSpell * spell, SpellCasting::ECastingMode mode ) const
  1447. {
  1448. SpellCasting::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
  1449. if(genProblem != SpellCasting::OK)
  1450. return genProblem;
  1451. int cside = sides[0] == player ? 0 : 1; //caster's side
  1452. switch(mode)
  1453. {
  1454. case SpellCasting::HERO_CASTING:
  1455. {
  1456. const CGHeroInstance * caster = heroes[cside];
  1457. if(!caster->canCastThisSpell(spell))
  1458. return SpellCasting::HERO_DOESNT_KNOW_SPELL;
  1459. if(caster->mana < getSpellCost(spell, caster)) //not enough mana
  1460. return SpellCasting::NOT_ENOUGH_MANA;
  1461. }
  1462. break;
  1463. }
  1464. if(spell->id < 10) //it's adventure spell (not combat))
  1465. return SpellCasting::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1466. if(NBonus::hasOfType(heroes[1-cside], Bonus::SPELL_IMMUNITY, spell->id)) //non - casting hero provides immunity for this spell
  1467. return SpellCasting::SECOND_HEROS_SPELL_IMMUNITY;
  1468. if(battleMinSpellLevel() > spell->level) //non - casting hero stops caster from casting this spell
  1469. return SpellCasting::SPELL_LEVEL_LIMIT_EXCEEDED;
  1470. int spellIDs[] = {66, 67, 68, 69}; //IDs of summon elemental spells (fire, earth, water, air)
  1471. int creIDs[] = {114, 113, 115, 112}; //(fire, earth, water, air)
  1472. int * idp = std::find(spellIDs, spellIDs + ARRAY_COUNT(spellIDs), spell->id);
  1473. int arpos = idp - spellIDs;
  1474. if(arpos < ARRAY_COUNT(spellIDs))
  1475. {
  1476. //check if there are summoned elementals of other type
  1477. BOOST_FOREACH ( const CStack * st, stacks)
  1478. {
  1479. if (vstd::contains(st->state, SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
  1480. {
  1481. return SpellCasting::ANOTHER_ELEMENTAL_SUMMONED;
  1482. }
  1483. }
  1484. }
  1485. //checking if there exists an appropriate target
  1486. switch(spell->getTargetType())
  1487. {
  1488. case CSpell::CREATURE:
  1489. case CSpell::CREATURE_EXPERT_MASSIVE:
  1490. if(mode == SpellCasting::HERO_CASTING)
  1491. {
  1492. const CGHeroInstance * caster = getHero(player);
  1493. bool targetExists = false;
  1494. BOOST_FOREACH(const CStack * stack, stacks)
  1495. {
  1496. switch (spell->positiveness)
  1497. {
  1498. case 1:
  1499. if(stack->owner == caster->getOwner())
  1500. {
  1501. if(battleIsImmune(player, spell, mode, stack->position) == SpellCasting::OK)
  1502. {
  1503. targetExists = true;
  1504. break;
  1505. }
  1506. }
  1507. break;
  1508. case 0:
  1509. if(battleIsImmune(player, spell, mode, stack->position) == SpellCasting::OK)
  1510. {
  1511. targetExists = true;
  1512. break;
  1513. }
  1514. break;
  1515. case -1:
  1516. if(stack->owner != caster->getOwner())
  1517. {
  1518. if(battleIsImmune(player, spell, mode, stack->position) == SpellCasting::OK)
  1519. {
  1520. targetExists = true;
  1521. break;
  1522. }
  1523. }
  1524. break;
  1525. }
  1526. }
  1527. if(!targetExists)
  1528. {
  1529. return SpellCasting::NO_APPROPRIATE_TARGET;
  1530. }
  1531. }
  1532. break;
  1533. case CSpell::OBSTACLE:
  1534. break;
  1535. }
  1536. return SpellCasting::OK;
  1537. }
  1538. SpellCasting::ESpellCastProblem BattleInfo::battleCanCastThisSpellHere( int player, const CSpell * spell, SpellCasting::ECastingMode mode, THex dest )
  1539. {
  1540. SpellCasting::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
  1541. if(moreGeneralProblem != SpellCasting::OK)
  1542. return moreGeneralProblem;
  1543. return battleIsImmune(player, spell, mode, dest);
  1544. }
  1545. const CGHeroInstance * BattleInfo::getHero( int player ) const
  1546. {
  1547. if(heroes[0] && heroes[0]->getOwner() == player)
  1548. return heroes[0];
  1549. return heroes[1];
  1550. }
  1551. bool NegateRemover(const Bonus* b)
  1552. {
  1553. return b->source == Bonus::CREATURE_ABILITY;
  1554. }
  1555. SpellCasting::ESpellCastProblem BattleInfo::battleIsImmune( int player, const CSpell * spell, SpellCasting::ECastingMode mode, THex dest ) const
  1556. {
  1557. const CStack * subject = getStackT(dest, false);
  1558. const CGHeroInstance * caster = mode == SpellCasting::HERO_CASTING ? getHero(player) : NULL;
  1559. if(subject)
  1560. {
  1561. BonusList immunities = subject->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  1562. if(subject->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  1563. {
  1564. std::remove_if(immunities.begin(), immunities.end(), NegateRemover);
  1565. }
  1566. if(subject->hasBonusOfType(Bonus::SPELL_IMMUNITY, spell->id)
  1567. || ( immunities.size() > 0 && immunities.totalValue() >= spell->level))
  1568. {
  1569. return SpellCasting::STACK_IMMUNE_TO_SPELL;
  1570. }
  1571. //dispel helpful spells
  1572. if(spell->id == 78)
  1573. {
  1574. BonusList spellBon = subject->getSpellBonuses();
  1575. bool hasPositiveSpell = false;
  1576. BOOST_FOREACH(const Bonus * b, spellBon)
  1577. {
  1578. if(VLC->spellh->spells[b->sid]->positiveness > 0)
  1579. {
  1580. hasPositiveSpell = true;
  1581. break;
  1582. }
  1583. }
  1584. if(!hasPositiveSpell)
  1585. {
  1586. return SpellCasting::NO_SPELLS_TO_DISPEL;
  1587. }
  1588. }
  1589. }
  1590. else
  1591. {
  1592. if(spell->getTargetType() == CSpell::CREATURE ||
  1593. (spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE && caster && caster->getSpellSchoolLevel(spell) < 3))
  1594. {
  1595. return SpellCasting::WRONG_SPELL_TARGET;
  1596. }
  1597. }
  1598. return SpellCasting::OK;
  1599. }
  1600. 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
  1601. {
  1602. std::vector<ui32> ret;
  1603. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  1604. {
  1605. if(battleIsImmune(caster->getOwner(), sp, mode, (*it)->position) != SpellCasting::OK)
  1606. {
  1607. ret.push_back((*it)->ID);
  1608. continue;
  1609. }
  1610. //non-negative spells on friendly stacks should always succeed, unless immune
  1611. if(sp->positiveness >= 0 && (*it)->owner == casterSideOwner)
  1612. continue;
  1613. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  1614. if((*it)->owner == casterSideOwner)
  1615. bonusHero = caster;
  1616. else
  1617. bonusHero = hero2;
  1618. int prob = (*it)->valOfBonuses(Bonus::MAGIC_RESISTANCE); //probability of resistance in %
  1619. if(bonusHero)
  1620. {
  1621. //bonusHero's resistance support (secondary skils and artifacts)
  1622. prob += bonusHero->valOfBonuses(Bonus::MAGIC_RESISTANCE);
  1623. //resistance skill
  1624. prob += bonusHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 26) / 100.0f;
  1625. }
  1626. if(prob > 100) prob = 100;
  1627. if(rand()%100 < prob) //immunity from resistance
  1628. ret.push_back((*it)->ID);
  1629. }
  1630. if(sp->id == 60) //hypnotize
  1631. {
  1632. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  1633. {
  1634. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  1635. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  1636. >
  1637. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  1638. )
  1639. {
  1640. ret.push_back((*it)->ID);
  1641. }
  1642. }
  1643. }
  1644. return ret;
  1645. }
  1646. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  1647. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  1648. counterAttacks(1)
  1649. {
  1650. assert(base);
  1651. type = base->type;
  1652. count = baseAmount = base->count;
  1653. nodeType = STACK_BATTLE;
  1654. }
  1655. CStack::CStack()
  1656. {
  1657. init();
  1658. nodeType = STACK_BATTLE;
  1659. }
  1660. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  1661. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  1662. {
  1663. type = stack->type;
  1664. count = baseAmount = stack->count;
  1665. nodeType = STACK_BATTLE;
  1666. }
  1667. void CStack::init()
  1668. {
  1669. base = NULL;
  1670. type = NULL;
  1671. ID = -1;
  1672. count = baseAmount = -1;
  1673. firstHPleft = -1;
  1674. owner = 255;
  1675. slot = 255;
  1676. attackerOwned = false;
  1677. position = THex();
  1678. counterAttacks = -1;
  1679. }
  1680. void CStack::postInit()
  1681. {
  1682. assert(type);
  1683. assert(parents.size());
  1684. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  1685. shots = getCreature()->shots;
  1686. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  1687. state.insert(ALIVE); //alive state indication
  1688. assert(firstHPleft > 0);
  1689. }
  1690. ui32 CStack::Speed( int turn /*= 0*/ ) const
  1691. {
  1692. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  1693. return 0;
  1694. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  1695. int percentBonus = 0;
  1696. BOOST_FOREACH(const Bonus *b, bonuses)
  1697. {
  1698. if(b->type == Bonus::STACKS_SPEED)
  1699. {
  1700. percentBonus += b->additionalInfo;
  1701. }
  1702. }
  1703. speed = ((100 + percentBonus) * speed)/100;
  1704. //bind effect check
  1705. if(getEffect(72))
  1706. {
  1707. return 0;
  1708. }
  1709. return speed;
  1710. }
  1711. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  1712. {
  1713. BOOST_FOREACH(Bonus *it, bonuses)
  1714. {
  1715. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  1716. {
  1717. if(!turn || it->turnsRemain > turn)
  1718. return &(*it);
  1719. }
  1720. }
  1721. return NULL;
  1722. }
  1723. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  1724. {
  1725. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  1726. //why, why, WHY this code is here?!?
  1727. // Bonus * bonus = getBonus(Selector::typeSybtype(Bonus::SPECIAL_PECULIAR_ENCHANT, sse.id));
  1728. // if (bonus)
  1729. // {
  1730. // switch(bonus->additionalInfo)
  1731. // {
  1732. // case 0: //normal
  1733. // switch(type->level)
  1734. // {
  1735. // case 1: case 2:
  1736. // power += 3; //it doesn't necessarily make sense for some spells, use it wisely
  1737. // break;
  1738. // case 3: case 4:
  1739. // power += 2;
  1740. // break;
  1741. // case 5: case 6:
  1742. // power += 1;
  1743. // break;
  1744. // }
  1745. // break;
  1746. // case 1: //only Coronius as yet
  1747. // power = std::max(5 - type->level, 0);
  1748. // break;
  1749. // }
  1750. // }
  1751. switch(sse.sid)
  1752. {
  1753. case 27: //shield
  1754. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1755. sf.back().sid = sse.sid;
  1756. break;
  1757. case 28: //air shield
  1758. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1759. sf.back().sid = sse.sid;
  1760. break;
  1761. case 29: //fire shield
  1762. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  1763. sf.back().sid = sse.sid;
  1764. break;
  1765. case 30: //protection from air
  1766. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1767. sf.back().sid = sse.sid;
  1768. break;
  1769. case 31: //protection from fire
  1770. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1771. sf.back().sid = sse.sid;
  1772. break;
  1773. case 32: //protection from water
  1774. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  1775. sf.back().sid = sse.sid;
  1776. break;
  1777. case 33: //protection from earth
  1778. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  1779. sf.back().sid = sse.sid;
  1780. break;
  1781. case 34: //anti-magic
  1782. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, SPELL_LEVELS, power - 1, sse.turnsRemain));
  1783. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1784. sf.back().sid = sse.sid;
  1785. break;
  1786. case 41: //bless
  1787. // if (hasBonusOfType(Bonus::SPECIAL_BLESS_DAMAGE, 41)) //TODO: better handling of bonus percentages
  1788. // {
  1789. // int damagePercent = dynamic_cast<const CGHeroInstance*>(armyObj)->level * valOfBonuses(Bonus::SPECIAL_BLESS_DAMAGE, 41) / type->level;
  1790. // sf.push_back(featureGenerator(Bonus::CREATURE_DAMAGE, 0, damagePercent, sse.turnsRemain));
  1791. // sf.back().sid = sse.sid;
  1792. // sf.back().valType = Bonus::PERCENT_TO_ALL;
  1793. // }
  1794. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  1795. sf.back().sid = sse.sid;
  1796. break;
  1797. case 42: //curse
  1798. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, -1 * power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  1799. sf.back().sid = sse.sid;
  1800. break;
  1801. case 43: //bloodlust
  1802. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  1803. sf.back().sid = sse.sid;
  1804. break;
  1805. case 44: //precision
  1806. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  1807. sf.back().sid = sse.sid;
  1808. break;
  1809. case 45: //weakness
  1810. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  1811. sf.back().sid = sse.sid;
  1812. break;
  1813. case 46: //stone skin
  1814. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1815. sf.back().sid = sse.sid;
  1816. break;
  1817. case 47: //disrupting ray
  1818. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  1819. sf.back().sid = sse.sid;
  1820. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1821. break;
  1822. case 48: //prayer
  1823. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1824. sf.back().sid = sse.sid;
  1825. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1826. sf.back().sid = sse.sid;
  1827. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1828. sf.back().sid = sse.sid;
  1829. break;
  1830. case 49: //mirth
  1831. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  1832. sf.back().sid = sse.sid;
  1833. break;
  1834. case 50: //sorrow
  1835. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  1836. sf.back().sid = sse.sid;
  1837. break;
  1838. case 51: //fortune
  1839. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  1840. sf.back().sid = sse.sid;
  1841. break;
  1842. case 52: //misfortune
  1843. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  1844. sf.back().sid = sse.sid;
  1845. break;
  1846. case 53: //haste
  1847. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1848. sf.back().sid = sse.sid;
  1849. break;
  1850. case 54: //slow
  1851. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1852. sf.back().sid = sse.sid;
  1853. break;
  1854. case 55: //slayer
  1855. // if (bonus) //Coronius
  1856. // {
  1857. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1858. // sf.back().sid = sse.sid;
  1859. // }
  1860. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  1861. sf.back().sid = sse.sid;
  1862. break;
  1863. case 56: //frenzy
  1864. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  1865. sf.back().sid = sse.sid;
  1866. break;
  1867. case 58: //counterstrike
  1868. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  1869. sf.back().sid = sse.sid;
  1870. break;
  1871. case 59: //bersek
  1872. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  1873. sf.back().sid = sse.sid;
  1874. break;
  1875. case 60: //hypnotize
  1876. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  1877. sf.back().sid = sse.sid;
  1878. break;
  1879. case 61: //forgetfulness
  1880. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  1881. sf.back().sid = sse.sid;
  1882. break;
  1883. case 62: //blind
  1884. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, 0, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1885. sf.back().sid = sse.sid;
  1886. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1887. sf.back().sid = sse.sid;
  1888. break;
  1889. }
  1890. }
  1891. ui8 CStack::howManyEffectsSet(ui16 id) const
  1892. {
  1893. ui8 ret = 0;
  1894. BOOST_FOREACH(const Bonus *it, bonuses)
  1895. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  1896. {
  1897. ++ret;
  1898. }
  1899. return ret;
  1900. }
  1901. bool CStack::willMove(int turn /*= 0*/) const
  1902. {
  1903. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  1904. && !moved(turn)
  1905. && canMove(turn);
  1906. }
  1907. bool CStack::canMove( int turn /*= 0*/ ) const
  1908. {
  1909. return alive()
  1910. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  1911. }
  1912. bool CStack::moved( int turn /*= 0*/ ) const
  1913. {
  1914. if(!turn)
  1915. return vstd::contains(state, MOVED);
  1916. else
  1917. return false;
  1918. }
  1919. bool CStack::doubleWide() const
  1920. {
  1921. return getCreature()->doubleWide;
  1922. }
  1923. THex CStack::occupiedHex() const
  1924. {
  1925. if (doubleWide())
  1926. {
  1927. if (attackerOwned)
  1928. return position - 1;
  1929. else
  1930. return position + 1;
  1931. }
  1932. else
  1933. {
  1934. return THex::INVALID;
  1935. }
  1936. }
  1937. BonusList CStack::getSpellBonuses() const
  1938. {
  1939. return getBonuses(Selector::sourceTypeSel(Bonus::SPELL_EFFECT));
  1940. }
  1941. std::vector<si32> CStack::activeSpells() const
  1942. {
  1943. std::vector<si32> ret;
  1944. BonusList spellEffects = getSpellBonuses();
  1945. BOOST_FOREACH(const Bonus *it, spellEffects)
  1946. {
  1947. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  1948. ret.push_back(it->sid);
  1949. }
  1950. return ret;
  1951. }
  1952. CStack::~CStack()
  1953. {
  1954. detachFromAll();
  1955. if(vstd::contains(state, SUMMONED))
  1956. delNull(base);
  1957. }
  1958. const CGHeroInstance * CStack::getMyHero() const
  1959. {
  1960. if(base)
  1961. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1962. else //we are attached directly?
  1963. BOOST_FOREACH(const CBonusSystemNode *n, parents)
  1964. if(n->nodeType == HERO)
  1965. dynamic_cast<const CGHeroInstance *>(n);
  1966. return NULL;
  1967. }
  1968. std::string CStack::nodeName() const
  1969. {
  1970. std::ostringstream oss;
  1971. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1972. if(type)
  1973. oss << type->namePl;
  1974. else
  1975. oss << "[UNDEFINED TYPE]";
  1976. oss << " from slot " << (int)slot;
  1977. if(base && base->armyObj)
  1978. oss << " of armyobj=" << base->armyObj->id;
  1979. return oss.str();
  1980. }
  1981. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  1982. {
  1983. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  1984. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  1985. if( firstHPleft <= damageFirst )
  1986. {
  1987. bsa.killedAmount++;
  1988. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  1989. }
  1990. else
  1991. {
  1992. bsa.newHP = firstHPleft - damageFirst;
  1993. }
  1994. if(count <= bsa.killedAmount) //stack killed
  1995. {
  1996. bsa.newAmount = 0;
  1997. bsa.flags |= BattleStackAttacked::KILLED;
  1998. bsa.killedAmount = count; //we cannot kill more creatures than we have
  1999. }
  2000. else
  2001. {
  2002. bsa.newAmount = count - bsa.killedAmount;
  2003. }
  2004. }
  2005. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, THex attackerPos /*= THex::INVALID*/, THex defenderPos /*= THex::INVALID*/)
  2006. {
  2007. if (!attackerPos.isValid())
  2008. {
  2009. attackerPos = attacker->position;
  2010. }
  2011. if (!defenderPos.isValid())
  2012. {
  2013. defenderPos = defender->position;
  2014. }
  2015. return
  2016. (THex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  2017. || (attacker->doubleWide() //back <=> front
  2018. && THex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  2019. || (defender->doubleWide() //front <=> back
  2020. && THex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  2021. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  2022. && THex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  2023. }
  2024. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2025. {
  2026. switch(phase)
  2027. {
  2028. case 0: //catapult moves after turrets
  2029. return a->getCreature()->idNumber < b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  2030. //TODO? turrets order
  2031. case 1: //fastest first, upper slot first
  2032. {
  2033. int as = a->Speed(turn), bs = b->Speed(turn);
  2034. if(as != bs)
  2035. return as > bs;
  2036. else
  2037. return a->slot < b->slot;
  2038. }
  2039. case 2: //fastest last, upper slot first
  2040. //TODO: should be replaced with order of receiving morale!
  2041. case 3: //fastest last, upper slot first
  2042. {
  2043. int as = a->Speed(turn), bs = b->Speed(turn);
  2044. if(as != bs)
  2045. return as < bs;
  2046. else
  2047. return a->slot < b->slot;
  2048. }
  2049. default:
  2050. assert(0);
  2051. return false;
  2052. }
  2053. }
  2054. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2055. {
  2056. phase = Phase;
  2057. turn = Turn;
  2058. }