2
0

BattleInfo.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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->getDefendedTown()->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->getDefendedTown()->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->getDefendedTown()->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. :CBonusSystemNode(BonusNodeType::BATTLE_WIDE),
  397. GameCallbackHolder(cb),
  398. sides({SideInBattle(cb), SideInBattle(cb)}),
  399. layout(std::make_unique<BattleLayout>()),
  400. round(-1),
  401. activeStack(-1),
  402. tile(-1,-1,-1),
  403. battlefieldType(BattleField::NONE),
  404. tacticsSide(BattleSide::NONE),
  405. tacticDistance(0)
  406. {
  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. uint8_t BattleInfo::getTacticDist() const
  479. {
  480. return tacticDistance;
  481. }
  482. BattleSide BattleInfo::getTacticsSide() const
  483. {
  484. return tacticsSide;
  485. }
  486. const CGTownInstance * BattleInfo::getDefendedTown() const
  487. {
  488. if (townID.hasValue())
  489. return cb->getTown(townID);
  490. return nullptr;
  491. }
  492. EWallState BattleInfo::getWallState(EWallPart partOfWall) const
  493. {
  494. return si.wallState.at(partOfWall);
  495. }
  496. EGateState BattleInfo::getGateState() const
  497. {
  498. return si.gateState;
  499. }
  500. int32_t BattleInfo::getCastSpells(BattleSide side) const
  501. {
  502. return getSide(side).castSpellsCount;
  503. }
  504. int32_t BattleInfo::getEnchanterCounter(BattleSide side) const
  505. {
  506. return getSide(side).enchanterCounter;
  507. }
  508. const IBonusBearer * BattleInfo::getBonusBearer() const
  509. {
  510. return this;
  511. }
  512. int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  513. {
  514. if(damage.min != damage.max)
  515. {
  516. int64_t sum = 0;
  517. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  518. for(int32_t g = 0; g < howManyToAv; ++g)
  519. sum += rng.nextInt64(damage.min, damage.max);
  520. return sum / howManyToAv;
  521. }
  522. else
  523. {
  524. return damage.min;
  525. }
  526. }
  527. int3 BattleInfo::getLocation() const
  528. {
  529. return tile;
  530. }
  531. std::vector<SpellID> BattleInfo::getUsedSpells(BattleSide side) const
  532. {
  533. return getSide(side).usedSpellsHistory;
  534. }
  535. void BattleInfo::nextRound()
  536. {
  537. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  538. {
  539. sides.at(i).castSpellsCount = 0;
  540. vstd::amax(--sides.at(i).enchanterCounter, 0);
  541. }
  542. round += 1;
  543. for(auto & s : stacks)
  544. {
  545. // new turn effects
  546. s->reduceBonusDurations(Bonus::NTurns);
  547. s->afterNewRound();
  548. }
  549. for(auto & obst : obstacles)
  550. obst->battleTurnPassed();
  551. }
  552. void BattleInfo::nextTurn(uint32_t unitId, BattleUnitTurnReason reason)
  553. {
  554. activeStack = unitId;
  555. CStack * st = getStack(activeStack);
  556. //remove bonuses that last until when stack gets new turn
  557. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  558. st->afterGetsTurn(reason);
  559. }
  560. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  561. {
  562. battle::UnitInfo info;
  563. info.load(id, data);
  564. CStackBasicDescriptor base(info.type, info.count);
  565. PlayerColor owner = getSidePlayer(info.side);
  566. auto ret = std::make_unique<CStack>(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  567. ret->initialPosition = info.position;
  568. stacks.push_back(std::move(ret));
  569. stacks.back()->localInit(this);
  570. stacks.back()->summoned = info.summoned;
  571. }
  572. void BattleInfo::moveUnit(uint32_t id, const BattleHex & destination)
  573. {
  574. auto * sta = getStack(id);
  575. if(!sta)
  576. {
  577. logGlobal->error("Cannot find stack %d", id);
  578. return;
  579. }
  580. sta->position = destination;
  581. //Bonuses can be limited by unit placement, so, change tree version
  582. //to force updating a bonus. TODO: update version only when such bonuses are present
  583. nodeHasChanged();
  584. }
  585. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  586. {
  587. CStack * changedStack = getStack(id, false);
  588. if(!changedStack)
  589. throw std::runtime_error("Invalid unit id in BattleInfo update");
  590. if(!changedStack->alive() && healthDelta > 0)
  591. {
  592. //checking if we resurrect a stack that is under a living stack
  593. auto accessibility = getAccessibility();
  594. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  595. {
  596. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition());
  597. return; //position is already occupied
  598. }
  599. }
  600. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  601. bool resurrected = !changedStack->alive() && healthDelta > 0;
  602. //applying changes
  603. changedStack->load(data);
  604. if(healthDelta < 0)
  605. {
  606. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  607. }
  608. resurrected = resurrected || (killed && changedStack->alive());
  609. if(killed)
  610. {
  611. if(changedStack->cloneID >= 0)
  612. {
  613. //remove clone as well
  614. CStack * clone = getStack(changedStack->cloneID);
  615. if(clone)
  616. clone->makeGhost();
  617. changedStack->cloneID = -1;
  618. }
  619. }
  620. if(resurrected || killed)
  621. {
  622. //removing all spells effects
  623. auto selector = [](const Bonus * b)
  624. {
  625. //Special case: DISRUPTING_RAY is absolutely permanent
  626. return b->source == BonusSource::SPELL_EFFECT && b->sid.as<SpellID>() != SpellID::DISRUPTING_RAY;
  627. };
  628. changedStack->removeBonusesRecursive(selector);
  629. }
  630. if(!changedStack->alive() && changedStack->isClone())
  631. {
  632. for(auto & s : stacks)
  633. {
  634. if(s->cloneID == changedStack->unitId())
  635. s->cloneID = -1;
  636. }
  637. }
  638. }
  639. void BattleInfo::removeUnit(uint32_t id)
  640. {
  641. std::set<uint32_t> ids;
  642. ids.insert(id);
  643. while(!ids.empty())
  644. {
  645. auto toRemoveId = *ids.begin();
  646. auto * toRemove = getStack(toRemoveId, false);
  647. if(!toRemove)
  648. {
  649. logGlobal->error("Cannot find stack %d", toRemoveId);
  650. return;
  651. }
  652. if(!toRemove->ghost)
  653. {
  654. toRemove->onRemoved();
  655. toRemove->detachFromAll();
  656. //stack may be removed instantly (not being killed first)
  657. //handle clone remove also here
  658. if(toRemove->cloneID >= 0)
  659. {
  660. ids.insert(toRemove->cloneID);
  661. toRemove->cloneID = -1;
  662. }
  663. //cleanup remaining clone links if any
  664. for(const auto & s : stacks)
  665. {
  666. if(s->cloneID == toRemoveId)
  667. s->cloneID = -1;
  668. }
  669. }
  670. ids.erase(toRemoveId);
  671. }
  672. }
  673. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  674. {
  675. //TODO
  676. }
  677. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  678. {
  679. CStack * sta = getStack(id, false);
  680. if(!sta)
  681. {
  682. logGlobal->error("Cannot find stack %d", id);
  683. return;
  684. }
  685. for(const Bonus & b : bonus)
  686. addOrUpdateUnitBonus(sta, b, true);
  687. }
  688. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  689. {
  690. CStack * sta = getStack(id, false);
  691. if(!sta)
  692. {
  693. logGlobal->error("Cannot find stack %d", id);
  694. return;
  695. }
  696. for(const Bonus & b : bonus)
  697. addOrUpdateUnitBonus(sta, b, false);
  698. }
  699. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  700. {
  701. CStack * sta = getStack(id, false);
  702. if(!sta)
  703. {
  704. logGlobal->error("Cannot find stack %d", id);
  705. return;
  706. }
  707. for(const Bonus & one : bonus)
  708. {
  709. auto selector = [one](const Bonus * b)
  710. {
  711. //compare everything but turnsRemain, limiter and propagator
  712. return one.duration == b->duration
  713. && one.type == b->type
  714. && one.subtype == b->subtype
  715. && one.source == b->source
  716. && one.val == b->val
  717. && one.sid == b->sid
  718. && one.valType == b->valType
  719. && one.additionalInfo == b->additionalInfo
  720. && one.effectRange == b->effectRange;
  721. };
  722. sta->removeBonusesRecursive(selector);
  723. }
  724. }
  725. uint32_t BattleInfo::nextUnitId() const
  726. {
  727. return static_cast<uint32_t>(stacks.size());
  728. }
  729. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  730. {
  731. if(forceAdd || !sta->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, value.sid).And(Selector::typeSubtypeValueType(value.type, value.subtype, value.valType))))
  732. {
  733. //no such effect or cumulative - add new
  734. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description(nullptr));
  735. sta->addNewBonus(std::make_shared<Bonus>(value));
  736. }
  737. else
  738. {
  739. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description(nullptr));
  740. for(const auto & stackBonus : sta->getExportedBonusList()) //TODO: optimize
  741. {
  742. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype && stackBonus->valType == value.valType)
  743. {
  744. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  745. }
  746. }
  747. sta->nodeHasChanged();
  748. }
  749. }
  750. void BattleInfo::setWallState(EWallPart partOfWall, EWallState state)
  751. {
  752. si.wallState[partOfWall] = state;
  753. }
  754. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  755. {
  756. auto obstacle = std::make_shared<SpellCreatedObstacle>();
  757. obstacle->fromInfo(changes);
  758. obstacles.push_back(obstacle);
  759. }
  760. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  761. {
  762. auto changedObstacle = std::make_shared<SpellCreatedObstacle>();
  763. changedObstacle->fromInfo(changes);
  764. for(auto & obstacle : obstacles)
  765. {
  766. if(obstacle->uniqueID == changes.id) // update this obstacle
  767. {
  768. auto * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacle.get());
  769. assert(spellObstacle);
  770. // Currently we only support to update the "revealed" property
  771. spellObstacle->revealed = changedObstacle->revealed;
  772. break;
  773. }
  774. }
  775. }
  776. void BattleInfo::removeObstacle(uint32_t id)
  777. {
  778. for(int i=0; i < obstacles.size(); ++i)
  779. {
  780. if(obstacles[i]->uniqueID == id) //remove this obstacle
  781. {
  782. obstacles.erase(obstacles.begin() + i);
  783. break;
  784. }
  785. }
  786. }
  787. CArmedInstance * BattleInfo::battleGetArmyObject(BattleSide side) const
  788. {
  789. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  790. }
  791. CGHeroInstance * BattleInfo::battleGetFightingHero(BattleSide side) const
  792. {
  793. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  794. }
  795. void BattleInfo::postDeserialize()
  796. {
  797. for (const auto & unit : stacks)
  798. unit->postDeserialize(getSideArmy(unit->unitSide()));
  799. }
  800. #if SCRIPTING_ENABLED
  801. scripting::Pool * BattleInfo::getContextPool() const
  802. {
  803. //this is real battle, use global scripting context pool
  804. //TODO: make this line not ugly
  805. return battleGetFightingHero(BattleSide::ATTACKER)->cb->getGlobalContextPool();
  806. }
  807. #endif
  808. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
  809. {
  810. switch(phase)
  811. {
  812. case 0: //catapult moves after turrets
  813. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  814. case 1:
  815. case 2:
  816. case 3:
  817. {
  818. int as = a->getInitiative(turn);
  819. int bs = b->getInitiative(turn);
  820. if(as != bs)
  821. return as > bs;
  822. if(a->unitSide() == b->unitSide())
  823. return a->unitSlot() < b->unitSlot();
  824. return (a->unitSide() == side || b->unitSide() == side)
  825. ? a->unitSide() != side
  826. : a->unitSide() < b->unitSide();
  827. }
  828. default:
  829. assert(false);
  830. return false;
  831. }
  832. assert(false);
  833. return false;
  834. }
  835. CMP_stack::CMP_stack(int Phase, int Turn, BattleSide Side):
  836. phase(Phase),
  837. turn(Turn),
  838. side(Side)
  839. {
  840. }
  841. VCMI_LIB_NAMESPACE_END