ArmyManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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->getType());
  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->getFactionID()] += slot.power;
  120. }
  121. std::set<FactionID> allowedFactions;
  122. std::vector<SlotInfo> resultingArmy;
  123. uint64_t armyValue = 0;
  124. TemporaryArmy newArmyInstance;
  125. auto bonusModifiers = armyCarrier->getBonuses(Selector::type()(BonusType::MORALE));
  126. for(auto bonus : *bonusModifiers)
  127. {
  128. // army bonuses will change and object bonuses are temporary
  129. if(bonus->source != BonusSource::ARMY && bonus->source != BonusSource::OBJECT_INSTANCE && bonus->source != BonusSource::OBJECT_TYPE)
  130. {
  131. newArmyInstance.addNewBonus(std::make_shared<Bonus>(*bonus));
  132. }
  133. }
  134. while(allowedFactions.size() < alignmentMap.size())
  135. {
  136. auto strongestAlignment = vstd::maxElementByFun(alignmentMap, [&](std::pair<FactionID, uint64_t> pair) -> uint64_t
  137. {
  138. return vstd::contains(allowedFactions, pair.first) ? 0 : pair.second;
  139. });
  140. allowedFactions.insert(strongestAlignment->first);
  141. std::vector<SlotInfo> newArmy;
  142. uint64_t newValue = 0;
  143. newArmyInstance.clearSlots();
  144. for(auto & slot : sortedSlots)
  145. {
  146. if(vstd::contains(allowedFactions, slot.creature->getFactionID()))
  147. {
  148. auto slotID = newArmyInstance.getSlotFor(slot.creature->getId());
  149. if(slotID.validSlot())
  150. {
  151. newArmyInstance.setCreature(slotID, slot.creature->getId(), slot.count);
  152. newArmy.push_back(slot);
  153. }
  154. }
  155. }
  156. newArmyInstance.updateMoraleBonusFromArmy();
  157. for(auto & slot : newArmyInstance.Slots())
  158. {
  159. auto morale = slot.second->moraleVal();
  160. auto multiplier = 1.0f;
  161. const float BadMoraleChance = 0.083f;
  162. const float HighMoraleChance = 0.04f;
  163. if(morale < 0)
  164. {
  165. multiplier += morale * BadMoraleChance;
  166. }
  167. else if(morale > 0)
  168. {
  169. multiplier += morale * HighMoraleChance;
  170. }
  171. newValue += multiplier * slot.second->getPower();
  172. }
  173. if(armyValue >= newValue)
  174. {
  175. break;
  176. }
  177. resultingArmy = newArmy;
  178. armyValue = newValue;
  179. }
  180. if(resultingArmy.size() <= GameConstants::ARMY_SIZE
  181. && allowedFactions.size() == alignmentMap.size()
  182. && source->needsLastStack())
  183. {
  184. auto weakest = getWeakestCreature(resultingArmy);
  185. if(weakest->count == 1)
  186. {
  187. if (resultingArmy.size() == 1)
  188. logAi->warn("Unexpected resulting army size!");
  189. resultingArmy.erase(weakest);
  190. }
  191. else
  192. {
  193. weakest->power -= weakest->power / weakest->count;
  194. weakest->count--;
  195. }
  196. }
  197. return resultingArmy;
  198. }
  199. ui64 ArmyManager::howManyReinforcementsCanBuy(const CCreatureSet * h, const CGDwelling * t) const
  200. {
  201. return howManyReinforcementsCanBuy(h, t, ai->getFreeResources());
  202. }
  203. std::shared_ptr<CCreatureSet> ArmyManager::getArmyAvailableToBuyAsCCreatureSet(
  204. const CGDwelling * dwelling,
  205. TResources availableRes) const
  206. {
  207. std::vector<creInfo> creaturesInDwellings;
  208. auto army = std::make_shared<TemporaryArmy>();
  209. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  210. {
  211. auto ci = infoFromDC(dwelling->creatures[i]);
  212. if(!ci.count || ci.creID == CreatureID::NONE)
  213. continue;
  214. vstd::amin(ci.count, availableRes / ci.creID.toCreature()->getFullRecruitCost()); //max count we can afford
  215. if(!ci.count)
  216. continue;
  217. SlotID dst = army->getFreeSlot();
  218. if(!dst.validSlot())
  219. break;
  220. army->setCreature(dst, ci.creID, ci.count);
  221. availableRes -= ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  222. }
  223. return army;
  224. }
  225. ui64 ArmyManager::howManyReinforcementsCanBuy(
  226. const CCreatureSet * targetArmy,
  227. const CGDwelling * dwelling,
  228. const TResources & availableResources,
  229. uint8_t turn) const
  230. {
  231. ui64 aivalue = 0;
  232. auto army = getArmyAvailableToBuy(targetArmy, dwelling, availableResources);
  233. for(const creInfo & ci : army)
  234. {
  235. aivalue += ci.count * ci.creID.toCreature()->getAIValue();
  236. }
  237. return aivalue;
  238. }
  239. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  240. {
  241. return getArmyAvailableToBuy(hero, dwelling, ai->getFreeResources());
  242. }
  243. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(
  244. const CCreatureSet * hero,
  245. const CGDwelling * dwelling,
  246. TResources availableRes,
  247. uint8_t turn) const
  248. {
  249. std::vector<creInfo> creaturesInDwellings;
  250. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  251. bool countGrowth = (cb->getDate(Date::DAY_OF_WEEK) + turn) > 7;
  252. const CGTownInstance * town = dwelling->ID == Obj::TOWN
  253. ? dynamic_cast<const CGTownInstance *>(dwelling)
  254. : nullptr;
  255. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  256. {
  257. auto ci = infoFromDC(dwelling->creatures[i]);
  258. if(ci.creID == CreatureID::NONE) continue;
  259. if(i < GameConstants::CREATURES_PER_TOWN && countGrowth)
  260. {
  261. ci.count += town ? town->creatureGrowth(i) : ci.creID.toCreature()->getGrowth();
  262. }
  263. if(!ci.count) continue;
  264. SlotID dst = hero->getSlotFor(ci.creID);
  265. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  266. {
  267. if(!freeHeroSlots) //no more place for stacks
  268. continue;
  269. else
  270. freeHeroSlots--; //new slot will be occupied
  271. }
  272. vstd::amin(ci.count, availableRes / ci.creID.toCreature()->getFullRecruitCost()); //max count we can afford
  273. if(!ci.count) continue;
  274. ci.level = i; //this is important for Dungeon Summoning Portal
  275. creaturesInDwellings.push_back(ci);
  276. availableRes -= ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  277. }
  278. return creaturesInDwellings;
  279. }
  280. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  281. {
  282. if(source->stacksCount() == 0)
  283. {
  284. return 0;
  285. }
  286. auto bestArmy = getBestArmy(armyCarrier, target, source);
  287. uint64_t newArmy = 0;
  288. uint64_t oldArmy = target->getArmyStrength();
  289. for(auto & slot : bestArmy)
  290. {
  291. newArmy += slot.power;
  292. }
  293. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  294. }
  295. uint64_t ArmyManager::evaluateStackPower(const Creature * creature, int count) const
  296. {
  297. return creature->getAIValue() * count;
  298. }
  299. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  300. {
  301. auto creatureInfo = totalArmy.find(creatureID);
  302. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  303. }
  304. void ArmyManager::update()
  305. {
  306. logAi->trace("Start analysing army");
  307. std::vector<const CCreatureSet *> total;
  308. auto heroes = cb->getHeroesInfo();
  309. auto towns = cb->getTownsInfo();
  310. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  311. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  312. totalArmy.clear();
  313. for(auto army : total)
  314. {
  315. for(auto slot : army->Slots())
  316. {
  317. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  318. }
  319. }
  320. for(auto & army : totalArmy)
  321. {
  322. army.second.creature = army.first.toCreature();
  323. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  324. }
  325. }
  326. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  327. {
  328. std::vector<SlotInfo> result;
  329. for(auto slot : army->Slots())
  330. {
  331. SlotInfo slotInfo;
  332. slotInfo.creature = slot.second->getCreatureID().toCreature();
  333. slotInfo.count = slot.second->count;
  334. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  335. result.push_back(slotInfo);
  336. }
  337. return result;
  338. }
  339. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  340. {
  341. std::vector<StackUpgradeInfo> upgrades;
  342. for(auto creature : army->Slots())
  343. {
  344. CreatureID initial = creature.second->getCreatureID();
  345. auto possibleUpgrades = initial.toCreature()->upgrades;
  346. if(possibleUpgrades.empty())
  347. continue;
  348. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  349. {
  350. return cre.toCreature()->getAIValue();
  351. });
  352. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  353. if(initial.toCreature()->getLevel() == 1)
  354. upgrade.cost = TResources();
  355. upgrades.push_back(upgrade);
  356. }
  357. return upgrades;
  358. }
  359. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  360. {
  361. std::vector<StackUpgradeInfo> upgrades;
  362. for(auto creature : army->Slots())
  363. {
  364. CreatureID initial = creature.second->getCreatureID();
  365. auto possibleUpgrades = initial.toCreature()->upgrades;
  366. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  367. {
  368. for(auto pair : dwelling->creatures)
  369. {
  370. if(vstd::contains(pair.second, creID))
  371. return false;
  372. }
  373. return true;
  374. });
  375. if(possibleUpgrades.empty())
  376. continue;
  377. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  378. {
  379. return cre.toCreature()->getAIValue();
  380. });
  381. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  382. upgrades.push_back(upgrade);
  383. }
  384. return upgrades;
  385. }
  386. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  387. {
  388. std::vector<StackUpgradeInfo> upgrades;
  389. if(upgrader->ID == Obj::HILL_FORT)
  390. {
  391. upgrades = getHillFortUpgrades(army);
  392. }
  393. else
  394. {
  395. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  396. if(dwelling)
  397. {
  398. upgrades = getDwellingUpgrades(army, dwelling);
  399. }
  400. }
  401. return upgrades;
  402. }
  403. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  404. const CCreatureSet * army,
  405. const CGObjectInstance * upgrader,
  406. const TResources & availableResources) const
  407. {
  408. if(!upgrader)
  409. return ArmyUpgradeInfo();
  410. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  411. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  412. {
  413. return !availableResources.canAfford(u.cost);
  414. });
  415. if(upgrades.empty())
  416. return ArmyUpgradeInfo();
  417. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  418. {
  419. return u1.upgradeValue > u2.upgradeValue;
  420. });
  421. TResources resourcesLeft = availableResources;
  422. ArmyUpgradeInfo result;
  423. result.resultingArmy = convertToSlots(army);
  424. for(auto upgrade : upgrades)
  425. {
  426. if(resourcesLeft.canAfford(upgrade.cost))
  427. {
  428. SlotInfo upgradedArmy;
  429. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  430. upgradedArmy.count = upgrade.count;
  431. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  432. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  433. return slot.count == upgradedArmy.count && slot.creature->getId() == upgrade.initialCreature;
  434. });
  435. resourcesLeft -= upgrade.cost;
  436. result.upgradeCost += upgrade.cost;
  437. result.upgradeValue += upgrade.upgradeValue;
  438. *slotToReplace = upgradedArmy;
  439. }
  440. }
  441. return result;
  442. }
  443. }