Nullkiller.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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 <boost/range/algorithm/sort.hpp>
  13. #include "../AIGateway.h"
  14. #include "../Behaviors/CaptureObjectsBehavior.h"
  15. #include "../Behaviors/RecruitHeroBehavior.h"
  16. #include "../Behaviors/BuyArmyBehavior.h"
  17. #include "../Behaviors/StartupBehavior.h"
  18. #include "../Behaviors/DefenceBehavior.h"
  19. #include "../Behaviors/BuildingBehavior.h"
  20. #include "../Behaviors/GatherArmyBehavior.h"
  21. #include "../Behaviors/ClusterBehavior.h"
  22. #include "../Behaviors/StayAtTownBehavior.h"
  23. #include "../Behaviors/ExplorationBehavior.h"
  24. #include "../Goals/Invalid.h"
  25. #include "../Goals/Composition.h"
  26. #include "../../../lib/CPlayerState.h"
  27. #include "../../lib/StartInfo.h"
  28. #include "../../lib/pathfinder/PathfinderCache.h"
  29. #include "../../lib/pathfinder/PathfinderOptions.h"
  30. namespace NK2AI
  31. {
  32. // extern thread_local CCallback * ccTl;
  33. // extern thread_local AIGateway * aiGwTl;
  34. using namespace Goals;
  35. // while we play vcmieagles graph can be shared
  36. std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
  37. Nullkiller::Nullkiller()
  38. : activeHero(nullptr)
  39. , scanDepth(ScanDepth::MAIN_FULL)
  40. , useHeroChain(true)
  41. , pathfinderInvalidated(false)
  42. , memory(std::make_unique<AIMemory>())
  43. {
  44. }
  45. Nullkiller::~Nullkiller() = default;
  46. bool canUseOpenMap(std::shared_ptr<CCallback> cb, PlayerColor playerID)
  47. {
  48. if(!cb->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  49. {
  50. return false;
  51. }
  52. const TeamState * team = cb->getPlayerTeam(playerID);
  53. auto hasHumanInTeam = vstd::contains_if(team->players, [cb](PlayerColor teamMateID) -> bool
  54. {
  55. return cb->getPlayerState(teamMateID)->isHuman();
  56. });
  57. return !hasHumanInTeam;
  58. }
  59. void Nullkiller::init(std::shared_ptr<CCallback> cb, AIGateway * aiGw)
  60. {
  61. this->cc = cb;
  62. this->aiGw = aiGw;
  63. this->playerID = aiGw->playerID;
  64. settings = std::make_unique<Settings>(cb->getStartInfo()->difficulty);
  65. PathfinderOptions pathfinderOptions(*cb);
  66. pathfinderOptions.useTeleportTwoWay = true;
  67. pathfinderOptions.useTeleportOneWay = settings->isOneWayMonolithUsageAllowed();
  68. pathfinderOptions.useTeleportOneWayRandom = settings->isOneWayMonolithUsageAllowed();
  69. pathfinderCache = std::make_unique<PathfinderCache>(cb.get(), pathfinderOptions);
  70. if(canUseOpenMap(cb, playerID))
  71. {
  72. useObjectGraph = settings->isObjectGraphAllowed();
  73. openMap = settings->isOpenMap() || useObjectGraph;
  74. }
  75. else
  76. {
  77. useObjectGraph = false;
  78. openMap = false;
  79. }
  80. baseGraph.reset();
  81. priorityEvaluator.reset(new PriorityEvaluator(this));
  82. priorityEvaluators.reset(
  83. new SharedPool<PriorityEvaluator>(
  84. [&]()->std::unique_ptr<PriorityEvaluator>
  85. {
  86. return std::make_unique<PriorityEvaluator>(this);
  87. }));
  88. dangerHitMap.reset(new DangerHitMapAnalyzer(this));
  89. buildAnalyzer.reset(new BuildAnalyzer(this));
  90. objectClusterizer.reset(new ObjectClusterizer(this));
  91. dangerEvaluator.reset(new FuzzyHelper(this));
  92. pathfinder.reset(new AIPathfinder(cb.get(), this));
  93. armyManager.reset(new ArmyManager(cb.get(), this));
  94. heroManager.reset(new HeroManager(cb.get(), this));
  95. decomposer.reset(new DeepDecomposer(this));
  96. armyFormation.reset(new ArmyFormation(cb, this));
  97. }
  98. TaskPlanItem::TaskPlanItem(const TSubgoal & task)
  99. :task(task), affectedObjects(task->asTask()->getAffectedObjects())
  100. {
  101. }
  102. Goals::TTaskVec TaskPlan::getTasks() const
  103. {
  104. Goals::TTaskVec result;
  105. for(auto & item : tasks)
  106. {
  107. result.push_back(taskptr(*item.task));
  108. }
  109. vstd::removeDuplicates(result);
  110. return result;
  111. }
  112. void TaskPlan::merge(const TSubgoal & task)
  113. {
  114. TGoalVec blockers;
  115. if (task->asTask()->priority <= 0)
  116. return;
  117. for(auto & item : tasks)
  118. {
  119. for(auto objid : item.affectedObjects)
  120. {
  121. if(task == item.task || task->asTask()->isObjectAffected(objid) || (task->asTask()->getHero() != nullptr && task->asTask()->getHero() == item.task->asTask()->getHero()))
  122. {
  123. if(item.task->asTask()->priority >= task->asTask()->priority)
  124. return;
  125. blockers.push_back(item.task);
  126. break;
  127. }
  128. }
  129. }
  130. vstd::erase_if(tasks, [&](const TaskPlanItem & task2)
  131. {
  132. return vstd::contains(blockers, task2.task);
  133. });
  134. tasks.emplace_back(task);
  135. }
  136. Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
  137. {
  138. if(tasks.empty())
  139. {
  140. return taskptr(Invalid());
  141. }
  142. for(const TSubgoal & task : tasks)
  143. {
  144. if(task->asTask()->priority <= 0)
  145. task->asTask()->priority = priorityEvaluator->evaluate(task);
  146. }
  147. auto bestTask = *vstd::maxElementByFun(tasks, [](const Goals::TSubgoal& task) -> float
  148. {
  149. return task->asTask()->priority;
  150. });
  151. return taskptr(*bestTask);
  152. }
  153. Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks, int priorityTier) const
  154. {
  155. TaskPlan taskPlan;
  156. tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks, priorityTier](const tbb::blocked_range<size_t> & r)
  157. {
  158. SET_GLOBAL_STATE_TBB(this->aiGw);
  159. auto evaluator = this->priorityEvaluators->acquire();
  160. for(size_t i = r.begin(); i != r.end(); i++)
  161. {
  162. const auto & task = tasks[i];
  163. if(task->asTask()->priority <= 0 || priorityTier != PriorityEvaluator::PriorityTier::BUILDINGS)
  164. task->asTask()->priority = evaluator->evaluate(task, priorityTier);
  165. }
  166. });
  167. boost::range::sort(tasks, [](const TSubgoal& g1, const TSubgoal& g2) -> bool
  168. {
  169. return g2->asTask()->priority < g1->asTask()->priority;
  170. });
  171. for(const TSubgoal & task : tasks)
  172. {
  173. taskPlan.merge(task);
  174. }
  175. return taskPlan.getTasks();
  176. }
  177. void Nullkiller::decompose(Goals::TGoalVec & results, const Goals::TSubgoal& behavior, int decompositionMaxDepth) const
  178. {
  179. makingTurnInterrupption.interruptionPoint();
  180. logAi->debug("Decomposing behavior %s", behavior->toString());
  181. const auto start = std::chrono::high_resolution_clock::now();
  182. decomposer->decompose(results, behavior, decompositionMaxDepth);
  183. makingTurnInterrupption.interruptionPoint();
  184. logAi->debug("Decomposing behavior %s done in %ld", behavior->toString(), timeElapsed(start));
  185. }
  186. void Nullkiller::resetState()
  187. {
  188. std::unique_lock lockGuard(aiStateMutex);
  189. lockedResources = TResources();
  190. scanDepth = ScanDepth::MAIN_FULL;
  191. lockedHeroes.clear();
  192. dangerHitMap->resetHitmap();
  193. useHeroChain = true;
  194. objectClusterizer->reset();
  195. if(!baseGraph && isObjectGraphAllowed())
  196. {
  197. baseGraph = std::make_unique<ObjectGraph>();
  198. baseGraph->updateGraph(this);
  199. }
  200. }
  201. void Nullkiller::invalidatePathfinderData()
  202. {
  203. pathfinderInvalidated = true;
  204. }
  205. void Nullkiller::updateState()
  206. {
  207. makingTurnInterrupption.interruptionPoint();
  208. std::unique_lock lockGuard(aiStateMutex);
  209. auto start = std::chrono::high_resolution_clock::now();
  210. activeHero = nullptr;
  211. setTargetObject(-1);
  212. decomposer->reset();
  213. buildAnalyzer->update();
  214. if (!pathfinderInvalidated)
  215. logAi->trace("Skipping paths regeneration - up to date");
  216. else
  217. {
  218. memory->removeInvisibleObjects(cc.get());
  219. dangerHitMap->updateHitMap();
  220. dangerHitMap->calculateTileOwners();
  221. makingTurnInterrupption.interruptionPoint();
  222. heroManager->update();
  223. logAi->trace("Updating paths");
  224. std::map<const CGHeroInstance *, HeroRole> activeHeroes;
  225. for(auto hero : cc->getHeroesInfo())
  226. {
  227. if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
  228. continue;
  229. activeHeroes[hero] = heroManager->getHeroRole(hero);
  230. }
  231. PathfinderSettings cfg;
  232. cfg.useHeroChain = useHeroChain;
  233. cfg.allowBypassObjects = true;
  234. if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
  235. {
  236. cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
  237. }
  238. if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
  239. {
  240. cfg.scoutTurnDistanceLimit = settings->getScoutHeroTurnDistanceLimit();
  241. }
  242. makingTurnInterrupption.interruptionPoint();
  243. pathfinder->updatePaths(activeHeroes, cfg);
  244. if(isObjectGraphAllowed())
  245. {
  246. pathfinder->updateGraphs(
  247. activeHeroes,
  248. scanDepth == ScanDepth::SMALL ? 255 : 10,
  249. scanDepth == ScanDepth::ALL_FULL ? 255 : 3);
  250. }
  251. makingTurnInterrupption.interruptionPoint();
  252. objectClusterizer->clusterize();
  253. pathfinderInvalidated = false;
  254. }
  255. armyManager->update();
  256. logAi->debug("AI state updated in %ld ms", timeElapsed(start));
  257. }
  258. bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
  259. {
  260. return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
  261. }
  262. bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
  263. {
  264. if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
  265. {
  266. #if NK2AI_TRACE_LEVEL >= 1
  267. logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
  268. #endif
  269. return true;
  270. }
  271. for(auto & node : path.nodes)
  272. {
  273. auto lockReason = getHeroLockedReason(node.targetHero);
  274. if(lockReason != HeroLockedReason::NOT_LOCKED)
  275. {
  276. #if NK2AI_TRACE_LEVEL >= 1
  277. logAi->trace("Hero %s is locked by %d. Discarding %s", path.targetHero->getObjectName(), (int)lockReason, path.toString());
  278. #endif
  279. return true;
  280. }
  281. }
  282. return false;
  283. }
  284. HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
  285. {
  286. auto found = lockedHeroes.find(hero);
  287. return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
  288. }
  289. void Nullkiller::makeTurn()
  290. {
  291. std::lock_guard<std::mutex> sharedStorageLock(AISharedStorage::locker);
  292. const int MAX_DEPTH = 10;
  293. resetState();
  294. Goals::TGoalVec tasks;
  295. tracePlayerStatus(true);
  296. for(int i = 1; i <= settings->getMaxPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  297. {
  298. updateState();
  299. if (!makeTurnHelperPriorityPass(tasks, i)) return;
  300. tasks.clear();
  301. decompose(tasks, sptr(CaptureObjectsBehavior()), 1);
  302. decompose(tasks, sptr(ClusterBehavior()), MAX_DEPTH);
  303. decompose(tasks, sptr(DefenceBehavior()), MAX_DEPTH);
  304. decompose(tasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
  305. decompose(tasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
  306. if(!isOpenMap())
  307. decompose(tasks, sptr(ExplorationBehavior()), MAX_DEPTH);
  308. TTaskVec selectedTasks;
  309. #if NK2AI_TRACE_LEVEL >= 1
  310. int prioOfTask = 0;
  311. #endif
  312. for (int prio = PriorityEvaluator::PriorityTier::INSTAKILL; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
  313. {
  314. #if NK2AI_TRACE_LEVEL >= 1
  315. prioOfTask = prio;
  316. #endif
  317. selectedTasks = buildPlan(tasks, prio);
  318. if (!selectedTasks.empty() || settings->isUseFuzzy())
  319. break;
  320. }
  321. boost::range::sort(selectedTasks, [](const TTask& a, const TTask& b)
  322. {
  323. return a->priority > b->priority;
  324. });
  325. if(selectedTasks.empty())
  326. {
  327. selectedTasks.push_back(taskptr(Goals::Invalid()));
  328. }
  329. bool hasAnySuccess = false;
  330. for(const auto& selectedTask : selectedTasks)
  331. {
  332. if(cc->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  333. return;
  334. if(!areAffectedObjectsPresent(selectedTask))
  335. {
  336. logAi->debug("Affected object not found. Canceling task.");
  337. continue;
  338. }
  339. std::string taskDescription = selectedTask->toString();
  340. HeroRole heroRole = getTaskRole(selectedTask);
  341. if(heroRole != HeroRole::MAIN || selectedTask->getHeroExchangeCount() <= 1)
  342. useHeroChain = false;
  343. // TODO: better to check turn distance here instead of priority
  344. if((heroRole != HeroRole::MAIN || selectedTask->priority < SMALL_SCAN_MIN_PRIORITY)
  345. && scanDepth == ScanDepth::MAIN_FULL)
  346. {
  347. useHeroChain = false;
  348. scanDepth = ScanDepth::SMALL;
  349. logAi->trace(
  350. "Goal %s has low priority %f so decreasing scan depth to gain performance.",
  351. taskDescription,
  352. selectedTask->priority);
  353. }
  354. if((settings->isUseFuzzy() && selectedTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && selectedTask->priority <= 0))
  355. {
  356. auto heroes = cc->getHeroesInfo();
  357. const auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
  358. {
  359. return h->movementPointsRemaining() > 100;
  360. });
  361. if(hasMp && scanDepth != ScanDepth::ALL_FULL)
  362. {
  363. logAi->trace(
  364. "Goal %s has too low priority %f so increasing scan depth to full.",
  365. taskDescription,
  366. selectedTask->priority);
  367. scanDepth = ScanDepth::ALL_FULL;
  368. useHeroChain = false;
  369. hasAnySuccess = true;
  370. break;
  371. }
  372. logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
  373. continue;
  374. }
  375. #if NK2AI_TRACE_LEVEL >= 1
  376. logAi->info("Pass %d: Performing prio %d task %s with prio: %d", i, prioOfTask, selectedTask->toString(), selectedTask->priority);
  377. #endif
  378. if(!executeTask(selectedTask))
  379. {
  380. if(hasAnySuccess)
  381. break;
  382. return;
  383. }
  384. hasAnySuccess = true;
  385. }
  386. hasAnySuccess |= handleTrading();
  387. if(!hasAnySuccess)
  388. {
  389. logAi->trace("Nothing was done this turn. Ending turn.");
  390. tracePlayerStatus(false);
  391. return;
  392. }
  393. for (const auto *heroInfo : cc->getHeroesInfo())
  394. AIGateway::pickBestArtifacts(cc, heroInfo);
  395. if(i == settings->getMaxPass())
  396. {
  397. logAi->warn("MaxPass reached. Terminating AI turn.");
  398. }
  399. }
  400. }
  401. bool Nullkiller::makeTurnHelperPriorityPass(Goals::TGoalVec & tempResults, int passIndex)
  402. {
  403. Goals::TTask bestPrioPassTask = taskptr(Goals::Invalid());
  404. for(int i = 1; i <= settings->getMaxPriorityPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
  405. {
  406. tempResults.clear();
  407. // Call updateHitMap here instead of inside each of the 3 behaviors
  408. dangerHitMap->updateHitMap();
  409. decompose(tempResults, sptr(RecruitHeroBehavior()), 1);
  410. decompose(tempResults, sptr(BuyArmyBehavior()), 1);
  411. decompose(tempResults, sptr(BuildingBehavior()), 1);
  412. bestPrioPassTask = choseBestTask(tempResults);
  413. if(bestPrioPassTask->priority > 0)
  414. {
  415. #if NK2AI_TRACE_LEVEL >= 1
  416. logAi->info("Pass %d: Performing priorityPass %d task %s with prio: %d", passIndex, i, bestPrioPassTask->toString(), bestPrioPassTask->priority);
  417. #endif
  418. if(!executeTask(bestPrioPassTask))
  419. return false;
  420. updateState();
  421. }
  422. else
  423. {
  424. break;
  425. }
  426. if(i == settings->getMaxPriorityPass())
  427. {
  428. logAi->warn("MaxPriorityPass reached. Terminating priorityPass loop.");
  429. }
  430. }
  431. return true;
  432. }
  433. bool Nullkiller::areAffectedObjectsPresent(Goals::TTask task) const
  434. {
  435. auto affectedObjs = task->getAffectedObjects();
  436. for(auto oid : affectedObjs)
  437. {
  438. if(!cc->getObj(oid, false))
  439. return false;
  440. }
  441. return true;
  442. }
  443. HeroRole Nullkiller::getTaskRole(Goals::TTask task) const
  444. {
  445. HeroPtr hero = task->getHero();
  446. HeroRole heroRole = HeroRole::MAIN;
  447. if(hero.validAndSet())
  448. heroRole = heroManager->getHeroRole(hero);
  449. return heroRole;
  450. }
  451. bool Nullkiller::executeTask(Goals::TTask task)
  452. {
  453. auto start = std::chrono::high_resolution_clock::now();
  454. std::string taskDescr = task->toString();
  455. makingTurnInterrupption.interruptionPoint();
  456. logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
  457. try
  458. {
  459. task->accept(aiGw);
  460. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  461. }
  462. catch(goalFulfilledException &)
  463. {
  464. logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
  465. }
  466. catch(cannotFulfillGoalException & e)
  467. {
  468. logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
  469. logAi->error("The error message was: %s", e.what());
  470. return false;
  471. }
  472. return true;
  473. }
  474. TResources Nullkiller::getFreeResources() const
  475. {
  476. auto freeRes = cc->getResourceAmount() - lockedResources;
  477. freeRes.positive();
  478. return freeRes;
  479. }
  480. void Nullkiller::lockResources(const TResources & res)
  481. {
  482. lockedResources += res;
  483. }
  484. bool Nullkiller::handleTrading()
  485. {
  486. bool haveTraded = false;
  487. bool shouldTryToTrade = true;
  488. ObjectInstanceID marketId;
  489. for (auto town : cc->getTownsInfo())
  490. {
  491. if (town->hasBuiltSomeTradeBuilding())
  492. {
  493. marketId = town->id;
  494. }
  495. }
  496. if (!marketId.hasValue())
  497. return false;
  498. if (const CGObjectInstance* obj = cc->getObj(marketId, false))
  499. {
  500. if (const auto* m = dynamic_cast<const IMarket*>(obj))
  501. {
  502. while (shouldTryToTrade)
  503. {
  504. shouldTryToTrade = false;
  505. buildAnalyzer->update();
  506. TResources required = buildAnalyzer->getTotalResourcesRequired();
  507. TResources income = buildAnalyzer->getDailyIncome();
  508. TResources available = cc->getResourceAmount();
  509. #if NK2AI_TRACE_LEVEL >= 2
  510. logAi->debug("Available %s", available.toString());
  511. logAi->debug("Required %s", required.toString());
  512. #endif
  513. int mostWanted = -1;
  514. int mostExpendable = -1;
  515. float minRatio = std::numeric_limits<float>::max();
  516. float maxRatio = std::numeric_limits<float>::min();
  517. for (int i = 0; i < required.size(); ++i)
  518. {
  519. if (required[i] <= 0)
  520. continue;
  521. float ratio = static_cast<float>(available[i]) / required[i];
  522. if (ratio < minRatio) {
  523. minRatio = ratio;
  524. mostWanted = i;
  525. }
  526. }
  527. for (int i = 0; i < required.size(); ++i)
  528. {
  529. float ratio = available[i];
  530. if (required[i] > 0)
  531. ratio = static_cast<float>(available[i]) / required[i];
  532. else
  533. ratio = available[i];
  534. bool okToSell = false;
  535. if (i == GameResID::GOLD)
  536. {
  537. if (income[i] > 0 && !buildAnalyzer->isGoldPressureOverMax())
  538. okToSell = true;
  539. }
  540. else
  541. {
  542. if (required[i] <= 0 && income[i] > 0)
  543. okToSell = true;
  544. }
  545. if (ratio > maxRatio && okToSell) {
  546. maxRatio = ratio;
  547. mostExpendable = i;
  548. }
  549. }
  550. #if NK2AI_TRACE_LEVEL >= 2
  551. logAi->debug("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
  552. #endif
  553. if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
  554. return false;
  555. int toGive;
  556. int toGet;
  557. m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  558. //logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
  559. //TODO trade only as much as needed
  560. if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
  561. {
  562. cc->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
  563. #if NK2AI_TRACE_LEVEL >= 2
  564. logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
  565. #endif
  566. haveTraded = true;
  567. shouldTryToTrade = true;
  568. }
  569. }
  570. }
  571. }
  572. return haveTraded;
  573. }
  574. std::shared_ptr<const CPathsInfo> Nullkiller::getPathsInfo(const CGHeroInstance * h) const
  575. {
  576. return pathfinderCache->getPathsInfo(h);
  577. }
  578. void Nullkiller::invalidatePaths()
  579. {
  580. pathfinderCache->invalidatePaths();
  581. }
  582. void Nullkiller::tracePlayerStatus(bool beginning) const
  583. {
  584. #if NK2AI_TRACE_LEVEL >= 1
  585. float totalHeroesStrength = 0;
  586. int totalTownsLevel = 0;
  587. for (const auto *heroInfo : cc->getHeroesInfo())
  588. {
  589. totalHeroesStrength += heroInfo->getTotalStrength();
  590. }
  591. for (const auto *townInfo : cc->getTownsInfo())
  592. {
  593. totalTownsLevel += townInfo->getTownLevel();
  594. }
  595. const auto *firstWord = beginning ? "Beginning:" : "End:";
  596. logAi->info("%s totalHeroesStrength: %f, totalTownsLevel: %d, resources: %s", firstWord, totalHeroesStrength, totalTownsLevel, cc->getResourceAmount().toString());
  597. #endif
  598. }
  599. }