BuildAnalyzer.cpp 13 KB

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