BattleInfo.cpp 27 KB

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