mirror of
https://github.com/vcmi/vcmi.git
synced 2024-12-24 22:14:36 +02:00
commit
c9c118cff2
@ -374,6 +374,11 @@ void AIGateway::objectRemoved(const CGObjectInstance * obj, const PlayerColor &
|
||||
|
||||
nullkiller->memory->removeFromMemory(obj);
|
||||
|
||||
if(nullkiller->baseGraph && nullkiller->settings->isObjectGraphAllowed())
|
||||
{
|
||||
nullkiller->baseGraph->removeObject(obj);
|
||||
}
|
||||
|
||||
if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
|
||||
{
|
||||
lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
|
||||
|
@ -185,8 +185,8 @@ void foreach_tile_pos(const Func & foo)
|
||||
}
|
||||
}
|
||||
|
||||
template<class Func>
|
||||
void foreach_tile_pos(CCallback * cbp, const Func & foo) // avoid costly retrieval of thread-specific pointer
|
||||
template<class Func, class TCallback>
|
||||
void foreach_tile_pos(TCallback * cbp, const Func & foo) // avoid costly retrieval of thread-specific pointer
|
||||
{
|
||||
int3 mapSize = cbp->getMapSize();
|
||||
for(int z = 0; z < mapSize.z; z++)
|
||||
|
@ -75,8 +75,7 @@ void DangerHitMapAnalyzer::updateHitMap()
|
||||
|
||||
PathfinderSettings ps;
|
||||
|
||||
ps.mainTurnDistanceLimit = 10;
|
||||
ps.scoutTurnDistanceLimit = 10;
|
||||
ps.scoutTurnDistanceLimit = ps.mainTurnDistanceLimit = ai->settings->getMainHeroTurnDistanceLimit();
|
||||
ps.useHeroChain = false;
|
||||
|
||||
ai->pathfinder->updatePaths(pair.second, ps);
|
||||
@ -158,15 +157,13 @@ void DangerHitMapAnalyzer::calculateTileOwners()
|
||||
if(hitMap.shape()[0] != mapSize.x || hitMap.shape()[1] != mapSize.y || hitMap.shape()[2] != mapSize.z)
|
||||
hitMap.resize(boost::extents[mapSize.x][mapSize.y][mapSize.z]);
|
||||
|
||||
std::map<const CGHeroInstance *, HeroRole> townHeroes;
|
||||
std::vector<std::unique_ptr<CGHeroInstance>> temporaryHeroes;
|
||||
std::map<const CGHeroInstance *, const CGTownInstance *> heroTownMap;
|
||||
PathfinderSettings pathfinderSettings;
|
||||
|
||||
pathfinderSettings.mainTurnDistanceLimit = 5;
|
||||
std::map<const CGHeroInstance *, HeroRole> townHeroes;
|
||||
|
||||
auto addTownHero = [&](const CGTownInstance * town)
|
||||
{
|
||||
auto townHero = new CGHeroInstance(town->cb);
|
||||
auto townHero = temporaryHeroes.emplace_back(std::make_unique<CGHeroInstance>(town->cb)).get();
|
||||
CRandomGenerator rng;
|
||||
auto visitablePos = town->visitablePos();
|
||||
|
||||
@ -192,7 +189,10 @@ void DangerHitMapAnalyzer::calculateTileOwners()
|
||||
addTownHero(town);
|
||||
}
|
||||
|
||||
ai->pathfinder->updatePaths(townHeroes, PathfinderSettings());
|
||||
PathfinderSettings ps;
|
||||
ps.mainTurnDistanceLimit = ps.scoutTurnDistanceLimit = ai->settings->getMainHeroTurnDistanceLimit();
|
||||
|
||||
ai->pathfinder->updatePaths(townHeroes, ps);
|
||||
|
||||
pforeachTilePos(mapSize, [&](const int3 & pos)
|
||||
{
|
||||
|
@ -189,15 +189,7 @@ bool ObjectClusterizer::shouldVisitObject(const CGObjectInstance * obj) const
|
||||
return true; //all of the following is met
|
||||
}
|
||||
|
||||
void ObjectClusterizer::clusterize()
|
||||
{
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
|
||||
nearObjects.reset();
|
||||
farObjects.reset();
|
||||
blockedObjects.clear();
|
||||
|
||||
Obj ignoreObjects[] = {
|
||||
Obj ObjectClusterizer::IgnoredObjectTypes[] = {
|
||||
Obj::BOAT,
|
||||
Obj::EYE_OF_MAGI,
|
||||
Obj::MONOLITH_ONE_WAY_ENTRANCE,
|
||||
@ -216,7 +208,15 @@ void ObjectClusterizer::clusterize()
|
||||
Obj::REDWOOD_OBSERVATORY,
|
||||
Obj::CARTOGRAPHER,
|
||||
Obj::PILLAR_OF_FIRE
|
||||
};
|
||||
};
|
||||
|
||||
void ObjectClusterizer::clusterize()
|
||||
{
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
|
||||
nearObjects.reset();
|
||||
farObjects.reset();
|
||||
blockedObjects.clear();
|
||||
|
||||
logAi->debug("Begin object clusterization");
|
||||
|
||||
@ -224,131 +224,20 @@ void ObjectClusterizer::clusterize()
|
||||
ai->memory->visitableObjs.begin(),
|
||||
ai->memory->visitableObjs.end());
|
||||
|
||||
parallel_for(blocked_range<size_t>(0, objs.size()), [&](const blocked_range<size_t> & r)
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL == 0
|
||||
parallel_for(blocked_range<size_t>(0, objs.size()), [&](const blocked_range<size_t> & r) {
|
||||
#else
|
||||
blocked_range<size_t> r(0, objs.size());
|
||||
#endif
|
||||
auto priorityEvaluator = ai->priorityEvaluators->acquire();
|
||||
|
||||
for(int i = r.begin(); i != r.end(); i++)
|
||||
{
|
||||
auto obj = objs[i];
|
||||
|
||||
if(!shouldVisitObject(obj))
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Skip object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Check object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
|
||||
#endif
|
||||
|
||||
auto paths = ai->pathfinder->getPathInfo(obj->visitablePos());
|
||||
|
||||
if(paths.empty())
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("No paths found.");
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
std::sort(paths.begin(), paths.end(), [](const AIPath & p1, const AIPath & p2) -> bool
|
||||
{
|
||||
return p1.movementCost() < p2.movementCost();
|
||||
});
|
||||
|
||||
if(vstd::contains(ignoreObjects, obj->ID))
|
||||
{
|
||||
farObjects.addObject(obj, paths.front(), 0);
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Object ignored. Moved to far objects with path %s", paths.front().toString());
|
||||
#endif
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
std::set<const CGHeroInstance *> heroesProcessed;
|
||||
|
||||
for(auto & path : paths)
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Checking path %s", path.toString());
|
||||
#endif
|
||||
|
||||
if(!shouldVisit(ai, path.targetHero, obj))
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Hero %s does not need to visit %s", path.targetHero->getObjectName(), obj->getObjectName());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
if(path.nodes.size() > 1)
|
||||
{
|
||||
auto blocker = getBlocker(path);
|
||||
|
||||
if(blocker)
|
||||
{
|
||||
if(vstd::contains(heroesProcessed, path.targetHero))
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Hero %s is already processed.", path.targetHero->getObjectName());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
heroesProcessed.insert(path.targetHero);
|
||||
|
||||
float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
|
||||
|
||||
if(priority < MIN_PRIORITY)
|
||||
continue;
|
||||
|
||||
ClusterMap::accessor cluster;
|
||||
blockedObjects.insert(
|
||||
cluster,
|
||||
ClusterMap::value_type(blocker, std::make_shared<ObjectCluster>(blocker)));
|
||||
|
||||
cluster->second->addObject(obj, path, priority);
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Path added to cluster %s%s", blocker->getObjectName(), blocker->visitablePos().toString());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
heroesProcessed.insert(path.targetHero);
|
||||
|
||||
float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
|
||||
|
||||
if(priority < MIN_PRIORITY)
|
||||
continue;
|
||||
|
||||
bool interestingObject = path.turn() <= 2 || priority > 0.5f;
|
||||
|
||||
if(interestingObject)
|
||||
{
|
||||
nearObjects.addObject(obj, path, priority);
|
||||
}
|
||||
else
|
||||
{
|
||||
farObjects.addObject(obj, path, priority);
|
||||
}
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Path %s added to %s objects. Turn: %d, priority: %f",
|
||||
path.toString(),
|
||||
interestingObject ? "near" : "far",
|
||||
path.turn(),
|
||||
priority);
|
||||
#endif
|
||||
}
|
||||
clusterizeObject(objs[i], priorityEvaluator.get());
|
||||
}
|
||||
#if NKAI_TRACE_LEVEL == 0
|
||||
});
|
||||
#endif
|
||||
|
||||
logAi->trace("Near objects count: %i", nearObjects.objects.size());
|
||||
logAi->trace("Far objects count: %i", farObjects.objects.size());
|
||||
@ -368,4 +257,123 @@ void ObjectClusterizer::clusterize()
|
||||
logAi->trace("Clusterization complete in %ld", timeElapsed(start));
|
||||
}
|
||||
|
||||
void ObjectClusterizer::clusterizeObject(const CGObjectInstance * obj, PriorityEvaluator * priorityEvaluator)
|
||||
{
|
||||
if(!shouldVisitObject(obj))
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Skip object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Check object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
|
||||
#endif
|
||||
|
||||
auto paths = ai->pathfinder->getPathInfo(obj->visitablePos(), true);
|
||||
|
||||
if(paths.empty())
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("No paths found.");
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
std::sort(paths.begin(), paths.end(), [](const AIPath & p1, const AIPath & p2) -> bool
|
||||
{
|
||||
return p1.movementCost() < p2.movementCost();
|
||||
});
|
||||
|
||||
if(vstd::contains(IgnoredObjectTypes, obj->ID))
|
||||
{
|
||||
farObjects.addObject(obj, paths.front(), 0);
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Object ignored. Moved to far objects with path %s", paths.front().toString());
|
||||
#endif
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
std::set<const CGHeroInstance *> heroesProcessed;
|
||||
|
||||
for(auto & path : paths)
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Checking path %s", path.toString());
|
||||
#endif
|
||||
|
||||
if(!shouldVisit(ai, path.targetHero, obj))
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Hero %s does not need to visit %s", path.targetHero->getObjectName(), obj->getObjectName());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
if(path.nodes.size() > 1)
|
||||
{
|
||||
auto blocker = getBlocker(path);
|
||||
|
||||
if(blocker)
|
||||
{
|
||||
if(vstd::contains(heroesProcessed, path.targetHero))
|
||||
{
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Hero %s is already processed.", path.targetHero->getObjectName());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
heroesProcessed.insert(path.targetHero);
|
||||
|
||||
float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
|
||||
|
||||
if(priority < MIN_PRIORITY)
|
||||
continue;
|
||||
|
||||
ClusterMap::accessor cluster;
|
||||
blockedObjects.insert(
|
||||
cluster,
|
||||
ClusterMap::value_type(blocker, std::make_shared<ObjectCluster>(blocker)));
|
||||
|
||||
cluster->second->addObject(obj, path, priority);
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Path added to cluster %s%s", blocker->getObjectName(), blocker->visitablePos().toString());
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
heroesProcessed.insert(path.targetHero);
|
||||
|
||||
float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
|
||||
|
||||
if(priority < MIN_PRIORITY)
|
||||
continue;
|
||||
|
||||
bool interestingObject = path.turn() <= 2 || priority > 0.5f;
|
||||
|
||||
if(interestingObject)
|
||||
{
|
||||
nearObjects.addObject(obj, path, priority);
|
||||
}
|
||||
else
|
||||
{
|
||||
farObjects.addObject(obj, path, priority);
|
||||
}
|
||||
|
||||
#if NKAI_TRACE_LEVEL >= 2
|
||||
logAi->trace("Path %s added to %s objects. Turn: %d, priority: %f",
|
||||
path.toString(),
|
||||
interestingObject ? "near" : "far",
|
||||
path.turn(),
|
||||
priority);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -49,9 +49,13 @@ public:
|
||||
|
||||
using ClusterMap = tbb::concurrent_hash_map<const CGObjectInstance *, std::shared_ptr<ObjectCluster>>;
|
||||
|
||||
class PriorityEvaluator;
|
||||
|
||||
class ObjectClusterizer
|
||||
{
|
||||
private:
|
||||
static Obj IgnoredObjectTypes[];
|
||||
|
||||
ObjectCluster nearObjects;
|
||||
ObjectCluster farObjects;
|
||||
ClusterMap blockedObjects;
|
||||
@ -68,6 +72,7 @@ public:
|
||||
|
||||
private:
|
||||
bool shouldVisitObject(const CGObjectInstance * obj) const;
|
||||
void clusterizeObject(const CGObjectInstance * obj, PriorityEvaluator * priorityEvaluator);
|
||||
};
|
||||
|
||||
}
|
||||
|
@ -178,8 +178,11 @@ Goals::TGoalVec CaptureObjectsBehavior::decompose() const
|
||||
#endif
|
||||
|
||||
const int3 pos = objToVisit->visitablePos();
|
||||
bool useObjectGraph = ai->nullkiller->settings->isObjectGraphAllowed()
|
||||
&& ai->nullkiller->getScanDepth() != ScanDepth::SMALL;
|
||||
|
||||
auto paths = ai->nullkiller->pathfinder->getPathInfo(pos, useObjectGraph);
|
||||
|
||||
auto paths = ai->nullkiller->pathfinder->getPathInfo(pos);
|
||||
std::vector<std::shared_ptr<ExecuteHeroChain>> waysToVisitObj;
|
||||
std::shared_ptr<ExecuteHeroChain> closestWay;
|
||||
|
||||
|
@ -42,7 +42,7 @@ Goals::TGoalVec ClusterBehavior::decompose() const
|
||||
Goals::TGoalVec ClusterBehavior::decomposeCluster(std::shared_ptr<ObjectCluster> cluster) const
|
||||
{
|
||||
auto center = cluster->calculateCenter();
|
||||
auto paths = ai->nullkiller->pathfinder->getPathInfo(center->visitablePos());
|
||||
auto paths = ai->nullkiller->pathfinder->getPathInfo(center->visitablePos(), ai->nullkiller->settings->isObjectGraphAllowed());
|
||||
auto blockerPos = cluster->blocker->visitablePos();
|
||||
std::vector<AIPath> blockerPaths;
|
||||
|
||||
|
@ -443,6 +443,10 @@ void DefenceBehavior::evaluateRecruitingHero(Goals::TGoalVec & tasks, const HitM
|
||||
heroToDismiss = town->garrisonHero.get();
|
||||
}
|
||||
}
|
||||
|
||||
// avoid dismissing one weak hero in order to recruit another.
|
||||
if(heroToDismiss && heroToDismiss->getArmyStrength() + 500 > hero->getArmyStrength())
|
||||
continue;
|
||||
}
|
||||
else if(ai->nullkiller->heroManager->heroCapReached())
|
||||
{
|
||||
|
@ -14,6 +14,7 @@ set(Nullkiller_SRCS
|
||||
Pathfinding/Rules/AIMovementAfterDestinationRule.cpp
|
||||
Pathfinding/Rules/AIMovementToDestinationRule.cpp
|
||||
Pathfinding/Rules/AIPreviousNodeRule.cpp
|
||||
Pathfinding/ObjectGraph.cpp
|
||||
AIUtility.cpp
|
||||
Analyzers/ArmyManager.cpp
|
||||
Analyzers/HeroManager.cpp
|
||||
@ -78,6 +79,7 @@ set(Nullkiller_HEADERS
|
||||
Pathfinding/Rules/AIMovementAfterDestinationRule.h
|
||||
Pathfinding/Rules/AIMovementToDestinationRule.h
|
||||
Pathfinding/Rules/AIPreviousNodeRule.h
|
||||
Pathfinding/ObjectGraph.h
|
||||
AIUtility.h
|
||||
Analyzers/ArmyManager.h
|
||||
Analyzers/HeroManager.h
|
||||
|
@ -27,6 +27,9 @@ namespace NKAI
|
||||
|
||||
using namespace Goals;
|
||||
|
||||
// while we play vcmieagles graph can be shared
|
||||
std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
|
||||
|
||||
Nullkiller::Nullkiller()
|
||||
:activeHero(nullptr), scanDepth(ScanDepth::MAIN_FULL), useHeroChain(true)
|
||||
{
|
||||
@ -39,6 +42,8 @@ void Nullkiller::init(std::shared_ptr<CCallback> cb, PlayerColor playerID)
|
||||
this->cb = cb;
|
||||
this->playerID = playerID;
|
||||
|
||||
baseGraph.reset();
|
||||
|
||||
priorityEvaluator.reset(new PriorityEvaluator(this));
|
||||
priorityEvaluators.reset(
|
||||
new SharedPool<PriorityEvaluator>(
|
||||
@ -119,6 +124,12 @@ void Nullkiller::resetAiState()
|
||||
lockedHeroes.clear();
|
||||
dangerHitMap->reset();
|
||||
useHeroChain = true;
|
||||
|
||||
if(!baseGraph && ai->nullkiller->settings->isObjectGraphAllowed())
|
||||
{
|
||||
baseGraph = std::make_unique<ObjectGraph>();
|
||||
baseGraph->updateGraph(this);
|
||||
}
|
||||
}
|
||||
|
||||
void Nullkiller::updateAiState(int pass, bool fast)
|
||||
@ -159,21 +170,27 @@ void Nullkiller::updateAiState(int pass, bool fast)
|
||||
|
||||
PathfinderSettings cfg;
|
||||
cfg.useHeroChain = useHeroChain;
|
||||
cfg.allowBypassObjects = true;
|
||||
|
||||
if(scanDepth == ScanDepth::SMALL)
|
||||
if(scanDepth == ScanDepth::SMALL || settings->isObjectGraphAllowed())
|
||||
{
|
||||
cfg.mainTurnDistanceLimit = ai->nullkiller->settings->getMainHeroTurnDistanceLimit();
|
||||
cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
|
||||
}
|
||||
|
||||
if(scanDepth != ScanDepth::ALL_FULL)
|
||||
if(scanDepth != ScanDepth::ALL_FULL || settings->isObjectGraphAllowed())
|
||||
{
|
||||
cfg.scoutTurnDistanceLimit = ai->nullkiller->settings->getScoutHeroTurnDistanceLimit();
|
||||
cfg.scoutTurnDistanceLimit =settings->getScoutHeroTurnDistanceLimit();
|
||||
}
|
||||
|
||||
boost::this_thread::interruption_point();
|
||||
|
||||
pathfinder->updatePaths(activeHeroes, cfg);
|
||||
|
||||
if(settings->isObjectGraphAllowed())
|
||||
{
|
||||
pathfinder->updateGraphs(activeHeroes);
|
||||
}
|
||||
|
||||
boost::this_thread::interruption_point();
|
||||
|
||||
objectClusterizer->clusterize();
|
||||
@ -286,7 +303,8 @@ void Nullkiller::makeTurn()
|
||||
|
||||
// TODO: better to check turn distance here instead of priority
|
||||
if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
|
||||
&& scanDepth == ScanDepth::MAIN_FULL)
|
||||
&& scanDepth == ScanDepth::MAIN_FULL
|
||||
&& !settings->isObjectGraphAllowed())
|
||||
{
|
||||
useHeroChain = false;
|
||||
scanDepth = ScanDepth::SMALL;
|
||||
@ -299,22 +317,25 @@ void Nullkiller::makeTurn()
|
||||
|
||||
if(bestTask->priority < MIN_PRIORITY)
|
||||
{
|
||||
auto heroes = cb->getHeroesInfo();
|
||||
auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
|
||||
{
|
||||
return h->movementPointsRemaining() > 100;
|
||||
});
|
||||
|
||||
if(hasMp && scanDepth != ScanDepth::ALL_FULL)
|
||||
if(!settings->isObjectGraphAllowed())
|
||||
{
|
||||
logAi->trace(
|
||||
"Goal %s has too low priority %f so increasing scan depth to full.",
|
||||
taskDescription,
|
||||
bestTask->priority);
|
||||
auto heroes = cb->getHeroesInfo();
|
||||
auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
|
||||
{
|
||||
return h->movementPointsRemaining() > 100;
|
||||
});
|
||||
|
||||
scanDepth = ScanDepth::ALL_FULL;
|
||||
useHeroChain = false;
|
||||
continue;
|
||||
if(hasMp && scanDepth != ScanDepth::ALL_FULL)
|
||||
{
|
||||
logAi->trace(
|
||||
"Goal %s has too low priority %f so increasing scan depth to full.",
|
||||
taskDescription,
|
||||
bestTask->priority);
|
||||
|
||||
scanDepth = ScanDepth::ALL_FULL;
|
||||
useHeroChain = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
logAi->trace("Goal %s has too low priority. It is not worth doing it. Ending turn.", taskDescription);
|
||||
|
@ -59,6 +59,8 @@ private:
|
||||
bool useHeroChain;
|
||||
|
||||
public:
|
||||
static std::unique_ptr<ObjectGraph> baseGraph;
|
||||
|
||||
std::unique_ptr<DangerHitMapAnalyzer> dangerHitMap;
|
||||
std::unique_ptr<BuildAnalyzer> buildAnalyzer;
|
||||
std::unique_ptr<ObjectClusterizer> objectClusterizer;
|
||||
|
@ -27,7 +27,8 @@ namespace NKAI
|
||||
mainHeroTurnDistanceLimit(10),
|
||||
scoutHeroTurnDistanceLimit(5),
|
||||
maxGoldPreasure(0.3f),
|
||||
maxpass(30)
|
||||
maxpass(30),
|
||||
allowObjectGraph(false)
|
||||
{
|
||||
ResourcePath resource("config/ai/nkai/nkai-settings", EResType::JSON);
|
||||
|
||||
@ -74,5 +75,10 @@ namespace NKAI
|
||||
{
|
||||
maxGoldPreasure = node.Struct()["maxGoldPreasure"].Float();
|
||||
}
|
||||
|
||||
if(!node.Struct()["allowObjectGraph"].isNull())
|
||||
{
|
||||
allowObjectGraph = node.Struct()["allowObjectGraph"].Bool();
|
||||
}
|
||||
}
|
||||
}
|
@ -26,6 +26,7 @@ namespace NKAI
|
||||
int scoutHeroTurnDistanceLimit;
|
||||
int maxpass;
|
||||
float maxGoldPreasure;
|
||||
bool allowObjectGraph;
|
||||
|
||||
public:
|
||||
Settings();
|
||||
@ -35,6 +36,7 @@ namespace NKAI
|
||||
int getMaxRoamingHeroes() const { return maxRoamingHeroes; }
|
||||
int getMainHeroTurnDistanceLimit() const { return mainHeroTurnDistanceLimit; }
|
||||
int getScoutHeroTurnDistanceLimit() const { return scoutHeroTurnDistanceLimit; }
|
||||
bool isObjectGraphAllowed() const { return allowObjectGraph; }
|
||||
|
||||
private:
|
||||
void loadFromMod(const std::string & modName, const ResourcePath & resource);
|
||||
|
@ -39,12 +39,18 @@ void AdventureSpellCast::accept(AIGateway * ai)
|
||||
if(hero->mana < hero->getSpellCost(spell))
|
||||
throw cannotFulfillGoalException("Hero has not enough mana to cast " + spell->getNameTranslated());
|
||||
|
||||
if(spellID == SpellID::TOWN_PORTAL && town && town->visitingHero)
|
||||
throw cannotFulfillGoalException("The town is already occupied by " + town->visitingHero->getNameTranslated());
|
||||
|
||||
if(town && spellID == SpellID::TOWN_PORTAL)
|
||||
{
|
||||
ai->selectedObject = town->id;
|
||||
|
||||
if(town->visitingHero && town->tempOwner == ai->playerID && !town->getUpperArmy()->stacksCount())
|
||||
{
|
||||
ai->myCb->swapGarrisonHero(town);
|
||||
}
|
||||
|
||||
if(town->visitingHero)
|
||||
throw cannotFulfillGoalException("The town is already occupied by " + town->visitingHero->getNameTranslated());
|
||||
}
|
||||
|
||||
auto wait = cb->waitTillRealize;
|
||||
|
@ -1123,14 +1123,14 @@ void AINodeStorage::calculateTownPortal(
|
||||
{
|
||||
for(const CGTownInstance * targetTown : towns)
|
||||
{
|
||||
// TODO: allow to hide visiting hero in garrison
|
||||
if(targetTown->visitingHero && maskMap.find(targetTown->visitingHero.get()) != maskMap.end())
|
||||
if(targetTown->visitingHero
|
||||
&& targetTown->getUpperArmy()->stacksCount()
|
||||
&& maskMap.find(targetTown->visitingHero.get()) != maskMap.end())
|
||||
{
|
||||
auto basicMask = maskMap.at(targetTown->visitingHero.get());
|
||||
bool heroIsInChain = (actor->chainMask & basicMask) != 0;
|
||||
bool sameActorInTown = actor->chainMask == basicMask;
|
||||
|
||||
if(sameActorInTown || !heroIsInChain)
|
||||
if(!sameActorInTown)
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -11,6 +11,7 @@
|
||||
#pragma once
|
||||
|
||||
#define NKAI_PATHFINDER_TRACE_LEVEL 0
|
||||
constexpr int NKAI_GRAPH_TRACE_LEVEL = 0;
|
||||
#define NKAI_TRACE_LEVEL 0
|
||||
|
||||
#include "../../../lib/pathfinder/CGPathNode.h"
|
||||
@ -26,15 +27,9 @@ namespace NKAI
|
||||
{
|
||||
namespace AIPathfinding
|
||||
{
|
||||
#ifdef ENVIRONMENT64
|
||||
const int BUCKET_COUNT = 7;
|
||||
#else
|
||||
const int BUCKET_COUNT = 5;
|
||||
#endif // ENVIRONMENT64
|
||||
|
||||
const int BUCKET_SIZE = 5;
|
||||
const int BUCKET_SIZE = 3;
|
||||
const int NUM_CHAINS = BUCKET_COUNT * BUCKET_SIZE;
|
||||
const int THREAD_COUNT = 8;
|
||||
const int CHAIN_MAX_DEPTH = 4;
|
||||
}
|
||||
|
||||
|
@ -33,7 +33,7 @@ bool AIPathfinder::isTileAccessible(const HeroPtr & hero, const int3 & tile) con
|
||||
|| storage->isTileAccessible(hero, tile, EPathfindingLayer::SAIL);
|
||||
}
|
||||
|
||||
std::vector<AIPath> AIPathfinder::getPathInfo(const int3 & tile) const
|
||||
std::vector<AIPath> AIPathfinder::getPathInfo(const int3 & tile, bool includeGraph) const
|
||||
{
|
||||
const TerrainTile * tileInfo = cb->getTile(tile, false);
|
||||
|
||||
@ -42,10 +42,23 @@ std::vector<AIPath> AIPathfinder::getPathInfo(const int3 & tile) const
|
||||
return std::vector<AIPath>();
|
||||
}
|
||||
|
||||
return storage->getChainInfo(tile, !tileInfo->isWater());
|
||||
auto info = storage->getChainInfo(tile, !tileInfo->isWater());
|
||||
|
||||
if(includeGraph)
|
||||
{
|
||||
for(auto hero : cb->getHeroesInfo())
|
||||
{
|
||||
auto graph = heroGraphs.find(hero->id);
|
||||
|
||||
if(graph != heroGraphs.end())
|
||||
graph->second.addChainInfo(info, tile, hero, ai);
|
||||
}
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
void AIPathfinder::updatePaths(std::map<const CGHeroInstance *, HeroRole> heroes, PathfinderSettings pathfinderSettings)
|
||||
void AIPathfinder::updatePaths(const std::map<const CGHeroInstance *, HeroRole> & heroes, PathfinderSettings pathfinderSettings)
|
||||
{
|
||||
if(!storage)
|
||||
{
|
||||
@ -71,7 +84,7 @@ void AIPathfinder::updatePaths(std::map<const CGHeroInstance *, HeroRole> heroes
|
||||
storage->setTownsAndDwellings(cb->getTownsInfo(), ai->memory->visitableObjs);
|
||||
}
|
||||
|
||||
auto config = std::make_shared<AIPathfinding::AIPathfinderConfig>(cb, ai, storage);
|
||||
auto config = std::make_shared<AIPathfinding::AIPathfinderConfig>(cb, ai, storage, pathfinderSettings.allowBypassObjects);
|
||||
|
||||
logAi->trace("Recalculate paths pass %d", pass++);
|
||||
cb->calculatePaths(config);
|
||||
@ -112,4 +125,34 @@ void AIPathfinder::updatePaths(std::map<const CGHeroInstance *, HeroRole> heroes
|
||||
logAi->trace("Recalculated paths in %ld", timeElapsed(start));
|
||||
}
|
||||
|
||||
void AIPathfinder::updateGraphs(const std::map<const CGHeroInstance *, HeroRole> & heroes)
|
||||
{
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
std::vector<const CGHeroInstance *> heroesVector;
|
||||
|
||||
heroGraphs.clear();
|
||||
|
||||
for(auto hero : heroes)
|
||||
{
|
||||
if(heroGraphs.try_emplace(hero.first->id, GraphPaths()).second)
|
||||
heroesVector.push_back(hero.first);
|
||||
}
|
||||
|
||||
parallel_for(blocked_range<size_t>(0, heroesVector.size()), [this, &heroesVector](const blocked_range<size_t> & r)
|
||||
{
|
||||
for(auto i = r.begin(); i != r.end(); i++)
|
||||
heroGraphs.at(heroesVector[i]->id).calculatePaths(heroesVector[i], ai);
|
||||
});
|
||||
|
||||
if(NKAI_GRAPH_TRACE_LEVEL >= 1)
|
||||
{
|
||||
for(auto hero : heroes)
|
||||
{
|
||||
heroGraphs[hero.first->id].dumpToLog();
|
||||
}
|
||||
}
|
||||
|
||||
logAi->trace("Graph paths updated in %lld", timeElapsed(start));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -11,6 +11,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "AINodeStorage.h"
|
||||
#include "ObjectGraph.h"
|
||||
#include "../AIUtility.h"
|
||||
|
||||
namespace NKAI
|
||||
@ -23,11 +24,13 @@ struct PathfinderSettings
|
||||
bool useHeroChain;
|
||||
uint8_t scoutTurnDistanceLimit;
|
||||
uint8_t mainTurnDistanceLimit;
|
||||
bool allowBypassObjects;
|
||||
|
||||
PathfinderSettings()
|
||||
:useHeroChain(false),
|
||||
scoutTurnDistanceLimit(255),
|
||||
mainTurnDistanceLimit(255)
|
||||
mainTurnDistanceLimit(255),
|
||||
allowBypassObjects(true)
|
||||
{ }
|
||||
};
|
||||
|
||||
@ -37,13 +40,20 @@ private:
|
||||
std::shared_ptr<AINodeStorage> storage;
|
||||
CPlayerSpecificInfoCallback * cb;
|
||||
Nullkiller * ai;
|
||||
std::map<ObjectInstanceID, GraphPaths> heroGraphs;
|
||||
|
||||
public:
|
||||
AIPathfinder(CPlayerSpecificInfoCallback * cb, Nullkiller * ai);
|
||||
std::vector<AIPath> getPathInfo(const int3 & tile) const;
|
||||
std::vector<AIPath> getPathInfo(const int3 & tile, bool includeGraph = false) const;
|
||||
bool isTileAccessible(const HeroPtr & hero, const int3 & tile) const;
|
||||
void updatePaths(std::map<const CGHeroInstance *, HeroRole> heroes, PathfinderSettings pathfinderSettings);
|
||||
void updatePaths(const std::map<const CGHeroInstance *, HeroRole> & heroes, PathfinderSettings pathfinderSettings);
|
||||
void updateGraphs(const std::map<const CGHeroInstance *, HeroRole> & heroes);
|
||||
void init();
|
||||
|
||||
std::shared_ptr<AINodeStorage>getStorage()
|
||||
{
|
||||
return storage;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
@ -24,16 +24,17 @@ namespace AIPathfinding
|
||||
std::vector<std::shared_ptr<IPathfindingRule>> makeRuleset(
|
||||
CPlayerSpecificInfoCallback * cb,
|
||||
Nullkiller * ai,
|
||||
std::shared_ptr<AINodeStorage> nodeStorage)
|
||||
std::shared_ptr<AINodeStorage> nodeStorage,
|
||||
bool allowBypassObjects)
|
||||
{
|
||||
std::vector<std::shared_ptr<IPathfindingRule>> rules = {
|
||||
std::make_shared<AILayerTransitionRule>(cb, ai, nodeStorage),
|
||||
std::make_shared<DestinationActionRule>(),
|
||||
std::make_shared<AIMovementToDestinationRule>(nodeStorage),
|
||||
std::make_shared<MovementCostRule>(),
|
||||
std::make_shared<AIPreviousNodeRule>(nodeStorage),
|
||||
std::make_shared<AIMovementAfterDestinationRule>(cb, nodeStorage)
|
||||
};
|
||||
std::vector<std::shared_ptr<IPathfindingRule>> rules = {
|
||||
std::make_shared<AILayerTransitionRule>(cb, ai, nodeStorage),
|
||||
std::make_shared<DestinationActionRule>(),
|
||||
std::make_shared<AIMovementToDestinationRule>(nodeStorage, allowBypassObjects),
|
||||
std::make_shared<MovementCostRule>(),
|
||||
std::make_shared<AIPreviousNodeRule>(nodeStorage),
|
||||
std::make_shared<AIMovementAfterDestinationRule>(cb, nodeStorage, allowBypassObjects)
|
||||
};
|
||||
|
||||
return rules;
|
||||
}
|
||||
@ -41,8 +42,9 @@ namespace AIPathfinding
|
||||
AIPathfinderConfig::AIPathfinderConfig(
|
||||
CPlayerSpecificInfoCallback * cb,
|
||||
Nullkiller * ai,
|
||||
std::shared_ptr<AINodeStorage> nodeStorage)
|
||||
:PathfinderConfig(nodeStorage, makeRuleset(cb, ai, nodeStorage)), aiNodeStorage(nodeStorage)
|
||||
std::shared_ptr<AINodeStorage> nodeStorage,
|
||||
bool allowBypassObjects)
|
||||
:PathfinderConfig(nodeStorage, makeRuleset(cb, ai, nodeStorage, allowBypassObjects)), aiNodeStorage(nodeStorage)
|
||||
{
|
||||
options.canUseCast = true;
|
||||
}
|
||||
|
@ -30,7 +30,8 @@ namespace AIPathfinding
|
||||
AIPathfinderConfig(
|
||||
CPlayerSpecificInfoCallback * cb,
|
||||
Nullkiller * ai,
|
||||
std::shared_ptr<AINodeStorage> nodeStorage);
|
||||
std::shared_ptr<AINodeStorage> nodeStorage,
|
||||
bool allowBypassObjects);
|
||||
|
||||
~AIPathfinderConfig();
|
||||
|
||||
|
421
AI/Nullkiller/Pathfinding/ObjectGraph.cpp
Normal file
421
AI/Nullkiller/Pathfinding/ObjectGraph.cpp
Normal file
@ -0,0 +1,421 @@
|
||||
/*
|
||||
* ObjectGraph.cpp, part of VCMI engine
|
||||
*
|
||||
* Authors: listed in file AUTHORS in main folder
|
||||
*
|
||||
* License: GNU General Public License v2.0 or later
|
||||
* Full text of license available in license.txt file, in main folder
|
||||
*
|
||||
*/
|
||||
#include "StdInc.h"
|
||||
#include "ObjectGraph.h"
|
||||
#include "AIPathfinderConfig.h"
|
||||
#include "../../../lib/CRandomGenerator.h"
|
||||
#include "../../../CCallback.h"
|
||||
#include "../../../lib/mapping/CMap.h"
|
||||
#include "../Engine/Nullkiller.h"
|
||||
#include "../../../lib/logging/VisualLogger.h"
|
||||
|
||||
namespace NKAI
|
||||
{
|
||||
|
||||
class ObjectGraphCalculator
|
||||
{
|
||||
private:
|
||||
ObjectGraph * target;
|
||||
const Nullkiller * ai;
|
||||
|
||||
std::map<const CGHeroInstance *, HeroRole> actors;
|
||||
std::map<const CGHeroInstance *, const CGObjectInstance *> actorObjectMap;
|
||||
|
||||
std::vector<std::unique_ptr<CGBoat>> temporaryBoats;
|
||||
std::vector<std::unique_ptr<CGHeroInstance>> temporaryActorHeroes;
|
||||
|
||||
public:
|
||||
ObjectGraphCalculator(ObjectGraph * target, const Nullkiller * ai)
|
||||
:ai(ai), target(target)
|
||||
{
|
||||
for(auto obj : ai->memory->visitableObjs)
|
||||
{
|
||||
if(obj && obj->isVisitable() && obj->ID != Obj::HERO)
|
||||
{
|
||||
addObjectActor(obj);
|
||||
}
|
||||
}
|
||||
|
||||
for(auto town : ai->cb->getTownsInfo())
|
||||
{
|
||||
addObjectActor(town);
|
||||
}
|
||||
|
||||
PathfinderSettings ps;
|
||||
|
||||
ps.mainTurnDistanceLimit = 5;
|
||||
ps.scoutTurnDistanceLimit = 1;
|
||||
ps.allowBypassObjects = false;
|
||||
|
||||
ai->pathfinder->updatePaths(actors, ps);
|
||||
}
|
||||
|
||||
void calculateConnections(const int3 & pos)
|
||||
{
|
||||
auto guarded = ai->cb->getGuardingCreaturePosition(pos).valid();
|
||||
|
||||
if(guarded)
|
||||
return;
|
||||
|
||||
auto paths = ai->pathfinder->getPathInfo(pos);
|
||||
|
||||
for(AIPath & path1 : paths)
|
||||
{
|
||||
for(AIPath & path2 : paths)
|
||||
{
|
||||
if(path1.targetHero == path2.targetHero)
|
||||
continue;
|
||||
|
||||
auto obj1 = actorObjectMap[path1.targetHero];
|
||||
auto obj2 = actorObjectMap[path2.targetHero];
|
||||
|
||||
auto tile1 = cb->getTile(obj1->visitablePos());
|
||||
auto tile2 = cb->getTile(obj2->visitablePos());
|
||||
|
||||
if(tile2->isWater() && !tile1->isWater())
|
||||
{
|
||||
auto linkTile = cb->getTile(pos);
|
||||
|
||||
if(!linkTile->isWater() || obj1->ID != Obj::BOAT || obj1->ID != Obj::SHIPYARD)
|
||||
continue;
|
||||
}
|
||||
|
||||
auto danger = ai->pathfinder->getStorage()->evaluateDanger(obj2->visitablePos(), path1.targetHero, true);
|
||||
|
||||
auto updated = target->tryAddConnection(
|
||||
obj1->visitablePos(),
|
||||
obj2->visitablePos(),
|
||||
path1.movementCost() + path2.movementCost(),
|
||||
danger);
|
||||
|
||||
if(NKAI_GRAPH_TRACE_LEVEL >= 2 && updated)
|
||||
{
|
||||
logAi->trace(
|
||||
"Connected %s[%s] -> %s[%s] through [%s], cost %2f",
|
||||
obj1->getObjectName(), obj1->visitablePos().toString(),
|
||||
obj2->getObjectName(), obj2->visitablePos().toString(),
|
||||
pos.toString(),
|
||||
path1.movementCost() + path2.movementCost());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void addObjectActor(const CGObjectInstance * obj)
|
||||
{
|
||||
auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(obj->cb)).get();
|
||||
|
||||
CRandomGenerator rng;
|
||||
auto visitablePos = obj->visitablePos();
|
||||
|
||||
objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
|
||||
objectActor->initHero(rng, static_cast<HeroTypeID>(0));
|
||||
objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
|
||||
objectActor->initObj(rng);
|
||||
|
||||
if(cb->getTile(visitablePos)->isWater())
|
||||
{
|
||||
objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
|
||||
}
|
||||
|
||||
actorObjectMap[objectActor] = obj;
|
||||
actors[objectActor] = obj->ID == Obj::TOWN || obj->ID == Obj::SHIPYARD ? HeroRole::MAIN : HeroRole::SCOUT;
|
||||
|
||||
target->addObject(obj);
|
||||
};
|
||||
};
|
||||
|
||||
bool ObjectGraph::tryAddConnection(
|
||||
const int3 & from,
|
||||
const int3 & to,
|
||||
float cost,
|
||||
uint64_t danger)
|
||||
{
|
||||
return nodes[from].connections[to].update(cost, danger);
|
||||
}
|
||||
|
||||
void ObjectGraph::updateGraph(const Nullkiller * ai)
|
||||
{
|
||||
auto cb = ai->cb;
|
||||
|
||||
ObjectGraphCalculator calculator(this, ai);
|
||||
|
||||
foreach_tile_pos(cb.get(), [this, &calculator](const CPlayerSpecificInfoCallback * cb, const int3 & pos)
|
||||
{
|
||||
if(nodes.find(pos) != nodes.end())
|
||||
return;
|
||||
|
||||
calculator.calculateConnections(pos);
|
||||
});
|
||||
|
||||
if(NKAI_GRAPH_TRACE_LEVEL >= 1)
|
||||
dumpToLog("graph");
|
||||
|
||||
}
|
||||
|
||||
void ObjectGraph::addObject(const CGObjectInstance * obj)
|
||||
{
|
||||
nodes[obj->visitablePos()].init(obj);
|
||||
}
|
||||
|
||||
void ObjectGraph::removeObject(const CGObjectInstance * obj)
|
||||
{
|
||||
nodes[obj->visitablePos()].objectExists = false;
|
||||
|
||||
if(obj->ID == Obj::BOAT)
|
||||
{
|
||||
vstd::erase_if(nodes[obj->visitablePos()].connections, [&](const std::pair<int3, ObjectLink> & link) -> bool
|
||||
{
|
||||
auto tile = cb->getTile(link.first, false);
|
||||
|
||||
return tile && tile->isWater();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void ObjectGraph::connectHeroes(const Nullkiller * ai)
|
||||
{
|
||||
for(auto obj : ai->memory->visitableObjs)
|
||||
{
|
||||
if(obj && obj->ID == Obj::HERO)
|
||||
{
|
||||
addObject(obj);
|
||||
}
|
||||
}
|
||||
|
||||
for(auto & node : nodes)
|
||||
{
|
||||
auto pos = node.first;
|
||||
auto paths = ai->pathfinder->getPathInfo(pos);
|
||||
|
||||
for(AIPath & path : paths)
|
||||
{
|
||||
auto heroPos = path.targetHero->visitablePos();
|
||||
|
||||
nodes[pos].connections[heroPos].update(
|
||||
path.movementCost(),
|
||||
path.getPathDanger());
|
||||
|
||||
nodes[heroPos].connections[pos].update(
|
||||
path.movementCost(),
|
||||
path.getPathDanger());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ObjectGraph::dumpToLog(std::string visualKey) const
|
||||
{
|
||||
logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
|
||||
{
|
||||
for(auto & tile : nodes)
|
||||
{
|
||||
for(auto & node : tile.second.connections)
|
||||
{
|
||||
if(NKAI_GRAPH_TRACE_LEVEL >= 2)
|
||||
{
|
||||
logAi->trace(
|
||||
"%s -> %s: %f !%d",
|
||||
node.first.toString(),
|
||||
tile.first.toString(),
|
||||
node.second.cost,
|
||||
node.second.danger);
|
||||
}
|
||||
|
||||
logBuilder.addLine(tile.first, node.first);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bool GraphNodeComparer::operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const
|
||||
{
|
||||
return pathNodes.at(lhs.coord)[lhs.nodeType].cost > pathNodes.at(rhs.coord)[rhs.nodeType].cost;
|
||||
}
|
||||
|
||||
void GraphPaths::calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai)
|
||||
{
|
||||
graph = *ai->baseGraph;
|
||||
graph.connectHeroes(ai);
|
||||
|
||||
visualKey = std::to_string(ai->playerID) + ":" + targetHero->getNameTranslated();
|
||||
pathNodes.clear();
|
||||
|
||||
GraphNodeComparer cmp(pathNodes);
|
||||
GraphPathNode::TFibHeap pq(cmp);
|
||||
|
||||
pathNodes[targetHero->visitablePos()][GrapthPathNodeType::NORMAL].cost = 0;
|
||||
pq.emplace(GraphPathNodePointer(targetHero->visitablePos(), GrapthPathNodeType::NORMAL));
|
||||
|
||||
while(!pq.empty())
|
||||
{
|
||||
GraphPathNodePointer pos = pq.top();
|
||||
pq.pop();
|
||||
|
||||
auto & node = getNode(pos);
|
||||
|
||||
node.isInQueue = false;
|
||||
|
||||
graph.iterateConnections(pos.coord, [&](int3 target, ObjectLink o)
|
||||
{
|
||||
auto targetNodeType = o.danger ? GrapthPathNodeType::BATTLE : pos.nodeType;
|
||||
auto targetPointer = GraphPathNodePointer(target, targetNodeType);
|
||||
auto & targetNode = getNode(targetPointer);
|
||||
|
||||
if(targetNode.tryUpdate(pos, node, o))
|
||||
{
|
||||
if(graph.getNode(target).objTypeID == Obj::HERO)
|
||||
return;
|
||||
|
||||
if(targetNode.isInQueue)
|
||||
{
|
||||
pq.increase(targetNode.handle);
|
||||
}
|
||||
else
|
||||
{
|
||||
targetNode.handle = pq.emplace(targetPointer);
|
||||
targetNode.isInQueue = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void GraphPaths::dumpToLog() const
|
||||
{
|
||||
logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
|
||||
{
|
||||
for(auto & tile : pathNodes)
|
||||
{
|
||||
for(auto & node : tile.second)
|
||||
{
|
||||
if(!node.previous.valid())
|
||||
continue;
|
||||
|
||||
if(NKAI_GRAPH_TRACE_LEVEL >= 2)
|
||||
{
|
||||
logAi->trace(
|
||||
"%s -> %s: %f !%d",
|
||||
node.previous.coord.toString(),
|
||||
tile.first.toString(),
|
||||
node.cost,
|
||||
node.danger);
|
||||
}
|
||||
|
||||
logBuilder.addLine(node.previous.coord, tile.first);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bool GraphPathNode::tryUpdate(const GraphPathNodePointer & pos, const GraphPathNode & prev, const ObjectLink & link)
|
||||
{
|
||||
auto newCost = prev.cost + link.cost;
|
||||
|
||||
if(newCost < cost)
|
||||
{
|
||||
if(nodeType < pos.nodeType)
|
||||
{
|
||||
logAi->error("Linking error");
|
||||
}
|
||||
|
||||
previous = pos;
|
||||
danger = prev.danger + link.danger;
|
||||
cost = newCost;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void GraphPaths::addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
|
||||
{
|
||||
auto nodes = pathNodes.find(tile);
|
||||
|
||||
if(nodes == pathNodes.end())
|
||||
return;
|
||||
|
||||
for(auto & node : nodes->second)
|
||||
{
|
||||
if(!node.reachable())
|
||||
continue;
|
||||
|
||||
std::vector<int3> tilesToPass;
|
||||
|
||||
uint64_t danger = node.danger;
|
||||
float cost = node.cost;
|
||||
bool allowBattle = false;
|
||||
|
||||
auto current = GraphPathNodePointer(nodes->first, node.nodeType);
|
||||
|
||||
while(true)
|
||||
{
|
||||
auto currentTile = pathNodes.find(current.coord);
|
||||
|
||||
if(currentTile == pathNodes.end())
|
||||
break;
|
||||
|
||||
auto currentNode = currentTile->second[current.nodeType];
|
||||
|
||||
if(!currentNode.previous.valid())
|
||||
break;
|
||||
|
||||
allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
|
||||
vstd::amax(danger, currentNode.danger);
|
||||
vstd::amax(cost, currentNode.cost);
|
||||
|
||||
tilesToPass.push_back(current.coord);
|
||||
|
||||
if(currentNode.cost < 2.0f)
|
||||
break;
|
||||
|
||||
current = currentNode.previous;
|
||||
}
|
||||
|
||||
if(tilesToPass.empty())
|
||||
continue;
|
||||
|
||||
auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back());
|
||||
|
||||
for(auto & path : entryPaths)
|
||||
{
|
||||
if(path.targetHero != hero)
|
||||
continue;
|
||||
|
||||
for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
|
||||
{
|
||||
AIPathNodeInfo n;
|
||||
|
||||
n.coord = *graphTile;
|
||||
n.cost = cost;
|
||||
n.turns = static_cast<ui8>(cost) + 1; // just in case lets select worst scenario
|
||||
n.danger = danger;
|
||||
n.targetHero = hero;
|
||||
n.parentIndex = 0;
|
||||
|
||||
for(auto & node : path.nodes)
|
||||
{
|
||||
node.parentIndex++;
|
||||
}
|
||||
|
||||
path.nodes.insert(path.nodes.begin(), n);
|
||||
}
|
||||
|
||||
path.armyLoss += ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
|
||||
path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
|
||||
path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
|
||||
|
||||
paths.push_back(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
170
AI/Nullkiller/Pathfinding/ObjectGraph.h
Normal file
170
AI/Nullkiller/Pathfinding/ObjectGraph.h
Normal file
@ -0,0 +1,170 @@
|
||||
/*
|
||||
* ObjectGraph.h, part of VCMI engine
|
||||
*
|
||||
* Authors: listed in file AUTHORS in main folder
|
||||
*
|
||||
* License: GNU General Public License v2.0 or later
|
||||
* Full text of license available in license.txt file, in main folder
|
||||
*
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "AINodeStorage.h"
|
||||
#include "../AIUtility.h"
|
||||
|
||||
namespace NKAI
|
||||
{
|
||||
|
||||
class Nullkiller;
|
||||
|
||||
struct ObjectLink
|
||||
{
|
||||
float cost = 100000; // some big number
|
||||
uint64_t danger = 0;
|
||||
|
||||
bool update(float newCost, uint64_t newDanger)
|
||||
{
|
||||
if(cost > newCost)
|
||||
{
|
||||
cost = newCost;
|
||||
danger = newDanger;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
struct ObjectNode
|
||||
{
|
||||
ObjectInstanceID objID;
|
||||
MapObjectID objTypeID;
|
||||
bool objectExists;
|
||||
std::unordered_map<int3, ObjectLink> connections;
|
||||
|
||||
void init(const CGObjectInstance * obj)
|
||||
{
|
||||
objectExists = true;
|
||||
objID = obj->id;
|
||||
objTypeID = obj->ID;
|
||||
}
|
||||
};
|
||||
|
||||
class ObjectGraph
|
||||
{
|
||||
std::unordered_map<int3, ObjectNode> nodes;
|
||||
|
||||
public:
|
||||
void updateGraph(const Nullkiller * ai);
|
||||
void addObject(const CGObjectInstance * obj);
|
||||
void connectHeroes(const Nullkiller * ai);
|
||||
void removeObject(const CGObjectInstance * obj);
|
||||
void dumpToLog(std::string visualKey) const;
|
||||
|
||||
template<typename Func>
|
||||
void iterateConnections(const int3 & pos, Func fn)
|
||||
{
|
||||
for(auto & connection : nodes.at(pos).connections)
|
||||
{
|
||||
fn(connection.first, connection.second);
|
||||
}
|
||||
}
|
||||
|
||||
const ObjectNode & getNode(int3 tile) const
|
||||
{
|
||||
return nodes.at(tile);
|
||||
}
|
||||
|
||||
bool tryAddConnection(const int3 & from, const int3 & to, float cost, uint64_t danger);
|
||||
};
|
||||
|
||||
struct GraphPathNode;
|
||||
|
||||
enum GrapthPathNodeType
|
||||
{
|
||||
NORMAL,
|
||||
|
||||
BATTLE,
|
||||
|
||||
LAST
|
||||
};
|
||||
|
||||
struct GraphPathNodePointer
|
||||
{
|
||||
int3 coord = int3(-1);
|
||||
GrapthPathNodeType nodeType = GrapthPathNodeType::NORMAL;
|
||||
|
||||
GraphPathNodePointer() = default;
|
||||
|
||||
GraphPathNodePointer(int3 coord, GrapthPathNodeType type)
|
||||
:coord(coord), nodeType(type)
|
||||
{ }
|
||||
|
||||
bool valid() const
|
||||
{
|
||||
return coord.valid();
|
||||
}
|
||||
};
|
||||
|
||||
typedef std::unordered_map<int3, GraphPathNode[GrapthPathNodeType::LAST]> GraphNodeStorage;
|
||||
|
||||
class GraphNodeComparer
|
||||
{
|
||||
const GraphNodeStorage & pathNodes;
|
||||
|
||||
public:
|
||||
GraphNodeComparer(const GraphNodeStorage & pathNodes)
|
||||
:pathNodes(pathNodes)
|
||||
{
|
||||
}
|
||||
|
||||
bool operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const;
|
||||
};
|
||||
|
||||
struct GraphPathNode
|
||||
{
|
||||
const float BAD_COST = 100000;
|
||||
|
||||
GrapthPathNodeType nodeType = GrapthPathNodeType::NORMAL;
|
||||
GraphPathNodePointer previous;
|
||||
float cost = BAD_COST;
|
||||
uint64_t danger = 0;
|
||||
|
||||
using TFibHeap = boost::heap::fibonacci_heap<GraphPathNodePointer, boost::heap::compare<GraphNodeComparer>>;
|
||||
|
||||
TFibHeap::handle_type handle;
|
||||
bool isInQueue = false;
|
||||
|
||||
bool reachable() const
|
||||
{
|
||||
return cost < BAD_COST;
|
||||
}
|
||||
|
||||
bool tryUpdate(const GraphPathNodePointer & pos, const GraphPathNode & prev, const ObjectLink & link);
|
||||
};
|
||||
|
||||
class GraphPaths
|
||||
{
|
||||
ObjectGraph graph;
|
||||
GraphNodeStorage pathNodes;
|
||||
std::string visualKey;
|
||||
|
||||
public:
|
||||
void calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai);
|
||||
void addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const;
|
||||
void dumpToLog() const;
|
||||
|
||||
private:
|
||||
GraphPathNode & getNode(const GraphPathNodePointer & pos)
|
||||
{
|
||||
auto & node = pathNodes[pos.coord][pos.nodeType];
|
||||
|
||||
node.nodeType = pos.nodeType;
|
||||
|
||||
return node;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
@ -13,6 +13,7 @@
|
||||
#include "../Actions/QuestAction.h"
|
||||
#include "../../Goals/Invalid.h"
|
||||
#include "AIPreviousNodeRule.h"
|
||||
#include "../../../../lib/pathfinder/PathfinderOptions.h"
|
||||
|
||||
namespace NKAI
|
||||
{
|
||||
@ -20,8 +21,9 @@ namespace AIPathfinding
|
||||
{
|
||||
AIMovementAfterDestinationRule::AIMovementAfterDestinationRule(
|
||||
CPlayerSpecificInfoCallback * cb,
|
||||
std::shared_ptr<AINodeStorage> nodeStorage)
|
||||
:cb(cb), nodeStorage(nodeStorage)
|
||||
std::shared_ptr<AINodeStorage> nodeStorage,
|
||||
bool allowBypassObjects)
|
||||
:cb(cb), nodeStorage(nodeStorage), allowBypassObjects(allowBypassObjects)
|
||||
{
|
||||
}
|
||||
|
||||
@ -46,6 +48,9 @@ namespace AIPathfinding
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if(!allowBypassObjects)
|
||||
return;
|
||||
|
||||
#if NKAI_PATHFINDER_TRACE_LEVEL >= 2
|
||||
logAi->trace(
|
||||
|
@ -25,9 +25,13 @@ namespace AIPathfinding
|
||||
private:
|
||||
CPlayerSpecificInfoCallback * cb;
|
||||
std::shared_ptr<AINodeStorage> nodeStorage;
|
||||
bool allowBypassObjects;
|
||||
|
||||
public:
|
||||
AIMovementAfterDestinationRule(CPlayerSpecificInfoCallback * cb, std::shared_ptr<AINodeStorage> nodeStorage);
|
||||
AIMovementAfterDestinationRule(
|
||||
CPlayerSpecificInfoCallback * cb,
|
||||
std::shared_ptr<AINodeStorage> nodeStorage,
|
||||
bool allowBypassObjects);
|
||||
|
||||
virtual void process(
|
||||
const PathNodeInfo & source,
|
||||
|
@ -14,8 +14,10 @@ namespace NKAI
|
||||
{
|
||||
namespace AIPathfinding
|
||||
{
|
||||
AIMovementToDestinationRule::AIMovementToDestinationRule(std::shared_ptr<AINodeStorage> nodeStorage)
|
||||
: nodeStorage(nodeStorage)
|
||||
AIMovementToDestinationRule::AIMovementToDestinationRule(
|
||||
std::shared_ptr<AINodeStorage> nodeStorage,
|
||||
bool allowBypassObjects)
|
||||
: nodeStorage(nodeStorage), allowBypassObjects(allowBypassObjects)
|
||||
{
|
||||
}
|
||||
|
||||
@ -37,15 +39,30 @@ namespace AIPathfinding
|
||||
return;
|
||||
}
|
||||
|
||||
if(blocker == BlockingReason::SOURCE_GUARDED && nodeStorage->getAINode(source.node)->actor->allowBattle)
|
||||
if(blocker == BlockingReason::SOURCE_GUARDED)
|
||||
{
|
||||
auto actor = nodeStorage->getAINode(source.node)->actor;
|
||||
|
||||
if(!allowBypassObjects)
|
||||
{
|
||||
if (source.node->getCost() < 0.0001f)
|
||||
return;
|
||||
|
||||
// when actor represents moster graph node, we need to let him escape monster
|
||||
if(!destination.guarded && cb->getGuardingCreaturePosition(source.coord) == actor->initialPosition)
|
||||
return;
|
||||
}
|
||||
|
||||
if(actor->allowBattle)
|
||||
{
|
||||
#if NKAI_PATHFINDER_TRACE_LEVEL >= 1
|
||||
logAi->trace(
|
||||
"Bypass src guard while moving from %s to %s",
|
||||
source.coord.toString(),
|
||||
destination.coord.toString());
|
||||
logAi->trace(
|
||||
"Bypass src guard while moving from %s to %s",
|
||||
source.coord.toString(),
|
||||
destination.coord.toString());
|
||||
#endif
|
||||
return;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
destination.blocked = true;
|
||||
|
@ -24,9 +24,10 @@ namespace AIPathfinding
|
||||
{
|
||||
private:
|
||||
std::shared_ptr<AINodeStorage> nodeStorage;
|
||||
bool allowBypassObjects;
|
||||
|
||||
public:
|
||||
AIMovementToDestinationRule(std::shared_ptr<AINodeStorage> nodeStorage);
|
||||
AIMovementToDestinationRule(std::shared_ptr<AINodeStorage> nodeStorage, bool allowBypassObjects);
|
||||
|
||||
virtual void process(
|
||||
const PathNodeInfo & source,
|
||||
|
14
Global.h
14
Global.h
@ -512,6 +512,20 @@ namespace vstd
|
||||
}
|
||||
}
|
||||
|
||||
//works for std::unordered_map, maybe something else
|
||||
template<typename Key, typename Val, typename Predicate>
|
||||
void erase_if(std::unordered_map<Key, Val> & container, Predicate pred)
|
||||
{
|
||||
auto itr = container.begin();
|
||||
auto endItr = container.end();
|
||||
while(itr != endItr)
|
||||
{
|
||||
auto tmpItr = itr++;
|
||||
if(pred(*tmpItr))
|
||||
container.erase(tmpItr);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename InputRange, typename OutputIterator, typename Predicate>
|
||||
OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
|
||||
{
|
||||
|
@ -37,6 +37,7 @@
|
||||
#include "../lib/modding/ModUtility.h"
|
||||
#include "../lib/CHeroHandler.h"
|
||||
#include "../lib/VCMIDirs.h"
|
||||
#include "../lib/logging/VisualLogger.h"
|
||||
#include "CMT.h"
|
||||
|
||||
#ifdef SCRIPTING_ENABLED
|
||||
@ -427,6 +428,14 @@ void ClientCommandManager::handleCrashCommand()
|
||||
//disaster!
|
||||
}
|
||||
|
||||
void ClientCommandManager::handleVsLog(std::istringstream & singleWordBuffer)
|
||||
{
|
||||
std::string key;
|
||||
singleWordBuffer >> key;
|
||||
|
||||
logVisual->setKey(key);
|
||||
}
|
||||
|
||||
void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType)
|
||||
{
|
||||
switch(messageType)
|
||||
@ -546,6 +555,9 @@ void ClientCommandManager::processCommand(const std::string & message, bool call
|
||||
else if(commandName == "crash")
|
||||
handleCrashCommand();
|
||||
|
||||
else if(commandName == "vslog")
|
||||
handleVsLog(singleWordBuffer);
|
||||
|
||||
else
|
||||
{
|
||||
if (!commandName.empty() && !vstd::iswithin(commandName[0], 0, ' ')) // filter-out debugger/IDE noise
|
||||
|
@ -81,6 +81,9 @@ class ClientCommandManager //take mantis #2292 issue about account if thinking a
|
||||
// Crashes the game forcing an exception
|
||||
void handleCrashCommand();
|
||||
|
||||
// shows object graph
|
||||
void handleVsLog(std::istringstream & singleWordBuffer);
|
||||
|
||||
// Prints in Chat the given message
|
||||
void printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType = ELogLevel::NOT_SET);
|
||||
void giveTurn(const PlayerColor &color);
|
||||
|
@ -31,6 +31,7 @@
|
||||
|
||||
#include "../../lib/CConfigHandler.h"
|
||||
#include "../../lib/mapObjects/CGHeroInstance.h"
|
||||
#include "../../lib/logging/VisualLogger.h"
|
||||
|
||||
BasicMapView::~BasicMapView() = default;
|
||||
|
||||
@ -57,11 +58,46 @@ BasicMapView::BasicMapView(const Point & offset, const Point & dimensions)
|
||||
pos.h = dimensions.y;
|
||||
}
|
||||
|
||||
class VisualLoggerRenderer : public ILogVisualizer
|
||||
{
|
||||
private:
|
||||
Canvas & target;
|
||||
std::shared_ptr<MapViewModel> model;
|
||||
|
||||
public:
|
||||
VisualLoggerRenderer(Canvas & target, std::shared_ptr<MapViewModel> model) : target(target), model(model)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void drawLine(int3 start, int3 end) override
|
||||
{
|
||||
auto level = model->getLevel();
|
||||
|
||||
if(start.z != level || end.z != level)
|
||||
return;
|
||||
|
||||
auto pStart = model->getTargetTileArea(start).topLeft();
|
||||
auto pEnd = model->getTargetTileArea(end).topLeft();
|
||||
auto viewPort = target.getRenderArea();
|
||||
|
||||
pStart.x += 3;
|
||||
pEnd.x -= 3;
|
||||
|
||||
if(viewPort.isInside(pStart) && viewPort.isInside(pEnd))
|
||||
{
|
||||
target.drawLine(pStart, pEnd, ColorRGBA(255, 255, 0), ColorRGBA(255, 0, 0));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void BasicMapView::render(Canvas & target, bool fullUpdate)
|
||||
{
|
||||
Canvas targetClipped(target, pos);
|
||||
tilesCache->update(controller->getContext());
|
||||
tilesCache->render(controller->getContext(), targetClipped, fullUpdate);
|
||||
|
||||
VisualLoggerRenderer r(target, model);
|
||||
logVisual->visualize(r);
|
||||
}
|
||||
|
||||
void BasicMapView::tick(uint32_t msPassed)
|
||||
|
@ -76,6 +76,7 @@ set(lib_SRCS
|
||||
|
||||
logging/CBasicLogConfigurator.cpp
|
||||
logging/CLogger.cpp
|
||||
logging/VisualLogger.cpp
|
||||
|
||||
mapObjectConstructors/AObjectTypeHandler.cpp
|
||||
mapObjectConstructors/CBankInstanceConstructor.cpp
|
||||
@ -424,6 +425,7 @@ set(lib_HEADERS
|
||||
|
||||
logging/CBasicLogConfigurator.h
|
||||
logging/CLogger.h
|
||||
logging/VisualLogger.h
|
||||
|
||||
mapObjectConstructors/AObjectTypeHandler.h
|
||||
mapObjectConstructors/CBankInstanceConstructor.h
|
||||
|
44
lib/logging/VisualLogger.cpp
Normal file
44
lib/logging/VisualLogger.cpp
Normal file
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* CLogger.cpp, part of VCMI engine
|
||||
*
|
||||
* Authors: listed in file AUTHORS in main folder
|
||||
*
|
||||
* License: GNU General Public License v2.0 or later
|
||||
* Full text of license available in license.txt file, in main folder
|
||||
*
|
||||
*/
|
||||
#include "StdInc.h"
|
||||
#include "VisualLogger.h"
|
||||
|
||||
VCMI_LIB_NAMESPACE_BEGIN
|
||||
|
||||
DLL_LINKAGE VisualLogger * logVisual = new VisualLogger();
|
||||
|
||||
|
||||
void VisualLogger::updateWithLock(std::string channel, std::function<void(IVisualLogBuilder & logBuilder)> func)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
|
||||
mapLines[channel].clear();
|
||||
|
||||
VisualLogBuilder builder(mapLines[channel]);
|
||||
|
||||
func(builder);
|
||||
}
|
||||
|
||||
void VisualLogger::visualize(ILogVisualizer & visulizer)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
|
||||
for(auto line : mapLines[keyToShow])
|
||||
{
|
||||
visulizer.drawLine(line.start, line.end);
|
||||
}
|
||||
}
|
||||
|
||||
void VisualLogger::setKey(std::string key)
|
||||
{
|
||||
keyToShow = key;
|
||||
}
|
||||
|
||||
VCMI_LIB_NAMESPACE_END
|
75
lib/logging/VisualLogger.h
Normal file
75
lib/logging/VisualLogger.h
Normal file
@ -0,0 +1,75 @@
|
||||
/*
|
||||
* VisualLogger.h, part of VCMI engine
|
||||
*
|
||||
* Authors: listed in file AUTHORS in main folder
|
||||
*
|
||||
* License: GNU General Public License v2.0 or later
|
||||
* Full text of license available in license.txt file, in main folder
|
||||
*
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "../int3.h"
|
||||
#include "../constants/EntityIdentifiers.h"
|
||||
|
||||
VCMI_LIB_NAMESPACE_BEGIN
|
||||
|
||||
class ILogVisualizer
|
||||
{
|
||||
public:
|
||||
virtual void drawLine(int3 start, int3 end) = 0;
|
||||
};
|
||||
|
||||
class IVisualLogBuilder
|
||||
{
|
||||
public:
|
||||
virtual void addLine(int3 start, int3 end) = 0;
|
||||
};
|
||||
|
||||
/// The logger is used to show screen overlay
|
||||
class DLL_LINKAGE VisualLogger
|
||||
{
|
||||
private:
|
||||
struct MapLine
|
||||
{
|
||||
int3 start;
|
||||
int3 end;
|
||||
|
||||
MapLine(int3 start, int3 end)
|
||||
:start(start), end(end)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class VisualLogBuilder : public IVisualLogBuilder
|
||||
{
|
||||
private:
|
||||
std::vector<MapLine> & mapLines;
|
||||
|
||||
public:
|
||||
VisualLogBuilder(std::vector<MapLine> & mapLines)
|
||||
:mapLines(mapLines)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void addLine(int3 start, int3 end) override
|
||||
{
|
||||
mapLines.push_back(MapLine(start, end));
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
std::map<std::string, std::vector<MapLine>> mapLines;
|
||||
std::mutex mutex;
|
||||
std::string keyToShow;
|
||||
|
||||
public:
|
||||
|
||||
void updateWithLock(std::string channel, std::function<void(IVisualLogBuilder & logBuilder)> func);
|
||||
void visualize(ILogVisualizer & visulizer);
|
||||
void setKey(std::string key);
|
||||
};
|
||||
|
||||
extern DLL_LINKAGE VisualLogger * logVisual;
|
||||
|
||||
VCMI_LIB_NAMESPACE_END
|
Loading…
Reference in New Issue
Block a user