BattleState.cpp 37 KB

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