123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056 |
- /*
- * BattleInfo.cpp, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
- #include "StdInc.h"
- #include "BattleInfo.h"
- #include "CObstacleInstance.h"
- #include "bonuses/Limiters.h"
- #include "bonuses/Updaters.h"
- #include "../CRandomGenerator.h"
- #include "../CStack.h"
- #include "../CHeroHandler.h"
- #include "../filesystem/Filesystem.h"
- #include "../mapObjects/CGTownInstance.h"
- #include "../CGeneralTextHandler.h"
- #include "../BattleFieldHandler.h"
- #include "../ObstacleHandler.h"
- //TODO: remove
- #include "../IGameCallback.h"
- VCMI_LIB_NAMESPACE_BEGIN
- ///BattleInfo
- CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, ui8 side, const SlotID & slot, BattleHex position)
- {
- PlayerColor owner = sides[side].color;
- assert(!owner.isValidPlayer() || (base.armyObj && base.armyObj->tempOwner == owner));
- auto * ret = new CStack(&base, owner, id, side, slot);
- ret->initialPosition = getAvaliableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
- stacks.push_back(ret);
- return ret;
- }
- CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, ui8 side, const SlotID & slot, BattleHex position)
- {
- PlayerColor owner = sides[side].color;
- auto * ret = new CStack(&base, owner, id, side, slot);
- ret->initialPosition = position;
- stacks.push_back(ret);
- return ret;
- }
- void BattleInfo::localInit()
- {
- for(int i = 0; i < 2; i++)
- {
- auto * armyObj = battleGetArmyObject(i);
- armyObj->battle = this;
- armyObj->attachTo(*this);
- }
- for(CStack * s : stacks)
- s->localInit(this);
- exportBonuses();
- }
- namespace CGH
- {
- static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
- {
- for(const JsonNode &level : node.Vector())
- {
- std::vector<int> pom;
- for(const JsonNode &value : level.Vector())
- {
- pom.push_back(static_cast<int>(value.Float()));
- }
- dest.push_back(pom);
- }
- }
- }
- //RNG that works like H3 one
- struct RandGen
- {
- ui32 seed;
- void srand(ui32 s)
- {
- seed = s;
- }
- void srand(const int3 & pos)
- {
- srand(110291 * static_cast<ui32>(pos.x) + 167801 * static_cast<ui32>(pos.y) + 81569);
- }
- int rand()
- {
- seed = 214013 * seed + 2531011;
- return (seed >> 16) & 0x7FFF;
- }
- int rand(int min, int max)
- {
- if(min == max)
- return min;
- if(min > max)
- return min;
- return min + rand() % (max - min + 1);
- }
- };
- struct RangeGenerator
- {
- class ExhaustedPossibilities : public std::exception
- {
- };
- RangeGenerator(int _min, int _max, std::function<int()> _myRand):
- min(_min),
- remainingCount(_max - _min + 1),
- remaining(remainingCount, true),
- myRand(std::move(_myRand))
- {
- }
- int generateNumber() const
- {
- if(!remainingCount)
- throw ExhaustedPossibilities();
- if(remainingCount == 1)
- return 0;
- return myRand() % remainingCount;
- }
- //get number fulfilling predicate. Never gives the same number twice.
- int getSuchNumber(const std::function<bool(int)> & goodNumberPred = nullptr)
- {
- int ret = -1;
- do
- {
- int n = generateNumber();
- int i = 0;
- for(;;i++)
- {
- assert(i < (int)remaining.size());
- if(!remaining[i])
- continue;
- if(!n)
- break;
- n--;
- }
- remainingCount--;
- remaining[i] = false;
- ret = i + min;
- } while(goodNumberPred && !goodNumberPred(ret));
- return ret;
- }
- int min;
- int remainingCount;
- std::vector<bool> remaining;
- std::function<int()> myRand;
- };
- BattleInfo * BattleInfo::setupBattle(const int3 & tile, TerrainId terrain, const BattleField & battlefieldType, const CArmedInstance * armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance * town)
- {
- CMP_stack cmpst;
- auto * curB = new BattleInfo();
- for(auto i = 0u; i < curB->sides.size(); i++)
- curB->sides[i].init(heroes[i], armies[i]);
- std::vector<CStack*> & stacks = (curB->stacks);
- curB->tile = tile;
- curB->battlefieldType = battlefieldType;
- curB->round = -2;
- curB->activeStack = -1;
- curB->creatureBank = creatureBank;
- curB->replayAllowed = false;
- if(town)
- {
- curB->town = town;
- curB->terrainType = town->getNativeTerrain();
- }
- else
- {
- curB->town = nullptr;
- curB->terrainType = terrain;
- }
- //setting up siege obstacles
- if (town && town->hasFort())
- {
- curB->si.gateState = EGateState::CLOSED;
- curB->si.wallState[EWallPart::GATE] = EWallState::INTACT;
- for(const auto wall : {EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL})
- {
- if (town->hasBuilt(BuildingID::CASTLE))
- curB->si.wallState[wall] = EWallState::REINFORCED;
- else
- curB->si.wallState[wall] = EWallState::INTACT;
- }
- if (town->hasBuilt(BuildingID::CITADEL))
- curB->si.wallState[EWallPart::KEEP] = EWallState::INTACT;
- if (town->hasBuilt(BuildingID::CASTLE))
- {
- curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::INTACT;
- curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::INTACT;
- }
- }
- //randomize obstacles
- if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
- {
- RandGen r{};
- auto ourRand = [&](){ return r.rand(); };
- r.srand(tile);
- r.rand(1,8); //battle sound ID to play... can't do anything with it here
- int tilesToBlock = r.rand(5,12);
- std::vector<BattleHex> blockedTiles;
- auto appropriateAbsoluteObstacle = [&](int id)
- {
- const auto * info = Obstacle(id).getInfo();
- return info && info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
- };
- auto appropriateUsualObstacle = [&](int id)
- {
- const auto * info = Obstacle(id).getInfo();
- return info && !info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
- };
- if(r.rand(1,100) <= 40) //put cliff-like obstacle
- {
- try
- {
- RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
- auto obstPtr = std::make_shared<CObstacleInstance>();
- obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
- obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
- obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
- curB->obstacles.push_back(obstPtr);
- for(BattleHex blocked : obstPtr->getBlockedTiles())
- blockedTiles.push_back(blocked);
- tilesToBlock -= Obstacle(obstPtr->ID).getInfo()->blockedTiles.size() / 2;
- }
- catch(RangeGenerator::ExhaustedPossibilities &)
- {
- //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
- logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place absolute obstacle");
- }
- }
- try
- {
- while(tilesToBlock > 0)
- {
- RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
- auto tileAccessibility = curB->getAccesibility();
- const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
- const ObstacleInfo &obi = *Obstacle(obid).getInfo();
- auto validPosition = [&](BattleHex pos) -> bool
- {
- if(obi.height >= pos.getY())
- return false;
- if(pos.getX() == 0)
- return false;
- if(pos.getX() + obi.width > 15)
- return false;
- if(vstd::contains(blockedTiles, pos))
- return false;
- for(BattleHex blocked : obi.getBlocked(pos))
- {
- if(tileAccessibility[blocked] == EAccessibility::UNAVAILABLE) //for ship-to-ship battlefield - exclude hardcoded unavailable tiles
- return false;
- if(vstd::contains(blockedTiles, blocked))
- return false;
- int x = blocked.getX();
- if(x <= 2 || x >= 14)
- return false;
- }
- return true;
- };
- RangeGenerator posgenerator(18, 168, ourRand);
- auto obstPtr = std::make_shared<CObstacleInstance>();
- obstPtr->ID = obid;
- obstPtr->pos = posgenerator.getSuchNumber(validPosition);
- obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
- curB->obstacles.push_back(obstPtr);
- for(BattleHex blocked : obstPtr->getBlockedTiles())
- blockedTiles.push_back(blocked);
- tilesToBlock -= static_cast<int>(obi.blockedTiles.size());
- }
- }
- catch(RangeGenerator::ExhaustedPossibilities &)
- {
- logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place usual obstacle");
- }
- }
- //reading battleStartpos - add creatures AFTER random obstacles are generated
- //TODO: parse once to some structure
- std::vector<std::vector<int>> looseFormations[2];
- std::vector<std::vector<int>> tightFormations[2];
- std::vector<std::vector<int>> creBankFormations[2];
- std::vector<int> commanderField;
- std::vector<int> commanderBank;
- const JsonNode config(JsonPath::builtin("config/battleStartpos.json"));
- const JsonVector &positions = config["battle_positions"].Vector();
- CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
- CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
- CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
- CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
- CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
- CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
- for (auto position : config["commanderPositions"]["field"].Vector())
- {
- commanderField.push_back(static_cast<int>(position.Float()));
- }
- for (auto position : config["commanderPositions"]["creBank"].Vector())
- {
- commanderBank.push_back(static_cast<int>(position.Float()));
- }
- //adding war machines
- if(!creatureBank)
- {
- //Checks if hero has artifact and create appropriate stack
- auto handleWarMachine = [&](int side, const ArtifactPosition & artslot, BattleHex hex)
- {
- const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
- if(nullptr != warMachineArt)
- {
- CreatureID cre = warMachineArt->artType->getWarMachine();
- if(cre != CreatureID::NONE)
- curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex);
- }
- };
- if(heroes[0])
- {
- handleWarMachine(0, ArtifactPosition::MACH1, 52);
- handleWarMachine(0, ArtifactPosition::MACH2, 18);
- handleWarMachine(0, ArtifactPosition::MACH3, 154);
- if(town && town->hasFort())
- handleWarMachine(0, ArtifactPosition::MACH4, 120);
- }
- if(heroes[1])
- {
- if(!town) //defending hero shouldn't receive ballista (bug #551)
- handleWarMachine(1, ArtifactPosition::MACH1, 66);
- handleWarMachine(1, ArtifactPosition::MACH2, 32);
- handleWarMachine(1, ArtifactPosition::MACH3, 168);
- }
- }
- //war machines added
- //battleStartpos read
- for(int side = 0; side < 2; side++)
- {
- int formationNo = armies[side]->stacksCount() - 1;
- vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
- int k = 0; //stack serial
- for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
- {
- std::vector<int> *formationVector = nullptr;
- if(armies[side]->formation == EArmyFormation::TIGHT )
- formationVector = &tightFormations[side][formationNo];
- else
- formationVector = &looseFormations[side][formationNo];
- if(creatureBank)
- formationVector = &creBankFormations[side][formationNo];
- BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
- if(creatureBank && i->second->type->isDoubleWide())
- pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
- curB->generateNewStack(curB->nextUnitId(), *i->second, side, i->first, pos);
- }
- }
- //adding commanders
- for (int i = 0; i < 2; ++i)
- {
- if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
- {
- curB->generateNewStack(curB->nextUnitId(), *heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER, creatureBank ? commanderBank[i] : commanderField[i]);
- }
- }
- if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
- {
- // keep tower
- curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
- if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
- {
- // lower tower + upper tower
- curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
- curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
- }
- //Moat generating is done on server
- }
- std::stable_sort(stacks.begin(),stacks.end(),cmpst);
- auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
- auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
- auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
- const auto * bgInfo = VLC->battlefields()->getById(battlefieldType);
- for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
- {
- curB->addNewBonus(bonus);
- }
- //native terrain bonuses
- auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
-
- curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::STACKS_SPEED, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID())->addLimiter(nativeTerrain));
- curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::ATTACK))->addLimiter(nativeTerrain));
- curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE))->addLimiter(nativeTerrain));
- //////////////////////////////////////////////////////////////////////////
- //tactics
- bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
- constexpr int sideSize = 2;
- std::array<int, sideSize> battleRepositionHex = {};
- std::array<int, sideSize> battleRepositionHexBlock = {};
- for(int i = 0; i < sideSize; i++)
- {
- if(heroes[i])
- {
- battleRepositionHex[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION));
- battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION_BLOCK));
- }
- }
- int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
- int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
- /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
- when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
- will not happen because tactics block opposite tactics on same value.
- TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
- double tactics will be implemented.
- */
- if(isTacticsAllowed)
- {
- if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
- logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
- if(tacticsSkillDiffAttacker > 0)
- {
- curB->tacticsSide = BattleSide::ATTACKER;
- //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
- curB->tacticDistance = 1 + tacticsSkillDiffAttacker;
- }
- else if(tacticsSkillDiffDefender > 0)
- {
- curB->tacticsSide = BattleSide::DEFENDER;
- //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
- curB->tacticDistance = 1 + tacticsSkillDiffDefender;
- }
- else
- curB->tacticDistance = 0;
- }
- return curB;
- }
- const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
- {
- for(const auto & side : sides)
- if(side.color == player)
- return side.hero;
- logGlobal->error("Player %s is not in battle!", player.toString());
- return nullptr;
- }
- ui8 BattleInfo::whatSide(const PlayerColor & player) const
- {
- for(int i = 0; i < sides.size(); i++)
- if(sides[i].color == player)
- return i;
- logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.toString());
- return -1;
- }
- CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
- {
- return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
- }
- BattleInfo::BattleInfo():
- round(-1),
- activeStack(-1),
- town(nullptr),
- tile(-1,-1,-1),
- battlefieldType(BattleField::NONE),
- tacticsSide(0),
- tacticDistance(0)
- {
- setNodeType(BATTLE);
- }
- BattleID BattleInfo::getBattleID() const
- {
- return battleID;
- }
- const IBattleInfo * BattleInfo::getBattle() const
- {
- return this;
- }
- std::optional<PlayerColor> BattleInfo::getPlayerID() const
- {
- return std::nullopt;
- }
- BattleInfo::~BattleInfo()
- {
- for (auto & elem : stacks)
- delete elem;
- for(int i = 0; i < 2; i++)
- if(auto * _armyObj = battleGetArmyObject(i))
- _armyObj->battle = nullptr;
- }
- int32_t BattleInfo::getActiveStackID() const
- {
- return activeStack;
- }
- TStacks BattleInfo::getStacksIf(const TStackFilter & predicate) const
- {
- TStacks ret;
- vstd::copy_if(stacks, std::back_inserter(ret), predicate);
- return ret;
- }
- battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
- {
- battle::Units ret;
- vstd::copy_if(stacks, std::back_inserter(ret), predicate);
- return ret;
- }
- BattleField BattleInfo::getBattlefieldType() const
- {
- return battlefieldType;
- }
- TerrainId BattleInfo::getTerrainType() const
- {
- return terrainType;
- }
- IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
- {
- ObstacleCList ret;
- for(const auto & obstacle : obstacles)
- ret.push_back(obstacle);
- return ret;
- }
- PlayerColor BattleInfo::getSidePlayer(ui8 side) const
- {
- return sides.at(side).color;
- }
- const CArmedInstance * BattleInfo::getSideArmy(ui8 side) const
- {
- return sides.at(side).armyObject;
- }
- const CGHeroInstance * BattleInfo::getSideHero(ui8 side) const
- {
- return sides.at(side).hero;
- }
- ui8 BattleInfo::getTacticDist() const
- {
- return tacticDistance;
- }
- ui8 BattleInfo::getTacticsSide() const
- {
- return tacticsSide;
- }
- const CGTownInstance * BattleInfo::getDefendedTown() const
- {
- return town;
- }
- EWallState BattleInfo::getWallState(EWallPart partOfWall) const
- {
- return si.wallState.at(partOfWall);
- }
- EGateState BattleInfo::getGateState() const
- {
- return si.gateState;
- }
- uint32_t BattleInfo::getCastSpells(ui8 side) const
- {
- return sides.at(side).castSpellsCount;
- }
- int32_t BattleInfo::getEnchanterCounter(ui8 side) const
- {
- return sides.at(side).enchanterCounter;
- }
- const IBonusBearer * BattleInfo::getBonusBearer() const
- {
- return this;
- }
- int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
- {
- if(damage.min != damage.max)
- {
- int64_t sum = 0;
- auto howManyToAv = std::min<int32_t>(10, attackerCount);
- auto rangeGen = rng.getInt64Range(damage.min, damage.max);
- for(int32_t g = 0; g < howManyToAv; ++g)
- sum += rangeGen();
- return sum / howManyToAv;
- }
- else
- {
- return damage.min;
- }
- }
- int3 BattleInfo::getLocation() const
- {
- return tile;
- }
- bool BattleInfo::isCreatureBank() const
- {
- return creatureBank;
- }
- std::vector<SpellID> BattleInfo::getUsedSpells(ui8 side) const
- {
- return sides.at(side).usedSpellsHistory;
- }
- void BattleInfo::nextRound()
- {
- for(int i = 0; i < 2; ++i)
- {
- sides.at(i).castSpellsCount = 0;
- vstd::amax(--sides.at(i).enchanterCounter, 0);
- }
- round += 1;
- for(CStack * s : stacks)
- {
- // new turn effects
- s->reduceBonusDurations(Bonus::NTurns);
- s->afterNewRound();
- }
- for(auto & obst : obstacles)
- obst->battleTurnPassed();
- }
- void BattleInfo::nextTurn(uint32_t unitId)
- {
- activeStack = unitId;
- CStack * st = getStack(activeStack);
- //remove bonuses that last until when stack gets new turn
- st->removeBonusesRecursive(Bonus::UntilGetsTurn);
- st->afterGetsTurn();
- }
- void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
- {
- battle::UnitInfo info;
- info.load(id, data);
- CStackBasicDescriptor base(info.type, info.count);
- PlayerColor owner = getSidePlayer(info.side);
- auto * ret = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
- ret->initialPosition = info.position;
- stacks.push_back(ret);
- ret->localInit(this);
- ret->summoned = info.summoned;
- }
- void BattleInfo::moveUnit(uint32_t id, BattleHex destination)
- {
- auto * sta = getStack(id);
- if(!sta)
- {
- logGlobal->error("Cannot find stack %d", id);
- return;
- }
- sta->position = destination;
- //Bonuses can be limited by unit placement, so, change tree version
- //to force updating a bonus. TODO: update version only when such bonuses are present
- CBonusSystemNode::treeHasChanged();
- }
- void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
- {
- CStack * changedStack = getStack(id, false);
- if(!changedStack)
- throw std::runtime_error("Invalid unit id in BattleInfo update");
- if(!changedStack->alive() && healthDelta > 0)
- {
- //checking if we resurrect a stack that is under a living stack
- auto accessibility = getAccesibility();
- if(!accessibility.accessible(changedStack->getPosition(), changedStack))
- {
- logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition().hex);
- return; //position is already occupied
- }
- }
- bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
- bool resurrected = !changedStack->alive() && healthDelta > 0;
- //applying changes
- changedStack->load(data);
- if(healthDelta < 0)
- {
- changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
- }
- resurrected = resurrected || (killed && changedStack->alive());
- if(killed)
- {
- if(changedStack->cloneID >= 0)
- {
- //remove clone as well
- CStack * clone = getStack(changedStack->cloneID);
- if(clone)
- clone->makeGhost();
- changedStack->cloneID = -1;
- }
- }
- if(resurrected || killed)
- {
- //removing all spells effects
- auto selector = [](const Bonus * b)
- {
- //Special case: DISRUPTING_RAY is absolutely permanent
- return b->source == BonusSource::SPELL_EFFECT && b->sid.as<SpellID>() != SpellID::DISRUPTING_RAY;
- };
- changedStack->removeBonusesRecursive(selector);
- }
- if(!changedStack->alive() && changedStack->isClone())
- {
- for(CStack * s : stacks)
- {
- if(s->cloneID == changedStack->unitId())
- s->cloneID = -1;
- }
- }
- }
- void BattleInfo::removeUnit(uint32_t id)
- {
- std::set<uint32_t> ids;
- ids.insert(id);
- while(!ids.empty())
- {
- auto toRemoveId = *ids.begin();
- auto * toRemove = getStack(toRemoveId, false);
- if(!toRemove)
- {
- logGlobal->error("Cannot find stack %d", toRemoveId);
- return;
- }
- if(!toRemove->ghost)
- {
- toRemove->onRemoved();
- toRemove->detachFromAll();
- //stack may be removed instantly (not being killed first)
- //handle clone remove also here
- if(toRemove->cloneID >= 0)
- {
- ids.insert(toRemove->cloneID);
- toRemove->cloneID = -1;
- }
- //cleanup remaining clone links if any
- for(auto * s : stacks)
- {
- if(s->cloneID == toRemoveId)
- s->cloneID = -1;
- }
- }
- ids.erase(toRemoveId);
- }
- }
- void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
- {
- //TODO
- }
- void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
- {
- CStack * sta = getStack(id, false);
- if(!sta)
- {
- logGlobal->error("Cannot find stack %d", id);
- return;
- }
- for(const Bonus & b : bonus)
- addOrUpdateUnitBonus(sta, b, true);
- }
- void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
- {
- CStack * sta = getStack(id, false);
- if(!sta)
- {
- logGlobal->error("Cannot find stack %d", id);
- return;
- }
- for(const Bonus & b : bonus)
- addOrUpdateUnitBonus(sta, b, false);
- }
- void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
- {
- CStack * sta = getStack(id, false);
- if(!sta)
- {
- logGlobal->error("Cannot find stack %d", id);
- return;
- }
- for(const Bonus & one : bonus)
- {
- auto selector = [one](const Bonus * b)
- {
- //compare everything but turnsRemain, limiter and propagator
- return one.duration == b->duration
- && one.type == b->type
- && one.subtype == b->subtype
- && one.source == b->source
- && one.val == b->val
- && one.sid == b->sid
- && one.valType == b->valType
- && one.additionalInfo == b->additionalInfo
- && one.effectRange == b->effectRange;
- };
- sta->removeBonusesRecursive(selector);
- }
- }
- uint32_t BattleInfo::nextUnitId() const
- {
- return static_cast<uint32_t>(stacks.size());
- }
- void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
- {
- if(forceAdd || !sta->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, value.sid).And(Selector::typeSubtype(value.type, value.subtype))))
- {
- //no such effect or cumulative - add new
- logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description());
- sta->addNewBonus(std::make_shared<Bonus>(value));
- }
- else
- {
- logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description());
- for(const auto & stackBonus : sta->getExportedBonusList()) //TODO: optimize
- {
- if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype)
- {
- stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
- }
- }
- CBonusSystemNode::treeHasChanged();
- }
- }
- void BattleInfo::setWallState(EWallPart partOfWall, EWallState state)
- {
- si.wallState[partOfWall] = state;
- }
- void BattleInfo::addObstacle(const ObstacleChanges & changes)
- {
- auto obstacle = std::make_shared<SpellCreatedObstacle>();
- obstacle->fromInfo(changes);
- obstacles.push_back(obstacle);
- }
- void BattleInfo::updateObstacle(const ObstacleChanges& changes)
- {
- auto changedObstacle = std::make_shared<SpellCreatedObstacle>();
- changedObstacle->fromInfo(changes);
- for(auto & obstacle : obstacles)
- {
- if(obstacle->uniqueID == changes.id) // update this obstacle
- {
- auto * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacle.get());
- assert(spellObstacle);
- // Currently we only support to update the "revealed" property
- spellObstacle->revealed = changedObstacle->revealed;
- break;
- }
- }
- }
- void BattleInfo::removeObstacle(uint32_t id)
- {
- for(int i=0; i < obstacles.size(); ++i)
- {
- if(obstacles[i]->uniqueID == id) //remove this obstacle
- {
- obstacles.erase(obstacles.begin() + i);
- break;
- }
- }
- }
- CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
- {
- return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
- }
- CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
- {
- return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
- }
- #if SCRIPTING_ENABLED
- scripting::Pool * BattleInfo::getContextPool() const
- {
- //this is real battle, use global scripting context pool
- //TODO: make this line not ugly
- return battleGetFightingHero(0)->cb->getGlobalContextPool();
- }
- #endif
- bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
- {
- switch(phase)
- {
- case 0: //catapult moves after turrets
- return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
- case 1:
- case 2:
- case 3:
- {
- int as = a->getInitiative(turn);
- int bs = b->getInitiative(turn);
- if(as != bs)
- return as > bs;
- if(a->unitSide() == b->unitSide())
- return a->unitSlot() < b->unitSlot();
- return (a->unitSide() == side || b->unitSide() == side)
- ? a->unitSide() != side
- : a->unitSide() < b->unitSide();
- }
- default:
- assert(false);
- return false;
- }
- assert(false);
- return false;
- }
- CMP_stack::CMP_stack(int Phase, int Turn, uint8_t Side):
- phase(Phase),
- turn(Turn),
- side(Side)
- {
- }
- VCMI_LIB_NAMESPACE_END
|