BattleState.cpp 36 KB

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