BattleState.cpp 78 KB

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