BattleState.cpp 37 KB

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