Nullkiller.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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 true;
  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. if (task->asTask()->priority <= 0)
  103. return;
  104. for(auto & item : tasks)
  105. {
  106. for(auto objid : item.affectedObjects)
  107. {
  108. if(task == item.task || task->asTask()->isObjectAffected(objid))
  109. {
  110. if(item.task->asTask()->priority >= task->asTask()->priority)
  111. return;
  112. blockers.push_back(item.task);
  113. break;
  114. }
  115. }
  116. }
  117. vstd::erase_if(tasks, [&](const TaskPlanItem & task)
  118. {
  119. return vstd::contains(blockers, task.task);
  120. });
  121. tasks.emplace_back(task);
  122. }
  123. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  124. {
  125. if(tasks.empty())
  126. {
  127. return taskptr(Invalid());
  128. }
  129. for(TSubgoal & task : tasks)
  130. {
  131. if(task->asTask()->priority <= 0)
  132. task->asTask()->priority = priorityEvaluator->evaluate(task);
  133. }
  134. auto bestTask = *vstd::maxElementByFun(tasks, [](Goals::TSubgoal task) -> float
  135. {
  136. return task->asTask()->priority;
  137. });
  138. return taskptr(*bestTask);
  139. }
  140. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks, int priorityTier) const
  141. {
  142. TaskPlan taskPlan;
  143. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks, priorityTier](const tbb::blocked_range<size_t> & r)
  144. {
  145. auto evaluator = this->priorityEvaluators->acquire();
  146. for(size_t i = r.begin(); i != r.end(); i++)
  147. {
  148. auto task = tasks[i];
  149. if(task->asTask()->priority <= 0)
  150. task->asTask()->priority = evaluator->evaluate(task, priorityTier);
  151. }
  152. });
  153. std::sort(tasks.begin(), tasks.end(), [](TSubgoal g1, TSubgoal g2) -> bool
  154. {
  155. return g2->asTask()->priority < g1->asTask()->priority;
  156. });
  157. for(TSubgoal & task : tasks)
  158. {
  159. taskPlan.merge(task);
  160. }
  161. return taskPlan.getTasks();
  162. }
  163. void Nullkiller::decompose(Goals::TGoalVec & result, Goals::TSubgoal behavior, int decompositionMaxDepth) const
  164. {
  165. boost::this_thread::interruption_point();
  166. logAi->debug("Checking behavior %s", behavior->toString());
  167. auto start = std::chrono::high_resolution_clock::now();
  168. decomposer->decompose(result, behavior, decompositionMaxDepth);
  169. boost::this_thread::interruption_point();
  170. logAi->debug(
  171. "Behavior %s. Time taken %ld",
  172. behavior->toString(),
  173. timeElapsed(start));
  174. }
  175. void Nullkiller::resetAiState()
  176. {
  177. std::unique_lock lockGuard(aiStateMutex);
  178. lockedResources = TResources();
  179. scanDepth = ScanDepth::MAIN_FULL;
  180. lockedHeroes.clear();
  181. dangerHitMap->reset();
  182. useHeroChain = true;
  183. objectClusterizer->reset();
  184. if(!baseGraph && isObjectGraphAllowed())
  185. {
  186. baseGraph = std::make_unique<ObjectGraph>();
  187. baseGraph->updateGraph(this);
  188. }
  189. }
  190. void Nullkiller::updateAiState(int pass, bool fast)
  191. {
  192. boost::this_thread::interruption_point();
  193. std::unique_lock lockGuard(aiStateMutex);
  194. auto start = std::chrono::high_resolution_clock::now();
  195. activeHero = nullptr;
  196. setTargetObject(-1);
  197. decomposer->reset();
  198. buildAnalyzer->update();
  199. if(!fast)
  200. {
  201. memory->removeInvisibleObjects(cb.get());
  202. dangerHitMap->updateHitMap();
  203. dangerHitMap->calculateTileOwners();
  204. boost::this_thread::interruption_point();
  205. heroManager->update();
  206. logAi->trace("Updating paths");
  207. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  208. for(auto hero : cb->getHeroesInfo())
  209. {
  210. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  211. continue;
  212. activeHeroes[hero] = heroManager->getHeroRole(hero);
  213. }
  214. PathfinderSettings cfg;
  215. cfg.useHeroChain = useHeroChain;
  216. cfg.allowBypassObjects = true;
  217. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  218. {
  219. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  220. }
  221. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  222. {
  223. cfg.scoutTurnDistanceLimit =settings->getScoutHeroTurnDistanceLimit();
  224. }
  225. boost::this_thread::interruption_point();
  226. pathfinder->updatePaths(activeHeroes, cfg);
  227. if(isObjectGraphAllowed())
  228. {
  229. pathfinder->updateGraphs(
  230. activeHeroes,
  231. scanDepth == ScanDepth::SMALL ? 255 : 10,
  232. scanDepth == ScanDepth::ALL_FULL ? 255 : 3);
  233. }
  234. boost::this_thread::interruption_point();
  235. objectClusterizer->clusterize();
  236. }
  237. armyManager->update();
  238. logAi->debug("AI state updated in %ld", timeElapsed(start));
  239. }
  240. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  241. {
  242. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  243. }
  244. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  245. {
  246. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  247. {
  248. #if NKAI_TRACE_LEVEL >= 1
  249. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  250. #endif
  251. return true;
  252. }
  253. for(auto & node : path.nodes)
  254. {
  255. auto lockReason = getHeroLockedReason(node.targetHero);
  256. if(lockReason != HeroLockedReason::NOT_LOCKED)
  257. {
  258. #if NKAI_TRACE_LEVEL >= 1
  259. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  260. #endif
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  267. {
  268. auto found = lockedHeroes.find(hero);
  269. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  270. }
  271. void Nullkiller::makeTurn()
  272. {
  273. boost::lock_guard<boost::mutex> sharedStorageLock(AISharedStorage::locker);
  274. const int MAX_DEPTH = 10;
  275. const float FAST_TASK_MINIMAL_PRIORITY = 0.7f;
  276. float totalHeroStrength = 0;
  277. int totalTownLevel = 0;
  278. for (auto heroInfo : cb->getHeroesInfo())
  279. {
  280. totalHeroStrength += heroInfo->getTotalStrength();
  281. }
  282. for (auto townInfo : cb->getTownsInfo())
  283. {
  284. totalTownLevel += townInfo->getTownLevel();
  285. }
  286. logAi->info("Resources: %s Strength: %f Townlevel: %d", cb->getResourceAmount().toString(), totalHeroStrength, totalTownLevel);
  287. resetAiState();
  288. Goals::TGoalVec bestTasks;
  289. for(int i = 1; i <= settings->getMaxPass() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  290. {
  291. auto start = std::chrono::high_resolution_clock::now();
  292. updateAiState(i);
  293. Goals::TTask bestTask = taskptr(Goals::Invalid());
  294. for(;i <= settings->getMaxPass(); i++)
  295. {
  296. bestTasks.clear();
  297. decompose(bestTasks, sptr(BuyArmyBehavior()), 1);
  298. decompose(bestTasks, sptr(BuildingBehavior()), 1);
  299. bestTask = choseBestTask(bestTasks);
  300. if(bestTask->priority >= FAST_TASK_MINIMAL_PRIORITY)
  301. {
  302. logAi->info("Performing task %s with prio: %d", bestTask->toString(), bestTask->priority);
  303. if(!executeTask(bestTask))
  304. return;
  305. updateAiState(i, true);
  306. }
  307. else
  308. {
  309. break;
  310. }
  311. }
  312. decompose(bestTasks, sptr(RecruitHeroBehavior()), 1);
  313. decompose(bestTasks, sptr(CaptureObjectsBehavior()), 1);
  314. decompose(bestTasks, sptr(ClusterBehavior()), MAX_DEPTH);
  315. decompose(bestTasks, sptr(DefenceBehavior()), MAX_DEPTH);
  316. decompose(bestTasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  317. decompose(bestTasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  318. if(!isOpenMap())
  319. decompose(bestTasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  320. auto selectedTasks = buildPlan(bestTasks, 0);
  321. if (selectedTasks.empty() && !settings->isUseFuzzy())
  322. selectedTasks = buildPlan(bestTasks, 1);
  323. if (selectedTasks.empty() && !settings->isUseFuzzy())
  324. selectedTasks = buildPlan(bestTasks, 2);
  325. std::sort(selectedTasks.begin(), selectedTasks.end(), [](const TTask& a, const TTask& b)
  326. {
  327. return a->priority > b->priority;
  328. });
  329. logAi->debug("Decision madel in %ld", timeElapsed(start));
  330. if(selectedTasks.empty())
  331. {
  332. selectedTasks.push_back(taskptr(Goals::Invalid()));
  333. }
  334. bool hasAnySuccess = false;
  335. for(auto bestTask : selectedTasks)
  336. {
  337. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  338. return;
  339. if(!areAffectedObjectsPresent(bestTask))
  340. {
  341. logAi->debug("Affected object not found. Canceling task.");
  342. continue;
  343. }
  344. std::string taskDescription = bestTask->toString();
  345. HeroRole heroRole = getTaskRole(bestTask);
  346. if(heroRole != HeroRole::MAIN || bestTask->getHeroExchangeCount() <= 1)
  347. useHeroChain = false;
  348. // TODO: better to check turn distance here instead of priority
  349. if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
  350. && scanDepth == ScanDepth::MAIN_FULL)
  351. {
  352. useHeroChain = false;
  353. scanDepth = ScanDepth::SMALL;
  354. logAi->trace(
  355. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  356. taskDescription,
  357. bestTask->priority);
  358. }
  359. if((settings->isUseFuzzy() && bestTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && bestTask->priority <= 0))
  360. {
  361. auto heroes = cb->getHeroesInfo();
  362. auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  363. {
  364. return h->movementPointsRemaining() > 100;
  365. });
  366. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  367. {
  368. logAi->trace(
  369. "Goal %s has too low priority %f so increasing scan depth to full.",
  370. taskDescription,
  371. bestTask->priority);
  372. scanDepth = ScanDepth::ALL_FULL;
  373. useHeroChain = false;
  374. hasAnySuccess = true;
  375. break;
  376. }
  377. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  378. continue;
  379. }
  380. logAi->info("Performing task %s with prio: %d", bestTask->toString(), bestTask->priority);
  381. if(!executeTask(bestTask))
  382. {
  383. if(hasAnySuccess)
  384. break;
  385. else
  386. return;
  387. }
  388. hasAnySuccess = true;
  389. }
  390. hasAnySuccess |= handleTrading();
  391. if(!hasAnySuccess)
  392. {
  393. logAi->trace("Nothing was done this turn. Ending turn.");
  394. return;
  395. }
  396. if(i == settings->getMaxPass())
  397. {
  398. logAi->warn("Maxpass exceeded. Terminating AI turn.");
  399. }
  400. }
  401. }
  402. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  403. {
  404. auto affectedObjs = task->getAffectedObjects();
  405. for(auto oid : affectedObjs)
  406. {
  407. if(!cb->getObj(oid, false))
  408. return false;
  409. }
  410. return true;
  411. }
  412. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  413. {
  414. HeroPtr hero = task->getHero();
  415. HeroRole heroRole = HeroRole::MAIN;
  416. if(hero.validAndSet())
  417. heroRole = heroManager->getHeroRole(hero);
  418. return heroRole;
  419. }
  420. bool Nullkiller::executeTask(Goals::TTask task)
  421. {
  422. auto start = std::chrono::high_resolution_clock::now();
  423. std::string taskDescr = task->toString();
  424. boost::this_thread::interruption_point();
  425. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  426. try
  427. {
  428. task->accept(gateway);
  429. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  430. }
  431. catch(goalFulfilledException &)
  432. {
  433. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  434. }
  435. catch(cannotFulfillGoalException & e)
  436. {
  437. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  438. logAi->error("The error message was: %s", e.what());
  439. return false;
  440. }
  441. return true;
  442. }
  443. TResources Nullkiller::getFreeResources() const
  444. {
  445. auto freeRes = cb->getResourceAmount() - lockedResources;
  446. freeRes.positive();
  447. return freeRes;
  448. }
  449. void Nullkiller::lockResources(const TResources & res)
  450. {
  451. lockedResources += res;
  452. }
  453. bool Nullkiller::handleTrading()
  454. {
  455. bool haveTraded = false;
  456. bool shouldTryToTrade = true;
  457. int marketId = -1;
  458. for (auto town : cb->getTownsInfo())
  459. {
  460. if (town->hasBuiltSomeTradeBuilding())
  461. {
  462. marketId = town->id;
  463. }
  464. }
  465. if (marketId == -1)
  466. return false;
  467. if (const CGObjectInstance* obj = cb->getObj(ObjectInstanceID(marketId), false))
  468. {
  469. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  470. {
  471. while (shouldTryToTrade)
  472. {
  473. shouldTryToTrade = false;
  474. buildAnalyzer->update();
  475. TResources required = buildAnalyzer->getTotalResourcesRequired();
  476. TResources income = buildAnalyzer->getDailyIncome();
  477. TResources available = getFreeResources();
  478. int mostWanted = -1;
  479. int mostExpendable = -1;
  480. float minRatio = std::numeric_limits<float>::max();
  481. float maxRatio = std::numeric_limits<float>::min();
  482. for (int i = 0; i < required.size(); ++i)
  483. {
  484. if (required[i] == 0)
  485. continue;
  486. float ratio = static_cast<float>(available[i]) / required[i];
  487. if (ratio < minRatio) {
  488. minRatio = ratio;
  489. mostWanted = i;
  490. }
  491. }
  492. for (int i = 0; i < required.size(); ++i)
  493. {
  494. float ratio = available[i];
  495. if (required[i] > 0)
  496. ratio = static_cast<float>(available[i]) / required[i];
  497. bool okToSell = false;
  498. if (i == 6)
  499. {
  500. if (income[i] > 0)
  501. okToSell = true;
  502. }
  503. else
  504. {
  505. if (available[i] > required[i])
  506. okToSell = true;
  507. }
  508. if (ratio > maxRatio && okToSell) {
  509. maxRatio = ratio;
  510. mostExpendable = i;
  511. }
  512. }
  513. //logAi->info("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  514. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  515. return false;
  516. int toGive;
  517. int toGet;
  518. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  519. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  520. //TODO trade only as much as needed
  521. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  522. {
  523. cb->trade(m, EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  524. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  525. haveTraded = true;
  526. shouldTryToTrade = true;
  527. }
  528. }
  529. }
  530. }
  531. return haveTraded;
  532. }
  533. }