2
0

PriorityEvaluator.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. /*
  2. * PriorityEvaluator.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 <limits>
  12. #include "Nullkiller.h"
  13. #include "../../../lib/mapObjectConstructors/AObjectTypeHandler.h"
  14. #include "../../../lib/mapObjectConstructors/CObjectClassesHandler.h"
  15. #include "../../../lib/mapObjectConstructors/CBankInstanceConstructor.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/CCreatureHandler.h"
  18. #include "../../../lib/VCMI_Lib.h"
  19. #include "../../../lib/StartInfo.h"
  20. #include "../../../CCallback.h"
  21. #include "../../../lib/filesystem/Filesystem.h"
  22. #include "../Goals/ExecuteHeroChain.h"
  23. #include "../Goals/BuildThis.h"
  24. #include "../Goals/ExchangeSwapTownHeroes.h"
  25. #include "../Goals/DismissHero.h"
  26. #include "../Markers/UnlockCluster.h"
  27. #include "../Markers/HeroExchange.h"
  28. #include "../Markers/ArmyUpgrade.h"
  29. #include "../Markers/DefendTown.h"
  30. namespace NKAI
  31. {
  32. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  33. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  34. const float MIN_CRITICAL_VALUE = 2.0f;
  35. EvaluationContext::EvaluationContext(const Nullkiller * ai)
  36. : movementCost(0.0),
  37. manaCost(0),
  38. danger(0),
  39. closestWayRatio(1),
  40. movementCostByRole(),
  41. skillReward(0),
  42. goldReward(0),
  43. goldCost(0),
  44. armyReward(0),
  45. armyLossPersentage(0),
  46. heroRole(HeroRole::SCOUT),
  47. turn(0),
  48. strategicalValue(0),
  49. evaluator(ai),
  50. enemyHeroDangerRatio(0),
  51. armyGrowth(0)
  52. {
  53. }
  54. void EvaluationContext::addNonCriticalStrategicalValue(float value)
  55. {
  56. vstd::amax(strategicalValue, std::min(value, MIN_CRITICAL_VALUE));
  57. }
  58. PriorityEvaluator::~PriorityEvaluator()
  59. {
  60. delete engine;
  61. }
  62. void PriorityEvaluator::initVisitTile()
  63. {
  64. auto file = CResourceHandler::get()->load(ResourceID("config/ai/object-priorities.txt"))->readAll();
  65. std::string str = std::string((char *)file.first.get(), file.second);
  66. engine = fl::FllImporter().fromString(str);
  67. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  68. armyGrowthVariable = engine->getInputVariable("armyGrowth");
  69. heroRoleVariable = engine->getInputVariable("heroRole");
  70. dangerVariable = engine->getInputVariable("danger");
  71. turnVariable = engine->getInputVariable("turn");
  72. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  73. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  74. goldRewardVariable = engine->getInputVariable("goldReward");
  75. armyRewardVariable = engine->getInputVariable("armyReward");
  76. skillRewardVariable = engine->getInputVariable("skillReward");
  77. rewardTypeVariable = engine->getInputVariable("rewardType");
  78. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  79. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  80. goldPreasureVariable = engine->getInputVariable("goldPreasure");
  81. goldCostVariable = engine->getInputVariable("goldCost");
  82. fearVariable = engine->getInputVariable("fear");
  83. value = engine->getOutputVariable("Value");
  84. }
  85. bool isAnotherAi(const CGObjectInstance * obj, const CPlayerSpecificInfoCallback & cb)
  86. {
  87. return obj->getOwner().isValidPlayer()
  88. && cb.getStartInfo()->getIthPlayersSettings(obj->getOwner()).isControlledByAI();
  89. }
  90. int32_t estimateTownIncome(CCallback * cb, const CGObjectInstance * target, const CGHeroInstance * hero)
  91. {
  92. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  93. if(relations != PlayerRelations::ENEMIES)
  94. return 0; // if we already own it, no additional reward will be received by just visiting it
  95. auto booster = isAnotherAi(target, *cb) ? 1 : 2;
  96. auto town = cb->getTown(target->id);
  97. auto fortLevel = town->fortLevel();
  98. if(town->hasCapitol())
  99. return booster * 2000;
  100. // probably well developed town will have city hall
  101. if(fortLevel == CGTownInstance::CASTLE) return booster * 750;
  102. return booster * (town->hasFort() && town->tempOwner != PlayerColor::NEUTRAL ? booster * 500 : 250);
  103. }
  104. TResources getCreatureBankResources(const CGObjectInstance * target, const CGHeroInstance * hero)
  105. {
  106. //Fixme: unused variable hero
  107. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  108. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  109. auto resources = bankInfo->getPossibleResourcesReward();
  110. TResources result = TResources();
  111. int sum = 0;
  112. for(auto & reward : resources)
  113. {
  114. result += reward.data * reward.chance;
  115. sum += reward.chance;
  116. }
  117. return sum > 1 ? result / sum : result;
  118. }
  119. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  120. {
  121. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  122. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  123. auto creatures = bankInfo->getPossibleCreaturesReward();
  124. uint64_t result = 0;
  125. const auto& slots = hero->Slots();
  126. ui64 weakestStackPower = 0;
  127. if (slots.size() >= GameConstants::ARMY_SIZE)
  128. {
  129. //No free slot, we might discard our weakest stack
  130. weakestStackPower = std::numeric_limits<ui64>().max();
  131. for (const auto & stack : slots)
  132. {
  133. vstd::amin(weakestStackPower, stack.second->getPower());
  134. }
  135. }
  136. for (auto c : creatures)
  137. {
  138. //Only if hero has slot for this creature in the army
  139. auto ccre = dynamic_cast<const CCreature*>(c.data.type);
  140. if (hero->getSlotFor(ccre).validSlot())
  141. {
  142. result += (c.data.type->getAIValue() * c.data.count) * c.chance;
  143. }
  144. /*else
  145. {
  146. //we will need to discard the weakest stack
  147. result += (c.data.type->getAIValue() * c.data.count - weakestStackPower) * c.chance;
  148. }*/
  149. }
  150. result /= 100; //divide by total chance
  151. return result;
  152. }
  153. uint64_t getDwellingArmyValue(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  154. {
  155. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  156. uint64_t score = 0;
  157. for(auto & creLevel : dwelling->creatures)
  158. {
  159. if(creLevel.first && creLevel.second.size())
  160. {
  161. auto creature = creLevel.second.back().toCreature();
  162. auto creaturesAreFree = creature->getLevel() == 1;
  163. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->getFullRecruitCost() * creLevel.first))
  164. continue;
  165. score += creature->getAIValue() * creLevel.first;
  166. }
  167. }
  168. return score;
  169. }
  170. uint64_t getDwellingArmyGrowth(CCallback * cb, const CGObjectInstance * target, PlayerColor myColor)
  171. {
  172. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  173. uint64_t score = 0;
  174. if(dwelling->getOwner() == myColor)
  175. return 0;
  176. for(auto & creLevel : dwelling->creatures)
  177. {
  178. if(creLevel.second.size())
  179. {
  180. auto creature = creLevel.second.back().toCreature();
  181. score += creature->getAIValue() * creature->getGrowth();
  182. }
  183. }
  184. return score;
  185. }
  186. int getDwellingArmyCost(const CGObjectInstance * target)
  187. {
  188. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  189. int cost = 0;
  190. for(auto & creLevel : dwelling->creatures)
  191. {
  192. if(creLevel.first && creLevel.second.size())
  193. {
  194. auto creature = creLevel.second.back().toCreature();
  195. auto creaturesAreFree = creature->getLevel() == 1;
  196. if(!creaturesAreFree)
  197. cost += creature->getRecruitCost(EGameResID::GOLD) * creLevel.first;
  198. }
  199. }
  200. return cost;
  201. }
  202. uint64_t evaluateArtifactArmyValue(CArtifactInstance * art)
  203. {
  204. if(art->artType->getId() == ArtifactID::SPELL_SCROLL)
  205. return 1500;
  206. auto statsValue =
  207. 10 * art->valOfBonuses(BonusType::MOVEMENT, 1)
  208. + 1200 * art->valOfBonuses(BonusType::STACKS_SPEED)
  209. + 700 * art->valOfBonuses(BonusType::MORALE)
  210. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::ATTACK)
  211. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE)
  212. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::KNOWLEDGE)
  213. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::SPELL_POWER)
  214. + 500 * art->valOfBonuses(BonusType::LUCK);
  215. auto classValue = 0;
  216. switch(art->artType->aClass)
  217. {
  218. case CArtifact::EartClass::ART_MINOR:
  219. classValue = 1000;
  220. break;
  221. case CArtifact::EartClass::ART_MAJOR:
  222. classValue = 3000;
  223. break;
  224. case CArtifact::EartClass::ART_RELIC:
  225. case CArtifact::EartClass::ART_SPECIAL:
  226. classValue = 8000;
  227. break;
  228. }
  229. return statsValue > classValue ? statsValue : classValue;
  230. }
  231. uint64_t RewardEvaluator::getArmyReward(
  232. const CGObjectInstance * target,
  233. const CGHeroInstance * hero,
  234. const CCreatureSet * army,
  235. bool checkGold) const
  236. {
  237. const float enemyArmyEliminationRewardRatio = 0.5f;
  238. auto relations = ai->cb->getPlayerRelations(target->tempOwner, ai->playerID);
  239. if(!target)
  240. return 0;
  241. switch(target->ID)
  242. {
  243. case Obj::HILL_FORT:
  244. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  245. case Obj::CREATURE_BANK:
  246. return getCreatureBankArmyReward(target, hero);
  247. case Obj::CREATURE_GENERATOR1:
  248. case Obj::CREATURE_GENERATOR2:
  249. case Obj::CREATURE_GENERATOR3:
  250. case Obj::CREATURE_GENERATOR4:
  251. return getDwellingArmyValue(ai->cb.get(), target, checkGold);
  252. case Obj::CRYPT:
  253. case Obj::SHIPWRECK:
  254. case Obj::SHIPWRECK_SURVIVOR:
  255. case Obj::WARRIORS_TOMB:
  256. return 1000;
  257. case Obj::ARTIFACT:
  258. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact);
  259. case Obj::DRAGON_UTOPIA:
  260. return 10000;
  261. case Obj::HERO:
  262. return relations == PlayerRelations::ENEMIES
  263. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  264. : 0;
  265. case Obj::PANDORAS_BOX:
  266. return 5000;
  267. default:
  268. return 0;
  269. }
  270. }
  271. uint64_t RewardEvaluator::getArmyGrowth(
  272. const CGObjectInstance * target,
  273. const CGHeroInstance * hero,
  274. const CCreatureSet * army) const
  275. {
  276. if(!target)
  277. return 0;
  278. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  279. if(relations != PlayerRelations::ENEMIES)
  280. return 0;
  281. switch(target->ID)
  282. {
  283. case Obj::TOWN:
  284. {
  285. auto town = dynamic_cast<const CGTownInstance *>(target);
  286. auto fortLevel = town->fortLevel();
  287. auto neutral = !town->getOwner().isValidPlayer();
  288. auto booster = isAnotherAi(town, *ai->cb) || neutral ? 1 : 2;
  289. if(fortLevel < CGTownInstance::CITADEL)
  290. return town->hasFort() ? booster * 500 : 0;
  291. else
  292. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  293. }
  294. case Obj::CREATURE_GENERATOR1:
  295. case Obj::CREATURE_GENERATOR2:
  296. case Obj::CREATURE_GENERATOR3:
  297. case Obj::CREATURE_GENERATOR4:
  298. return getDwellingArmyGrowth(ai->cb.get(), target, hero->getOwner());
  299. case Obj::ARTIFACT:
  300. // it is not supported now because hero will not sit in town on 7th day but later parts of legion may be counted as army growth as well.
  301. return 0;
  302. default:
  303. return 0;
  304. }
  305. }
  306. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  307. {
  308. if(!target)
  309. return 0;
  310. if(auto * m = dynamic_cast<const IMarket *>(target))
  311. {
  312. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  313. return 2000;
  314. }
  315. switch(target->ID)
  316. {
  317. case Obj::HILL_FORT:
  318. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  319. case Obj::SCHOOL_OF_MAGIC:
  320. case Obj::SCHOOL_OF_WAR:
  321. return 1000;
  322. case Obj::CREATURE_GENERATOR1:
  323. case Obj::CREATURE_GENERATOR2:
  324. case Obj::CREATURE_GENERATOR3:
  325. case Obj::CREATURE_GENERATOR4:
  326. return getDwellingArmyCost(target);
  327. default:
  328. return 0;
  329. }
  330. }
  331. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  332. {
  333. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  334. float objectValue = 0;
  335. for(auto obj : objectsUnderTreat)
  336. {
  337. vstd::amax(objectValue, getStrategicalValue(obj));
  338. }
  339. /*
  340. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  341. Killing the hero is almost as important (0.9) as capturing the object itself.
  342. 2. The formula quickly approaches 1.0 as hero level increases,
  343. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  344. */
  345. return std::min(1.5f, objectValue * 0.9f + (1.5f - (1.5f / (1 + enemy->level))));
  346. }
  347. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  348. {
  349. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  350. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  351. if(requiredResources[resType] == 0)
  352. return 0;
  353. if(dailyIncome[resType] == 0)
  354. return 1.0f;
  355. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  356. return std::min(ratio, 1.0f);
  357. }
  358. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  359. {
  360. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  361. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  362. if(requiredResources[resType] == 0)
  363. return 0;
  364. float ratio = dailyIncome[resType] == 0
  365. ? (float)requiredResources[resType] / 10.0f
  366. : (float)requiredResources[resType] / dailyIncome[resType] / 20.0f;
  367. return std::min(ratio, 2.0f);
  368. }
  369. uint64_t RewardEvaluator::townArmyGrowth(const CGTownInstance * town) const
  370. {
  371. uint64_t result = 0;
  372. for(auto creatureInfo : town->creatures)
  373. {
  374. if(creatureInfo.second.empty())
  375. continue;
  376. auto creature = creatureInfo.second.back().toCreature();
  377. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  378. }
  379. return result;
  380. }
  381. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target) const
  382. {
  383. if(!target)
  384. return 0;
  385. switch(target->ID)
  386. {
  387. case Obj::MINE:
  388. return target->subID == GameResID(EGameResID::GOLD)
  389. ? 0.5f
  390. : 0.4f * getTotalResourceRequirementStrength(target->subID) + 0.1f * getResourceRequirementStrength(target->subID);
  391. case Obj::RESOURCE:
  392. return target->subID == GameResID(EGameResID::GOLD)
  393. ? 0
  394. : 0.2f * getTotalResourceRequirementStrength(target->subID) + 0.4f * getResourceRequirementStrength(target->subID);
  395. case Obj::CREATURE_BANK:
  396. {
  397. auto resourceReward = getCreatureBankResources(target, nullptr);
  398. float sum = 0.0f;
  399. for (TResources::nziterator it (resourceReward); it.valid(); it++)
  400. {
  401. //Evaluate resources used for construction. Gold is evaluated separately.
  402. if (it->resType != EGameResID::GOLD)
  403. {
  404. sum += 0.1f * getResourceRequirementStrength(it->resType);
  405. }
  406. }
  407. return sum;
  408. }
  409. case Obj::TOWN:
  410. {
  411. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  412. return 10.0f;
  413. auto town = dynamic_cast<const CGTownInstance *>(target);
  414. if(town->getOwner() == ai->playerID)
  415. {
  416. auto armyIncome = townArmyGrowth(town);
  417. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  418. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  419. }
  420. auto fortLevel = town->fortLevel();
  421. auto booster = isAnotherAi(town, *ai->cb) ? 0.4f : 1.0f;
  422. if(town->hasCapitol())
  423. return booster * 1.5;
  424. if(fortLevel < CGTownInstance::CITADEL)
  425. return booster * (town->hasFort() ? 1.0 : 0.8);
  426. else
  427. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  428. }
  429. case Obj::HERO:
  430. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  431. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  432. : 0;
  433. default:
  434. return 0;
  435. }
  436. }
  437. float RewardEvaluator::evaluateWitchHutSkillScore(const CGWitchHut * hut, const CGHeroInstance * hero, HeroRole role) const
  438. {
  439. if(!hut->wasVisited(hero->tempOwner))
  440. return role == HeroRole::SCOUT ? 2 : 0;
  441. auto skill = SecondarySkill(hut->ability);
  442. if(hero->getSecSkillLevel(skill) != SecSkillLevel::NONE
  443. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  444. return 0;
  445. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  446. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  447. }
  448. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  449. {
  450. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  451. if(!target)
  452. return 0;
  453. switch(target->ID)
  454. {
  455. case Obj::STAR_AXIS:
  456. case Obj::SCHOLAR:
  457. case Obj::SCHOOL_OF_MAGIC:
  458. case Obj::SCHOOL_OF_WAR:
  459. case Obj::GARDEN_OF_REVELATION:
  460. case Obj::MARLETTO_TOWER:
  461. case Obj::MERCENARY_CAMP:
  462. case Obj::TREE_OF_KNOWLEDGE:
  463. return 1;
  464. case Obj::LEARNING_STONE:
  465. return 1.0f / std::sqrt(hero->level);
  466. case Obj::ARENA:
  467. return 2;
  468. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  469. return 0.2f;
  470. case Obj::SHRINE_OF_MAGIC_GESTURE:
  471. return 0.3f;
  472. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  473. return 0.5f;
  474. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  475. return 8;
  476. case Obj::WITCH_HUT:
  477. return evaluateWitchHutSkillScore(dynamic_cast<const CGWitchHut *>(target), hero, role);
  478. case Obj::PANDORAS_BOX:
  479. //Can contains experience, spells, or skills (only on custom maps)
  480. return 2.5f;
  481. case Obj::HERO:
  482. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  483. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  484. : 0;
  485. default:
  486. return 0;
  487. }
  488. }
  489. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  490. {
  491. auto & treatNode = ai->dangerHitMap->getTileTreat(tile);
  492. if(treatNode.maximumDanger.danger == 0)
  493. return HitMapInfo::NoTreat;
  494. if(treatNode.maximumDanger.turn <= turn)
  495. return treatNode.maximumDanger;
  496. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoTreat;
  497. }
  498. int32_t getArmyCost(const CArmedInstance * army)
  499. {
  500. int32_t value = 0;
  501. for(auto stack : army->Slots())
  502. {
  503. value += stack.second->getCreatureID().toCreature()->getRecruitCost(EGameResID::GOLD) * stack.second->count;
  504. }
  505. return value;
  506. }
  507. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  508. {
  509. if(!target)
  510. return 0;
  511. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  512. const int dailyIncomeMultiplier = 5;
  513. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  514. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  515. auto isGold = target->subID == GameResID(EGameResID::GOLD); // TODO: other resorces could be sold but need to evaluate market power
  516. switch(target->ID)
  517. {
  518. case Obj::RESOURCE:
  519. return isGold ? 600 : 100;
  520. case Obj::TREASURE_CHEST:
  521. return 1500;
  522. case Obj::WATER_WHEEL:
  523. return 1000;
  524. case Obj::TOWN:
  525. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  526. case Obj::MINE:
  527. case Obj::ABANDONED_MINE:
  528. return dailyIncomeMultiplier * (isGold ? 1000 : 75);
  529. case Obj::MYSTICAL_GARDEN:
  530. case Obj::WINDMILL:
  531. return 100;
  532. case Obj::CAMPFIRE:
  533. return 800;
  534. case Obj::WAGON:
  535. return 100;
  536. case Obj::CREATURE_BANK:
  537. return getCreatureBankResources(target, hero)[EGameResID::GOLD];
  538. case Obj::CRYPT:
  539. case Obj::DERELICT_SHIP:
  540. return 3000;
  541. case Obj::DRAGON_UTOPIA:
  542. return 10000;
  543. case Obj::SEA_CHEST:
  544. return 1500;
  545. case Obj::PANDORAS_BOX:
  546. return 2500;
  547. case Obj::PRISON:
  548. //Objectively saves us 2500 to hire hero
  549. return GameConstants::HERO_GOLD_COST;
  550. case Obj::HERO:
  551. return relations == PlayerRelations::ENEMIES
  552. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  553. : 0;
  554. default:
  555. return 0;
  556. }
  557. }
  558. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  559. {
  560. public:
  561. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  562. {
  563. if(task->goalType != Goals::HERO_EXCHANGE)
  564. return;
  565. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  566. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength();
  567. evaluationContext.addNonCriticalStrategicalValue(2.0f * armyStrength / (float)heroExchange.hero.get()->getArmyStrength());
  568. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroExchange.hero.get());
  569. }
  570. };
  571. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  572. {
  573. public:
  574. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  575. {
  576. if(task->goalType != Goals::ARMY_UPGRADE)
  577. return;
  578. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  579. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  580. evaluationContext.armyReward += upgradeValue;
  581. evaluationContext.addNonCriticalStrategicalValue(upgradeValue / (float)armyUpgrade.hero->getArmyStrength());
  582. }
  583. };
  584. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  585. {
  586. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  587. if(enemyDanger.danger)
  588. {
  589. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  590. auto enemyHero = evaluationContext.evaluator.ai->cb->getObj(enemyDanger.hero.hid, false);
  591. bool isAI = enemyHero && isAnotherAi(enemyHero, *evaluationContext.evaluator.ai->cb);
  592. if(isAI)
  593. {
  594. dangerRatio *= 1.5; // lets make AI bit more afraid of other AI.
  595. }
  596. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  597. }
  598. }
  599. class DefendTownEvaluator : public IEvaluationContextBuilder
  600. {
  601. public:
  602. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  603. {
  604. if(task->goalType != Goals::DEFEND_TOWN)
  605. return;
  606. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  607. const CGTownInstance * town = defendTown.town;
  608. auto & treat = defendTown.getTreat();
  609. auto strategicalValue = evaluationContext.evaluator.getStrategicalValue(town);
  610. float multiplier = 1;
  611. if(treat.turn < defendTown.getTurn())
  612. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  613. multiplier /= 1.0f + treat.turn / 5.0f;
  614. if(defendTown.getTurn() > 0 && defendTown.isCounterAttack())
  615. {
  616. auto ourSpeed = defendTown.hero->movementPointsLimit(true);
  617. auto enemySpeed = treat.hero->movementPointsLimit(true);
  618. if(enemySpeed > ourSpeed) multiplier *= 0.7f;
  619. }
  620. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  621. auto armyGrowth = evaluationContext.evaluator.townArmyGrowth(town);
  622. evaluationContext.armyGrowth += armyGrowth * multiplier;
  623. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  624. if(evaluationContext.evaluator.ai->buildAnalyzer->getDevelopmentInfo().size() == 1)
  625. vstd::amax(evaluationContext.strategicalValue, 2.5f * multiplier * strategicalValue);
  626. else
  627. evaluationContext.addNonCriticalStrategicalValue(1.7f * multiplier * strategicalValue);
  628. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  629. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  630. }
  631. };
  632. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  633. {
  634. private:
  635. const Nullkiller * ai;
  636. public:
  637. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  638. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  639. {
  640. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  641. return;
  642. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  643. const AIPath & path = chain.getPath();
  644. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  645. evaluationContext.movementCost += path.movementCost();
  646. evaluationContext.closestWayRatio = chain.closestWayRatio;
  647. std::map<const CGHeroInstance *, float> costsPerHero;
  648. for(auto & node : path.nodes)
  649. {
  650. vstd::amax(costsPerHero[node.targetHero], node.cost);
  651. }
  652. for(auto pair : costsPerHero)
  653. {
  654. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  655. evaluationContext.movementCostByRole[role] += pair.second;
  656. }
  657. auto heroPtr = task->hero;
  658. auto hero = heroPtr.get(ai->cb.get());
  659. bool checkGold = evaluationContext.danger == 0;
  660. auto army = path.heroArmy;
  661. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  662. auto heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroPtr);
  663. if(heroRole == HeroRole::MAIN)
  664. evaluationContext.heroRole = heroRole;
  665. if (target)
  666. {
  667. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  668. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  669. evaluationContext.armyGrowth += evaluationContext.evaluator.getArmyGrowth(target, hero, army);
  670. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, heroRole);
  671. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target));
  672. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  673. }
  674. vstd::amax(evaluationContext.armyLossPersentage, path.getTotalArmyLoss() / (double)path.getHeroStrength());
  675. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  676. vstd::amax(evaluationContext.turn, path.turn());
  677. }
  678. };
  679. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  680. {
  681. public:
  682. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  683. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  684. {
  685. if(task->goalType != Goals::UNLOCK_CLUSTER)
  686. return;
  687. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  688. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  689. auto hero = clusterGoal.hero.get();
  690. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(clusterGoal.hero);
  691. std::vector<std::pair<const CGObjectInstance *, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  692. std::sort(objects.begin(), objects.end(), [](std::pair<const CGObjectInstance *, ClusterObjectInfo> o1, std::pair<const CGObjectInstance *, ClusterObjectInfo> o2) -> bool
  693. {
  694. return o1.second.priority > o2.second.priority;
  695. });
  696. int boost = 1;
  697. for(auto objInfo : objects)
  698. {
  699. auto target = objInfo.first;
  700. bool checkGold = objInfo.second.danger == 0;
  701. auto army = hero;
  702. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  703. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  704. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  705. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target) / boost);
  706. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  707. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  708. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  709. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  710. boost <<= 1;
  711. if(boost > 8)
  712. break;
  713. }
  714. }
  715. };
  716. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  717. {
  718. public:
  719. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  720. {
  721. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  722. return;
  723. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  724. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  725. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  726. {
  727. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  728. auto mpLeft = garrisonHero->movementPointsRemaining() / (float)garrisonHero->movementPointsLimit(true);
  729. evaluationContext.movementCost += mpLeft;
  730. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  731. evaluationContext.heroRole = defenderRole;
  732. }
  733. }
  734. };
  735. class DismissHeroContextBuilder : public IEvaluationContextBuilder
  736. {
  737. private:
  738. const Nullkiller * ai;
  739. public:
  740. DismissHeroContextBuilder(const Nullkiller * ai) : ai(ai) {}
  741. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  742. {
  743. if(task->goalType != Goals::DISMISS_HERO)
  744. return;
  745. Goals::DismissHero & dismissCommand = dynamic_cast<Goals::DismissHero &>(*task);
  746. const CGHeroInstance * dismissedHero = dismissCommand.getHero().get();
  747. auto role = ai->heroManager->getHeroRole(dismissedHero);
  748. auto mpLeft = dismissedHero->movementPointsRemaining();
  749. evaluationContext.movementCost += mpLeft;
  750. evaluationContext.movementCostByRole[role] += mpLeft;
  751. evaluationContext.goldCost += GameConstants::HERO_GOLD_COST + getArmyCost(dismissedHero);
  752. }
  753. };
  754. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  755. {
  756. public:
  757. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  758. {
  759. if(task->goalType != Goals::BUILD_STRUCTURE)
  760. return;
  761. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  762. auto & bi = buildThis.buildingInfo;
  763. evaluationContext.goldReward += 7 * bi.dailyIncome[EGameResID::GOLD] / 2; // 7 day income but half we already have
  764. evaluationContext.heroRole = HeroRole::MAIN;
  765. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  766. evaluationContext.goldCost += bi.buildCostWithPrerequisits[EGameResID::GOLD];
  767. evaluationContext.closestWayRatio = 1;
  768. if(bi.creatureID != CreatureID::NONE)
  769. {
  770. evaluationContext.addNonCriticalStrategicalValue(buildThis.townInfo.armyStrength / 50000.0);
  771. if(bi.baseCreatureID == bi.creatureID)
  772. {
  773. evaluationContext.addNonCriticalStrategicalValue((0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount);
  774. evaluationContext.armyReward += bi.armyStrength;
  775. }
  776. else
  777. {
  778. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  779. evaluationContext.addNonCriticalStrategicalValue(potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount);
  780. evaluationContext.armyReward += potentialUpgradeValue / (float)bi.prerequisitesCount;
  781. }
  782. }
  783. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  784. {
  785. evaluationContext.addNonCriticalStrategicalValue(buildThis.town->creatures.size() * 0.2f);
  786. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  787. }
  788. else if(bi.id >= BuildingID::MAGES_GUILD_1 && bi.id <= BuildingID::MAGES_GUILD_5)
  789. {
  790. evaluationContext.skillReward += 2 * (bi.id - BuildingID::MAGES_GUILD_1);
  791. }
  792. if(evaluationContext.goldReward)
  793. {
  794. auto goldPreasure = evaluationContext.evaluator.ai->buildAnalyzer->getGoldPreasure();
  795. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPreasure / 3500.0f / bi.prerequisitesCount);
  796. }
  797. if(bi.notEnoughRes && bi.prerequisitesCount == 1)
  798. {
  799. evaluationContext.strategicalValue /= 3;
  800. evaluationContext.movementCostByRole[evaluationContext.heroRole] += 5;
  801. evaluationContext.turn += 5;
  802. }
  803. }
  804. };
  805. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  806. {
  807. if(ai->buildAnalyzer->hasAnyBuilding(town->subID, bi.id))
  808. return 0;
  809. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  810. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  811. return upgradedPower - creaturesToUpgrade.power;
  812. }
  813. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  814. :ai(ai)
  815. {
  816. initVisitTile();
  817. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  818. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  819. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  820. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  821. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  822. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  823. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  824. evaluationContextBuilders.push_back(std::make_shared<DismissHeroContextBuilder>(ai));
  825. }
  826. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  827. {
  828. Goals::TGoalVec parts;
  829. EvaluationContext context(ai);
  830. if(goal->goalType == Goals::COMPOSITION)
  831. {
  832. parts = goal->decompose();
  833. }
  834. else
  835. {
  836. parts.push_back(goal);
  837. }
  838. for(auto subgoal : parts)
  839. {
  840. context.goldCost += subgoal->goldCost;
  841. for(auto builder : evaluationContextBuilders)
  842. {
  843. builder->buildEvaluationContext(context, subgoal);
  844. }
  845. }
  846. return context;
  847. }
  848. float PriorityEvaluator::evaluate(Goals::TSubgoal task)
  849. {
  850. auto evaluationContext = buildEvaluationContext(task);
  851. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  852. + (evaluationContext.armyReward > 0 ? 1 : 0)
  853. + (evaluationContext.skillReward > 0 ? 1 : 0)
  854. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  855. float goldRewardPerTurn = evaluationContext.goldReward / std::log2f(2 + evaluationContext.movementCost * 10);
  856. double result = 0;
  857. try
  858. {
  859. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  860. heroRoleVariable->setValue(evaluationContext.heroRole);
  861. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  862. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  863. goldRewardVariable->setValue(goldRewardPerTurn);
  864. armyRewardVariable->setValue(evaluationContext.armyReward);
  865. armyGrowthVariable->setValue(evaluationContext.armyGrowth);
  866. skillRewardVariable->setValue(evaluationContext.skillReward);
  867. dangerVariable->setValue(evaluationContext.danger);
  868. rewardTypeVariable->setValue(rewardType);
  869. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  870. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  871. goldPreasureVariable->setValue(ai->buildAnalyzer->getGoldPreasure());
  872. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  873. turnVariable->setValue(evaluationContext.turn);
  874. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  875. engine->process();
  876. result = value->getValue();
  877. }
  878. catch(fl::Exception & fe)
  879. {
  880. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  881. }
  882. #if NKAI_TRACE_LEVEL >= 2
  883. logAi->trace("Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, gold: %f, cost: %d, army gain: %d, danger: %d, role: %s, strategical value: %f, cwr: %f, fear: %f, result %f",
  884. task->toString(),
  885. evaluationContext.armyLossPersentage,
  886. (int)evaluationContext.turn,
  887. evaluationContext.movementCostByRole[HeroRole::MAIN],
  888. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  889. goldRewardPerTurn,
  890. evaluationContext.goldCost,
  891. evaluationContext.armyReward,
  892. evaluationContext.danger,
  893. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  894. evaluationContext.strategicalValue,
  895. evaluationContext.closestWayRatio,
  896. evaluationContext.enemyHeroDangerRatio,
  897. result);
  898. #endif
  899. return result;
  900. }
  901. }