BattleInfo.cpp 27 KB

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