BattleInfo.cpp 23 KB

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