BattleState.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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 addFull = [&](Bonus::BonusType type, si16 subtype, si32 value, si32 additionalInfo, si32 limit)
  811. {
  812. sf.push_back(featureGenerator(type, subtype, value, sse.turnsRemain,additionalInfo, limit));
  813. sf.back().sid = sse.sid;
  814. };
  815. auto add = [&](Bonus::BonusType type, si16 subtype, si32 value)
  816. {
  817. addFull(type, subtype, value, 0, Bonus::NO_LIMIT);
  818. };
  819. auto addVT = [&](Bonus::BonusType type, si16 subtype, si32 value, ui8 valType)
  820. {
  821. add(type, subtype, value);
  822. sf.back().valType = valType;
  823. };
  824. auto addVTFull = [&](Bonus::BonusType type, si16 subtype, si32 value, ui8 valType,si32 additionalInfo)
  825. {
  826. addFull(type, subtype, value, additionalInfo, Bonus::NO_LIMIT);
  827. sf.back().valType = valType;
  828. };
  829. auto addDur = [&](Bonus::BonusType type, si16 subtype, si32 value, ui8 duration)
  830. {
  831. add(type, subtype, value);
  832. sf.back().duration = duration;
  833. };
  834. switch(sse.sid)
  835. {
  836. case Spells::SHIELD:
  837. add(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power);
  838. break;
  839. case Spells::AIR_SHIELD:
  840. add(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power);
  841. break;
  842. case Spells::FIRE_SHIELD:
  843. add(Bonus::FIRE_SHIELD, 0, power);
  844. break;
  845. case Spells::PROTECTION_FROM_AIR:
  846. add(Bonus::SPELL_DAMAGE_REDUCTION, 0, power);
  847. break;
  848. case Spells::PROTECTION_FROM_FIRE:
  849. add(Bonus::SPELL_DAMAGE_REDUCTION, 1, power);
  850. break;
  851. case Spells::PROTECTION_FROM_WATER:
  852. add(Bonus::SPELL_DAMAGE_REDUCTION, 2, power);
  853. break;
  854. case Spells::PROTECTION_FROM_EARTH:
  855. add(Bonus::SPELL_DAMAGE_REDUCTION, 3, power);
  856. break;
  857. case Spells::ANTI_MAGIC:
  858. addVT(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, Bonus::INDEPENDENT_MAX);break;
  859. case Spells::MAGIC_MIRROR:
  860. addVT(Bonus::MAGIC_MIRROR, -1, power, Bonus::INDEPENDENT_MAX);
  861. break;
  862. case Spells::BLESS:
  863. addVT(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power,Bonus::INDEPENDENT_MAX);
  864. break;
  865. case Spells::CURSE:
  866. addVTFull(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, Bonus::INDEPENDENT_MAX, sse.val >= 2 ? 20 : 0);
  867. break;
  868. case Spells::BLOODLUST:
  869. addFull(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, 0, Bonus::ONLY_MELEE_FIGHT);
  870. break;
  871. case Spells::PRECISION:
  872. addFull(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, 0, Bonus::ONLY_DISTANCE_FIGHT);
  873. break;
  874. case Spells::WEAKNESS:
  875. add(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power);
  876. break;
  877. case Spells::STONE_SKIN:
  878. add(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power);
  879. break;
  880. case Spells::DISRUPTING_RAY:
  881. addVT(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power,Bonus::ADDITIVE_VALUE);
  882. break;
  883. case Spells::PRAYER:
  884. add(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power);
  885. add(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power);
  886. add(Bonus::STACKS_SPEED, 0, power);
  887. break;
  888. case Spells::MIRTH:
  889. add(Bonus::MORALE, 0, power);
  890. break;
  891. case Spells::SORROW:
  892. add(Bonus::MORALE, 0, -1 * power);
  893. break;
  894. case Spells::FORTUNE:
  895. add(Bonus::LUCK, 0, power);
  896. break;
  897. case Spells::MISFORTUNE:
  898. add(Bonus::LUCK, 0, -1 * power);
  899. break;
  900. case Spells::HASTE: //haste
  901. add(Bonus::STACKS_SPEED, 0, power);
  902. break;
  903. case Spells::SLOW:
  904. addVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ),Bonus::PERCENT_TO_ALL);
  905. break;
  906. case Spells::SLAYER:
  907. add(Bonus::SLAYER, 0, sse.val);
  908. break;
  909. case Spells::FRENZY:
  910. add(Bonus::IN_FRENZY, 0, power/100.0);
  911. break;
  912. case Spells::COUNTERSTRIKE:
  913. add(Bonus::ADDITIONAL_RETALIATION, 0, power);
  914. break;
  915. case Spells::BERSERK:
  916. add(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val);
  917. break;
  918. case Spells::HYPNOTIZE:
  919. add(Bonus::HYPNOTIZED, 0, sse.val);
  920. break;
  921. case Spells::FORGETFULNESS:
  922. add(Bonus::FORGETFULL, 0, sse.val);
  923. break;
  924. case Spells::BLIND:
  925. addDur(Bonus::NOT_ACTIVE, sse.sid, 0, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS);
  926. addDur(Bonus::GENERAL_ATTACK_REDUCTION, 0, power, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS);
  927. addDur(Bonus::NO_RETALIATION,0,0, Bonus::UNITL_BEING_ATTACKED);
  928. break;
  929. case Spells::STONE_GAZE:
  930. case Spells::PARALYZE:
  931. addDur(Bonus::NOT_ACTIVE, sse.sid, 0, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS);
  932. addDur(Bonus::NO_RETALIATION,0,0, Bonus::UNITL_BEING_ATTACKED);
  933. break;
  934. case Spells::POISON: //Poison
  935. addVT(Bonus::POISON, 0, 30,Bonus::INDEPENDENT_MAX); //max hp penalty from this source
  936. addVT(Bonus::STACK_HEALTH, 0, -10, Bonus::PERCENT_TO_ALL);
  937. break;
  938. case Spells::BIND:
  939. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  940. sf.back().duration = Bonus::PERMANENT;
  941. sf.back().sid = sse.sid;
  942. break;
  943. case Spells::DISEASE:
  944. add(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2);
  945. add(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2);
  946. break;
  947. case Spells::AGE:
  948. addVT(Bonus::STACK_HEALTH, 0, -50, Bonus::PERCENT_TO_ALL);
  949. break;
  950. case Spells::ACID_BREATH_DEFENSE:
  951. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  952. sf.back().sid = sse.sid;
  953. sf.back().duration = Bonus::PERMANENT;
  954. sf.back().valType = Bonus::ADDITIVE_VALUE;
  955. break;
  956. }
  957. }
  958. bool CStack::willMove(int turn /*= 0*/) const
  959. {
  960. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  961. && !moved(turn)
  962. && canMove(turn);
  963. }
  964. bool CStack::canMove( int turn /*= 0*/ ) const
  965. {
  966. return alive()
  967. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  968. }
  969. bool CStack::moved( int turn /*= 0*/ ) const
  970. {
  971. if(!turn)
  972. return vstd::contains(state, EBattleStackState::MOVED);
  973. else
  974. return false;
  975. }
  976. bool CStack::waited(int turn /*= 0*/) const
  977. {
  978. if(!turn)
  979. return vstd::contains(state, EBattleStackState::WAITING);
  980. else
  981. return false;
  982. }
  983. bool CStack::doubleWide() const
  984. {
  985. return getCreature()->doubleWide;
  986. }
  987. BattleHex CStack::occupiedHex() const
  988. {
  989. return occupiedHex(position);
  990. }
  991. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  992. {
  993. if (doubleWide())
  994. {
  995. if (attackerOwned)
  996. return assumedPos - 1;
  997. else
  998. return assumedPos + 1;
  999. }
  1000. else
  1001. {
  1002. return BattleHex::INVALID;
  1003. }
  1004. }
  1005. std::vector<BattleHex> CStack::getHexes() const
  1006. {
  1007. return getHexes(position);
  1008. }
  1009. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  1010. {
  1011. return getHexes(assumedPos, doubleWide(), attackerOwned);
  1012. }
  1013. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  1014. {
  1015. std::vector<BattleHex> hexes;
  1016. hexes.push_back(assumedPos);
  1017. if (twoHex)
  1018. {
  1019. if (AttackerOwned)
  1020. hexes.push_back(assumedPos - 1);
  1021. else
  1022. hexes.push_back(assumedPos + 1);
  1023. }
  1024. return hexes;
  1025. }
  1026. bool CStack::coversPos(BattleHex pos) const
  1027. {
  1028. return vstd::contains(getHexes(), pos);
  1029. }
  1030. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  1031. {
  1032. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  1033. std::vector<BattleHex> hexes;
  1034. if (doubleWide())
  1035. {
  1036. const int WN = GameConstants::BFIELD_WIDTH;
  1037. if(attackerOwned)
  1038. { //position is equal to front hex
  1039. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  1040. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1041. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1042. BattleHex::checkAndPush(hex - 2, hexes);
  1043. BattleHex::checkAndPush(hex + 1, hexes);
  1044. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  1045. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1046. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1047. }
  1048. else
  1049. {
  1050. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  1051. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  1052. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  1053. BattleHex::checkAndPush(hex + 2, hexes);
  1054. BattleHex::checkAndPush(hex - 1, hexes);
  1055. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  1056. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  1057. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  1058. }
  1059. return hexes;
  1060. }
  1061. else
  1062. {
  1063. return hex.neighbouringTiles();
  1064. }
  1065. }
  1066. std::vector<si32> CStack::activeSpells() const
  1067. {
  1068. std::vector<si32> ret;
  1069. TBonusListPtr spellEffects = getSpellBonuses();
  1070. BOOST_FOREACH(const Bonus *it, *spellEffects)
  1071. {
  1072. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  1073. ret.push_back(it->sid);
  1074. }
  1075. return ret;
  1076. }
  1077. CStack::~CStack()
  1078. {
  1079. detachFromAll();
  1080. }
  1081. const CGHeroInstance * CStack::getMyHero() const
  1082. {
  1083. if(base)
  1084. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1085. else //we are attached directly?
  1086. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  1087. if(n->getNodeType() == HERO)
  1088. return dynamic_cast<const CGHeroInstance *>(n);
  1089. return NULL;
  1090. }
  1091. std::string CStack::nodeName() const
  1092. {
  1093. std::ostringstream oss;
  1094. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1095. if(type)
  1096. oss << type->namePl;
  1097. else
  1098. oss << "[UNDEFINED TYPE]";
  1099. oss << " from slot " << (int)slot;
  1100. if(base && base->armyObj)
  1101. oss << " of armyobj=" << base->armyObj->id;
  1102. return oss.str();
  1103. }
  1104. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  1105. {
  1106. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  1107. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  1108. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  1109. {
  1110. bsa.killedAmount = count;
  1111. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  1112. return; // no rebirth I believe
  1113. }
  1114. if( firstHPleft <= damageFirst )
  1115. {
  1116. bsa.killedAmount++;
  1117. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  1118. }
  1119. else
  1120. {
  1121. bsa.newHP = firstHPleft - damageFirst;
  1122. }
  1123. if(count <= bsa.killedAmount) //stack killed
  1124. {
  1125. bsa.newAmount = 0;
  1126. bsa.flags |= BattleStackAttacked::KILLED;
  1127. bsa.killedAmount = count; //we cannot kill more creatures than we have
  1128. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  1129. if (resurrectFactor > 0 && casts) //there must be casts left
  1130. {
  1131. int resurrectedCount = base->count * resurrectFactor / 100;
  1132. if (resurrectedCount)
  1133. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  1134. else //only one unit
  1135. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  1136. if (hasBonusOfType(Bonus::REBIRTH, 1))
  1137. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  1138. if (resurrectedCount)
  1139. {
  1140. bsa.flags |= BattleStackAttacked::REBIRTH;
  1141. bsa.newAmount = resurrectedCount; //risky?
  1142. bsa.newHP = MaxHealth(); //resore full health
  1143. }
  1144. }
  1145. }
  1146. else
  1147. {
  1148. bsa.newAmount = count - bsa.killedAmount;
  1149. }
  1150. }
  1151. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  1152. {
  1153. if (!attackerPos.isValid())
  1154. {
  1155. attackerPos = attacker->position;
  1156. }
  1157. if (!defenderPos.isValid())
  1158. {
  1159. defenderPos = defender->position;
  1160. }
  1161. return
  1162. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  1163. || (attacker->doubleWide() //back <=> front
  1164. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  1165. || (defender->doubleWide() //front <=> back
  1166. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  1167. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  1168. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  1169. }
  1170. bool CStack::ableToRetaliate() const
  1171. {
  1172. return alive()
  1173. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  1174. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  1175. && !hasBonusOfType(Bonus::HYPNOTIZED)
  1176. && !hasBonusOfType(Bonus::NO_RETALIATION);
  1177. }
  1178. std::string CStack::getName() const
  1179. {
  1180. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1181. }
  1182. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  1183. {
  1184. return (alive() || allowDead) && position.isValid();
  1185. }
  1186. bool CStack::canBeHealed() const
  1187. {
  1188. return firstHPleft < MaxHealth()
  1189. && isValidTarget()
  1190. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1191. }
  1192. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1193. {
  1194. switch(phase)
  1195. {
  1196. case 0: //catapult moves after turrets
  1197. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1198. case 1: //fastest first, upper slot first
  1199. {
  1200. int as = a->Speed(turn), bs = b->Speed(turn);
  1201. if(as != bs)
  1202. return as > bs;
  1203. else
  1204. return a->slot < b->slot;
  1205. }
  1206. case 2: //fastest last, upper slot first
  1207. //TODO: should be replaced with order of receiving morale!
  1208. case 3: //fastest last, upper slot first
  1209. {
  1210. int as = a->Speed(turn), bs = b->Speed(turn);
  1211. if(as != bs)
  1212. return as < bs;
  1213. else
  1214. return a->slot < b->slot;
  1215. }
  1216. default:
  1217. assert(0);
  1218. return false;
  1219. }
  1220. }
  1221. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1222. {
  1223. phase = Phase;
  1224. turn = Turn;
  1225. }