1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-11-27 22:49:25 +02:00

Nullkiller: better tracing and hero locking for hero chain

This commit is contained in:
Andrii Danylchenko
2021-05-15 21:57:27 +03:00
committed by Andrii Danylchenko
parent ffa626dc2f
commit 286d084445
7 changed files with 135 additions and 68 deletions

View File

@@ -22,19 +22,27 @@ extern FuzzyHelper * fh;
using namespace Goals; using namespace Goals;
std::string CaptureObjectsBehavior::toString() const { std::string CaptureObjectsBehavior::toString() const
{
return "Capture objects"; return "Capture objects";
} }
Goals::TGoalVec CaptureObjectsBehavior::getTasks() { Goals::TGoalVec CaptureObjectsBehavior::getTasks()
{
Goals::TGoalVec tasks; Goals::TGoalVec tasks;
auto captureObjects = [&](std::vector<const CGObjectInstance*> objs) -> void { auto captureObjects = [&](const std::vector<const CGObjectInstance*> & objs) -> void{
if (objs.empty()) { if(objs.empty())
{
return; return;
} }
for (auto objToVisit : objs) { for(auto objToVisit : objs)
{
#ifdef VCMI_TRACE_PATHFINDER
logAi->trace("Checking object %s, %s", objToVisit->getObjectName(), objToVisit->visitablePos().toString());
#endif
if(!shouldVisitObject(objToVisit)) if(!shouldVisitObject(objToVisit))
continue; continue;
@@ -42,27 +50,36 @@ Goals::TGoalVec CaptureObjectsBehavior::getTasks() {
auto paths = ai->ah->getPathsToTile(pos); auto paths = ai->ah->getPathsToTile(pos);
std::vector<std::shared_ptr<ExecuteHeroChain>> waysToVisitObj; std::vector<std::shared_ptr<ExecuteHeroChain>> waysToVisitObj;
std::shared_ptr<ExecuteHeroChain> closestWay; std::shared_ptr<ExecuteHeroChain> closestWay;
#ifdef VCMI_TRACE_PATHFINDER
logAi->trace("Found %" PRId32 "paths", paths.size());
#endif
for(auto & path : paths) for(auto & path : paths)
{ {
#ifdef VCMI_TRACE_PATHFINDER #ifdef VCMI_TRACE_PATHFINDER
std::stringstream str; logAi->trace("Path found %s", path.toString());
str << "Path found ";
for(auto node : path.nodes)
str << node.targetHero->name << "->" << node.coord.toString() << "; ";
logAi->trace(str.str());
#endif #endif
if(!shouldVisit(path.targetHero, objToVisit)) if(!shouldVisit(path.targetHero, objToVisit))
continue; continue;
auto hero = path.targetHero; auto hero = path.targetHero;
auto danger = path.getTotalDanger(hero); auto danger = path.getTotalDanger(hero);
auto isSafe = isSafeToVisit(hero, path.heroArmy, danger);
#ifdef VCMI_TRACE_PATHFINDER
logAi->trace(
"It is %s to visit %s by %s with army %" PRId64 ", danger %" PRId64 " and army loss %" PRId64,
isSafe ? "safe" : "not safe",
objToVisit->instanceName,
hero->name,
path.getHeroStrength(),
danger,
path.armyLoss);
#endif
if(isSafeToVisit(hero, path.heroArmy, danger)) if(isSafe)
{ {
auto newWay = std::make_shared<ExecuteHeroChain>(path, objToVisit); auto newWay = std::make_shared<ExecuteHeroChain>(path, objToVisit);
@@ -72,26 +89,26 @@ Goals::TGoalVec CaptureObjectsBehavior::getTasks() {
closestWay = newWay; closestWay = newWay;
} }
} }
if(waysToVisitObj.empty()) if(waysToVisitObj.empty())
continue; continue;
for(auto way : waysToVisitObj) for(auto way : waysToVisitObj)
{ {
way->evaluationContext.closestWayRatio way->evaluationContext.closestWayRatio
= way->evaluationContext.movementCost / closestWay->evaluationContext.movementCost; = way->evaluationContext.movementCost / closestWay->evaluationContext.movementCost;
logAi->trace("Behavior %s found %s(%s), danger %d", toString(), way->name(), way->tile.toString(), way->evaluationContext.danger);
tasks.push_back(sptr(*way)); tasks.push_back(sptr(*way));
} }
} }
}; };
if (specificObjects) { if(specificObjects)
{
captureObjects(objectsToCapture); captureObjects(objectsToCapture);
} }
else { else
{
captureObjects(std::vector<const CGObjectInstance*>(ai->visitableObjs.begin(), ai->visitableObjs.end())); captureObjects(std::vector<const CGObjectInstance*>(ai->visitableObjs.begin(), ai->visitableObjs.end()));
} }
@@ -102,22 +119,26 @@ bool CaptureObjectsBehavior::shouldVisitObject(ObjectIdRef obj) const
{ {
const CGObjectInstance* objInstance = obj; const CGObjectInstance* objInstance = obj;
if (!objInstance || objectTypes.size() && !vstd::contains(objectTypes, objInstance->ID.num)) { if(!objInstance || objectTypes.size() && !vstd::contains(objectTypes, objInstance->ID.num))
{
return false; return false;
} }
if (!objInstance || objectSubTypes.size() && !vstd::contains(objectSubTypes, objInstance->subID)) { if(!objInstance || objectSubTypes.size() && !vstd::contains(objectSubTypes, objInstance->subID))
{
return false; return false;
} }
const int3 pos = objInstance->visitablePos(); const int3 pos = objInstance->visitablePos();
if (vstd::contains(ai->alreadyVisited, objInstance)) { if(vstd::contains(ai->alreadyVisited, objInstance))
{
return false; return false;
} }
auto playerRelations = cb->getPlayerRelations(ai->playerID, objInstance->tempOwner); auto playerRelations = cb->getPlayerRelations(ai->playerID, objInstance->tempOwner);
if (playerRelations != PlayerRelations::ENEMIES && !isWeeklyRevisitable(objInstance)) { if(playerRelations != PlayerRelations::ENEMIES && !isWeeklyRevisitable(objInstance))
{
return false; return false;
} }
@@ -126,7 +147,7 @@ bool CaptureObjectsBehavior::shouldVisitObject(ObjectIdRef obj) const
// -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
const CGObjectInstance * topObj = cb->getTopObj(obj->visitablePos()); const CGObjectInstance * topObj = cb->getTopObj(obj->visitablePos());
if (topObj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, topObj->tempOwner) != PlayerRelations::ENEMIES) if(topObj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, topObj->tempOwner) != PlayerRelations::ENEMIES)
return false; return false;
else else
return true; //all of the following is met return true; //all of the following is met

View File

@@ -49,11 +49,29 @@ Goals::TSubgoal Nullkiller::choseBestTask(Behavior & behavior)
return task; return task;
} }
void Nullkiller::resetAiState()
{
lockedHeroes.clear();
}
void Nullkiller::updateAiState()
{
auto activeHeroes = ai->getMyHeroes();
vstd::erase_if(activeHeroes, [&](const HeroPtr & hero) -> bool{
return vstd::contains(lockedHeroes, hero);
});
ai->ah->updatePaths(activeHeroes, true);
}
void Nullkiller::makeTurn() void Nullkiller::makeTurn()
{ {
resetAiState();
while(true) while(true)
{ {
ai->ah->updatePaths(ai->getMyHeroes(), true); updateAiState();
Goals::TGoalVec bestTasks = { Goals::TGoalVec bestTasks = {
choseBestTask(CaptureObjectsBehavior()), choseBestTask(CaptureObjectsBehavior()),

View File

@@ -9,14 +9,18 @@ class Nullkiller
private: private:
std::unique_ptr<PriorityEvaluator> priorityEvaluator; std::unique_ptr<PriorityEvaluator> priorityEvaluator;
HeroPtr activeHero; HeroPtr activeHero;
std::set<HeroPtr> lockedHeroes;
public: public:
Nullkiller(); Nullkiller();
void makeTurn(); void makeTurn();
bool isActive(const CGHeroInstance * hero) const { return activeHero.h == hero; } bool isActive(const CGHeroInstance * hero) const { return activeHero.h == hero; }
void setActive(const HeroPtr & hero) { activeHero = hero; } void setActive(const HeroPtr & hero) { activeHero = hero; }
void lockHero(const HeroPtr & hero) { lockedHeroes.insert(hero); }
private: private:
void resetAiState();
void updateAiState();
Goals::TSubgoal choseBestTask(Behavior & behavior); Goals::TSubgoal choseBestTask(Behavior & behavior);
Goals::TSubgoal choseBestTask(Goals::TGoalVec tasks); Goals::TSubgoal choseBestTask(Goals::TGoalVec tasks);
}; };

View File

@@ -26,15 +26,22 @@ using namespace Goals;
ExecuteHeroChain::ExecuteHeroChain(const AIPath & path, const CGObjectInstance * obj) ExecuteHeroChain::ExecuteHeroChain(const AIPath & path, const CGObjectInstance * obj)
:CGoal(Goals::EXECUTE_HERO_CHAIN), chainPath(path) :CGoal(Goals::EXECUTE_HERO_CHAIN), chainPath(path)
{ {
if(obj)
objid = obj->id.getNum();
evaluationContext.danger = path.getTotalDanger(hero); evaluationContext.danger = path.getTotalDanger(hero);
evaluationContext.movementCost = path.movementCost(); evaluationContext.movementCost = path.movementCost();
evaluationContext.armyLoss = path.armyLoss; evaluationContext.armyLoss = path.armyLoss;
evaluationContext.heroStrength = path.getHeroStrength(); evaluationContext.heroStrength = path.getHeroStrength();
hero = path.targetHero; hero = path.targetHero;
tile = path.firstTileToGet(); tile = path.targetTile();
if(obj)
{
objid = obj->id.getNum();
targetName = obj->getObjectName() + tile.toString();
}
else
{
targetName = "tile" + tile.toString();
}
} }
bool ExecuteHeroChain::operator==(const ExecuteHeroChain & other) const bool ExecuteHeroChain::operator==(const ExecuteHeroChain & other) const
@@ -49,18 +56,7 @@ TSubgoal ExecuteHeroChain::whatToDoToAchieve()
void ExecuteHeroChain::accept(VCAI * ai) void ExecuteHeroChain::accept(VCAI * ai)
{ {
logAi->debug("Executing hero chain towards %s", tile.toString()); logAi->debug("Executing hero chain towards %s. Path %s", targetName, chainPath.toString());
#ifdef VCMI_TRACE_PATHFINDER
std::stringstream str;
str << "Path ";
for(auto node : chainPath.nodes)
str << node.targetHero->name << "->" << node.coord.toString() << "; ";
logAi->trace(str.str());
#endif
std::set<int> blockedIndexes; std::set<int> blockedIndexes;
@@ -69,23 +65,25 @@ void ExecuteHeroChain::accept(VCAI * ai)
auto & node = chainPath.nodes[i]; auto & node = chainPath.nodes[i];
HeroPtr hero = node.targetHero; HeroPtr hero = node.targetHero;
auto vt = Goals::sptr(Goals::VisitTile(node.coord).sethero(hero));
if(vstd::contains(blockedIndexes, i)) if(vstd::contains(blockedIndexes, i))
{ {
blockedIndexes.insert(node.parentIndex); blockedIndexes.insert(node.parentIndex);
ai->setGoal(hero, vt); ai->nullkiller->lockHero(hero);
continue; continue;
} }
logAi->debug("Moving hero %s to %s", hero.name, node.coord.toString()); logAi->debug("Executing chain node %" PRId32 ". Moving hero %s to %s", i, hero.name, node.coord.toString());
try try
{ {
ai->nullkiller->setActive(hero); ai->nullkiller->setActive(hero);
vt->accept(ai);
Goals::VisitTile(node.coord).sethero(hero).accept(ai);
// no exception means we were not able to rich the tile
ai->nullkiller->lockHero(hero);
blockedIndexes.insert(node.parentIndex); blockedIndexes.insert(node.parentIndex);
} }
catch(goalFulfilledException) catch(goalFulfilledException)
@@ -102,7 +100,7 @@ void ExecuteHeroChain::accept(VCAI * ai)
std::string ExecuteHeroChain::name() const std::string ExecuteHeroChain::name() const
{ {
return "ExecuteHeroChain"; return "ExecuteHeroChain " + targetName;
} }
std::string ExecuteHeroChain::completeMessage() const std::string ExecuteHeroChain::completeMessage() const

View File

@@ -17,6 +17,7 @@ namespace Goals
{ {
private: private:
AIPath chainPath; AIPath chainPath;
std::string targetName;
public: public:
ExecuteHeroChain(const AIPath & path, const CGObjectInstance * obj = nullptr); ExecuteHeroChain(const AIPath & path, const CGObjectInstance * obj = nullptr);

View File

@@ -76,7 +76,7 @@ void AINodeStorage::clear()
{ {
actors.clear(); actors.clear();
heroChainPass = false; heroChainPass = false;
heroChainTurn = 0; heroChainTurn = 1;
} }
const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
@@ -184,7 +184,7 @@ void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInf
dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode); dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
} }
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace( logAi->trace(
"Commited %s -> %s, cost: %f, hero: %s, mask: %x, army: %i", "Commited %s -> %s, cost: %f, hero: %s, mask: %x, army: %i",
source.coord.toString(), source.coord.toString(),
@@ -310,7 +310,7 @@ void AINodeStorage::calculateHeroChain(
continue; continue;
} }
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace( logAi->trace(
"Thy exchange %s[%i] -> %s[%i] at %s", "Thy exchange %s[%i] -> %s[%i] at %s",
node->actor->toString(), node->actor->toString(),
@@ -331,7 +331,7 @@ void AINodeStorage::calculateHeroChain(
{ {
if(carrier->actor->canExchange(other->actor)) if(carrier->actor->canExchange(other->actor))
{ {
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace( logAi->trace(
"Exchange allowed %s[%i] -> %s[%i] at %s", "Exchange allowed %s[%i] -> %s[%i] at %s",
other->actor->toString(), other->actor->toString(),
@@ -341,15 +341,18 @@ void AINodeStorage::calculateHeroChain(
carrier->coord.toString()); carrier->coord.toString());
#endif #endif
bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains; if(other->actor->isMovable)
bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
if(hasLessMp && hasLessExperience)
{ {
#ifdef VCMI_TRACE_PATHFINDER_EX bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString()); bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
if(hasLessMp && hasLessExperience)
{
#if VCMI_TRACE_PATHFINDER >= 2
logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
#endif #endif
return; return;
}
} }
auto newActor = carrier->actor->exchange(other->actor); auto newActor = carrier->actor->exchange(other->actor);
@@ -369,7 +372,7 @@ void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
if(!chainNodeOptional) if(!chainNodeOptional)
{ {
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString()); logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
#endif #endif
continue; continue;
@@ -379,7 +382,7 @@ void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN) if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
{ {
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString()); logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
#endif #endif
continue; continue;
@@ -387,7 +390,7 @@ void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost) if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
{ {
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace( logAi->trace(
"Exchange at %s is is not effective enough. %f < %f", "Exchange at %s is is not effective enough. %f < %f",
exchangeNode->coord.toString(), exchangeNode->coord.toString(),
@@ -402,7 +405,7 @@ void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
exchangeNode->chainOther = other; exchangeNode->chainOther = other;
exchangeNode->armyLoss = chainInfo.armyLoss; exchangeNode->armyLoss = chainInfo.armyLoss;
#ifdef VCMI_TRACE_PATHFINDER_EX #if VCMI_TRACE_PATHFINDER >= 2
logAi->trace( logAi->trace(
"Chain accepted at %s %s -> %s, mask %x, cost %f, army %i", "Chain accepted at %s %s -> %s, mask %x, cost %f, army %i",
exchangeNode->coord.toString(), exchangeNode->coord.toString(),
@@ -785,6 +788,16 @@ int3 AIPath::firstTileToGet() const
return int3(-1, -1, -1); return int3(-1, -1, -1);
} }
int3 AIPath::targetTile() const
{
if(nodes.size())
{
return nodes.front().coord;
}
return int3(-1, -1, -1);
}
const AIPathNodeInfo & AIPath::firstNode() const const AIPathNodeInfo & AIPath::firstNode() const
{ {
return nodes.back(); return nodes.back();
@@ -822,4 +835,14 @@ uint64_t AIPath::getTotalDanger(HeroPtr hero) const
uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger; uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
return danger; return danger;
}
std::string AIPath::toString()
{
std::stringstream str;
for(auto node : nodes)
str << node.targetHero->name << "->" << node.coord.toString() << "; ";
return str.str();
} }

View File

@@ -10,8 +10,7 @@
#pragma once #pragma once
#define VCMI_TRACE_PATHFINDER #define VCMI_TRACE_PATHFINDER 1
#define NVCMI_TRACE_PATHFINDER_EX
#include "../../../lib/CPathfinder.h" #include "../../../lib/CPathfinder.h"
#include "../../../lib/mapObjects/CGHeroInstance.h" #include "../../../lib/mapObjects/CGHeroInstance.h"
@@ -61,12 +60,15 @@ struct AIPath
uint64_t getTotalDanger(HeroPtr hero) const; uint64_t getTotalDanger(HeroPtr hero) const;
int3 firstTileToGet() const; int3 firstTileToGet() const;
int3 targetTile() const;
const AIPathNodeInfo & firstNode() const; const AIPathNodeInfo & firstNode() const;
float movementCost() const; float movementCost() const;
uint64_t getHeroStrength() const; uint64_t getHeroStrength() const;
std::string toString();
}; };
struct ExchangeCandidate : public AIPathNode struct ExchangeCandidate : public AIPathNode