Nullkiller.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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) || (task->asTask()->getHero() != nullptr && task->asTask()->getHero() == item.task->asTask()->getHero()))
  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 || priorityTier != 3)
  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 %d. Discarding %s", path.targetHero->getObjectName(), (int)lockReason, 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. float totalHeroStrength = 0;
  276. int totalTownLevel = 0;
  277. for (auto heroInfo : cb->getHeroesInfo())
  278. {
  279. totalHeroStrength += heroInfo->getTotalStrength();
  280. }
  281. for (auto townInfo : cb->getTownsInfo())
  282. {
  283. totalTownLevel += townInfo->getTownLevel();
  284. }
  285. resetAiState();
  286. Goals::TGoalVec bestTasks;
  287. logAi->info("Beginning: Strength: %f Townlevel: %d Resources: %s", totalHeroStrength, totalTownLevel, cb->getResourceAmount().toString());
  288. for(int i = 1; i <= settings->getMaxPass() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  289. {
  290. auto start = std::chrono::high_resolution_clock::now();
  291. updateAiState(i);
  292. Goals::TTask bestTask = taskptr(Goals::Invalid());
  293. for(;i <= settings->getMaxPass(); i++)
  294. {
  295. bestTasks.clear();
  296. decompose(bestTasks, sptr(RecruitHeroBehavior()), 1);
  297. decompose(bestTasks, sptr(BuyArmyBehavior()), 1);
  298. decompose(bestTasks, sptr(BuildingBehavior()), 1);
  299. bestTask = choseBestTask(bestTasks);
  300. if(bestTask->priority > 0)
  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(CaptureObjectsBehavior()), 1);
  313. decompose(bestTasks, sptr(ClusterBehavior()), MAX_DEPTH);
  314. decompose(bestTasks, sptr(DefenceBehavior()), MAX_DEPTH);
  315. decompose(bestTasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  316. decompose(bestTasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  317. if(!isOpenMap())
  318. decompose(bestTasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  319. TTaskVec selectedTasks;
  320. int prioOfTask = 0;
  321. for (int prio = 1; prio <= 5; ++prio)
  322. {
  323. prioOfTask = prio;
  324. selectedTasks = buildPlan(bestTasks, prio);
  325. if (!selectedTasks.empty() || settings->isUseFuzzy())
  326. break;
  327. }
  328. std::sort(selectedTasks.begin(), selectedTasks.end(), [](const TTask& a, const TTask& b)
  329. {
  330. return a->priority > b->priority;
  331. });
  332. logAi->debug("Decision madel in %ld", timeElapsed(start));
  333. if(selectedTasks.empty())
  334. {
  335. selectedTasks.push_back(taskptr(Goals::Invalid()));
  336. }
  337. bool hasAnySuccess = false;
  338. for(auto bestTask : selectedTasks)
  339. {
  340. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  341. return;
  342. if(!areAffectedObjectsPresent(bestTask))
  343. {
  344. logAi->debug("Affected object not found. Canceling task.");
  345. continue;
  346. }
  347. std::string taskDescription = bestTask->toString();
  348. HeroRole heroRole = getTaskRole(bestTask);
  349. if(heroRole != HeroRole::MAIN || bestTask->getHeroExchangeCount() <= 1)
  350. useHeroChain = false;
  351. // TODO: better to check turn distance here instead of priority
  352. if((heroRole != HeroRole::MAIN || bestTask->priority < SMALL_SCAN_MIN_PRIORITY)
  353. && scanDepth == ScanDepth::MAIN_FULL)
  354. {
  355. useHeroChain = false;
  356. scanDepth = ScanDepth::SMALL;
  357. logAi->trace(
  358. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  359. taskDescription,
  360. bestTask->priority);
  361. }
  362. if((settings->isUseFuzzy() && bestTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && bestTask->priority <= 0))
  363. {
  364. auto heroes = cb->getHeroesInfo();
  365. auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  366. {
  367. return h->movementPointsRemaining() > 100;
  368. });
  369. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  370. {
  371. logAi->trace(
  372. "Goal %s has too low priority %f so increasing scan depth to full.",
  373. taskDescription,
  374. bestTask->priority);
  375. scanDepth = ScanDepth::ALL_FULL;
  376. useHeroChain = false;
  377. hasAnySuccess = true;
  378. break;
  379. }
  380. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  381. continue;
  382. }
  383. logAi->info("Pass %d: Performing prio %d task %s with prio: %d", i, prioOfTask, bestTask->toString(), bestTask->priority);
  384. if(!executeTask(bestTask))
  385. {
  386. if(hasAnySuccess)
  387. break;
  388. else
  389. return;
  390. }
  391. hasAnySuccess = true;
  392. }
  393. hasAnySuccess |= handleTrading();
  394. if(!hasAnySuccess)
  395. {
  396. logAi->trace("Nothing was done this turn. Ending turn.");
  397. return;
  398. }
  399. if(i == settings->getMaxPass())
  400. {
  401. logAi->warn("Maxpass exceeded. Terminating AI turn.");
  402. }
  403. }
  404. for (auto heroInfo : cb->getHeroesInfo())
  405. {
  406. totalHeroStrength += heroInfo->getTotalStrength();
  407. }
  408. for (auto townInfo : cb->getTownsInfo())
  409. {
  410. totalTownLevel += townInfo->getTownLevel();
  411. }
  412. logAi->info("End: Strength: %f Townlevel: %d Resources: %s", totalHeroStrength, totalTownLevel, cb->getResourceAmount().toString());
  413. }
  414. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  415. {
  416. auto affectedObjs = task->getAffectedObjects();
  417. for(auto oid : affectedObjs)
  418. {
  419. if(!cb->getObj(oid, false))
  420. return false;
  421. }
  422. return true;
  423. }
  424. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  425. {
  426. HeroPtr hero = task->getHero();
  427. HeroRole heroRole = HeroRole::MAIN;
  428. if(hero.validAndSet())
  429. heroRole = heroManager->getHeroRole(hero);
  430. return heroRole;
  431. }
  432. bool Nullkiller::executeTask(Goals::TTask task)
  433. {
  434. auto start = std::chrono::high_resolution_clock::now();
  435. std::string taskDescr = task->toString();
  436. boost::this_thread::interruption_point();
  437. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  438. try
  439. {
  440. task->accept(gateway);
  441. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  442. }
  443. catch(goalFulfilledException &)
  444. {
  445. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  446. }
  447. catch(cannotFulfillGoalException & e)
  448. {
  449. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  450. logAi->error("The error message was: %s", e.what());
  451. return false;
  452. }
  453. return true;
  454. }
  455. TResources Nullkiller::getFreeResources() const
  456. {
  457. auto freeRes = cb->getResourceAmount() - lockedResources;
  458. freeRes.positive();
  459. return freeRes;
  460. }
  461. void Nullkiller::lockResources(const TResources & res)
  462. {
  463. lockedResources += res;
  464. }
  465. bool Nullkiller::handleTrading()
  466. {
  467. bool haveTraded = false;
  468. bool shouldTryToTrade = true;
  469. int marketId = -1;
  470. for (auto town : cb->getTownsInfo())
  471. {
  472. if (town->hasBuiltSomeTradeBuilding())
  473. {
  474. marketId = town->id;
  475. }
  476. }
  477. if (marketId == -1)
  478. return false;
  479. if (const CGObjectInstance* obj = cb->getObj(ObjectInstanceID(marketId), false))
  480. {
  481. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  482. {
  483. while (shouldTryToTrade)
  484. {
  485. shouldTryToTrade = false;
  486. buildAnalyzer->update();
  487. TResources required = buildAnalyzer->getTotalResourcesRequired();
  488. TResources income = buildAnalyzer->getDailyIncome();
  489. TResources available = cb->getResourceAmount();
  490. logAi->debug("Available %s", available.toString());
  491. logAi->debug("Required %s", required.toString());
  492. int mostWanted = -1;
  493. int mostExpendable = -1;
  494. float minRatio = std::numeric_limits<float>::max();
  495. float maxRatio = std::numeric_limits<float>::min();
  496. for (int i = 0; i < required.size(); ++i)
  497. {
  498. if (required[i] <= 0)
  499. continue;
  500. float ratio = static_cast<float>(available[i]) / required[i];
  501. if (ratio < minRatio) {
  502. minRatio = ratio;
  503. mostWanted = i;
  504. }
  505. }
  506. for (int i = 0; i < required.size(); ++i)
  507. {
  508. float ratio = available[i];
  509. if (required[i] > 0)
  510. ratio = static_cast<float>(available[i]) / required[i];
  511. else
  512. ratio = available[i];
  513. bool okToSell = false;
  514. if (i == 6)
  515. {
  516. if (income[i] > 0 && !buildAnalyzer->isGoldPressureHigh())
  517. okToSell = true;
  518. }
  519. else
  520. {
  521. if (required[i] <= 0)
  522. okToSell = true;
  523. }
  524. if (ratio > maxRatio && okToSell) {
  525. maxRatio = ratio;
  526. mostExpendable = i;
  527. }
  528. }
  529. logAi->debug("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  530. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  531. return false;
  532. int toGive;
  533. int toGet;
  534. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  535. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  536. //TODO trade only as much as needed
  537. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  538. {
  539. cb->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  540. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  541. haveTraded = true;
  542. shouldTryToTrade = true;
  543. }
  544. }
  545. }
  546. }
  547. return haveTraded;
  548. }
  549. }