Nullkiller.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * Nullkiller.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "Nullkiller.h"
  12. #include "../AIGateway.h"
  13. #include "../Behaviors/CaptureObjectsBehavior.h"
  14. #include "../Behaviors/RecruitHeroBehavior.h"
  15. #include "../Behaviors/BuyArmyBehavior.h"
  16. #include "../Behaviors/StartupBehavior.h"
  17. #include "../Behaviors/DefenceBehavior.h"
  18. #include "../Behaviors/BuildingBehavior.h"
  19. #include "../Behaviors/GatherArmyBehavior.h"
  20. #include "../Behaviors/ClusterBehavior.h"
  21. #include "../Behaviors/StayAtTownBehavior.h"
  22. #include "../Goals/Invalid.h"
  23. #include "../Goals/Composition.h"
  24. namespace NKAI
  25. {
  26. using namespace Goals;
  27. // while we play vcmieagles graph can be shared
  28. std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
  29. Nullkiller::Nullkiller()
  30. :activeHero(nullptr), scanDepth(ScanDepth::MAIN_FULL), useHeroChain(true)
  31. {
  32. memory = std::make_unique<AIMemory>();
  33. settings = std::make_unique<Settings>();
  34. }
  35. void Nullkiller::init(std::shared_ptr<CCallback> cb, PlayerColor playerID)
  36. {
  37. this->cb = cb;
  38. this->playerID = playerID;
  39. priorityEvaluator.reset(new PriorityEvaluator(this));
  40. priorityEvaluators.reset(
  41. new SharedPool<PriorityEvaluator>(
  42. [&]()->std::unique_ptr<PriorityEvaluator>
  43. {
  44. return std::make_unique<PriorityEvaluator>(this);
  45. }));
  46. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  47. buildAnalyzer.reset(new BuildAnalyzer(this));
  48. objectClusterizer.reset(new ObjectClusterizer(this));
  49. dangerEvaluator.reset(new FuzzyHelper(this));
  50. pathfinder.reset(new AIPathfinder(cb.get(), this));
  51. armyManager.reset(new ArmyManager(cb.get(), this));
  52. heroManager.reset(new HeroManager(cb.get(), this));
  53. decomposer.reset(new DeepDecomposer());
  54. armyFormation.reset(new ArmyFormation(cb, this));
  55. }
  56. Goals::TTask Nullkiller::choseBestTask(Goals::TTaskVec & tasks) const
  57. {
  58. Goals::TTask bestTask = *vstd::maxElementByFun(tasks, [](Goals::TTask task) -> float{
  59. return task->priority;
  60. });
  61. return bestTask;
  62. }
  63. Goals::TTask Nullkiller::choseBestTask(Goals::TSubgoal behavior, int decompositionMaxDepth) const
  64. {
  65. boost::this_thread::interruption_point();
  66. logAi->debug("Checking behavior %s", behavior->toString());
  67. auto start = std::chrono::high_resolution_clock::now();
  68. Goals::TGoalVec elementarGoals = decomposer->decompose(behavior, decompositionMaxDepth);
  69. Goals::TTaskVec tasks;
  70. boost::this_thread::interruption_point();
  71. for(auto goal : elementarGoals)
  72. {
  73. Goals::TTask task = Goals::taskptr(*goal);
  74. if(task->priority <= 0)
  75. task->priority = priorityEvaluator->evaluate(goal);
  76. tasks.push_back(task);
  77. }
  78. if(tasks.empty())
  79. {
  80. logAi->debug("Behavior %s found no tasks. Time taken %ld", behavior->toString(), timeElapsed(start));
  81. return Goals::taskptr(Goals::Invalid());
  82. }
  83. auto task = choseBestTask(tasks);
  84. logAi->debug(
  85. "Behavior %s returns %s, priority %f. Time taken %ld",
  86. behavior->toString(),
  87. task->toString(),
  88. task->priority,
  89. timeElapsed(start));
  90. return task;
  91. }
  92. void Nullkiller::resetAiState()
  93. {
  94. std::unique_lock<std::mutex> lockGuard(aiStateMutex);
  95. lockedResources = TResources();
  96. scanDepth = ScanDepth::MAIN_FULL;
  97. playerID = ai->playerID;
  98. lockedHeroes.clear();
  99. dangerHitMap->reset();
  100. useHeroChain = true;
  101. if(!baseGraph)
  102. {
  103. baseGraph = std::make_unique<ObjectGraph>();
  104. baseGraph->updateGraph(this);
  105. }
  106. }
  107. void Nullkiller::updateAiState(int pass, bool fast)
  108. {
  109. boost::this_thread::interruption_point();
  110. std::unique_lock<std::mutex> lockGuard(aiStateMutex);
  111. auto start = std::chrono::high_resolution_clock::now();
  112. activeHero = nullptr;
  113. setTargetObject(-1);
  114. decomposer->reset();
  115. buildAnalyzer->update();
  116. if(!fast)
  117. {
  118. memory->removeInvisibleObjects(cb.get());
  119. dangerHitMap->updateHitMap();
  120. dangerHitMap->calculateTileOwners();
  121. boost::this_thread::interruption_point();
  122. heroManager->update();
  123. logAi->trace("Updating paths");
  124. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  125. for(auto hero : cb->getHeroesInfo())
  126. {
  127. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  128. continue;
  129. activeHeroes[hero] = heroManager->getHeroRole(hero);
  130. }
  131. PathfinderSettings cfg;
  132. cfg.useHeroChain = useHeroChain;
  133. cfg.allowBypassObjects = true;
  134. if(scanDepth == ScanDepth::SMALL)
  135. {
  136. cfg.mainTurnDistanceLimit = ai->nullkiller->settings->getMainHeroTurnDistanceLimit();
  137. }
  138. if(scanDepth != ScanDepth::ALL_FULL)
  139. {
  140. cfg.scoutTurnDistanceLimit = ai->nullkiller->settings->getScoutHeroTurnDistanceLimit();
  141. }
  142. boost::this_thread::interruption_point();
  143. pathfinder->updatePaths(activeHeroes, cfg);
  144. pathfinder->updateGraphs(activeHeroes);
  145. boost::this_thread::interruption_point();
  146. objectClusterizer->clusterize();
  147. }
  148. armyManager->update();
  149. logAi->debug("AI state updated in %ld", timeElapsed(start));
  150. }
  151. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  152. {
  153. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  154. }
  155. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  156. {
  157. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  158. {
  159. #if NKAI_TRACE_LEVEL >= 1
  160. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  161. #endif
  162. return true;
  163. }
  164. for(auto & node : path.nodes)
  165. {
  166. auto lockReason = getHeroLockedReason(node.targetHero);
  167. if(lockReason != HeroLockedReason::NOT_LOCKED)
  168. {
  169. #if NKAI_TRACE_LEVEL >= 1
  170. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  171. #endif
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  178. {
  179. auto found = lockedHeroes.find(hero);
  180. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  181. }
  182. void Nullkiller::makeTurn()
  183. {
  184. boost::lock_guard<boost::mutex> sharedStorageLock(AISharedStorage::locker);
  185. const int MAX_DEPTH = 10;
  186. const float FAST_TASK_MINIMAL_PRIORITY = 0.7f;
  187. resetAiState();
  188. for(int i = 1; i <= settings->getMaxPass(); i++)
  189. {
  190. updateAiState(i);
  191. Goals::TTask bestTask = taskptr(Goals::Invalid());
  192. for(;i <= settings->getMaxPass(); i++)
  193. {
  194. Goals::TTaskVec fastTasks = {
  195. choseBestTask(sptr(BuyArmyBehavior()), 1),
  196. choseBestTask(sptr(BuildingBehavior()), 1)
  197. };
  198. bestTask = choseBestTask(fastTasks);
  199. if(bestTask->priority >= FAST_TASK_MINIMAL_PRIORITY)
  200. {
  201. executeTask(bestTask);
  202. updateAiState(i, true);
  203. }
  204. else
  205. {
  206. break;
  207. }
  208. }
  209. Goals::TTaskVec bestTasks = {
  210. bestTask,
  211. choseBestTask(sptr(RecruitHeroBehavior()), 1),
  212. choseBestTask(sptr(CaptureObjectsBehavior()), 1),
  213. choseBestTask(sptr(ClusterBehavior()), MAX_DEPTH),
  214. choseBestTask(sptr(DefenceBehavior()), MAX_DEPTH),
  215. choseBestTask(sptr(GatherArmyBehavior()), MAX_DEPTH),
  216. choseBestTask(sptr(StayAtTownBehavior()), MAX_DEPTH)
  217. };
  218. if(cb->getDate(Date::DAY) == 1)
  219. {
  220. bestTasks.push_back(choseBestTask(sptr(StartupBehavior()), 1));
  221. }
  222. bestTask = choseBestTask(bestTasks);
  223. std::string taskDescription = bestTask->toString();
  224. HeroPtr hero = bestTask->getHero();
  225. HeroRole heroRole = HeroRole::MAIN;
  226. if(hero.validAndSet())
  227. heroRole = heroManager->getHeroRole(hero);
  228. if(heroRole != HeroRole::MAIN || bestTask->getHeroExchangeCount() <= 1)
  229. useHeroChain = false;
  230. // TODO: better to check turn distance here instead of priority
  231. if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
  232. && scanDepth == ScanDepth::MAIN_FULL)
  233. {
  234. useHeroChain = false;
  235. scanDepth = ScanDepth::SMALL;
  236. logAi->trace(
  237. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  238. taskDescription,
  239. bestTask->priority);
  240. }
  241. if(bestTask->priority < MIN_PRIORITY)
  242. {
  243. auto heroes = cb->getHeroesInfo();
  244. auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  245. {
  246. return h->movementPointsRemaining() > 100;
  247. });
  248. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  249. {
  250. logAi->trace(
  251. "Goal %s has too low priority %f so increasing scan depth to full.",
  252. taskDescription,
  253. bestTask->priority);
  254. scanDepth = ScanDepth::ALL_FULL;
  255. useHeroChain = false;
  256. continue;
  257. }
  258. logAi->trace("Goal %s has too low priority. It is not worth doing it. Ending turn.", taskDescription);
  259. return;
  260. }
  261. executeTask(bestTask);
  262. if(i == settings->getMaxPass())
  263. {
  264. logAi->warn("Goal %s exceeded maxpass. Terminating AI turn.", taskDescription);
  265. }
  266. }
  267. }
  268. void Nullkiller::executeTask(Goals::TTask task)
  269. {
  270. auto start = std::chrono::high_resolution_clock::now();
  271. std::string taskDescr = task->toString();
  272. boost::this_thread::interruption_point();
  273. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  274. try
  275. {
  276. task->accept(ai);
  277. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  278. }
  279. catch(goalFulfilledException &)
  280. {
  281. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  282. }
  283. catch(cannotFulfillGoalException & e)
  284. {
  285. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  286. logAi->error("The error message was: %s", e.what());
  287. #if NKAI_TRACE_LEVEL == 0
  288. throw; // will be recatched and AI turn ended
  289. #endif
  290. }
  291. }
  292. TResources Nullkiller::getFreeResources() const
  293. {
  294. auto freeRes = cb->getResourceAmount() - lockedResources;
  295. freeRes.positive();
  296. return freeRes;
  297. }
  298. void Nullkiller::lockResources(const TResources & res)
  299. {
  300. lockedResources += res;
  301. }
  302. }