BattleInfo.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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 "../CHeroHandler.h"
  18. #include "../entities/building/TownFortifications.h"
  19. #include "../filesystem/Filesystem.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. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, BattleSide side, const SlotID & slot, BattleHex position)
  38. {
  39. PlayerColor owner = getSide(side).color;
  40. assert(!owner.isValidPlayer() || (base.armyObj && base.armyObj->tempOwner == owner));
  41. auto * ret = new CStack(&base, owner, id, side, slot);
  42. ret->initialPosition = getAvailableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
  43. stacks.push_back(ret);
  44. return ret;
  45. }
  46. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, BattleSide side, const SlotID & slot, BattleHex position)
  47. {
  48. PlayerColor owner = getSide(side).color;
  49. auto * ret = new CStack(&base, owner, id, side, slot);
  50. ret->initialPosition = position;
  51. stacks.push_back(ret);
  52. return ret;
  53. }
  54. void BattleInfo::localInit()
  55. {
  56. for(BattleSide i : { BattleSide::ATTACKER, BattleSide::DEFENDER})
  57. {
  58. auto * armyObj = battleGetArmyObject(i);
  59. armyObj->battle = this;
  60. armyObj->attachTo(*this);
  61. }
  62. for(CStack * s : stacks)
  63. s->localInit(this);
  64. exportBonuses();
  65. }
  66. //RNG that works like H3 one
  67. struct RandGen
  68. {
  69. ui32 seed;
  70. void srand(ui32 s)
  71. {
  72. seed = s;
  73. }
  74. void srand(const int3 & pos)
  75. {
  76. srand(110291 * static_cast<ui32>(pos.x) + 167801 * static_cast<ui32>(pos.y) + 81569);
  77. }
  78. int rand()
  79. {
  80. seed = 214013 * seed + 2531011;
  81. return (seed >> 16) & 0x7FFF;
  82. }
  83. int rand(int min, int max)
  84. {
  85. if(min == max)
  86. return min;
  87. if(min > max)
  88. return min;
  89. return min + rand() % (max - min + 1);
  90. }
  91. };
  92. struct RangeGenerator
  93. {
  94. class ExhaustedPossibilities : public std::exception
  95. {
  96. };
  97. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  98. min(_min),
  99. remainingCount(_max - _min + 1),
  100. remaining(remainingCount, true),
  101. myRand(std::move(_myRand))
  102. {
  103. }
  104. int generateNumber() const
  105. {
  106. if(!remainingCount)
  107. throw ExhaustedPossibilities();
  108. if(remainingCount == 1)
  109. return 0;
  110. return myRand() % remainingCount;
  111. }
  112. //get number fulfilling predicate. Never gives the same number twice.
  113. int getSuchNumber(const std::function<bool(int)> & goodNumberPred = nullptr)
  114. {
  115. int ret = -1;
  116. do
  117. {
  118. int n = generateNumber();
  119. int i = 0;
  120. for(;;i++)
  121. {
  122. assert(i < (int)remaining.size());
  123. if(!remaining[i])
  124. continue;
  125. if(!n)
  126. break;
  127. n--;
  128. }
  129. remainingCount--;
  130. remaining[i] = false;
  131. ret = i + min;
  132. } while(goodNumberPred && !goodNumberPred(ret));
  133. return ret;
  134. }
  135. int min;
  136. int remainingCount;
  137. std::vector<bool> remaining;
  138. std::function<int()> myRand;
  139. };
  140. BattleInfo * BattleInfo::setupBattle(const int3 & tile, TerrainId terrain, const BattleField & battlefieldType, BattleSideArray<const CArmedInstance *> armies, BattleSideArray<const CGHeroInstance *> heroes, const BattleLayout & layout, const CGTownInstance * town)
  141. {
  142. CMP_stack cmpst;
  143. auto * curB = new BattleInfo(layout);
  144. for(auto i : { BattleSide::LEFT_SIDE, BattleSide::RIGHT_SIDE})
  145. curB->sides[i].init(heroes[i], armies[i]);
  146. std::vector<CStack*> & stacks = (curB->stacks);
  147. curB->tile = tile;
  148. curB->battlefieldType = battlefieldType;
  149. curB->round = -2;
  150. curB->activeStack = -1;
  151. curB->replayAllowed = false;
  152. if(town)
  153. {
  154. curB->town = town;
  155. curB->terrainType = town->getNativeTerrain();
  156. }
  157. else
  158. {
  159. curB->town = nullptr;
  160. curB->terrainType = terrain;
  161. }
  162. //setting up siege obstacles
  163. if (town && town->fortificationsLevel().wallsHealth != 0)
  164. {
  165. auto fortification = town->fortificationsLevel();
  166. curB->si.gateState = EGateState::CLOSED;
  167. curB->si.wallState[EWallPart::GATE] = EWallState::INTACT;
  168. for(const auto wall : {EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL})
  169. curB->si.wallState[wall] = static_cast<EWallState>(fortification.wallsHealth);
  170. if (fortification.citadelHealth != 0)
  171. curB->si.wallState[EWallPart::KEEP] = static_cast<EWallState>(fortification.citadelHealth);
  172. if (fortification.upperTowerHealth != 0)
  173. curB->si.wallState[EWallPart::UPPER_TOWER] = static_cast<EWallState>(fortification.upperTowerHealth);
  174. if (fortification.lowerTowerHealth != 0)
  175. curB->si.wallState[EWallPart::BOTTOM_TOWER] = static_cast<EWallState>(fortification.lowerTowerHealth);
  176. }
  177. //randomize obstacles
  178. if (layout.obstaclesAllowed)
  179. {
  180. RandGen r{};
  181. auto ourRand = [&](){ return r.rand(); };
  182. r.srand(tile);
  183. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  184. int tilesToBlock = r.rand(5,12);
  185. std::vector<BattleHex> blockedTiles;
  186. auto appropriateAbsoluteObstacle = [&](int id)
  187. {
  188. const auto * info = Obstacle(id).getInfo();
  189. return info && info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
  190. };
  191. auto appropriateUsualObstacle = [&](int id)
  192. {
  193. const auto * info = Obstacle(id).getInfo();
  194. return info && !info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
  195. };
  196. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  197. {
  198. try
  199. {
  200. RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
  201. auto obstPtr = std::make_shared<CObstacleInstance>();
  202. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  203. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  204. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  205. curB->obstacles.push_back(obstPtr);
  206. for(BattleHex blocked : obstPtr->getBlockedTiles())
  207. blockedTiles.push_back(blocked);
  208. tilesToBlock -= Obstacle(obstPtr->ID).getInfo()->blockedTiles.size() / 2;
  209. }
  210. catch(RangeGenerator::ExhaustedPossibilities &)
  211. {
  212. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  213. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place absolute obstacle");
  214. }
  215. }
  216. try
  217. {
  218. while(tilesToBlock > 0)
  219. {
  220. RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
  221. auto tileAccessibility = curB->getAccessibility();
  222. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  223. const ObstacleInfo &obi = *Obstacle(obid).getInfo();
  224. auto validPosition = [&](BattleHex pos) -> bool
  225. {
  226. if(obi.height >= pos.getY())
  227. return false;
  228. if(pos.getX() == 0)
  229. return false;
  230. if(pos.getX() + obi.width > 15)
  231. return false;
  232. if(vstd::contains(blockedTiles, pos))
  233. return false;
  234. for(BattleHex blocked : obi.getBlocked(pos))
  235. {
  236. if(tileAccessibility[blocked] == EAccessibility::UNAVAILABLE) //for ship-to-ship battlefield - exclude hardcoded unavailable tiles
  237. return false;
  238. if(vstd::contains(blockedTiles, blocked))
  239. return false;
  240. int x = blocked.getX();
  241. if(x <= 2 || x >= 14)
  242. return false;
  243. }
  244. return true;
  245. };
  246. RangeGenerator posgenerator(18, 168, ourRand);
  247. auto obstPtr = std::make_shared<CObstacleInstance>();
  248. obstPtr->ID = obid;
  249. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  250. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  251. curB->obstacles.push_back(obstPtr);
  252. for(BattleHex blocked : obstPtr->getBlockedTiles())
  253. blockedTiles.push_back(blocked);
  254. tilesToBlock -= static_cast<int>(obi.blockedTiles.size());
  255. }
  256. }
  257. catch(RangeGenerator::ExhaustedPossibilities &)
  258. {
  259. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place usual obstacle");
  260. }
  261. }
  262. //adding war machines
  263. //Checks if hero has artifact and create appropriate stack
  264. auto handleWarMachine = [&](BattleSide side, const ArtifactPosition & artslot, BattleHex hex)
  265. {
  266. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  267. if(nullptr != warMachineArt && hex.isValid())
  268. {
  269. CreatureID cre = warMachineArt->artType->getWarMachine();
  270. if(cre != CreatureID::NONE)
  271. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex);
  272. }
  273. };
  274. if(heroes[BattleSide::ATTACKER])
  275. {
  276. auto warMachineHexes = layout.warMachines.at(BattleSide::ATTACKER);
  277. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH1, warMachineHexes.at(0));
  278. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH2, warMachineHexes.at(1));
  279. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH3, warMachineHexes.at(2));
  280. if(town && town->fortificationsLevel().wallsHealth > 0)
  281. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH4, warMachineHexes.at(3));
  282. }
  283. if(heroes[BattleSide::DEFENDER])
  284. {
  285. auto warMachineHexes = layout.warMachines.at(BattleSide::DEFENDER);
  286. if(!town) //defending hero shouldn't receive ballista (bug #551)
  287. handleWarMachine(BattleSide::DEFENDER, ArtifactPosition::MACH1, warMachineHexes.at(0));
  288. handleWarMachine(BattleSide::DEFENDER, ArtifactPosition::MACH2, warMachineHexes.at(1));
  289. handleWarMachine(BattleSide::DEFENDER, ArtifactPosition::MACH3, warMachineHexes.at(2));
  290. }
  291. //war machines added
  292. //battleStartpos read
  293. for(BattleSide side : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  294. {
  295. int formationNo = armies[side]->stacksCount() - 1;
  296. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  297. int k = 0; //stack serial
  298. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  299. {
  300. const BattleHex & pos = layout.units.at(side).at(k);
  301. //if(creatureBank && i->second->type->isDoubleWide())
  302. // pos += side == BattleSide::RIGHT_SIDE ? BattleHex::LEFT : BattleHex::RIGHT;
  303. if (pos.isValid())
  304. curB->generateNewStack(curB->nextUnitId(), *i->second, side, i->first, pos);
  305. }
  306. }
  307. //adding commanders
  308. for(BattleSide i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  309. {
  310. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  311. {
  312. curB->generateNewStack(curB->nextUnitId(), *heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER, layout.commanders.at(i));
  313. }
  314. }
  315. if (curB->town)
  316. {
  317. if (curB->town->fortificationsLevel().citadelHealth != 0)
  318. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
  319. if (curB->town->fortificationsLevel().upperTowerHealth != 0)
  320. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
  321. if (curB->town->fortificationsLevel().lowerTowerHealth != 0)
  322. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
  323. //Moat generating is done on server
  324. }
  325. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  326. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  327. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  328. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  329. const auto * bgInfo = VLC->battlefields()->getById(battlefieldType);
  330. for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
  331. {
  332. curB->addNewBonus(bonus);
  333. }
  334. //native terrain bonuses
  335. auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
  336. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::STACKS_SPEED, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID())->addLimiter(nativeTerrain));
  337. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::ATTACK))->addLimiter(nativeTerrain));
  338. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE))->addLimiter(nativeTerrain));
  339. //////////////////////////////////////////////////////////////////////////
  340. //tactics
  341. BattleSideArray<int> battleRepositionHex = {};
  342. BattleSideArray<int> battleRepositionHexBlock = {};
  343. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  344. {
  345. if(heroes[i])
  346. {
  347. battleRepositionHex[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION));
  348. battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION_BLOCK));
  349. }
  350. }
  351. int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
  352. int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
  353. /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
  354. when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
  355. will not happen because tactics block opposite tactics on same value.
  356. TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
  357. double tactics will be implemented.
  358. */
  359. if(layout.tacticsAllowed)
  360. {
  361. if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
  362. logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
  363. if(tacticsSkillDiffAttacker > 0)
  364. {
  365. curB->tacticsSide = BattleSide::ATTACKER;
  366. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  367. curB->tacticDistance = 1 + tacticsSkillDiffAttacker;
  368. }
  369. else if(tacticsSkillDiffDefender > 0)
  370. {
  371. curB->tacticsSide = BattleSide::DEFENDER;
  372. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  373. curB->tacticDistance = 1 + tacticsSkillDiffDefender;
  374. }
  375. else
  376. curB->tacticDistance = 0;
  377. }
  378. return curB;
  379. }
  380. const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
  381. {
  382. for(const auto & side : sides)
  383. if(side.color == player)
  384. return side.hero;
  385. logGlobal->error("Player %s is not in battle!", player.toString());
  386. return nullptr;
  387. }
  388. BattleSide BattleInfo::whatSide(const PlayerColor & player) const
  389. {
  390. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  391. if(sides[i].color == player)
  392. return i;
  393. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.toString());
  394. return BattleSide::NONE;
  395. }
  396. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  397. {
  398. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  399. }
  400. BattleInfo::BattleInfo(const BattleLayout & layout):
  401. BattleInfo()
  402. {
  403. *this->layout = layout;
  404. }
  405. BattleInfo::BattleInfo():
  406. round(-1),
  407. activeStack(-1),
  408. town(nullptr),
  409. tile(-1,-1,-1),
  410. layout(std::make_unique<BattleLayout>()),
  411. battlefieldType(BattleField::NONE),
  412. tacticsSide(BattleSide::NONE),
  413. tacticDistance(0)
  414. {
  415. setNodeType(BATTLE);
  416. }
  417. BattleLayout BattleInfo::getLayout() const
  418. {
  419. return *layout;
  420. }
  421. BattleID BattleInfo::getBattleID() const
  422. {
  423. return battleID;
  424. }
  425. const IBattleInfo * BattleInfo::getBattle() const
  426. {
  427. return this;
  428. }
  429. std::optional<PlayerColor> BattleInfo::getPlayerID() const
  430. {
  431. return std::nullopt;
  432. }
  433. BattleInfo::~BattleInfo()
  434. {
  435. for (auto & elem : stacks)
  436. delete elem;
  437. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  438. if(auto * _armyObj = battleGetArmyObject(i))
  439. _armyObj->battle = nullptr;
  440. }
  441. int32_t BattleInfo::getActiveStackID() const
  442. {
  443. return activeStack;
  444. }
  445. TStacks BattleInfo::getStacksIf(const TStackFilter & predicate) const
  446. {
  447. TStacks ret;
  448. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  449. return ret;
  450. }
  451. battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
  452. {
  453. battle::Units ret;
  454. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  455. return ret;
  456. }
  457. BattleField BattleInfo::getBattlefieldType() const
  458. {
  459. return battlefieldType;
  460. }
  461. TerrainId BattleInfo::getTerrainType() const
  462. {
  463. return terrainType;
  464. }
  465. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  466. {
  467. ObstacleCList ret;
  468. for(const auto & obstacle : obstacles)
  469. ret.push_back(obstacle);
  470. return ret;
  471. }
  472. PlayerColor BattleInfo::getSidePlayer(BattleSide side) const
  473. {
  474. return getSide(side).color;
  475. }
  476. const CArmedInstance * BattleInfo::getSideArmy(BattleSide side) const
  477. {
  478. return getSide(side).armyObject;
  479. }
  480. const CGHeroInstance * BattleInfo::getSideHero(BattleSide side) const
  481. {
  482. return getSide(side).hero;
  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. return town;
  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(CStack * 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)
  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();
  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 = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  571. ret->initialPosition = info.position;
  572. stacks.push_back(ret);
  573. ret->localInit(this);
  574. ret->summoned = info.summoned;
  575. }
  576. void BattleInfo::moveUnit(uint32_t id, 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. CBonusSystemNode::treeHasChanged();
  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().hex);
  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(CStack * 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(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());
  739. sta->addNewBonus(std::make_shared<Bonus>(value));
  740. }
  741. else
  742. {
  743. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description());
  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. CBonusSystemNode::treeHasChanged();
  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. #if SCRIPTING_ENABLED
  800. scripting::Pool * BattleInfo::getContextPool() const
  801. {
  802. //this is real battle, use global scripting context pool
  803. //TODO: make this line not ugly
  804. return battleGetFightingHero(BattleSide::ATTACKER)->cb->getGlobalContextPool();
  805. }
  806. #endif
  807. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
  808. {
  809. switch(phase)
  810. {
  811. case 0: //catapult moves after turrets
  812. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  813. case 1:
  814. case 2:
  815. case 3:
  816. {
  817. int as = a->getInitiative(turn);
  818. int bs = b->getInitiative(turn);
  819. if(as != bs)
  820. return as > bs;
  821. if(a->unitSide() == b->unitSide())
  822. return a->unitSlot() < b->unitSlot();
  823. return (a->unitSide() == side || b->unitSide() == side)
  824. ? a->unitSide() != side
  825. : a->unitSide() < b->unitSide();
  826. }
  827. default:
  828. assert(false);
  829. return false;
  830. }
  831. assert(false);
  832. return false;
  833. }
  834. CMP_stack::CMP_stack(int Phase, int Turn, BattleSide Side):
  835. phase(Phase),
  836. turn(Turn),
  837. side(Side)
  838. {
  839. }
  840. VCMI_LIB_NAMESPACE_END