BattleInfo.cpp 27 KB

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