BattleInfo.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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. //TODO: remove
  19. #include "../IGameCallback.h"
  20. ///BattleInfo
  21. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack * stack)
  22. {
  23. auto reachability = getReachability(stack);
  24. if(reachability.predecessors[dest] == -1) //cannot reach destination
  25. {
  26. return std::make_pair(std::vector<BattleHex>(), 0);
  27. }
  28. //making the Path
  29. std::vector<BattleHex> path;
  30. BattleHex curElem = dest;
  31. while(curElem != start)
  32. {
  33. path.push_back(curElem);
  34. curElem = reachability.predecessors[curElem];
  35. }
  36. return std::make_pair(path, reachability.distances[dest]);
  37. }
  38. void BattleInfo::calculateCasualties(std::map<ui32,si32> * casualties) const
  39. {
  40. for(auto & elem : stacks)//setting casualties
  41. {
  42. const CStack * const st = elem;
  43. si32 killed = st->getKilled();
  44. if(killed > 0)
  45. casualties[st->side][st->getCreature()->idNumber] += killed;
  46. }
  47. }
  48. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, ui8 side, SlotID slot, BattleHex position)
  49. {
  50. PlayerColor owner = sides[side].color;
  51. assert((owner >= PlayerColor::PLAYER_LIMIT) ||
  52. (base.armyObj && base.armyObj->tempOwner == owner));
  53. auto ret = new CStack(&base, owner, id, side, slot);
  54. ret->initialPosition = getAvaliableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
  55. stacks.push_back(ret);
  56. return ret;
  57. }
  58. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, ui8 side, SlotID slot, BattleHex position)
  59. {
  60. PlayerColor owner = sides[side].color;
  61. auto ret = new CStack(&base, owner, id, side, slot);
  62. ret->initialPosition = position;
  63. stacks.push_back(ret);
  64. return ret;
  65. }
  66. void BattleInfo::localInit()
  67. {
  68. for(int i = 0; i < 2; i++)
  69. {
  70. auto armyObj = battleGetArmyObject(i);
  71. armyObj->battle = this;
  72. armyObj->attachTo(this);
  73. }
  74. for(CStack * s : stacks)
  75. s->localInit(this);
  76. exportBonuses();
  77. }
  78. namespace CGH
  79. {
  80. static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
  81. {
  82. for(const JsonNode &level : node.Vector())
  83. {
  84. std::vector<int> pom;
  85. for(const JsonNode &value : level.Vector())
  86. {
  87. pom.push_back((int)value.Float());
  88. }
  89. dest.push_back(pom);
  90. }
  91. }
  92. }
  93. //RNG that works like H3 one
  94. struct RandGen
  95. {
  96. ui32 seed;
  97. void srand(ui32 s)
  98. {
  99. seed = s;
  100. }
  101. void srand(int3 pos)
  102. {
  103. srand(110291 * ui32(pos.x) + 167801 * ui32(pos.y) + 81569);
  104. }
  105. int rand()
  106. {
  107. seed = 214013 * seed + 2531011;
  108. return (seed >> 16) & 0x7FFF;
  109. }
  110. int rand(int min, int max)
  111. {
  112. if(min == max)
  113. return min;
  114. if(min > max)
  115. return min;
  116. return min + rand() % (max - min + 1);
  117. }
  118. };
  119. struct RangeGenerator
  120. {
  121. class ExhaustedPossibilities : public std::exception
  122. {
  123. };
  124. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  125. min(_min),
  126. remainingCount(_max - _min + 1),
  127. remaining(remainingCount, true),
  128. myRand(_myRand)
  129. {
  130. }
  131. int generateNumber()
  132. {
  133. if(!remainingCount)
  134. throw ExhaustedPossibilities();
  135. if(remainingCount == 1)
  136. return 0;
  137. return myRand() % remainingCount;
  138. }
  139. //get number fulfilling predicate. Never gives the same number twice.
  140. int getSuchNumber(std::function<bool(int)> goodNumberPred = nullptr)
  141. {
  142. int ret = -1;
  143. do
  144. {
  145. int n = generateNumber();
  146. int i = 0;
  147. for(;;i++)
  148. {
  149. assert(i < (int)remaining.size());
  150. if(!remaining[i])
  151. continue;
  152. if(!n)
  153. break;
  154. n--;
  155. }
  156. remainingCount--;
  157. remaining[i] = false;
  158. ret = i + min;
  159. } while(goodNumberPred && !goodNumberPred(ret));
  160. return ret;
  161. }
  162. int min, remainingCount;
  163. std::vector<bool> remaining;
  164. std::function<int()> myRand;
  165. };
  166. BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance * armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance * town)
  167. {
  168. CMP_stack cmpst;
  169. auto curB = new BattleInfo();
  170. for(auto i = 0u; i < curB->sides.size(); i++)
  171. curB->sides[i].init(heroes[i], armies[i]);
  172. std::vector<CStack*> & stacks = (curB->stacks);
  173. curB->tile = tile;
  174. curB->battlefieldType = battlefieldType;
  175. curB->round = -2;
  176. curB->activeStack = -1;
  177. if(town)
  178. {
  179. curB->town = town;
  180. curB->terrainType = (*VLC->townh)[town->subID]->nativeTerrain;
  181. }
  182. else
  183. {
  184. curB->town = nullptr;
  185. curB->terrainType = terrain;
  186. }
  187. //setting up siege obstacles
  188. if (town && town->hasFort())
  189. {
  190. curB->si.gateState = EGateState::CLOSED;
  191. for (int b = 0; b < curB->si.wallState.size(); ++b)
  192. {
  193. curB->si.wallState[b] = EWallState::INTACT;
  194. }
  195. if (!town->hasBuilt(BuildingID::CITADEL))
  196. {
  197. curB->si.wallState[EWallPart::KEEP] = EWallState::NONE;
  198. }
  199. if (!town->hasBuilt(BuildingID::CASTLE))
  200. {
  201. curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::NONE;
  202. curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::NONE;
  203. }
  204. }
  205. //randomize obstacles
  206. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  207. {
  208. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  209. RandGen r;
  210. auto ourRand = [&](){ return r.rand(); };
  211. r.srand(tile);
  212. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  213. int tilesToBlock = r.rand(5,12);
  214. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  215. std::vector<BattleHex> blockedTiles;
  216. auto appropriateAbsoluteObstacle = [&](int id)
  217. {
  218. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  219. };
  220. auto appropriateUsualObstacle = [&](int id) -> bool
  221. {
  222. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  223. };
  224. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  225. {
  226. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  227. try
  228. {
  229. auto obstPtr = std::make_shared<CObstacleInstance>();
  230. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  231. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  232. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  233. curB->obstacles.push_back(obstPtr);
  234. for(BattleHex blocked : obstPtr->getBlockedTiles())
  235. blockedTiles.push_back(blocked);
  236. tilesToBlock -= (int)VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  237. }
  238. catch(RangeGenerator::ExhaustedPossibilities &)
  239. {
  240. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  241. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occured - cannot place absolute obstacle");
  242. }
  243. }
  244. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  245. try
  246. {
  247. while(tilesToBlock > 0)
  248. {
  249. auto tileAccessibility = curB->getAccesibility();
  250. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  251. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  252. auto validPosition = [&](BattleHex pos) -> bool
  253. {
  254. if(obi.height >= pos.getY())
  255. return false;
  256. if(pos.getX() == 0)
  257. return false;
  258. if(pos.getX() + obi.width > 15)
  259. return false;
  260. if(vstd::contains(blockedTiles, pos))
  261. return false;
  262. for(BattleHex blocked : obi.getBlocked(pos))
  263. {
  264. if(tileAccessibility[blocked] == EAccessibility::UNAVAILABLE) //for ship-to-ship battlefield - exclude hardcoded unavailable tiles
  265. return false;
  266. if(vstd::contains(blockedTiles, blocked))
  267. return false;
  268. int x = blocked.getX();
  269. if(x <= 2 || x >= 14)
  270. return false;
  271. }
  272. return true;
  273. };
  274. RangeGenerator posgenerator(18, 168, ourRand);
  275. auto obstPtr = std::make_shared<CObstacleInstance>();
  276. obstPtr->ID = obid;
  277. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  278. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  279. curB->obstacles.push_back(obstPtr);
  280. for(BattleHex blocked : obstPtr->getBlockedTiles())
  281. blockedTiles.push_back(blocked);
  282. tilesToBlock -= static_cast<int>(obi.blockedTiles.size());
  283. }
  284. }
  285. catch(RangeGenerator::ExhaustedPossibilities &)
  286. {
  287. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occured - cannot place usual obstacle");
  288. }
  289. }
  290. //reading battleStartpos - add creatures AFTER random obstacles are generated
  291. //TODO: parse once to some structure
  292. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  293. std::vector <int> commanderField, commanderBank;
  294. const JsonNode config(ResourceID("config/battleStartpos.json"));
  295. const JsonVector &positions = config["battle_positions"].Vector();
  296. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  297. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  298. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  299. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  300. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  301. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  302. for (auto position : config["commanderPositions"]["field"].Vector())
  303. {
  304. commanderField.push_back ((int)position.Float());
  305. }
  306. for (auto position : config["commanderPositions"]["creBank"].Vector())
  307. {
  308. commanderBank.push_back ((int)position.Float());
  309. }
  310. //adding war machines
  311. if(!creatureBank)
  312. {
  313. //Checks if hero has artifact and create appropriate stack
  314. auto handleWarMachine= [&](int side, ArtifactPosition artslot, BattleHex hex)
  315. {
  316. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  317. if(nullptr != warMachineArt)
  318. {
  319. CreatureID cre = warMachineArt->artType->warMachine;
  320. if(cre != CreatureID::NONE)
  321. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex);
  322. }
  323. };
  324. if(heroes[0])
  325. {
  326. handleWarMachine(0, ArtifactPosition::MACH1, 52);
  327. handleWarMachine(0, ArtifactPosition::MACH2, 18);
  328. handleWarMachine(0, ArtifactPosition::MACH3, 154);
  329. if(town && town->hasFort())
  330. handleWarMachine(0, ArtifactPosition::MACH4, 120);
  331. }
  332. if(heroes[1])
  333. {
  334. if(!town) //defending hero shouldn't receive ballista (bug #551)
  335. handleWarMachine(1, ArtifactPosition::MACH1, 66);
  336. handleWarMachine(1, ArtifactPosition::MACH2, 32);
  337. handleWarMachine(1, ArtifactPosition::MACH3, 168);
  338. }
  339. }
  340. //war machines added
  341. //battleStartpos read
  342. for(int side = 0; side < 2; side++)
  343. {
  344. int formationNo = armies[side]->stacksCount() - 1;
  345. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  346. int k = 0; //stack serial
  347. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  348. {
  349. std::vector<int> *formationVector = nullptr;
  350. if(creatureBank)
  351. formationVector = &creBankFormations[side][formationNo];
  352. else if(armies[side]->formation)
  353. formationVector = &tightFormations[side][formationNo];
  354. else
  355. formationVector = &looseFormations[side][formationNo];
  356. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  357. if(creatureBank && i->second->type->isDoubleWide())
  358. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  359. curB->generateNewStack(curB->nextUnitId(), *i->second, side, i->first, pos);
  360. }
  361. }
  362. //adding commanders
  363. for (int i = 0; i < 2; ++i)
  364. {
  365. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  366. {
  367. curB->generateNewStack(curB->nextUnitId(), *heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER, creatureBank ? commanderBank[i] : commanderField[i]);
  368. }
  369. }
  370. if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
  371. {
  372. // keep tower
  373. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -2);
  374. if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
  375. {
  376. // lower tower + upper tower
  377. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -4);
  378. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -3);
  379. }
  380. //moat
  381. auto moat = std::make_shared<MoatObstacle>();
  382. moat->ID = curB->town->subID;
  383. moat->obstacleType = CObstacleInstance::MOAT;
  384. moat->uniqueID = static_cast<si32>(curB->obstacles.size());
  385. curB->obstacles.push_back(moat);
  386. }
  387. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  388. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  389. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  390. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  391. //giving terrain overlay premies
  392. int bonusSubtype = -1;
  393. switch(battlefieldType)
  394. {
  395. case BFieldType::MAGIC_PLAINS:
  396. {
  397. bonusSubtype = 0;
  398. }
  399. FALLTHROUGH
  400. case BFieldType::FIERY_FIELDS:
  401. {
  402. if(bonusSubtype == -1) bonusSubtype = 1;
  403. }
  404. FALLTHROUGH
  405. case BFieldType::ROCKLANDS:
  406. {
  407. if(bonusSubtype == -1) bonusSubtype = 8;
  408. }
  409. FALLTHROUGH
  410. case BFieldType::MAGIC_CLOUDS:
  411. {
  412. if(bonusSubtype == -1) bonusSubtype = 2;
  413. }
  414. FALLTHROUGH
  415. case BFieldType::LUCID_POOLS:
  416. {
  417. if(bonusSubtype == -1) bonusSubtype = 4;
  418. }
  419. { //common part for cases 9, 14, 15, 16, 17
  420. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, battlefieldType, bonusSubtype));
  421. break;
  422. }
  423. case BFieldType::HOLY_GROUND:
  424. {
  425. std::string goodArmyDesc = VLC->generaltexth->arraytxt[123];
  426. goodArmyDesc.erase(goodArmyDesc.size() - 2, 2); //omitting hardcoded +1 in description
  427. std::string evilArmyDesc = VLC->generaltexth->arraytxt[124];
  428. evilArmyDesc.erase(evilArmyDesc.size() - 2, 2);
  429. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, goodArmyDesc, 0)->addLimiter(good));
  430. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, evilArmyDesc, 0)->addLimiter(evil));
  431. break;
  432. }
  433. case BFieldType::CLOVER_FIELD:
  434. { //+2 luck bonus for neutral creatures
  435. std::string desc = VLC->generaltexth->arraytxt[83];
  436. desc.erase(desc.size() - 2, 2);
  437. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::LUCK, Bonus::TERRAIN_OVERLAY, +2, battlefieldType, desc, 0)->addLimiter(neutral));
  438. break;
  439. }
  440. case BFieldType::EVIL_FOG:
  441. {
  442. std::string goodArmyDesc = VLC->generaltexth->arraytxt[126];
  443. goodArmyDesc.erase(goodArmyDesc.size() - 2, 2);
  444. std::string evilArmyDesc = VLC->generaltexth->arraytxt[125];
  445. evilArmyDesc.erase(evilArmyDesc.size() - 2, 2);
  446. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, goodArmyDesc, 0)->addLimiter(good));
  447. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, evilArmyDesc, 0)->addLimiter(evil));
  448. break;
  449. }
  450. case BFieldType::CURSED_GROUND:
  451. {
  452. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_MORALE, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, VLC->generaltexth->arraytxt[112], 0));
  453. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_LUCK, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, VLC->generaltexth->arraytxt[81], 0));
  454. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::BLOCK_MAGIC_ABOVE, Bonus::TERRAIN_OVERLAY, 1, battlefieldType, 0, Bonus::INDEPENDENT_MIN));
  455. break;
  456. }
  457. }
  458. //overlay premies given
  459. //native terrain bonuses
  460. auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
  461. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::STACKS_SPEED, Bonus::TERRAIN_NATIVE, 1, 0, 0)->addLimiter(nativeTerrain));
  462. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::ATTACK)->addLimiter(nativeTerrain));
  463. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::DEFENSE)->addLimiter(nativeTerrain));
  464. //////////////////////////////////////////////////////////////////////////
  465. //tactics
  466. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  467. int tacticLvls[2] = {0};
  468. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  469. {
  470. if(heroes[i])
  471. tacticLvls[i] += heroes[i]->valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::TACTICS));
  472. }
  473. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  474. if(tacticsSkillDiff && isTacticsAllowed)
  475. {
  476. curB->tacticsSide = tacticsSkillDiff < 0;
  477. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  478. curB->tacticDistance = 1 + std::abs(tacticsSkillDiff);
  479. }
  480. else
  481. curB->tacticDistance = 0;
  482. // workaround — bonuses affecting only enemy - DOES NOT WORK
  483. for(int i = 0; i < 2; i++)
  484. {
  485. TNodes nodes;
  486. curB->battleGetArmyObject(i)->getRedAncestors(nodes);
  487. for(CBonusSystemNode *n : nodes)
  488. {
  489. for(auto b : n->getExportedBonusList())
  490. {
  491. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  492. {
  493. auto bCopy = std::make_shared<Bonus>(*b);
  494. bCopy->effectRange = Bonus::NO_LIMIT;
  495. bCopy->propagator.reset();
  496. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i].color));
  497. curB->addNewBonus(bCopy);
  498. }
  499. }
  500. }
  501. }
  502. return curB;
  503. }
  504. const CGHeroInstance * BattleInfo::getHero(PlayerColor player) const
  505. {
  506. for(int i = 0; i < sides.size(); i++)
  507. if(sides[i].color == player)
  508. return sides[i].hero;
  509. logGlobal->error("Player %s is not in battle!", player.getStr());
  510. return nullptr;
  511. }
  512. ui8 BattleInfo::whatSide(PlayerColor player) const
  513. {
  514. for(int i = 0; i < sides.size(); i++)
  515. if(sides[i].color == player)
  516. return i;
  517. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.getStr());
  518. return -1;
  519. }
  520. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  521. {
  522. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap =
  523. {
  524. {BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD},
  525. {BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND},
  526. {BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG},
  527. {BFieldType::FAVORABLE_WINDS, BattlefieldBI::NONE},
  528. {BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS},
  529. {BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND},
  530. {BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS},
  531. {BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS},
  532. {BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS},
  533. {BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS},
  534. {BFieldType::SAND_SHORE, BattlefieldBI::COASTAL}
  535. };
  536. auto itr = theMap.find(bfieldType);
  537. if(itr != theMap.end())
  538. return itr->second;
  539. return BattlefieldBI::NONE;
  540. }
  541. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  542. {
  543. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  544. }
  545. BattleInfo::BattleInfo()
  546. : round(-1), activeStack(-1), town(nullptr), tile(-1,-1,-1),
  547. battlefieldType(BFieldType::NONE), terrainType(ETerrainType::WRONG),
  548. tacticsSide(0), tacticDistance(0)
  549. {
  550. setBattle(this);
  551. setNodeType(BATTLE);
  552. }
  553. BattleInfo::~BattleInfo() = default;
  554. int32_t BattleInfo::getActiveStackID() const
  555. {
  556. return activeStack;
  557. }
  558. TStacks BattleInfo::getStacksIf(TStackFilter predicate) const
  559. {
  560. TStacks ret;
  561. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  562. return ret;
  563. }
  564. battle::Units BattleInfo::getUnitsIf(battle::UnitFilter predicate) const
  565. {
  566. battle::Units ret;
  567. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  568. return ret;
  569. }
  570. BFieldType BattleInfo::getBattlefieldType() const
  571. {
  572. return battlefieldType;
  573. }
  574. ETerrainType BattleInfo::getTerrainType() const
  575. {
  576. return terrainType;
  577. }
  578. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  579. {
  580. ObstacleCList ret;
  581. for(auto iter = obstacles.cbegin(); iter != obstacles.cend(); iter++)
  582. ret.push_back(*iter);
  583. return ret;
  584. }
  585. PlayerColor BattleInfo::getSidePlayer(ui8 side) const
  586. {
  587. return sides.at(side).color;
  588. }
  589. const CArmedInstance * BattleInfo::getSideArmy(ui8 side) const
  590. {
  591. return sides.at(side).armyObject;
  592. }
  593. const CGHeroInstance * BattleInfo::getSideHero(ui8 side) const
  594. {
  595. return sides.at(side).hero;
  596. }
  597. ui8 BattleInfo::getTacticDist() const
  598. {
  599. return tacticDistance;
  600. }
  601. ui8 BattleInfo::getTacticsSide() const
  602. {
  603. return tacticsSide;
  604. }
  605. const CGTownInstance * BattleInfo::getDefendedTown() const
  606. {
  607. return town;
  608. }
  609. si8 BattleInfo::getWallState(int partOfWall) const
  610. {
  611. return si.wallState.at(partOfWall);
  612. }
  613. EGateState BattleInfo::getGateState() const
  614. {
  615. return si.gateState;
  616. }
  617. uint32_t BattleInfo::getCastSpells(ui8 side) const
  618. {
  619. return sides.at(side).castSpellsCount;
  620. }
  621. int32_t BattleInfo::getEnchanterCounter(ui8 side) const
  622. {
  623. return sides.at(side).enchanterCounter;
  624. }
  625. const IBonusBearer * BattleInfo::asBearer() const
  626. {
  627. return this;
  628. }
  629. int64_t BattleInfo::getActualDamage(const TDmgRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  630. {
  631. if(damage.first != damage.second)
  632. {
  633. int64_t sum = 0;
  634. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  635. auto rangeGen = rng.getInt64Range(damage.first, damage.second);
  636. for(int32_t g = 0; g < howManyToAv; ++g)
  637. sum += rangeGen();
  638. return sum / howManyToAv;
  639. }
  640. else
  641. {
  642. return damage.first;
  643. }
  644. }
  645. void BattleInfo::nextRound(int32_t roundNr)
  646. {
  647. for(int i = 0; i < 2; ++i)
  648. {
  649. sides.at(i).castSpellsCount = 0;
  650. vstd::amax(--sides.at(i).enchanterCounter, 0);
  651. }
  652. round = roundNr;
  653. for(CStack * s : stacks)
  654. {
  655. // new turn effects
  656. s->reduceBonusDurations(Bonus::NTurns);
  657. s->afterNewRound();
  658. }
  659. for(auto & obst : obstacles)
  660. obst->battleTurnPassed();
  661. }
  662. void BattleInfo::nextTurn(uint32_t unitId)
  663. {
  664. activeStack = unitId;
  665. CStack * st = getStack(activeStack);
  666. //remove bonuses that last until when stack gets new turn
  667. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  668. st->afterGetsTurn();
  669. }
  670. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  671. {
  672. battle::UnitInfo info;
  673. info.load(id, data);
  674. CStackBasicDescriptor base(info.type, info.count);
  675. PlayerColor owner = getSidePlayer(info.side);
  676. auto ret = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  677. ret->initialPosition = info.position;
  678. stacks.push_back(ret);
  679. ret->localInit(this);
  680. ret->summoned = info.summoned;
  681. }
  682. void BattleInfo::moveUnit(uint32_t id, BattleHex destination)
  683. {
  684. auto sta = getStack(id);
  685. if(!sta)
  686. {
  687. logGlobal->error("Cannot find stack %d", id);
  688. return;
  689. }
  690. sta->position = destination;
  691. }
  692. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  693. {
  694. CStack * changedStack = getStack(id, false);
  695. if(!changedStack)
  696. throw std::runtime_error("Invalid unit id in BattleInfo update");
  697. if(!changedStack->alive() && healthDelta > 0)
  698. {
  699. //checking if we resurrect a stack that is under a living stack
  700. auto accessibility = getAccesibility();
  701. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  702. {
  703. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition().hex);
  704. return; //position is already occupied
  705. }
  706. }
  707. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  708. bool resurrected = !changedStack->alive() && healthDelta > 0;
  709. //applying changes
  710. changedStack->load(data);
  711. if(healthDelta < 0)
  712. {
  713. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  714. }
  715. resurrected = resurrected || (killed && changedStack->alive());
  716. if(killed)
  717. {
  718. if(changedStack->cloneID >= 0)
  719. {
  720. //remove clone as well
  721. CStack * clone = getStack(changedStack->cloneID);
  722. if(clone)
  723. clone->makeGhost();
  724. changedStack->cloneID = -1;
  725. }
  726. }
  727. if(resurrected || killed)
  728. {
  729. //removing all spells effects
  730. auto selector = [](const Bonus * b)
  731. {
  732. //Special case: DISRUPTING_RAY is absolutely permanent
  733. return b->source == Bonus::SPELL_EFFECT && b->sid != SpellID::DISRUPTING_RAY;
  734. };
  735. changedStack->removeBonusesRecursive(selector);
  736. }
  737. if(!changedStack->alive() && changedStack->isClone())
  738. {
  739. for(CStack * s : stacks)
  740. {
  741. if(s->cloneID == changedStack->unitId())
  742. s->cloneID = -1;
  743. }
  744. }
  745. }
  746. void BattleInfo::removeUnit(uint32_t id)
  747. {
  748. std::set<uint32_t> ids;
  749. ids.insert(id);
  750. while(!ids.empty())
  751. {
  752. auto toRemoveId = *ids.begin();
  753. auto toRemove = getStack(toRemoveId, false);
  754. if(!toRemove)
  755. {
  756. logGlobal->error("Cannot find stack %d", toRemoveId);
  757. return;
  758. }
  759. if(!toRemove->ghost)
  760. {
  761. toRemove->onRemoved();
  762. toRemove->detachFromAll();
  763. //stack may be removed instantly (not being killed first)
  764. //handle clone remove also here
  765. if(toRemove->cloneID >= 0)
  766. {
  767. ids.insert(toRemove->cloneID);
  768. toRemove->cloneID = -1;
  769. }
  770. //cleanup remaining clone links if any
  771. for(auto s : stacks)
  772. {
  773. if(s->cloneID == toRemoveId)
  774. s->cloneID = -1;
  775. }
  776. }
  777. ids.erase(toRemoveId);
  778. }
  779. }
  780. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  781. {
  782. //TODO
  783. }
  784. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  785. {
  786. CStack * sta = getStack(id, false);
  787. if(!sta)
  788. {
  789. logGlobal->error("Cannot find stack %d", id);
  790. return;
  791. }
  792. for(const Bonus & b : bonus)
  793. addOrUpdateUnitBonus(sta, b, true);
  794. }
  795. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  796. {
  797. CStack * sta = getStack(id, false);
  798. if(!sta)
  799. {
  800. logGlobal->error("Cannot find stack %d", id);
  801. return;
  802. }
  803. for(const Bonus & b : bonus)
  804. addOrUpdateUnitBonus(sta, b, false);
  805. }
  806. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  807. {
  808. CStack * sta = getStack(id, false);
  809. if(!sta)
  810. {
  811. logGlobal->error("Cannot find stack %d", id);
  812. return;
  813. }
  814. for(const Bonus & one : bonus)
  815. {
  816. auto selector = [one](const Bonus * b)
  817. {
  818. //compare everything but turnsRemain, limiter and propagator
  819. return one.duration == b->duration
  820. && one.type == b->type
  821. && one.subtype == b->subtype
  822. && one.source == b->source
  823. && one.val == b->val
  824. && one.sid == b->sid
  825. && one.valType == b->valType
  826. && one.additionalInfo == b->additionalInfo
  827. && one.effectRange == b->effectRange
  828. && one.description == b->description;
  829. };
  830. sta->removeBonusesRecursive(selector);
  831. }
  832. }
  833. uint32_t BattleInfo::nextUnitId() const
  834. {
  835. return static_cast<uint32_t>(stacks.size());
  836. }
  837. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  838. {
  839. if(forceAdd || !sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, value.sid).And(Selector::typeSubtype(value.type, value.subtype))))
  840. {
  841. //no such effect or cumulative - add new
  842. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description());
  843. sta->addNewBonus(std::make_shared<Bonus>(value));
  844. }
  845. else
  846. {
  847. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description());
  848. for(auto stackBonus : sta->getExportedBonusList()) //TODO: optimize
  849. {
  850. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype)
  851. {
  852. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  853. }
  854. }
  855. CBonusSystemNode::treeHasChanged();
  856. }
  857. }
  858. void BattleInfo::setWallState(int partOfWall, si8 state)
  859. {
  860. si.wallState.at(partOfWall) = state;
  861. }
  862. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  863. {
  864. std::shared_ptr<SpellCreatedObstacle> obstacle = std::make_shared<SpellCreatedObstacle>();
  865. obstacle->fromInfo(changes);
  866. obstacles.push_back(obstacle);
  867. }
  868. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  869. {
  870. std::shared_ptr<SpellCreatedObstacle> changedObstacle = std::make_shared<SpellCreatedObstacle>();
  871. changedObstacle->fromInfo(changes);
  872. for(int i = 0; i < obstacles.size(); ++i)
  873. {
  874. if(obstacles[i]->uniqueID == changes.id) // update this obstacle
  875. {
  876. SpellCreatedObstacle * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacles[i].get());
  877. assert(spellObstacle);
  878. // Currently we only support to update the "revealed" property
  879. spellObstacle->revealed = changedObstacle->revealed;
  880. break;
  881. }
  882. }
  883. }
  884. void BattleInfo::removeObstacle(uint32_t id)
  885. {
  886. for(int i=0; i < obstacles.size(); ++i)
  887. {
  888. if(obstacles[i]->uniqueID == id) //remove this obstacle
  889. {
  890. obstacles.erase(obstacles.begin() + i);
  891. break;
  892. }
  893. }
  894. }
  895. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  896. {
  897. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  898. }
  899. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  900. {
  901. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  902. }
  903. scripting::Pool * BattleInfo::getContextPool() const
  904. {
  905. //this is real battle, use global scripting context pool
  906. //TODO: make this line not ugly
  907. return IObjectInterface::cb->getGlobalContextPool();
  908. }
  909. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b)
  910. {
  911. switch(phase)
  912. {
  913. case 0: //catapult moves after turrets
  914. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  915. case 1:
  916. case 2:
  917. case 3:
  918. {
  919. int as = a->getInitiative(turn), bs = b->getInitiative(turn);
  920. if(as != bs)
  921. return as > bs;
  922. if(a->unitSide() == b->unitSide())
  923. return a->unitSlot() < b->unitSlot();
  924. return (a->unitSide() == side || b->unitSide() == side)
  925. ? a->unitSide() != side
  926. : a->unitSide() < b->unitSide();
  927. }
  928. default:
  929. assert(false);
  930. return false;
  931. }
  932. assert(false);
  933. return false;
  934. }
  935. CMP_stack::CMP_stack(int Phase, int Turn, uint8_t Side)
  936. {
  937. phase = Phase;
  938. turn = Turn;
  939. side = Side;
  940. }