ArmyManager.cpp 14 KB

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