BattleInfo.cpp 24 KB

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