BattleInfo.cpp 27 KB

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