BattleInfo.cpp 26 KB

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