ArmyManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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(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. std::map<FactionID, uint64_t> alignmentMap;
  115. for(auto & slot : sortedSlots)
  116. {
  117. alignmentMap[slot.creature->getFaction()] += slot.power;
  118. }
  119. std::set<FactionID> allowedFactions;
  120. std::vector<SlotInfo> resultingArmy;
  121. uint64_t armyValue = 0;
  122. TemporaryArmy newArmyInstance;
  123. auto bonusModifiers = armyCarrier->getBonuses(Selector::type()(BonusType::MORALE));
  124. for(auto bonus : *bonusModifiers)
  125. {
  126. // army bonuses will change and object bonuses are temporary
  127. if(bonus->source != BonusSource::ARMY && bonus->source != BonusSource::OBJECT_INSTANCE && bonus->source != BonusSource::OBJECT_TYPE)
  128. {
  129. newArmyInstance.addNewBonus(std::make_shared<Bonus>(*bonus));
  130. }
  131. }
  132. while(allowedFactions.size() < alignmentMap.size())
  133. {
  134. auto strongestAlignment = vstd::maxElementByFun(alignmentMap, [&](std::pair<FactionID, uint64_t> pair) -> uint64_t
  135. {
  136. return vstd::contains(allowedFactions, pair.first) ? 0 : pair.second;
  137. });
  138. allowedFactions.insert(strongestAlignment->first);
  139. std::vector<SlotInfo> newArmy;
  140. uint64_t newValue = 0;
  141. newArmyInstance.clearSlots();
  142. for(auto & slot : sortedSlots)
  143. {
  144. if(vstd::contains(allowedFactions, slot.creature->getFaction()))
  145. {
  146. auto slotID = newArmyInstance.getSlotFor(slot.creature->getId());
  147. if(slotID.validSlot())
  148. {
  149. newArmyInstance.setCreature(slotID, slot.creature->getId(), slot.count);
  150. newArmy.push_back(slot);
  151. }
  152. }
  153. }
  154. newArmyInstance.updateMoraleBonusFromArmy();
  155. for(auto & slot : newArmyInstance.Slots())
  156. {
  157. auto morale = slot.second->moraleVal();
  158. auto multiplier = 1.0f;
  159. const float BadMoraleChance = 0.083f;
  160. const float HighMoraleChance = 0.04f;
  161. if(morale < 0)
  162. {
  163. multiplier += morale * BadMoraleChance;
  164. }
  165. else if(morale > 0)
  166. {
  167. multiplier += morale * HighMoraleChance;
  168. }
  169. newValue += multiplier * slot.second->getPower();
  170. }
  171. if(armyValue >= newValue)
  172. {
  173. break;
  174. }
  175. resultingArmy = newArmy;
  176. armyValue = newValue;
  177. }
  178. if(resultingArmy.size() <= GameConstants::ARMY_SIZE
  179. && allowedFactions.size() == alignmentMap.size()
  180. && source->needsLastStack())
  181. {
  182. auto weakest = getWeakestCreature(resultingArmy);
  183. if(weakest->count == 1)
  184. {
  185. if (resultingArmy.size() == 1)
  186. logAi->warn("Unexpected resulting army size!");
  187. resultingArmy.erase(weakest);
  188. }
  189. else
  190. {
  191. weakest->power -= weakest->power / weakest->count;
  192. weakest->count--;
  193. }
  194. }
  195. return resultingArmy;
  196. }
  197. ui64 ArmyManager::howManyReinforcementsCanBuy(const CCreatureSet * h, const CGDwelling * t) const
  198. {
  199. return howManyReinforcementsCanBuy(h, t, ai->getFreeResources());
  200. }
  201. std::shared_ptr<CCreatureSet> ArmyManager::getArmyAvailableToBuyAsCCreatureSet(
  202. const CGDwelling * dwelling,
  203. TResources availableRes) const
  204. {
  205. std::vector<creInfo> creaturesInDwellings;
  206. auto army = std::make_shared<TemporaryArmy>();
  207. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  208. {
  209. auto ci = infoFromDC(dwelling->creatures[i]);
  210. if(!ci.count || ci.creID == CreatureID::NONE)
  211. continue;
  212. vstd::amin(ci.count, availableRes / ci.creID.toCreature()->getFullRecruitCost()); //max count we can afford
  213. if(!ci.count)
  214. continue;
  215. SlotID dst = army->getFreeSlot();
  216. if(!dst.validSlot())
  217. break;
  218. army->setCreature(dst, ci.creID, ci.count);
  219. availableRes -= ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  220. }
  221. return army;
  222. }
  223. ui64 ArmyManager::howManyReinforcementsCanBuy(
  224. const CCreatureSet * targetArmy,
  225. const CGDwelling * dwelling,
  226. const TResources & availableResources,
  227. uint8_t turn) const
  228. {
  229. ui64 aivalue = 0;
  230. auto army = getArmyAvailableToBuy(targetArmy, dwelling, availableResources);
  231. for(const creInfo & ci : army)
  232. {
  233. aivalue += ci.count * ci.creID.toCreature()->getAIValue();
  234. }
  235. return aivalue;
  236. }
  237. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(const CCreatureSet * hero, const CGDwelling * dwelling) const
  238. {
  239. return getArmyAvailableToBuy(hero, dwelling, ai->getFreeResources());
  240. }
  241. std::vector<creInfo> ArmyManager::getArmyAvailableToBuy(
  242. const CCreatureSet * hero,
  243. const CGDwelling * dwelling,
  244. TResources availableRes,
  245. uint8_t turn) const
  246. {
  247. std::vector<creInfo> creaturesInDwellings;
  248. int freeHeroSlots = GameConstants::ARMY_SIZE - hero->stacksCount();
  249. bool countGrowth = (cb->getDate(Date::DAY_OF_WEEK) + turn) > 7;
  250. const CGTownInstance * town = dwelling->ID == Obj::TOWN
  251. ? dynamic_cast<const CGTownInstance *>(dwelling)
  252. : nullptr;
  253. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  254. {
  255. auto ci = infoFromDC(dwelling->creatures[i]);
  256. if(ci.creID == CreatureID::NONE) continue;
  257. if(i < GameConstants::CREATURES_PER_TOWN && countGrowth)
  258. {
  259. ci.count += town ? town->creatureGrowth(i) : ci.creID.toCreature()->getGrowth();
  260. }
  261. if(!ci.count) continue;
  262. SlotID dst = hero->getSlotFor(ci.creID);
  263. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  264. {
  265. if(!freeHeroSlots) //no more place for stacks
  266. continue;
  267. else
  268. freeHeroSlots--; //new slot will be occupied
  269. }
  270. vstd::amin(ci.count, availableRes / ci.creID.toCreature()->getFullRecruitCost()); //max count we can afford
  271. if(!ci.count) continue;
  272. ci.level = i; //this is important for Dungeon Summoning Portal
  273. creaturesInDwellings.push_back(ci);
  274. availableRes -= ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  275. }
  276. return creaturesInDwellings;
  277. }
  278. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  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. }