BattleState.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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(auto & elem : stacks)//setting casualties
  94. {
  95. const CStack * const st = elem;
  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 = 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 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(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. if(sp->id == SpellID::HYPNOTIZE) //hypnotize
  648. {
  649. for(auto & affectedCreature : affectedCreatures)
  650. {
  651. if( (affectedCreature)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  652. || ( (affectedCreature)->count - 1 ) * (affectedCreature)->MaxHealth() + (affectedCreature)->firstHPleft
  653. >
  654. calculateSpellBonus (usedSpellPower * 25 + sp->powers[spellLevel], sp, caster, affectedCreature) //apply 'damage' bonus for hypnotize, including hero specialty
  655. )
  656. {
  657. ret.push_back((affectedCreature)->ID);
  658. }
  659. }
  660. }
  661. return ret;
  662. }
  663. PlayerColor BattleInfo::theOtherPlayer(PlayerColor player) const
  664. {
  665. return sides[!whatSide(player)].color;
  666. }
  667. ui8 BattleInfo::whatSide(PlayerColor player) const
  668. {
  669. for(int i = 0; i < sides.size(); i++)
  670. if(sides[i].color == player)
  671. return i;
  672. logGlobal->warnStream() << "BattleInfo::whatSide: Player " << player << " is not in battle!";
  673. return -1;
  674. }
  675. int BattleInfo::getIdForNewStack() const
  676. {
  677. if(stacks.size())
  678. {
  679. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  680. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  681. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  682. return highestIDStack->ID + 1;
  683. }
  684. return 0;
  685. }
  686. shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  687. {
  688. for(auto &obs : obstacles)
  689. if(vstd::contains(obs->getAffectedTiles(), tile))
  690. return obs;
  691. return shared_ptr<CObstacleInstance>();
  692. }
  693. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  694. {
  695. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap = boost::assign::map_list_of
  696. (BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD)
  697. (BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND)
  698. (BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG)
  699. (BFieldType::FAVOURABLE_WINDS, BattlefieldBI::NONE)
  700. (BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS)
  701. (BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND)
  702. (BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS)
  703. (BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS)
  704. (BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS)
  705. (BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS)
  706. (BFieldType::SAND_SHORE, BattlefieldBI::COASTAL);
  707. auto itr = theMap.find(bfieldType);
  708. if(itr != theMap.end())
  709. return itr->second;
  710. return BattlefieldBI::NONE;
  711. }
  712. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  713. {
  714. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  715. }
  716. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive /*= true*/)
  717. {
  718. return const_cast<CStack *>(battleGetStackByPos(tileID, onlyAlive));
  719. }
  720. BattleInfo::BattleInfo()
  721. {
  722. setBattle(this);
  723. setNodeType(BATTLE);
  724. }
  725. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  726. {
  727. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  728. }
  729. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  730. {
  731. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  732. }
  733. CStack::CStack(const CStackInstance *Base, PlayerColor O, int I, bool AO, SlotID S)
  734. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  735. counterAttacks(1)
  736. {
  737. assert(base);
  738. type = base->type;
  739. count = baseAmount = base->count;
  740. setNodeType(STACK_BATTLE);
  741. }
  742. CStack::CStack()
  743. {
  744. init();
  745. setNodeType(STACK_BATTLE);
  746. }
  747. CStack::CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, bool AO, SlotID S)
  748. : base(nullptr), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  749. {
  750. type = stack->type;
  751. count = baseAmount = stack->count;
  752. setNodeType(STACK_BATTLE);
  753. }
  754. void CStack::init()
  755. {
  756. base = nullptr;
  757. type = nullptr;
  758. ID = -1;
  759. count = baseAmount = -1;
  760. firstHPleft = -1;
  761. owner = PlayerColor::NEUTRAL;
  762. slot = SlotID(255);
  763. attackerOwned = false;
  764. position = BattleHex();
  765. counterAttacks = -1;
  766. }
  767. void CStack::postInit()
  768. {
  769. assert(type);
  770. assert(getParentNodes().size());
  771. firstHPleft = MaxHealth();
  772. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  773. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  774. casts = valOfBonuses(Bonus::CASTS);
  775. }
  776. ui32 CStack::level() const
  777. {
  778. if (base)
  779. return base->getLevel(); //creatture or commander
  780. else
  781. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  782. }
  783. si32 CStack::magicResistance() const
  784. {
  785. si32 magicResistance;
  786. if (base) //TODO: make war machines receive aura of magic resistance
  787. {
  788. magicResistance = base->magicResistance();
  789. int auraBonus = 0;
  790. for (const CStack * stack : base->armyObj->battle-> batteAdjacentCreatures(this))
  791. {
  792. if (stack->owner == owner)
  793. {
  794. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  795. }
  796. }
  797. magicResistance += auraBonus;
  798. vstd::amin (magicResistance, 100);
  799. }
  800. else
  801. magicResistance = type->magicResistance();
  802. return magicResistance;
  803. }
  804. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  805. {
  806. const CSpell * sp = SpellID(sse.sid).toSpell();
  807. std::vector<Bonus> tmp;
  808. sp->getEffects(tmp, sse.val);
  809. for(Bonus& b : tmp)
  810. {
  811. b.turnsRemain = sse.turnsRemain;
  812. sf.push_back(b);
  813. }
  814. }
  815. bool CStack::willMove(int turn /*= 0*/) const
  816. {
  817. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  818. && !moved(turn)
  819. && canMove(turn);
  820. }
  821. bool CStack::canMove( int turn /*= 0*/ ) const
  822. {
  823. return alive()
  824. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  825. }
  826. bool CStack::moved( int turn /*= 0*/ ) const
  827. {
  828. if(!turn)
  829. return vstd::contains(state, EBattleStackState::MOVED);
  830. else
  831. return false;
  832. }
  833. bool CStack::waited(int turn /*= 0*/) const
  834. {
  835. if(!turn)
  836. return vstd::contains(state, EBattleStackState::WAITING);
  837. else
  838. return false;
  839. }
  840. bool CStack::doubleWide() const
  841. {
  842. return getCreature()->doubleWide;
  843. }
  844. BattleHex CStack::occupiedHex() const
  845. {
  846. return occupiedHex(position);
  847. }
  848. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  849. {
  850. if (doubleWide())
  851. {
  852. if (attackerOwned)
  853. return assumedPos - 1;
  854. else
  855. return assumedPos + 1;
  856. }
  857. else
  858. {
  859. return BattleHex::INVALID;
  860. }
  861. }
  862. std::vector<BattleHex> CStack::getHexes() const
  863. {
  864. return getHexes(position);
  865. }
  866. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  867. {
  868. return getHexes(assumedPos, doubleWide(), attackerOwned);
  869. }
  870. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  871. {
  872. std::vector<BattleHex> hexes;
  873. hexes.push_back(assumedPos);
  874. if (twoHex)
  875. {
  876. if (AttackerOwned)
  877. hexes.push_back(assumedPos - 1);
  878. else
  879. hexes.push_back(assumedPos + 1);
  880. }
  881. return hexes;
  882. }
  883. bool CStack::coversPos(BattleHex pos) const
  884. {
  885. return vstd::contains(getHexes(), pos);
  886. }
  887. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  888. {
  889. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  890. std::vector<BattleHex> hexes;
  891. if (doubleWide())
  892. {
  893. const int WN = GameConstants::BFIELD_WIDTH;
  894. if(attackerOwned)
  895. { //position is equal to front hex
  896. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  897. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  898. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  899. BattleHex::checkAndPush(hex - 2, hexes);
  900. BattleHex::checkAndPush(hex + 1, hexes);
  901. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  902. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  903. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  904. }
  905. else
  906. {
  907. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  908. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  909. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  910. BattleHex::checkAndPush(hex + 2, hexes);
  911. BattleHex::checkAndPush(hex - 1, hexes);
  912. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  913. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  914. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  915. }
  916. return hexes;
  917. }
  918. else
  919. {
  920. return hex.neighbouringTiles();
  921. }
  922. }
  923. std::vector<si32> CStack::activeSpells() const
  924. {
  925. std::vector<si32> ret;
  926. TBonusListPtr spellEffects = getSpellBonuses();
  927. for(const Bonus *it : *spellEffects)
  928. {
  929. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  930. ret.push_back(it->sid);
  931. }
  932. return ret;
  933. }
  934. CStack::~CStack()
  935. {
  936. detachFromAll();
  937. }
  938. const CGHeroInstance * CStack::getMyHero() const
  939. {
  940. if(base)
  941. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  942. else //we are attached directly?
  943. for(const CBonusSystemNode *n : getParentNodes())
  944. if(n->getNodeType() == HERO)
  945. return dynamic_cast<const CGHeroInstance *>(n);
  946. return nullptr;
  947. }
  948. std::string CStack::nodeName() const
  949. {
  950. std::ostringstream oss;
  951. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  952. if(type)
  953. oss << type->namePl;
  954. else
  955. oss << "[UNDEFINED TYPE]";
  956. oss << " from slot " << slot;
  957. if(base && base->armyObj)
  958. oss << " of armyobj=" << base->armyObj->id.getNum();
  959. return oss.str();
  960. }
  961. std::pair<int,int> CStack::countKilledByAttack(int damageReceived) const
  962. {
  963. int killedCount = 0;
  964. int newRemainingHP = 0;
  965. killedCount = damageReceived / MaxHealth();
  966. unsigned damageFirst = damageReceived % MaxHealth();
  967. if (damageReceived && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  968. {
  969. killedCount = count;
  970. }
  971. else
  972. {
  973. if( firstHPleft <= damageFirst )
  974. {
  975. killedCount++;
  976. newRemainingHP = firstHPleft + MaxHealth() - damageFirst;
  977. }
  978. else
  979. {
  980. newRemainingHP = firstHPleft - damageFirst;
  981. }
  982. }
  983. return std::make_pair(killedCount, newRemainingHP);
  984. }
  985. void CStack::prepareAttacked(BattleStackAttacked &bsa, boost::optional<int> customCount /*= boost::none*/) const
  986. {
  987. auto afterAttack = countKilledByAttack(bsa.damageAmount);
  988. bsa.killedAmount = afterAttack.first;
  989. bsa.newHP = afterAttack.second;
  990. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  991. {
  992. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  993. return; // no rebirth I believe
  994. }
  995. const int countToUse = customCount ? *customCount : count;
  996. if(countToUse <= bsa.killedAmount) //stack killed
  997. {
  998. bsa.newAmount = 0;
  999. bsa.flags |= BattleStackAttacked::KILLED;
  1000. bsa.killedAmount = countToUse; //we cannot kill more creatures than we have
  1001. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  1002. if (resurrectFactor > 0 && casts) //there must be casts left
  1003. {
  1004. int resurrectedCount = base->count * resurrectFactor / 100;
  1005. if (resurrectedCount)
  1006. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  1007. else //only one unit
  1008. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  1009. if (hasBonusOfType(Bonus::REBIRTH, 1))
  1010. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  1011. if (resurrectedCount)
  1012. {
  1013. bsa.flags |= BattleStackAttacked::REBIRTH;
  1014. bsa.newAmount = resurrectedCount; //risky?
  1015. bsa.newHP = MaxHealth(); //resore full health
  1016. }
  1017. }
  1018. }
  1019. else
  1020. {
  1021. bsa.newAmount = countToUse - bsa.killedAmount;
  1022. }
  1023. }
  1024. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  1025. {
  1026. if (!attackerPos.isValid())
  1027. {
  1028. attackerPos = attacker->position;
  1029. }
  1030. if (!defenderPos.isValid())
  1031. {
  1032. defenderPos = defender->position;
  1033. }
  1034. return
  1035. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1036. || (attacker->doubleWide() //back <=> front
  1037. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1038. || (defender->doubleWide() //front <=> back
  1039. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1040. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1041. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1042. }
  1043. bool CStack::ableToRetaliate() const
  1044. {
  1045. return alive()
  1046. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  1047. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  1048. && !hasBonusOfType(Bonus::HYPNOTIZED)
  1049. && !hasBonusOfType(Bonus::NO_RETALIATION);
  1050. }
  1051. std::string CStack::getName() const
  1052. {
  1053. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1054. }
  1055. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  1056. {
  1057. return (alive() || allowDead) && position.isValid();
  1058. }
  1059. bool CStack::canBeHealed() const
  1060. {
  1061. return firstHPleft < MaxHealth()
  1062. && isValidTarget()
  1063. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1064. }
  1065. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1066. {
  1067. switch(phase)
  1068. {
  1069. case 0: //catapult moves after turrets
  1070. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1071. case 1: //fastest first, upper slot first
  1072. {
  1073. int as = a->Speed(turn), bs = b->Speed(turn);
  1074. if(as != bs)
  1075. return as > bs;
  1076. else
  1077. return a->slot < b->slot;
  1078. }
  1079. case 2: //fastest last, upper slot first
  1080. //TODO: should be replaced with order of receiving morale!
  1081. case 3: //fastest last, upper slot first
  1082. {
  1083. int as = a->Speed(turn), bs = b->Speed(turn);
  1084. if(as != bs)
  1085. return as < bs;
  1086. else
  1087. return a->slot < b->slot;
  1088. }
  1089. default:
  1090. assert(0);
  1091. return false;
  1092. }
  1093. }
  1094. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1095. {
  1096. phase = Phase;
  1097. turn = Turn;
  1098. }
  1099. SideInBattle::SideInBattle()
  1100. {
  1101. hero = nullptr;
  1102. armyObject = nullptr;
  1103. castSpellsCount = 0;
  1104. enchanterCounter = 0;
  1105. }
  1106. void SideInBattle::init(const CGHeroInstance *Hero, const CArmedInstance *Army)
  1107. {
  1108. hero = Hero;
  1109. armyObject = Army;
  1110. color = armyObject->getOwner();
  1111. if(color == PlayerColor::UNFLAGGABLE)
  1112. color = PlayerColor::NEUTRAL;
  1113. }