Nullkiller.cpp 19 KB

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