ArmyManager.cpp 14 KB

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