ArmyManager.cpp 12 KB

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