Nullkiller.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 "../Behaviors/ExplorationBehavior.h"
  23. #include "../Goals/Invalid.h"
  24. #include "../Goals/Composition.h"
  25. #include "../../../lib/CPlayerState.h"
  26. #include "../../lib/StartInfo.h"
  27. namespace NKAI
  28. {
  29. using namespace Goals;
  30. // while we play vcmieagles graph can be shared
  31. std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
  32. Nullkiller::Nullkiller()
  33. :activeHero(nullptr), scanDepth(ScanDepth::MAIN_FULL), useHeroChain(true)
  34. {
  35. memory = std::make_unique<AIMemory>();
  36. settings = std::make_unique<Settings>();
  37. useObjectGraph = settings->isObjectGraphAllowed();
  38. openMap = settings->isOpenMap() || useObjectGraph;
  39. }
  40. bool canUseOpenMap(std::shared_ptr<CCallback> cb, PlayerColor playerID)
  41. {
  42. if(!cb->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  43. {
  44. return false;
  45. }
  46. const TeamState * team = cb->getPlayerTeam(playerID);
  47. auto hasHumanInTeam = vstd::contains_if(team->players, [cb](PlayerColor teamMateID) -> bool
  48. {
  49. return cb->getPlayerState(teamMateID)->isHuman();
  50. });
  51. if(hasHumanInTeam)
  52. {
  53. return false;
  54. }
  55. return cb->getStartInfo()->difficulty >= 3;
  56. }
  57. void Nullkiller::init(std::shared_ptr<CCallback> cb, AIGateway * gateway)
  58. {
  59. this->cb = cb;
  60. this->gateway = gateway;
  61. playerID = gateway->playerID;
  62. if(openMap && !canUseOpenMap(cb, playerID))
  63. {
  64. useObjectGraph = false;
  65. openMap = false;
  66. }
  67. baseGraph.reset();
  68. priorityEvaluator.reset(new PriorityEvaluator(this));
  69. priorityEvaluators.reset(
  70. new SharedPool<PriorityEvaluator>(
  71. [&]()->std::unique_ptr<PriorityEvaluator>
  72. {
  73. return std::make_unique<PriorityEvaluator>(this);
  74. }));
  75. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  76. buildAnalyzer.reset(new BuildAnalyzer(this));
  77. objectClusterizer.reset(new ObjectClusterizer(this));
  78. dangerEvaluator.reset(new FuzzyHelper(this));
  79. pathfinder.reset(new AIPathfinder(cb.get(), this));
  80. armyManager.reset(new ArmyManager(cb.get(), this));
  81. heroManager.reset(new HeroManager(cb.get(), this));
  82. decomposer.reset(new DeepDecomposer(this));
  83. armyFormation.reset(new ArmyFormation(cb, this));
  84. }
  85. TaskPlanItem::TaskPlanItem(TSubgoal task)
  86. :task(task), affectedObjects(task->asTask()->getAffectedObjects())
  87. {
  88. }
  89. Goals::TTaskVec TaskPlan::getTasks() const
  90. {
  91. Goals::TTaskVec result;
  92. for(auto & item : tasks)
  93. {
  94. result.push_back(taskptr(*item.task));
  95. }
  96. vstd::removeDuplicates(result);
  97. return result;
  98. }
  99. void TaskPlan::merge(TSubgoal task)
  100. {
  101. TGoalVec blockers;
  102. for(auto & item : tasks)
  103. {
  104. for(auto objid : item.affectedObjects)
  105. {
  106. if(task == item.task || task->asTask()->isObjectAffected(objid))
  107. {
  108. if(item.task->asTask()->priority >= task->asTask()->priority)
  109. return;
  110. blockers.push_back(item.task);
  111. break;
  112. }
  113. }
  114. }
  115. vstd::erase_if(tasks, [&](const TaskPlanItem & task)
  116. {
  117. return vstd::contains(blockers, task.task);
  118. });
  119. tasks.emplace_back(task);
  120. }
  121. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  122. {
  123. if(tasks.empty())
  124. {
  125. return taskptr(Invalid());
  126. }
  127. for(TSubgoal & task : tasks)
  128. {
  129. if(task->asTask()->priority <= 0)
  130. task->asTask()->priority = priorityEvaluator->evaluate(task);
  131. }
  132. auto bestTask = *vstd::maxElementByFun(tasks, [](Goals::TSubgoal task) -> float
  133. {
  134. return task->asTask()->priority;
  135. });
  136. return taskptr(*bestTask);
  137. }
  138. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks) const
  139. {
  140. TaskPlan taskPlan;
  141. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks](const tbb::blocked_range<size_t> & r)
  142. {
  143. auto evaluator = this->priorityEvaluators->acquire();
  144. for(size_t i = r.begin(); i != r.end(); i++)
  145. {
  146. auto task = tasks[i];
  147. if(task->asTask()->priority <= 0)
  148. task->asTask()->priority = evaluator->evaluate(task);
  149. }
  150. });
  151. std::sort(tasks.begin(), tasks.end(), [](TSubgoal g1, TSubgoal g2) -> bool
  152. {
  153. return g2->asTask()->priority < g1->asTask()->priority;
  154. });
  155. for(TSubgoal & task : tasks)
  156. {
  157. taskPlan.merge(task);
  158. }
  159. return taskPlan.getTasks();
  160. }
  161. void Nullkiller::decompose(Goals::TGoalVec & result, Goals::TSubgoal behavior, int decompositionMaxDepth) const
  162. {
  163. boost::this_thread::interruption_point();
  164. logAi->debug("Checking behavior %s", behavior->toString());
  165. auto start = std::chrono::high_resolution_clock::now();
  166. decomposer->decompose(result, behavior, decompositionMaxDepth);
  167. boost::this_thread::interruption_point();
  168. logAi->debug(
  169. "Behavior %s. Time taken %ld",
  170. behavior->toString(),
  171. timeElapsed(start));
  172. }
  173. void Nullkiller::resetAiState()
  174. {
  175. std::unique_lock lockGuard(aiStateMutex);
  176. lockedResources = TResources();
  177. scanDepth = ScanDepth::MAIN_FULL;
  178. lockedHeroes.clear();
  179. dangerHitMap->reset();
  180. useHeroChain = true;
  181. objectClusterizer->reset();
  182. if(!baseGraph && isObjectGraphAllowed())
  183. {
  184. baseGraph = std::make_unique<ObjectGraph>();
  185. baseGraph->updateGraph(this);
  186. }
  187. }
  188. void Nullkiller::updateAiState(int pass, bool fast)
  189. {
  190. boost::this_thread::interruption_point();
  191. std::unique_lock lockGuard(aiStateMutex);
  192. auto start = std::chrono::high_resolution_clock::now();
  193. activeHero = nullptr;
  194. setTargetObject(-1);
  195. decomposer->reset();
  196. buildAnalyzer->update();
  197. if(!fast)
  198. {
  199. memory->removeInvisibleObjects(cb.get());
  200. dangerHitMap->updateHitMap();
  201. dangerHitMap->calculateTileOwners();
  202. boost::this_thread::interruption_point();
  203. heroManager->update();
  204. logAi->trace("Updating paths");
  205. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  206. for(auto hero : cb->getHeroesInfo())
  207. {
  208. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  209. continue;
  210. activeHeroes[hero] = heroManager->getHeroRole(hero);
  211. }
  212. PathfinderSettings cfg;
  213. cfg.useHeroChain = useHeroChain;
  214. cfg.allowBypassObjects = true;
  215. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  216. {
  217. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  218. }
  219. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  220. {
  221. cfg.scoutTurnDistanceLimit =settings->getScoutHeroTurnDistanceLimit();
  222. }
  223. boost::this_thread::interruption_point();
  224. pathfinder->updatePaths(activeHeroes, cfg);
  225. if(isObjectGraphAllowed())
  226. {
  227. pathfinder->updateGraphs(
  228. activeHeroes,
  229. scanDepth == ScanDepth::SMALL ? 255 : 10,
  230. scanDepth == ScanDepth::ALL_FULL ? 255 : 3);
  231. }
  232. boost::this_thread::interruption_point();
  233. objectClusterizer->clusterize();
  234. }
  235. armyManager->update();
  236. logAi->debug("AI state updated in %ld", timeElapsed(start));
  237. }
  238. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  239. {
  240. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  241. }
  242. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  243. {
  244. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  245. {
  246. #if NKAI_TRACE_LEVEL >= 1
  247. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  248. #endif
  249. return true;
  250. }
  251. for(auto & node : path.nodes)
  252. {
  253. auto lockReason = getHeroLockedReason(node.targetHero);
  254. if(lockReason != HeroLockedReason::NOT_LOCKED)
  255. {
  256. #if NKAI_TRACE_LEVEL >= 1
  257. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  258. #endif
  259. return true;
  260. }
  261. }
  262. return false;
  263. }
  264. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  265. {
  266. auto found = lockedHeroes.find(hero);
  267. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  268. }
  269. void Nullkiller::makeTurn()
  270. {
  271. boost::lock_guard<boost::mutex> sharedStorageLock(AISharedStorage::locker);
  272. const int MAX_DEPTH = 10;
  273. const float FAST_TASK_MINIMAL_PRIORITY = 0.7f;
  274. resetAiState();
  275. Goals::TGoalVec bestTasks;
  276. for(int i = 1; i <= settings->getMaxPass() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  277. {
  278. auto start = std::chrono::high_resolution_clock::now();
  279. updateAiState(i);
  280. Goals::TTask bestTask = taskptr(Goals::Invalid());
  281. for(;i <= settings->getMaxPass(); i++)
  282. {
  283. bestTasks.clear();
  284. decompose(bestTasks, sptr(BuyArmyBehavior()), 1);
  285. decompose(bestTasks, sptr(BuildingBehavior()), 1);
  286. bestTask = choseBestTask(bestTasks);
  287. if(bestTask->priority >= FAST_TASK_MINIMAL_PRIORITY)
  288. {
  289. if(!executeTask(bestTask))
  290. return;
  291. updateAiState(i, true);
  292. }
  293. else
  294. {
  295. break;
  296. }
  297. }
  298. decompose(bestTasks, sptr(RecruitHeroBehavior()), 1);
  299. decompose(bestTasks, sptr(CaptureObjectsBehavior()), 1);
  300. decompose(bestTasks, sptr(ClusterBehavior()), MAX_DEPTH);
  301. decompose(bestTasks, sptr(DefenceBehavior()), MAX_DEPTH);
  302. decompose(bestTasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  303. decompose(bestTasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  304. if(!isOpenMap())
  305. decompose(bestTasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  306. if(cb->getDate(Date::DAY) == 1 || heroManager->getHeroRoles().empty())
  307. {
  308. decompose(bestTasks, sptr(StartupBehavior()), 1);
  309. }
  310. auto selectedTasks = buildPlan(bestTasks);
  311. logAi->debug("Decision madel in %ld", timeElapsed(start));
  312. if(selectedTasks.empty())
  313. {
  314. selectedTasks.push_back(taskptr(Goals::Invalid()));
  315. }
  316. bool hasAnySuccess = false;
  317. for(auto bestTask : selectedTasks)
  318. {
  319. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  320. return;
  321. if(!areAffectedObjectsPresent(bestTask))
  322. {
  323. logAi->debug("Affected object not found. Canceling task.");
  324. continue;
  325. }
  326. std::string taskDescription = bestTask->toString();
  327. HeroRole heroRole = getTaskRole(bestTask);
  328. if(heroRole != HeroRole::MAIN || bestTask->getHeroExchangeCount() <= 1)
  329. useHeroChain = false;
  330. // TODO: better to check turn distance here instead of priority
  331. if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
  332. && scanDepth == ScanDepth::MAIN_FULL)
  333. {
  334. useHeroChain = false;
  335. scanDepth = ScanDepth::SMALL;
  336. logAi->trace(
  337. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  338. taskDescription,
  339. bestTask->priority);
  340. }
  341. if(bestTask->priority < MIN_PRIORITY)
  342. {
  343. auto heroes = cb->getHeroesInfo();
  344. auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  345. {
  346. return h->movementPointsRemaining() > 100;
  347. });
  348. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  349. {
  350. logAi->trace(
  351. "Goal %s has too low priority %f so increasing scan depth to full.",
  352. taskDescription,
  353. bestTask->priority);
  354. scanDepth = ScanDepth::ALL_FULL;
  355. useHeroChain = false;
  356. hasAnySuccess = true;
  357. break;
  358. }
  359. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  360. continue;
  361. }
  362. if(!executeTask(bestTask))
  363. {
  364. if(hasAnySuccess)
  365. break;
  366. else
  367. return;
  368. }
  369. hasAnySuccess = true;
  370. }
  371. if(!hasAnySuccess)
  372. {
  373. logAi->trace("Nothing was done this turn. Ending turn.");
  374. return;
  375. }
  376. if(i == settings->getMaxPass())
  377. {
  378. logAi->warn("Maxpass exceeded. Terminating AI turn.");
  379. }
  380. }
  381. }
  382. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  383. {
  384. auto affectedObjs = task->getAffectedObjects();
  385. for(auto oid : affectedObjs)
  386. {
  387. if(!cb->getObj(oid, false))
  388. return false;
  389. }
  390. return true;
  391. }
  392. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  393. {
  394. HeroPtr hero = task->getHero();
  395. HeroRole heroRole = HeroRole::MAIN;
  396. if(hero.validAndSet())
  397. heroRole = heroManager->getHeroRole(hero);
  398. return heroRole;
  399. }
  400. bool Nullkiller::executeTask(Goals::TTask task)
  401. {
  402. auto start = std::chrono::high_resolution_clock::now();
  403. std::string taskDescr = task->toString();
  404. boost::this_thread::interruption_point();
  405. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  406. try
  407. {
  408. task->accept(gateway);
  409. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  410. }
  411. catch(goalFulfilledException &)
  412. {
  413. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  414. }
  415. catch(cannotFulfillGoalException & e)
  416. {
  417. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  418. logAi->error("The error message was: %s", e.what());
  419. return false;
  420. }
  421. return true;
  422. }
  423. TResources Nullkiller::getFreeResources() const
  424. {
  425. auto freeRes = cb->getResourceAmount() - lockedResources;
  426. freeRes.positive();
  427. return freeRes;
  428. }
  429. void Nullkiller::lockResources(const TResources & res)
  430. {
  431. lockedResources += res;
  432. }
  433. }