BattleInfo.cpp 28 KB

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