ArmyManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. TemporaryArmy()
  73. :CArmedInstance(true)
  74. {
  75. }
  76. };
  77. std::vector<SlotInfo> ArmyManager::getBestArmy(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  78. {
  79. auto sortedSlots = getSortedSlots(target, source);
  80. std::map<TFaction, uint64_t> alignmentMap;
  81. for(auto & slot : sortedSlots)
  82. {
  83. alignmentMap[slot.creature->faction] += slot.power;
  84. }
  85. std::set<TFaction> allowedFactions;
  86. std::vector<SlotInfo> resultingArmy;
  87. uint64_t armyValue = 0;
  88. TemporaryArmy newArmyInstance;
  89. auto bonusModifiers = armyCarrier->getBonuses(Selector::type()(Bonus::MORALE));
  90. for(auto bonus : *bonusModifiers)
  91. {
  92. // army bonuses will change and object bonuses are temporary
  93. if(bonus->source != Bonus::ARMY || bonus->source != Bonus::OBJECT)
  94. {
  95. newArmyInstance.addNewBonus(std::make_shared<Bonus>(*bonus));
  96. }
  97. }
  98. while(allowedFactions.size() < alignmentMap.size())
  99. {
  100. auto strongestAlignment = vstd::maxElementByFun(alignmentMap, [&](std::pair<TFaction, uint64_t> pair) -> uint64_t
  101. {
  102. return vstd::contains(allowedFactions, pair.first) ? 0 : pair.second;
  103. });
  104. allowedFactions.insert(strongestAlignment->first);
  105. std::vector<SlotInfo> newArmy;
  106. uint64_t newValue = 0;
  107. newArmyInstance.clear();
  108. for(auto & slot : sortedSlots)
  109. {
  110. if(vstd::contains(allowedFactions, slot.creature->faction))
  111. {
  112. auto slotID = newArmyInstance.getSlotFor(slot.creature);
  113. if(slotID.validSlot())
  114. {
  115. newArmyInstance.setCreature(slotID, slot.creature->idNumber, slot.count);
  116. newArmy.push_back(slot);
  117. }
  118. }
  119. }
  120. newArmyInstance.updateMoraleBonusFromArmy();
  121. for(auto & slot : newArmyInstance.Slots())
  122. {
  123. auto morale = slot.second->MoraleVal();
  124. auto multiplier = 1.0f;
  125. const float BadMoraleChance = 0.083f;
  126. const float HighMoraleChance = 0.04f;
  127. if(morale < 0)
  128. {
  129. multiplier += morale * BadMoraleChance;
  130. }
  131. else if(morale > 0)
  132. {
  133. multiplier += morale * HighMoraleChance;
  134. }
  135. newValue += multiplier * slot.second->getPower();
  136. }
  137. if(armyValue >= newValue)
  138. {
  139. break;
  140. }
  141. resultingArmy = newArmy;
  142. armyValue = newValue;
  143. }
  144. if(resultingArmy.size() <= GameConstants::ARMY_SIZE
  145. && allowedFactions.size() == alignmentMap.size()
  146. && source->needsLastStack())
  147. {
  148. auto weakest = getWeakestCreature(resultingArmy);
  149. if(weakest->count == 1)
  150. {
  151. resultingArmy.erase(weakest);
  152. }
  153. else
  154. {
  155. weakest->power -= weakest->power / weakest->count;
  156. weakest->count--;
  157. }
  158. }
  159. return resultingArmy;
  160. }
  161. ui64 ArmyManager::howManyReinforcementsCanBuy(const CCreatureSet * h, const CGDwelling * t) const
  162. {
  163. return howManyReinforcementsCanBuy(h, t, ai->getFreeResources());
  164. }
  165. std::shared_ptr<CCreatureSet> ArmyManager::getArmyAvailableToBuyAsCCreatureSet(
  166. const CGDwelling * dwelling,
  167. TResources availableRes) const
  168. {
  169. std::vector<creInfo> creaturesInDwellings;
  170. auto army = std::make_shared<TemporaryArmy>();
  171. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  172. {
  173. auto ci = infoFromDC(dwelling->creatures[i]);
  174. if(!ci.count || ci.creID == -1)
  175. continue;
  176. vstd::amin(ci.count, availableRes / ci.cre->cost); //max count we can afford
  177. if(!ci.count)
  178. continue;
  179. SlotID dst = army->getFreeSlot();
  180. if(!dst.validSlot())
  181. break;
  182. army->setCreature(dst, ci.creID, ci.count);
  183. availableRes -= ci.cre->cost * ci.count;
  184. }
  185. return army;
  186. }
  187. ui64 ArmyManager::howManyReinforcementsCanBuy(
  188. const CCreatureSet * targetArmy,
  189. const CGDwelling * dwelling,
  190. const TResources & availableResources) const
  191. {
  192. ui64 aivalue = 0;
  193. auto army = getArmyAvailableToBuy(targetArmy, dwelling, availableResources);
  194. for(const creInfo & ci : army)
  195. {
  196. aivalue += ci.count * ci.cre->AIValue;
  197. }
  198. return aivalue;
  199. }
  200. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  201. {
  202. return getArmyAvailableToBuy(hero, dwelling, ai->getFreeResources());
  203. }
  204. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(
  205. const CCreatureSet * hero,
  206. const CGDwelling * dwelling,
  207. TResources availableRes) const
  208. {
  209. std::vector<creInfo> creaturesInDwellings;
  210. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  211. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  212. {
  213. auto ci = infoFromDC(dwelling->creatures[i]);
  214. if(!ci.count || ci.creID == -1)
  215. continue;
  216. SlotID dst = hero->getSlotFor(ci.creID);
  217. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  218. {
  219. if(!freeHeroSlots) //no more place for stacks
  220. continue;
  221. else
  222. freeHeroSlots--; //new slot will be occupied
  223. }
  224. vstd::amin(ci.count, availableRes / ci.cre->cost); //max count we can afford
  225. if(!ci.count)
  226. continue;
  227. ci.level = i; //this is important for Dungeon Summoning Portal
  228. creaturesInDwellings.push_back(ci);
  229. availableRes -= ci.cre->cost * ci.count;
  230. }
  231. return creaturesInDwellings;
  232. }
  233. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  234. {
  235. auto bestArmy = getBestArmy(armyCarrier, target, source);
  236. uint64_t newArmy = 0;
  237. uint64_t oldArmy = target->getArmyStrength();
  238. for(auto & slot : bestArmy)
  239. {
  240. newArmy += slot.power;
  241. }
  242. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  243. }
  244. uint64_t ArmyManager::evaluateStackPower(const CCreature * creature, int count) const
  245. {
  246. return creature->AIValue * count;
  247. }
  248. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  249. {
  250. auto creatureInfo = totalArmy.find(creatureID);
  251. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  252. }
  253. void ArmyManager::update()
  254. {
  255. logAi->trace("Start analysing army");
  256. std::vector<const CCreatureSet *> total;
  257. auto heroes = cb->getHeroesInfo();
  258. auto towns = cb->getTownsInfo();
  259. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  260. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  261. totalArmy.clear();
  262. for(auto army : total)
  263. {
  264. for(auto slot : army->Slots())
  265. {
  266. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  267. }
  268. }
  269. for(auto army : totalArmy)
  270. {
  271. army.second.creature = army.first.toCreature();
  272. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  273. }
  274. }
  275. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  276. {
  277. std::vector<SlotInfo> result;
  278. for(auto slot : army->Slots())
  279. {
  280. SlotInfo slotInfo;
  281. slotInfo.creature = slot.second->getCreatureID().toCreature();
  282. slotInfo.count = slot.second->count;
  283. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  284. result.push_back(slotInfo);
  285. }
  286. return result;
  287. }
  288. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  289. {
  290. std::vector<StackUpgradeInfo> upgrades;
  291. for(auto creature : army->Slots())
  292. {
  293. CreatureID initial = creature.second->getCreatureID();
  294. auto possibleUpgrades = initial.toCreature()->upgrades;
  295. if(possibleUpgrades.empty())
  296. continue;
  297. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  298. {
  299. return cre.toCreature()->AIValue;
  300. });
  301. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  302. if(initial.toCreature()->level == 1)
  303. upgrade.cost = TResources();
  304. upgrades.push_back(upgrade);
  305. }
  306. return upgrades;
  307. }
  308. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  309. {
  310. std::vector<StackUpgradeInfo> upgrades;
  311. for(auto creature : army->Slots())
  312. {
  313. CreatureID initial = creature.second->getCreatureID();
  314. auto possibleUpgrades = initial.toCreature()->upgrades;
  315. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  316. {
  317. for(auto pair : dwelling->creatures)
  318. {
  319. if(vstd::contains(pair.second, creID))
  320. return false;
  321. }
  322. return true;
  323. });
  324. if(possibleUpgrades.empty())
  325. continue;
  326. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  327. {
  328. return cre.toCreature()->AIValue;
  329. });
  330. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  331. upgrades.push_back(upgrade);
  332. }
  333. return upgrades;
  334. }
  335. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  336. {
  337. std::vector<StackUpgradeInfo> upgrades;
  338. if(upgrader->ID == Obj::HILL_FORT)
  339. {
  340. upgrades = getHillFortUpgrades(army);
  341. }
  342. else
  343. {
  344. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  345. if(dwelling)
  346. {
  347. upgrades = getDwellingUpgrades(army, dwelling);
  348. }
  349. }
  350. return upgrades;
  351. }
  352. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  353. const CCreatureSet * army,
  354. const CGObjectInstance * upgrader,
  355. const TResources & availableResources) const
  356. {
  357. if(!upgrader)
  358. return ArmyUpgradeInfo();
  359. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  360. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  361. {
  362. return !availableResources.canAfford(u.cost);
  363. });
  364. if(upgrades.empty())
  365. return ArmyUpgradeInfo();
  366. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  367. {
  368. return u1.upgradeValue > u2.upgradeValue;
  369. });
  370. TResources resourcesLeft = availableResources;
  371. ArmyUpgradeInfo result;
  372. result.resultingArmy = convertToSlots(army);
  373. for(auto upgrade : upgrades)
  374. {
  375. if(resourcesLeft.canAfford(upgrade.cost))
  376. {
  377. SlotInfo upgradedArmy;
  378. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  379. upgradedArmy.count = upgrade.count;
  380. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  381. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  382. return slot.count == upgradedArmy.count && slot.creature->idNumber == upgrade.initialCreature;
  383. });
  384. resourcesLeft -= upgrade.cost;
  385. result.upgradeCost += upgrade.cost;
  386. result.upgradeValue += upgrade.upgradeValue;
  387. *slotToReplace = upgradedArmy;
  388. }
  389. }
  390. return result;
  391. }