ArmyManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. resultingArmy.erase(weakest);
  154. }
  155. else
  156. {
  157. weakest->power -= weakest->power / weakest->count;
  158. weakest->count--;
  159. }
  160. }
  161. return resultingArmy;
  162. }
  163. ui64 ArmyManager::howManyReinforcementsCanBuy(const CCreatureSet * h, const CGDwelling * t) const
  164. {
  165. return howManyReinforcementsCanBuy(h, t, ai->getFreeResources());
  166. }
  167. std::shared_ptr<CCreatureSet> ArmyManager::getArmyAvailableToBuyAsCCreatureSet(
  168. const CGDwelling * dwelling,
  169. TResources availableRes) const
  170. {
  171. std::vector<creInfo> creaturesInDwellings;
  172. auto army = std::make_shared<TemporaryArmy>();
  173. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  174. {
  175. auto ci = infoFromDC(dwelling->creatures[i]);
  176. if(!ci.count || ci.creID == -1)
  177. continue;
  178. vstd::amin(ci.count, availableRes / ci.cre->cost); //max count we can afford
  179. if(!ci.count)
  180. continue;
  181. SlotID dst = army->getFreeSlot();
  182. if(!dst.validSlot())
  183. break;
  184. army->setCreature(dst, ci.creID, ci.count);
  185. availableRes -= ci.cre->cost * ci.count;
  186. }
  187. return army;
  188. }
  189. ui64 ArmyManager::howManyReinforcementsCanBuy(
  190. const CCreatureSet * targetArmy,
  191. const CGDwelling * dwelling,
  192. const TResources & availableResources) const
  193. {
  194. ui64 aivalue = 0;
  195. auto army = getArmyAvailableToBuy(targetArmy, dwelling, availableResources);
  196. for(const creInfo & ci : army)
  197. {
  198. aivalue += ci.count * ci.cre->AIValue;
  199. }
  200. return aivalue;
  201. }
  202. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  203. {
  204. return getArmyAvailableToBuy(hero, dwelling, ai->getFreeResources());
  205. }
  206. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(
  207. const CCreatureSet * hero,
  208. const CGDwelling * dwelling,
  209. TResources availableRes) const
  210. {
  211. std::vector<creInfo> creaturesInDwellings;
  212. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  213. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  214. {
  215. auto ci = infoFromDC(dwelling->creatures[i]);
  216. if(!ci.count || ci.creID == -1)
  217. continue;
  218. SlotID dst = hero->getSlotFor(ci.creID);
  219. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  220. {
  221. if(!freeHeroSlots) //no more place for stacks
  222. continue;
  223. else
  224. freeHeroSlots--; //new slot will be occupied
  225. }
  226. vstd::amin(ci.count, availableRes / ci.cre->cost); //max count we can afford
  227. if(!ci.count)
  228. continue;
  229. ci.level = i; //this is important for Dungeon Summoning Portal
  230. creaturesInDwellings.push_back(ci);
  231. availableRes -= ci.cre->cost * ci.count;
  232. }
  233. return creaturesInDwellings;
  234. }
  235. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  236. {
  237. auto bestArmy = getBestArmy(armyCarrier, target, source);
  238. uint64_t newArmy = 0;
  239. uint64_t oldArmy = target->getArmyStrength();
  240. for(auto & slot : bestArmy)
  241. {
  242. newArmy += slot.power;
  243. }
  244. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  245. }
  246. uint64_t ArmyManager::evaluateStackPower(const CCreature * creature, int count) const
  247. {
  248. return creature->AIValue * count;
  249. }
  250. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  251. {
  252. auto creatureInfo = totalArmy.find(creatureID);
  253. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  254. }
  255. void ArmyManager::update()
  256. {
  257. logAi->trace("Start analysing army");
  258. std::vector<const CCreatureSet *> total;
  259. auto heroes = cb->getHeroesInfo();
  260. auto towns = cb->getTownsInfo();
  261. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  262. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  263. totalArmy.clear();
  264. for(auto army : total)
  265. {
  266. for(auto slot : army->Slots())
  267. {
  268. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  269. }
  270. }
  271. for(auto army : totalArmy)
  272. {
  273. army.second.creature = army.first.toCreature();
  274. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  275. }
  276. }
  277. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  278. {
  279. std::vector<SlotInfo> result;
  280. for(auto slot : army->Slots())
  281. {
  282. SlotInfo slotInfo;
  283. slotInfo.creature = slot.second->getCreatureID().toCreature();
  284. slotInfo.count = slot.second->count;
  285. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  286. result.push_back(slotInfo);
  287. }
  288. return result;
  289. }
  290. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  291. {
  292. std::vector<StackUpgradeInfo> upgrades;
  293. for(auto creature : army->Slots())
  294. {
  295. CreatureID initial = creature.second->getCreatureID();
  296. auto possibleUpgrades = initial.toCreature()->upgrades;
  297. if(possibleUpgrades.empty())
  298. continue;
  299. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  300. {
  301. return cre.toCreature()->AIValue;
  302. });
  303. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  304. if(initial.toCreature()->level == 1)
  305. upgrade.cost = TResources();
  306. upgrades.push_back(upgrade);
  307. }
  308. return upgrades;
  309. }
  310. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  311. {
  312. std::vector<StackUpgradeInfo> upgrades;
  313. for(auto creature : army->Slots())
  314. {
  315. CreatureID initial = creature.second->getCreatureID();
  316. auto possibleUpgrades = initial.toCreature()->upgrades;
  317. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  318. {
  319. for(auto pair : dwelling->creatures)
  320. {
  321. if(vstd::contains(pair.second, creID))
  322. return false;
  323. }
  324. return true;
  325. });
  326. if(possibleUpgrades.empty())
  327. continue;
  328. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  329. {
  330. return cre.toCreature()->AIValue;
  331. });
  332. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  333. upgrades.push_back(upgrade);
  334. }
  335. return upgrades;
  336. }
  337. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  338. {
  339. std::vector<StackUpgradeInfo> upgrades;
  340. if(upgrader->ID == Obj::HILL_FORT)
  341. {
  342. upgrades = getHillFortUpgrades(army);
  343. }
  344. else
  345. {
  346. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  347. if(dwelling)
  348. {
  349. upgrades = getDwellingUpgrades(army, dwelling);
  350. }
  351. }
  352. return upgrades;
  353. }
  354. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  355. const CCreatureSet * army,
  356. const CGObjectInstance * upgrader,
  357. const TResources & availableResources) const
  358. {
  359. if(!upgrader)
  360. return ArmyUpgradeInfo();
  361. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  362. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  363. {
  364. return !availableResources.canAfford(u.cost);
  365. });
  366. if(upgrades.empty())
  367. return ArmyUpgradeInfo();
  368. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  369. {
  370. return u1.upgradeValue > u2.upgradeValue;
  371. });
  372. TResources resourcesLeft = availableResources;
  373. ArmyUpgradeInfo result;
  374. result.resultingArmy = convertToSlots(army);
  375. for(auto upgrade : upgrades)
  376. {
  377. if(resourcesLeft.canAfford(upgrade.cost))
  378. {
  379. SlotInfo upgradedArmy;
  380. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  381. upgradedArmy.count = upgrade.count;
  382. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  383. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  384. return slot.count == upgradedArmy.count && slot.creature->idNumber == upgrade.initialCreature;
  385. });
  386. resourcesLeft -= upgrade.cost;
  387. result.upgradeCost += upgrade.cost;
  388. result.upgradeValue += upgrade.upgradeValue;
  389. *slotToReplace = upgradedArmy;
  390. }
  391. }
  392. return result;
  393. }
  394. }