BattleState.cpp 41 KB

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