BattleInfo.cpp 23 KB

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