BuildAnalyzer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. float economyDevelopmentCost = 0;
  120. for(const CGTownInstance* town : towns)
  121. {
  122. logAi->trace("Checking town %s", town->getNameTranslated());
  123. developmentInfos.push_back(TownDevelopmentInfo(town));
  124. TownDevelopmentInfo & developmentInfo = developmentInfos.back();
  125. updateTownDwellings(developmentInfo);
  126. updateOtherBuildings(developmentInfo);
  127. requiredResources += developmentInfo.requiredResources;
  128. totalDevelopmentCost += developmentInfo.townDevelopmentCost;
  129. for(auto building : developmentInfo.toBuild)
  130. {
  131. if (building.dailyIncome[EGameResID::GOLD] > 0)
  132. economyDevelopmentCost += building.buildCostWithPrerequisites[EGameResID::GOLD];
  133. }
  134. armyCost += developmentInfo.armyCost;
  135. for(auto bi : developmentInfo.toBuild)
  136. {
  137. logAi->trace("Building preferences %s", bi.toString());
  138. }
  139. }
  140. std::sort(developmentInfos.begin(), developmentInfos.end(), [](const TownDevelopmentInfo & t1, const TownDevelopmentInfo & t2) -> bool
  141. {
  142. auto val1 = convertToGold(t1.armyCost) - convertToGold(t1.townDevelopmentCost);
  143. auto val2 = convertToGold(t2.armyCost) - convertToGold(t2.townDevelopmentCost);
  144. return val1 > val2;
  145. });
  146. updateDailyIncome();
  147. goldPressure = ai->getLockedResources()[EGameResID::GOLD] / 5000.0f
  148. + ((float)armyCost[EGameResID::GOLD] + economyDevelopmentCost) / (1 + 2 * ai->getFreeGold() + (float)dailyIncome[EGameResID::GOLD] * 7.0f);
  149. logAi->trace("Gold pressure: %f", goldPressure);
  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->town;
  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(BuildingID::DWELL_FIRST <= toBuild && toBuild <= BuildingID::DWELL_UP_LAST)
  171. {
  172. creatureLevel = (toBuild - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  173. creatureUpgrade = (toBuild - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  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", info.name);
  194. logAi->trace("buildInfo %s", info.toString());
  195. int highestFort = 0;
  196. for (auto twn : ai->cb->getTownsInfo())
  197. {
  198. highestFort = std::max(highestFort, (int)twn->fortLevel());
  199. }
  200. if(!town->hasBuilt(building))
  201. {
  202. auto canBuild = ai->cb->canBuildStructure(town, building);
  203. if(canBuild == EBuildingState::ALLOWED)
  204. {
  205. info.canBuild = true;
  206. }
  207. else if(canBuild == EBuildingState::NO_RESOURCES)
  208. {
  209. logAi->trace("cant build. Not enough resources. Need %s", info.buildCost.toString());
  210. info.notEnoughRes = true;
  211. }
  212. else if(canBuild == EBuildingState::PREREQUIRES)
  213. {
  214. auto buildExpression = town->genBuildingRequirements(building, false);
  215. auto missingBuildings = buildExpression.getFulfillmentCandidates([&](const BuildingID & id) -> bool
  216. {
  217. return town->hasBuilt(id);
  218. });
  219. auto otherDwelling = [](const BuildingID & id) -> bool
  220. {
  221. return BuildingID::DWELL_FIRST <= id && id <= BuildingID::DWELL_UP_LAST;
  222. };
  223. if(vstd::contains_if(missingBuildings, otherDwelling))
  224. {
  225. logAi->trace("cant build. Need other dwelling");
  226. }
  227. else if(missingBuildings[0] != toBuild)
  228. {
  229. logAi->trace("cant build. Need %d", missingBuildings[0].num);
  230. BuildingInfo prerequisite = getBuildingOrPrerequisite(town, missingBuildings[0], excludeDwellingDependencies);
  231. prerequisite.buildCostWithPrerequisites += info.buildCost;
  232. prerequisite.creatureCost = info.creatureCost;
  233. prerequisite.creatureGrows = info.creatureGrows;
  234. prerequisite.creatureLevel = info.creatureLevel;
  235. prerequisite.creatureID = info.creatureID;
  236. prerequisite.baseCreatureID = info.baseCreatureID;
  237. prerequisite.prerequisitesCount++;
  238. prerequisite.armyCost = info.armyCost;
  239. bool haveSameOrBetterFort = false;
  240. if (prerequisite.id == BuildingID::FORT && highestFort >= CGTownInstance::EFortLevel::FORT)
  241. haveSameOrBetterFort = true;
  242. if (prerequisite.id == BuildingID::CITADEL && highestFort >= CGTownInstance::EFortLevel::CITADEL)
  243. haveSameOrBetterFort = true;
  244. if (prerequisite.id == BuildingID::CASTLE && highestFort >= CGTownInstance::EFortLevel::CASTLE)
  245. haveSameOrBetterFort = true;
  246. if(!haveSameOrBetterFort)
  247. prerequisite.dailyIncome = info.dailyIncome;
  248. return prerequisite;
  249. }
  250. else
  251. {
  252. logAi->trace("Cant build. The building requires itself as prerequisite");
  253. return info;
  254. }
  255. }
  256. }
  257. else
  258. {
  259. logAi->trace("exists");
  260. info.exists = true;
  261. }
  262. return info;
  263. }
  264. void BuildAnalyzer::updateDailyIncome()
  265. {
  266. auto objects = ai->cb->getMyObjects();
  267. auto towns = ai->cb->getTownsInfo();
  268. dailyIncome = TResources();
  269. for(const CGObjectInstance* obj : objects)
  270. {
  271. const CGMine* mine = dynamic_cast<const CGMine*>(obj);
  272. if(mine)
  273. {
  274. dailyIncome[mine->producedResource.getNum()] += mine->getProducedQuantity();
  275. }
  276. }
  277. for(const CGTownInstance* town : towns)
  278. {
  279. dailyIncome += town->dailyIncome();
  280. }
  281. }
  282. bool BuildAnalyzer::hasAnyBuilding(int32_t alignment, BuildingID bid) const
  283. {
  284. for(auto tdi : developmentInfos)
  285. {
  286. if(tdi.town->getFaction() == alignment && tdi.town->hasBuilt(bid))
  287. return true;
  288. }
  289. return false;
  290. }
  291. void TownDevelopmentInfo::addExistingDwelling(const BuildingInfo & existingDwelling)
  292. {
  293. existingDwellings.push_back(existingDwelling);
  294. armyCost += existingDwelling.armyCost;
  295. armyStrength += existingDwelling.armyStrength;
  296. }
  297. void TownDevelopmentInfo::addBuildingToBuild(const BuildingInfo & nextToBuild)
  298. {
  299. townDevelopmentCost += nextToBuild.buildCostWithPrerequisites;
  300. townDevelopmentCost += withoutGold(nextToBuild.armyCost);
  301. if(nextToBuild.canBuild)
  302. {
  303. hasSomethingToBuild = true;
  304. toBuild.push_back(nextToBuild);
  305. }
  306. else if(nextToBuild.notEnoughRes)
  307. {
  308. requiredResources += nextToBuild.buildCost;
  309. hasSomethingToBuild = true;
  310. toBuild.push_back(nextToBuild);
  311. }
  312. }
  313. BuildingInfo::BuildingInfo()
  314. {
  315. id = BuildingID::NONE;
  316. creatureGrows = 0;
  317. creatureID = CreatureID::NONE;
  318. buildCost = 0;
  319. buildCostWithPrerequisites = 0;
  320. prerequisitesCount = 0;
  321. name.clear();
  322. armyStrength = 0;
  323. }
  324. BuildingInfo::BuildingInfo(
  325. const CBuilding * building,
  326. const CCreature * creature,
  327. CreatureID baseCreature,
  328. const CGTownInstance * town,
  329. Nullkiller * ai)
  330. {
  331. id = building->bid;
  332. buildCost = building->resources;
  333. buildCostWithPrerequisites = building->resources;
  334. dailyIncome = building->produce;
  335. exists = town->hasBuilt(id);
  336. prerequisitesCount = 1;
  337. name = building->getNameTranslated();
  338. if(creature)
  339. {
  340. creatureGrows = creature->getGrowth();
  341. creatureID = creature->getId();
  342. creatureCost = creature->getFullRecruitCost();
  343. creatureLevel = creature->getLevel();
  344. baseCreatureID = baseCreature;
  345. if(exists)
  346. {
  347. creatureGrows = town->creatureGrowth(creatureLevel - 1);
  348. }
  349. else
  350. {
  351. if(BuildingID::DWELL_FIRST <= id && id <= BuildingID::DWELL_UP_LAST)
  352. {
  353. creatureGrows = creature->getGrowth();
  354. if(town->hasBuilt(BuildingID::CASTLE))
  355. creatureGrows *= 2;
  356. else if(town->hasBuilt(BuildingID::CITADEL))
  357. creatureGrows += creatureGrows / 2;
  358. }
  359. else
  360. {
  361. creatureGrows = creature->getHorde();
  362. }
  363. }
  364. armyStrength = ai->armyManager->evaluateStackPower(creature, creatureGrows);
  365. armyCost = creatureCost * creatureGrows;
  366. }
  367. else
  368. {
  369. creatureGrows = 0;
  370. creatureID = CreatureID::NONE;
  371. baseCreatureID = CreatureID::NONE;
  372. creatureCost = TResources();
  373. armyCost = TResources();
  374. creatureLevel = 0;
  375. armyStrength = 0;
  376. }
  377. }
  378. std::string BuildingInfo::toString() const
  379. {
  380. return name + ", cost: " + buildCost.toString()
  381. + ", creature: " + std::to_string(creatureGrows) + " x " + std::to_string(creatureLevel)
  382. + " x " + creatureCost.toString()
  383. + ", daily: " + dailyIncome.toString();
  384. }
  385. }