BattleInfo.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. /*
  2. * BattleInfo.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 "BattleInfo.h"
  12. #include "CStack.h"
  13. #include "CHeroHandler.h"
  14. #include "NetPacks.h"
  15. #include "filesystem/Filesystem.h"
  16. #include "mapObjects/CGTownInstance.h"
  17. const CStack * BattleInfo::getNextStack() const
  18. {
  19. std::vector<const CStack *> hlp;
  20. battleGetStackQueue(hlp, 1, -1);
  21. if(hlp.size())
  22. return hlp[0];
  23. else
  24. return nullptr;
  25. }
  26. int BattleInfo::getAvaliableHex(CreatureID creID, bool attackerOwned, int initialPos) const
  27. {
  28. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  29. //bool flying = VLC->creh->creatures[creID]->isFlying();
  30. int pos;
  31. if (initialPos > -1)
  32. pos = initialPos;
  33. else //summon elementals depending on player side
  34. {
  35. if (attackerOwned)
  36. pos = 0; //top left
  37. else
  38. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  39. }
  40. auto accessibility = getAccesibility();
  41. std::set<BattleHex> occupyable;
  42. for(int i = 0; i < accessibility.size(); i++)
  43. if(accessibility.accessible(i, twoHex, attackerOwned))
  44. occupyable.insert(i);
  45. if (occupyable.empty())
  46. {
  47. return BattleHex::INVALID; //all tiles are covered
  48. }
  49. return BattleHex::getClosestTile(attackerOwned, pos, occupyable);
  50. }
  51. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack *stack)
  52. {
  53. auto reachability = getReachability(stack);
  54. if(reachability.predecessors[dest] == -1) //cannot reach destination
  55. {
  56. return std::make_pair(std::vector<BattleHex>(), 0);
  57. }
  58. //making the Path
  59. std::vector<BattleHex> path;
  60. BattleHex curElem = dest;
  61. while(curElem != start)
  62. {
  63. path.push_back(curElem);
  64. curElem = reachability.predecessors[curElem];
  65. }
  66. return std::make_pair(path, reachability.distances[dest]);
  67. }
  68. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender,
  69. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg, CRandomGenerator & rand )
  70. {
  71. TDmgRange range = calculateDmgRange(attacker, defender, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  72. if(range.first != range.second)
  73. {
  74. ui32 sum = 0;
  75. ui32 howManyToAv = std::min<ui32>(10, attacker->count);
  76. for(int g=0; g<howManyToAv; ++g)
  77. sum += (ui32)rand.nextInt(range.first, range.second);
  78. return sum / howManyToAv;
  79. }
  80. else
  81. return range.first;
  82. }
  83. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  84. {
  85. for(auto & elem : stacks)//setting casualties
  86. {
  87. const CStack * const st = elem;
  88. si32 killed = (st->alive() ? (st->baseAmount - st->count + st->resurrected) : st->baseAmount);
  89. vstd::amax(killed, 0);
  90. if(killed)
  91. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  92. }
  93. }
  94. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, SlotID slot, BattleHex position) const
  95. {
  96. int stackID = getIdForNewStack();
  97. PlayerColor owner = sides[attackerOwned ? 0 : 1].color;
  98. assert((owner >= PlayerColor::PLAYER_LIMIT) ||
  99. (base.armyObj && base.armyObj->tempOwner == owner));
  100. auto ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  101. ret->position = getAvaliableHex (base.getCreatureID(), attackerOwned, position); //TODO: what if no free tile on battlefield was found?
  102. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  103. return ret;
  104. }
  105. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, SlotID slot, BattleHex position) const
  106. {
  107. int stackID = getIdForNewStack();
  108. PlayerColor owner = sides[attackerOwned ? 0 : 1].color;
  109. auto ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  110. ret->position = position;
  111. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  112. return ret;
  113. }
  114. void BattleInfo::localInit()
  115. {
  116. for(int i = 0; i < 2; i++)
  117. {
  118. auto armyObj = battleGetArmyObject(i);
  119. armyObj->battle = this;
  120. armyObj->attachTo(this);
  121. }
  122. for(CStack *s : stacks)
  123. localInitStack(s);
  124. exportBonuses();
  125. }
  126. void BattleInfo::localInitStack(CStack * s)
  127. {
  128. s->exportBonuses();
  129. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  130. {
  131. s->attachTo(const_cast<CStackInstance*>(s->base));
  132. }
  133. else //attach directly to obj to which stack belongs and creature type
  134. {
  135. CArmedInstance *army = battleGetArmyObject(!s->attackerOwned);
  136. s->attachTo(army);
  137. assert(s->type);
  138. s->attachTo(const_cast<CCreature*>(s->type));
  139. }
  140. s->postInit();
  141. }
  142. namespace CGH
  143. {
  144. static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
  145. {
  146. for(const JsonNode &level : node.Vector())
  147. {
  148. std::vector<int> pom;
  149. for(const JsonNode &value : level.Vector())
  150. {
  151. pom.push_back(value.Float());
  152. }
  153. dest.push_back(pom);
  154. }
  155. }
  156. }
  157. //RNG that works like H3 one
  158. struct RandGen
  159. {
  160. int seed;
  161. void srand(int s)
  162. {
  163. seed = s;
  164. }
  165. void srand(int3 pos)
  166. {
  167. srand(110291 * pos.x + 167801 * pos.y + 81569);
  168. }
  169. int rand()
  170. {
  171. seed = 214013 * seed + 2531011;
  172. return (seed >> 16) & 0x7FFF;
  173. }
  174. int rand(int min, int max)
  175. {
  176. if(min == max)
  177. return min;
  178. if(min > max)
  179. return min;
  180. return min + rand() % (max - min + 1);
  181. }
  182. };
  183. struct RangeGenerator
  184. {
  185. class ExhaustedPossibilities : public std::exception
  186. {
  187. };
  188. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  189. min(_min),
  190. remainingCount(_max - _min + 1),
  191. remaining(remainingCount, true),
  192. myRand(_myRand)
  193. {
  194. }
  195. int generateNumber()
  196. {
  197. if(!remainingCount)
  198. throw ExhaustedPossibilities();
  199. if(remainingCount == 1)
  200. return 0;
  201. return myRand() % remainingCount;
  202. }
  203. //get number fulfilling predicate. Never gives the same number twice.
  204. int getSuchNumber(std::function<bool(int)> goodNumberPred = nullptr)
  205. {
  206. int ret = -1;
  207. do
  208. {
  209. int n = generateNumber();
  210. int i = 0;
  211. for(;;i++)
  212. {
  213. assert(i < (int)remaining.size());
  214. if(!remaining[i])
  215. continue;
  216. if(!n)
  217. break;
  218. n--;
  219. }
  220. remainingCount--;
  221. remaining[i] = false;
  222. ret = i + min;
  223. } while(goodNumberPred && !goodNumberPred(ret));
  224. return ret;
  225. }
  226. int min, remainingCount;
  227. std::vector<bool> remaining;
  228. std::function<int()> myRand;
  229. };
  230. BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  231. {
  232. CMP_stack cmpst;
  233. auto curB = new BattleInfo();
  234. for(auto i = 0u; i < curB->sides.size(); i++)
  235. curB->sides[i].init(heroes[i], armies[i]);
  236. std::vector<CStack*> & stacks = (curB->stacks);
  237. curB->tile = tile;
  238. curB->battlefieldType = battlefieldType;
  239. curB->round = -2;
  240. curB->activeStack = -1;
  241. if(town)
  242. {
  243. curB->town = town;
  244. curB->terrainType = VLC->townh->factions[town->subID]->nativeTerrain;
  245. }
  246. else
  247. {
  248. curB->town = nullptr;
  249. curB->terrainType = terrain;
  250. }
  251. //setting up siege obstacles
  252. if (town && town->hasFort())
  253. {
  254. curB->si.gateState = EGateState::CLOSED;
  255. for (int b = 0; b < curB->si.wallState.size(); ++b)
  256. {
  257. curB->si.wallState[b] = EWallState::INTACT;
  258. }
  259. if (!town->hasBuilt(BuildingID::CITADEL))
  260. {
  261. curB->si.wallState[EWallPart::KEEP] = EWallState::NONE;
  262. }
  263. if (!town->hasBuilt(BuildingID::CASTLE))
  264. {
  265. curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::NONE;
  266. curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::NONE;
  267. }
  268. }
  269. //randomize obstacles
  270. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  271. {
  272. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  273. RandGen r;
  274. auto ourRand = [&]{ return r.rand(); };
  275. r.srand(tile);
  276. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  277. int tilesToBlock = r.rand(5,12);
  278. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  279. std::vector<BattleHex> blockedTiles;
  280. auto appropriateAbsoluteObstacle = [&](int id)
  281. {
  282. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  283. };
  284. auto appropriateUsualObstacle = [&](int id) -> bool
  285. {
  286. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  287. };
  288. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  289. {
  290. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  291. try
  292. {
  293. auto obstPtr = std::make_shared<CObstacleInstance>();
  294. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  295. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  296. obstPtr->uniqueID = curB->obstacles.size();
  297. curB->obstacles.push_back(obstPtr);
  298. for(BattleHex blocked : obstPtr->getBlockedTiles())
  299. blockedTiles.push_back(blocked);
  300. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  301. }
  302. catch(RangeGenerator::ExhaustedPossibilities &)
  303. {
  304. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  305. }
  306. }
  307. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  308. try
  309. {
  310. while(tilesToBlock > 0)
  311. {
  312. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  313. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  314. auto validPosition = [&](BattleHex pos) -> bool
  315. {
  316. if(obi.height >= pos.getY())
  317. return false;
  318. if(pos.getX() == 0)
  319. return false;
  320. if(pos.getX() + obi.width > 15)
  321. return false;
  322. if(vstd::contains(blockedTiles, pos))
  323. return false;
  324. for(BattleHex blocked : obi.getBlocked(pos))
  325. {
  326. if(vstd::contains(blockedTiles, blocked))
  327. return false;
  328. int x = blocked.getX();
  329. if(x <= 2 || x >= 14)
  330. return false;
  331. }
  332. return true;
  333. };
  334. RangeGenerator posgenerator(18, 168, ourRand);
  335. auto obstPtr = std::make_shared<CObstacleInstance>();
  336. obstPtr->ID = obid;
  337. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  338. obstPtr->uniqueID = curB->obstacles.size();
  339. curB->obstacles.push_back(obstPtr);
  340. for(BattleHex blocked : obstPtr->getBlockedTiles())
  341. blockedTiles.push_back(blocked);
  342. tilesToBlock -= obi.blockedTiles.size();
  343. }
  344. }
  345. catch(RangeGenerator::ExhaustedPossibilities &)
  346. {
  347. }
  348. }
  349. //reading battleStartpos - add creatures AFTER random obstacles are generated
  350. //TODO: parse once to some structure
  351. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  352. std::vector <int> commanderField, commanderBank;
  353. const JsonNode config(ResourceID("config/battleStartpos.json"));
  354. const JsonVector &positions = config["battle_positions"].Vector();
  355. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  356. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  357. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  358. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  359. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  360. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  361. for (auto position : config["commanderPositions"]["field"].Vector())
  362. {
  363. commanderField.push_back (position.Float());
  364. }
  365. for (auto position : config["commanderPositions"]["creBank"].Vector())
  366. {
  367. commanderBank.push_back (position.Float());
  368. }
  369. //adding war machines
  370. if(!creatureBank)
  371. {
  372. //Checks if hero has artifact and create appropriate stack
  373. auto handleWarMachine= [&](int side, ArtifactPosition artslot, BattleHex hex)
  374. {
  375. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  376. if(nullptr != warMachineArt)
  377. {
  378. CreatureID cre = warMachineArt->artType->warMachine;
  379. if(cre != CreatureID::NONE)
  380. stacks.push_back(curB->generateNewStack(CStackBasicDescriptor(cre, 1), !side, SlotID::WAR_MACHINES_SLOT, hex));
  381. }
  382. };
  383. if(heroes[0])
  384. {
  385. handleWarMachine(0, ArtifactPosition::MACH1, 52);
  386. handleWarMachine(0, ArtifactPosition::MACH2, 18);
  387. handleWarMachine(0, ArtifactPosition::MACH3, 154);
  388. if(town && town->hasFort())
  389. handleWarMachine(0, ArtifactPosition::MACH4, 120);
  390. }
  391. if(heroes[1])
  392. {
  393. if(!town) //defending hero shouldn't receive ballista (bug #551)
  394. handleWarMachine(1, ArtifactPosition::MACH1, 66);
  395. handleWarMachine(1, ArtifactPosition::MACH2, 32);
  396. handleWarMachine(1, ArtifactPosition::MACH3, 168);
  397. }
  398. }
  399. //war machines added
  400. //battleStartpos read
  401. for(int side = 0; side < 2; side++)
  402. {
  403. int formationNo = armies[side]->stacksCount() - 1;
  404. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  405. int k = 0; //stack serial
  406. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  407. {
  408. std::vector<int> *formationVector = nullptr;
  409. if(creatureBank)
  410. formationVector = &creBankFormations[side][formationNo];
  411. else if(armies[side]->formation)
  412. formationVector = &tightFormations[side][formationNo];
  413. else
  414. formationVector = &looseFormations[side][formationNo];
  415. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  416. if(creatureBank && i->second->type->isDoubleWide())
  417. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  418. CStack * stack = curB->generateNewStack(*i->second, !side, i->first, pos);
  419. stacks.push_back(stack);
  420. }
  421. }
  422. //adding commanders
  423. for (int i = 0; i < 2; ++i)
  424. {
  425. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  426. {
  427. CStack * stack = curB->generateNewStack (*heroes[i]->commander, !i, SlotID::COMMANDER_SLOT_PLACEHOLDER,
  428. creatureBank ? commanderBank[i] : commanderField[i]);
  429. stacks.push_back(stack);
  430. }
  431. }
  432. if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
  433. {
  434. // keep tower
  435. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID::ARROW_TOWERS_SLOT, -2);
  436. stacks.push_back(stack);
  437. if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
  438. {
  439. // lower tower + upper tower
  440. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID::ARROW_TOWERS_SLOT, -4);
  441. stacks.push_back(stack);
  442. stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID::ARROW_TOWERS_SLOT, -3);
  443. stacks.push_back(stack);
  444. }
  445. //moat
  446. auto moat = std::make_shared<MoatObstacle>();
  447. moat->ID = curB->town->subID;
  448. moat->obstacleType = CObstacleInstance::MOAT;
  449. moat->uniqueID = curB->obstacles.size();
  450. curB->obstacles.push_back(moat);
  451. }
  452. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  453. //spell level limiting bonus
  454. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  455. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  456. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  457. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  458. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  459. //giving terrain overlay premies
  460. int bonusSubtype = -1;
  461. switch(battlefieldType)
  462. {
  463. case BFieldType::MAGIC_PLAINS:
  464. {
  465. bonusSubtype = 0;
  466. }
  467. case BFieldType::FIERY_FIELDS:
  468. {
  469. if(bonusSubtype == -1) bonusSubtype = 1;
  470. }
  471. case BFieldType::ROCKLANDS:
  472. {
  473. if(bonusSubtype == -1) bonusSubtype = 8;
  474. }
  475. case BFieldType::MAGIC_CLOUDS:
  476. {
  477. if(bonusSubtype == -1) bonusSubtype = 2;
  478. }
  479. case BFieldType::LUCID_POOLS:
  480. {
  481. if(bonusSubtype == -1) bonusSubtype = 4;
  482. }
  483. { //common part for cases 9, 14, 15, 16, 17
  484. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, battlefieldType, bonusSubtype));
  485. break;
  486. }
  487. case BFieldType::HOLY_GROUND:
  488. {
  489. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, 0)->addLimiter(good));
  490. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, 0)->addLimiter(evil));
  491. break;
  492. }
  493. case BFieldType::CLOVER_FIELD:
  494. { //+2 luck bonus for neutral creatures
  495. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::LUCK, Bonus::TERRAIN_OVERLAY, +2, battlefieldType, 0)->addLimiter(neutral));
  496. break;
  497. }
  498. case BFieldType::EVIL_FOG:
  499. {
  500. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, 0)->addLimiter(good));
  501. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, 0)->addLimiter(evil));
  502. break;
  503. }
  504. case BFieldType::CURSED_GROUND:
  505. {
  506. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_MORALE, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, 0));
  507. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_LUCK, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, 0));
  508. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::BLOCK_MAGIC_ABOVE, Bonus::TERRAIN_OVERLAY, 1, battlefieldType, 0, Bonus::INDEPENDENT_MIN));
  509. break;
  510. }
  511. }
  512. //overlay premies given
  513. //native terrain bonuses
  514. auto nativeTerrain = std::make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  515. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::STACKS_SPEED, Bonus::TERRAIN_NATIVE, 1, 0, 0)->addLimiter(nativeTerrain));
  516. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::ATTACK)->addLimiter(nativeTerrain));
  517. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::DEFENSE)->addLimiter(nativeTerrain));
  518. //////////////////////////////////////////////////////////////////////////
  519. //tactics
  520. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  521. int tacticLvls[2] = {0};
  522. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  523. {
  524. if(heroes[i])
  525. tacticLvls[i] += heroes[i]->getSecSkillLevel(SecondarySkill::TACTICS);
  526. }
  527. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  528. if(tacticsSkillDiff && isTacticsAllowed)
  529. {
  530. curB->tacticsSide = tacticsSkillDiff < 0;
  531. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  532. }
  533. else
  534. curB->tacticDistance = 0;
  535. // workaround — bonuses affecting only enemy - DOES NOT WORK
  536. for(int i = 0; i < 2; i++)
  537. {
  538. TNodes nodes;
  539. curB->battleGetArmyObject(i)->getRedAncestors(nodes);
  540. for(CBonusSystemNode *n : nodes)
  541. {
  542. for(auto b : n->getExportedBonusList())
  543. {
  544. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  545. {
  546. auto bCopy = std::make_shared<Bonus>(*b);
  547. bCopy->effectRange = Bonus::NO_LIMIT;
  548. bCopy->propagator.reset();
  549. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i].color));
  550. curB->addNewBonus(bCopy);
  551. }
  552. }
  553. }
  554. }
  555. return curB;
  556. }
  557. const CGHeroInstance * BattleInfo::getHero( PlayerColor player ) const
  558. {
  559. for(int i = 0; i < sides.size(); i++)
  560. if(sides[i].color == player)
  561. return sides[i].hero;
  562. logGlobal->errorStream() << "Player " << player << " is not in battle!";
  563. return nullptr;
  564. }
  565. PlayerColor BattleInfo::theOtherPlayer(PlayerColor player) const
  566. {
  567. return sides[!whatSide(player)].color;
  568. }
  569. ui8 BattleInfo::whatSide(PlayerColor player) const
  570. {
  571. for(int i = 0; i < sides.size(); i++)
  572. if(sides[i].color == player)
  573. return i;
  574. logGlobal->warnStream() << "BattleInfo::whatSide: Player " << player << " is not in battle!";
  575. return -1;
  576. }
  577. int BattleInfo::getIdForNewStack() const
  578. {
  579. if(stacks.size())
  580. {
  581. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  582. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  583. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  584. return highestIDStack->ID + 1;
  585. }
  586. return 0;
  587. }
  588. std::shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  589. {
  590. for(auto &obs : obstacles)
  591. if(vstd::contains(obs->getAffectedTiles(), tile))
  592. return obs;
  593. return std::shared_ptr<CObstacleInstance>();
  594. }
  595. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  596. {
  597. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap =
  598. {
  599. {BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD},
  600. {BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND},
  601. {BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG},
  602. {BFieldType::FAVORABLE_WINDS, BattlefieldBI::NONE},
  603. {BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS},
  604. {BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND},
  605. {BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS},
  606. {BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS},
  607. {BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS},
  608. {BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS},
  609. {BFieldType::SAND_SHORE, BattlefieldBI::COASTAL}
  610. };
  611. auto itr = theMap.find(bfieldType);
  612. if(itr != theMap.end())
  613. return itr->second;
  614. return BattlefieldBI::NONE;
  615. }
  616. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  617. {
  618. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  619. }
  620. BattleInfo::BattleInfo()
  621. : round(-1), activeStack(-1), selectedStack(-1), town(nullptr), tile(-1,-1,-1),
  622. battlefieldType(BFieldType::NONE), terrainType(ETerrainType::WRONG),
  623. tacticsSide(0), tacticDistance(0)
  624. {
  625. setBattle(this);
  626. setNodeType(BATTLE);
  627. }
  628. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  629. {
  630. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  631. }
  632. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  633. {
  634. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  635. }
  636. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  637. {
  638. switch(phase)
  639. {
  640. case 0: //catapult moves after turrets
  641. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  642. case 1: //fastest first, upper slot first
  643. {
  644. int as = a->Speed(turn), bs = b->Speed(turn);
  645. if(as != bs)
  646. return as > bs;
  647. else
  648. return a->slot < b->slot;
  649. }
  650. case 2: //fastest last, upper slot first
  651. //TODO: should be replaced with order of receiving morale!
  652. case 3: //fastest last, upper slot first
  653. {
  654. int as = a->Speed(turn), bs = b->Speed(turn);
  655. if(as != bs)
  656. return as < bs;
  657. else
  658. return a->slot < b->slot;
  659. }
  660. default:
  661. assert(0);
  662. return false;
  663. }
  664. }
  665. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  666. {
  667. phase = Phase;
  668. turn = Turn;
  669. }