BuildAnalyzer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /*
  2. * BuildAnalyzer.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 <boost/range/algorithm/sort.hpp>
  12. #include "../Engine/Nullkiller.h"
  13. #include "../../../lib/entities/building/CBuilding.h"
  14. #include "../../../lib/IGameSettings.h"
  15. #include "../AIUtility.h"
  16. namespace NK2AI
  17. {
  18. TResources BuildAnalyzer::getMissingResourcesNow(const float armyGoldRatio) const
  19. {
  20. auto armyGold = goldOnly(armyCost);
  21. armyGold[GameResID::GOLD] = armyGoldRatio * armyGold[GameResID::GOLD];
  22. auto result = requiredResources + goldRemove(armyCost) + armyGold - aiNk->getFreeResources();
  23. result.positive();
  24. return result;
  25. }
  26. TResources BuildAnalyzer::getMissingResourcesInTotal(const float armyGoldRatio) const
  27. {
  28. auto armyGold = goldOnly(armyCost);
  29. armyGold[GameResID::GOLD] = armyGoldRatio * armyGold[GameResID::GOLD];
  30. auto result = totalDevelopmentCost + goldRemove(armyCost) + armyGold - aiNk->getFreeResources();
  31. result.positive();
  32. return result;
  33. }
  34. TResources BuildAnalyzer::getFreeResourcesAfterMissingTotal(const float armyGoldRatio) const
  35. {
  36. auto armyGold = goldOnly(armyCost);
  37. armyGold[GameResID::GOLD] = armyGoldRatio * armyGold[GameResID::GOLD];
  38. auto result = aiNk->getFreeResources() - totalDevelopmentCost - goldRemove(armyCost) - armyGold;
  39. result.positive();
  40. return result;
  41. }
  42. bool BuildAnalyzer::isGoldPressureOverMax() const
  43. {
  44. return goldPressure > aiNk->settings->getMaxGoldPressure();
  45. }
  46. void BuildAnalyzer::update()
  47. {
  48. logAi->trace("Start BuildAnalyzer::update");
  49. reset();
  50. const auto towns = aiNk->cc->getTownsInfo();
  51. float economyDevelopmentCost = 0;
  52. for(const CGTownInstance * town : towns)
  53. {
  54. if(town->built >= aiNk->cc->getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  55. continue; // Not much point in trying anything - can't built in this town anymore today
  56. #if NK2AI_TRACE_LEVEL >= 1
  57. logAi->trace("Checking town %s", town->getNameTranslated());
  58. #endif
  59. developmentInfos.push_back(TownDevelopmentInfo(town));
  60. TownDevelopmentInfo & tdi = developmentInfos.back();
  61. updateDwellings(tdi, aiNk->armyManager, aiNk->cc);
  62. updateOtherBuildings(tdi, aiNk->armyManager, aiNk->cc);
  63. requiredResources += tdi.requiredResources;
  64. totalDevelopmentCost += tdi.townDevelopmentCost;
  65. for(auto building : tdi.toBuild)
  66. {
  67. if (building.dailyIncome[EGameResID::GOLD] > 0)
  68. economyDevelopmentCost += building.buildCostWithPrerequisites[EGameResID::GOLD];
  69. }
  70. armyCost += tdi.armyCost;
  71. #if NK2AI_TRACE_LEVEL >= 1
  72. for(const auto & biToBuild : tdi.toBuild)
  73. logAi->trace("Building preferences %s", biToBuild.toString());
  74. #endif
  75. }
  76. boost::range::sort(developmentInfos, [](const TownDevelopmentInfo & tdi1, const TownDevelopmentInfo & tdi2) -> bool
  77. {
  78. auto val1 = goldApproximate(tdi1.armyCost) - goldApproximate(tdi1.townDevelopmentCost);
  79. auto val2 = goldApproximate(tdi2.armyCost) - goldApproximate(tdi2.townDevelopmentCost);
  80. return val1 > val2;
  81. });
  82. dailyIncome = calculateDailyIncome(aiNk->cc->getMyObjects(), aiNk->cc->getTownsInfo());
  83. goldPressure = calculateGoldPressure(aiNk->getLockedResources()[EGameResID::GOLD],
  84. static_cast<float>(armyCost[EGameResID::GOLD]),
  85. economyDevelopmentCost,
  86. aiNk->getFreeGold(),
  87. static_cast<float>(dailyIncome[EGameResID::GOLD]));
  88. }
  89. void BuildAnalyzer::reset()
  90. {
  91. requiredResources = TResources();
  92. totalDevelopmentCost = TResources();
  93. armyCost = TResources();
  94. developmentInfos.clear();
  95. }
  96. bool BuildAnalyzer::isBuilt(FactionID alignment, BuildingID bid) const
  97. {
  98. for(const auto & tdi : developmentInfos)
  99. {
  100. if(tdi.town->getFactionID() == alignment && tdi.town->hasBuilt(bid))
  101. return true;
  102. }
  103. return false;
  104. }
  105. void TownDevelopmentInfo::addBuildingBuilt(const BuildingInfo & bi)
  106. {
  107. armyCost += bi.armyCost;
  108. armyStrength += bi.armyStrength;
  109. built.push_back(bi);
  110. }
  111. void TownDevelopmentInfo::addBuildingToBuild(const BuildingInfo & bi)
  112. {
  113. townDevelopmentCost += bi.buildCostWithPrerequisites;
  114. townDevelopmentCost += BuildAnalyzer::goldRemove(bi.armyCost);
  115. if (bi.isBuildable)
  116. {
  117. toBuild.push_back(bi);
  118. }
  119. else if (bi.isMissingResources)
  120. {
  121. requiredResources += bi.buildCost;
  122. toBuild.push_back(bi);
  123. }
  124. }
  125. BuildingInfo::BuildingInfo() {}
  126. BuildingInfo::BuildingInfo(
  127. const CBuilding * building,
  128. const CCreature * creature,
  129. CreatureID baseCreature,
  130. const CGTownInstance * town,
  131. const std::unique_ptr<ArmyManager> & armyManager)
  132. {
  133. id = building->bid;
  134. buildCost = building->resources;
  135. buildCostWithPrerequisites = building->resources;
  136. dailyIncome = building->produce;
  137. isBuilt = town->hasBuilt(id);
  138. prerequisitesCount = 1;
  139. name = building->getNameTranslated();
  140. if(creature)
  141. {
  142. creatureGrowth = creature->getGrowth();
  143. creatureID = creature->getId();
  144. baseCreatureID = baseCreature;
  145. creatureUnitCost = creature->getFullRecruitCost();
  146. creatureLevel = creature->getLevel();
  147. if(isBuilt)
  148. {
  149. creatureGrowth = town->creatureGrowth(creatureLevel - 1);
  150. }
  151. else
  152. {
  153. if(id.isDwelling())
  154. {
  155. creatureGrowth = creature->getGrowth();
  156. if(town->hasBuilt(BuildingID::CASTLE))
  157. creatureGrowth *= 2;
  158. else if(town->hasBuilt(BuildingID::CITADEL))
  159. creatureGrowth += creatureGrowth / 2;
  160. }
  161. else
  162. {
  163. creatureGrowth = creature->getHorde();
  164. }
  165. }
  166. armyStrength = armyManager->evaluateStackPower(creature, creatureGrowth);
  167. armyCost = creatureUnitCost * creatureGrowth;
  168. }
  169. }
  170. std::string BuildingInfo::toString() const
  171. {
  172. return name + ", cost: " + buildCost.toString()
  173. + ", creature: " + std::to_string(creatureGrowth) + " x " + std::to_string(creatureLevel)
  174. + " x " + creatureUnitCost.toString()
  175. + ", daily: " + dailyIncome.toString();
  176. }
  177. float BuildAnalyzer::calculateGoldPressure(TResource lockedGold, float armyCostGold, float economyDevelopmentCost, float freeGold, float dailyIncomeGold)
  178. {
  179. auto pressure = (lockedGold + armyCostGold + economyDevelopmentCost) / (1 + 2 * freeGold + dailyIncomeGold * 7.0f);
  180. #if NK2AI_TRACE_LEVEL >= 1
  181. logAi->trace("Gold pressure: %f", pressure);
  182. #endif
  183. return pressure;
  184. }
  185. TResources BuildAnalyzer::calculateDailyIncome(const std::vector<const CGObjectInstance *> & objects, const std::vector<const CGTownInstance *> & townInfos)
  186. {
  187. auto result = TResources();
  188. for(const CGObjectInstance * obj : objects)
  189. {
  190. if(const auto * mine = dynamic_cast<const CGMine *>(obj))
  191. result += mine->dailyIncome();
  192. }
  193. for(const CGTownInstance * town : townInfos)
  194. {
  195. result += town->dailyIncome();
  196. }
  197. return result;
  198. }
  199. void BuildAnalyzer::updateDwellings(TownDevelopmentInfo & developmentInfo, std::unique_ptr<ArmyManager> & armyManager, std::shared_ptr<CCallback> & cc)
  200. {
  201. for(int level = 0; level < developmentInfo.town->getTown()->creatures.size(); level++)
  202. {
  203. #if NK2AI_TRACE_LEVEL >= 1
  204. logAi->trace("Checking dwelling level %d", level);
  205. #endif
  206. std::vector<BuildingID> dwellingsInTown;
  207. for(BuildingID buildID = BuildingID::getDwellingFromLevel(level, 0); buildID.hasValue(); BuildingID::advanceDwelling(buildID))
  208. if(developmentInfo.town->getTown()->buildings.count(buildID) != 0)
  209. dwellingsInTown.push_back(buildID);
  210. // find best, already built dwelling
  211. for (const auto & buildID : boost::adaptors::reverse(dwellingsInTown))
  212. {
  213. if (!developmentInfo.town->hasBuilt(buildID))
  214. continue;
  215. const auto & info = getBuildingOrPrerequisite(developmentInfo.town, buildID, armyManager, cc);
  216. developmentInfo.addBuildingBuilt(info);
  217. break;
  218. }
  219. // find all non-built dwellings that can be built and add them for consideration
  220. for (const auto & buildID : dwellingsInTown)
  221. {
  222. if (developmentInfo.town->hasBuilt(buildID))
  223. continue;
  224. const auto & info = getBuildingOrPrerequisite(developmentInfo.town, buildID, armyManager, cc);
  225. if (info.isBuildable || info.isMissingResources)
  226. developmentInfo.addBuildingToBuild(info);
  227. }
  228. }
  229. }
  230. void BuildAnalyzer::updateOtherBuildings(TownDevelopmentInfo & developmentInfo,
  231. std::unique_ptr<ArmyManager> & armyManager,
  232. std::shared_ptr<CCallback> & cc)
  233. {
  234. logAi->trace("Checking other buildings");
  235. std::vector<std::vector<BuildingID>> otherBuildings = {
  236. {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL},
  237. {BuildingID::MAGES_GUILD_3, BuildingID::MAGES_GUILD_5}
  238. };
  239. if(developmentInfo.built.size() >= 2 && cc->getDate(Date::DAY_OF_WEEK) > 4)
  240. {
  241. otherBuildings.push_back({BuildingID::HORDE_1});
  242. otherBuildings.push_back({BuildingID::HORDE_2});
  243. }
  244. otherBuildings.push_back({ BuildingID::CITADEL, BuildingID::CASTLE });
  245. otherBuildings.push_back({ BuildingID::RESOURCE_SILO });
  246. otherBuildings.push_back({ BuildingID::SPECIAL_1 });
  247. otherBuildings.push_back({ BuildingID::SPECIAL_2 });
  248. otherBuildings.push_back({ BuildingID::SPECIAL_3 });
  249. otherBuildings.push_back({ BuildingID::SPECIAL_4 });
  250. otherBuildings.push_back({ BuildingID::MARKETPLACE });
  251. for(auto & buildingSet : otherBuildings)
  252. {
  253. for(auto & buildingID : buildingSet)
  254. {
  255. if(!developmentInfo.town->hasBuilt(buildingID) && developmentInfo.town->getTown()->buildings.count(buildingID))
  256. {
  257. developmentInfo.addBuildingToBuild(getBuildingOrPrerequisite(developmentInfo.town, buildingID, armyManager, cc));
  258. break;
  259. }
  260. }
  261. }
  262. }
  263. BuildingInfo BuildAnalyzer::getBuildingOrPrerequisite(
  264. const CGTownInstance * town,
  265. BuildingID b,
  266. std::unique_ptr<ArmyManager> & armyManager,
  267. std::shared_ptr<CCallback> & cc,
  268. bool excludeDwellingDependencies)
  269. {
  270. // TODO: Mircea: Remove redundant variable
  271. BuildingID building = b;
  272. const auto * townInfo = town->getTown();
  273. const auto & buildPtr = townInfo->buildings.at(building);
  274. const CCreature * creature = nullptr;
  275. CreatureID baseCreatureID;
  276. int creatureLevelIndex = -1;
  277. int creatureUpgradeNo = 0;
  278. if(b.isDwelling())
  279. {
  280. creatureLevelIndex = BuildingID::getLevelIndexFromDwelling(b);
  281. creatureUpgradeNo = BuildingID::getUpgradeNoFromDwelling(b);
  282. }
  283. else if(b == BuildingID::HORDE_1 || b == BuildingID::HORDE_1_UPGR)
  284. {
  285. creatureLevelIndex = townInfo->hordeLvl.at(0);
  286. }
  287. else if(b == BuildingID::HORDE_2 || b == BuildingID::HORDE_2_UPGR)
  288. {
  289. creatureLevelIndex = townInfo->hordeLvl.at(1);
  290. }
  291. if(creatureLevelIndex >= 0)
  292. {
  293. auto creatures = townInfo->creatures.at(creatureLevelIndex);
  294. auto creatureID = creatures.size() > creatureUpgradeNo
  295. ? creatures.at(creatureUpgradeNo)
  296. : creatures.front();
  297. baseCreatureID = creatures.front();
  298. creature = creatureID.toCreature();
  299. }
  300. auto info = BuildingInfo(buildPtr.get(), creature, baseCreatureID, town, armyManager);
  301. //logAi->trace("checking %s buildInfo %s", info.name, info.toString());
  302. int highestFort = 0;
  303. for (const auto * ti : cc->getTownsInfo())
  304. {
  305. highestFort = std::max(highestFort, static_cast<int>(ti->fortLevel()));
  306. }
  307. if(!town->hasBuilt(building))
  308. {
  309. auto canBuild = cc->canBuildStructure(town, building);
  310. if(canBuild == EBuildingState::ALLOWED)
  311. {
  312. info.isBuildable = true;
  313. }
  314. else if(canBuild == EBuildingState::NO_RESOURCES)
  315. {
  316. //logAi->trace("cant build. Not enough resources. Need %s", info.buildCost.toString());
  317. info.isMissingResources = true;
  318. }
  319. else if(canBuild == EBuildingState::PREREQUIRES)
  320. {
  321. auto buildExpression = town->genBuildingRequirements(building, false);
  322. auto missingBuildings = buildExpression.getFulfillmentCandidates([&](const BuildingID & id) -> bool
  323. {
  324. return town->hasBuilt(id);
  325. });
  326. auto otherDwelling = [](const BuildingID & id) -> bool
  327. {
  328. return id.isDwelling();
  329. };
  330. if(vstd::contains_if(missingBuildings, otherDwelling))
  331. {
  332. #if NK2AI_TRACE_LEVEL >= 1
  333. logAi->trace("Can't build %d. Needs other dwelling %d", b.getNum(), missingBuildings.front().getNum());
  334. #endif
  335. }
  336. else if(missingBuildings[0] != b)
  337. {
  338. #if NK2AI_TRACE_LEVEL >= 1
  339. logAi->trace("Can't build %d. Needs %d", b.getNum(), missingBuildings[0].num);
  340. #endif
  341. BuildingInfo prerequisite = getBuildingOrPrerequisite(town, missingBuildings[0], armyManager, cc, excludeDwellingDependencies);
  342. prerequisite.buildCostWithPrerequisites += info.buildCost;
  343. prerequisite.creatureUnitCost = info.creatureUnitCost;
  344. prerequisite.creatureGrowth = info.creatureGrowth;
  345. prerequisite.creatureLevel = info.creatureLevel;
  346. prerequisite.creatureID = info.creatureID;
  347. prerequisite.baseCreatureID = info.baseCreatureID;
  348. prerequisite.prerequisitesCount++;
  349. prerequisite.armyCost = info.armyCost;
  350. prerequisite.armyStrength = info.armyStrength;
  351. bool haveSameOrBetterFort = false;
  352. if (prerequisite.id == BuildingID::FORT && highestFort >= CGTownInstance::EFortLevel::FORT)
  353. haveSameOrBetterFort = true;
  354. if (prerequisite.id == BuildingID::CITADEL && highestFort >= CGTownInstance::EFortLevel::CITADEL)
  355. haveSameOrBetterFort = true;
  356. if (prerequisite.id == BuildingID::CASTLE && highestFort >= CGTownInstance::EFortLevel::CASTLE)
  357. haveSameOrBetterFort = true;
  358. if(!haveSameOrBetterFort)
  359. prerequisite.dailyIncome = info.dailyIncome;
  360. return prerequisite;
  361. }
  362. else
  363. {
  364. #if NK2AI_TRACE_LEVEL >= 1
  365. logAi->trace("Can't build. The building requires itself as prerequisite");
  366. #endif
  367. return info;
  368. }
  369. }
  370. else
  371. {
  372. #if NK2AI_TRACE_LEVEL >= 1
  373. logAi->trace("Can't build. Reason: %d", static_cast<int>(canBuild));
  374. #endif
  375. }
  376. }
  377. else
  378. {
  379. #if NK2AI_TRACE_LEVEL >= 1
  380. logAi->trace("Dwelling %d exists", b.getNum());
  381. #endif
  382. info.isBuilt = true;
  383. }
  384. return info;
  385. }
  386. TResource BuildAnalyzer::goldApproximate(const TResources & res)
  387. {
  388. // TODO: Would it make sense to use the marketplace rate of the player? See Nullkiller::handleTrading()
  389. return res[EGameResID::GOLD]
  390. + 75 * (res[EGameResID::WOOD] + res[EGameResID::ORE])
  391. + 125 * (res[EGameResID::GEMS] + res[EGameResID::CRYSTAL] + res[EGameResID::MERCURY] + res[EGameResID::SULFUR]);
  392. }
  393. TResources BuildAnalyzer::goldRemove(TResources other)
  394. {
  395. TResources copy;
  396. for(int i = 0; i < GameResID::COUNT; ++i)
  397. copy[i] = other[i];
  398. copy[GameResID::GOLD] = 0;
  399. return copy;
  400. }
  401. TResources BuildAnalyzer::goldOnly(TResources other)
  402. {
  403. TResources copy;
  404. copy[GameResID::GOLD] = other[GameResID::GOLD];
  405. return copy;
  406. }
  407. }