Nullkiller.cpp 8.2 KB

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