BattleState.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  1. #include "StdInc.h"
  2. #include "BattleState.h"
  3. #include <numeric>
  4. #include <boost/random/linear_congruential.hpp>
  5. #include "VCMI_Lib.h"
  6. #include "CObjectHandler.h"
  7. #include "CHeroHandler.h"
  8. #include "CCreatureHandler.h"
  9. #include "CSpellHandler.h"
  10. #include "CTownHandler.h"
  11. #include "NetPacks.h"
  12. #include "JsonNode.h"
  13. #include "Filesystem/CResourceLoader.h"
  14. /*
  15. * BattleState.h, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. extern boost::rand48 ran;
  24. const CStack * BattleInfo::getNextStack() const
  25. {
  26. std::vector<const CStack *> hlp;
  27. battleGetStackQueue(hlp, 1, -1);
  28. if(hlp.size())
  29. return hlp[0];
  30. else
  31. return NULL;
  32. }
  33. // const CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive) const
  34. // {
  35. // return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  36. // }
  37. // void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<BattleHex> & occupyable, bool flying, const CStack * stackToOmmit) const
  38. // {
  39. // memset(accessibility, 1, GameConstants::BFIELD_SIZE); //initialize array with trues
  40. //
  41. // //removing accessibility for side columns of hexes
  42. // for(int v = 0; v < GameConstants::BFIELD_SIZE; ++v)
  43. // {
  44. // if( v % GameConstants::BFIELD_WIDTH == 0 || v % GameConstants::BFIELD_WIDTH == (GameConstants::BFIELD_WIDTH - 1) )
  45. // accessibility[v] = false;
  46. // }
  47. //
  48. // for(ui32 g=0; g<stacks.size(); ++g)
  49. // {
  50. // 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)
  51. // continue;
  52. //
  53. // accessibility[stacks[g]->position] = false;
  54. // if(stacks[g]->doubleWide()) //if it's a double hex creature
  55. // {
  56. // if(stacks[g]->attackerOwned)
  57. // accessibility[stacks[g]->position-1] = false;
  58. // else
  59. // accessibility[stacks[g]->position+1] = false;
  60. // }
  61. // }
  62. // //obstacles
  63. // BOOST_FOREACH(const auto &obstacle, obstacles)
  64. // {
  65. // BOOST_FOREACH(BattleHex hex, obstacle->getBlockedTiles())
  66. // {
  67. // assert(hex.isValid());
  68. // accessibility[hex] = false;
  69. // }
  70. // }
  71. //
  72. // //walls
  73. // if(siege > 0)
  74. // {
  75. // static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  76. // for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  77. // {
  78. // accessibility[permanentlyLocked[b]] = false;
  79. // }
  80. //
  81. // static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  82. // {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
  83. // std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
  84. // for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  85. // {
  86. // if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  87. // {
  88. // accessibility[lockedIfNotDestroyed[b].second] = false;
  89. // }
  90. // }
  91. //
  92. // //gate
  93. // if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  94. // {
  95. // accessibility[95] = accessibility[96] = false; //block gate's hexes
  96. // }
  97. // }
  98. //
  99. // //occupyability
  100. // if(addOccupiable && twoHex)
  101. // {
  102. // std::set<BattleHex> rem; //tiles to unlock
  103. // for(int h=0; h<GameConstants::BFIELD_HEIGHT; ++h)
  104. // {
  105. // for(int w=1; w<GameConstants::BFIELD_WIDTH-1; ++w)
  106. // {
  107. // BattleHex hex(w, h);
  108. // if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  109. // && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  110. // )
  111. // rem.insert(hex);
  112. // }
  113. // }
  114. // occupyable = rem;
  115. // /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  116. // {
  117. // accessibility[*it] = true;
  118. // }*/
  119. // }
  120. // }
  121. // bool BattleInfo::isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  122. // {
  123. // if(flying && !lastPos)
  124. // return true;
  125. //
  126. // if(twoHex)
  127. // {
  128. // //if given hex is accessible and appropriate adjacent one is free too
  129. // return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  130. // }
  131. // else
  132. // {
  133. // return accessibility[hex];
  134. // }
  135. // }
  136. // void BattleInfo::makeBFS(BattleHex start, bool *accessibility, BattleHex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  137. // {
  138. // std::set<BattleHex> quicksands = getStoppers(!attackerOwned);
  139. //
  140. // //inits
  141. // for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  142. // predecessor[b] = -1;
  143. // for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  144. // dists[g] = 100000000;
  145. //
  146. // std::queue< std::pair<BattleHex, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  147. // hexq.push(std::make_pair(start, true));
  148. // dists[hexq.front().first] = 0;
  149. // int curNext = -1; //for bfs loop only (helper var)
  150. // while(!hexq.empty()) //bfs loop
  151. // {
  152. // std::pair<BattleHex, bool> curHex = hexq.front();
  153. // std::vector<BattleHex> neighbours = curHex.first.neighbouringTiles();
  154. // hexq.pop();
  155. // if(curHex.first != start && !flying && vstd::contains(quicksands, curHex.first)) //walking stack can't step past the quicksands
  156. // continue;
  157. //
  158. // for(ui32 nr=0; nr<neighbours.size(); nr++)
  159. // {
  160. // curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  161. // bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  162. // if( dists[curHex.first]+1 >= dists[curNext] )
  163. // continue;
  164. // if(accessible && curHex.second)
  165. // {
  166. // hexq.push(std::make_pair(curNext, true));
  167. // dists[curNext] = dists[curHex.first] + 1;
  168. // }
  169. // else if(fillPredecessors && !(accessible && !curHex.second))
  170. // {
  171. // hexq.push(std::make_pair(curNext, false));
  172. // dists[curNext] = dists[curHex.first] + 1;
  173. // }
  174. // predecessor[curNext] = curHex.first;
  175. // }
  176. // }
  177. // };
  178. //
  179. BattleHex BattleInfo::getClosestTile(bool attackerOwned, BattleHex initialPos, std::set<BattleHex> & possibilities) const
  180. {
  181. std::vector<BattleHex> sortedTiles (possibilities.begin(), possibilities.end()); //set can't be sorted properly :(
  182. BattleHex initialHex = BattleHex(initialPos);
  183. auto compareDistance = [initialHex](const BattleHex left, const BattleHex right) -> bool
  184. {
  185. return initialHex.getDistance (initialHex, left) < initialHex.getDistance (initialHex, right);
  186. };
  187. boost::sort (sortedTiles, compareDistance); //closest tiles at front
  188. int closestDistance = initialHex.getDistance(initialPos, sortedTiles.front()); //sometimes closest tiles can be many hexes away
  189. auto notClosest = [closestDistance, initialPos](const BattleHex here) -> bool
  190. {
  191. return closestDistance < here.getDistance (initialPos, here);
  192. };
  193. vstd::erase_if(sortedTiles, notClosest); //only closest tiles are interesting
  194. auto compareHorizontal = [attackerOwned, initialPos](const BattleHex left, const BattleHex right) -> bool
  195. {
  196. if(left.getX() != right.getX())
  197. {
  198. if (attackerOwned)
  199. return left.getX() > right.getX(); //find furthest right
  200. else
  201. return left.getX() < right.getX(); //find furthest left
  202. }
  203. else
  204. {
  205. //Prefer tiles in the same row.
  206. return std::abs(left.getY() - initialPos.getY()) < std::abs(right.getY() - initialPos.getY());
  207. }
  208. };
  209. boost::sort (sortedTiles, compareHorizontal);
  210. return sortedTiles.front();
  211. }
  212. int BattleInfo::getAvaliableHex(TCreature creID, bool attackerOwned, int initialPos) const
  213. {
  214. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  215. //bool flying = VLC->creh->creatures[creID]->isFlying();
  216. int pos;
  217. if (initialPos > -1)
  218. pos = initialPos;
  219. else //summon elementals depending on player side
  220. {
  221. if (attackerOwned)
  222. pos = 0; //top left
  223. else
  224. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  225. }
  226. auto accessibility = getAccesibility();
  227. std::set<BattleHex> occupyable;
  228. for(int i = 0; i < accessibility.size(); i++)
  229. if(accessibility.accessible(i, twoHex, attackerOwned))
  230. occupyable.insert(i);
  231. if (!occupyable.size())
  232. {
  233. return BattleHex::INVALID; //all tiles are covered
  234. }
  235. return getClosestTile(attackerOwned, pos, occupyable);
  236. }
  237. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack *stack)
  238. {
  239. auto reachability = getReachability(stack);
  240. if(reachability.predecessors[dest] == -1) //cannot reach destination
  241. {
  242. return std::make_pair(std::vector<BattleHex>(), 0);
  243. }
  244. //making the Path
  245. std::vector<BattleHex> path;
  246. BattleHex curElem = dest;
  247. while(curElem != start)
  248. {
  249. path.push_back(curElem);
  250. curElem = reachability.predecessors[curElem];
  251. }
  252. return std::make_pair(path, reachability.distances[dest]);
  253. }
  254. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  255. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg )
  256. {
  257. TDmgRange range = calculateDmgRange(attacker, defender, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  258. if(range.first != range.second)
  259. {
  260. int valuesToAverage[10];
  261. int howManyToAv = std::min<ui32>(10, attacker->count);
  262. for (int g=0; g<howManyToAv; ++g)
  263. {
  264. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  265. }
  266. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  267. }
  268. else
  269. return range.first;
  270. }
  271. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  272. {
  273. for(ui32 i=0; i<stacks.size();i++)//setting casualties
  274. {
  275. const CStack * const st = stacks[i];
  276. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  277. vstd::amax(killed, 0);
  278. if(killed)
  279. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  280. }
  281. }
  282. std::set<const CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, BattleHex destinationTile)
  283. {
  284. std::set<const CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  285. const ui8 attackerSide = sides[1] == attackerOwner;
  286. const auto attackedHexes = s->rangeInHexes(destinationTile, skillLevel, attackerSide);
  287. const bool onlyAlive = s->id != Spells::RESURRECTION && s->id != Spells::ANIMATE_DEAD; //when casting resurrection or animate dead we should be allow to select dead stack
  288. //fixme: what about other rising spells (Sacrifice) ?
  289. if(s->id == Spells::DEATH_RIPPLE || s->id == Spells::DESTROY_UNDEAD || s->id == Spells::ARMAGEDDON)
  290. {
  291. for(int it=0; it<stacks.size(); ++it)
  292. {
  293. if((s->id == Spells::DEATH_RIPPLE && !stacks[it]->getCreature()->isUndead()) //death ripple
  294. || (s->id == Spells::DESTROY_UNDEAD && stacks[it]->getCreature()->isUndead()) //destroy undead
  295. || (s->id == Spells::ARMAGEDDON) //Armageddon
  296. )
  297. {
  298. if(stacks[it]->isValidTarget())
  299. attackedCres.insert(stacks[it]);
  300. }
  301. }
  302. }
  303. else if (s->id == Spells::CHAIN_LIGHTNING)
  304. {
  305. std::set<BattleHex> possibleHexes;
  306. BOOST_FOREACH (auto stack, stacks)
  307. {
  308. if (stack->isValidTarget())
  309. {
  310. BOOST_FOREACH (auto hex, stack->getHexes())
  311. {
  312. possibleHexes.insert (hex);
  313. }
  314. }
  315. }
  316. BattleHex lightningHex = destinationTile;
  317. for (int i = 0; i < 5; ++i) //TODO: depends on spell school level
  318. {
  319. auto stack = battleGetStackByPos (lightningHex, true);
  320. if (!stack)
  321. break;
  322. attackedCres.insert (stack);
  323. BOOST_FOREACH (auto hex, stack->getHexes())
  324. {
  325. possibleHexes.erase (hex); //can't hit same place twice
  326. }
  327. lightningHex = getClosestTile (attackerOwner, destinationTile, possibleHexes);
  328. }
  329. }
  330. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  331. {
  332. BOOST_FOREACH(BattleHex hex, attackedHexes)
  333. {
  334. if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
  335. {
  336. if (s->id == 76) //Death Cloud //TODO: fireball and fire immunity
  337. {
  338. if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
  339. {
  340. attackedCres.insert(st);
  341. }
  342. }
  343. else
  344. attackedCres.insert(st);
  345. }
  346. }
  347. }
  348. else if(s->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  349. {
  350. if(skillLevel < 3) /*not expert */
  351. {
  352. const CStack * st = battleGetStackByPos(destinationTile, onlyAlive);
  353. if(st)
  354. attackedCres.insert(st);
  355. }
  356. else
  357. {
  358. for(int it=0; it<stacks.size(); ++it)
  359. {
  360. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  361. if((!s->isNegative() && stacks[it]->owner == attackerOwner)
  362. ||(!s->isPositive() && stacks[it]->owner != attackerOwner )
  363. )
  364. {
  365. if(stacks[it]->isValidTarget(!onlyAlive))
  366. attackedCres.insert(stacks[it]);
  367. }
  368. }
  369. } //if(caster->getSpellSchoolLevel(s) < 3)
  370. }
  371. else if(s->getTargetType() == CSpell::CREATURE)
  372. {
  373. if(const CStack * st = battleGetStackByPos(destinationTile, onlyAlive))
  374. attackedCres.insert(st);
  375. }
  376. else //custom range from attackedHexes
  377. {
  378. BOOST_FOREACH(BattleHex hex, attackedHexes)
  379. {
  380. if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
  381. attackedCres.insert(st);
  382. }
  383. }
  384. return attackedCres;
  385. }
  386. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower)
  387. {
  388. if(!caster)
  389. {
  390. if (!usedSpellPower)
  391. return 3; //default duration of all creature spells
  392. else
  393. return usedSpellPower; //use creature spell power
  394. }
  395. switch(spell->id)
  396. {
  397. case Spells::FRENZY:
  398. return 1;
  399. default: //other spells
  400. return caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  401. }
  402. }
  403. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, int slot, BattleHex position) const
  404. {
  405. int stackID = getIdForNewStack();
  406. int owner = attackerOwned ? sides[0] : sides[1];
  407. assert((owner >= GameConstants::PLAYER_LIMIT) ||
  408. (base.armyObj && base.armyObj->tempOwner == owner));
  409. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  410. ret->position = getAvaliableHex (base.getCreatureID(), attackerOwned, position); //TODO: what if no free tile on battlefield was found?
  411. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  412. return ret;
  413. }
  414. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, int slot, BattleHex position) const
  415. {
  416. int stackID = getIdForNewStack();
  417. int owner = attackerOwned ? sides[0] : sides[1];
  418. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  419. ret->position = position;
  420. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  421. return ret;
  422. }
  423. // std::pair<const CStack *, BattleHex> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  424. // {
  425. // bool ac[GameConstants::BFIELD_SIZE];
  426. // std::set<BattleHex> occupyable;
  427. //
  428. // getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest);
  429. //
  430. // BattleHex predecessor[GameConstants::BFIELD_SIZE];
  431. // int dist[GameConstants::BFIELD_SIZE];
  432. // makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  433. //
  434. // std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  435. // for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  436. // {
  437. // const CStack * atG = getStackT(g);
  438. // if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  439. // continue;
  440. // if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  441. // {
  442. // if(predecessor[g] == -1) //TODO: is it really the best solution?
  443. // continue;
  444. // stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  445. // }
  446. // }
  447. //
  448. // if(stackPairs.size() > 0)
  449. // {
  450. // std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  451. // minimalPairs.push_back(stackPairs[0]);
  452. //
  453. // for(int b=1; b<stackPairs.size(); ++b)
  454. // {
  455. // if(stackPairs[b].first.first < minimalPairs[0].first.first)
  456. // {
  457. // minimalPairs.clear();
  458. // minimalPairs.push_back(stackPairs[b]);
  459. // }
  460. // else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  461. // {
  462. // minimalPairs.push_back(stackPairs[b]);
  463. // }
  464. // }
  465. //
  466. // std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  467. //
  468. // return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  469. // }
  470. //
  471. // return std::make_pair<const CStack * , BattleHex>(NULL, BattleHex::INVALID);
  472. // }
  473. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  474. {
  475. ui32 ret = baseDamage;
  476. //applying sorcery secondary skill
  477. if(caster)
  478. {
  479. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0;
  480. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0;
  481. if(sp->air)
  482. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  483. else if(sp->fire) //only one type of bonus for Magic Arrow
  484. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  485. else if(sp->water)
  486. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  487. else if(sp->earth)
  488. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  489. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  490. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  491. }
  492. return ret;
  493. }
  494. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  495. {
  496. ui32 ret = 0; //value to return
  497. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  498. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  499. //check if spell really does damage - if not, return 0
  500. if(VLC->spellh->damageSpells.find(sp->id) == VLC->spellh->damageSpells.end())
  501. return 0;
  502. ret = usedSpellPower * sp->power;
  503. ret += sp->powers[spellSchoolLevel];
  504. //affected creature-specific part
  505. if(affectedCreature)
  506. {
  507. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  508. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  509. {
  510. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  511. ret /= 100;
  512. }
  513. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  514. {
  515. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  516. ret /= 100;
  517. }
  518. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  519. {
  520. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  521. ret /= 100;
  522. }
  523. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  524. {
  525. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  526. ret /= 100;
  527. }
  528. //general spell dmg reduction
  529. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  530. {
  531. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  532. ret /= 100;
  533. }
  534. //dmg increasing
  535. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  536. {
  537. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  538. ret /= 100;
  539. }
  540. }
  541. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  542. return ret;
  543. }
  544. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack, const CStack * sacrificedStack) const
  545. {
  546. bool resurrect = resurrects(spell->id);
  547. int healedHealth;
  548. if (spell->id == Spells::SACRIFICE && sacrificedStack)
  549. healedHealth = (caster->getPrimSkillLevel(2) + sacrificedStack->MaxHealth() + spell->powers[caster->getSpellSchoolLevel(spell)]) * sacrificedStack->count;
  550. else
  551. healedHealth = caster->getPrimSkillLevel(2) * spell->power + spell->powers[caster->getSpellSchoolLevel(spell)];
  552. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  553. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  554. }
  555. ui32 BattleInfo::calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const
  556. {
  557. bool resurrect = resurrects(spell->id);
  558. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  559. }
  560. ui32 BattleInfo::calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const
  561. {
  562. bool resurrect = resurrects(spell->id);
  563. int healedHealth = usedSpellPower * spell->power + spell->powers[spellSchoolLevel];
  564. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  565. }
  566. bool BattleInfo::resurrects(TSpell spellid) const
  567. {
  568. return vstd::contains(VLC->spellh->risingSpells, spellid);
  569. }
  570. const CStack * BattleInfo::battleGetStack(BattleHex pos, bool onlyAlive)
  571. {
  572. CStack * stack = NULL;
  573. for(ui32 g=0; g<stacks.size(); ++g)
  574. {
  575. if(stacks[g]->position == pos
  576. || (stacks[g]->doubleWide()
  577. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  578. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  579. ) )
  580. {
  581. if (stacks[g]->alive())
  582. return stacks[g]; //we prefer living stacks - there cna be only one stack on te tile, so return it imediately
  583. else if (!onlyAlive)
  584. stack = stacks[g]; //dead stacks are only accessible when there's no alive stack on this tile
  585. }
  586. }
  587. return stack;
  588. }
  589. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  590. {
  591. return heroes[!stack->attackerOwned];
  592. }
  593. void BattleInfo::localInit()
  594. {
  595. belligerents[0]->battle = belligerents[1]->battle = this;
  596. BOOST_FOREACH(CArmedInstance *b, belligerents)
  597. b->attachTo(this);
  598. BOOST_FOREACH(CStack *s, stacks)
  599. localInitStack(s);
  600. exportBonuses();
  601. }
  602. void BattleInfo::localInitStack(CStack * s)
  603. {
  604. s->exportBonuses();
  605. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  606. {
  607. s->attachTo(const_cast<CStackInstance*>(s->base));
  608. }
  609. else //attach directly to obj to which stack belongs and creature type
  610. {
  611. CArmedInstance *army = belligerents[!s->attackerOwned];
  612. s->attachTo(army);
  613. assert(s->type);
  614. s->attachTo(const_cast<CCreature*>(s->type));
  615. }
  616. s->postInit();
  617. }
  618. namespace CGH
  619. {
  620. using namespace std;
  621. static void readBattlePositions(const JsonNode &node, vector< vector<int> > & dest)
  622. {
  623. BOOST_FOREACH(const JsonNode &level, node.Vector())
  624. {
  625. std::vector<int> pom;
  626. BOOST_FOREACH(const JsonNode &value, level.Vector())
  627. {
  628. pom.push_back(value.Float());
  629. }
  630. dest.push_back(pom);
  631. }
  632. }
  633. }
  634. //RNG that works like H3 one
  635. struct RandGen
  636. {
  637. int seed;
  638. void srand(int s)
  639. {
  640. seed = s;
  641. }
  642. void srand(int3 pos)
  643. {
  644. srand(110291 * pos.x + 167801 * pos.y + 81569);
  645. }
  646. int rand()
  647. {
  648. seed = 214013 * seed + 2531011;
  649. return (seed >> 16) & 0x7FFF;
  650. }
  651. int rand(int min, int max)
  652. {
  653. if(min == max)
  654. return min;
  655. if(min > max)
  656. return min;
  657. return min + rand() % (max - min + 1);
  658. }
  659. };
  660. struct RangeGenerator
  661. {
  662. class ExhaustedPossibilities : public std::exception
  663. {
  664. };
  665. RangeGenerator(int _min, int _max, boost::function<int()> _myRand)
  666. {
  667. myRand = _myRand;
  668. min = _min;
  669. remainingCount = _max - _min + 1;
  670. remaining.resize(remainingCount, true);
  671. }
  672. int generateNumber()
  673. {
  674. if(!remainingCount)
  675. throw ExhaustedPossibilities();
  676. if(remainingCount == 1)
  677. return 0;
  678. return myRand() % remainingCount;
  679. }
  680. //get number fulfilling predicate. Never gives the same number twice.
  681. int getSuchNumber(boost::function<bool(int)> goodNumberPred = 0)
  682. {
  683. int ret = -1;
  684. do
  685. {
  686. int n = generateNumber();
  687. int i = 0;
  688. for(;;i++)
  689. {
  690. assert(i < (int)remaining.size());
  691. if(!remaining[i])
  692. continue;
  693. if(!n)
  694. break;
  695. n--;
  696. }
  697. remainingCount--;
  698. remaining[i] = false;
  699. ret = i + min;
  700. } while(goodNumberPred && !goodNumberPred(ret));
  701. return ret;
  702. }
  703. int min, remainingCount;
  704. std::vector<bool> remaining;
  705. boost::function<int()> myRand;
  706. };
  707. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  708. {
  709. CMP_stack cmpst;
  710. BattleInfo *curB = new BattleInfo;
  711. curB->castSpells[0] = curB->castSpells[1] = 0;
  712. curB->sides[0] = armies[0]->tempOwner;
  713. curB->sides[1] = armies[1]->tempOwner;
  714. if(curB->sides[1] == 254)
  715. curB->sides[1] = 255;
  716. std::vector<CStack*> & stacks = (curB->stacks);
  717. curB->tile = tile;
  718. curB->battlefieldType = battlefieldType;
  719. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  720. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  721. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  722. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  723. curB->round = -2;
  724. curB->activeStack = -1;
  725. curB->enchanterCounter[0] = curB->enchanterCounter[1] = 0; //ready to cast
  726. if(town)
  727. {
  728. curB->town = town;
  729. curB->siege = town->fortLevel();
  730. curB->terrainType = VLC->heroh->nativeTerrains[town->town->typeID];
  731. }
  732. else
  733. {
  734. curB->town = NULL;
  735. curB->siege = 0;
  736. curB->terrainType = terrain;
  737. }
  738. //setting up siege obstacles
  739. if (town && town->hasFort())
  740. {
  741. for (int b = 0; b < ARRAY_COUNT (curB->si.wallState); ++b)
  742. {
  743. curB->si.wallState[b] = 1;
  744. }
  745. }
  746. //randomize obstacles
  747. if (town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  748. {
  749. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  750. RandGen r;
  751. auto ourRand = [&]{ return r.rand(); };
  752. r.srand(tile);
  753. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  754. int tilesToBlock = r.rand(5,12);
  755. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  756. std::vector<BattleHex> blockedTiles;
  757. auto appropriateAbsoluteObstacle = [&](int id)
  758. {
  759. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  760. };
  761. auto appropriateUsualObstacle = [&](int id) -> bool
  762. {
  763. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  764. };
  765. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  766. {
  767. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  768. try
  769. {
  770. auto obstPtr = make_shared<CObstacleInstance>();
  771. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  772. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  773. obstPtr->uniqueID = curB->obstacles.size();
  774. curB->obstacles.push_back(obstPtr);
  775. BOOST_FOREACH(BattleHex blocked, obstPtr->getBlockedTiles())
  776. blockedTiles.push_back(blocked);
  777. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  778. }
  779. catch(RangeGenerator::ExhaustedPossibilities &)
  780. {
  781. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  782. }
  783. }
  784. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  785. try
  786. {
  787. while(tilesToBlock > 0)
  788. {
  789. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  790. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  791. auto validPosition = [&](BattleHex pos) -> bool
  792. {
  793. if(obi.height >= pos.getY())
  794. return false;
  795. if(pos.getX() == 0)
  796. return false;
  797. if(pos.getX() + obi.width > 15)
  798. return false;
  799. if(vstd::contains(blockedTiles, pos))
  800. return false;
  801. BOOST_FOREACH(BattleHex blocked, obi.getBlocked(pos))
  802. {
  803. if(vstd::contains(blockedTiles, blocked))
  804. return false;
  805. int x = blocked.getX();
  806. if(x <= 2 || x >= 14)
  807. return false;
  808. }
  809. return true;
  810. };
  811. RangeGenerator posgenerator(18, 168, ourRand);
  812. auto obstPtr = make_shared<CObstacleInstance>();
  813. obstPtr->ID = obid;
  814. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  815. obstPtr->uniqueID = curB->obstacles.size();
  816. curB->obstacles.push_back(obstPtr);
  817. BOOST_FOREACH(BattleHex blocked, obstPtr->getBlockedTiles())
  818. blockedTiles.push_back(blocked);
  819. tilesToBlock -= obi.blockedTiles.size();
  820. }
  821. }
  822. catch(RangeGenerator::ExhaustedPossibilities &)
  823. {
  824. }
  825. }
  826. //reading battleStartpos - add creatures AFTER random obstacles are generated
  827. //TODO: parse once to some structure
  828. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  829. std::vector <int> commanderField, commanderBank;
  830. const JsonNode config(ResourceID("config/battleStartpos.json"));
  831. const JsonVector &positions = config["battle_positions"].Vector();
  832. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  833. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  834. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  835. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  836. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  837. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  838. BOOST_FOREACH (auto position, config["commanderPositions"]["field"].Vector())
  839. {
  840. commanderField.push_back (position.Float());
  841. }
  842. BOOST_FOREACH (auto position, config["commanderPositions"]["creBank"].Vector())
  843. {
  844. commanderBank.push_back (position.Float());
  845. }
  846. //adding war machines
  847. if(!creatureBank)
  848. {
  849. //Checks if hero has artifact and create appropriate stack
  850. auto handleWarMachine= [&](int side, int artslot, int cretype, int hex)
  851. {
  852. if(heroes[side] && heroes[side]->getArt(artslot))
  853. stacks.push_back(curB->generateNewStack(CStackBasicDescriptor(cretype, 1), true, 255, hex));
  854. };
  855. handleWarMachine(0, 13, 146, 52); //ballista
  856. handleWarMachine(0, 14, 148, 18); //ammo cart
  857. handleWarMachine(0, 15, 147, 154);//first aid tent
  858. if(town && town->hasFort())
  859. handleWarMachine(0, 16, 145, 120);//catapult
  860. if(!town) //defending hero shouldn't receive ballista (bug #551)
  861. handleWarMachine(1, 13, 146, 66); //ballista
  862. handleWarMachine(1, 14, 148, 32); //ammo cart
  863. handleWarMachine(1, 15, 147, 168); //first aid tent
  864. }
  865. //war machines added
  866. //battleStartpos read
  867. for(int side = 0; side < 2; side++)
  868. {
  869. int formationNo = armies[side]->stacksCount() - 1;
  870. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  871. int k = 0; //stack serial
  872. for(TSlots::const_iterator i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  873. {
  874. std::vector<int> *formationVector = nullptr;
  875. if(creatureBank)
  876. formationVector = &creBankFormations[side][formationNo];
  877. else if(armies[side]->formation)
  878. formationVector = &tightFormations[side][formationNo];
  879. else
  880. formationVector = &looseFormations[side][formationNo];
  881. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  882. if(creatureBank && i->second->type->isDoubleWide())
  883. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  884. CStack * stack = curB->generateNewStack(*i->second, !side, i->first, pos);
  885. stacks.push_back(stack);
  886. }
  887. }
  888. //adding commanders
  889. for (int i = 0; i < 2; ++i)
  890. {
  891. if (heroes[i] && heroes[i]->commander)
  892. {
  893. CStack * stack = curB->generateNewStack (*heroes[i]->commander, !i, -2, //TODO: use COMMANDER_SLOT_PLACEHOLDER
  894. creatureBank ? commanderBank[i] : commanderField[i]);
  895. stacks.push_back(stack);
  896. }
  897. }
  898. if (curB->siege == 2 || curB->siege == 3)
  899. {
  900. // keep tower
  901. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -2);
  902. stacks.push_back(stack);
  903. if (curB->siege == 3)
  904. {
  905. // lower tower + upper tower
  906. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -4);
  907. stacks.push_back(stack);
  908. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -3);
  909. stacks.push_back(stack);
  910. }
  911. //moat
  912. auto moat = make_shared<MoatObstacle>();
  913. moat->ID = curB->town->subID;
  914. moat->obstacleType = CObstacleInstance::MOAT;
  915. moat->uniqueID = curB->obstacles.size();
  916. curB->obstacles.push_back(moat);
  917. }
  918. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  919. //spell level limiting bonus
  920. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  921. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  922. //giving terrain overalay premies
  923. int bonusSubtype = -1;
  924. switch(battlefieldType)
  925. {
  926. case 9: //magic plains
  927. {
  928. bonusSubtype = 0;
  929. }
  930. case 14: //fiery fields
  931. {
  932. if(bonusSubtype == -1) bonusSubtype = 1;
  933. }
  934. case 15: //rock lands
  935. {
  936. if(bonusSubtype == -1) bonusSubtype = 8;
  937. }
  938. case 16: //magic clouds
  939. {
  940. if(bonusSubtype == -1) bonusSubtype = 2;
  941. }
  942. case 17: //lucid pools
  943. {
  944. if(bonusSubtype == -1) bonusSubtype = 4;
  945. }
  946. { //common part for cases 9, 14, 15, 16, 17
  947. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  948. break;
  949. }
  950. case 18: //holy ground
  951. {
  952. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  953. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  954. break;
  955. }
  956. case 19: //clover field
  957. { //+2 luck bonus for neutral creatures
  958. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureFactionLimiter>(-1)));
  959. break;
  960. }
  961. case 20: //evil fog
  962. {
  963. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  964. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  965. break;
  966. }
  967. case 22: //cursed ground
  968. {
  969. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  970. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  971. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  972. b->valType = Bonus::INDEPENDENT_MAX;
  973. curB->addNewBonus(b);
  974. break;
  975. }
  976. }
  977. //overlay premies given
  978. //native terrain bonuses
  979. auto nativeTerrain = make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  980. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  981. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  982. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  983. //////////////////////////////////////////////////////////////////////////
  984. //tactics
  985. bool isTacticsAllowed = !creatureBank; //no tactics in crebanks
  986. int tacticLvls[2] = {0};
  987. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  988. {
  989. if(heroes[i])
  990. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  991. }
  992. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  993. if(tacticsSkillDiff && isTacticsAllowed)
  994. {
  995. curB->tacticsSide = tacticsSkillDiff < 0;
  996. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  997. }
  998. else
  999. curB->tacticDistance = 0;
  1000. // workaround — bonuses affecting only enemy
  1001. for(int i = 0; i < 2; i++)
  1002. {
  1003. TNodes nodes;
  1004. curB->belligerents[i]->getRedAncestors(nodes);
  1005. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  1006. {
  1007. BOOST_FOREACH(Bonus *b, n->getExportedBonusList())
  1008. {
  1009. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  1010. {
  1011. Bonus *bCopy = new Bonus(*b);
  1012. bCopy->effectRange = Bonus::NO_LIMIT;
  1013. bCopy->propagator.reset();
  1014. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  1015. curB->addNewBonus(bCopy);
  1016. }
  1017. }
  1018. }
  1019. }
  1020. return curB;
  1021. }
  1022. const CGHeroInstance * BattleInfo::getHero( int player ) const
  1023. {
  1024. assert(sides[0] == player || sides[1] == player);
  1025. if(heroes[0] && heroes[0]->getOwner() == player)
  1026. return heroes[0];
  1027. return heroes[1];
  1028. }
  1029. std::vector<ui32> BattleInfo::calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<const CStack*> affectedCreatures, int casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const
  1030. {
  1031. std::vector<ui32> ret;
  1032. for(auto it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  1033. {
  1034. if(battleIsImmune(caster, sp, mode, (*it)->position) != ESpellCastProblem::OK)
  1035. {
  1036. ret.push_back((*it)->ID);
  1037. continue;
  1038. }
  1039. //non-negative spells on friendly stacks should always succeed, unless immune
  1040. if(!sp->isNegative() && (*it)->owner == casterSideOwner)
  1041. continue;
  1042. /*
  1043. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  1044. if((*it)->owner == casterSideOwner)
  1045. bonusHero = caster;
  1046. else
  1047. bonusHero = hero2;*/
  1048. int prob = (*it)->magicResistance(); //probability of resistance in %
  1049. if(prob > 100) prob = 100;
  1050. if(rand()%100 < prob) //immunity from resistance
  1051. ret.push_back((*it)->ID);
  1052. }
  1053. if(sp->id == 60) //hypnotize
  1054. {
  1055. for(auto it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  1056. {
  1057. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  1058. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  1059. >
  1060. usedSpellPower * 25 + sp->powers[spellLevel]
  1061. )
  1062. {
  1063. ret.push_back((*it)->ID);
  1064. }
  1065. }
  1066. }
  1067. return ret;
  1068. }
  1069. int BattleInfo::theOtherPlayer(int player) const
  1070. {
  1071. return sides[!whatSide(player)];
  1072. }
  1073. ui8 BattleInfo::whatSide(int player) const
  1074. {
  1075. for(int i = 0; i < ARRAY_COUNT(sides); i++)
  1076. if(sides[i] == player)
  1077. return i;
  1078. tlog1 << "BattleInfo::whatSide: Player " << player << " is not in battle!\n";
  1079. return -1;
  1080. }
  1081. int BattleInfo::getIdForNewStack() const
  1082. {
  1083. if(stacks.size())
  1084. {
  1085. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  1086. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  1087. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  1088. return highestIDStack->ID + 1;
  1089. }
  1090. return 0;
  1091. }
  1092. shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  1093. {
  1094. BOOST_FOREACH(auto &obs, obstacles)
  1095. if(vstd::contains(obs->getAffectedTiles(), tile))
  1096. return obs;
  1097. return shared_ptr<CObstacleInstance>();
  1098. }
  1099. int BattleInfo::battlefieldTypeToBI(int bfieldType)
  1100. {
  1101. static const std::map<int, int> theMap = boost::assign::map_list_of(19, BattlefieldBI::CLOVER_FIELD)
  1102. (22, BattlefieldBI::CURSED_GROUND)(20, BattlefieldBI::EVIL_FOG)(21, BattlefieldBI::NONE)
  1103. (14, BattlefieldBI::FIERY_FIELDS)(18, BattlefieldBI::HOLY_GROUND)(17, BattlefieldBI::LUCID_POOLS)
  1104. (16, BattlefieldBI::MAGIC_CLOUDS)(9, BattlefieldBI::MAGIC_PLAINS)(15, BattlefieldBI::ROCKLANDS)
  1105. (1, BattlefieldBI::COASTAL);
  1106. auto itr = theMap.find(bfieldType);
  1107. if(itr != theMap.end())
  1108. return itr->second;
  1109. return BattlefieldBI::NONE;
  1110. }
  1111. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  1112. {
  1113. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  1114. }
  1115. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive /*= true*/)
  1116. {
  1117. return const_cast<CStack *>(battleGetStackByPos(tileID, onlyAlive));
  1118. }
  1119. BattleInfo::BattleInfo()
  1120. {
  1121. setBattle(this);
  1122. setNodeType(BATTLE);
  1123. }
  1124. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  1125. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  1126. counterAttacks(1)
  1127. {
  1128. assert(base);
  1129. type = base->type;
  1130. count = baseAmount = base->count;
  1131. setNodeType(STACK_BATTLE);
  1132. }
  1133. CStack::CStack()
  1134. {
  1135. init();
  1136. setNodeType(STACK_BATTLE);
  1137. }
  1138. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  1139. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  1140. {
  1141. type = stack->type;
  1142. count = baseAmount = stack->count;
  1143. setNodeType(STACK_BATTLE);
  1144. }
  1145. void CStack::init()
  1146. {
  1147. base = NULL;
  1148. type = NULL;
  1149. ID = -1;
  1150. count = baseAmount = -1;
  1151. firstHPleft = -1;
  1152. owner = 255;
  1153. slot = 255;
  1154. attackerOwned = false;
  1155. position = BattleHex();
  1156. counterAttacks = -1;
  1157. }
  1158. void CStack::postInit()
  1159. {
  1160. assert(type);
  1161. assert(getParentNodes().size());
  1162. firstHPleft = MaxHealth();
  1163. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  1164. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  1165. casts = valOfBonuses(Bonus::CASTS);
  1166. }
  1167. ui32 CStack::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  1168. {
  1169. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  1170. return 0;
  1171. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  1172. int percentBonus = 0;
  1173. BOOST_FOREACH(const Bonus *b, getBonusList())
  1174. {
  1175. if(b->type == Bonus::STACKS_SPEED)
  1176. {
  1177. percentBonus += b->additionalInfo;
  1178. }
  1179. }
  1180. speed = ((100 + percentBonus) * speed)/100;
  1181. //bind effect check - doesn't influence stack initiative
  1182. if (useBind && getEffect (Spells::BIND))
  1183. {
  1184. return 0;
  1185. }
  1186. return speed;
  1187. }
  1188. si32 CStack::magicResistance() const
  1189. {
  1190. si32 magicResistance;
  1191. if (base) //TODO: make war machines receive aura of magic resistance
  1192. {
  1193. magicResistance = base->magicResistance();
  1194. int auraBonus = 0;
  1195. BOOST_FOREACH (const CStack * stack, base->armyObj->battle-> batteAdjacentCreatures(this))
  1196. {
  1197. if (stack->owner == owner)
  1198. {
  1199. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  1200. }
  1201. }
  1202. magicResistance += auraBonus;
  1203. vstd::amin (magicResistance, 100);
  1204. }
  1205. else
  1206. magicResistance = type->magicResistance();
  1207. return magicResistance;
  1208. }
  1209. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  1210. {
  1211. BOOST_FOREACH(Bonus *it, getBonusList())
  1212. {
  1213. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  1214. {
  1215. if(!turn || it->turnsRemain > turn)
  1216. return &(*it);
  1217. }
  1218. }
  1219. return NULL;
  1220. }
  1221. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  1222. {
  1223. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  1224. switch(sse.sid)
  1225. {
  1226. case 27: //shield
  1227. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1228. sf.back().sid = sse.sid;
  1229. break;
  1230. case 28: //air shield
  1231. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1232. sf.back().sid = sse.sid;
  1233. break;
  1234. case 29: //fire shield
  1235. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  1236. sf.back().sid = sse.sid;
  1237. break;
  1238. case 30: //protection from air
  1239. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1240. sf.back().sid = sse.sid;
  1241. break;
  1242. case 31: //protection from fire
  1243. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1244. sf.back().sid = sse.sid;
  1245. break;
  1246. case 32: //protection from water
  1247. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  1248. sf.back().sid = sse.sid;
  1249. break;
  1250. case 33: //protection from earth
  1251. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  1252. sf.back().sid = sse.sid;
  1253. break;
  1254. case 34: //anti-magic
  1255. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, sse.turnsRemain));
  1256. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1257. sf.back().sid = sse.sid;
  1258. break;
  1259. case 36: //magic mirror
  1260. sf.push_back(featureGenerator(Bonus::MAGIC_MIRROR, -1, power, sse.turnsRemain));
  1261. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1262. sf.back().sid = sse.sid;
  1263. case 41: //bless
  1264. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  1265. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1266. sf.back().sid = sse.sid;
  1267. break;
  1268. case 42: //curse
  1269. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  1270. sf.back().valType = Bonus::INDEPENDENT_MAX;
  1271. sf.back().sid = sse.sid;
  1272. break;
  1273. case 43: //bloodlust
  1274. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  1275. sf.back().sid = sse.sid;
  1276. break;
  1277. case 44: //precision
  1278. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  1279. sf.back().sid = sse.sid;
  1280. break;
  1281. case 45: //weakness
  1282. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  1283. sf.back().sid = sse.sid;
  1284. break;
  1285. case 46: //stone skin
  1286. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1287. sf.back().sid = sse.sid;
  1288. break;
  1289. case 47: //disrupting ray
  1290. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  1291. sf.back().sid = sse.sid;
  1292. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1293. break;
  1294. case 48: //prayer
  1295. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1296. sf.back().sid = sse.sid;
  1297. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1298. sf.back().sid = sse.sid;
  1299. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1300. sf.back().sid = sse.sid;
  1301. break;
  1302. case 49: //mirth
  1303. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  1304. sf.back().sid = sse.sid;
  1305. break;
  1306. case 50: //sorrow
  1307. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  1308. sf.back().sid = sse.sid;
  1309. break;
  1310. case 51: //fortune
  1311. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  1312. sf.back().sid = sse.sid;
  1313. break;
  1314. case 52: //misfortune
  1315. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  1316. sf.back().sid = sse.sid;
  1317. break;
  1318. case 53: //haste
  1319. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1320. sf.back().sid = sse.sid;
  1321. break;
  1322. case 54: //slow
  1323. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1324. sf.back().sid = sse.sid;
  1325. break;
  1326. case 55: //slayer
  1327. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  1328. sf.back().sid = sse.sid;
  1329. break;
  1330. case 56: //frenzy
  1331. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  1332. sf.back().sid = sse.sid;
  1333. break;
  1334. case 58: //counterstrike
  1335. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  1336. sf.back().sid = sse.sid;
  1337. break;
  1338. case 59: //bersek
  1339. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  1340. sf.back().sid = sse.sid;
  1341. break;
  1342. case 60: //hypnotize
  1343. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  1344. sf.back().sid = sse.sid;
  1345. break;
  1346. case 61: //forgetfulness
  1347. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  1348. sf.back().sid = sse.sid;
  1349. break;
  1350. case Spells::BLIND: //blind
  1351. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1352. sf.back().sid = sse.sid;
  1353. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1354. sf.back().sid = sse.sid;
  1355. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  1356. sf.back().sid = sse.sid;
  1357. break;
  1358. case Spells::STONE_GAZE: //Stone Gaze
  1359. case Spells::PARALYZE: //Paralyze
  1360. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1361. sf.back().sid = sse.sid;
  1362. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  1363. sf.back().sid = sse.sid;
  1364. break;
  1365. case 71: //Poison
  1366. sf.push_back(featureGeneratorVT(Bonus::POISON, 0, 30, sse.turnsRemain, Bonus::INDEPENDENT_MAX)); //max hp penalty from this source
  1367. sf.back().sid = sse.sid;
  1368. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -10, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1369. sf.back().sid = sse.sid;
  1370. break;
  1371. case 72: //Bind
  1372. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  1373. sf.back().duration = Bonus::PERMANENT;
  1374. sf.back().sid = sse.sid;
  1375. break;
  1376. case 73: //Disease
  1377. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2 , sse.turnsRemain));
  1378. sf.back().sid = sse.sid;
  1379. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2 , sse.turnsRemain));
  1380. sf.back().sid = sse.sid;
  1381. break;
  1382. case 75: //Age
  1383. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -50, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1384. sf.back().sid = sse.sid;
  1385. break;
  1386. case 80: //Acid Breath
  1387. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  1388. sf.back().sid = sse.sid;
  1389. sf.back().duration = Bonus::PERMANENT;
  1390. sf.back().valType = Bonus::ADDITIVE_VALUE;
  1391. break;
  1392. }
  1393. }
  1394. ui8 CStack::howManyEffectsSet(ui16 id) const
  1395. {
  1396. ui8 ret = 0;
  1397. BOOST_FOREACH(const Bonus *it, getBonusList())
  1398. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  1399. {
  1400. ++ret;
  1401. }
  1402. return ret;
  1403. }
  1404. bool CStack::willMove(int turn /*= 0*/) const
  1405. {
  1406. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  1407. && !moved(turn)
  1408. && canMove(turn);
  1409. }
  1410. bool CStack::canMove( int turn /*= 0*/ ) const
  1411. {
  1412. return alive()
  1413. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  1414. }
  1415. bool CStack::moved( int turn /*= 0*/ ) const
  1416. {
  1417. if(!turn)
  1418. return vstd::contains(state, EBattleStackState::MOVED);
  1419. else
  1420. return false;
  1421. }
  1422. bool CStack::doubleWide() const
  1423. {
  1424. return getCreature()->doubleWide;
  1425. }
  1426. BattleHex CStack::occupiedHex() const
  1427. {
  1428. return occupiedHex(position);
  1429. }
  1430. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  1431. {
  1432. if (doubleWide())
  1433. {
  1434. if (attackerOwned)
  1435. return assumedPos - 1;
  1436. else
  1437. return assumedPos + 1;
  1438. }
  1439. else
  1440. {
  1441. return BattleHex::INVALID;
  1442. }
  1443. }
  1444. std::vector<BattleHex> CStack::getHexes() const
  1445. {
  1446. return getHexes(position);
  1447. }
  1448. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  1449. {
  1450. return getHexes(assumedPos, doubleWide(), attackerOwned);
  1451. }
  1452. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  1453. {
  1454. std::vector<BattleHex> hexes;
  1455. hexes.push_back(assumedPos);
  1456. if (twoHex)
  1457. {
  1458. if (AttackerOwned)
  1459. hexes.push_back(assumedPos - 1);
  1460. else
  1461. hexes.push_back(assumedPos + 1);
  1462. }
  1463. return hexes;
  1464. }
  1465. bool CStack::coversPos(BattleHex pos) const
  1466. {
  1467. return vstd::contains(getHexes(), pos);
  1468. }
  1469. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  1470. {
  1471. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  1472. std::vector<BattleHex> hexes;
  1473. if (doubleWide())
  1474. {
  1475. const int WN = GameConstants::BFIELD_WIDTH;
  1476. if(attackerOwned)
  1477. { //position is equal to front hex
  1478. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  1479. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1480. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1481. BattleHex::checkAndPush(hex - 2, hexes);
  1482. BattleHex::checkAndPush(hex + 1, hexes);
  1483. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  1484. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1485. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1486. }
  1487. else
  1488. {
  1489. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1490. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1491. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  1492. BattleHex::checkAndPush(hex + 2, hexes);
  1493. BattleHex::checkAndPush(hex - 1, hexes);
  1494. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1495. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1496. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  1497. }
  1498. return hexes;
  1499. }
  1500. else
  1501. {
  1502. return hex.neighbouringTiles();
  1503. }
  1504. }
  1505. std::vector<si32> CStack::activeSpells() const
  1506. {
  1507. std::vector<si32> ret;
  1508. TBonusListPtr spellEffects = getSpellBonuses();
  1509. BOOST_FOREACH(const Bonus *it, *spellEffects)
  1510. {
  1511. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  1512. ret.push_back(it->sid);
  1513. }
  1514. return ret;
  1515. }
  1516. CStack::~CStack()
  1517. {
  1518. detachFromAll();
  1519. }
  1520. const CGHeroInstance * CStack::getMyHero() const
  1521. {
  1522. if(base)
  1523. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1524. else //we are attached directly?
  1525. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  1526. if(n->getNodeType() == HERO)
  1527. return dynamic_cast<const CGHeroInstance *>(n);
  1528. return NULL;
  1529. }
  1530. std::string CStack::nodeName() const
  1531. {
  1532. std::ostringstream oss;
  1533. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1534. if(type)
  1535. oss << type->namePl;
  1536. else
  1537. oss << "[UNDEFINED TYPE]";
  1538. oss << " from slot " << (int)slot;
  1539. if(base && base->armyObj)
  1540. oss << " of armyobj=" << base->armyObj->id;
  1541. return oss.str();
  1542. }
  1543. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  1544. {
  1545. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  1546. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  1547. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  1548. {
  1549. bsa.killedAmount = count;
  1550. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  1551. return; // no rebirth I believe
  1552. }
  1553. if( firstHPleft <= damageFirst )
  1554. {
  1555. bsa.killedAmount++;
  1556. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  1557. }
  1558. else
  1559. {
  1560. bsa.newHP = firstHPleft - damageFirst;
  1561. }
  1562. if(count <= bsa.killedAmount) //stack killed
  1563. {
  1564. bsa.newAmount = 0;
  1565. bsa.flags |= BattleStackAttacked::KILLED;
  1566. bsa.killedAmount = count; //we cannot kill more creatures than we have
  1567. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  1568. if (resurrectFactor > 0 && casts) //there must be casts left
  1569. {
  1570. int resurrectedCount = base->count * resurrectFactor / 100;
  1571. if (resurrectedCount)
  1572. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  1573. else //only one unit
  1574. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  1575. if (hasBonusOfType(Bonus::REBIRTH, 1))
  1576. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  1577. if (resurrectedCount)
  1578. {
  1579. bsa.flags |= BattleStackAttacked::REBIRTH;
  1580. bsa.newAmount = resurrectedCount; //risky?
  1581. bsa.newHP = MaxHealth(); //resore full health
  1582. }
  1583. }
  1584. }
  1585. else
  1586. {
  1587. bsa.newAmount = count - bsa.killedAmount;
  1588. }
  1589. }
  1590. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  1591. {
  1592. if (!attackerPos.isValid())
  1593. {
  1594. attackerPos = attacker->position;
  1595. }
  1596. if (!defenderPos.isValid())
  1597. {
  1598. defenderPos = defender->position;
  1599. }
  1600. return
  1601. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1602. || (attacker->doubleWide() //back <=> front
  1603. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1604. || (defender->doubleWide() //front <=> back
  1605. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1606. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1607. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1608. }
  1609. bool CStack::ableToRetaliate() const
  1610. {
  1611. return alive()
  1612. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  1613. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  1614. && !hasBonusOfType(Bonus::HYPNOTIZED)
  1615. && !hasBonusOfType(Bonus::NO_RETALIATION);
  1616. }
  1617. std::string CStack::getName() const
  1618. {
  1619. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1620. }
  1621. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  1622. {
  1623. return (alive() || allowDead) && position.isValid();
  1624. }
  1625. bool CStack::canBeHealed() const
  1626. {
  1627. return firstHPleft < MaxHealth()
  1628. && isValidTarget()
  1629. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1630. }
  1631. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1632. {
  1633. switch(phase)
  1634. {
  1635. case 0: //catapult moves after turrets
  1636. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1637. case 1: //fastest first, upper slot first
  1638. {
  1639. int as = a->Speed(turn), bs = b->Speed(turn);
  1640. if(as != bs)
  1641. return as > bs;
  1642. else
  1643. return a->slot < b->slot;
  1644. }
  1645. case 2: //fastest last, upper slot first
  1646. //TODO: should be replaced with order of receiving morale!
  1647. case 3: //fastest last, upper slot first
  1648. {
  1649. int as = a->Speed(turn), bs = b->Speed(turn);
  1650. if(as != bs)
  1651. return as < bs;
  1652. else
  1653. return a->slot < b->slot;
  1654. }
  1655. default:
  1656. assert(0);
  1657. return false;
  1658. }
  1659. }
  1660. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1661. {
  1662. phase = Phase;
  1663. turn = Turn;
  1664. }