ArmyManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /*
  2. * BuildingManager.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 "ArmyManager.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../../../CCallback.h"
  14. #include "../../../lib/mapObjects/MapObjects.h"
  15. class StackUpgradeInfo
  16. {
  17. public:
  18. CreatureID initialCreature;
  19. CreatureID upgradedCreature;
  20. TResources cost;
  21. int count;
  22. uint64_t upgradeValue;
  23. StackUpgradeInfo(CreatureID initial, CreatureID upgraded, int count)
  24. :initialCreature(initial), upgradedCreature(upgraded), count(count)
  25. {
  26. cost = (upgradedCreature.toCreature()->cost - initialCreature.toCreature()->cost) * count;
  27. upgradeValue = (upgradedCreature.toCreature()->AIValue - initialCreature.toCreature()->AIValue) * count;
  28. }
  29. };
  30. uint64_t ArmyManager::howManyReinforcementsCanGet(const CGHeroInstance * hero, const CCreatureSet * source) const
  31. {
  32. return howManyReinforcementsCanGet(hero, hero, source);
  33. }
  34. std::vector<SlotInfo> ArmyManager::getSortedSlots(const CCreatureSet * target, const CCreatureSet * source) const
  35. {
  36. const CCreatureSet * armies[] = { target, source };
  37. //we calculate total strength for each creature type available in armies
  38. std::map<const CCreature *, SlotInfo> creToPower;
  39. std::vector<SlotInfo> resultingArmy;
  40. for(auto armyPtr : armies)
  41. {
  42. for(auto & i : armyPtr->Slots())
  43. {
  44. auto & slotInfp = creToPower[i.second->type];
  45. slotInfp.creature = i.second->type;
  46. slotInfp.power += i.second->getPower();
  47. slotInfp.count += i.second->count;
  48. }
  49. }
  50. for(auto pair : creToPower)
  51. resultingArmy.push_back(pair.second);
  52. boost::sort(resultingArmy, [](const SlotInfo & left, const SlotInfo & right) -> bool
  53. {
  54. return left.power > right.power;
  55. });
  56. return resultingArmy;
  57. }
  58. std::vector<SlotInfo>::iterator ArmyManager::getWeakestCreature(std::vector<SlotInfo> & army) const
  59. {
  60. auto weakest = boost::min_element(army, [](const SlotInfo & left, const SlotInfo & right) -> bool
  61. {
  62. if(left.creature->level != right.creature->level)
  63. return left.creature->level < right.creature->level;
  64. return left.creature->Speed() > right.creature->Speed();
  65. });
  66. return weakest;
  67. }
  68. class TemporaryArmy : public CArmedInstance
  69. {
  70. public:
  71. void armyChanged() override {}
  72. };
  73. std::vector<SlotInfo> ArmyManager::getBestArmy(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  74. {
  75. auto sortedSlots = getSortedSlots(target, source);
  76. std::map<TFaction, uint64_t> alignmentMap;
  77. for(auto & slot : sortedSlots)
  78. {
  79. alignmentMap[slot.creature->faction] += slot.power;
  80. }
  81. std::set<TFaction> allowedFactions;
  82. std::vector<SlotInfo> resultingArmy;
  83. uint64_t armyValue = 0;
  84. TemporaryArmy newArmyInstance;
  85. auto bonusModifiers = armyCarrier->getBonuses(Selector::type()(Bonus::MORALE));
  86. for(auto bonus : *bonusModifiers)
  87. {
  88. // army bonuses will change and object bonuses are temporary
  89. if(bonus->source != Bonus::ARMY || bonus->source != Bonus::OBJECT)
  90. {
  91. newArmyInstance.addNewBonus(bonus);
  92. }
  93. }
  94. while(allowedFactions.size() < alignmentMap.size())
  95. {
  96. auto strongestAlignment = vstd::maxElementByFun(alignmentMap, [&](std::pair<TFaction, uint64_t> pair) -> uint64_t
  97. {
  98. return vstd::contains(allowedFactions, pair.first) ? 0 : pair.second;
  99. });
  100. allowedFactions.insert(strongestAlignment->first);
  101. std::vector<SlotInfo> newArmy;
  102. uint64_t newValue = 0;
  103. newArmyInstance.clear();
  104. for(auto & slot : sortedSlots)
  105. {
  106. if(vstd::contains(allowedFactions, slot.creature->faction))
  107. {
  108. auto slotID = newArmyInstance.getSlotFor(slot.creature);
  109. if(slotID.validSlot())
  110. {
  111. newArmyInstance.setCreature(slotID, slot.creature->idNumber, slot.count);
  112. newArmy.push_back(slot);
  113. }
  114. }
  115. }
  116. newArmyInstance.updateMoraleBonusFromArmy();
  117. for(auto & slot : newArmyInstance.Slots())
  118. {
  119. auto morale = slot.second->MoraleVal();
  120. auto multiplier = 1.0f;
  121. if(morale < 0)
  122. {
  123. multiplier += morale * 0.083f;
  124. }
  125. else if(morale > 0)
  126. {
  127. multiplier += morale * 0.04f;
  128. }
  129. newValue += multiplier * slot.second->getPower();
  130. }
  131. if(armyValue >= newValue)
  132. {
  133. break;
  134. }
  135. resultingArmy = newArmy;
  136. armyValue = newValue;
  137. }
  138. if(resultingArmy.size() <= GameConstants::ARMY_SIZE
  139. && allowedFactions.size() == alignmentMap.size()
  140. && source->needsLastStack())
  141. {
  142. auto weakest = getWeakestCreature(resultingArmy);
  143. if(weakest->count == 1)
  144. {
  145. resultingArmy.erase(weakest);
  146. }
  147. else
  148. {
  149. weakest->power -= weakest->power / weakest->count;
  150. weakest->count--;
  151. }
  152. }
  153. return resultingArmy;
  154. }
  155. ui64 ArmyManager::howManyReinforcementsCanBuy(const CCreatureSet * h, const CGDwelling * t) const
  156. {
  157. return howManyReinforcementsCanBuy(h, t, cb->getResourceAmount());
  158. }
  159. ui64 ArmyManager::howManyReinforcementsCanBuy(
  160. const CCreatureSet * h,
  161. const CGDwelling * t,
  162. const TResources & availableResources) const
  163. {
  164. ui64 aivalue = 0;
  165. auto army = getArmyAvailableToBuy(h, t, availableResources);
  166. for(const creInfo & ci : army)
  167. {
  168. aivalue += ci.count * ci.cre->AIValue;
  169. }
  170. return aivalue;
  171. }
  172. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  173. {
  174. return getArmyAvailableToBuy(hero, dwelling, cb->getResourceAmount());
  175. }
  176. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling, TResources availableRes) const
  177. {
  178. std::vector<creInfo> creaturesInDwellings;
  179. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  180. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  181. {
  182. auto ci = infoFromDC(dwelling->creatures[i]);
  183. if(!ci.count || ci.creID == -1)
  184. continue;
  185. SlotID dst = hero->getSlotFor(ci.creID);
  186. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  187. {
  188. if(!freeHeroSlots) //no more place for stacks
  189. continue;
  190. else
  191. freeHeroSlots--; //new slot will be occupied
  192. }
  193. vstd::amin(ci.count, availableRes / ci.cre->cost); //max count we can afford
  194. if(!ci.count)
  195. continue;
  196. ci.level = i; //this is important for Dungeon Summoning Portal
  197. creaturesInDwellings.push_back(ci);
  198. availableRes -= ci.cre->cost * ci.count;
  199. }
  200. return creaturesInDwellings;
  201. }
  202. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  203. {
  204. auto bestArmy = getBestArmy(armyCarrier, target, source);
  205. uint64_t newArmy = 0;
  206. uint64_t oldArmy = target->getArmyStrength();
  207. for(auto & slot : bestArmy)
  208. {
  209. newArmy += slot.power;
  210. }
  211. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  212. }
  213. uint64_t ArmyManager::evaluateStackPower(const CCreature * creature, int count) const
  214. {
  215. return creature->AIValue * count;
  216. }
  217. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  218. {
  219. auto creatureInfo = totalArmy.find(creatureID);
  220. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  221. }
  222. void ArmyManager::update()
  223. {
  224. logAi->trace("Start analysing army");
  225. std::vector<const CCreatureSet *> total;
  226. auto heroes = cb->getHeroesInfo();
  227. auto towns = cb->getTownsInfo();
  228. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  229. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  230. totalArmy.clear();
  231. for(auto army : total)
  232. {
  233. for(auto slot : army->Slots())
  234. {
  235. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  236. }
  237. }
  238. for(auto army : totalArmy)
  239. {
  240. army.second.creature = army.first.toCreature();
  241. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  242. }
  243. }
  244. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  245. {
  246. std::vector<SlotInfo> result;
  247. for(auto slot : army->Slots())
  248. {
  249. SlotInfo slotInfo;
  250. slotInfo.creature = slot.second->getCreatureID().toCreature();
  251. slotInfo.count = slot.second->count;
  252. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  253. result.push_back(slotInfo);
  254. }
  255. return result;
  256. }
  257. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  258. {
  259. std::vector<StackUpgradeInfo> upgrades;
  260. for(auto creature : army->Slots())
  261. {
  262. CreatureID initial = creature.second->getCreatureID();
  263. auto possibleUpgrades = initial.toCreature()->upgrades;
  264. if(possibleUpgrades.empty())
  265. continue;
  266. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  267. {
  268. return cre.toCreature()->AIValue;
  269. });
  270. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  271. if(initial.toCreature()->level == 1)
  272. upgrade.cost = TResources();
  273. upgrades.push_back(upgrade);
  274. }
  275. return upgrades;
  276. }
  277. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  278. {
  279. std::vector<StackUpgradeInfo> upgrades;
  280. for(auto creature : army->Slots())
  281. {
  282. CreatureID initial = creature.second->getCreatureID();
  283. auto possibleUpgrades = initial.toCreature()->upgrades;
  284. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  285. {
  286. for(auto pair : dwelling->creatures)
  287. {
  288. if(vstd::contains(pair.second, creID))
  289. return false;
  290. }
  291. return true;
  292. });
  293. if(possibleUpgrades.empty())
  294. continue;
  295. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  296. {
  297. return cre.toCreature()->AIValue;
  298. });
  299. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  300. upgrades.push_back(upgrade);
  301. }
  302. return upgrades;
  303. }
  304. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  305. {
  306. std::vector<StackUpgradeInfo> upgrades;
  307. if(upgrader->ID == Obj::HILL_FORT)
  308. {
  309. upgrades = getHillFortUpgrades(army);
  310. }
  311. else
  312. {
  313. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  314. if(dwelling)
  315. {
  316. upgrades = getDwellingUpgrades(army, dwelling);
  317. }
  318. }
  319. return upgrades;
  320. }
  321. ArmyUpgradeInfo ArmyManager::calculateCreateresUpgrade(
  322. const CCreatureSet * army,
  323. const CGObjectInstance * upgrader,
  324. const TResources & availableResources) const
  325. {
  326. if(!upgrader)
  327. return ArmyUpgradeInfo();
  328. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  329. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  330. {
  331. return !availableResources.canAfford(u.cost);
  332. });
  333. if(upgrades.empty())
  334. return ArmyUpgradeInfo();
  335. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  336. {
  337. return u1.upgradeValue > u2.upgradeValue;
  338. });
  339. TResources resourcesLeft = availableResources;
  340. ArmyUpgradeInfo result;
  341. result.resultingArmy = convertToSlots(army);
  342. for(auto upgrade : upgrades)
  343. {
  344. if(resourcesLeft.canAfford(upgrade.cost))
  345. {
  346. SlotInfo upgradedArmy;
  347. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  348. upgradedArmy.count = upgrade.count;
  349. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  350. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  351. return slot.count == upgradedArmy.count && slot.creature->idNumber == upgrade.initialCreature;
  352. });
  353. resourcesLeft -= upgrade.cost;
  354. result.upgradeCost += upgrade.cost;
  355. result.upgradeValue += upgrade.upgradeValue;
  356. *slotToReplace = upgradedArmy;
  357. }
  358. }
  359. return result;
  360. }