BattleState.cpp 37 KB

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