BattleState.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. #include "StdInc.h"
  2. #include "BattleState.h"
  3. #include <numeric>
  4. #include "VCMI_Lib.h"
  5. #include "CObjectHandler.h"
  6. #include "CHeroHandler.h"
  7. #include "CCreatureHandler.h"
  8. #include "CSpellHandler.h"
  9. #include "CTownHandler.h"
  10. #include "NetPacks.h"
  11. #include "JsonNode.h"
  12. #include "filesystem/CResourceLoader.h"
  13. /*
  14. * BattleState.h, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. extern std::minstd_rand ran;
  23. const CStack * BattleInfo::getNextStack() const
  24. {
  25. std::vector<const CStack *> hlp;
  26. battleGetStackQueue(hlp, 1, -1);
  27. if(hlp.size())
  28. return hlp[0];
  29. else
  30. return nullptr;
  31. }
  32. int BattleInfo::getAvaliableHex(CreatureID creID, bool attackerOwned, int initialPos) const
  33. {
  34. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  35. //bool flying = VLC->creh->creatures[creID]->isFlying();
  36. int pos;
  37. if (initialPos > -1)
  38. pos = initialPos;
  39. else //summon elementals depending on player side
  40. {
  41. if (attackerOwned)
  42. pos = 0; //top left
  43. else
  44. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  45. }
  46. auto accessibility = getAccesibility();
  47. std::set<BattleHex> occupyable;
  48. for(int i = 0; i < accessibility.size(); i++)
  49. if(accessibility.accessible(i, twoHex, attackerOwned))
  50. occupyable.insert(i);
  51. if (!occupyable.size())
  52. {
  53. return BattleHex::INVALID; //all tiles are covered
  54. }
  55. return BattleHex::getClosestTile(attackerOwned, pos, occupyable);
  56. }
  57. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack *stack)
  58. {
  59. auto reachability = getReachability(stack);
  60. if(reachability.predecessors[dest] == -1) //cannot reach destination
  61. {
  62. return std::make_pair(std::vector<BattleHex>(), 0);
  63. }
  64. //making the Path
  65. std::vector<BattleHex> path;
  66. BattleHex curElem = dest;
  67. while(curElem != start)
  68. {
  69. path.push_back(curElem);
  70. curElem = reachability.predecessors[curElem];
  71. }
  72. return std::make_pair(path, reachability.distances[dest]);
  73. }
  74. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  75. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg )
  76. {
  77. TDmgRange range = calculateDmgRange(attacker, defender, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  78. if(range.first != range.second)
  79. {
  80. int valuesToAverage[10];
  81. int howManyToAv = std::min<ui32>(10, attacker->count);
  82. for (int g=0; g<howManyToAv; ++g)
  83. {
  84. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  85. }
  86. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  87. }
  88. else
  89. return range.first;
  90. }
  91. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  92. {
  93. for(ui32 i=0; i<stacks.size();i++)//setting casualties
  94. {
  95. const CStack * const st = stacks[i];
  96. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  97. vstd::amax(killed, 0);
  98. if(killed)
  99. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  100. }
  101. }
  102. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower)
  103. {
  104. if(!caster)
  105. {
  106. if (!usedSpellPower)
  107. return 3; //default duration of all creature spells
  108. else
  109. return usedSpellPower; //use creature spell power
  110. }
  111. switch(spell->id)
  112. {
  113. case SpellID::FRENZY:
  114. return 1;
  115. default: //other spells
  116. return caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  117. }
  118. }
  119. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, SlotID slot, BattleHex position) const
  120. {
  121. int stackID = getIdForNewStack();
  122. PlayerColor owner = attackerOwned ? sides[0] : sides[1];
  123. assert((owner >= PlayerColor::PLAYER_LIMIT) ||
  124. (base.armyObj && base.armyObj->tempOwner == owner));
  125. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  126. ret->position = getAvaliableHex (base.getCreatureID(), attackerOwned, position); //TODO: what if no free tile on battlefield was found?
  127. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  128. return ret;
  129. }
  130. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, SlotID slot, BattleHex position) const
  131. {
  132. int stackID = getIdForNewStack();
  133. PlayerColor owner = attackerOwned ? sides[0] : sides[1];
  134. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  135. ret->position = position;
  136. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  137. return ret;
  138. }
  139. //All spells casted by hero 9resurrection, cure, sacrifice)
  140. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack, const CStack * sacrificedStack) const
  141. {
  142. bool resurrect = resurrects(spell->id);
  143. int healedHealth;
  144. if (spell->id == SpellID::SACRIFICE && sacrificedStack)
  145. healedHealth = (caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + sacrificedStack->MaxHealth() + spell->powers[caster->getSpellSchoolLevel(spell)]) * sacrificedStack->count;
  146. else
  147. healedHealth = caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) * spell->power + spell->powers[caster->getSpellSchoolLevel(spell)];
  148. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  149. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  150. }
  151. //Archangel
  152. ui32 BattleInfo::calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const
  153. {
  154. bool resurrect = resurrects(spell->id);
  155. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  156. }
  157. //Casted by stack, no hero bonus applied
  158. ui32 BattleInfo::calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const
  159. {
  160. bool resurrect = resurrects(spell->id);
  161. int healedHealth = usedSpellPower * spell->power + spell->powers[spellSchoolLevel];
  162. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  163. }
  164. bool BattleInfo::resurrects(SpellID spellid) const
  165. {
  166. return spellid.toSpell()->isRisingSpell();
  167. }
  168. const CStack * BattleInfo::battleGetStack(BattleHex pos, bool onlyAlive)
  169. {
  170. CStack * stack = nullptr;
  171. for(ui32 g=0; g<stacks.size(); ++g)
  172. {
  173. if(stacks[g]->position == pos
  174. || (stacks[g]->doubleWide()
  175. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  176. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  177. ) )
  178. {
  179. if (stacks[g]->alive())
  180. return stacks[g]; //we prefer living stacks - there cna be only one stack on te tile, so return it imediately
  181. else if (!onlyAlive)
  182. stack = stacks[g]; //dead stacks are only accessible when there's no alive stack on this tile
  183. }
  184. }
  185. return stack;
  186. }
  187. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  188. {
  189. return heroes[!stack->attackerOwned];
  190. }
  191. void BattleInfo::localInit()
  192. {
  193. belligerents[0]->battle = belligerents[1]->battle = this;
  194. BOOST_FOREACH(CArmedInstance *b, belligerents)
  195. b->attachTo(this);
  196. BOOST_FOREACH(CStack *s, stacks)
  197. localInitStack(s);
  198. exportBonuses();
  199. }
  200. void BattleInfo::localInitStack(CStack * s)
  201. {
  202. s->exportBonuses();
  203. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  204. {
  205. s->attachTo(const_cast<CStackInstance*>(s->base));
  206. }
  207. else //attach directly to obj to which stack belongs and creature type
  208. {
  209. CArmedInstance *army = belligerents[!s->attackerOwned];
  210. s->attachTo(army);
  211. assert(s->type);
  212. s->attachTo(const_cast<CCreature*>(s->type));
  213. }
  214. s->postInit();
  215. }
  216. namespace CGH
  217. {
  218. using namespace std;
  219. static void readBattlePositions(const JsonNode &node, vector< vector<int> > & dest)
  220. {
  221. BOOST_FOREACH(const JsonNode &level, node.Vector())
  222. {
  223. std::vector<int> pom;
  224. BOOST_FOREACH(const JsonNode &value, level.Vector())
  225. {
  226. pom.push_back(value.Float());
  227. }
  228. dest.push_back(pom);
  229. }
  230. }
  231. }
  232. //RNG that works like H3 one
  233. struct RandGen
  234. {
  235. int seed;
  236. void srand(int s)
  237. {
  238. seed = s;
  239. }
  240. void srand(int3 pos)
  241. {
  242. srand(110291 * pos.x + 167801 * pos.y + 81569);
  243. }
  244. int rand()
  245. {
  246. seed = 214013 * seed + 2531011;
  247. return (seed >> 16) & 0x7FFF;
  248. }
  249. int rand(int min, int max)
  250. {
  251. if(min == max)
  252. return min;
  253. if(min > max)
  254. return min;
  255. return min + rand() % (max - min + 1);
  256. }
  257. };
  258. struct RangeGenerator
  259. {
  260. class ExhaustedPossibilities : public std::exception
  261. {
  262. };
  263. RangeGenerator(int _min, int _max, std::function<int()> _myRand)
  264. {
  265. myRand = _myRand;
  266. min = _min;
  267. remainingCount = _max - _min + 1;
  268. remaining.resize(remainingCount, true);
  269. }
  270. int generateNumber()
  271. {
  272. if(!remainingCount)
  273. throw ExhaustedPossibilities();
  274. if(remainingCount == 1)
  275. return 0;
  276. return myRand() % remainingCount;
  277. }
  278. //get number fulfilling predicate. Never gives the same number twice.
  279. int getSuchNumber(std::function<bool(int)> goodNumberPred = 0)
  280. {
  281. int ret = -1;
  282. do
  283. {
  284. int n = generateNumber();
  285. int i = 0;
  286. for(;;i++)
  287. {
  288. assert(i < (int)remaining.size());
  289. if(!remaining[i])
  290. continue;
  291. if(!n)
  292. break;
  293. n--;
  294. }
  295. remainingCount--;
  296. remaining[i] = false;
  297. ret = i + min;
  298. } while(goodNumberPred && !goodNumberPred(ret));
  299. return ret;
  300. }
  301. int min, remainingCount;
  302. std::vector<bool> remaining;
  303. std::function<int()> myRand;
  304. };
  305. BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  306. {
  307. CMP_stack cmpst;
  308. BattleInfo *curB = new BattleInfo;
  309. curB->castSpells[0] = curB->castSpells[1] = 0;
  310. curB->sides[0] = armies[0]->tempOwner;
  311. curB->sides[1] = armies[1]->tempOwner;
  312. if(curB->sides[1] == PlayerColor::UNFLAGGABLE)
  313. curB->sides[1] = PlayerColor::NEUTRAL;
  314. std::vector<CStack*> & stacks = (curB->stacks);
  315. curB->tile = tile;
  316. curB->battlefieldType = battlefieldType;
  317. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  318. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  319. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  320. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  321. curB->round = -2;
  322. curB->activeStack = -1;
  323. curB->enchanterCounter[0] = curB->enchanterCounter[1] = 0; //ready to cast
  324. if(town)
  325. {
  326. curB->town = town;
  327. curB->siege = town->fortLevel();
  328. curB->terrainType = VLC->townh->factions[town->subID]->nativeTerrain;
  329. }
  330. else
  331. {
  332. curB->town = nullptr;
  333. curB->siege = CGTownInstance::NONE;
  334. curB->terrainType = terrain;
  335. }
  336. //setting up siege obstacles
  337. if (town && town->hasFort())
  338. {
  339. for (int b = 0; b < ARRAY_COUNT (curB->si.wallState); ++b)
  340. {
  341. curB->si.wallState[b] = 1;
  342. }
  343. }
  344. //randomize obstacles
  345. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  346. {
  347. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  348. RandGen r;
  349. auto ourRand = [&]{ return r.rand(); };
  350. r.srand(tile);
  351. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  352. int tilesToBlock = r.rand(5,12);
  353. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  354. std::vector<BattleHex> blockedTiles;
  355. auto appropriateAbsoluteObstacle = [&](int id)
  356. {
  357. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  358. };
  359. auto appropriateUsualObstacle = [&](int id) -> bool
  360. {
  361. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  362. };
  363. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  364. {
  365. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  366. try
  367. {
  368. auto obstPtr = make_shared<CObstacleInstance>();
  369. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  370. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  371. obstPtr->uniqueID = curB->obstacles.size();
  372. curB->obstacles.push_back(obstPtr);
  373. BOOST_FOREACH(BattleHex blocked, obstPtr->getBlockedTiles())
  374. blockedTiles.push_back(blocked);
  375. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  376. }
  377. catch(RangeGenerator::ExhaustedPossibilities &)
  378. {
  379. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  380. }
  381. }
  382. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  383. try
  384. {
  385. while(tilesToBlock > 0)
  386. {
  387. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  388. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  389. auto validPosition = [&](BattleHex pos) -> bool
  390. {
  391. if(obi.height >= pos.getY())
  392. return false;
  393. if(pos.getX() == 0)
  394. return false;
  395. if(pos.getX() + obi.width > 15)
  396. return false;
  397. if(vstd::contains(blockedTiles, pos))
  398. return false;
  399. BOOST_FOREACH(BattleHex blocked, obi.getBlocked(pos))
  400. {
  401. if(vstd::contains(blockedTiles, blocked))
  402. return false;
  403. int x = blocked.getX();
  404. if(x <= 2 || x >= 14)
  405. return false;
  406. }
  407. return true;
  408. };
  409. RangeGenerator posgenerator(18, 168, ourRand);
  410. auto obstPtr = make_shared<CObstacleInstance>();
  411. obstPtr->ID = obid;
  412. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  413. obstPtr->uniqueID = curB->obstacles.size();
  414. curB->obstacles.push_back(obstPtr);
  415. BOOST_FOREACH(BattleHex blocked, obstPtr->getBlockedTiles())
  416. blockedTiles.push_back(blocked);
  417. tilesToBlock -= obi.blockedTiles.size();
  418. }
  419. }
  420. catch(RangeGenerator::ExhaustedPossibilities &)
  421. {
  422. }
  423. }
  424. //reading battleStartpos - add creatures AFTER random obstacles are generated
  425. //TODO: parse once to some structure
  426. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  427. std::vector <int> commanderField, commanderBank;
  428. const JsonNode config(ResourceID("config/battleStartpos.json"));
  429. const JsonVector &positions = config["battle_positions"].Vector();
  430. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  431. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  432. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  433. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  434. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  435. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  436. BOOST_FOREACH (auto position, config["commanderPositions"]["field"].Vector())
  437. {
  438. commanderField.push_back (position.Float());
  439. }
  440. BOOST_FOREACH (auto position, config["commanderPositions"]["creBank"].Vector())
  441. {
  442. commanderBank.push_back (position.Float());
  443. }
  444. //adding war machines
  445. if(!creatureBank)
  446. {
  447. //Checks if hero has artifact and create appropriate stack
  448. auto handleWarMachine= [&](int side, ArtifactPosition artslot, CreatureID cretype, BattleHex hex)
  449. {
  450. if(heroes[side] && heroes[side]->getArt(artslot))
  451. stacks.push_back(curB->generateNewStack(CStackBasicDescriptor(cretype, 1), !side, SlotID(255), hex));
  452. };
  453. handleWarMachine(0, ArtifactPosition::MACH1, CreatureID::BALLISTA, 52);
  454. handleWarMachine(0, ArtifactPosition::MACH2, CreatureID::AMMO_CART, 18);
  455. handleWarMachine(0, ArtifactPosition::MACH3, CreatureID::FIRST_AID_TENT, 154);
  456. if(town && town->hasFort())
  457. handleWarMachine(0, ArtifactPosition::MACH4, CreatureID::CATAPULT, 120);
  458. if(!town) //defending hero shouldn't receive ballista (bug #551)
  459. handleWarMachine(1, ArtifactPosition::MACH1, CreatureID::BALLISTA, 66);
  460. handleWarMachine(1, ArtifactPosition::MACH2, CreatureID::AMMO_CART, 32);
  461. handleWarMachine(1, ArtifactPosition::MACH3, CreatureID::FIRST_AID_TENT, 168);
  462. }
  463. //war machines added
  464. //battleStartpos read
  465. for(int side = 0; side < 2; side++)
  466. {
  467. int formationNo = armies[side]->stacksCount() - 1;
  468. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  469. int k = 0; //stack serial
  470. for(TSlots::const_iterator i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  471. {
  472. std::vector<int> *formationVector = nullptr;
  473. if(creatureBank)
  474. formationVector = &creBankFormations[side][formationNo];
  475. else if(armies[side]->formation)
  476. formationVector = &tightFormations[side][formationNo];
  477. else
  478. formationVector = &looseFormations[side][formationNo];
  479. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  480. if(creatureBank && i->second->type->isDoubleWide())
  481. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  482. CStack * stack = curB->generateNewStack(*i->second, !side, i->first, pos);
  483. stacks.push_back(stack);
  484. }
  485. }
  486. //adding commanders
  487. for (int i = 0; i < 2; ++i)
  488. {
  489. if (heroes[i] && heroes[i]->commander)
  490. {
  491. CStack * stack = curB->generateNewStack (*heroes[i]->commander, !i, SlotID::COMMANDER_SLOT_PLACEHOLDER,
  492. creatureBank ? commanderBank[i] : commanderField[i]);
  493. stacks.push_back(stack);
  494. }
  495. }
  496. if (curB->siege == CGTownInstance::CITADEL || curB->siege == CGTownInstance::CASTLE)
  497. {
  498. // keep tower
  499. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID(255), -2);
  500. stacks.push_back(stack);
  501. if (curB->siege == CGTownInstance::CASTLE)
  502. {
  503. // lower tower + upper tower
  504. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID(255), -4);
  505. stacks.push_back(stack);
  506. stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID(255), -3);
  507. stacks.push_back(stack);
  508. }
  509. //moat
  510. auto moat = make_shared<MoatObstacle>();
  511. moat->ID = curB->town->subID;
  512. moat->obstacleType = CObstacleInstance::MOAT;
  513. moat->uniqueID = curB->obstacles.size();
  514. curB->obstacles.push_back(moat);
  515. }
  516. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  517. //spell level limiting bonus
  518. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  519. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  520. //giving terrain overalay premies
  521. int bonusSubtype = -1;
  522. switch(battlefieldType)
  523. {
  524. case BFieldType::MAGIC_PLAINS:
  525. {
  526. bonusSubtype = 0;
  527. }
  528. case BFieldType::FIERY_FIELDS:
  529. {
  530. if(bonusSubtype == -1) bonusSubtype = 1;
  531. }
  532. case BFieldType::ROCKLANDS:
  533. {
  534. if(bonusSubtype == -1) bonusSubtype = 8;
  535. }
  536. case BFieldType::MAGIC_CLOUDS:
  537. {
  538. if(bonusSubtype == -1) bonusSubtype = 2;
  539. }
  540. case BFieldType::LUCID_POOLS:
  541. {
  542. if(bonusSubtype == -1) bonusSubtype = 4;
  543. }
  544. { //common part for cases 9, 14, 15, 16, 17
  545. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  546. break;
  547. }
  548. case BFieldType::HOLY_GROUND:
  549. {
  550. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  551. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  552. break;
  553. }
  554. case BFieldType::CLOVER_FIELD:
  555. { //+2 luck bonus for neutral creatures
  556. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL)));
  557. break;
  558. }
  559. case BFieldType::EVIL_FOG:
  560. {
  561. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  562. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  563. break;
  564. }
  565. case BFieldType::CURSED_GROUND:
  566. {
  567. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  568. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  569. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  570. b->valType = Bonus::INDEPENDENT_MAX;
  571. curB->addNewBonus(b);
  572. break;
  573. }
  574. }
  575. //overlay premies given
  576. //native terrain bonuses
  577. auto nativeTerrain = make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  578. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  579. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  580. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  581. //////////////////////////////////////////////////////////////////////////
  582. //tactics
  583. bool isTacticsAllowed = !creatureBank; //no tactics in crebanks
  584. int tacticLvls[2] = {0};
  585. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  586. {
  587. if(heroes[i])
  588. tacticLvls[i] += heroes[i]->getSecSkillLevel(SecondarySkill::TACTICS);
  589. }
  590. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  591. if(tacticsSkillDiff && isTacticsAllowed)
  592. {
  593. curB->tacticsSide = tacticsSkillDiff < 0;
  594. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  595. }
  596. else
  597. curB->tacticDistance = 0;
  598. // workaround — bonuses affecting only enemy - DOES NOT WORK
  599. for(int i = 0; i < 2; i++)
  600. {
  601. TNodes nodes;
  602. curB->belligerents[i]->getRedAncestors(nodes);
  603. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  604. {
  605. BOOST_FOREACH(Bonus *b, n->getExportedBonusList())
  606. {
  607. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  608. {
  609. Bonus *bCopy = new Bonus(*b);
  610. bCopy->effectRange = Bonus::NO_LIMIT;
  611. bCopy->propagator.reset();
  612. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  613. curB->addNewBonus(bCopy);
  614. }
  615. }
  616. }
  617. }
  618. return curB;
  619. }
  620. const CGHeroInstance * BattleInfo::getHero( PlayerColor player ) const
  621. {
  622. assert(sides[0] == player || sides[1] == player);
  623. if(heroes[0] && heroes[0]->getOwner() == player)
  624. return heroes[0];
  625. return heroes[1];
  626. }
  627. std::vector<ui32> BattleInfo::calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<const CStack*> affectedCreatures, PlayerColor casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const
  628. {
  629. std::vector<ui32> ret;
  630. for(auto it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  631. {
  632. if(battleIsImmune(caster, sp, mode, (*it)->position) != ESpellCastProblem::OK) //FIXME: immune stacks should not display resisted animation
  633. {
  634. ret.push_back((*it)->ID);
  635. continue;
  636. }
  637. //non-negative spells should always succeed, unless immune
  638. if(!sp->isNegative())// && (*it)->owner == casterSideOwner)
  639. continue;
  640. /*
  641. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  642. if((*it)->owner == casterSideOwner)
  643. bonusHero = caster;
  644. else
  645. bonusHero = hero2;*/
  646. int prob = (*it)->magicResistance(); //probability of resistance in %
  647. if(prob > 100) prob = 100;
  648. if(rand()%100 < prob) //immunity from resistance
  649. ret.push_back((*it)->ID);
  650. }
  651. if(sp->id == SpellID::HYPNOTIZE) //hypnotize
  652. {
  653. for(auto it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  654. {
  655. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  656. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  657. >
  658. calculateSpellBonus (usedSpellPower * 25 + sp->powers[spellLevel], sp, caster, *it) //apply 'damage' bonus for hypnotize, including hero specialty
  659. )
  660. {
  661. ret.push_back((*it)->ID);
  662. }
  663. }
  664. }
  665. return ret;
  666. }
  667. PlayerColor BattleInfo::theOtherPlayer(PlayerColor player) const
  668. {
  669. return sides[!whatSide(player)];
  670. }
  671. ui8 BattleInfo::whatSide(PlayerColor player) const
  672. {
  673. for(int i = 0; i < ARRAY_COUNT(sides); i++)
  674. if(sides[i] == player)
  675. return i;
  676. logGlobal->warnStream() << "BattleInfo::whatSide: Player " << player << " is not in battle!";
  677. return -1;
  678. }
  679. int BattleInfo::getIdForNewStack() const
  680. {
  681. if(stacks.size())
  682. {
  683. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  684. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  685. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  686. return highestIDStack->ID + 1;
  687. }
  688. return 0;
  689. }
  690. shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  691. {
  692. BOOST_FOREACH(auto &obs, obstacles)
  693. if(vstd::contains(obs->getAffectedTiles(), tile))
  694. return obs;
  695. return shared_ptr<CObstacleInstance>();
  696. }
  697. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  698. {
  699. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap = boost::assign::map_list_of
  700. (BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD)
  701. (BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND)
  702. (BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG)
  703. (BFieldType::FAVOURABLE_WINDS, BattlefieldBI::NONE)
  704. (BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS)
  705. (BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND)
  706. (BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS)
  707. (BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS)
  708. (BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS)
  709. (BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS)
  710. (BFieldType::SAND_SHORE, BattlefieldBI::COASTAL);
  711. auto itr = theMap.find(bfieldType);
  712. if(itr != theMap.end())
  713. return itr->second;
  714. return BattlefieldBI::NONE;
  715. }
  716. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  717. {
  718. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  719. }
  720. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive /*= true*/)
  721. {
  722. return const_cast<CStack *>(battleGetStackByPos(tileID, onlyAlive));
  723. }
  724. BattleInfo::BattleInfo()
  725. {
  726. setBattle(this);
  727. setNodeType(BATTLE);
  728. }
  729. CStack::CStack(const CStackInstance *Base, PlayerColor O, int I, bool AO, SlotID S)
  730. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  731. counterAttacks(1)
  732. {
  733. assert(base);
  734. type = base->type;
  735. count = baseAmount = base->count;
  736. setNodeType(STACK_BATTLE);
  737. }
  738. CStack::CStack()
  739. {
  740. init();
  741. setNodeType(STACK_BATTLE);
  742. }
  743. CStack::CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, bool AO, SlotID S)
  744. : base(nullptr), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  745. {
  746. type = stack->type;
  747. count = baseAmount = stack->count;
  748. setNodeType(STACK_BATTLE);
  749. }
  750. void CStack::init()
  751. {
  752. base = nullptr;
  753. type = nullptr;
  754. ID = -1;
  755. count = baseAmount = -1;
  756. firstHPleft = -1;
  757. owner = PlayerColor::NEUTRAL;
  758. slot = SlotID(255);
  759. attackerOwned = false;
  760. position = BattleHex();
  761. counterAttacks = -1;
  762. }
  763. void CStack::postInit()
  764. {
  765. assert(type);
  766. assert(getParentNodes().size());
  767. firstHPleft = MaxHealth();
  768. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  769. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  770. casts = valOfBonuses(Bonus::CASTS);
  771. }
  772. ui32 CStack::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  773. {
  774. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  775. return 0;
  776. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  777. int percentBonus = 0;
  778. BOOST_FOREACH(const Bonus *b, getBonusList())
  779. {
  780. if(b->type == Bonus::STACKS_SPEED)
  781. {
  782. percentBonus += b->additionalInfo;
  783. }
  784. }
  785. speed = ((100 + percentBonus) * speed)/100;
  786. //bind effect check - doesn't influence stack initiative
  787. if (useBind && getEffect (SpellID::BIND))
  788. {
  789. return 0;
  790. }
  791. return speed;
  792. }
  793. ui32 CStack::level() const
  794. {
  795. if (base)
  796. return base->getLevel(); //creatture or commander
  797. else
  798. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  799. }
  800. si32 CStack::magicResistance() const
  801. {
  802. si32 magicResistance;
  803. if (base) //TODO: make war machines receive aura of magic resistance
  804. {
  805. magicResistance = base->magicResistance();
  806. int auraBonus = 0;
  807. BOOST_FOREACH (const CStack * stack, base->armyObj->battle-> batteAdjacentCreatures(this))
  808. {
  809. if (stack->owner == owner)
  810. {
  811. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  812. }
  813. }
  814. magicResistance += auraBonus;
  815. vstd::amin (magicResistance, 100);
  816. }
  817. else
  818. magicResistance = type->magicResistance();
  819. return magicResistance;
  820. }
  821. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  822. {
  823. const CSpell * sp = SpellID(sse.sid).toSpell();
  824. std::vector<Bonus> tmp;
  825. sp->getEffects(tmp, sse.val);
  826. BOOST_FOREACH(Bonus& b, tmp)
  827. {
  828. b.turnsRemain = sse.turnsRemain;
  829. sf.push_back(b);
  830. }
  831. }
  832. bool CStack::willMove(int turn /*= 0*/) const
  833. {
  834. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  835. && !moved(turn)
  836. && canMove(turn);
  837. }
  838. bool CStack::canMove( int turn /*= 0*/ ) const
  839. {
  840. return alive()
  841. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  842. }
  843. bool CStack::moved( int turn /*= 0*/ ) const
  844. {
  845. if(!turn)
  846. return vstd::contains(state, EBattleStackState::MOVED);
  847. else
  848. return false;
  849. }
  850. bool CStack::waited(int turn /*= 0*/) const
  851. {
  852. if(!turn)
  853. return vstd::contains(state, EBattleStackState::WAITING);
  854. else
  855. return false;
  856. }
  857. bool CStack::doubleWide() const
  858. {
  859. return getCreature()->doubleWide;
  860. }
  861. BattleHex CStack::occupiedHex() const
  862. {
  863. return occupiedHex(position);
  864. }
  865. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  866. {
  867. if (doubleWide())
  868. {
  869. if (attackerOwned)
  870. return assumedPos - 1;
  871. else
  872. return assumedPos + 1;
  873. }
  874. else
  875. {
  876. return BattleHex::INVALID;
  877. }
  878. }
  879. std::vector<BattleHex> CStack::getHexes() const
  880. {
  881. return getHexes(position);
  882. }
  883. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  884. {
  885. return getHexes(assumedPos, doubleWide(), attackerOwned);
  886. }
  887. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  888. {
  889. std::vector<BattleHex> hexes;
  890. hexes.push_back(assumedPos);
  891. if (twoHex)
  892. {
  893. if (AttackerOwned)
  894. hexes.push_back(assumedPos - 1);
  895. else
  896. hexes.push_back(assumedPos + 1);
  897. }
  898. return hexes;
  899. }
  900. bool CStack::coversPos(BattleHex pos) const
  901. {
  902. return vstd::contains(getHexes(), pos);
  903. }
  904. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  905. {
  906. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  907. std::vector<BattleHex> hexes;
  908. if (doubleWide())
  909. {
  910. const int WN = GameConstants::BFIELD_WIDTH;
  911. if(attackerOwned)
  912. { //position is equal to front hex
  913. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  914. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  915. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  916. BattleHex::checkAndPush(hex - 2, hexes);
  917. BattleHex::checkAndPush(hex + 1, hexes);
  918. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  919. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  920. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  921. }
  922. else
  923. {
  924. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  925. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  926. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  927. BattleHex::checkAndPush(hex + 2, hexes);
  928. BattleHex::checkAndPush(hex - 1, hexes);
  929. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  930. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  931. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  932. }
  933. return hexes;
  934. }
  935. else
  936. {
  937. return hex.neighbouringTiles();
  938. }
  939. }
  940. std::vector<si32> CStack::activeSpells() const
  941. {
  942. std::vector<si32> ret;
  943. TBonusListPtr spellEffects = getSpellBonuses();
  944. BOOST_FOREACH(const Bonus *it, *spellEffects)
  945. {
  946. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  947. ret.push_back(it->sid);
  948. }
  949. return ret;
  950. }
  951. CStack::~CStack()
  952. {
  953. detachFromAll();
  954. }
  955. const CGHeroInstance * CStack::getMyHero() const
  956. {
  957. if(base)
  958. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  959. else //we are attached directly?
  960. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  961. if(n->getNodeType() == HERO)
  962. return dynamic_cast<const CGHeroInstance *>(n);
  963. return nullptr;
  964. }
  965. std::string CStack::nodeName() const
  966. {
  967. std::ostringstream oss;
  968. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  969. if(type)
  970. oss << type->namePl;
  971. else
  972. oss << "[UNDEFINED TYPE]";
  973. oss << " from slot " << slot;
  974. if(base && base->armyObj)
  975. oss << " of armyobj=" << base->armyObj->id.getNum();
  976. return oss.str();
  977. }
  978. std::pair<int,int> CStack::countKilledByAttack(int damageReceived) const
  979. {
  980. int killedCount = 0;
  981. int newRemainingHP = 0;
  982. killedCount = damageReceived / MaxHealth();
  983. unsigned damageFirst = damageReceived % MaxHealth();
  984. if (damageReceived && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  985. {
  986. killedCount = count;
  987. }
  988. else
  989. {
  990. if( firstHPleft <= damageFirst )
  991. {
  992. killedCount++;
  993. newRemainingHP = firstHPleft + MaxHealth() - damageFirst;
  994. }
  995. else
  996. {
  997. newRemainingHP = firstHPleft - damageFirst;
  998. }
  999. }
  1000. return std::make_pair(killedCount, newRemainingHP);
  1001. }
  1002. void CStack::prepareAttacked(BattleStackAttacked &bsa, boost::optional<int> customCount /*= boost::none*/) const
  1003. {
  1004. auto afterAttack = countKilledByAttack(bsa.damageAmount);
  1005. bsa.killedAmount = afterAttack.first;
  1006. bsa.newHP = afterAttack.second;
  1007. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  1008. {
  1009. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  1010. return; // no rebirth I believe
  1011. }
  1012. const int countToUse = customCount ? *customCount : count;
  1013. if(countToUse <= bsa.killedAmount) //stack killed
  1014. {
  1015. bsa.newAmount = 0;
  1016. bsa.flags |= BattleStackAttacked::KILLED;
  1017. bsa.killedAmount = countToUse; //we cannot kill more creatures than we have
  1018. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  1019. if (resurrectFactor > 0 && casts) //there must be casts left
  1020. {
  1021. int resurrectedCount = base->count * resurrectFactor / 100;
  1022. if (resurrectedCount)
  1023. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  1024. else //only one unit
  1025. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  1026. if (hasBonusOfType(Bonus::REBIRTH, 1))
  1027. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  1028. if (resurrectedCount)
  1029. {
  1030. bsa.flags |= BattleStackAttacked::REBIRTH;
  1031. bsa.newAmount = resurrectedCount; //risky?
  1032. bsa.newHP = MaxHealth(); //resore full health
  1033. }
  1034. }
  1035. }
  1036. else
  1037. {
  1038. bsa.newAmount = countToUse - bsa.killedAmount;
  1039. }
  1040. }
  1041. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  1042. {
  1043. if (!attackerPos.isValid())
  1044. {
  1045. attackerPos = attacker->position;
  1046. }
  1047. if (!defenderPos.isValid())
  1048. {
  1049. defenderPos = defender->position;
  1050. }
  1051. return
  1052. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1053. || (attacker->doubleWide() //back <=> front
  1054. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1055. || (defender->doubleWide() //front <=> back
  1056. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1057. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1058. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1059. }
  1060. bool CStack::ableToRetaliate() const
  1061. {
  1062. return alive()
  1063. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  1064. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  1065. && !hasBonusOfType(Bonus::HYPNOTIZED)
  1066. && !hasBonusOfType(Bonus::NO_RETALIATION);
  1067. }
  1068. std::string CStack::getName() const
  1069. {
  1070. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1071. }
  1072. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  1073. {
  1074. return (alive() || allowDead) && position.isValid();
  1075. }
  1076. bool CStack::canBeHealed() const
  1077. {
  1078. return firstHPleft < MaxHealth()
  1079. && isValidTarget()
  1080. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1081. }
  1082. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1083. {
  1084. switch(phase)
  1085. {
  1086. case 0: //catapult moves after turrets
  1087. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1088. case 1: //fastest first, upper slot first
  1089. {
  1090. int as = a->Speed(turn), bs = b->Speed(turn);
  1091. if(as != bs)
  1092. return as > bs;
  1093. else
  1094. return a->slot < b->slot;
  1095. }
  1096. case 2: //fastest last, upper slot first
  1097. //TODO: should be replaced with order of receiving morale!
  1098. case 3: //fastest last, upper slot first
  1099. {
  1100. int as = a->Speed(turn), bs = b->Speed(turn);
  1101. if(as != bs)
  1102. return as < bs;
  1103. else
  1104. return a->slot < b->slot;
  1105. }
  1106. default:
  1107. assert(0);
  1108. return false;
  1109. }
  1110. }
  1111. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1112. {
  1113. phase = Phase;
  1114. turn = Turn;
  1115. }