HeroManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * HeroManager.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 "../Engine/Nullkiller.h"
  12. #include "../../../lib/mapObjects/MapObjects.h"
  13. #include "../../../lib/IGameSettings.h"
  14. #include "../../../lib/spells/ISpellMechanics.h"
  15. #include "../../../lib/spells/adventure/TownPortalEffect.h"
  16. namespace NK2AI
  17. {
  18. const SecondarySkillEvaluator HeroManager::wariorSkillsScores = SecondarySkillEvaluator(
  19. {
  20. std::make_shared<SecondarySkillScoreMap>(
  21. std::map<SecondarySkill, float>
  22. {
  23. {SecondarySkill::DIPLOMACY, 2},
  24. {SecondarySkill::LOGISTICS, 2},
  25. {SecondarySkill::EARTH_MAGIC, 2},
  26. {SecondarySkill::ARMORER, 2},
  27. {SecondarySkill::OFFENCE, 2},
  28. {SecondarySkill::AIR_MAGIC, 1},
  29. {SecondarySkill::WISDOM, 1},
  30. {SecondarySkill::LEADERSHIP, 1},
  31. {SecondarySkill::INTELLIGENCE, 1},
  32. {SecondarySkill::RESISTANCE, 1},
  33. {SecondarySkill::MYSTICISM, -1},
  34. {SecondarySkill::SORCERY, -1},
  35. {SecondarySkill::ESTATES, -1},
  36. {SecondarySkill::FIRST_AID, -1},
  37. {SecondarySkill::LEARNING, -1},
  38. {SecondarySkill::SCHOLAR, -1},
  39. {SecondarySkill::EAGLE_EYE, -1},
  40. {SecondarySkill::NAVIGATION, -1}
  41. }),
  42. std::make_shared<ExistingSkillRule>(),
  43. std::make_shared<WisdomRule>(),
  44. std::make_shared<AtLeastOneMagicRule>()
  45. });
  46. const SecondarySkillEvaluator HeroManager::scountSkillsScores = SecondarySkillEvaluator(
  47. {
  48. std::make_shared<SecondarySkillScoreMap>(
  49. std::map<SecondarySkill, float>
  50. {
  51. {SecondarySkill::LOGISTICS, 2},
  52. {SecondarySkill::ESTATES, 2},
  53. {SecondarySkill::PATHFINDING, 1},
  54. {SecondarySkill::SCHOLAR, 1}
  55. }),
  56. std::make_shared<ExistingSkillRule>()
  57. });
  58. float HeroManager::evaluateSecSkill(SecondarySkill skill, const CGHeroInstance * hero) const
  59. {
  60. auto role = getHeroRole(HeroPtr(hero));
  61. if(role == HeroRole::MAIN)
  62. return wariorSkillsScores.evaluateSecSkill(hero, skill);
  63. return scountSkillsScores.evaluateSecSkill(hero, skill);
  64. }
  65. float HeroManager::evaluateSpeciality(const CGHeroInstance * hero) const
  66. {
  67. auto heroSpecial = Selector::source(BonusSource::HERO_SPECIAL, BonusSourceID(hero->getHeroTypeID()));
  68. auto secondarySkillBonus = Selector::targetSourceType()(BonusSource::SECONDARY_SKILL);
  69. auto specialSecondarySkillBonuses = hero->getBonuses(heroSpecial.And(secondarySkillBonus), "HeroManager::evaluateSpeciality");
  70. auto secondarySkillBonuses = hero->getBonusesFrom(BonusSource::SECONDARY_SKILL);
  71. float specialityScore = 0.0f;
  72. for(auto bonus : *secondarySkillBonuses)
  73. {
  74. auto hasBonus = !!specialSecondarySkillBonuses->getFirst(Selector::typeSubtype(bonus->type, bonus->subtype));
  75. if(hasBonus)
  76. {
  77. SecondarySkill bonusSkill = bonus->sid.as<SecondarySkill>();
  78. float bonusScore = wariorSkillsScores.evaluateSecSkill(hero, bonusSkill);
  79. if(bonusScore > 0)
  80. specialityScore += bonusScore * bonusScore * bonusScore;
  81. }
  82. }
  83. return specialityScore;
  84. }
  85. float HeroManager::evaluateFightingStrength(const CGHeroInstance * hero) const
  86. {
  87. // TODO: Mircea: Shouldn't we count bonuses from artifacts when generating the fighting strength? That could make a huge difference
  88. return evaluateSpeciality(hero) + wariorSkillsScores.evaluateSecSkills(hero) + hero->getBasePrimarySkillValue(PrimarySkill::ATTACK) + hero->getBasePrimarySkillValue(PrimarySkill::DEFENSE) + hero->getBasePrimarySkillValue(PrimarySkill::SPELL_POWER) + hero->getBasePrimarySkillValue(PrimarySkill::KNOWLEDGE);
  89. }
  90. void HeroManager::update()
  91. {
  92. logAi->trace("Start analysing our heroes");
  93. std::map<const CGHeroInstance *, float> scores;
  94. auto myHeroes = cc->getHeroesInfo();
  95. for(auto & hero : myHeroes)
  96. {
  97. scores[hero] = evaluateFightingStrength(hero);
  98. knownFightingStrength[hero->id] = hero->getHeroStrength();
  99. }
  100. auto scoreSort = [&](const CGHeroInstance * h1, const CGHeroInstance * h2) -> bool
  101. {
  102. return scores.at(h1) > scores.at(h2);
  103. };
  104. int globalMainCount = std::min(((int)myHeroes.size() + 2) / 3, cc->getMapSize().x / 50 + 1);
  105. //vstd::amin(globalMainCount, 1 + (cb->getTownsInfo().size() / 3));
  106. if(cc->getTownsInfo().size() < 4 && globalMainCount > 2)
  107. {
  108. globalMainCount = 2;
  109. }
  110. std::sort(myHeroes.begin(), myHeroes.end(), scoreSort);
  111. heroToRoleMap.clear();
  112. for(auto hero : myHeroes)
  113. {
  114. if(hero->patrol.patrolling)
  115. {
  116. heroToRoleMap[HeroPtr(hero)] = HeroRole::MAIN;
  117. }
  118. else
  119. {
  120. heroToRoleMap[HeroPtr(hero)] = (globalMainCount--) > 0 ? HeroRole::MAIN : HeroRole::SCOUT;
  121. }
  122. }
  123. for(auto hero : myHeroes)
  124. {
  125. logAi->trace("Hero %s has role %s", hero->getNameTranslated(), heroToRoleMap[HeroPtr(hero)] == HeroRole::MAIN ? "main" : "scout");
  126. }
  127. }
  128. HeroRole HeroManager::getHeroRole(const HeroPtr & hPtr) const
  129. {
  130. if (heroToRoleMap.find(hPtr) != heroToRoleMap.end())
  131. return heroToRoleMap.at(hPtr);
  132. else
  133. return HeroRole::SCOUT;
  134. }
  135. const std::map<HeroPtr, HeroRole> & HeroManager::getHeroToRoleMap() const
  136. {
  137. return heroToRoleMap;
  138. }
  139. int HeroManager::selectBestSkill(const HeroPtr & hero, const std::vector<SecondarySkill> & skills) const
  140. {
  141. auto role = getHeroRole(hero);
  142. auto & evaluator = role == HeroRole::MAIN ? wariorSkillsScores : scountSkillsScores;
  143. int result = 0;
  144. float resultScore = -100;
  145. for(int i = 0; i < skills.size(); i++)
  146. {
  147. auto score = evaluator.evaluateSecSkill(hero.get(aiNk->cc.get()), skills[i]);
  148. if(score > resultScore)
  149. {
  150. resultScore = score;
  151. result = i;
  152. }
  153. logAi->trace(
  154. "Hero %s is proposed to learn %d with score %f",
  155. hero.name(),
  156. skills[i].toEnum(),
  157. score);
  158. }
  159. return result;
  160. }
  161. float HeroManager::evaluateHero(const CGHeroInstance * hero) const
  162. {
  163. return evaluateFightingStrength(hero);
  164. }
  165. bool HeroManager::heroCapReached(bool includeGarrisoned) const
  166. {
  167. int heroCount = cc->getHeroCount(aiNk->playerID, includeGarrisoned);
  168. int maxAllowed = aiNk->settings->getMaxRoamingHeroes();
  169. if (aiNk->settings->getMaxRoamingHeroesPerTown() > 0)
  170. {
  171. maxAllowed += cc->howManyTowns() * aiNk->settings->getMaxRoamingHeroesPerTown();
  172. }
  173. return heroCount >= maxAllowed
  174. || heroCount >= cc->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP)
  175. || heroCount >= cc->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP);
  176. }
  177. float HeroManager::getFightingStrengthCached(const CGHeroInstance * hero) const
  178. {
  179. auto cached = knownFightingStrength.find(hero->id);
  180. //FIXME: fallback to hero->getFightingStrength() is VERY slow on higher difficulties (no object graph? map reveal?)
  181. return cached != knownFightingStrength.end() ? cached->second : hero->getHeroStrength();
  182. }
  183. float HeroManager::getMagicStrength(const CGHeroInstance * hero) const
  184. {
  185. auto manaLimit = hero->manaLimit();
  186. auto spellPower = hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  187. auto score = 0.0f;
  188. // FIXME: this will not cover spells give by scrolls / tomes. Intended?
  189. for(auto spellId : hero->getSpellsInSpellbook())
  190. {
  191. auto spell = spellId.toSpell();
  192. if (!spell->isAdventure())
  193. continue;
  194. auto schoolLevel = hero->getSpellSchoolLevel(spell);
  195. auto townPortalEffect = spell->getAdventureMechanics().getEffectAs<TownPortalEffect>(hero);
  196. score += (spell->getLevel() + 1) * (schoolLevel + 1) * 0.05f;
  197. if (spell->getAdventureMechanics().givesBonus(hero, BonusType::FLYING_MOVEMENT))
  198. score += 0.3;
  199. if(townPortalEffect != nullptr && schoolLevel != 0)
  200. score += 0.6f;
  201. }
  202. vstd::amin(score, 1);
  203. score *= std::min(1.0f, spellPower / 10.0f);
  204. vstd::amin(score, 1);
  205. score *= std::min(1.0f, manaLimit / 100.0f);
  206. return std::min(score, 1.0f);
  207. }
  208. bool HeroManager::canRecruitHero(const CGTownInstance * town) const
  209. {
  210. if(!town)
  211. town = findTownWithTavern();
  212. if(!town || !townHasFreeTavern(town))
  213. return false;
  214. if(cc->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
  215. return false;
  216. if(heroCapReached())
  217. return false;
  218. if(!cc->getAvailableHeroes(town).size())
  219. return false;
  220. return true;
  221. }
  222. const CGTownInstance * HeroManager::findTownWithTavern() const
  223. {
  224. for(const CGTownInstance * t : cc->getTownsInfo())
  225. if(townHasFreeTavern(t))
  226. return t;
  227. return nullptr;
  228. }
  229. const CGHeroInstance * HeroManager::findHeroWithGrail() const
  230. {
  231. for(const CGHeroInstance * h : cc->getHeroesInfo())
  232. {
  233. if(h->hasArt(ArtifactID::GRAIL))
  234. return h;
  235. }
  236. return nullptr;
  237. }
  238. const CGHeroInstance * HeroManager::findWeakHeroToDismiss(uint64_t armyLimit, const CGTownInstance* townToSpare) const
  239. {
  240. const CGHeroInstance * weakestHero = nullptr;
  241. auto myHeroes = aiNk->cc->getHeroesInfo();
  242. for(auto existingHero : myHeroes)
  243. {
  244. if(aiNk->getHeroLockedReason(existingHero) == HeroLockedReason::DEFENCE
  245. || existingHero->getArmyStrength() >armyLimit
  246. || getHeroRole(HeroPtr(existingHero)) == HeroRole::MAIN
  247. || existingHero->movementPointsRemaining()
  248. || (townToSpare != nullptr && existingHero->getVisitedTown() == townToSpare)
  249. || existingHero->artifactsWorn.size() > (existingHero->hasSpellbook() ? 2 : 1))
  250. {
  251. continue;
  252. }
  253. if(!weakestHero || weakestHero->getHeroStrength() > existingHero->getHeroStrength())
  254. {
  255. weakestHero = existingHero;
  256. }
  257. }
  258. return weakestHero;
  259. }
  260. SecondarySkillScoreMap::SecondarySkillScoreMap(std::map<SecondarySkill, float> scoreMap)
  261. :scoreMap(scoreMap)
  262. {
  263. }
  264. void SecondarySkillScoreMap::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  265. {
  266. auto it = scoreMap.find(skill);
  267. if(it != scoreMap.end())
  268. {
  269. score = it->second;
  270. }
  271. }
  272. void ExistingSkillRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  273. {
  274. int upgradesLeft = 0;
  275. for(auto & heroSkill : hero->secSkills)
  276. {
  277. if(heroSkill.first == skill)
  278. return;
  279. upgradesLeft += MasteryLevel::EXPERT - heroSkill.second;
  280. }
  281. if(score >= 2 || (score >= 1 && upgradesLeft <= 1))
  282. score += 1.5;
  283. }
  284. void WisdomRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  285. {
  286. if(skill != SecondarySkill::WISDOM)
  287. return;
  288. auto wisdomLevel = hero->getSecSkillLevel(SecondarySkill::WISDOM);
  289. if(hero->level > 10 && wisdomLevel == MasteryLevel::NONE)
  290. score += 1.5;
  291. }
  292. const std::vector<SecondarySkill> AtLeastOneMagicRule::magicSchools = {
  293. SecondarySkill::AIR_MAGIC,
  294. SecondarySkill::EARTH_MAGIC,
  295. SecondarySkill::FIRE_MAGIC,
  296. SecondarySkill::WATER_MAGIC
  297. };
  298. void AtLeastOneMagicRule::evaluateScore(const CGHeroInstance * hero, SecondarySkill skill, float & score) const
  299. {
  300. if(!vstd::contains(magicSchools, skill))
  301. return;
  302. bool heroHasAnyMagic = vstd::contains_if(magicSchools, [&](SecondarySkill skill) -> bool
  303. {
  304. return hero->getSecSkillLevel(skill) > MasteryLevel::NONE;
  305. });
  306. if(!heroHasAnyMagic)
  307. score += 1;
  308. }
  309. SecondarySkillEvaluator::SecondarySkillEvaluator(std::vector<std::shared_ptr<ISecondarySkillRule>> evaluationRules)
  310. : evaluationRules(evaluationRules)
  311. {
  312. }
  313. float SecondarySkillEvaluator::evaluateSecSkills(const CGHeroInstance * hero) const
  314. {
  315. float totalScore = 0;
  316. for(auto skill : hero->secSkills)
  317. {
  318. totalScore += skill.second * evaluateSecSkill(hero, skill.first);
  319. }
  320. return totalScore;
  321. }
  322. float SecondarySkillEvaluator::evaluateSecSkill(const CGHeroInstance * hero, SecondarySkill skill) const
  323. {
  324. float score = 0;
  325. for(auto rule : evaluationRules)
  326. rule->evaluateScore(hero, skill, score);
  327. return score;
  328. }
  329. }