BuildAnalyzer.cpp 12 KB

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