1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-05-13 22:06:58 +02:00

vcmi: use std::optional

This commit is contained in:
Konstantin 2023-04-16 20:42:56 +03:00
parent 0d35606a44
commit 7a5775a9f9
135 changed files with 552 additions and 585 deletions

View File

@ -134,7 +134,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
//evaluate casting spell for spellcasting stack //evaluate casting spell for spellcasting stack
boost::optional<PossibleSpellcast> bestSpellcast(boost::none); std::optional<PossibleSpellcast> bestSpellcast(std::nullopt);
//TODO: faerie dragon type spell should be selected by server //TODO: faerie dragon type spell should be selected by server
SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED); SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
if(stack->hasBonusOfType(Bonus::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE) if(stack->hasBonusOfType(Bonus::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
@ -157,7 +157,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; }); std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
if(!possibleCasts.empty() && possibleCasts.front().value > 0) if(!possibleCasts.empty() && possibleCasts.front().value > 0)
{ {
bestSpellcast = boost::optional<PossibleSpellcast>(possibleCasts.front()); bestSpellcast = std::optional<PossibleSpellcast>(possibleCasts.front());
} }
} }
} }
@ -180,7 +180,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
auto & bestAttack = evaluationResult.bestAttack; auto & bestAttack = evaluationResult.bestAttack;
//TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc. //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
if(bestSpellcast.is_initialized() && bestSpellcast->value > bestAttack.damageDiff()) if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
{ {
// return because spellcast value is damage dealt and score is dps reduce // return because spellcast value is damage dealt and score is dps reduce
movesSkippedByDefense = 0; movesSkippedByDefense = 0;
@ -219,7 +219,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack )
); );
} }
} }
else if(bestSpellcast.is_initialized()) else if(bestSpellcast.has_value())
{ {
movesSkippedByDefense = 0; movesSkippedByDefense = 0;
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id); return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
@ -801,7 +801,7 @@ void CBattleAI::print(const std::string &text) const
logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text); logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
} }
boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering() std::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
{ {
BattleStateInfoForRetreat bs; BattleStateInfoForRetreat bs;
@ -829,7 +829,7 @@ boost::optional<BattleAction> CBattleAI::considerFleeingOrSurrendering()
if(!bs.canFlee || !bs.canSurrender) if(!bs.canFlee || !bs.canSurrender)
{ {
return boost::none; return std::nullopt;
} }
auto result = cb->makeSurrenderRetreatDecision(bs); auto result = cb->makeSurrenderRetreatDecision(bs);

View File

@ -73,7 +73,7 @@ public:
BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack
boost::optional<BattleAction> considerFleeingOrSurrendering(); std::optional<BattleAction> considerFleeingOrSurrendering();
void print(const std::string &text) const; void print(const std::string &text) const;
BattleAction useCatapult(const CStack *stack); BattleAction useCatapult(const CStack *stack);

View File

@ -501,8 +501,7 @@ void AIGateway::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositio
NET_EVENT_HANDLER; NET_EVENT_HANDLER;
} }
boost::optional<BattleAction> AIGateway::makeSurrenderRetreatDecision( std::optional<BattleAction> AIGateway::makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState)
const BattleStateInfoForRetreat & battleState)
{ {
LOG_TRACE(logAi); LOG_TRACE(logAi);
NET_EVENT_HANDLER; NET_EVENT_HANDLER;
@ -516,7 +515,7 @@ boost::optional<BattleAction> AIGateway::makeSurrenderRetreatDecision(
return BattleAction::makeRetreat(battleState.ourSide); return BattleAction::makeRetreat(battleState.ourSide);
} }
return boost::none; return std::nullopt;
} }

View File

@ -166,7 +166,7 @@ public:
void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override; void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override;
void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override; void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override;
void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain) override; void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain) override;
boost::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override; std::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override;
void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override; void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override;
void battleEnd(const BattleResult * br, QueryID queryID) override; void battleEnd(const BattleResult * br, QueryID queryID) override;

View File

@ -42,10 +42,10 @@ TGoalVec Build::getAllPossibleSubgoals()
auto expensiveBuilding = ai->ah->expensiveBuilding(); auto expensiveBuilding = ai->ah->expensiveBuilding();
//handling for early town development to save money and focus on income //handling for early town development to save money and focus on income
if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.is_initialized()) if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.has_value())
{ {
auto potentialBuilding = expensiveBuilding.get(); auto potentialBuilding = expensiveBuilding.value();
switch(expensiveBuilding.get().bid) switch(expensiveBuilding.value().bid)
{ {
case BuildingID::TOWN_HALL: case BuildingID::TOWN_HALL:
case BuildingID::CITY_HALL: case BuildingID::CITY_HALL:
@ -61,15 +61,15 @@ TGoalVec Build::getAllPossibleSubgoals()
} }
} }
if(immediateBuilding.is_initialized()) if(immediateBuilding.has_value())
{ {
ret.push_back(sptr(BuildThis(immediateBuilding.get().bid, t).setpriority(2))); //prioritize buildings we can build quick ret.push_back(sptr(BuildThis(immediateBuilding.value().bid, t).setpriority(2))); //prioritize buildings we can build quick
} }
else //try build later else //try build later
{ {
if(expensiveBuilding.is_initialized()) if(expensiveBuilding.has_value())
{ {
auto potentialBuilding = expensiveBuilding.get(); //gather resources for any we can't afford auto potentialBuilding = expensiveBuilding.value(); //gather resources for any we can't afford
auto goal = ai->ah->whatToDo(potentialBuilding.price, sptr(BuildThis(potentialBuilding.bid, t).setpriority(0.5))); auto goal = ai->ah->whatToDo(potentialBuilding.price, sptr(BuildThis(potentialBuilding.bid, t).setpriority(0.5)));
ret.push_back(goal); ret.push_back(goal);
} }

View File

@ -97,7 +97,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals()
//Do not use below code for now, rely on generic Build. Code below needs to know a lot of town/resource context to do more good than harm //Do not use below code for now, rely on generic Build. Code below needs to know a lot of town/resource context to do more good than harm
/*auto bid = ai->ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 1); /*auto bid = ai->ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 1);
if (bid.is_initialized()) if (bid.has_value())
{ {
auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority)); auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority));
if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice

View File

@ -120,7 +120,7 @@ void AINodeStorage::clear()
turnDistanceLimit[HeroRole::SCOUT] = 255; turnDistanceLimit[HeroRole::SCOUT] = 255;
} }
boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode( std::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
const int3 & pos, const int3 & pos,
const EPathfindingLayer layer, const EPathfindingLayer layer,
const ChainActor * actor) const ChainActor * actor)
@ -131,7 +131,7 @@ boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
if(chains[0].blocked()) if(chains[0].blocked())
{ {
return boost::none; return std::nullopt;
} }
for(auto i = AIPathfinding::BUCKET_SIZE - 1; i >= 0; i--) for(auto i = AIPathfinding::BUCKET_SIZE - 1; i >= 0; i--)
@ -151,7 +151,7 @@ boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
} }
} }
return boost::none; return std::nullopt;
} }
std::vector<CGPathNode *> AINodeStorage::getInitialNodes() std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
@ -175,7 +175,7 @@ std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
if(!allocated) if(!allocated)
continue; continue;
AIPathNode * initialNode = allocated.get(); AIPathNode * initialNode = allocated.value();
initialNode->inPQ = false; initialNode->inPQ = false;
initialNode->pq = nullptr; initialNode->pq = nullptr;
@ -289,10 +289,10 @@ std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
{ {
auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor); auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET) if(!nextNode || nextNode.value()->accessible == CGPathNode::NOT_SET)
continue; continue;
neighbours.push_back(nextNode.get()); neighbours.push_back(nextNode.value());
} }
} }
@ -722,7 +722,7 @@ void HeroChainCalculationTask::addHeroChain(const std::vector<ExchangeCandidate>
continue; continue;
} }
auto exchangeNode = chainNodeOptional.get(); auto exchangeNode = chainNodeOptional.value();
if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN) if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
{ {
@ -946,7 +946,7 @@ std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
if(!node) if(!node)
continue; continue;
neighbours.push_back(node.get()); neighbours.push_back(node.value());
} }
} }
@ -1017,19 +1017,19 @@ struct TowmPortalFinder
return nullptr; return nullptr;
} }
boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown) std::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
{ {
auto bestNode = getBestInitialNodeForTownPortal(targetTown); auto bestNode = getBestInitialNodeForTownPortal(targetTown);
if(!bestNode) if(!bestNode)
return boost::none; return std::nullopt;
auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor); auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
if(!nodeOptional) if(!nodeOptional)
return boost::none; return std::nullopt;
AIPathNode * node = nodeOptional.get(); AIPathNode * node = nodeOptional.value();
float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND); float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
movementCost += bestNode->getCost(); movementCost += bestNode->getCost();
@ -1095,7 +1095,7 @@ void AINodeStorage::calculateTownPortal(
#if NKAI_PATHFINDER_TRACE_LEVEL >= 1 #if NKAI_PATHFINDER_TRACE_LEVEL >= 1
logAi->trace("Adding town portal node at %s", targetTown->name); logAi->trace("Adding town portal node at %s", targetTown->name);
#endif #endif
output.push_back(nodeOptional.get()); output.push_back(nodeOptional.value());
} }
} }
} }

View File

@ -232,7 +232,7 @@ public:
const AIPathNode * destinationNode, const AIPathNode * destinationNode,
const NodeRange & chains) const; const NodeRange & chains) const;
boost::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor); std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor);
std::vector<AIPath> getChainInfo(const int3 & pos, bool isOnLand) const; std::vector<AIPath> getChainInfo(const int3 & pos, bool isOnLand) const;
bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const; bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const;
void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes); void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes);

View File

@ -131,7 +131,7 @@ namespace AIPathfinding
if(boatNodeOptional) if(boatNodeOptional)
{ {
AIPathNode * boatNode = boatNodeOptional.get(); AIPathNode * boatNode = boatNodeOptional.value();
if(boatNode->action == CGPathNode::UNKNOWN) if(boatNode->action == CGPathNode::UNKNOWN)
{ {

View File

@ -139,17 +139,17 @@ namespace AIPathfinding
{ {
if(!destinationNode->actor->allowUseResources) if(!destinationNode->actor->allowUseResources)
{ {
boost::optional<AIPathNode *> questNode = nodeStorage->getOrCreateNode( std::optional<AIPathNode *> questNode = nodeStorage->getOrCreateNode(
destination.coord, destination.coord,
destination.node->layer, destination.node->layer,
destinationNode->actor->resourceActor); destinationNode->actor->resourceActor);
if(!questNode || questNode.get()->getCost() < destination.cost) if(!questNode || questNode.value()->getCost() < destination.cost)
{ {
return false; return false;
} }
destination.node = questNode.get(); destination.node = questNode.value();
nodeStorage->commit(destination, source); nodeStorage->commit(destination, source);
AIPreviousNodeRule(nodeStorage).process(source, destination, pathfinderConfig, pathfinderHelper); AIPreviousNodeRule(nodeStorage).process(source, destination, pathfinderConfig, pathfinderHelper);
@ -259,7 +259,7 @@ namespace AIPathfinding
return false; return false;
} }
AIPathNode * battleNode = battleNodeOptional.get(); auto * battleNode = battleNodeOptional.value();
if(battleNode->locked) if(battleNode->locked)
{ {

View File

@ -50,17 +50,17 @@ BuildingID AIhelper::getMaxPossibleGoldBuilding(const CGTownInstance * t)
return buildingManager->getMaxPossibleGoldBuilding(t); return buildingManager->getMaxPossibleGoldBuilding(t);
} }
boost::optional<PotentialBuilding> AIhelper::immediateBuilding() const std::optional<PotentialBuilding> AIhelper::immediateBuilding() const
{ {
return buildingManager->immediateBuilding(); return buildingManager->immediateBuilding();
} }
boost::optional<PotentialBuilding> AIhelper::expensiveBuilding() const std::optional<PotentialBuilding> AIhelper::expensiveBuilding() const
{ {
return buildingManager->expensiveBuilding(); return buildingManager->expensiveBuilding();
} }
boost::optional<BuildingID> AIhelper::canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays) const std::optional<BuildingID> AIhelper::canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays) const
{ {
return buildingManager->canBuildAnyStructure(t, buildList, maxDays); return buildingManager->canBuildAnyStructure(t, buildList, maxDays);
} }

View File

@ -52,9 +52,9 @@ public:
bool getBuildingOptions(const CGTownInstance * t) override; bool getBuildingOptions(const CGTownInstance * t) override;
BuildingID getMaxPossibleGoldBuilding(const CGTownInstance * t); BuildingID getMaxPossibleGoldBuilding(const CGTownInstance * t);
boost::optional<PotentialBuilding> immediateBuilding() const override; std::optional<PotentialBuilding> immediateBuilding() const override;
boost::optional<PotentialBuilding> expensiveBuilding() const override; std::optional<PotentialBuilding> expensiveBuilding() const override;
boost::optional<BuildingID> canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays = 7) const override; std::optional<BuildingID> canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays = 7) const override;
Goals::TGoalVec howToVisitTile(const HeroPtr & hero, const int3 & tile, bool allowGatherArmy = true) const override; Goals::TGoalVec howToVisitTile(const HeroPtr & hero, const int3 & tile, bool allowGatherArmy = true) const override;
Goals::TGoalVec howToVisitObj(const HeroPtr & hero, ObjectIdRef obj, bool allowGatherArmy = true) const override; Goals::TGoalVec howToVisitObj(const HeroPtr & hero, ObjectIdRef obj, bool allowGatherArmy = true) const override;

View File

@ -99,7 +99,7 @@ bool BuildingManager::tryBuildAnyStructure(const CGTownInstance * t, std::vector
return false; //Can't build anything return false; //Can't build anything
} }
boost::optional<BuildingID> BuildingManager::canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays) const std::optional<BuildingID> BuildingManager::canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays) const
{ {
for (const auto & building : buildList) for (const auto & building : buildList)
{ {
@ -109,11 +109,11 @@ boost::optional<BuildingID> BuildingManager::canBuildAnyStructure(const CGTownIn
{ {
case EBuildingState::ALLOWED: case EBuildingState::ALLOWED:
case EBuildingState::NO_RESOURCES: //TODO: allow this via optional parameter? case EBuildingState::NO_RESOURCES: //TODO: allow this via optional parameter?
return boost::optional<BuildingID>(building); return std::optional<BuildingID>(building);
break; break;
} }
} }
return boost::optional<BuildingID>(); //Can't build anything return std::optional<BuildingID>(); //Can't build anything
} }
bool BuildingManager::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays) bool BuildingManager::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
@ -240,18 +240,18 @@ BuildingID BuildingManager::getMaxPossibleGoldBuilding(const CGTownInstance * t)
return BuildingID::VILLAGE_HALL; return BuildingID::VILLAGE_HALL;
} }
boost::optional<PotentialBuilding> BuildingManager::immediateBuilding() const std::optional<PotentialBuilding> BuildingManager::immediateBuilding() const
{ {
if (immediateBuildings.size()) if (immediateBuildings.size())
return boost::optional<PotentialBuilding>(immediateBuildings.front()); //back? whatever return std::optional<PotentialBuilding>(immediateBuildings.front()); //back? whatever
else else
return boost::optional<PotentialBuilding>(); return std::optional<PotentialBuilding>();
} }
boost::optional<PotentialBuilding> BuildingManager::expensiveBuilding() const std::optional<PotentialBuilding> BuildingManager::expensiveBuilding() const
{ {
if (expensiveBuildings.size()) if (expensiveBuildings.size())
return boost::optional<PotentialBuilding>(expensiveBuildings.front()); return std::optional<PotentialBuilding>(expensiveBuildings.front());
else else
return boost::optional<PotentialBuilding>(); return std::optional<PotentialBuilding>();
} }

View File

@ -33,9 +33,9 @@ public:
virtual void setAI(VCAI * AI) = 0; virtual void setAI(VCAI * AI) = 0;
virtual bool getBuildingOptions(const CGTownInstance * t) = 0; virtual bool getBuildingOptions(const CGTownInstance * t) = 0;
virtual boost::optional<PotentialBuilding> immediateBuilding() const = 0; virtual std::optional<PotentialBuilding> immediateBuilding() const = 0;
virtual boost::optional<PotentialBuilding> expensiveBuilding() const = 0; virtual std::optional<PotentialBuilding> expensiveBuilding() const = 0;
virtual boost::optional<BuildingID> canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays) const = 0; virtual std::optional<BuildingID> canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays) const = 0;
}; };
class DLL_EXPORT BuildingManager : public IBuildingManager class DLL_EXPORT BuildingManager : public IBuildingManager
@ -52,9 +52,9 @@ public:
//try build anything in given town, and execute resulting Goal if any //try build anything in given town, and execute resulting Goal if any
bool getBuildingOptions(const CGTownInstance * t) override; bool getBuildingOptions(const CGTownInstance * t) override;
BuildingID getMaxPossibleGoldBuilding(const CGTownInstance * t); BuildingID getMaxPossibleGoldBuilding(const CGTownInstance * t);
boost::optional<PotentialBuilding> immediateBuilding() const override; std::optional<PotentialBuilding> immediateBuilding() const override;
boost::optional<PotentialBuilding> expensiveBuilding() const override; std::optional<PotentialBuilding> expensiveBuilding() const override;
boost::optional<BuildingID> canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays = 7) const override; std::optional<BuildingID> canBuildAnyStructure(const CGTownInstance * t, const std::vector<BuildingID> & buildList, unsigned int maxDays = 7) const override;
protected: protected:

View File

@ -399,12 +399,12 @@ float VisitObjEngine::evaluate(Goals::VisitObj & goal)
return -100; // FIXME: Added check when goal was used for hero instead of VisitHero, but crashes are bad anyway return -100; // FIXME: Added check when goal was used for hero instead of VisitHero, but crashes are bad anyway
} }
boost::optional<int> objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj); std::optional<int> objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj);
int objValue = 0; int objValue = 0;
if(objValueKnownByAI != boost::none) //consider adding value manipulation based on object instances on map if(objValueKnownByAI != std::nullopt) //consider adding value manipulation based on object instances on map
{ {
objValue = std::min(std::max(objValueKnownByAI.get(), 0), 20000); objValue = std::min(std::max(objValueKnownByAI.value(), 0), 20000);
} }
else else
{ {

View File

@ -39,10 +39,10 @@ TGoalVec Build::getAllPossibleSubgoals()
auto expensiveBuilding = ai->ah->expensiveBuilding(); auto expensiveBuilding = ai->ah->expensiveBuilding();
//handling for early town development to save money and focus on income //handling for early town development to save money and focus on income
if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.is_initialized()) if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.has_value())
{ {
auto potentialBuilding = expensiveBuilding.get(); auto potentialBuilding = expensiveBuilding.value();
switch(expensiveBuilding.get().bid) switch(expensiveBuilding.value().bid)
{ {
case BuildingID::TOWN_HALL: case BuildingID::TOWN_HALL:
case BuildingID::CITY_HALL: case BuildingID::CITY_HALL:
@ -58,15 +58,15 @@ TGoalVec Build::getAllPossibleSubgoals()
} }
} }
if(immediateBuilding.is_initialized()) if(immediateBuilding.has_value())
{ {
ret.push_back(sptr(BuildThis(immediateBuilding.get().bid, t).setpriority(2))); //prioritize buildings we can build quick ret.push_back(sptr(BuildThis(immediateBuilding.value().bid, t).setpriority(2))); //prioritize buildings we can build quick
} }
else //try build later else //try build later
{ {
if(expensiveBuilding.is_initialized()) if(expensiveBuilding.has_value())
{ {
auto potentialBuilding = expensiveBuilding.get(); //gather resources for any we can't afford auto potentialBuilding = expensiveBuilding.value(); //gather resources for any we can't afford
auto goal = ai->ah->whatToDo(potentialBuilding.price, sptr(BuildThis(potentialBuilding.bid, t).setpriority(0.5))); auto goal = ai->ah->whatToDo(potentialBuilding.price, sptr(BuildThis(potentialBuilding.bid, t).setpriority(0.5)));
ret.push_back(goal); ret.push_back(goal);
} }

View File

@ -94,7 +94,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals()
//Do not use below code for now, rely on generic Build. Code below needs to know a lot of town/resource context to do more good than harm //Do not use below code for now, rely on generic Build. Code below needs to know a lot of town/resource context to do more good than harm
/*auto bid = ai->ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + std::size(unitsSource)), 1); /*auto bid = ai->ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + std::size(unitsSource)), 1);
if (bid.is_initialized()) if (bid.has_value())
{ {
auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority)); auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority));
if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice

View File

@ -28,9 +28,9 @@ MapObjectsEvaluator::MapObjectsEvaluator()
auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID); auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
if(handler && !handler->isStaticObject()) if(handler && !handler->isStaticObject())
{ {
if(handler->getAiValue() != boost::none) if(handler->getAiValue() != std::nullopt)
{ {
objectDatabase[CompoundMapObjectID(primaryID, secondaryID)] = handler->getAiValue().get(); objectDatabase[CompoundMapObjectID(primaryID, secondaryID)] = handler->getAiValue().value();
} }
else //some default handling when aiValue not found, objects that require advanced properties (unavailable from handler) get their value calculated in getObjectValue else //some default handling when aiValue not found, objects that require advanced properties (unavailable from handler) get their value calculated in getObjectValue
{ {
@ -41,7 +41,7 @@ MapObjectsEvaluator::MapObjectsEvaluator()
} }
} }
boost::optional<int> MapObjectsEvaluator::getObjectValue(int primaryID, int secondaryID) const std::optional<int> MapObjectsEvaluator::getObjectValue(int primaryID, int secondaryID) const
{ {
CompoundMapObjectID internalIdentifier = CompoundMapObjectID(primaryID, secondaryID); CompoundMapObjectID internalIdentifier = CompoundMapObjectID(primaryID, secondaryID);
auto object = objectDatabase.find(internalIdentifier); auto object = objectDatabase.find(internalIdentifier);
@ -49,10 +49,10 @@ boost::optional<int> MapObjectsEvaluator::getObjectValue(int primaryID, int seco
return object->second; return object->second;
logGlobal->trace("Unknown object for AI, ID: " + std::to_string(primaryID) + ", SubID: " + std::to_string(secondaryID)); logGlobal->trace("Unknown object for AI, ID: " + std::to_string(primaryID) + ", SubID: " + std::to_string(secondaryID));
return boost::optional<int>(); return std::optional<int>();
} }
boost::optional<int> MapObjectsEvaluator::getObjectValue(const CGObjectInstance * obj) const std::optional<int> MapObjectsEvaluator::getObjectValue(const CGObjectInstance * obj) const
{ {
if(obj->ID == Obj::HERO) if(obj->ID == Obj::HERO)
{ {

View File

@ -18,8 +18,8 @@ private:
public: public:
MapObjectsEvaluator(); MapObjectsEvaluator();
static MapObjectsEvaluator & getInstance(); static MapObjectsEvaluator & getInstance();
boost::optional<int> getObjectValue(int primaryID, int secondaryID) const; std::optional<int> getObjectValue(int primaryID, int secondaryID) const;
boost::optional<int> getObjectValue(const CGObjectInstance * obj) const; std::optional<int> getObjectValue(const CGObjectInstance * obj) const;
void addObjectData(int primaryID, int secondaryID, int value); void addObjectData(int primaryID, int secondaryID, int value);
void removeObjectData(int primaryID, int secondaryID); void removeObjectData(int primaryID, int secondaryID);
}; };

View File

@ -83,7 +83,7 @@ bool AINodeStorage::isBattleNode(const CGPathNode * node) const
return (getAINode(node)->chainMask & BATTLE_CHAIN) > 0; return (getAINode(node)->chainMask & BATTLE_CHAIN) > 0;
} }
boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber) std::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber)
{ {
auto chains = nodes[layer][pos.z][pos.x][pos.y]; auto chains = nodes[layer][pos.z][pos.x][pos.y];
@ -102,15 +102,13 @@ boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, c
} }
} }
return boost::none; return std::nullopt;
} }
std::vector<CGPathNode *> AINodeStorage::getInitialNodes() std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
{ {
auto hpos = hero->visitablePos(); auto hpos = hero->visitablePos();
auto initialNode = auto initialNode = getOrCreateNode(hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN).value();
getOrCreateNode(hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN)
.get();
initialNode->turns = 0; initialNode->turns = 0;
initialNode->moveRemains = hero->movement; initialNode->moveRemains = hero->movement;
@ -171,10 +169,10 @@ std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
{ {
auto nextNode = getOrCreateNode(neighbour, i, srcNode->chainMask); auto nextNode = getOrCreateNode(neighbour, i, srcNode->chainMask);
if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET) if(!nextNode || nextNode.value()->accessible == CGPathNode::NOT_SET)
continue; continue;
neighbours.push_back(nextNode.get()); neighbours.push_back(nextNode.value());
} }
} }
@ -207,7 +205,7 @@ std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
if(!node) if(!node)
continue; continue;
neighbours.push_back(node.get()); neighbours.push_back(node.value());
} }
} }
@ -273,7 +271,7 @@ void AINodeStorage::calculateTownPortalTeleportations(
logAi->trace("Adding town portal node at %s", targetTown->name); logAi->trace("Adding town portal node at %s", targetTown->name);
#endif #endif
AIPathNode * node = nodeOptional.get(); AIPathNode * node = nodeOptional.value();
node->theNodeBefore = source.node; node->theNodeBefore = source.node;
node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown)); node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));

View File

@ -107,7 +107,7 @@ public:
bool isBattleNode(const CGPathNode * node) const; bool isBattleNode(const CGPathNode * node) const;
bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const; bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
boost::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, int chainNumber); std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, int chainNumber);
std::vector<AIPath> getChainInfo(const int3 & pos, bool isOnLand) const; std::vector<AIPath> getChainInfo(const int3 & pos, bool isOnLand) const;
bool isTileAccessible(const int3 & pos, const EPathfindingLayer layer) const; bool isTileAccessible(const int3 & pos, const EPathfindingLayer layer) const;

View File

@ -114,7 +114,7 @@ Goals::TGoalVec PathfindingManager::findPath(
const std::function<Goals::TSubgoal(int3)> doVisitTile) const const std::function<Goals::TSubgoal(int3)> doVisitTile) const
{ {
Goals::TGoalVec result; Goals::TGoalVec result;
boost::optional<uint64_t> armyValueRequired; std::optional<uint64_t> armyValueRequired;
uint64_t danger; uint64_t danger;
std::vector<AIPath> chainInfo = pathfinder->getPathInfo(hero, dest); std::vector<AIPath> chainInfo = pathfinder->getPathInfo(hero, dest);
@ -165,12 +165,12 @@ Goals::TGoalVec PathfindingManager::findPath(
if(!armyValueRequired || armyValueRequired > danger) if(!armyValueRequired || armyValueRequired > danger)
{ {
armyValueRequired = boost::make_optional(danger); armyValueRequired = std::make_optional(danger);
} }
} }
} }
danger = armyValueRequired.get_value_or(0); danger = armyValueRequired.value_or(0);
if(allowGatherArmy && danger > 0) if(allowGatherArmy && danger > 0)
{ {

View File

@ -120,7 +120,7 @@ namespace AIPathfinding
if(boatNodeOptional) if(boatNodeOptional)
{ {
AIPathNode * boatNode = boatNodeOptional.get(); AIPathNode * boatNode = boatNodeOptional.value();
if(boatNode->action == CGPathNode::UNKNOWN) if(boatNode->action == CGPathNode::UNKNOWN)
{ {

View File

@ -106,7 +106,7 @@ namespace AIPathfinding
return; return;
} }
AIPathNode * battleNode = battleNodeOptional.get(); auto * battleNode = battleNodeOptional.value();
if(battleNode->locked) if(battleNode->locked)
{ {

View File

@ -1241,14 +1241,14 @@ void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruit
} }
} }
bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional<float> movementCostLimit) bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit)
{ {
int3 op = obj->visitablePos(); int3 op = obj->visitablePos();
auto paths = ah->getPathsToTile(h, op); auto paths = ah->getPathsToTile(h, op);
for(const auto & path : paths) for(const auto & path : paths)
{ {
if(movementCostLimit && movementCostLimit.get() < path.movementCost()) if(movementCostLimit && movementCostLimit.value() < path.movementCost())
return false; return false;
if(isGoodForVisit(obj, h, path)) if(isGoodForVisit(obj, h, path))
@ -1363,18 +1363,13 @@ void VCAI::wander(HeroPtr h)
}); });
int pass = 0; int pass = 0;
std::vector<boost::optional<float>> distanceLimits = std::vector<std::optional<float>> distanceLimits = {1.0, 2.0, std::nullopt};
{
1.0,
2.0,
boost::none
};
while(!dests.size() && pass < distanceLimits.size()) while(!dests.size() && pass < distanceLimits.size())
{ {
auto & distanceLimit = distanceLimits[pass]; auto & distanceLimit = distanceLimits[pass];
logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.get_value_or(-1.0)); logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0));
vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
{ {

View File

@ -217,7 +217,7 @@ public:
void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero
void recruitHero(const CGTownInstance * t, bool throwing = false); void recruitHero(const CGTownInstance * t, bool throwing = false);
bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional<float> movementCostLimit = boost::none); bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit = std::nullopt);
bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const; bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const;
//void recruitCreatures(const CGTownInstance * t); //void recruitCreatures(const CGTownInstance * t);
void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter); void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter);

View File

@ -90,7 +90,7 @@ bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, Crea
void CCallback::endTurn() void CCallback::endTurn()
{ {
logGlobal->trace("Player %d ended his turn.", player.get().getNum()); logGlobal->trace("Player %d ended his turn.", player->getNum());
EndTurn pack; EndTurn pack;
sendRequest(&pack); sendRequest(&pack);
} }
@ -306,8 +306,8 @@ void CCallback::buildBoat( const IShipyard *obj )
sendRequest(&bb); sendRequest(&bb);
} }
CCallback::CCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient * C) CCallback::CCallback(CGameState * GS, std::optional<PlayerColor> Player, CClient * C):
: CBattleCallback(Player, C) CBattleCallback(Player, C)
{ {
gs = GS; gs = GS;
@ -380,7 +380,7 @@ scripting::Pool * CBattleCallback::getContextPool() const
} }
#endif #endif
CBattleCallback::CBattleCallback(boost::optional<PlayerColor> Player, CClient *C ) CBattleCallback::CBattleCallback(std::optional<PlayerColor> Player, CClient * C)
{ {
player = Player; player = Player;
cl = C; cl = C;
@ -395,8 +395,7 @@ bool CBattleCallback::battleMakeTacticAction( BattleAction * action )
return true; return true;
} }
boost::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision( std::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState)
const BattleStateInfoForRetreat & battleState)
{ {
return cl->playerint[getPlayerID().get()]->makeSurrenderRetreatDecision(battleState); return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleState);
} }

View File

@ -54,7 +54,7 @@ public:
//battle //battle
virtual int battleMakeAction(const BattleAction * action) = 0;//for casting spells by hero - DO NOT use it for moving active stack virtual int battleMakeAction(const BattleAction * action) = 0;//for casting spells by hero - DO NOT use it for moving active stack
virtual bool battleMakeTacticAction(BattleAction * action) = 0; // performs tactic phase actions virtual bool battleMakeTacticAction(BattleAction * action) = 0; // performs tactic phase actions
virtual boost::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) = 0; virtual std::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) = 0;
}; };
class IGameActionCallback class IGameActionCallback
@ -113,10 +113,10 @@ protected:
CClient *cl; CClient *cl;
public: public:
CBattleCallback(boost::optional<PlayerColor> Player, CClient *C); CBattleCallback(std::optional<PlayerColor> Player, CClient * C);
int battleMakeAction(const BattleAction * action) override;//for casting spells by hero - DO NOT use it for moving active stack int battleMakeAction(const BattleAction * action) override;//for casting spells by hero - DO NOT use it for moving active stack
bool battleMakeTacticAction(BattleAction * action) override; // performs tactic phase actions bool battleMakeTacticAction(BattleAction * action) override; // performs tactic phase actions
boost::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override; std::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override;
#if SCRIPTING_ENABLED #if SCRIPTING_ENABLED
scripting::Pool * getContextPool() const override; scripting::Pool * getContextPool() const override;
@ -131,7 +131,7 @@ class CCallback : public CPlayerSpecificInfoCallback,
public CBattleCallback public CBattleCallback
{ {
public: public:
CCallback(CGameState * GS, boost::optional<PlayerColor> Player, CClient *C); CCallback(CGameState * GS, std::optional<PlayerColor> Player, CClient * C);
virtual ~CCallback(); virtual ~CCallback();
//client-specific functionalities (pathfinding) //client-specific functionalities (pathfinding)

View File

@ -577,8 +577,8 @@ namespace vstd
return i >= 0 && i < c.size(); return i >= 0 && i < c.size();
} }
template <typename Container, typename Index> template<typename Container, typename Index>
boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i) std::optional<typename Container::value_type> tryAt(const Container & c, Index i)
{ {
if(isValidIndex(c, i)) if(isValidIndex(c, i))
{ {
@ -586,15 +586,15 @@ namespace vstd
std::advance(itr, i); std::advance(itr, i);
return *itr; return *itr;
} }
return boost::none; return std::nullopt;
} }
template <typename Container, typename Pred> template<typename Container, typename Pred>
static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t) static std::optional<typename Container::const_reference> tryFindIf(const Container & r, const Pred & t)
{ {
auto pos = range::find_if(r, t); auto pos = range::find_if(r, t);
if(pos == boost::end(r)) if(pos == boost::end(r))
return boost::none; return std::nullopt;
else else
return *pos; return *pos;
} }
@ -669,8 +669,8 @@ namespace vstd
return false; return false;
} }
template <class M, class Key, class F> template<class M, class Key, class F>
typename M::mapped_type & getOrCompute(M & m, Key const & k, F f) typename M::mapped_type & getOrCompute(M & m, const Key & k, F f)
{ {
typedef typename M::mapped_type V; typedef typename M::mapped_type V;

View File

@ -328,7 +328,7 @@ void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
if (details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK) if (details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
{ {
if(hero->getRemovalSound() && hero->tempOwner == playerID) if(hero->getRemovalSound() && hero->tempOwner == playerID)
CCS->soundh->playSound(hero->getRemovalSound().get()); CCS->soundh->playSound(hero->getRemovalSound().value());
} }
adventureInt->minimap->updateTile(hero->convertToVisitablePos(details.start)); adventureInt->minimap->updateTile(hero->convertToVisitablePos(details.start));
@ -463,7 +463,7 @@ void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectI
if(start && visitedObj) if(start && visitedObj)
{ {
if(visitedObj->getVisitSound()) if(visitedObj->getVisitSound())
CCS->soundh->playSound(visitedObj->getVisitSound().get()); CCS->soundh->playSound(visitedObj->getVisitSound().value());
} }
} }
@ -1530,7 +1530,7 @@ void CPlayerInterface::objectRemoved(const CGObjectInstance * obj)
if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound()) if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound())
{ {
waitWhileDialog(); waitWhileDialog();
CCS->soundh->playSound(obj->getRemovalSound().get()); CCS->soundh->playSound(obj->getRemovalSound().value());
} }
CGI->mh->waitForOngoingAnimations(); CGI->mh->waitForOngoingAnimations();
@ -1758,7 +1758,7 @@ void CPlayerInterface::acceptTurn()
if(optDaysWithoutCastle) if(optDaysWithoutCastle)
{ {
auto daysWithoutCastle = optDaysWithoutCastle.get(); auto daysWithoutCastle = optDaysWithoutCastle.value();
if (daysWithoutCastle < 6) if (daysWithoutCastle < 6)
{ {
text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land. text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.

View File

@ -421,7 +421,7 @@ void CClient::initPlayerEnvironments()
if(settings["session"]["spectate"].Bool()) if(settings["session"]["spectate"].Bool())
{ {
playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, boost::none, this)); playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
} }
} }
@ -626,7 +626,7 @@ void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> ba
battleInt->yourTacticPhase(gs->curB->tacticDistance); battleInt->yourTacticPhase(gs->curB->tacticDistance);
if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game) if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
{ {
MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).get())); MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).value()));
sendRequest(&ma, battleInt->playerID); sendRequest(&ma, battleInt->playerID);
} }
} }

View File

@ -140,7 +140,7 @@ public:
std::map<PlayerColor, std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts; std::map<PlayerColor, std::vector<std::shared_ptr<IBattleEventsReceiver>>> additionalBattleInts;
boost::optional<BattleAction> curbaction; std::optional<BattleAction> curbaction;
CClient(); CClient();
~CClient(); ~CClient();

View File

@ -762,7 +762,7 @@ void ApplyClientNetPackVisitor::visitBattleAttack(BattleAttack & pack)
void ApplyFirstClientNetPackVisitor::visitStartAction(StartAction & pack) void ApplyFirstClientNetPackVisitor::visitStartAction(StartAction & pack)
{ {
cl.curbaction = boost::make_optional(pack.ba); cl.curbaction = std::make_optional(pack.ba);
callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionStarted, pack.ba); callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionStarted, pack.ba);
} }

View File

@ -853,7 +853,7 @@ void CAdvMapInt::keyPressed(const SDL_Keycode & key)
} }
} }
boost::optional<Point> CAdvMapInt::keyToMoveDirection(const SDL_Keycode & key) std::optional<Point> CAdvMapInt::keyToMoveDirection(const SDL_Keycode & key)
{ {
switch (key) { switch (key) {
case SDLK_DOWN: return Point( 0, +1); case SDLK_DOWN: return Point( 0, +1);
@ -871,7 +871,7 @@ boost::optional<Point> CAdvMapInt::keyToMoveDirection(const SDL_Keycode & key)
case SDLK_KP_8: return Point( 0, -1); case SDLK_KP_8: return Point( 0, -1);
case SDLK_KP_9: return Point(+1, -1); case SDLK_KP_9: return Point(+1, -1);
} }
return boost::none; return std::nullopt;
} }
void CAdvMapInt::select(const CArmedInstance *sel, bool centerView) void CAdvMapInt::select(const CArmedInstance *sel, bool centerView)

View File

@ -143,7 +143,7 @@ private:
const CGObjectInstance *getActiveObject(const int3 &tile); const CGObjectInstance *getActiveObject(const int3 &tile);
boost::optional<Point> keyToMoveDirection(const SDL_Keycode & key); std::optional<Point> keyToMoveDirection(const SDL_Keycode & key);
public: public:
CAdvMapInt(); CAdvMapInt();

View File

@ -136,7 +136,7 @@ std::vector<std::string> MapAudioPlayer::getAmbientSounds(const int3 & tile)
logGlobal->warn("Already removed object %d found on tile! (%d %d %d)", objectID.getNum(), tile.x, tile.y, tile.z); logGlobal->warn("Already removed object %d found on tile! (%d %d %d)", objectID.getNum(), tile.x, tile.y, tile.z);
if(object && object->getAmbientSound()) if(object && object->getAmbientSound())
result.push_back(object->getAmbientSound().get()); result.push_back(object->getAmbientSound().value());
} }
if(CGI->mh->getMap()->isCoastalTile(tile)) if(CGI->mh->getMap()->isCoastalTile(tile))

View File

@ -252,7 +252,7 @@ void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 addit
} }
auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()() auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()()
ba->side = side.get(); ba->side = side.value();
ba->actionType = action; ba->actionType = action;
ba->aimToHex(tile); ba->aimToHex(tile);
ba->actionSubtype = additional; ba->actionSubtype = additional;

View File

@ -68,7 +68,7 @@ void BattleConsole::showAll(SDL_Surface * to)
std::vector<std::string> BattleConsole::getVisibleText() std::vector<std::string> BattleConsole::getVisibleText()
{ {
// high priority texts that hide battle log entries // high priority texts that hide battle log entries
for (auto const & text : {consoleText, hoverText} ) for(const auto & text : {consoleText, hoverText})
{ {
if (text.empty()) if (text.empty())
continue; continue;
@ -94,7 +94,7 @@ std::vector<std::string> BattleConsole::splitText(const std::string &text)
boost::split(lines, text, boost::is_any_of("\n")); boost::split(lines, text, boost::is_any_of("\n"));
for (auto const & line : lines) for(const auto & line : lines)
{ {
if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w) if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w)
{ {
@ -679,7 +679,7 @@ int32_t StackQueue::getSiegeShooterIconID()
return owner.siegeController->getSiegedTown()->town->faction->getIndex(); return owner.siegeController->getSiegedTown()->town->faction->getIndex();
} }
boost::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const std::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const
{ {
for(const auto & stackBox : stackBoxes) for(const auto & stackBox : stackBoxes)
{ {
@ -689,7 +689,7 @@ boost::optional<uint32_t> StackQueue::getHoveredUnitIdIfAny() const
} }
} }
return boost::none; return std::nullopt;
} }
StackQueue::StackBox::StackBox(StackQueue * owner): StackQueue::StackBox::StackBox(StackQueue * owner):
@ -758,7 +758,7 @@ void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn)
} }
else else
{ {
boundUnitID = boost::none; boundUnitID = std::nullopt;
background->colorize(PlayerColor::NEUTRAL); background->colorize(PlayerColor::NEUTRAL);
icon->visible = false; icon->visible = false;
icon->setFrame(0); icon->setFrame(0);
@ -769,7 +769,7 @@ void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn)
} }
} }
boost::optional<uint32_t> StackQueue::StackBox::getBoundUnitID() const std::optional<uint32_t> StackQueue::StackBox::getBoundUnitID() const
{ {
return boundUnitID; return boundUnitID;
} }

View File

@ -166,7 +166,7 @@ class StackQueue : public CIntObject
class StackBox : public CIntObject class StackBox : public CIntObject
{ {
StackQueue * owner; StackQueue * owner;
boost::optional<uint32_t> boundUnitID; std::optional<uint32_t> boundUnitID;
bool highlighted = false; bool highlighted = false;
public: public:
@ -178,7 +178,7 @@ class StackQueue : public CIntObject
StackBox(StackQueue * owner); StackBox(StackQueue * owner);
void setUnit(const battle::Unit * unit, size_t turn = 0); void setUnit(const battle::Unit * unit, size_t turn = 0);
void toggleHighlight(bool value); void toggleHighlight(bool value);
boost::optional<uint32_t> getBoundUnitID() const; std::optional<uint32_t> getBoundUnitID() const;
void show(SDL_Surface * to) override; void show(SDL_Surface * to) override;
}; };
@ -197,7 +197,7 @@ public:
StackQueue(bool Embedded, BattleInterface & owner); StackQueue(bool Embedded, BattleInterface & owner);
void update(); void update();
boost::optional<uint32_t> getHoveredUnitIdIfAny() const; std::optional<uint32_t> getHoveredUnitIdIfAny() const;
void show(SDL_Surface * to) override; void show(SDL_Surface * to) override;
}; };

View File

@ -66,7 +66,7 @@ void BattleObstacleController::loadObstacleImage(const CObstacleInstance & oi)
void BattleObstacleController::obstacleRemoved(const std::vector<ObstacleChanges> & obstacles) void BattleObstacleController::obstacleRemoved(const std::vector<ObstacleChanges> & obstacles)
{ {
for (auto const & oi : obstacles) for(const auto & oi : obstacles)
{ {
auto & obstacle = oi.data["obstacle"]; auto & obstacle = oi.data["obstacle"];
@ -97,11 +97,11 @@ void BattleObstacleController::obstacleRemoved(const std::vector<ObstacleChanges
void BattleObstacleController::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> & obstacles) void BattleObstacleController::obstaclePlaced(const std::vector<std::shared_ptr<const CObstacleInstance>> & obstacles)
{ {
for (auto const & oi : obstacles) for(const auto & oi : obstacles)
{ {
auto side = owner.curInt->cb->playerToSide(owner.curInt->playerID); auto side = owner.curInt->cb->playerToSide(owner.curInt->playerID);
if(!oi->visibleForSide(side.get(),owner.curInt->cb->battleHasNativeStack(side.get()))) if(!oi->visibleForSide(side.value(), owner.curInt->cb->battleHasNativeStack(side.value())))
continue; continue;
auto animation = std::make_shared<CAnimation>(oi->getAppearAnimation()); auto animation = std::make_shared<CAnimation>(oi->getAppearAnimation());

View File

@ -281,7 +281,7 @@ std::shared_ptr<IImage> BattleStacksController::getStackAmountBox(const CStack *
int effectsPositivness = 0; int effectsPositivness = 0;
for ( auto const & spellID : activeSpells) for(const auto & spellID : activeSpells)
effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness; effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness;
if (effectsPositivness > 0) if (effectsPositivness > 0)
@ -336,7 +336,7 @@ void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack *
void BattleStacksController::showStack(Canvas & canvas, const CStack * stack) void BattleStacksController::showStack(Canvas & canvas, const CStack * stack)
{ {
ColorFilter fullFilter = ColorFilter::genEmptyShifter(); ColorFilter fullFilter = ColorFilter::genEmptyShifter();
for (auto const & filter : stackFilterEffects) for(const auto & filter : stackFilterEffects)
{ {
if (filter.target == stack) if (filter.target == stack)
fullFilter = ColorFilter::genCombined(fullFilter, filter.effect); fullFilter = ColorFilter::genCombined(fullFilter, filter.effect);
@ -814,7 +814,7 @@ void BattleStacksController::updateHoveredStacks()
{ {
auto newStacks = selectHoveredStacks(); auto newStacks = selectHoveredStacks();
for (auto const * stack : mouseHoveredStacks) for(const auto * stack : mouseHoveredStacks)
{ {
if (vstd::contains(newStacks, stack)) if (vstd::contains(newStacks, stack))
continue; continue;
@ -825,7 +825,7 @@ void BattleStacksController::updateHoveredStacks()
stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder()); stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder());
} }
for (auto const * stack : newStacks) for(const auto * stack : newStacks)
{ {
if (vstd::contains(mouseHoveredStacks, stack)) if (vstd::contains(mouseHoveredStacks, stack))
continue; continue;
@ -848,7 +848,7 @@ std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
return {}; return {};
auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId(); auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId();
if(hoveredQueueUnitId.is_initialized()) if(hoveredQueueUnitId.has_value())
{ {
return { owner.curInt->cb->battleGetStackByID(hoveredQueueUnitId.value(), true) }; return { owner.curInt->cb->battleGetStackByID(hoveredQueueUnitId.value(), true) };
} }
@ -889,7 +889,7 @@ std::vector<const CStack *> BattleStacksController::selectHoveredStacks()
const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const const std::vector<uint32_t> BattleStacksController::getHoveredStacksUnitIds() const
{ {
auto result = std::vector<uint32_t>(); auto result = std::vector<uint32_t>();
for (auto const * stack : mouseHoveredStacks) for(const auto * stack : mouseHoveredStacks)
{ {
result.push_back(stack->unitId()); result.push_back(stack->unitId());
} }

View File

@ -590,7 +590,7 @@ void BattleWindow::blockUI(bool on)
} }
} }
boost::optional<uint32_t> BattleWindow::getQueueHoveredUnitId() std::optional<uint32_t> BattleWindow::getQueueHoveredUnitId()
{ {
return queue->getHoveredUnitIdIfAny(); return queue->getHoveredUnitIdIfAny();
} }

View File

@ -80,7 +80,7 @@ public:
void updateQueue(); void updateQueue();
/// Get mouse-hovered battle queue unit ID if any found /// Get mouse-hovered battle queue unit ID if any found
boost::optional<uint32_t> getQueueHoveredUnitId(); std::optional<uint32_t> getQueueHoveredUnitId();
void activate() override; void activate() override;
void deactivate() override; void deactivate() override;

View File

@ -57,15 +57,15 @@ void CButton::update()
redraw(); redraw();
} }
void CButton::setBorderColor(boost::optional<SDL_Color> borderColor) void CButton::setBorderColor(std::optional<SDL_Color> borderColor)
{ {
setBorderColor(borderColor, borderColor, borderColor, borderColor); setBorderColor(borderColor, borderColor, borderColor, borderColor);
} }
void CButton::setBorderColor(boost::optional<SDL_Color> normalBorderColor, void CButton::setBorderColor(std::optional<SDL_Color> normalBorderColor,
boost::optional<SDL_Color> pressedBorderColor, std::optional<SDL_Color> pressedBorderColor,
boost::optional<SDL_Color> blockedBorderColor, std::optional<SDL_Color> blockedBorderColor,
boost::optional<SDL_Color> highlightedBorderColor) std::optional<SDL_Color> highlightedBorderColor)
{ {
stateToBorderColor[NORMAL] = normalBorderColor; stateToBorderColor[NORMAL] = normalBorderColor;
stateToBorderColor[PRESSED] = pressedBorderColor; stateToBorderColor[PRESSED] = pressedBorderColor;
@ -591,7 +591,7 @@ void CSlider::setScrollBounds(const Rect & bounds )
void CSlider::clearScrollBounds() void CSlider::clearScrollBounds()
{ {
scrollBounds = boost::none; scrollBounds = std::nullopt;
} }
int CSlider::getAmount() const int CSlider::getAmount() const

View File

@ -52,7 +52,7 @@ private:
std::array<int, 4> stateToIndex; // mapping of button state to index of frame in animation std::array<int, 4> stateToIndex; // mapping of button state to index of frame in animation
std::array<std::string, 4> hoverTexts; //texts for statusbar, if empty - first entry will be used std::array<std::string, 4> hoverTexts; //texts for statusbar, if empty - first entry will be used
std::array<boost::optional<SDL_Color>, 4> stateToBorderColor; // mapping of button state to border color std::array<std::optional<SDL_Color>, 4> stateToBorderColor; // mapping of button state to border color
std::string helpBox; //for right-click help std::string helpBox; //for right-click help
std::shared_ptr<CAnimImage> image; //image for this button std::shared_ptr<CAnimImage> image; //image for this button
@ -73,13 +73,13 @@ public:
// sets border color for each button state; // sets border color for each button state;
// if it's set, the button will have 1-px border around it with this color // if it's set, the button will have 1-px border around it with this color
void setBorderColor(boost::optional<SDL_Color> normalBorderColor, void setBorderColor(std::optional<SDL_Color> normalBorderColor,
boost::optional<SDL_Color> pressedBorderColor, std::optional<SDL_Color> pressedBorderColor,
boost::optional<SDL_Color> blockedBorderColor, std::optional<SDL_Color> blockedBorderColor,
boost::optional<SDL_Color> highlightedBorderColor); std::optional<SDL_Color> highlightedBorderColor);
// sets the same border color for all button states. // sets the same border color for all button states.
void setBorderColor(boost::optional<SDL_Color> borderColor); void setBorderColor(std::optional<SDL_Color> borderColor);
/// adds one more callback to on-click actions /// adds one more callback to on-click actions
void addCallback(std::function<void()> callback); void addCallback(std::function<void()> callback);
@ -229,7 +229,7 @@ class CSlider : public CIntObject
std::shared_ptr<CButton> right; std::shared_ptr<CButton> right;
std::shared_ptr<CButton> slider; std::shared_ptr<CButton> slider;
boost::optional<Rect> scrollBounds; std::optional<Rect> scrollBounds;
int capacity;//how many elements can be active at same time (e.g. hero list = 5) int capacity;//how many elements can be active at same time (e.g. hero list = 5)
int positions; //number of highest position (0 if there is only one) int positions; //number of highest position (0 if there is only one)

View File

@ -85,7 +85,7 @@ void CPicture::show(SDL_Surface * to)
void CPicture::showAll(SDL_Surface * to) void CPicture::showAll(SDL_Surface * to)
{ {
if(bg && visible) if(bg && visible)
bg->draw(to, pos.x, pos.y, srcRect.get_ptr()); bg->draw(to, pos.x, pos.y, srcRect.has_value() ? &srcRect.value() : nullptr);
} }
void CPicture::setAlpha(int value) void CPicture::setAlpha(int value)

View File

@ -30,7 +30,7 @@ class CPicture : public CIntObject
public: public:
/// if set, only specified section of internal image will be rendered /// if set, only specified section of internal image will be rendered
boost::optional<Rect> srcRect; std::optional<Rect> srcRect;
/// If set to true, iamge will be redrawn on each frame /// If set to true, iamge will be redrawn on each frame
bool needRefresh; bool needRefresh;

View File

@ -64,9 +64,9 @@ public:
const CGHeroInstance * owner; const CGHeroInstance * owner;
// temporary objects which should be kept as copy if needed // temporary objects which should be kept as copy if needed
boost::optional<CommanderLevelInfo> levelupInfo; std::optional<CommanderLevelInfo> levelupInfo;
boost::optional<StackDismissInfo> dismissInfo; std::optional<StackDismissInfo> dismissInfo;
boost::optional<StackUpgradeInfo> upgradeInfo; std::optional<StackUpgradeInfo> upgradeInfo;
// misc fields // misc fields
unsigned int creatureCount; unsigned int creatureCount;
@ -246,8 +246,8 @@ CStackWindow::BonusLineSection::BonusLineSection(CStackWindow * owner, size_t li
} }
} }
CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, boost::optional<size_t> preferredSize) CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, std::optional<size_t> preferredSize):
: CWindowSection(owner, "", yOffset) CWindowSection(owner, "", yOffset)
{ {
OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE); OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
@ -255,7 +255,7 @@ CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset,
static const int itemHeight = 59; static const int itemHeight = 59;
size_t totalSize = (owner->activeBonuses.size() + 1) / 2; size_t totalSize = (owner->activeBonuses.size() + 1) / 2;
size_t visibleSize = preferredSize ? preferredSize.get() : std::min<size_t>(3, totalSize); size_t visibleSize = preferredSize.value_or(std::min<size_t>(3, totalSize));
pos.w = owner->pos.w; pos.w = owner->pos.w;
pos.h = itemHeight * (int)visibleSize; pos.h = itemHeight * (int)visibleSize;
@ -292,7 +292,7 @@ CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
// used space overlaps with commander switch button // used space overlaps with commander switch button
// besides - should commander really be upgradeable? // besides - should commander really be upgradeable?
UnitView::StackUpgradeInfo & upgradeInfo = parent->info->upgradeInfo.get(); auto & upgradeInfo = parent->info->upgradeInfo.value();
const size_t buttonsToCreate = std::min<size_t>(upgradeInfo.info.newID.size(), upgrade.size()); const size_t buttonsToCreate = std::min<size_t>(upgradeInfo.info.newID.size(), upgrade.size());
for(size_t buttonIndex = 0; buttonIndex < buttonsToCreate; buttonIndex++) for(size_t buttonIndex = 0; buttonIndex < buttonsToCreate; buttonIndex++)
@ -686,8 +686,8 @@ CStackWindow::CStackWindow(const CStackInstance * stack, std::function<void()> d
info->creature = stack->type; info->creature = stack->type;
info->creatureCount = stack->count; info->creatureCount = stack->count;
info->upgradeInfo = boost::make_optional(UnitView::StackUpgradeInfo()); info->upgradeInfo = std::make_optional(UnitView::StackUpgradeInfo());
info->dismissInfo = boost::make_optional(UnitView::StackDismissInfo()); info->dismissInfo = std::make_optional(UnitView::StackDismissInfo());
info->upgradeInfo->info = upgradeInfo; info->upgradeInfo->info = upgradeInfo;
info->upgradeInfo->callback = callback; info->upgradeInfo->callback = callback;
info->dismissInfo->callback = dismiss; info->dismissInfo->callback = dismiss;
@ -716,7 +716,7 @@ CStackWindow::CStackWindow(const CCommanderInstance * commander, std::vector<ui3
info->creature = commander->type; info->creature = commander->type;
info->commander = commander; info->commander = commander;
info->creatureCount = 1; info->creatureCount = 1;
info->levelupInfo = boost::make_optional(UnitView::CommanderLevelInfo()); info->levelupInfo = std::make_optional(UnitView::CommanderLevelInfo());
info->levelupInfo->skills = skills; info->levelupInfo->skills = skills;
info->levelupInfo->callback = callback; info->levelupInfo->callback = callback;
info->owner = dynamic_cast<const CGHeroInstance *> (commander->armyObj); info->owner = dynamic_cast<const CGHeroInstance *> (commander->armyObj);
@ -814,7 +814,7 @@ void CStackWindow::initSections()
commanderMainSection = std::make_shared<CommanderMainSection>(this, 0); commanderMainSection = std::make_shared<CommanderMainSection>(this, 0);
auto size = boost::make_optional<size_t>((info->levelupInfo) ? 4 : 3); auto size = std::make_optional<size_t>((info->levelupInfo) ? 4 : 3);
commanderBonusesSection = std::make_shared<BonusesSection>(this, 0, size); commanderBonusesSection = std::make_shared<BonusesSection>(this, 0, size);
deactivateObj(commanderBonusesSection); deactivateObj(commanderBonusesSection);

View File

@ -83,7 +83,7 @@ class CStackWindow : public CWindowObject
{ {
std::shared_ptr<CListBox> lines; std::shared_ptr<CListBox> lines;
public: public:
BonusesSection(CStackWindow * owner, int yOffset, boost::optional<size_t> preferredSize = boost::optional<size_t>()); BonusesSection(CStackWindow * owner, int yOffset, std::optional<size_t> preferredSize = std::optional<size_t>());
}; };
class ButtonsSection : public CWindowSection class ButtonsSection : public CWindowSection

View File

@ -740,15 +740,16 @@ void CArtHandler::erasePickedArt(const ArtifactID & id)
{ {
CArtifact *art = objects[id]; CArtifact *art = objects[id];
if(auto artifactList = listFromClass(art->aClass)) if(auto artl = listFromClass(art->aClass))
{ {
if(artifactList->empty()) auto & artifactList = artl->get();
fillList(*artifactList, art->aClass); if(artifactList.empty())
fillList(artifactList, art->aClass);
auto itr = vstd::find(*artifactList, art); auto itr = vstd::find(artifactList, art);
if(itr != artifactList->end()) if(itr != artifactList.end())
{ {
artifactList->erase(itr); artifactList.erase(itr);
} }
else else
logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated()); logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated());
@ -758,20 +759,20 @@ void CArtHandler::erasePickedArt(const ArtifactID & id)
logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated()); logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated());
} }
boost::optional<std::vector<CArtifact*>&> CArtHandler::listFromClass( CArtifact::EartClass artifactClass ) std::optional<std::reference_wrapper<std::vector<CArtifact *>>> CArtHandler::listFromClass(CArtifact::EartClass artifactClass)
{ {
switch(artifactClass) switch(artifactClass)
{ {
case CArtifact::ART_TREASURE: case CArtifact::ART_TREASURE:
return treasures; return {std::ref(treasures)};
case CArtifact::ART_MINOR: case CArtifact::ART_MINOR:
return minors; return {std::ref(minors)};
case CArtifact::ART_MAJOR: case CArtifact::ART_MAJOR:
return majors; return {std::ref(majors)};
case CArtifact::ART_RELIC: case CArtifact::ART_RELIC:
return relics; return {std::ref(relics)};
default: //special artifacts should not be erased default: //special artifacts should not be erased
return boost::optional<std::vector<CArtifact*>&>(); return {};
} }
} }

View File

@ -244,7 +244,7 @@ public:
void fillList(std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass); //fills given empty list with allowed artifacts of given class. No side effects void fillList(std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass); //fills given empty list with allowed artifacts of given class. No side effects
boost::optional<std::vector<CArtifact*>&> listFromClass(CArtifact::EartClass artifactClass); std::optional<std::reference_wrapper<std::vector<CArtifact *>>> listFromClass(CArtifact::EartClass artifactClass);
static CArtifact::EartClass stringToClass(const std::string & className); //TODO: rework EartClass to make this a constructor static CArtifact::EartClass stringToClass(const std::string & className); //TODO: rework EartClass to make this a constructor

View File

@ -408,7 +408,7 @@ CCreatureHandler::CCreatureHandler()
const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const
{ {
boost::optional<si32> index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier); std::optional<si32> index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier);
if(!index) if(!index)
throw std::runtime_error("Creature not found "+identifier); throw std::runtime_error("Creature not found "+identifier);

View File

@ -624,7 +624,7 @@ void CCreatureSet::armyChanged()
} }
void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const boost::optional<int> fixedSize) void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const std::optional<int> fixedSize)
{ {
if(handler.saving && stacks.empty()) if(handler.saving && stacks.empty())
return; return;
@ -640,7 +640,7 @@ void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::strin
vstd::amax(sz, p.first.getNum()+1); vstd::amax(sz, p.first.getNum()+1);
if(fixedSize) if(fixedSize)
vstd::amax(sz, fixedSize.get()); vstd::amax(sz, fixedSize.value());
a.resize(sz, JsonNode::JsonType::DATA_STRUCT); a.resize(sz, JsonNode::JsonType::DATA_STRUCT);

View File

@ -75,7 +75,7 @@ public:
uint8_t upgrade; uint8_t upgrade;
}; };
// helper variable used during loading map, when object (hero or town) have creatures that must have same alignment. // helper variable used during loading map, when object (hero or town) have creatures that must have same alignment.
boost::optional<RandomStackInfo> randomStack; std::optional<RandomStackInfo> randomStack;
const CArmedInstance * const & armyObj; //stack must be part of some army, army must be part of some object const CArmedInstance * const & armyObj; //stack must be part of some army, army must be part of some object
TExpType experience;//commander needs same amount of exp as hero TExpType experience;//commander needs same amount of exp as hero
@ -286,7 +286,7 @@ public:
h & formation; h & formation;
} }
void serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const boost::optional<int> fixedSize = boost::none); void serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const std::optional<int> fixedSize = std::nullopt);
operator bool() const operator bool() const
{ {

View File

@ -401,7 +401,7 @@ int CGameInfoCallback::getDate(Date::EDateType mode) const
return gs->getDate(mode); return gs->getDate(mode);
} }
bool CGameInfoCallback::isVisible(int3 pos, const boost::optional<PlayerColor> & Player) const bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
{ {
//boost::shared_lock<boost::shared_mutex> lock(*gs->mx); //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
return gs->isVisible(pos, Player); return gs->isVisible(pos, Player);
@ -412,7 +412,7 @@ bool CGameInfoCallback::isVisible(int3 pos) const
return isVisible(pos, player); return isVisible(pos, player);
} }
bool CGameInfoCallback::isVisible( const CGObjectInstance *obj,const boost::optional<PlayerColor> & Player) const bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
{ {
return gs->isVisible(obj, Player); return gs->isVisible(obj, Player);
} }
@ -521,8 +521,8 @@ EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) cons
//TODO: typedef? //TODO: typedef?
std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
{ {
assert(player.is_initialized()); assert(player.has_value());
const auto * team = getPlayerTeam(player.get()); const auto * team = getPlayerTeam(player.value());
size_t width = gs->map->width; size_t width = gs->map->width;
size_t height = gs->map->height; size_t height = gs->map->height;
@ -619,9 +619,9 @@ const CMapHeader * CGameInfoCallback::getMapHeader() const
return gs->map; return gs->map;
} }
bool CGameInfoCallback::hasAccess(boost::optional<PlayerColor> playerId) const bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
{ {
return !player || player.get().isSpectator() || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES; return !player || player->isSpectator() || gs->getPlayerRelations(*playerId, *player) != PlayerRelations::ENEMIES;
} }
EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
@ -703,7 +703,7 @@ PlayerColor CGameInfoCallback::getCurrentPlayer() const
return gs->currentPlayer; return gs->currentPlayer;
} }
CGameInfoCallback::CGameInfoCallback(CGameState * GS, boost::optional<PlayerColor> Player): CGameInfoCallback::CGameInfoCallback(CGameState * GS, std::optional<PlayerColor> Player):
gs(GS) gs(GS)
{ {
player = std::move(Player); player = std::move(Player);
@ -754,7 +754,7 @@ std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo
return ret; return ret;
} }
boost::optional<PlayerColor> CPlayerSpecificInfoCallback::getMyColor() const std::optional<PlayerColor> CPlayerSpecificInfoCallback::getMyColor() const
{ {
return player; return player;
} }
@ -882,7 +882,7 @@ const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
if (team != gs->teams.end()) if (team != gs->teams.end())
{ {
const TeamState *ret = &team->second; const TeamState *ret = &team->second;
if (!player.is_initialized()) //neutral (or invalid) player if(!player.has_value()) //neutral (or invalid) player
return ret; return ret;
else else
{ {

View File

@ -133,8 +133,8 @@ protected:
CGameState * gs;//todo: replace with protected const getter, only actual Server and Client objects should hold game state CGameState * gs;//todo: replace with protected const getter, only actual Server and Client objects should hold game state
CGameInfoCallback() = default; CGameInfoCallback() = default;
CGameInfoCallback(CGameState *GS, boost::optional<PlayerColor> Player); CGameInfoCallback(CGameState * GS, std::optional<PlayerColor> Player);
bool hasAccess(boost::optional<PlayerColor> playerId) const; bool hasAccess(std::optional<PlayerColor> playerId) const;
bool canGetFullInfo(const CGObjectInstance *obj) const; //true we player owns obj or ally owns obj or privileged mode bool canGetFullInfo(const CGObjectInstance *obj) const; //true we player owns obj or ally owns obj or privileged mode
bool isOwnedOrVisited(const CGObjectInstance *obj) const; bool isOwnedOrVisited(const CGObjectInstance *obj) const;
@ -157,9 +157,9 @@ public:
virtual const PlayerSettings * getPlayerSettings(PlayerColor color) const; virtual const PlayerSettings * getPlayerSettings(PlayerColor color) const;
//map //map
virtual bool isVisible(int3 pos, const boost::optional<PlayerColor> & Player) const; virtual bool isVisible(int3 pos, const std::optional<PlayerColor> & Player) const;
virtual bool isVisible(const CGObjectInstance *obj, const boost::optional<PlayerColor> & Player) const; virtual bool isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const;
virtual bool isVisible(const CGObjectInstance *obj) const; virtual bool isVisible(const CGObjectInstance * obj) const;
virtual bool isVisible(int3 pos) const; virtual bool isVisible(int3 pos) const;
@ -234,7 +234,7 @@ public:
virtual int howManyTowns() const; virtual int howManyTowns() const;
virtual int howManyHeroes(bool includeGarrisoned = true) const; virtual int howManyHeroes(bool includeGarrisoned = true) const;
virtual int3 getGrailPos(double *outKnownRatio); virtual int3 getGrailPos(double *outKnownRatio);
virtual boost::optional<PlayerColor> getMyColor() const; virtual std::optional<PlayerColor> getMyColor() const;
virtual std::vector <const CGTownInstance *> getTownsInfo(bool onlyOur = true) const; //true -> only owned; false -> all visible virtual std::vector <const CGTownInstance *> getTownsInfo(bool onlyOur = true) const; //true -> only owned; false -> all visible
virtual int getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned=true) const; virtual int getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned=true) const;

View File

@ -110,9 +110,9 @@ public:
virtual void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain){}; virtual void showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain){};
virtual boost::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) virtual std::optional<BattleAction> makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState)
{ {
return boost::none; return std::nullopt;
} }
virtual void saveGame(BinarySerializer & h, const int version) = 0; virtual void saveGame(BinarySerializer & h, const int version) = 0;

View File

@ -925,7 +925,7 @@ void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRan
void CGameState::initCampaign() void CGameState::initCampaign()
{ {
logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.get()); logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.value());
map = scenarioOps->campState->getMap(); map = scenarioOps->campState->getMap();
} }
@ -1068,7 +1068,7 @@ void CGameState::placeCampaignHeroes()
{ {
// place bonus hero // place bonus hero
auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap(); auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
bool campaignGiveHero = campaignBonus && campaignBonus.get().type == CScenarioTravel::STravelBonus::HERO; bool campaignGiveHero = campaignBonus && campaignBonus->type == CScenarioTravel::STravelBonus::HERO;
if(campaignGiveHero) if(campaignGiveHero)
{ {
@ -1568,7 +1568,7 @@ void CGameState::initHeroes()
void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero) void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
{ {
const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap(); const std::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
if(!curBonus) if(!curBonus)
return; return;
@ -2234,7 +2234,7 @@ void CGameState::updateRumor()
while(!rumor.update(rumorId, rumorExtra)); while(!rumor.update(rumorId, rumorExtra));
} }
bool CGameState::isVisible(int3 pos, const boost::optional<PlayerColor> & player) const bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
{ {
if (!map->isInTheMap(pos)) if (!map->isInTheMap(pos))
return false; return false;
@ -2248,7 +2248,7 @@ bool CGameState::isVisible(int3 pos, const boost::optional<PlayerColor> & player
return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y]; return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
} }
bool CGameState::isVisible( const CGObjectInstance *obj, const boost::optional<PlayerColor> & player) const bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
{ {
if(!player) if(!player)
return true; return true;
@ -2433,7 +2433,7 @@ bool CGameState::checkForVictory(const PlayerColor & player, const EventConditio
case EventCondition::DAYS_WITHOUT_TOWN: case EventCondition::DAYS_WITHOUT_TOWN:
{ {
if (p->daysWithoutCastle) if (p->daysWithoutCastle)
return p->daysWithoutCastle.get() >= condition.value; return p->daysWithoutCastle >= condition.value;
else else
return false; return false;
} }

View File

@ -202,9 +202,8 @@ public:
void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
bool isVisible(int3 pos, const std::optional<PlayerColor> & player) const override;
bool isVisible(int3 pos, const boost::optional<PlayerColor> & player) const override; bool isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const override;
bool isVisible(const CGObjectInstance *obj, const boost::optional<PlayerColor> & player) const override;
int getDate(Date::EDateType mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month int getDate(Date::EDateType mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month

View File

@ -156,7 +156,7 @@ void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const Js
requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true)); requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true));
} }
boost::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent)
{ {
auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent)); auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent));
@ -165,10 +165,10 @@ boost::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scop
if (!silent) if (!silent)
logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope); logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
return boost::optional<si32>(); return std::optional<si32>();
} }
boost::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent)
{ {
auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent)); auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent));
@ -177,10 +177,10 @@ boost::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type
if (!silent) if (!silent)
logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta); logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
return boost::optional<si32>(); return std::optional<si32>();
} }
boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
{ {
auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent)); auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent));
@ -189,10 +189,10 @@ boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, b
if (!silent) if (!silent)
logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta); logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta);
return boost::optional<si32>(); return std::optional<si32>();
} }
boost::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent)
{ {
auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent)); auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent));
@ -201,7 +201,7 @@ boost::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scop
if (!silent) if (!silent)
logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope); logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope);
return boost::optional<si32>(); return std::optional<si32>();
} }
void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier) void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)

View File

@ -99,10 +99,10 @@ public:
void tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback); void tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback);
/// get identifier immediately. If identifier is not know and not silent call will result in error message /// get identifier immediately. If identifier is not know and not silent call will result in error message
boost::optional<si32> getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent = false); std::optional<si32> getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent = false);
boost::optional<si32> getIdentifier(const std::string & type, const JsonNode & name, bool silent = false); std::optional<si32> getIdentifier(const std::string & type, const JsonNode & name, bool silent = false);
boost::optional<si32> getIdentifier(const JsonNode & name, bool silent = false); std::optional<si32> getIdentifier(const JsonNode & name, bool silent = false);
boost::optional<si32> getIdentifier(const std::string & scope, const std::string & fullName, bool silent = false); std::optional<si32> getIdentifier(const std::string & scope, const std::string & fullName, bool silent = false);
/// registers new object /// registers new object
void registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier); void registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier);

View File

@ -897,7 +897,7 @@ void CPathfinderHelper::initializePatrol()
if(hero->patrol.patrolRadius) if(hero->patrol.patrolRadius)
{ {
state = PATROL_RADIUS; state = PATROL_RADIUS;
gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, boost::optional<PlayerColor>(), 0, int3::DIST_MANHATTAN); gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, std::optional<PlayerColor>(), 0, int3::DIST_MANHATTAN);
} }
else else
state = PATROL_LOCKED; state = PATROL_LOCKED;
@ -1100,8 +1100,12 @@ void TurnInfo::updateHeroBonuses(Bonus::BonusType type, const CSelector& sel) co
} }
} }
CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options) CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options):
: CGameInfoCallback(gs, boost::optional<PlayerColor>()), turn(-1), hero(Hero), options(Options), owner(Hero->tempOwner) CGameInfoCallback(gs, std::optional<PlayerColor>()),
turn(-1),
hero(Hero),
options(Options),
owner(Hero->tempOwner)
{ {
turnsInfo.reserve(16); turnsInfo.reserve(16);
updateTurnInfo(); updateTurnInfo();

View File

@ -38,7 +38,7 @@ public:
bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
EPlayerStatus::EStatus status; EPlayerStatus::EStatus status;
boost::optional<ui8> daysWithoutCastle; std::optional<ui8> daysWithoutCastle;
PlayerState(); PlayerState();
PlayerState(PlayerState && other) noexcept; PlayerState(PlayerState && other) noexcept;

View File

@ -262,7 +262,7 @@ si32 CSkillHandler::decodeSkill(const std::string & identifier)
{ {
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "skill", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "skill", identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return -1; return -1;
} }

View File

@ -1151,7 +1151,7 @@ void CTownHandler::initializeRequirements()
logMod->warn("Entry contains: "); logMod->warn("Entry contains: ");
logMod->warn(node.toJson()); logMod->warn(node.toJson());
} }
return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get()); return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).value());
}); });
} }
requirementsToLoad.clear(); requirementsToLoad.clear();
@ -1166,7 +1166,7 @@ void CTownHandler::initializeOverridden()
for(const auto & b : jsonNode.Vector()) for(const auto & b : jsonNode.Vector())
{ {
auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get()); auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).value());
bidHelper.building->overrideBids.insert(bid); bidHelper.building->overrideBids.insert(bid);
} }
} }

View File

@ -64,7 +64,7 @@ si32 HeroTypeID::decode(const std::string & identifier)
{ {
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return -1; return -1;
} }
@ -88,7 +88,7 @@ si32 ArtifactID::decode(const std::string & identifier)
{ {
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "artifact", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "artifact", identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return -1; return -1;
} }
@ -112,7 +112,7 @@ si32 CreatureID::decode(const std::string & identifier)
{ {
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return -1; return -1;
} }
@ -141,7 +141,7 @@ si32 SpellID::decode(const std::string & identifier)
{ {
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "spell", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "spell", identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return -1; return -1;
} }
@ -204,7 +204,7 @@ si32 FactionID::decode(const std::string & identifier)
{ {
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "faction", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "faction", identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return FactionID::DEFAULT; return FactionID::DEFAULT;
} }
@ -292,7 +292,7 @@ BattleField BattleField::fromString(const std::string & identifier)
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "battlefield", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "battlefield", identifier);
if(rawId) if(rawId)
return BattleField(rawId.get()); return BattleField(rawId.value());
else else
return BattleField::NONE; return BattleField::NONE;
} }
@ -312,7 +312,7 @@ Obstacle Obstacle::fromString(const std::string & identifier)
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "obstacle", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "obstacle", identifier);
if(rawId) if(rawId)
return Obstacle(rawId.get()); return Obstacle(rawId.value());
else else
return Obstacle(-1); return Obstacle(-1);
} }

View File

@ -1520,7 +1520,7 @@ int64_t CBonusSystemNode::getTreeVersion() const
return treeChanged; return treeChanged;
} }
std::string Bonus::Description(boost::optional<si32> customValue) const std::string Bonus::Description(std::optional<si32> customValue) const
{ {
std::ostringstream str; std::ostringstream str;

View File

@ -533,7 +533,7 @@ struct DLL_LINKAGE Bonus : public std::enable_shared_from_this<Bonus>
return sid & 0x0000FFFF; return sid & 0x0000FFFF;
} }
std::string Description(boost::optional<si32> customValue = {}) const; std::string Description(std::optional<si32> customValue = {}) const;
JsonNode toJsonNode() const; JsonNode toJsonNode() const;
std::string nameForBonus() const; // generate suitable name for bonus - e.g. for storing in json struct std::string nameForBonus() const; // generate suitable name for bonus - e.g. for storing in json struct

View File

@ -66,7 +66,7 @@ void CPrivilegedInfoCallback::getFreeTiles(std::vector<int3> & tiles) const
void CPrivilegedInfoCallback::getTilesInRange(std::unordered_set<int3, ShashInt3> & tiles, void CPrivilegedInfoCallback::getTilesInRange(std::unordered_set<int3, ShashInt3> & tiles,
const int3 & pos, const int3 & pos,
int radious, int radious,
boost::optional<PlayerColor> player, std::optional<PlayerColor> player,
int mode, int mode,
int3::EDistanceFormula distanceFormula) const int3::EDistanceFormula distanceFormula) const
{ {
@ -100,7 +100,7 @@ void CPrivilegedInfoCallback::getTilesInRange(std::unordered_set<int3, ShashInt3
} }
} }
void CPrivilegedInfoCallback::getAllTiles(std::unordered_set<int3, ShashInt3> & tiles, boost::optional<PlayerColor> Player, int level, MapTerrainFilterMode tileFilterMode) const void CPrivilegedInfoCallback::getAllTiles(std::unordered_set<int3, ShashInt3> & tiles, std::optional<PlayerColor> Player, int level, MapTerrainFilterMode tileFilterMode) const
{ {
if(!!Player && *Player >= PlayerColor::PLAYER_LIMIT) if(!!Player && *Player >= PlayerColor::PLAYER_LIMIT)
{ {

View File

@ -62,12 +62,12 @@ public:
void getTilesInRange(std::unordered_set<int3, ShashInt3> & tiles, void getTilesInRange(std::unordered_set<int3, ShashInt3> & tiles,
const int3 & pos, const int3 & pos,
int radious, int radious,
boost::optional<PlayerColor> player = boost::optional<PlayerColor>(), std::optional<PlayerColor> player = std::optional<PlayerColor>(),
int mode = 0, int mode = 0,
int3::EDistanceFormula formula = int3::DIST_2D) const; int3::EDistanceFormula formula = int3::DIST_2D) const;
//returns all tiles on given level (-1 - both levels, otherwise number of level) //returns all tiles on given level (-1 - both levels, otherwise number of level)
void getAllTiles(std::unordered_set<int3, ShashInt3> &tiles, boost::optional<PlayerColor> player = boost::optional<PlayerColor>(), void getAllTiles(std::unordered_set<int3, ShashInt3> &tiles, std::optional<PlayerColor> player = std::optional<PlayerColor>(),
int level = -1, MapTerrainFilterMode tileFilterMode = MapTerrainFilterMode::NONE) const; int level = -1, MapTerrainFilterMode tileFilterMode = MapTerrainFilterMode::NONE) const;
//gives 3 treasures, 3 minors, 1 major -> used by Black Market and Artifact Merchant //gives 3 treasures, 3 minors, 1 major -> used by Black Market and Artifact Merchant

View File

@ -145,7 +145,7 @@ struct DLL_LINKAGE YourTurn : public CPackForClient
void applyGs(CGameState * gs) const; void applyGs(CGameState * gs) const;
PlayerColor player; PlayerColor player;
boost::optional<ui8> daysWithoutCastle; std::optional<ui8> daysWithoutCastle;
virtual void visitTyped(ICPackVisitor & visitor) override; virtual void visitTyped(ICPackVisitor & visitor) override;
@ -591,7 +591,7 @@ struct DLL_LINKAGE TryMoveHero : public CPackForClient
EResult result = FAILED; //uses EResult EResult result = FAILED; //uses EResult
int3 start, end; //h3m format int3 start, end; //h3m format
std::unordered_set<int3, ShashInt3> fowRevealed; //revealed tiles std::unordered_set<int3, ShashInt3> fowRevealed; //revealed tiles
boost::optional<int3> attackedFrom; // Set when stepping into endangered tile. std::optional<int3> attackedFrom; // Set when stepping into endangered tile.
virtual void visitTyped(ICPackVisitor & visitor) override; virtual void visitTyped(ICPackVisitor & visitor) override;
@ -930,17 +930,17 @@ struct DLL_LINKAGE BulkSmartRebalanceStacks : CGarrisonOperationPack
} }
}; };
struct GetEngagedHeroIds : boost::static_visitor<boost::optional<ObjectInstanceID>> struct GetEngagedHeroIds: boost::static_visitor<std::optional<ObjectInstanceID>>
{ {
boost::optional<ObjectInstanceID> operator()(const ConstTransitivePtr<CGHeroInstance> & h) const std::optional<ObjectInstanceID> operator()(const ConstTransitivePtr<CGHeroInstance> & h) const
{ {
return h->id; return h->id;
} }
boost::optional<ObjectInstanceID> operator()(const ConstTransitivePtr<CStackInstance> & s) const std::optional<ObjectInstanceID> operator()(const ConstTransitivePtr<CStackInstance> & s) const
{ {
if(s->armyObj && s->armyObj->ID == Obj::HERO) if(s->armyObj && s->armyObj->ID == Obj::HERO)
return s->armyObj->id; return s->armyObj->id;
return boost::optional<ObjectInstanceID>(); return std::optional<ObjectInstanceID>();
} }
}; };

View File

@ -2050,11 +2050,11 @@ void NewTurn::applyGs(CGameState *gs)
if (playerState.daysWithoutCastle) if (playerState.daysWithoutCastle)
++(*playerState.daysWithoutCastle); ++(*playerState.daysWithoutCastle);
else else
playerState.daysWithoutCastle = boost::make_optional(0); playerState.daysWithoutCastle = std::make_optional(0);
} }
else else
{ {
playerState.daysWithoutCastle = boost::none; playerState.daysWithoutCastle = std::nullopt;
} }
} }
} }
@ -2085,7 +2085,7 @@ void SetObjectProperty::applyGs(CGameState * gs) const
//reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured
if(p->daysWithoutCastle) if(p->daysWithoutCastle)
p->daysWithoutCastle = boost::none; p->daysWithoutCastle = std::nullopt;
} }
} }

View File

@ -29,7 +29,7 @@ namespace GameConstants
const int BFIELD_SIZE = BFIELD_WIDTH * BFIELD_HEIGHT; const int BFIELD_SIZE = BFIELD_WIDTH * BFIELD_HEIGHT;
} }
using BattleSideOpt = boost::optional<ui8>; using BattleSideOpt = std::optional<ui8>;
// for battle stacks' positions // for battle stacks' positions
struct DLL_LINKAGE BattleHex //TODO: decide if this should be changed to class for better code design struct DLL_LINKAGE BattleHex //TODO: decide if this should be changed to class for better code design

View File

@ -106,7 +106,7 @@ ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(con
const auto side = playerToSide(player); const auto side = playerToSide(player);
if(!side) if(!side)
return ESpellCastProblem::INVALID; return ESpellCastProblem::INVALID;
if(!battleDoWeKnowAbout(side.get())) if(!battleDoWeKnowAbout(side.value()))
{ {
logGlobal->warn("You can't check if enemy can cast given spell!"); logGlobal->warn("You can't check if enemy can cast given spell!");
return ESpellCastProblem::INVALID; return ESpellCastProblem::INVALID;
@ -119,7 +119,7 @@ ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(con
{ {
case spells::Mode::HERO: case spells::Mode::HERO:
{ {
if(battleCastSpells(side.get()) > 0) if(battleCastSpells(side.value()) > 0)
return ESpellCastProblem::CASTS_PER_TURN_LIMIT; return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
const auto * hero = dynamic_cast<const CGHeroInstance *>(caster); const auto * hero = dynamic_cast<const CGHeroInstance *>(caster);
@ -229,7 +229,7 @@ std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsFor
{ {
if(stack->hasBonusOfType(Bonus::SPELLCASTER)) if(stack->hasBonusOfType(Bonus::SPELLCASTER))
{ {
for (auto const & spellID : data.creatureSpellsToCast) for(const auto & spellID : data.creatureSpellsToCast)
{ {
const CSpell *spell = spellID.toSpell(); const CSpell *spell = spellID.toSpell();
PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE); PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
@ -767,7 +767,7 @@ DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInf
//TODO: rewrite using boost::numeric::interval //TODO: rewrite using boost::numeric::interval
//TODO: rewire once more using interval-based fuzzy arithmetic //TODO: rewire once more using interval-based fuzzy arithmetic
auto const & estimateRetaliation = [&]( int64_t damage) const auto & estimateRetaliation = [&](int64_t damage)
{ {
auto retaliationAttack = bai.reverse(); auto retaliationAttack = bai.reverse();
auto state = retaliationAttack.attacker->acquireState(); auto state = retaliationAttack.attacker->acquireState();
@ -1763,7 +1763,7 @@ int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) cons
const auto sideOpt = playerToSide(Player); const auto sideOpt = playerToSide(Player);
if(!sideOpt) if(!sideOpt)
return -1; return -1;
const auto side = sideOpt.get(); const auto side = sideOpt.value();
int ret = 0; int ret = 0;
double discount = 0; double discount = 0;
@ -1816,7 +1816,7 @@ si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
return GameConstants::SPELL_LEVELS; return GameConstants::SPELL_LEVELS;
} }
boost::optional<int> CBattleInfoCallback::battleIsFinished() const std::optional<int> CBattleInfoCallback::battleIsFinished() const
{ {
auto units = battleGetUnitsIf([=](const battle::Unit * unit) auto units = battleGetUnitsIf([=](const battle::Unit * unit)
{ {
@ -1831,7 +1831,7 @@ boost::optional<int> CBattleInfoCallback::battleIsFinished() const
hasUnit.at(unit->unitSide()) = true; hasUnit.at(unit->unitSide()) = true;
if(hasUnit[0] && hasUnit[1]) if(hasUnit[0] && hasUnit[1])
return boost::none; return std::nullopt;
} }
hasUnit = {false, false}; hasUnit = {false, false};

View File

@ -58,7 +58,7 @@ public:
RANDOM_GENIE, RANDOM_AIMED RANDOM_GENIE, RANDOM_AIMED
}; };
boost::optional<int> battleIsFinished() const override; //return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw std::optional<int> battleIsFinished() const override; //return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw
std::vector<std::shared_ptr<const CObstacleInstance>> battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking = true) const override; std::vector<std::shared_ptr<const CObstacleInstance>> battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking = true) const override;
std::vector<std::shared_ptr<const CObstacleInstance>> getAllAffectedObstaclesByStack(const battle::Unit * unit, const std::set<BattleHex> & passed) const override; std::vector<std::shared_ptr<const CObstacleInstance>> getAllAffectedObstaclesByStack(const battle::Unit * unit, const std::set<BattleHex> & passed) const override;

View File

@ -34,7 +34,7 @@ int32_t CBattleInfoEssentials::battleGetEnchanterCounter(ui8 side) const
return getBattle()->getEnchanterCounter(side); return getBattle()->getEnchanterCounter(side);
} }
std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoEssentials::battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective) const std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoEssentials::battleGetAllObstacles(std::optional<BattlePerspective::BattlePerspective> perspective) const
{ {
std::vector<std::shared_ptr<const CObstacleInstance> > ret; std::vector<std::shared_ptr<const CObstacleInstance> > ret;
RETURN_IF_NOT_BATTLE(ret); RETURN_IF_NOT_BATTLE(ret);
@ -42,7 +42,7 @@ std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoEssentials::bat
if(!perspective) if(!perspective)
{ {
//if no particular perspective request, use default one //if no particular perspective request, use default one
perspective = boost::make_optional(battleGetMySide()); perspective = std::make_optional(battleGetMySide());
} }
else else
{ {
@ -156,7 +156,7 @@ const CGTownInstance * CBattleInfoEssentials::battleGetDefendedTown() const
BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const
{ {
RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID); RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID);
if(!player || player.get().isSpectator()) if(!player || player->isSpectator())
return BattlePerspective::ALL_KNOWING; return BattlePerspective::ALL_KNOWING;
if(*player == getBattle()->getSidePlayer(BattleSide::ATTACKER)) if(*player == getBattle()->getSidePlayer(BattleSide::ATTACKER))
return BattlePerspective::LEFT_SIDE; return BattlePerspective::LEFT_SIDE;
@ -264,7 +264,7 @@ bool CBattleInfoEssentials::battleCanFlee(const PlayerColor & player) const
if(!side) if(!side)
return false; return false;
const CGHeroInstance *myHero = battleGetFightingHero(side.get()); const CGHeroInstance * myHero = battleGetFightingHero(side.value());
//current player have no hero //current player have no hero
if(!myHero) if(!myHero)
@ -275,7 +275,7 @@ bool CBattleInfoEssentials::battleCanFlee(const PlayerColor & player) const
return false; return false;
//we are besieged defender //we are besieged defender
if(side.get() == BattleSide::DEFENDER && battleGetSiegeLevel()) if(side == BattleSide::DEFENDER && battleGetSiegeLevel())
{ {
const auto * town = battleGetDefendedTown(); const auto * town = battleGetDefendedTown();
if(!town->hasBuilt(BuildingSubID::ESCAPE_TUNNEL)) if(!town->hasBuilt(BuildingSubID::ESCAPE_TUNNEL))
@ -287,7 +287,7 @@ bool CBattleInfoEssentials::battleCanFlee(const PlayerColor & player) const
BattleSideOpt CBattleInfoEssentials::playerToSide(const PlayerColor & player) const BattleSideOpt CBattleInfoEssentials::playerToSide(const PlayerColor & player) const
{ {
RETURN_IF_NOT_BATTLE(boost::none); RETURN_IF_NOT_BATTLE(std::nullopt);
if(getBattle()->getSidePlayer(BattleSide::ATTACKER) == player) if(getBattle()->getSidePlayer(BattleSide::ATTACKER) == player)
return BattleSideOpt(BattleSide::ATTACKER); return BattleSideOpt(BattleSide::ATTACKER);
@ -297,7 +297,7 @@ BattleSideOpt CBattleInfoEssentials::playerToSide(const PlayerColor & player) co
logGlobal->warn("Cannot find side for player %s", player.getStr()); logGlobal->warn("Cannot find side for player %s", player.getStr());
return boost::none; return std::nullopt;
} }
PlayerColor CBattleInfoEssentials::sideToPlayer(ui8 side) const PlayerColor CBattleInfoEssentials::sideToPlayer(ui8 side) const
@ -322,7 +322,7 @@ PlayerColor CBattleInfoEssentials::otherPlayer(const PlayerColor & player) const
if(!side) if(!side)
return PlayerColor::CANNOT_DETERMINE; return PlayerColor::CANNOT_DETERMINE;
return getBattle()->getSidePlayer(otherSide(side.get())); return getBattle()->getSidePlayer(otherSide(side.value()));
} }
bool CBattleInfoEssentials::playerHasAccessToHeroInfo(const PlayerColor & player, const CGHeroInstance * h) const bool CBattleInfoEssentials::playerHasAccessToHeroInfo(const PlayerColor & player, const CGHeroInstance * h) const
@ -331,7 +331,7 @@ bool CBattleInfoEssentials::playerHasAccessToHeroInfo(const PlayerColor & player
const auto side = playerToSide(player); const auto side = playerToSide(player);
if(side) if(side)
{ {
auto opponentSide = otherSide(side.get()); auto opponentSide = otherSide(side.value());
if(getBattle()->getSideHero(opponentSide) == h) if(getBattle()->getSideHero(opponentSide) == h)
return true; return true;
} }
@ -350,9 +350,9 @@ bool CBattleInfoEssentials::battleCanSurrender(const PlayerColor & player) const
const auto side = playerToSide(player); const auto side = playerToSide(player);
if(!side) if(!side)
return false; return false;
bool iAmSiegeDefender = (side.get() == BattleSide::DEFENDER && battleGetSiegeLevel()); bool iAmSiegeDefender = (side.value() == BattleSide::DEFENDER && battleGetSiegeLevel());
//conditions like for fleeing (except escape tunnel presence) + enemy must have a hero //conditions like for fleeing (except escape tunnel presence) + enemy must have a hero
return battleCanFlee(player) && !iAmSiegeDefender && battleHasHero(otherSide(side.get())); return battleCanFlee(player) && !iAmSiegeDefender && battleHasHero(otherSide(side.value()));
} }
bool CBattleInfoEssentials::battleHasHero(ui8 side) const bool CBattleInfoEssentials::battleHasHero(ui8 side) const
@ -409,7 +409,7 @@ const CGHeroInstance * CBattleInfoEssentials::battleGetOwnerHero(const battle::U
const auto side = playerToSide(battleGetOwner(unit)); const auto side = playerToSide(battleGetOwner(unit));
if(!side) if(!side)
return nullptr; return nullptr;
return getBattle()->getSideHero(side.get()); return getBattle()->getSideHero(side.value());
} }
bool CBattleInfoEssentials::battleMatchOwner(const battle::Unit * attacker, const battle::Unit * defender, const boost::logic::tribool positivness) const bool CBattleInfoEssentials::battleMatchOwner(const battle::Unit * attacker, const battle::Unit * defender, const boost::logic::tribool positivness) const

View File

@ -52,7 +52,7 @@ public:
BattleField battleGetBattlefieldType() const override; BattleField battleGetBattlefieldType() const override;
int32_t battleGetEnchanterCounter(ui8 side) const; int32_t battleGetEnchanterCounter(ui8 side) const;
std::vector<std::shared_ptr<const CObstacleInstance> > battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective = boost::none) const; //returns all obstacles on the battlefield std::vector<std::shared_ptr<const CObstacleInstance> > battleGetAllObstacles(std::optional<BattlePerspective::BattlePerspective> perspective = std::nullopt) const; //returns all obstacles on the battlefield
std::shared_ptr<const CObstacleInstance> battleGetObstacleByID(uint32_t ID) const; std::shared_ptr<const CObstacleInstance> battleGetObstacleByID(uint32_t ID) const;

View File

@ -23,7 +23,7 @@ const IBattleInfo * CCallbackBase::getBattle() const
return battle; return battle;
} }
CCallbackBase::CCallbackBase(boost::optional<PlayerColor> Player): CCallbackBase::CCallbackBase(std::optional<PlayerColor> Player):
player(std::move(Player)) player(std::move(Player))
{ {
} }
@ -33,7 +33,7 @@ void CCallbackBase::setBattle(const IBattleInfo * B)
battle = B; battle = B;
} }
boost::optional<PlayerColor> CCallbackBase::getPlayerID() const std::optional<PlayerColor> CCallbackBase::getPlayerID() const
{ {
return player; return player;
} }

View File

@ -26,9 +26,9 @@ class DLL_LINKAGE CCallbackBase
const IBattleInfo * battle = nullptr; //battle to which the player is engaged, nullptr if none or not applicable const IBattleInfo * battle = nullptr; //battle to which the player is engaged, nullptr if none or not applicable
protected: protected:
boost::optional<PlayerColor> player; // not set gives access to all information, otherwise callback provides only information "visible" for player std::optional<PlayerColor> player; // not set gives access to all information, otherwise callback provides only information "visible" for player
CCallbackBase(boost::optional<PlayerColor> Player); CCallbackBase(std::optional<PlayerColor> Player);
CCallbackBase() = default; CCallbackBase() = default;
const IBattleInfo * getBattle() const; const IBattleInfo * getBattle() const;
@ -36,7 +36,7 @@ protected:
bool duringBattle() const; bool duringBattle() const;
public: public:
boost::optional<PlayerColor> getPlayerID() const; std::optional<PlayerColor> getPlayerID() const;
friend class CBattleInfoEssentials; friend class CBattleInfoEssentials;
}; };

View File

@ -58,7 +58,7 @@ public:
virtual BattleField battleGetBattlefieldType() const = 0; virtual BattleField battleGetBattlefieldType() const = 0;
///return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw ///return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw
virtual boost::optional<int> battleIsFinished() const = 0; virtual std::optional<int> battleIsFinished() const = 0;
virtual si8 battleTacticDist() const = 0; //returns tactic distance in current tactics phase; 0 if not in tactics phase virtual si8 battleTacticDist() const = 0; //returns tactic distance in current tactics phase; 0 if not in tactics phase
virtual si8 battleGetTacticsSide() const = 0; //returns which side is in tactics phase, undefined if none (?) virtual si8 battleGetTacticsSide() const = 0; //returns which side is in tactics phase, undefined if none (?)

View File

@ -39,7 +39,7 @@ std::string CMappedFileLoader::getMountPoint() const
return ""; // does not have any meaning with this type of data source return ""; // does not have any meaning with this type of data source
} }
boost::optional<boost::filesystem::path> CMappedFileLoader::getResourceName(const ResourceID & resourceName) const std::optional<boost::filesystem::path> CMappedFileLoader::getResourceName(const ResourceID & resourceName) const
{ {
return CResourceHandler::get()->getResourceName(fileList.at(resourceName)); return CResourceHandler::get()->getResourceName(fileList.at(resourceName));
} }
@ -90,11 +90,11 @@ std::string CFilesystemList::getMountPoint() const
return ""; return "";
} }
boost::optional<boost::filesystem::path> CFilesystemList::getResourceName(const ResourceID & resourceName) const std::optional<boost::filesystem::path> CFilesystemList::getResourceName(const ResourceID & resourceName) const
{ {
if (existsResource(resourceName)) if (existsResource(resourceName))
return getResourcesWithName(resourceName).back()->getResourceName(resourceName); return getResourcesWithName(resourceName).back()->getResourceName(resourceName);
return boost::optional<boost::filesystem::path>(); return std::optional<boost::filesystem::path>();
} }
std::set<boost::filesystem::path> CFilesystemList::getResourceNames(const ResourceID & resourceName) const std::set<boost::filesystem::path> CFilesystemList::getResourceNames(const ResourceID & resourceName) const

View File

@ -41,7 +41,7 @@ public:
std::unique_ptr<CInputStream> load(const ResourceID & resourceName) const override; std::unique_ptr<CInputStream> load(const ResourceID & resourceName) const override;
bool existsResource(const ResourceID & resourceName) const override; bool existsResource(const ResourceID & resourceName) const override;
std::string getMountPoint() const override; std::string getMountPoint() const override;
boost::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const override; std::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const override;
void updateFilteredFiles(std::function<bool(const std::string &)> filter) const override {} void updateFilteredFiles(std::function<bool(const std::string &)> filter) const override {}
std::unordered_set<ResourceID> getFilteredFiles(std::function<bool(const ResourceID &)> filter) const override; std::unordered_set<ResourceID> getFilteredFiles(std::function<bool(const ResourceID &)> filter) const override;
@ -71,7 +71,7 @@ public:
std::unique_ptr<CInputStream> load(const ResourceID & resourceName) const override; std::unique_ptr<CInputStream> load(const ResourceID & resourceName) const override;
bool existsResource(const ResourceID & resourceName) const override; bool existsResource(const ResourceID & resourceName) const override;
std::string getMountPoint() const override; std::string getMountPoint() const override;
boost::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const override; std::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const override;
std::set<boost::filesystem::path> getResourceNames(const ResourceID & resourceName) const override; std::set<boost::filesystem::path> getResourceNames(const ResourceID & resourceName) const override;
void updateFilteredFiles(std::function<bool(const std::string &)> filter) const override; void updateFilteredFiles(std::function<bool(const std::string &)> filter) const override;
std::unordered_set<ResourceID> getFilteredFiles(std::function<bool(const ResourceID &)> filter) const override; std::unordered_set<ResourceID> getFilteredFiles(std::function<bool(const ResourceID &)> filter) const override;

View File

@ -44,7 +44,7 @@ std::string CFilesystemLoader::getMountPoint() const
return mountPoint; return mountPoint;
} }
boost::optional<boost::filesystem::path> CFilesystemLoader::getResourceName(const ResourceID & resourceName) const std::optional<boost::filesystem::path> CFilesystemLoader::getResourceName(const ResourceID & resourceName) const
{ {
assert(existsResource(resourceName)); assert(existsResource(resourceName));

View File

@ -38,7 +38,7 @@ public:
bool existsResource(const ResourceID & resourceName) const override; bool existsResource(const ResourceID & resourceName) const override;
std::string getMountPoint() const override; std::string getMountPoint() const override;
bool createResource(std::string filename, bool update = false) override; bool createResource(std::string filename, bool update = false) override;
boost::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const override; std::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const override;
void updateFilteredFiles(std::function<bool(const std::string &)> filter) const override; void updateFilteredFiles(std::function<bool(const std::string &)> filter) const override;
std::unordered_set<ResourceID> getFilteredFiles(std::function<bool(const ResourceID &)> filter) const override; std::unordered_set<ResourceID> getFilteredFiles(std::function<bool(const ResourceID &)> filter) const override;

View File

@ -49,9 +49,9 @@ public:
* *
* @return path or empty optional if file can't be accessed independently (e.g. file in archive) * @return path or empty optional if file can't be accessed independently (e.g. file in archive)
*/ */
virtual boost::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const virtual std::optional<boost::filesystem::path> getResourceName(const ResourceID & resourceName) const
{ {
return boost::optional<boost::filesystem::path>(); return std::optional<boost::filesystem::path>();
} }
/** /**

View File

@ -29,7 +29,7 @@ void CArmedInstance::randomizeArmy(int type)
int upgrade = elem.second->randomStack->upgrade; int upgrade = elem.second->randomStack->upgrade;
elem.second->setType((*VLC->townh)[type]->town->creatures[level][upgrade]); elem.second->setType((*VLC->townh)[type]->town->creatures[level][upgrade]);
elem.second->randomStack = boost::none; elem.second->randomStack = std::nullopt;
} }
assert(elem.second->valid(false)); assert(elem.second->valid(false));
assert(elem.second->armyObj == this); assert(elem.second->armyObj == this);

View File

@ -1280,11 +1280,11 @@ PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & r
return static_cast<PrimarySkill::PrimarySkill>(primarySkill); return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
} }
boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const std::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
{ {
assert(gainsLevel()); assert(gainsLevel());
boost::optional<SecondarySkill> chosenSecondarySkill; std::optional<SecondarySkill> chosenSecondarySkill;
const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills(); const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
if(!proposedSecondarySkills.empty()) if(!proposedSecondarySkills.empty())
{ {
@ -1300,12 +1300,12 @@ boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenera
if(learnedSecondarySkills.empty()) if(learnedSecondarySkills.empty())
{ {
// there are only new skills to learn, so choose anyone of them // there are only new skills to learn, so choose anyone of them
chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand)); chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
} }
else else
{ {
// preferably upgrade a already learned secondary skill // preferably upgrade a already learned secondary skill
chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand)); chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
} }
} }
return chosenSecondarySkill; return chosenSecondarySkill;
@ -1441,7 +1441,7 @@ void CGHeroInstance::setHeroTypeName(const std::string & identifier)
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier);
if(rawId) if(rawId)
subID = rawId.get(); subID = rawId.value();
else else
{ {
throw std::runtime_error("Couldn't resolve hero identifier " + identifier); throw std::runtime_error("Couldn't resolve hero identifier " + identifier);

View File

@ -182,7 +182,7 @@ public:
PrimarySkill::PrimarySkill nextPrimarySkill(CRandomGenerator & rand) const; PrimarySkill::PrimarySkill nextPrimarySkill(CRandomGenerator & rand) const;
/// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up. /// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up.
boost::optional<SecondarySkill> nextSecondarySkill(CRandomGenerator & rand) const; std::optional<SecondarySkill> nextSecondarySkill(CRandomGenerator & rand) const;
/// Gets 0, 1 or 2 secondary skills which are proposed on hero level up. /// Gets 0, 1 or 2 secondary skills which are proposed on hero level up.
std::vector<SecondarySkill> getLevelUpProposedSecondarySkills() const; std::vector<SecondarySkill> getLevelUpProposedSecondarySkills() const;

View File

@ -1507,7 +1507,7 @@ void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
if(rawId) if(rawId)
return rawId.get(); return rawId.value();
else else
return -1; return -1;
}; };

View File

@ -165,7 +165,7 @@ void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::
obj->objects.push_back(object); obj->objects.push_back(object);
registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype); registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
for (auto const & compatID : entry["compatibilityIdentifiers"].Vector()) for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype); registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
} }
@ -178,7 +178,7 @@ void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::
obj->objects[index] = object; obj->objects[index] = object;
registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype); registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
for (auto const & compatID : entry["compatibilityIdentifiers"].Vector()) for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype); registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
} }
@ -313,14 +313,14 @@ TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype)
TObjectTypeHandler CObjectClassesHandler::getHandlerFor(const std::string & scope, const std::string & type, const std::string & subtype) const TObjectTypeHandler CObjectClassesHandler::getHandlerFor(const std::string & scope, const std::string & type, const std::string & subtype) const
{ {
boost::optional<si32> id = VLC->modh->identifiers.getIdentifier(scope, "object", type); std::optional<si32> id = VLC->modh->identifiers.getIdentifier(scope, "object", type);
if(id) if(id)
{ {
auto * object = objects[id.get()]; auto * object = objects[id.value()];
boost::optional<si32> subID = VLC->modh->identifiers.getIdentifier(scope, object->getJsonKey(), subtype); std::optional<si32> subID = VLC->modh->identifiers.getIdentifier(scope, object->getJsonKey(), subtype);
if (subID) if (subID)
return object->objects[subID.get()]; return object->objects[subID.value()];
} }
std::string errorString = "Failed to find object of type " + type + "::" + subtype; std::string errorString = "Failed to find object of type " + type + "::" + subtype;
@ -515,7 +515,7 @@ void AObjectTypeHandler::init(const JsonNode & input)
const JsonNode & mapLimit = input["rmg"]["mapLimit"]; const JsonNode & mapLimit = input["rmg"]["mapLimit"];
if (!mapLimit.isNull()) if (!mapLimit.isNull())
rmgInfo.mapLimit.reset(static_cast<ui32>(mapLimit.Float())); rmgInfo.mapLimit = static_cast<ui32>(mapLimit.Float());
rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]); rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]);
rmgInfo.rarity = static_cast<ui32>(input["rmg"]["rarity"].Float()); rmgInfo.rarity = static_cast<ui32>(input["rmg"]["rarity"].Float());
@ -551,14 +551,14 @@ void AObjectTypeHandler::init(const JsonNode & input)
sounds.removal.push_back(node.String()); sounds.removal.push_back(node.String());
if(input["aiValue"].isNull()) if(input["aiValue"].isNull())
aiValue = boost::none; aiValue = std::nullopt;
else else
aiValue = static_cast<boost::optional<si32>>(input["aiValue"].Integer()); aiValue = static_cast<std::optional<si32>>(input["aiValue"].Integer());
if(input["battleground"].getType() == JsonNode::JsonType::DATA_STRING) if(input["battleground"].getType() == JsonNode::JsonType::DATA_STRING)
battlefield = input["battleground"].String(); battlefield = input["battleground"].String();
else else
battlefield = boost::none; battlefield = std::nullopt;
initTypeData(input); initTypeData(input);
} }
@ -625,7 +625,7 @@ std::vector<std::shared_ptr<const ObjectTemplate>> AObjectTypeHandler::getTempla
BattleField AObjectTypeHandler::getBattlefield() const BattleField AObjectTypeHandler::getBattlefield() const
{ {
return battlefield ? BattleField::fromString(battlefield.get()) : BattleField::NONE; return battlefield ? BattleField::fromString(battlefield.value()) : BattleField::NONE;
} }
std::vector<std::shared_ptr<const ObjectTemplate>>AObjectTypeHandler::getTemplates(TerrainId terrainType) const std::vector<std::shared_ptr<const ObjectTemplate>>AObjectTypeHandler::getTemplates(TerrainId terrainType) const
@ -661,7 +661,7 @@ const RandomMapInfo & AObjectTypeHandler::getRMGInfo()
return rmgInfo; return rmgInfo;
} }
boost::optional<si32> AObjectTypeHandler::getAiValue() const std::optional<si32> AObjectTypeHandler::getAiValue() const
{ {
return aiValue; return aiValue;
} }

View File

@ -43,7 +43,7 @@ struct DLL_LINKAGE RandomMapInfo
ui32 value; ui32 value;
/// How many of such objects can be placed on map, 0 = object can not be placed by RMG /// How many of such objects can be placed on map, 0 = object can not be placed by RMG
boost::optional<ui32> mapLimit; std::optional<ui32> mapLimit;
/// How many of such objects can be placed in one zone, 0 = unplaceable /// How many of such objects can be placed in one zone, 0 = unplaceable
ui32 zoneLimit; ui32 zoneLimit;
@ -57,7 +57,7 @@ struct DLL_LINKAGE RandomMapInfo
rarity(0) rarity(0)
{} {}
void setMapLimit(ui32 val) { mapLimit.reset(val); } void setMapLimit(ui32 val) { mapLimit = val; }
template <typename Handler> void serialize(Handler &h, const int version) template <typename Handler> void serialize(Handler &h, const int version)
{ {
@ -150,8 +150,8 @@ class DLL_LINKAGE AObjectTypeHandler : public boost::noncopyable
SObjectSounds sounds; SObjectSounds sounds;
boost::optional<si32> aiValue; std::optional<si32> aiValue;
boost::optional<std::string> battlefield; std::optional<std::string> battlefield;
std::string modScope; std::string modScope;
std::string typeName; std::string typeName;
@ -200,7 +200,7 @@ public:
const RandomMapInfo & getRMGInfo(); const RandomMapInfo & getRMGInfo();
boost::optional<si32> getAiValue() const; std::optional<si32> getAiValue() const;
/// returns true if this class provides custom text ID's instead of generic per-object name /// returns true if this class provides custom text ID's instead of generic per-object name
virtual bool hasNameTextID() const; virtual bool hasNameTextID() const;

View File

@ -288,31 +288,31 @@ std::string CGObjectInstance::getObjectName() const
return VLC->objtypeh->getObjectName(ID, subID); return VLC->objtypeh->getObjectName(ID, subID);
} }
boost::optional<std::string> CGObjectInstance::getAmbientSound() const std::optional<std::string> CGObjectInstance::getAmbientSound() const
{ {
const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).ambient; const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).ambient;
if(!sounds.empty()) if(!sounds.empty())
return sounds.front(); // TODO: Support randomization of ambient sounds return sounds.front(); // TODO: Support randomization of ambient sounds
return boost::none; return std::nullopt;
} }
boost::optional<std::string> CGObjectInstance::getVisitSound() const std::optional<std::string> CGObjectInstance::getVisitSound() const
{ {
const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).visit; const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).visit;
if(!sounds.empty()) if(!sounds.empty())
return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault()); return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault());
return boost::none; return std::nullopt;
} }
boost::optional<std::string> CGObjectInstance::getRemovalSound() const std::optional<std::string> CGObjectInstance::getRemovalSound() const
{ {
const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).removal; const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).removal;
if(!sounds.empty()) if(!sounds.empty())
return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault()); return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault());
return boost::none; return std::nullopt;
} }
std::string CGObjectInstance::getHoverText(PlayerColor player) const std::string CGObjectInstance::getHoverText(PlayerColor player) const
@ -384,7 +384,7 @@ void CGObjectInstance::serializeJson(JsonSerializeFormat & handler)
handler.serializeInt("l", pos.z); handler.serializeInt("l", pos.z);
JsonNode app; JsonNode app;
appearance->writeJson(app, false); appearance->writeJson(app, false);
handler.serializeRaw("template",app, boost::none); handler.serializeRaw("template", app, std::nullopt);
} }
{ {

View File

@ -171,10 +171,9 @@ public:
virtual bool isTile2Terrain() const { return false; } virtual bool isTile2Terrain() const { return false; }
boost::optional<std::string> getAmbientSound() const; std::optional<std::string> getAmbientSound() const;
boost::optional<std::string> getVisitSound() const; std::optional<std::string> getVisitSound() const;
boost::optional<std::string> getRemovalSound() const; std::optional<std::string> getRemovalSound() const;
/** VIRTUAL METHODS **/ /** VIRTUAL METHODS **/

View File

@ -1067,7 +1067,7 @@ void CGSeerHut::serializeJsonOptions(JsonSerializeFormat & handler)
if(rawId) if(rawId)
{ {
rID = rawId.get(); rID = rawId.value();
} }
else else
{ {

View File

@ -140,8 +140,8 @@ void CRandomRewardObjectInfo::configureReward(CRewardableObject * object, CRando
for ( auto node : source["changeCreatures"].Struct() ) for ( auto node : source["changeCreatures"].Struct() )
{ {
CreatureID from (VLC->modh->identifiers.getIdentifier (node.second.meta, "creature", node.first) .get()); CreatureID from(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.first).value());
CreatureID dest (VLC->modh->identifiers.getIdentifier (node.second.meta, "creature", node.second.String()).get()); CreatureID dest(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.second.String()).value());
reward.extraComponents.emplace_back(Component::EComponentType::CREATURE, dest.getNum(), 0, 0); reward.extraComponents.emplace_back(Component::EComponentType::CREATURE, dest.getNum(), 0, 0);

View File

@ -50,7 +50,7 @@ void CTownInstanceConstructor::afterLoadFinalization()
{ {
filters[entry.first] = LogicalExpression<BuildingID>(entry.second, [this](const JsonNode & node) filters[entry.first] = LogicalExpression<BuildingID>(entry.second, [this](const JsonNode & node)
{ {
return BuildingID(VLC->modh->identifiers.getIdentifier("building." + faction->getJsonKey(), node.Vector()[0]).get()); return BuildingID(VLC->modh->identifiers.getIdentifier("building." + faction->getJsonKey(), node.Vector()[0]).value());
}); });
} }
} }
@ -98,7 +98,7 @@ void CHeroInstanceConstructor::afterLoadFinalization()
{ {
filters[entry.first] = LogicalExpression<HeroTypeID>(entry.second, [](const JsonNode & node) filters[entry.first] = LogicalExpression<HeroTypeID>(entry.second, [](const JsonNode & node)
{ {
return HeroTypeID(VLC->modh->identifiers.getIdentifier("hero", node.Vector()[0]).get()); return HeroTypeID(VLC->modh->identifiers.getIdentifier("hero", node.Vector()[0]).value());
}); });
} }
} }

View File

@ -99,7 +99,7 @@ namespace JsonRandom
std::string resourceName = loadKey(value, rng, defaultResources); std::string resourceName = loadKey(value, rng, defaultResources);
si32 resourceAmount = loadValue(value, rng, 0); si32 resourceAmount = loadValue(value, rng, 0);
si32 resourceID(VLC->modh->identifiers.getIdentifier(value.meta, "resource", resourceName).get()); si32 resourceID(VLC->modh->identifiers.getIdentifier(value.meta, "resource", resourceName).value());
TResources ret; TResources ret;
ret[resourceID] = resourceAmount; ret[resourceID] = resourceAmount;
@ -138,7 +138,7 @@ namespace JsonRandom
{ {
for(const auto & pair : value.Struct()) for(const auto & pair : value.Struct())
{ {
SecondarySkill id(VLC->modh->identifiers.getIdentifier(pair.second.meta, "skill", pair.first).get()); SecondarySkill id(VLC->modh->identifiers.getIdentifier(pair.second.meta, "skill", pair.first).value());
ret[id] = loadValue(pair.second, rng); ret[id] = loadValue(pair.second, rng);
} }
} }
@ -153,7 +153,7 @@ namespace JsonRandom
for(const auto & element : value.Vector()) for(const auto & element : value.Vector())
{ {
SecondarySkill id(VLC->modh->identifiers.getIdentifier(element.meta, "skill", loadKey(element, rng, defaultSkills)).get()); SecondarySkill id(VLC->modh->identifiers.getIdentifier(element.meta, "skill", loadKey(element, rng, defaultSkills)).value());
ret[id] = loadValue(element, rng); ret[id] = loadValue(element, rng);
} }
} }
@ -163,7 +163,7 @@ namespace JsonRandom
ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng) ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng)
{ {
if (value.getType() == JsonNode::JsonType::DATA_STRING) if (value.getType() == JsonNode::JsonType::DATA_STRING)
return ArtifactID(VLC->modh->identifiers.getIdentifier("artifact", value).get()); return ArtifactID(VLC->modh->identifiers.getIdentifier("artifact", value).value());
std::set<CArtifact::EartClass> allowedClasses; std::set<CArtifact::EartClass> allowedClasses;
std::set<ArtifactPosition> allowedPositions; std::set<ArtifactPosition> allowedPositions;
@ -224,7 +224,7 @@ namespace JsonRandom
SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, std::vector<SpellID> spells) SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, std::vector<SpellID> spells)
{ {
if (value.getType() == JsonNode::JsonType::DATA_STRING) if (value.getType() == JsonNode::JsonType::DATA_STRING)
return SpellID(VLC->modh->identifiers.getIdentifier("spell", value).get()); return SpellID(VLC->modh->identifiers.getIdentifier("spell", value).value());
vstd::erase_if(spells, [=](const SpellID & spell) vstd::erase_if(spells, [=](const SpellID & spell)
{ {
@ -252,7 +252,7 @@ namespace JsonRandom
CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng) CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng)
{ {
CStackBasicDescriptor stack; CStackBasicDescriptor stack;
stack.type = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", value["type"]).get()]; stack.type = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", value["type"]).value()];
stack.count = loadValue(value, rng); stack.count = loadValue(value, rng);
if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty()) if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty())
{ {
@ -288,7 +288,7 @@ namespace JsonRandom
info.minAmount = static_cast<si32>(node["min"].Float()); info.minAmount = static_cast<si32>(node["min"].Float());
info.maxAmount = static_cast<si32>(node["max"].Float()); info.maxAmount = static_cast<si32>(node["max"].Float());
} }
const CCreature * crea = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", node["type"]).get()]; const CCreature * crea = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", node["type"]).value()];
info.allowedCreatures.push_back(crea); info.allowedCreatures.push_back(crea);
if (node["upgradeChance"].Float() > 0) if (node["upgradeChance"].Float() > 0)
{ {

View File

@ -762,7 +762,7 @@ void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
one.String() = GameConstants::RESOURCE_NAMES[resID]; one.String() = GameConstants::RESOURCE_NAMES[resID];
node.Vector().push_back(one); node.Vector().push_back(one);
} }
handler.serializeRaw("possibleResources", node, boost::none); handler.serializeRaw("possibleResources", node, std::nullopt);
} }
else else
{ {
@ -1737,7 +1737,7 @@ void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
if(raw) if(raw)
{ {
bonusType = PRIM_SKILL; bonusType = PRIM_SKILL;
bonusID = raw.get(); bonusID = raw.value();
} }
} }
else if(!json["rewardSkill"].String().empty()) else if(!json["rewardSkill"].String().empty())
@ -1746,7 +1746,7 @@ void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
if(raw) if(raw)
{ {
bonusType = SECONDARY_SKILL; bonusType = SECONDARY_SKILL;
bonusID = raw.get(); bonusID = raw.value();
} }
} }
else if(!json["rewardSpell"].String().empty()) else if(!json["rewardSpell"].String().empty())
@ -1755,7 +1755,7 @@ void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
if(raw) if(raw)
{ {
bonusType = SPELL; bonusType = SPELL;
bonusID = raw.get(); bonusID = raw.value();
} }
} }
} }

View File

@ -450,13 +450,13 @@ void CCampaignState::setCurrentMapAsConquered(const std::vector<CGHeroInstance *
camp->scenarios[*currentMap].conquered = true; camp->scenarios[*currentMap].conquered = true;
} }
boost::optional<CScenarioTravel::STravelBonus> CCampaignState::getBonusForCurrentMap() const std::optional<CScenarioTravel::STravelBonus> CCampaignState::getBonusForCurrentMap() const
{ {
auto bonuses = getCurrentScenario().travelOptions.bonusesToChoose; auto bonuses = getCurrentScenario().travelOptions.bonusesToChoose;
assert(chosenCampaignBonuses.count(*currentMap) || bonuses.size() == 0); assert(chosenCampaignBonuses.count(*currentMap) || bonuses.size() == 0);
if(bonuses.empty()) if(bonuses.empty())
return boost::optional<CScenarioTravel::STravelBonus>(); return std::optional<CScenarioTravel::STravelBonus>();
else else
return bonuses[currentBonusID()]; return bonuses[currentBonusID()];
} }
@ -489,7 +489,7 @@ CMap * CCampaignState::getMap(int scenarioId) const
{ {
// FIXME: there is certainly better way to handle maps inside campaigns // FIXME: there is certainly better way to handle maps inside campaigns
if(scenarioId == -1) if(scenarioId == -1)
scenarioId = currentMap.get(); scenarioId = currentMap.value();
std::string scenarioName = camp->header.filename.substr(0, camp->header.filename.find('.')); std::string scenarioName = camp->header.filename.substr(0, camp->header.filename.find('.'));
boost::to_lower(scenarioName); boost::to_lower(scenarioName);
scenarioName += ':' + std::to_string(scenarioId); scenarioName += ':' + std::to_string(scenarioId);
@ -502,7 +502,7 @@ CMap * CCampaignState::getMap(int scenarioId) const
std::unique_ptr<CMapHeader> CCampaignState::getHeader(int scenarioId) const std::unique_ptr<CMapHeader> CCampaignState::getHeader(int scenarioId) const
{ {
if(scenarioId == -1) if(scenarioId == -1)
scenarioId = currentMap.get(); scenarioId = currentMap.value();
std::string scenarioName = camp->header.filename.substr(0, camp->header.filename.find('.')); std::string scenarioName = camp->header.filename.substr(0, camp->header.filename.find('.'));
boost::to_lower(scenarioName); boost::to_lower(scenarioName);
@ -516,7 +516,7 @@ std::unique_ptr<CMapHeader> CCampaignState::getHeader(int scenarioId) const
std::shared_ptr<CMapInfo> CCampaignState::getMapInfo(int scenarioId) const std::shared_ptr<CMapInfo> CCampaignState::getMapInfo(int scenarioId) const
{ {
if(scenarioId == -1) if(scenarioId == -1)
scenarioId = currentMap.get(); scenarioId = currentMap.value();
auto mapInfo = std::make_shared<CMapInfo>(); auto mapInfo = std::make_shared<CMapInfo>();
mapInfo->fileURI = camp->header.filename; mapInfo->fileURI = camp->header.filename;

View File

@ -186,12 +186,12 @@ public:
std::unique_ptr<CCampaign> camp; std::unique_ptr<CCampaign> camp;
std::string fileEncoding; std::string fileEncoding;
std::vector<ui8> mapsConquered, mapsRemaining; std::vector<ui8> mapsConquered, mapsRemaining;
boost::optional<si32> currentMap; std::optional<si32> currentMap;
std::map<ui8, ui8> chosenCampaignBonuses; std::map<ui8, ui8> chosenCampaignBonuses;
void setCurrentMapAsConquered(const std::vector<CGHeroInstance*> & heroes); void setCurrentMapAsConquered(const std::vector<CGHeroInstance*> & heroes);
boost::optional<CScenarioTravel::STravelBonus> getBonusForCurrentMap() const; std::optional<CScenarioTravel::STravelBonus> getBonusForCurrentMap() const;
const CCampaignScenario & getCurrentScenario() const; const CCampaignScenario & getCurrentScenario() const;
CCampaignScenario & getCurrentScenario(); CCampaignScenario & getCurrentScenario();
ui8 currentBonusID() const; ui8 currentBonusID() const;

Some files were not shown because too many files have changed in this diff Show More