BattleState.cpp 36 KB

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