BuildAnalyzer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. namespace NKAI
  15. {
  16. void BuildAnalyzer::updateTownDwellings(TownDevelopmentInfo & developmentInfo)
  17. {
  18. auto townInfo = developmentInfo.town->town;
  19. auto creatures = townInfo->creatures;
  20. auto buildings = townInfo->getAllBuildings();
  21. std::map<BuildingID, BuildingID> parentMap;
  22. for(auto &pair : townInfo->buildings)
  23. {
  24. if(pair.second->upgrade != BuildingID::NONE)
  25. {
  26. parentMap[pair.second->upgrade] = pair.first;
  27. }
  28. }
  29. BuildingID prefixes[] = {BuildingID::DWELL_UP_FIRST, BuildingID::DWELL_FIRST};
  30. for(int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  31. {
  32. logAi->trace("Checking dwelling level %d", level);
  33. BuildingInfo nextToBuild = BuildingInfo();
  34. for(BuildingID prefix : prefixes)
  35. {
  36. BuildingID building = BuildingID(prefix + level);
  37. if(!vstd::contains(buildings, building))
  38. continue; // no such building in town
  39. auto info = getBuildingOrPrerequisite(developmentInfo.town, building);
  40. if(info.exists)
  41. {
  42. developmentInfo.addExistingDwelling(info);
  43. break;
  44. }
  45. nextToBuild = info;
  46. }
  47. if(nextToBuild.id != BuildingID::NONE)
  48. {
  49. developmentInfo.addBuildingToBuild(nextToBuild);
  50. }
  51. }
  52. }
  53. void BuildAnalyzer::updateOtherBuildings(TownDevelopmentInfo & developmentInfo)
  54. {
  55. logAi->trace("Checking other buildings");
  56. std::vector<std::vector<BuildingID>> otherBuildings = {
  57. {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL},
  58. {BuildingID::MAGES_GUILD_3, BuildingID::MAGES_GUILD_5}
  59. };
  60. if(developmentInfo.existingDwellings.size() >= 2 && ai->cb->getDate(Date::DAY_OF_WEEK) > boost::date_time::Friday)
  61. {
  62. otherBuildings.push_back({BuildingID::HORDE_1});
  63. otherBuildings.push_back({BuildingID::HORDE_2});
  64. }
  65. otherBuildings.push_back({ BuildingID::CITADEL, BuildingID::CASTLE });
  66. otherBuildings.push_back({ BuildingID::RESOURCE_SILO });
  67. otherBuildings.push_back({ BuildingID::SPECIAL_1 });
  68. otherBuildings.push_back({ BuildingID::SPECIAL_2 });
  69. otherBuildings.push_back({ BuildingID::SPECIAL_3 });
  70. otherBuildings.push_back({ BuildingID::SPECIAL_4 });
  71. otherBuildings.push_back({ BuildingID::MARKETPLACE });
  72. for(auto & buildingSet : otherBuildings)
  73. {
  74. for(auto & buildingID : buildingSet)
  75. {
  76. if(!developmentInfo.town->hasBuilt(buildingID) && developmentInfo.town->town->buildings.count(buildingID))
  77. {
  78. developmentInfo.addBuildingToBuild(getBuildingOrPrerequisite(developmentInfo.town, buildingID));
  79. break;
  80. }
  81. }
  82. }
  83. }
  84. int32_t convertToGold(const TResources & res)
  85. {
  86. return res[EGameResID::GOLD]
  87. + 75 * (res[EGameResID::WOOD] + res[EGameResID::ORE])
  88. + 125 * (res[EGameResID::GEMS] + res[EGameResID::CRYSTAL] + res[EGameResID::MERCURY] + res[EGameResID::SULFUR]);
  89. }
  90. TResources withoutGold(TResources other)
  91. {
  92. other[GameResID::GOLD] = 0;
  93. return other;
  94. }
  95. TResources BuildAnalyzer::getResourcesRequiredNow() const
  96. {
  97. auto resourcesAvailable = ai->getFreeResources();
  98. auto result = withoutGold(armyCost) + requiredResources - resourcesAvailable;
  99. result.positive();
  100. return result;
  101. }
  102. TResources BuildAnalyzer::getTotalResourcesRequired() const
  103. {
  104. auto resourcesAvailable = ai->getFreeResources();
  105. auto result = totalDevelopmentCost + withoutGold(armyCost) - resourcesAvailable;
  106. result.positive();
  107. return result;
  108. }
  109. bool BuildAnalyzer::isGoldPressureHigh() const
  110. {
  111. return goldPressure > ai->settings->getMaxGoldPressure();
  112. }
  113. void BuildAnalyzer::update()
  114. {
  115. logAi->trace("Start analysing build");
  116. BuildingInfo bi;
  117. reset();
  118. auto towns = ai->cb->getTownsInfo();
  119. for(const CGTownInstance* town : towns)
  120. {
  121. logAi->trace("Checking town %s", town->getNameTranslated());
  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. armyCost += developmentInfo.armyCost;
  129. for(auto bi : developmentInfo.toBuild)
  130. {
  131. logAi->trace("Building preferences %s", bi.toString());
  132. }
  133. }
  134. std::sort(developmentInfos.begin(), developmentInfos.end(), [](const TownDevelopmentInfo & t1, const TownDevelopmentInfo & t2) -> bool
  135. {
  136. auto val1 = convertToGold(t1.armyCost) - convertToGold(t1.townDevelopmentCost);
  137. auto val2 = convertToGold(t2.armyCost) - convertToGold(t2.townDevelopmentCost);
  138. return val1 > val2;
  139. });
  140. updateDailyIncome();
  141. goldPressure = ai->getLockedResources()[EGameResID::GOLD] / 5000.0f
  142. + (float)armyCost[EGameResID::GOLD] / (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->town;
  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(BuildingID::DWELL_FIRST <= toBuild && toBuild <= BuildingID::DWELL_UP_LAST)
  165. {
  166. creatureLevel = (toBuild - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  167. creatureUpgrade = (toBuild - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  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", info.name);
  188. logAi->trace("buildInfo %s", info.toString());
  189. if(!town->hasBuilt(building))
  190. {
  191. auto canBuild = ai->cb->canBuildStructure(town, building);
  192. if(canBuild == EBuildingState::ALLOWED)
  193. {
  194. info.canBuild = true;
  195. }
  196. else if(canBuild == EBuildingState::NO_RESOURCES)
  197. {
  198. logAi->trace("cant build. Not enough resources. Need %s", info.buildCost.toString());
  199. info.notEnoughRes = true;
  200. }
  201. else if(canBuild == EBuildingState::PREREQUIRES)
  202. {
  203. auto buildExpression = town->genBuildingRequirements(building, false);
  204. auto missingBuildings = buildExpression.getFulfillmentCandidates([&](const BuildingID & id) -> bool
  205. {
  206. return town->hasBuilt(id);
  207. });
  208. auto otherDwelling = [](const BuildingID & id) -> bool
  209. {
  210. return BuildingID::DWELL_FIRST <= id && id <= BuildingID::DWELL_UP_LAST;
  211. };
  212. if(vstd::contains_if(missingBuildings, otherDwelling))
  213. {
  214. logAi->trace("cant build. Need other dwelling");
  215. }
  216. else if(missingBuildings[0] != toBuild)
  217. {
  218. logAi->trace("cant build. Need %d", missingBuildings[0].num);
  219. BuildingInfo prerequisite = getBuildingOrPrerequisite(town, missingBuildings[0], excludeDwellingDependencies);
  220. prerequisite.buildCostWithPrerequisites += info.buildCost;
  221. prerequisite.creatureCost = info.creatureCost;
  222. prerequisite.creatureGrows = info.creatureGrows;
  223. prerequisite.creatureLevel = info.creatureLevel;
  224. prerequisite.creatureID = info.creatureID;
  225. prerequisite.baseCreatureID = info.baseCreatureID;
  226. prerequisite.prerequisitesCount++;
  227. prerequisite.armyCost = info.armyCost;
  228. prerequisite.dailyIncome = info.dailyIncome;
  229. return prerequisite;
  230. }
  231. else
  232. {
  233. logAi->trace("Cant build. The building requires itself as prerequisite");
  234. return info;
  235. }
  236. }
  237. }
  238. else
  239. {
  240. logAi->trace("exists");
  241. info.exists = true;
  242. }
  243. return info;
  244. }
  245. void BuildAnalyzer::updateDailyIncome()
  246. {
  247. auto objects = ai->cb->getMyObjects();
  248. auto towns = ai->cb->getTownsInfo();
  249. dailyIncome = TResources();
  250. for(const CGObjectInstance* obj : objects)
  251. {
  252. const CGMine* mine = dynamic_cast<const CGMine*>(obj);
  253. if(mine)
  254. {
  255. dailyIncome[mine->producedResource.getNum()] += mine->producedQuantity;
  256. }
  257. }
  258. for(const CGTownInstance* town : towns)
  259. {
  260. dailyIncome += town->dailyIncome();
  261. }
  262. }
  263. bool BuildAnalyzer::hasAnyBuilding(int32_t alignment, BuildingID bid) const
  264. {
  265. for(auto tdi : developmentInfos)
  266. {
  267. if(tdi.town->getFaction() == alignment && tdi.town->hasBuilt(bid))
  268. return true;
  269. }
  270. return false;
  271. }
  272. void TownDevelopmentInfo::addExistingDwelling(const BuildingInfo & existingDwelling)
  273. {
  274. existingDwellings.push_back(existingDwelling);
  275. armyCost += existingDwelling.armyCost;
  276. armyStrength += existingDwelling.armyStrength;
  277. }
  278. void TownDevelopmentInfo::addBuildingToBuild(const BuildingInfo & nextToBuild)
  279. {
  280. townDevelopmentCost += nextToBuild.buildCostWithPrerequisites;
  281. townDevelopmentCost += withoutGold(nextToBuild.armyCost);
  282. if(nextToBuild.canBuild)
  283. {
  284. hasSomethingToBuild = true;
  285. toBuild.push_back(nextToBuild);
  286. }
  287. else if(nextToBuild.notEnoughRes)
  288. {
  289. requiredResources += nextToBuild.buildCost;
  290. hasSomethingToBuild = true;
  291. toBuild.push_back(nextToBuild);
  292. }
  293. }
  294. BuildingInfo::BuildingInfo()
  295. {
  296. id = BuildingID::NONE;
  297. creatureGrows = 0;
  298. creatureID = CreatureID::NONE;
  299. buildCost = 0;
  300. buildCostWithPrerequisites = 0;
  301. prerequisitesCount = 0;
  302. name.clear();
  303. armyStrength = 0;
  304. }
  305. BuildingInfo::BuildingInfo(
  306. const CBuilding * building,
  307. const CCreature * creature,
  308. CreatureID baseCreature,
  309. const CGTownInstance * town,
  310. Nullkiller * ai)
  311. {
  312. id = building->bid;
  313. buildCost = building->resources;
  314. buildCostWithPrerequisites = building->resources;
  315. dailyIncome = building->produce;
  316. exists = town->hasBuilt(id);
  317. prerequisitesCount = 1;
  318. name = building->getNameTranslated();
  319. if(creature)
  320. {
  321. creatureGrows = creature->getGrowth();
  322. creatureID = creature->getId();
  323. creatureCost = creature->getFullRecruitCost();
  324. creatureLevel = creature->getLevel();
  325. baseCreatureID = baseCreature;
  326. if(exists)
  327. {
  328. creatureGrows = town->creatureGrowth(creatureLevel - 1);
  329. }
  330. else
  331. {
  332. if(BuildingID::DWELL_FIRST <= id && id <= BuildingID::DWELL_UP_LAST)
  333. {
  334. creatureGrows = creature->getGrowth();
  335. if(town->hasBuilt(BuildingID::CASTLE))
  336. creatureGrows *= 2;
  337. else if(town->hasBuilt(BuildingID::CITADEL))
  338. creatureGrows += creatureGrows / 2;
  339. }
  340. else
  341. {
  342. creatureGrows = creature->getHorde();
  343. }
  344. }
  345. armyStrength = ai->armyManager->evaluateStackPower(creature, creatureGrows);
  346. armyCost = creatureCost * creatureGrows;
  347. }
  348. else
  349. {
  350. creatureGrows = 0;
  351. creatureID = CreatureID::NONE;
  352. baseCreatureID = CreatureID::NONE;
  353. creatureCost = TResources();
  354. armyCost = TResources();
  355. creatureLevel = 0;
  356. armyStrength = 0;
  357. }
  358. }
  359. std::string BuildingInfo::toString() const
  360. {
  361. return name + ", cost: " + buildCost.toString()
  362. + ", creature: " + std::to_string(creatureGrows) + " x " + std::to_string(creatureLevel)
  363. + " x " + creatureCost.toString()
  364. + ", daily: " + dailyIncome.toString();
  365. }
  366. }