ArmyManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. alreadyDisbanded.insert(leastValuableSlot);
  309. }
  310. ci.count -= disbandMalus;
  311. if(ci.count <= 0)
  312. continue;
  313. ci.level = i; //this is important for Dungeon Summoning Portal
  314. creaturesInDwellings.push_back(ci);
  315. availableRes -= ci.creID.toCreature()->getFullRecruitCost() * ci.count;
  316. }
  317. return creaturesInDwellings;
  318. }
  319. ui64 ArmyManager::howManyReinforcementsCanGet(const IBonusBearer * armyCarrier, const CCreatureSet * target, const CCreatureSet * source) const
  320. {
  321. if(source->stacksCount() == 0)
  322. {
  323. return 0;
  324. }
  325. auto bestArmy = getBestArmy(armyCarrier, target, source);
  326. uint64_t newArmy = 0;
  327. uint64_t oldArmy = target->getArmyStrength();
  328. for(auto & slot : bestArmy)
  329. {
  330. newArmy += slot.power;
  331. }
  332. return newArmy > oldArmy ? newArmy - oldArmy : 0;
  333. }
  334. uint64_t ArmyManager::evaluateStackPower(const Creature * creature, int count) const
  335. {
  336. return creature->getAIValue() * count;
  337. }
  338. SlotInfo ArmyManager::getTotalCreaturesAvailable(CreatureID creatureID) const
  339. {
  340. auto creatureInfo = totalArmy.find(creatureID);
  341. return creatureInfo == totalArmy.end() ? SlotInfo() : creatureInfo->second;
  342. }
  343. void ArmyManager::update()
  344. {
  345. logAi->trace("Start analysing army");
  346. std::vector<const CCreatureSet *> total;
  347. auto heroes = cb->getHeroesInfo();
  348. auto towns = cb->getTownsInfo();
  349. std::copy(heroes.begin(), heroes.end(), std::back_inserter(total));
  350. std::copy(towns.begin(), towns.end(), std::back_inserter(total));
  351. totalArmy.clear();
  352. for(auto army : total)
  353. {
  354. for(auto slot : army->Slots())
  355. {
  356. totalArmy[slot.second->getCreatureID()].count += slot.second->count;
  357. }
  358. }
  359. for(auto & army : totalArmy)
  360. {
  361. army.second.creature = army.first.toCreature();
  362. army.second.power = evaluateStackPower(army.second.creature, army.second.count);
  363. }
  364. }
  365. std::vector<SlotInfo> ArmyManager::convertToSlots(const CCreatureSet * army) const
  366. {
  367. std::vector<SlotInfo> result;
  368. for(auto slot : army->Slots())
  369. {
  370. SlotInfo slotInfo;
  371. slotInfo.creature = slot.second->getCreatureID().toCreature();
  372. slotInfo.count = slot.second->count;
  373. slotInfo.power = evaluateStackPower(slotInfo.creature, slotInfo.count);
  374. result.push_back(slotInfo);
  375. }
  376. return result;
  377. }
  378. std::vector<StackUpgradeInfo> ArmyManager::getHillFortUpgrades(const CCreatureSet * army) const
  379. {
  380. std::vector<StackUpgradeInfo> upgrades;
  381. for(auto creature : army->Slots())
  382. {
  383. CreatureID initial = creature.second->getCreatureID();
  384. auto possibleUpgrades = initial.toCreature()->upgrades;
  385. if(possibleUpgrades.empty())
  386. continue;
  387. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  388. {
  389. return cre.toCreature()->getAIValue();
  390. });
  391. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  392. if(initial.toCreature()->getLevel() == 1)
  393. upgrade.cost = TResources();
  394. upgrades.push_back(upgrade);
  395. }
  396. return upgrades;
  397. }
  398. std::vector<StackUpgradeInfo> ArmyManager::getDwellingUpgrades(const CCreatureSet * army, const CGDwelling * dwelling) const
  399. {
  400. std::vector<StackUpgradeInfo> upgrades;
  401. for(auto creature : army->Slots())
  402. {
  403. CreatureID initial = creature.second->getCreatureID();
  404. auto possibleUpgrades = initial.toCreature()->upgrades;
  405. vstd::erase_if(possibleUpgrades, [&](CreatureID creID) -> bool
  406. {
  407. for(auto pair : dwelling->creatures)
  408. {
  409. if(vstd::contains(pair.second, creID))
  410. return false;
  411. }
  412. return true;
  413. });
  414. if(possibleUpgrades.empty())
  415. continue;
  416. CreatureID strongestUpgrade = *vstd::minElementByFun(possibleUpgrades, [](CreatureID cre) -> uint64_t
  417. {
  418. return cre.toCreature()->getAIValue();
  419. });
  420. StackUpgradeInfo upgrade = StackUpgradeInfo(initial, strongestUpgrade, creature.second->count);
  421. upgrades.push_back(upgrade);
  422. }
  423. return upgrades;
  424. }
  425. std::vector<StackUpgradeInfo> ArmyManager::getPossibleUpgrades(const CCreatureSet * army, const CGObjectInstance * upgrader) const
  426. {
  427. std::vector<StackUpgradeInfo> upgrades;
  428. if(upgrader->ID == Obj::HILL_FORT)
  429. {
  430. upgrades = getHillFortUpgrades(army);
  431. }
  432. else
  433. {
  434. auto dwelling = dynamic_cast<const CGDwelling *>(upgrader);
  435. if(dwelling)
  436. {
  437. upgrades = getDwellingUpgrades(army, dwelling);
  438. }
  439. }
  440. return upgrades;
  441. }
  442. ArmyUpgradeInfo ArmyManager::calculateCreaturesUpgrade(
  443. const CCreatureSet * army,
  444. const CGObjectInstance * upgrader,
  445. const TResources & availableResources) const
  446. {
  447. if(!upgrader)
  448. return ArmyUpgradeInfo();
  449. std::vector<StackUpgradeInfo> upgrades = getPossibleUpgrades(army, upgrader);
  450. vstd::erase_if(upgrades, [&](const StackUpgradeInfo & u) -> bool
  451. {
  452. return !availableResources.canAfford(u.cost);
  453. });
  454. if(upgrades.empty())
  455. return ArmyUpgradeInfo();
  456. std::sort(upgrades.begin(), upgrades.end(), [](const StackUpgradeInfo & u1, const StackUpgradeInfo & u2) -> bool
  457. {
  458. return u1.upgradeValue > u2.upgradeValue;
  459. });
  460. TResources resourcesLeft = availableResources;
  461. ArmyUpgradeInfo result;
  462. result.resultingArmy = convertToSlots(army);
  463. for(auto upgrade : upgrades)
  464. {
  465. if(resourcesLeft.canAfford(upgrade.cost))
  466. {
  467. SlotInfo upgradedArmy;
  468. upgradedArmy.creature = upgrade.upgradedCreature.toCreature();
  469. upgradedArmy.count = upgrade.count;
  470. upgradedArmy.power = evaluateStackPower(upgradedArmy.creature, upgradedArmy.count);
  471. auto slotToReplace = std::find_if(result.resultingArmy.begin(), result.resultingArmy.end(), [&](const SlotInfo & slot) -> bool {
  472. return slot.count == upgradedArmy.count && slot.creature->getId() == upgrade.initialCreature;
  473. });
  474. resourcesLeft -= upgrade.cost;
  475. result.upgradeCost += upgrade.cost;
  476. result.upgradeValue += upgrade.upgradeValue;
  477. *slotToReplace = upgradedArmy;
  478. }
  479. }
  480. return result;
  481. }
  482. }