ArmyManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. std::set<SlotID> alreadyDisbanded;
  250. for(int i = dwelling->creatures.size() - 1; i >= 0; i--)
  251. {
  252. auto ci = infoFromDC(dwelling->creatures[i]);
  253. if(ci.creID == CreatureID::NONE) continue;
  254. if(i < GameConstants::CREATURES_PER_TOWN && countGrowth)
  255. {
  256. ci.count += town ? town->creatureGrowth(i) : ci.creID.toCreature()->getGrowth();
  257. }
  258. if(!ci.count) continue;
  259. // Calculate the market value of the new stack
  260. TResources newStackValue = ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  261. SlotID dst = hero->getSlotFor(ci.creID);
  262. // Keep track of the least valuable slot in the hero's army
  263. SlotID leastValuableSlot;
  264. TResources leastValuableStackValue;
  265. leastValuableStackValue[6] = std::numeric_limits<int>::max();
  266. bool shouldDisband = false;
  267. if(!hero->hasStackAtSlot(dst)) //need another new slot for this stack
  268. {
  269. if(!freeHeroSlots) // No free slots; consider replacing
  270. {
  271. // Check for the least valuable existing stack
  272. for (auto& slot : hero->Slots())
  273. {
  274. if (alreadyDisbanded.find(slot.first) != alreadyDisbanded.end())
  275. continue;
  276. if(slot.second->getCreatureID() != CreatureID::NONE)
  277. {
  278. TResources currentStackValue = slot.second->getCreatureID().toCreature()->getFullRecruitCost() * slot.second->getCount();
  279. if (town && slot.second->getCreatureID().toCreature()->getFactionID() == town->getFactionID())
  280. continue;
  281. if(currentStackValue.marketValue() < leastValuableStackValue.marketValue())
  282. {
  283. leastValuableStackValue = currentStackValue;
  284. leastValuableSlot = slot.first;
  285. }
  286. }
  287. }
  288. // Decide whether to replace the least valuable stack
  289. if(newStackValue.marketValue() <= leastValuableStackValue.marketValue())
  290. {
  291. continue; // Skip if the new stack isn't worth replacing
  292. }
  293. else
  294. {
  295. shouldDisband = true;
  296. }
  297. }
  298. else
  299. {
  300. freeHeroSlots--; //new slot will be occupied
  301. }
  302. }
  303. vstd::amin(ci.count, availableRes / ci.creID.toCreature()->getFullRecruitCost()); //max count we can afford
  304. int disbandMalus = 0;
  305. if (shouldDisband)
  306. {
  307. disbandMalus = leastValuableStackValue / ci.creID.toCreature()->getFullRecruitCost();
  308. logAi->info("Should disband %d %s at %s worth: %d", hero->getStack(leastValuableSlot).count, hero->getStack(leastValuableSlot).getCreatureID().toCreature()->getNamePluralTranslated(), town->getNameTranslated(), leastValuableStackValue.marketValue());
  309. alreadyDisbanded.insert(leastValuableSlot);
  310. }
  311. ci.count -= disbandMalus;
  312. if(ci.count <= 0)
  313. continue;
  314. ci.level = i; //this is important for Dungeon Summoning Portal
  315. creaturesInDwellings.push_back(ci);
  316. availableRes -= ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  317. }
  318. return creaturesInDwellings;
  319. }
  320. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  321. {
  322. if(source->stacksCount() == 0)
  323. {
  324. return 0;
  325. }
  326. auto bestArmy = getBestArmy(armyCarrier, target, source);
  327. uint64_t newArmy = 0;
  328. uint64_t oldArmy = target->getArmyStrength();
  329. for(auto & slot : bestArmy)
  330. {
  331. newArmy += slot.power;
  332. }
  333. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  334. }
  335. uint64_t ArmyManager::evaluateStackPower(const Creature * creature, int count) const
  336. {
  337. return creature->getAIValue() * count;
  338. }
  339. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  340. {
  341. auto creatureInfo = totalArmy.find(creatureID);
  342. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  343. }
  344. void ArmyManager::update()
  345. {
  346. logAi->trace("Start analysing army");
  347. std::vector<const CCreatureSet *> total;
  348. auto heroes = cb->getHeroesInfo();
  349. auto towns = cb->getTownsInfo();
  350. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  351. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  352. totalArmy.clear();
  353. for(auto army : total)
  354. {
  355. for(auto slot : army->Slots())
  356. {
  357. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  358. }
  359. }
  360. for(auto & army : totalArmy)
  361. {
  362. army.second.creature = army.first.toCreature();
  363. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  364. }
  365. }
  366. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  367. {
  368. std::vector<SlotInfo> result;
  369. for(auto slot : army->Slots())
  370. {
  371. SlotInfo slotInfo;
  372. slotInfo.creature = slot.second->getCreatureID().toCreature();
  373. slotInfo.count = slot.second->count;
  374. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  375. result.push_back(slotInfo);
  376. }
  377. return result;
  378. }
  379. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  380. {
  381. std::vector<StackUpgradeInfo> upgrades;
  382. for(auto creature : army->Slots())
  383. {
  384. CreatureID initial = creature.second->getCreatureID();
  385. auto possibleUpgrades = initial.toCreature()->upgrades;
  386. if(possibleUpgrades.empty())
  387. continue;
  388. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  389. {
  390. return cre.toCreature()->getAIValue();
  391. });
  392. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  393. if(initial.toCreature()->getLevel() == 1)
  394. upgrade.cost = TResources();
  395. upgrades.push_back(upgrade);
  396. }
  397. return upgrades;
  398. }
  399. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  400. {
  401. std::vector<StackUpgradeInfo> upgrades;
  402. for(auto creature : army->Slots())
  403. {
  404. CreatureID initial = creature.second->getCreatureID();
  405. auto possibleUpgrades = initial.toCreature()->upgrades;
  406. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  407. {
  408. for(auto pair : dwelling->creatures)
  409. {
  410. if(vstd::contains(pair.second, creID))
  411. return false;
  412. }
  413. return true;
  414. });
  415. if(possibleUpgrades.empty())
  416. continue;
  417. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  418. {
  419. return cre.toCreature()->getAIValue();
  420. });
  421. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  422. upgrades.push_back(upgrade);
  423. }
  424. return upgrades;
  425. }
  426. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  427. {
  428. std::vector<StackUpgradeInfo> upgrades;
  429. if(upgrader->ID == Obj::HILL_FORT)
  430. {
  431. upgrades = getHillFortUpgrades(army);
  432. }
  433. else
  434. {
  435. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  436. if(dwelling)
  437. {
  438. upgrades = getDwellingUpgrades(army, dwelling);
  439. }
  440. }
  441. return upgrades;
  442. }
  443. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  444. const CCreatureSet * army,
  445. const CGObjectInstance * upgrader,
  446. const TResources & availableResources) const
  447. {
  448. if(!upgrader)
  449. return ArmyUpgradeInfo();
  450. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  451. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  452. {
  453. return !availableResources.canAfford(u.cost);
  454. });
  455. if(upgrades.empty())
  456. return ArmyUpgradeInfo();
  457. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  458. {
  459. return u1.upgradeValue > u2.upgradeValue;
  460. });
  461. TResources resourcesLeft = availableResources;
  462. ArmyUpgradeInfo result;
  463. result.resultingArmy = convertToSlots(army);
  464. for(auto upgrade : upgrades)
  465. {
  466. if(resourcesLeft.canAfford(upgrade.cost))
  467. {
  468. SlotInfo upgradedArmy;
  469. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  470. upgradedArmy.count = upgrade.count;
  471. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  472. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  473. return slot.count == upgradedArmy.count && slot.creature->getId() == upgrade.initialCreature;
  474. });
  475. resourcesLeft -= upgrade.cost;
  476. result.upgradeCost += upgrade.cost;
  477. result.upgradeValue += upgrade.upgradeValue;
  478. *slotToReplace = upgradedArmy;
  479. }
  480. }
  481. return result;
  482. }
  483. }