Nullkiller.cpp 8.8 KB

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