BuildAnalyzer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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::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)
  104. {
  105. toBuild.push_back(bi);
  106. }
  107. else if (bi.isMissingResources)
  108. {
  109. requiredResources += bi.buildCost;
  110. toBuild.push_back(bi);
  111. }
  112. }
  113. BuildingInfo::BuildingInfo() {}
  114. BuildingInfo::BuildingInfo(
  115. const CBuilding * building,
  116. const CCreature * creature,
  117. CreatureID baseCreature,
  118. const CGTownInstance * town,
  119. const std::unique_ptr<ArmyManager> & armyManager)
  120. {
  121. id = building->bid;
  122. buildCost = building->resources;
  123. buildCostWithPrerequisites = building->resources;
  124. dailyIncome = building->produce;
  125. isBuilt = town->hasBuilt(id);
  126. prerequisitesCount = 1;
  127. name = building->getNameTranslated();
  128. if(creature)
  129. {
  130. creatureGrowth = creature->getGrowth();
  131. creatureID = creature->getId();
  132. baseCreatureID = baseCreature;
  133. creatureUnitCost = creature->getFullRecruitCost();
  134. creatureLevel = creature->getLevel();
  135. if(isBuilt)
  136. {
  137. creatureGrowth = town->creatureGrowth(creatureLevel - 1);
  138. }
  139. else
  140. {
  141. if(id.isDwelling())
  142. {
  143. creatureGrowth = creature->getGrowth();
  144. if(town->hasBuilt(BuildingID::CASTLE))
  145. creatureGrowth *= 2;
  146. else if(town->hasBuilt(BuildingID::CITADEL))
  147. creatureGrowth += creatureGrowth / 2;
  148. }
  149. else
  150. {
  151. creatureGrowth = creature->getHorde();
  152. }
  153. }
  154. armyStrength = armyManager->evaluateStackPower(creature, creatureGrowth);
  155. armyCost = creatureUnitCost * creatureGrowth;
  156. }
  157. }
  158. std::string BuildingInfo::toString() const
  159. {
  160. return name + ", cost: " + buildCost.toString()
  161. + ", creature: " + std::to_string(creatureGrowth) + " x " + std::to_string(creatureLevel)
  162. + " x " + creatureUnitCost.toString()
  163. + ", daily: " + dailyIncome.toString();
  164. }
  165. float BuildAnalyzer::calculateGoldPressure(TResource lockedGold, float armyCostGold, float economyDevelopmentCost, float freeGold, float dailyIncomeGold)
  166. {
  167. auto pressure = (lockedGold + armyCostGold + economyDevelopmentCost) / (1 + 2 * freeGold + dailyIncomeGold * 7.0f);
  168. #if NK2AI_TRACE_LEVEL >= 1
  169. logAi->trace("Gold pressure: %f", pressure);
  170. #endif
  171. return pressure;
  172. }
  173. TResources BuildAnalyzer::calculateDailyIncome(const std::vector<const CGObjectInstance *> & objects, const std::vector<const CGTownInstance *> & townInfos)
  174. {
  175. auto result = TResources();
  176. for(const CGObjectInstance * obj : objects)
  177. {
  178. if(const auto * mine = dynamic_cast<const CGMine *>(obj))
  179. result += mine->dailyIncome();
  180. }
  181. for(const CGTownInstance * town : townInfos)
  182. {
  183. result += town->dailyIncome();
  184. }
  185. return result;
  186. }
  187. void BuildAnalyzer::updateDwellings(TownDevelopmentInfo & developmentInfo, std::unique_ptr<ArmyManager> & armyManager, std::shared_ptr<CCallback> & cc)
  188. {
  189. for(int level = 0; level < developmentInfo.town->getTown()->creatures.size(); level++)
  190. {
  191. #if NK2AI_TRACE_LEVEL >= 1
  192. logAi->trace("Checking dwelling level %d", level);
  193. #endif
  194. std::vector<BuildingID> dwellingsInTown;
  195. for(BuildingID buildID = BuildingID::getDwellingFromLevel(level, 0); buildID.hasValue(); BuildingID::advanceDwelling(buildID))
  196. if(developmentInfo.town->getTown()->buildings.count(buildID) != 0)
  197. dwellingsInTown.push_back(buildID);
  198. // find best, already built dwelling
  199. for (const auto & buildID : boost::adaptors::reverse(dwellingsInTown))
  200. {
  201. if (!developmentInfo.town->hasBuilt(buildID))
  202. continue;
  203. const auto & info = getBuildingOrPrerequisite(developmentInfo.town, buildID, armyManager, cc);
  204. developmentInfo.addBuildingBuilt(info);
  205. break;
  206. }
  207. // find all non-built dwellings that can be built and add them for consideration
  208. for (const auto & buildID : dwellingsInTown)
  209. {
  210. if (developmentInfo.town->hasBuilt(buildID))
  211. continue;
  212. const auto & info = getBuildingOrPrerequisite(developmentInfo.town, buildID, armyManager, cc);
  213. if (info.isBuildable || info.isMissingResources)
  214. developmentInfo.addBuildingToBuild(info);
  215. }
  216. }
  217. }
  218. void BuildAnalyzer::updateOtherBuildings(TownDevelopmentInfo & developmentInfo,
  219. std::unique_ptr<ArmyManager> & armyManager,
  220. std::shared_ptr<CCallback> & cc)
  221. {
  222. logAi->trace("Checking other buildings");
  223. std::vector<std::vector<BuildingID>> otherBuildings = {
  224. {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL},
  225. {BuildingID::MAGES_GUILD_3, BuildingID::MAGES_GUILD_5}
  226. };
  227. if(developmentInfo.built.size() >= 2 && cc->getDate(Date::DAY_OF_WEEK) > 4)
  228. {
  229. otherBuildings.push_back({BuildingID::HORDE_1});
  230. otherBuildings.push_back({BuildingID::HORDE_2});
  231. }
  232. otherBuildings.push_back({ BuildingID::CITADEL, BuildingID::CASTLE });
  233. otherBuildings.push_back({ BuildingID::RESOURCE_SILO });
  234. otherBuildings.push_back({ BuildingID::SPECIAL_1 });
  235. otherBuildings.push_back({ BuildingID::SPECIAL_2 });
  236. otherBuildings.push_back({ BuildingID::SPECIAL_3 });
  237. otherBuildings.push_back({ BuildingID::SPECIAL_4 });
  238. otherBuildings.push_back({ BuildingID::MARKETPLACE });
  239. for(auto & buildingSet : otherBuildings)
  240. {
  241. for(auto & buildingID : buildingSet)
  242. {
  243. if(!developmentInfo.town->hasBuilt(buildingID) && developmentInfo.town->getTown()->buildings.count(buildingID))
  244. {
  245. developmentInfo.addBuildingToBuild(getBuildingOrPrerequisite(developmentInfo.town, buildingID, armyManager, cc));
  246. break;
  247. }
  248. }
  249. }
  250. }
  251. BuildingInfo BuildAnalyzer::getBuildingOrPrerequisite(
  252. const CGTownInstance * town,
  253. BuildingID b,
  254. std::unique_ptr<ArmyManager> & armyManager,
  255. std::shared_ptr<CCallback> & cc,
  256. bool excludeDwellingDependencies)
  257. {
  258. // TODO: Mircea: Remove redundant variable
  259. BuildingID building = b;
  260. const auto * townInfo = town->getTown();
  261. const auto & buildPtr = townInfo->buildings.at(building);
  262. const CCreature * creature = nullptr;
  263. CreatureID baseCreatureID;
  264. int creatureLevelIndex = -1;
  265. int creatureUpgradeNo = 0;
  266. if(b.isDwelling())
  267. {
  268. creatureLevelIndex = BuildingID::getLevelIndexFromDwelling(b);
  269. creatureUpgradeNo = BuildingID::getUpgradeNoFromDwelling(b);
  270. }
  271. else if(b == BuildingID::HORDE_1 || b == BuildingID::HORDE_1_UPGR)
  272. {
  273. creatureLevelIndex = townInfo->hordeLvl.at(0);
  274. }
  275. else if(b == BuildingID::HORDE_2 || b == BuildingID::HORDE_2_UPGR)
  276. {
  277. creatureLevelIndex = townInfo->hordeLvl.at(1);
  278. }
  279. if(creatureLevelIndex >= 0)
  280. {
  281. auto creatures = townInfo->creatures.at(creatureLevelIndex);
  282. auto creatureID = creatures.size() > creatureUpgradeNo
  283. ? creatures.at(creatureUpgradeNo)
  284. : creatures.front();
  285. baseCreatureID = creatures.front();
  286. creature = creatureID.toCreature();
  287. }
  288. auto info = BuildingInfo(buildPtr.get(), creature, baseCreatureID, town, armyManager);
  289. //logAi->trace("checking %s buildInfo %s", info.name, info.toString());
  290. int highestFort = 0;
  291. for (const auto * ti : cc->getTownsInfo())
  292. {
  293. highestFort = std::max(highestFort, static_cast<int>(ti->fortLevel()));
  294. }
  295. if(!town->hasBuilt(building))
  296. {
  297. auto canBuild = cc->canBuildStructure(town, building);
  298. if(canBuild == EBuildingState::ALLOWED)
  299. {
  300. info.isBuildable = true;
  301. }
  302. else if(canBuild == EBuildingState::NO_RESOURCES)
  303. {
  304. //logAi->trace("cant build. Not enough resources. Need %s", info.buildCost.toString());
  305. info.isMissingResources = true;
  306. }
  307. else if(canBuild == EBuildingState::PREREQUIRES)
  308. {
  309. auto buildExpression = town->genBuildingRequirements(building, false);
  310. auto missingBuildings = buildExpression.getFulfillmentCandidates([&](const BuildingID & id) -> bool
  311. {
  312. return town->hasBuilt(id);
  313. });
  314. auto otherDwelling = [](const BuildingID & id) -> bool
  315. {
  316. return id.isDwelling();
  317. };
  318. if(vstd::contains_if(missingBuildings, otherDwelling))
  319. {
  320. #if NK2AI_TRACE_LEVEL >= 1
  321. logAi->trace("Can't build %d. Needs other dwelling %d", b.getNum(), missingBuildings.front().getNum());
  322. #endif
  323. }
  324. else if(missingBuildings[0] != b)
  325. {
  326. #if NK2AI_TRACE_LEVEL >= 1
  327. logAi->trace("Can't build %d. Needs %d", b.getNum(), missingBuildings[0].num);
  328. #endif
  329. BuildingInfo prerequisite = getBuildingOrPrerequisite(town, missingBuildings[0], armyManager, cc, excludeDwellingDependencies);
  330. prerequisite.buildCostWithPrerequisites += info.buildCost;
  331. prerequisite.creatureUnitCost = info.creatureUnitCost;
  332. prerequisite.creatureGrowth = info.creatureGrowth;
  333. prerequisite.creatureLevel = info.creatureLevel;
  334. prerequisite.creatureID = info.creatureID;
  335. prerequisite.baseCreatureID = info.baseCreatureID;
  336. prerequisite.prerequisitesCount++;
  337. prerequisite.armyCost = info.armyCost;
  338. prerequisite.armyStrength = info.armyStrength;
  339. bool haveSameOrBetterFort = false;
  340. if (prerequisite.id == BuildingID::FORT && highestFort >= CGTownInstance::EFortLevel::FORT)
  341. haveSameOrBetterFort = true;
  342. if (prerequisite.id == BuildingID::CITADEL && highestFort >= CGTownInstance::EFortLevel::CITADEL)
  343. haveSameOrBetterFort = true;
  344. if (prerequisite.id == BuildingID::CASTLE && highestFort >= CGTownInstance::EFortLevel::CASTLE)
  345. haveSameOrBetterFort = true;
  346. if(!haveSameOrBetterFort)
  347. prerequisite.dailyIncome = info.dailyIncome;
  348. return prerequisite;
  349. }
  350. else
  351. {
  352. #if NK2AI_TRACE_LEVEL >= 1
  353. logAi->trace("Can't build. The building requires itself as prerequisite");
  354. #endif
  355. return info;
  356. }
  357. }
  358. else
  359. {
  360. #if NK2AI_TRACE_LEVEL >= 1
  361. logAi->trace("Can't build. Reason: %d", static_cast<int>(canBuild));
  362. #endif
  363. }
  364. }
  365. else
  366. {
  367. #if NK2AI_TRACE_LEVEL >= 1
  368. logAi->trace("Dwelling %d exists", b.getNum());
  369. #endif
  370. info.isBuilt = true;
  371. }
  372. return info;
  373. }
  374. int32_t BuildAnalyzer::approximateInGold(const TResources & res)
  375. {
  376. // TODO: Would it make sense to use the marketplace rate of the player?
  377. return res[EGameResID::GOLD]
  378. + 75 * (res[EGameResID::WOOD] + res[EGameResID::ORE])
  379. + 125 * (res[EGameResID::GEMS] + res[EGameResID::CRYSTAL] + res[EGameResID::MERCURY] + res[EGameResID::SULFUR]);
  380. }
  381. TResources BuildAnalyzer::withoutGold(TResources other)
  382. {
  383. // TODO: Mircea: Potential issue modifying the input directly? To inspect
  384. other[GameResID::GOLD] = 0;
  385. return other;
  386. }
  387. }