BattleState.cpp 78 KB

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