BattleInfo.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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 "../entities/building/TownFortifications.h"
  18. #include "../filesystem/Filesystem.h"
  19. #include "../GameLibrary.h"
  20. #include "../mapObjects/CGTownInstance.h"
  21. #include "../texts/CGeneralTextHandler.h"
  22. #include "../BattleFieldHandler.h"
  23. #include "../ObstacleHandler.h"
  24. #include <vstd/RNG.h>
  25. //TODO: remove
  26. #include "../IGameCallback.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(IGameCallback *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. }
  294. }
  295. //adding commanders
  296. for(BattleSide i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  297. {
  298. if (heroes[i] && heroes[i]->getCommander() && heroes[i]->getCommander()->alive)
  299. {
  300. currentBattle->generateNewStack(currentBattle->nextUnitId(), *heroes[i]->getCommander(), i, SlotID::COMMANDER_SLOT_PLACEHOLDER, layout.commanders.at(i));
  301. }
  302. }
  303. if (currentBattle->townID.hasValue())
  304. {
  305. if (currentBattle->getTown()->fortificationsLevel().citadelHealth != 0)
  306. currentBattle->generateNewStack(currentBattle->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
  307. if (currentBattle->getTown()->fortificationsLevel().upperTowerHealth != 0)
  308. currentBattle->generateNewStack(currentBattle->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
  309. if (currentBattle->getTown()->fortificationsLevel().lowerTowerHealth != 0)
  310. currentBattle->generateNewStack(currentBattle->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
  311. //Moat generating is done on server
  312. }
  313. std::stable_sort(currentBattle->stacks.begin(), currentBattle->stacks.end(), [cmpst](const auto & left, const auto & right){ return cmpst(left.get(), right.get());});
  314. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  315. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  316. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  317. const auto * bgInfo = LIBRARY->battlefields()->getById(battlefieldType);
  318. for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
  319. {
  320. currentBattle->addNewBonus(bonus);
  321. }
  322. //native terrain bonuses
  323. auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
  324. currentBattle->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::STACKS_SPEED, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID())->addLimiter(nativeTerrain));
  325. currentBattle->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::ATTACK))->addLimiter(nativeTerrain));
  326. currentBattle->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE))->addLimiter(nativeTerrain));
  327. //////////////////////////////////////////////////////////////////////////
  328. //tactics
  329. BattleSideArray<int> battleRepositionHex = {};
  330. BattleSideArray<int> battleRepositionHexBlock = {};
  331. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  332. {
  333. if(heroes[i])
  334. {
  335. battleRepositionHex[i] += heroes[i]->valOfBonuses(BonusType::BEFORE_BATTLE_REPOSITION);
  336. battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(BonusType::BEFORE_BATTLE_REPOSITION_BLOCK);
  337. }
  338. }
  339. int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
  340. int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
  341. /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
  342. when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
  343. will not happen because tactics block opposite tactics on same value.
  344. TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
  345. double tactics will be implemented.
  346. */
  347. if(layout.tacticsAllowed)
  348. {
  349. if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
  350. logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
  351. if(tacticsSkillDiffAttacker > 0)
  352. {
  353. currentBattle->tacticsSide = BattleSide::ATTACKER;
  354. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  355. currentBattle->tacticDistance = 1 + tacticsSkillDiffAttacker;
  356. }
  357. else if(tacticsSkillDiffDefender > 0)
  358. {
  359. currentBattle->tacticsSide = BattleSide::DEFENDER;
  360. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  361. currentBattle->tacticDistance = 1 + tacticsSkillDiffDefender;
  362. }
  363. else
  364. currentBattle->tacticDistance = 0;
  365. }
  366. return currentBattle;
  367. }
  368. const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
  369. {
  370. for(const auto & side : sides)
  371. if(side.color == player)
  372. return side.getHero();
  373. logGlobal->error("Player %s is not in battle!", player.toString());
  374. return nullptr;
  375. }
  376. BattleSide BattleInfo::whatSide(const PlayerColor & player) const
  377. {
  378. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  379. if(sides[i].color == player)
  380. return i;
  381. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.toString());
  382. return BattleSide::NONE;
  383. }
  384. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  385. {
  386. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  387. }
  388. BattleInfo::BattleInfo(IGameCallback *cb, const BattleLayout & layout):
  389. BattleInfo(cb)
  390. {
  391. *this->layout = layout;
  392. }
  393. BattleInfo::BattleInfo(IGameCallback *cb)
  394. :GameCallbackHolder(cb),
  395. sides({SideInBattle(cb), SideInBattle(cb)}),
  396. layout(std::make_unique<BattleLayout>()),
  397. round(-1),
  398. activeStack(-1),
  399. tile(-1,-1,-1),
  400. battlefieldType(BattleField::NONE),
  401. tacticsSide(BattleSide::NONE),
  402. tacticDistance(0)
  403. {
  404. setNodeType(BATTLE);
  405. }
  406. BattleLayout BattleInfo::getLayout() const
  407. {
  408. return *layout;
  409. }
  410. BattleID BattleInfo::getBattleID() const
  411. {
  412. return battleID;
  413. }
  414. const IBattleInfo * BattleInfo::getBattle() const
  415. {
  416. return this;
  417. }
  418. std::optional<PlayerColor> BattleInfo::getPlayerID() const
  419. {
  420. return std::nullopt;
  421. }
  422. BattleInfo::~BattleInfo()
  423. {
  424. stacks.clear();
  425. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  426. if(auto * _armyObj = battleGetArmyObject(i))
  427. _armyObj->battle = nullptr;
  428. }
  429. int32_t BattleInfo::getActiveStackID() const
  430. {
  431. return activeStack;
  432. }
  433. TStacks BattleInfo::getStacksIf(const TStackFilter & predicate) const
  434. {
  435. TStacks ret;
  436. for (const auto & stack : stacks)
  437. if (predicate(stack.get()))
  438. ret.push_back(stack.get());
  439. return ret;
  440. }
  441. battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
  442. {
  443. battle::Units ret;
  444. for (const auto & stack : stacks)
  445. if (predicate(stack.get()))
  446. ret.push_back(stack.get());
  447. return ret;
  448. }
  449. BattleField BattleInfo::getBattlefieldType() const
  450. {
  451. return battlefieldType;
  452. }
  453. TerrainId BattleInfo::getTerrainType() const
  454. {
  455. return terrainType;
  456. }
  457. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  458. {
  459. ObstacleCList ret;
  460. for(const auto & obstacle : obstacles)
  461. ret.push_back(obstacle);
  462. return ret;
  463. }
  464. PlayerColor BattleInfo::getSidePlayer(BattleSide side) const
  465. {
  466. return getSide(side).color;
  467. }
  468. const CArmedInstance * BattleInfo::getSideArmy(BattleSide side) const
  469. {
  470. return getSide(side).getArmy();
  471. }
  472. const CGHeroInstance * BattleInfo::getSideHero(BattleSide side) const
  473. {
  474. return getSide(side).getHero();
  475. }
  476. const CGTownInstance * BattleInfo::getTown() const
  477. {
  478. if (townID.hasValue())
  479. return cb->getTown(townID);
  480. return nullptr;
  481. }
  482. uint8_t BattleInfo::getTacticDist() const
  483. {
  484. return tacticDistance;
  485. }
  486. BattleSide BattleInfo::getTacticsSide() const
  487. {
  488. return tacticsSide;
  489. }
  490. const CGTownInstance * BattleInfo::getDefendedTown() const
  491. {
  492. if (townID.hasValue())
  493. return cb->getTown(townID);
  494. return nullptr;
  495. }
  496. EWallState BattleInfo::getWallState(EWallPart partOfWall) const
  497. {
  498. return si.wallState.at(partOfWall);
  499. }
  500. EGateState BattleInfo::getGateState() const
  501. {
  502. return si.gateState;
  503. }
  504. uint32_t BattleInfo::getCastSpells(BattleSide side) const
  505. {
  506. return getSide(side).castSpellsCount;
  507. }
  508. int32_t BattleInfo::getEnchanterCounter(BattleSide side) const
  509. {
  510. return getSide(side).enchanterCounter;
  511. }
  512. const IBonusBearer * BattleInfo::getBonusBearer() const
  513. {
  514. return this;
  515. }
  516. int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  517. {
  518. if(damage.min != damage.max)
  519. {
  520. int64_t sum = 0;
  521. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  522. for(int32_t g = 0; g < howManyToAv; ++g)
  523. sum += rng.nextInt64(damage.min, damage.max);
  524. return sum / howManyToAv;
  525. }
  526. else
  527. {
  528. return damage.min;
  529. }
  530. }
  531. int3 BattleInfo::getLocation() const
  532. {
  533. return tile;
  534. }
  535. std::vector<SpellID> BattleInfo::getUsedSpells(BattleSide side) const
  536. {
  537. return getSide(side).usedSpellsHistory;
  538. }
  539. void BattleInfo::nextRound()
  540. {
  541. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  542. {
  543. sides.at(i).castSpellsCount = 0;
  544. vstd::amax(--sides.at(i).enchanterCounter, 0);
  545. }
  546. round += 1;
  547. for(auto & s : stacks)
  548. {
  549. // new turn effects
  550. s->reduceBonusDurations(Bonus::NTurns);
  551. s->afterNewRound();
  552. }
  553. for(auto & obst : obstacles)
  554. obst->battleTurnPassed();
  555. }
  556. void BattleInfo::nextTurn(uint32_t unitId, BattleUnitTurnReason reason)
  557. {
  558. activeStack = unitId;
  559. CStack * st = getStack(activeStack);
  560. //remove bonuses that last until when stack gets new turn
  561. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  562. st->afterGetsTurn(reason);
  563. }
  564. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  565. {
  566. battle::UnitInfo info;
  567. info.load(id, data);
  568. CStackBasicDescriptor base(info.type, info.count);
  569. PlayerColor owner = getSidePlayer(info.side);
  570. auto ret = std::make_unique<CStack>(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  571. ret->initialPosition = info.position;
  572. stacks.push_back(std::move(ret));
  573. stacks.back()->localInit(this);
  574. stacks.back()->summoned = info.summoned;
  575. }
  576. void BattleInfo::moveUnit(uint32_t id, const BattleHex & destination)
  577. {
  578. auto * sta = getStack(id);
  579. if(!sta)
  580. {
  581. logGlobal->error("Cannot find stack %d", id);
  582. return;
  583. }
  584. sta->position = destination;
  585. //Bonuses can be limited by unit placement, so, change tree version
  586. //to force updating a bonus. TODO: update version only when such bonuses are present
  587. nodeHasChanged();
  588. }
  589. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  590. {
  591. CStack * changedStack = getStack(id, false);
  592. if(!changedStack)
  593. throw std::runtime_error("Invalid unit id in BattleInfo update");
  594. if(!changedStack->alive() && healthDelta > 0)
  595. {
  596. //checking if we resurrect a stack that is under a living stack
  597. auto accessibility = getAccessibility();
  598. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  599. {
  600. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition());
  601. return; //position is already occupied
  602. }
  603. }
  604. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  605. bool resurrected = !changedStack->alive() && healthDelta > 0;
  606. //applying changes
  607. changedStack->load(data);
  608. if(healthDelta < 0)
  609. {
  610. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  611. }
  612. resurrected = resurrected || (killed && changedStack->alive());
  613. if(killed)
  614. {
  615. if(changedStack->cloneID >= 0)
  616. {
  617. //remove clone as well
  618. CStack * clone = getStack(changedStack->cloneID);
  619. if(clone)
  620. clone->makeGhost();
  621. changedStack->cloneID = -1;
  622. }
  623. }
  624. if(resurrected || killed)
  625. {
  626. //removing all spells effects
  627. auto selector = [](const Bonus * b)
  628. {
  629. //Special case: DISRUPTING_RAY is absolutely permanent
  630. return b->source == BonusSource::SPELL_EFFECT && b->sid.as<SpellID>() != SpellID::DISRUPTING_RAY;
  631. };
  632. changedStack->removeBonusesRecursive(selector);
  633. }
  634. if(!changedStack->alive() && changedStack->isClone())
  635. {
  636. for(auto & s : stacks)
  637. {
  638. if(s->cloneID == changedStack->unitId())
  639. s->cloneID = -1;
  640. }
  641. }
  642. }
  643. void BattleInfo::removeUnit(uint32_t id)
  644. {
  645. std::set<uint32_t> ids;
  646. ids.insert(id);
  647. while(!ids.empty())
  648. {
  649. auto toRemoveId = *ids.begin();
  650. auto * toRemove = getStack(toRemoveId, false);
  651. if(!toRemove)
  652. {
  653. logGlobal->error("Cannot find stack %d", toRemoveId);
  654. return;
  655. }
  656. if(!toRemove->ghost)
  657. {
  658. toRemove->onRemoved();
  659. toRemove->detachFromAll();
  660. //stack may be removed instantly (not being killed first)
  661. //handle clone remove also here
  662. if(toRemove->cloneID >= 0)
  663. {
  664. ids.insert(toRemove->cloneID);
  665. toRemove->cloneID = -1;
  666. }
  667. //cleanup remaining clone links if any
  668. for(const auto & s : stacks)
  669. {
  670. if(s->cloneID == toRemoveId)
  671. s->cloneID = -1;
  672. }
  673. }
  674. ids.erase(toRemoveId);
  675. }
  676. }
  677. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  678. {
  679. //TODO
  680. }
  681. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  682. {
  683. CStack * sta = getStack(id, false);
  684. if(!sta)
  685. {
  686. logGlobal->error("Cannot find stack %d", id);
  687. return;
  688. }
  689. for(const Bonus & b : bonus)
  690. addOrUpdateUnitBonus(sta, b, true);
  691. }
  692. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  693. {
  694. CStack * sta = getStack(id, false);
  695. if(!sta)
  696. {
  697. logGlobal->error("Cannot find stack %d", id);
  698. return;
  699. }
  700. for(const Bonus & b : bonus)
  701. addOrUpdateUnitBonus(sta, b, false);
  702. }
  703. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  704. {
  705. CStack * sta = getStack(id, false);
  706. if(!sta)
  707. {
  708. logGlobal->error("Cannot find stack %d", id);
  709. return;
  710. }
  711. for(const Bonus & one : bonus)
  712. {
  713. auto selector = [one](const Bonus * b)
  714. {
  715. //compare everything but turnsRemain, limiter and propagator
  716. return one.duration == b->duration
  717. && one.type == b->type
  718. && one.subtype == b->subtype
  719. && one.source == b->source
  720. && one.val == b->val
  721. && one.sid == b->sid
  722. && one.valType == b->valType
  723. && one.additionalInfo == b->additionalInfo
  724. && one.effectRange == b->effectRange;
  725. };
  726. sta->removeBonusesRecursive(selector);
  727. }
  728. }
  729. uint32_t BattleInfo::nextUnitId() const
  730. {
  731. return static_cast<uint32_t>(stacks.size());
  732. }
  733. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  734. {
  735. if(forceAdd || !sta->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, value.sid).And(Selector::typeSubtypeValueType(value.type, value.subtype, value.valType))))
  736. {
  737. //no such effect or cumulative - add new
  738. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description(nullptr));
  739. sta->addNewBonus(std::make_shared<Bonus>(value));
  740. }
  741. else
  742. {
  743. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description(nullptr));
  744. for(const auto & stackBonus : sta->getExportedBonusList()) //TODO: optimize
  745. {
  746. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype && stackBonus->valType == value.valType)
  747. {
  748. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  749. }
  750. }
  751. sta->nodeHasChanged();
  752. }
  753. }
  754. void BattleInfo::setWallState(EWallPart partOfWall, EWallState state)
  755. {
  756. si.wallState[partOfWall] = state;
  757. }
  758. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  759. {
  760. auto obstacle = std::make_shared<SpellCreatedObstacle>();
  761. obstacle->fromInfo(changes);
  762. obstacles.push_back(obstacle);
  763. }
  764. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  765. {
  766. auto changedObstacle = std::make_shared<SpellCreatedObstacle>();
  767. changedObstacle->fromInfo(changes);
  768. for(auto & obstacle : obstacles)
  769. {
  770. if(obstacle->uniqueID == changes.id) // update this obstacle
  771. {
  772. auto * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacle.get());
  773. assert(spellObstacle);
  774. // Currently we only support to update the "revealed" property
  775. spellObstacle->revealed = changedObstacle->revealed;
  776. break;
  777. }
  778. }
  779. }
  780. void BattleInfo::removeObstacle(uint32_t id)
  781. {
  782. for(int i=0; i < obstacles.size(); ++i)
  783. {
  784. if(obstacles[i]->uniqueID == id) //remove this obstacle
  785. {
  786. obstacles.erase(obstacles.begin() + i);
  787. break;
  788. }
  789. }
  790. }
  791. CArmedInstance * BattleInfo::battleGetArmyObject(BattleSide side) const
  792. {
  793. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  794. }
  795. CGHeroInstance * BattleInfo::battleGetFightingHero(BattleSide side) const
  796. {
  797. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  798. }
  799. void BattleInfo::postDeserialize()
  800. {
  801. for (const auto & unit : stacks)
  802. unit->postDeserialize(getSideArmy(unit->unitSide()));
  803. }
  804. #if SCRIPTING_ENABLED
  805. scripting::Pool * BattleInfo::getContextPool() const
  806. {
  807. //this is real battle, use global scripting context pool
  808. //TODO: make this line not ugly
  809. return battleGetFightingHero(BattleSide::ATTACKER)->cb->getGlobalContextPool();
  810. }
  811. #endif
  812. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
  813. {
  814. switch(phase)
  815. {
  816. case 0: //catapult moves after turrets
  817. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  818. case 1:
  819. case 2:
  820. case 3:
  821. {
  822. int as = a->getInitiative(turn);
  823. int bs = b->getInitiative(turn);
  824. if(as != bs)
  825. return as > bs;
  826. if(a->unitSide() == b->unitSide())
  827. return a->unitSlot() < b->unitSlot();
  828. return (a->unitSide() == side || b->unitSide() == side)
  829. ? a->unitSide() != side
  830. : a->unitSide() < b->unitSide();
  831. }
  832. default:
  833. assert(false);
  834. return false;
  835. }
  836. assert(false);
  837. return false;
  838. }
  839. CMP_stack::CMP_stack(int Phase, int Turn, BattleSide Side):
  840. phase(Phase),
  841. turn(Turn),
  842. side(Side)
  843. {
  844. }
  845. VCMI_LIB_NAMESPACE_END