BuildAnalyzer.cpp 13 KB

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