PriorityEvaluator.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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/StayAtTown.h"
  25. #include "../Goals/ExchangeSwapTownHeroes.h"
  26. #include "../Goals/DismissHero.h"
  27. #include "../Markers/UnlockCluster.h"
  28. #include "../Markers/HeroExchange.h"
  29. #include "../Markers/ArmyUpgrade.h"
  30. #include "../Markers/DefendTown.h"
  31. namespace NKAI
  32. {
  33. #define MIN_AI_STRENGTH (0.5f) //lower when combat AI gets smarter
  34. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  35. const float MIN_CRITICAL_VALUE = 2.0f;
  36. EvaluationContext::EvaluationContext(const Nullkiller* ai)
  37. : movementCost(0.0),
  38. manaCost(0),
  39. danger(0),
  40. closestWayRatio(1),
  41. movementCostByRole(),
  42. skillReward(0),
  43. goldReward(0),
  44. goldCost(0),
  45. armyReward(0),
  46. armyLossPersentage(0),
  47. heroRole(HeroRole::SCOUT),
  48. turn(0),
  49. strategicalValue(0),
  50. conquestValue(0),
  51. evaluator(ai),
  52. enemyHeroDangerRatio(0),
  53. threat(0),
  54. armyGrowth(0),
  55. armyInvolvement(0),
  56. defenseValue(0),
  57. isDefend(false),
  58. threatTurns(INT_MAX),
  59. involvesSailing(false),
  60. isTradeBuilding(false),
  61. isChain(false),
  62. isEnemy(false)
  63. {
  64. }
  65. void EvaluationContext::addNonCriticalStrategicalValue(float value)
  66. {
  67. vstd::amax(strategicalValue, std::min(value, MIN_CRITICAL_VALUE));
  68. }
  69. PriorityEvaluator::~PriorityEvaluator()
  70. {
  71. delete engine;
  72. }
  73. void PriorityEvaluator::initVisitTile()
  74. {
  75. auto file = CResourceHandler::get()->load(ResourcePath("config/ai/nkai/object-priorities.txt"))->readAll();
  76. std::string str = std::string((char *)file.first.get(), file.second);
  77. engine = fl::FllImporter().fromString(str);
  78. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  79. armyGrowthVariable = engine->getInputVariable("armyGrowth");
  80. heroRoleVariable = engine->getInputVariable("heroRole");
  81. dangerVariable = engine->getInputVariable("danger");
  82. turnVariable = engine->getInputVariable("turn");
  83. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  84. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  85. goldRewardVariable = engine->getInputVariable("goldReward");
  86. armyRewardVariable = engine->getInputVariable("armyReward");
  87. skillRewardVariable = engine->getInputVariable("skillReward");
  88. rewardTypeVariable = engine->getInputVariable("rewardType");
  89. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  90. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  91. goldPressureVariable = engine->getInputVariable("goldPressure");
  92. goldCostVariable = engine->getInputVariable("goldCost");
  93. fearVariable = engine->getInputVariable("fear");
  94. value = engine->getOutputVariable("Value");
  95. }
  96. bool isAnotherAi(const CGObjectInstance * obj, const CPlayerSpecificInfoCallback & cb)
  97. {
  98. return obj->getOwner().isValidPlayer()
  99. && cb.getStartInfo()->getIthPlayersSettings(obj->getOwner()).isControlledByAI();
  100. }
  101. int32_t estimateTownIncome(CCallback * cb, const CGObjectInstance * target, const CGHeroInstance * hero)
  102. {
  103. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  104. if(relations != PlayerRelations::ENEMIES)
  105. return 0; // if we already own it, no additional reward will be received by just visiting it
  106. auto booster = isAnotherAi(target, *cb) ? 1 : 2;
  107. auto town = cb->getTown(target->id);
  108. auto fortLevel = town->fortLevel();
  109. if(town->hasCapitol())
  110. return booster * 2000;
  111. // probably well developed town will have city hall
  112. if(fortLevel == CGTownInstance::CASTLE) return booster * 750;
  113. return booster * (town->hasFort() && town->tempOwner != PlayerColor::NEUTRAL ? booster * 500 : 250);
  114. }
  115. TResources getCreatureBankResources(const CGObjectInstance * target, const CGHeroInstance * hero)
  116. {
  117. //Fixme: unused variable hero
  118. auto objectInfo = target->getObjectHandler()->getObjectInfo(target->appearance);
  119. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  120. auto resources = bankInfo->getPossibleResourcesReward();
  121. TResources result = TResources();
  122. int sum = 0;
  123. for(auto & reward : resources)
  124. {
  125. result += reward.data * reward.chance;
  126. sum += reward.chance;
  127. }
  128. return sum > 1 ? result / sum : result;
  129. }
  130. int32_t getResourcesGoldReward(const TResources & res)
  131. {
  132. int32_t result = 0;
  133. for(EGameResID r = EGameResID(0); r < EGameResID::COUNT; r.advance(1))
  134. {
  135. if(res[r] > 0)
  136. {
  137. result += r == EGameResID::GOLD ? res[r] : res[r] * 100;
  138. }
  139. }
  140. return result;
  141. }
  142. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  143. {
  144. auto objectInfo = target->getObjectHandler()->getObjectInfo(target->appearance);
  145. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  146. auto creatures = bankInfo->getPossibleCreaturesReward(target->cb);
  147. uint64_t result = 0;
  148. const auto& slots = hero->Slots();
  149. ui64 weakestStackPower = 0;
  150. int duplicatingSlots = getDuplicatingSlots(hero);
  151. if (slots.size() >= GameConstants::ARMY_SIZE)
  152. {
  153. //No free slot, we might discard our weakest stack
  154. weakestStackPower = std::numeric_limits<ui64>().max();
  155. for (const auto & stack : slots)
  156. {
  157. vstd::amin(weakestStackPower, stack.second->getPower());
  158. }
  159. }
  160. for (auto c : creatures)
  161. {
  162. //Only if hero has slot for this creature in the army
  163. auto ccre = dynamic_cast<const CCreature*>(c.data.type);
  164. if (hero->getSlotFor(ccre).validSlot() || duplicatingSlots > 0)
  165. {
  166. result += (c.data.type->getAIValue() * c.data.count) * c.chance;
  167. }
  168. /*else
  169. {
  170. //we will need to discard the weakest stack
  171. result += (c.data.type->getAIValue() * c.data.count - weakestStackPower) * c.chance;
  172. }*/
  173. }
  174. result /= 100; //divide by total chance
  175. return result;
  176. }
  177. uint64_t getDwellingArmyValue(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  178. {
  179. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  180. uint64_t score = 0;
  181. for(auto & creLevel : dwelling->creatures)
  182. {
  183. if(creLevel.first && creLevel.second.size())
  184. {
  185. auto creature = creLevel.second.back().toCreature();
  186. auto creaturesAreFree = creature->getLevel() == 1;
  187. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->getFullRecruitCost() * creLevel.first))
  188. continue;
  189. score += creature->getAIValue() * creLevel.first;
  190. }
  191. }
  192. return score;
  193. }
  194. uint64_t getDwellingArmyGrowth(CCallback * cb, const CGObjectInstance * target, PlayerColor myColor)
  195. {
  196. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  197. uint64_t score = 0;
  198. if(dwelling->getOwner() == myColor)
  199. return 0;
  200. for(auto & creLevel : dwelling->creatures)
  201. {
  202. if(creLevel.second.size())
  203. {
  204. auto creature = creLevel.second.back().toCreature();
  205. score += creature->getAIValue() * creature->getGrowth();
  206. }
  207. }
  208. return score;
  209. }
  210. int getDwellingArmyCost(const CGObjectInstance * target)
  211. {
  212. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  213. int cost = 0;
  214. for(auto & creLevel : dwelling->creatures)
  215. {
  216. if(creLevel.first && creLevel.second.size())
  217. {
  218. auto creature = creLevel.second.back().toCreature();
  219. auto creaturesAreFree = creature->getLevel() == 1;
  220. if(!creaturesAreFree)
  221. cost += creature->getFullRecruitCost().marketValue() * creLevel.first;
  222. }
  223. }
  224. return cost;
  225. }
  226. static uint64_t evaluateArtifactArmyValue(const CArtifact * art)
  227. {
  228. if(art->getId() == ArtifactID::SPELL_SCROLL)
  229. return 1500;
  230. auto statsValue =
  231. 10 * art->valOfBonuses(BonusType::MOVEMENT, BonusCustomSubtype::heroMovementLand)
  232. + 1200 * art->valOfBonuses(BonusType::STACKS_SPEED)
  233. + 700 * art->valOfBonuses(BonusType::MORALE)
  234. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::ATTACK))
  235. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE))
  236. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::KNOWLEDGE))
  237. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::SPELL_POWER))
  238. + 500 * art->valOfBonuses(BonusType::LUCK);
  239. auto classValue = 0;
  240. switch(art->aClass)
  241. {
  242. case CArtifact::EartClass::ART_MINOR:
  243. classValue = 1000;
  244. break;
  245. case CArtifact::EartClass::ART_MAJOR:
  246. classValue = 3000;
  247. break;
  248. case CArtifact::EartClass::ART_RELIC:
  249. case CArtifact::EartClass::ART_SPECIAL:
  250. classValue = 8000;
  251. break;
  252. }
  253. return statsValue > classValue ? statsValue : classValue;
  254. }
  255. uint64_t RewardEvaluator::getArmyReward(
  256. const CGObjectInstance * target,
  257. const CGHeroInstance * hero,
  258. const CCreatureSet * army,
  259. bool checkGold) const
  260. {
  261. const float enemyArmyEliminationRewardRatio = 0.5f;
  262. auto relations = ai->cb->getPlayerRelations(target->tempOwner, ai->playerID);
  263. if(!target)
  264. return 0;
  265. switch(target->ID)
  266. {
  267. case Obj::HILL_FORT:
  268. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  269. case Obj::CREATURE_BANK:
  270. return getCreatureBankArmyReward(target, hero);
  271. case Obj::CREATURE_GENERATOR1:
  272. case Obj::CREATURE_GENERATOR2:
  273. case Obj::CREATURE_GENERATOR3:
  274. case Obj::CREATURE_GENERATOR4:
  275. return getDwellingArmyValue(ai->cb.get(), target, checkGold);
  276. case Obj::CRYPT:
  277. case Obj::SHIPWRECK:
  278. case Obj::SHIPWRECK_SURVIVOR:
  279. case Obj::WARRIORS_TOMB:
  280. return 1000;
  281. case Obj::ARTIFACT:
  282. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact->artType);
  283. case Obj::DRAGON_UTOPIA:
  284. return 10000;
  285. case Obj::HERO:
  286. return relations == PlayerRelations::ENEMIES
  287. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  288. : 0;
  289. case Obj::PANDORAS_BOX:
  290. return 5000;
  291. case Obj::MAGIC_WELL:
  292. case Obj::MAGIC_SPRING:
  293. return getManaRecoveryArmyReward(hero);
  294. default:
  295. break;
  296. }
  297. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  298. if(rewardable)
  299. {
  300. auto totalValue = 0;
  301. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  302. {
  303. auto & info = rewardable->configuration.info[index];
  304. auto rewardValue = 0;
  305. if(!info.reward.artifacts.empty())
  306. {
  307. for(auto artID : info.reward.artifacts)
  308. {
  309. const CArtifact * art = dynamic_cast<const CArtifact *>(VLC->artifacts()->getById(artID));
  310. rewardValue += evaluateArtifactArmyValue(art);
  311. }
  312. }
  313. if(!info.reward.creatures.empty())
  314. {
  315. for(auto stackInfo : info.reward.creatures)
  316. {
  317. rewardValue += stackInfo.getType()->getAIValue() * stackInfo.getCount();
  318. }
  319. }
  320. totalValue += rewardValue > 0 ? rewardValue / (info.reward.artifacts.size() + info.reward.creatures.size()) : 0;
  321. }
  322. return totalValue;
  323. }
  324. return 0;
  325. }
  326. uint64_t RewardEvaluator::getArmyGrowth(
  327. const CGObjectInstance * target,
  328. const CGHeroInstance * hero,
  329. const CCreatureSet * army) const
  330. {
  331. if(!target)
  332. return 0;
  333. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  334. if(relations != PlayerRelations::ENEMIES)
  335. return 0;
  336. switch(target->ID)
  337. {
  338. case Obj::TOWN:
  339. {
  340. auto town = dynamic_cast<const CGTownInstance *>(target);
  341. auto fortLevel = town->fortLevel();
  342. auto neutral = !town->getOwner().isValidPlayer();
  343. auto booster = isAnotherAi(town, *ai->cb) || neutral ? 1 : 2;
  344. if(fortLevel < CGTownInstance::CITADEL)
  345. return town->hasFort() ? booster * 500 : 0;
  346. else
  347. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  348. }
  349. case Obj::CREATURE_GENERATOR1:
  350. case Obj::CREATURE_GENERATOR2:
  351. case Obj::CREATURE_GENERATOR3:
  352. case Obj::CREATURE_GENERATOR4:
  353. return getDwellingArmyGrowth(ai->cb.get(), target, hero->getOwner());
  354. case Obj::ARTIFACT:
  355. // 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.
  356. return 0;
  357. default:
  358. return 0;
  359. }
  360. }
  361. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  362. {
  363. if(!target)
  364. return 0;
  365. if(auto * m = dynamic_cast<const IMarket *>(target))
  366. {
  367. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  368. return 2000;
  369. }
  370. switch(target->ID)
  371. {
  372. case Obj::HILL_FORT:
  373. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  374. case Obj::SCHOOL_OF_MAGIC:
  375. case Obj::SCHOOL_OF_WAR:
  376. return 1000;
  377. case Obj::CREATURE_GENERATOR1:
  378. case Obj::CREATURE_GENERATOR2:
  379. case Obj::CREATURE_GENERATOR3:
  380. case Obj::CREATURE_GENERATOR4:
  381. return getDwellingArmyCost(target);
  382. default:
  383. return 0;
  384. }
  385. }
  386. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  387. {
  388. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  389. float objectValue = 0;
  390. for(auto obj : objectsUnderTreat)
  391. {
  392. vstd::amax(objectValue, getStrategicalValue(obj));
  393. }
  394. /*
  395. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  396. Killing the hero is almost as important (0.9) as capturing the object itself.
  397. 2. The formula quickly approaches 1.0 as hero level increases,
  398. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  399. */
  400. return std::min(1.5f, objectValue * 0.9f + (1.5f - (1.5f / (1 + enemy->level))));
  401. }
  402. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  403. {
  404. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  405. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  406. if(requiredResources[resType] == 0)
  407. return 0;
  408. if(dailyIncome[resType] == 0)
  409. return 1.0f;
  410. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  411. return std::min(ratio, 1.0f);
  412. }
  413. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  414. {
  415. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  416. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  417. if(requiredResources[resType] == 0)
  418. return 0;
  419. float ratio = dailyIncome[resType] == 0
  420. ? (float)requiredResources[resType] / 10.0f
  421. : (float)requiredResources[resType] / dailyIncome[resType] / 20.0f;
  422. return std::min(ratio, 2.0f);
  423. }
  424. uint64_t RewardEvaluator::townArmyGrowth(const CGTownInstance * town) const
  425. {
  426. uint64_t result = 0;
  427. for(auto creatureInfo : town->creatures)
  428. {
  429. if(creatureInfo.second.empty())
  430. continue;
  431. auto creature = creatureInfo.second.back().toCreature();
  432. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  433. }
  434. return result;
  435. }
  436. uint64_t RewardEvaluator::getManaRecoveryArmyReward(const CGHeroInstance * hero) const
  437. {
  438. return ai->heroManager->getMagicStrength(hero) * 10000 * (1.0f - std::sqrt(static_cast<float>(hero->mana) / hero->manaLimit()));
  439. }
  440. float RewardEvaluator::getResourceRequirementStrength(const TResources & res) const
  441. {
  442. float sum = 0.0f;
  443. for(TResources::nziterator it(res); it.valid(); it++)
  444. {
  445. //Evaluate resources used for construction. Gold is evaluated separately.
  446. if(it->resType != EGameResID::GOLD)
  447. {
  448. sum += 0.1f * it->resVal * getResourceRequirementStrength(it->resType)
  449. + 0.05f * it->resVal * getTotalResourceRequirementStrength(it->resType);
  450. }
  451. }
  452. return sum;
  453. }
  454. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target, const CGHeroInstance * hero) const
  455. {
  456. if(!target)
  457. return 0;
  458. switch(target->ID)
  459. {
  460. case Obj::MINE:
  461. {
  462. auto mine = dynamic_cast<const CGMine *>(target);
  463. return mine->producedResource == EGameResID::GOLD
  464. ? 0.5f
  465. : 0.4f * getTotalResourceRequirementStrength(mine->producedResource) + 0.1f * getResourceRequirementStrength(mine->producedResource);
  466. }
  467. case Obj::RESOURCE:
  468. {
  469. auto resource = dynamic_cast<const CGResource *>(target);
  470. TResources res;
  471. res[resource->resourceID()] = resource->amount;
  472. return getResourceRequirementStrength(res);
  473. }
  474. case Obj::CREATURE_BANK:
  475. {
  476. auto resourceReward = getCreatureBankResources(target, nullptr);
  477. return getResourceRequirementStrength(resourceReward);
  478. }
  479. case Obj::TOWN:
  480. {
  481. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  482. return 10.0f;
  483. auto town = dynamic_cast<const CGTownInstance *>(target);
  484. if(town->getOwner() == ai->playerID)
  485. {
  486. auto armyIncome = townArmyGrowth(town);
  487. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  488. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  489. }
  490. auto fortLevel = town->fortLevel();
  491. auto booster = isAnotherAi(town, *ai->cb) ? 0.4f : 1.0f;
  492. if(town->hasCapitol())
  493. return booster * 1.5;
  494. if(fortLevel < CGTownInstance::CITADEL)
  495. return booster * (town->hasFort() ? 1.0 : 0.8);
  496. else
  497. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  498. }
  499. case Obj::HERO:
  500. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  501. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  502. : 0;
  503. case Obj::KEYMASTER:
  504. return 0.6f;
  505. default:
  506. break;
  507. }
  508. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  509. if(rewardable && hero)
  510. {
  511. auto resourceReward = 0.0f;
  512. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  513. {
  514. resourceReward += getResourceRequirementStrength(rewardable->configuration.info[index].reward.resources);
  515. }
  516. return resourceReward;
  517. }
  518. return 0;
  519. }
  520. float RewardEvaluator::getConquestValue(const CGObjectInstance* target) const
  521. {
  522. if (!target)
  523. return 0;
  524. if (target->getOwner() == ai->playerID)
  525. return 0;
  526. switch (target->ID)
  527. {
  528. case Obj::TOWN:
  529. {
  530. if (ai->buildAnalyzer->getDevelopmentInfo().empty())
  531. return 10.0f;
  532. auto town = dynamic_cast<const CGTownInstance*>(target);
  533. if (town->getOwner() == ai->playerID)
  534. {
  535. auto armyIncome = townArmyGrowth(town);
  536. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  537. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  538. }
  539. auto fortLevel = town->fortLevel();
  540. auto booster = 1.0f;
  541. if (town->hasCapitol())
  542. return booster * 1.5;
  543. if (fortLevel < CGTownInstance::CITADEL)
  544. return booster * (town->hasFort() ? 1.0 : 0.8);
  545. else
  546. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  547. }
  548. case Obj::HERO:
  549. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  550. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance*>(target))
  551. : 0;
  552. case Obj::KEYMASTER:
  553. return 0.6f;
  554. default:
  555. return 0;
  556. }
  557. }
  558. float RewardEvaluator::evaluateWitchHutSkillScore(const CGObjectInstance * hut, const CGHeroInstance * hero, HeroRole role) const
  559. {
  560. auto rewardable = dynamic_cast<const CRewardableObject *>(hut);
  561. assert(rewardable);
  562. auto skill = SecondarySkill(*rewardable->configuration.getVariable("secondarySkill", "gainedSkill"));
  563. if(!hut->wasVisited(hero->tempOwner))
  564. return role == HeroRole::SCOUT ? 2 : 0;
  565. if(hero->getSecSkillLevel(skill) != MasteryLevel::NONE
  566. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  567. return 0;
  568. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  569. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  570. }
  571. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  572. {
  573. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  574. if(!target)
  575. return 0;
  576. switch(target->ID)
  577. {
  578. case Obj::STAR_AXIS:
  579. case Obj::SCHOLAR:
  580. case Obj::SCHOOL_OF_MAGIC:
  581. case Obj::SCHOOL_OF_WAR:
  582. case Obj::GARDEN_OF_REVELATION:
  583. case Obj::MARLETTO_TOWER:
  584. case Obj::MERCENARY_CAMP:
  585. case Obj::TREE_OF_KNOWLEDGE:
  586. return 1;
  587. case Obj::LEARNING_STONE:
  588. return 1.0f / std::sqrt(hero->level);
  589. case Obj::ARENA:
  590. return 2;
  591. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  592. return 0.25f;
  593. case Obj::SHRINE_OF_MAGIC_GESTURE:
  594. return 1.0f;
  595. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  596. return 2.0f;
  597. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  598. return 8;
  599. case Obj::WITCH_HUT:
  600. return evaluateWitchHutSkillScore(target, hero, role);
  601. case Obj::PANDORAS_BOX:
  602. //Can contains experience, spells, or skills (only on custom maps)
  603. return 2.5f;
  604. case Obj::PYRAMID:
  605. return 6.0f;
  606. case Obj::HERO:
  607. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  608. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  609. : 0;
  610. default:
  611. break;
  612. }
  613. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  614. if(rewardable)
  615. {
  616. auto totalValue = 0.0f;
  617. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  618. {
  619. auto & info = rewardable->configuration.info[index];
  620. auto rewardValue = 0.0f;
  621. if(!info.reward.spells.empty())
  622. {
  623. for(auto spellID : info.reward.spells)
  624. {
  625. const spells::Spell * spell = VLC->spells()->getById(spellID);
  626. if(hero->canLearnSpell(spell) && !hero->spellbookContainsSpell(spellID))
  627. {
  628. rewardValue += std::sqrt(spell->getLevel()) / 4.0f;
  629. }
  630. }
  631. totalValue += rewardValue / info.reward.spells.size();
  632. }
  633. if(!info.reward.primary.empty())
  634. {
  635. for(auto value : info.reward.primary)
  636. {
  637. totalValue += value;
  638. }
  639. }
  640. }
  641. return totalValue;
  642. }
  643. return 0;
  644. }
  645. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  646. {
  647. auto & treatNode = ai->dangerHitMap->getTileThreat(tile);
  648. if(treatNode.maximumDanger.danger == 0)
  649. return HitMapInfo::NoThreat;
  650. if(treatNode.maximumDanger.turn <= turn)
  651. return treatNode.maximumDanger;
  652. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoThreat;
  653. }
  654. int32_t getArmyCost(const CArmedInstance * army)
  655. {
  656. int32_t value = 0;
  657. for(auto stack : army->Slots())
  658. {
  659. value += stack.second->getCreatureID().toCreature()->getFullRecruitCost().marketValue() * stack.second->count;
  660. }
  661. return value;
  662. }
  663. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  664. {
  665. if(!target)
  666. return 0;
  667. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  668. const int dailyIncomeMultiplier = 5;
  669. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  670. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  671. switch(target->ID)
  672. {
  673. case Obj::RESOURCE:
  674. {
  675. auto * res = dynamic_cast<const CGResource*>(target);
  676. return res && res->resourceID() == GameResID::GOLD ? 600 : 100;
  677. }
  678. case Obj::TREASURE_CHEST:
  679. return 1500;
  680. case Obj::WATER_WHEEL:
  681. return 1000;
  682. case Obj::TOWN:
  683. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  684. case Obj::MINE:
  685. case Obj::ABANDONED_MINE:
  686. {
  687. auto * mine = dynamic_cast<const CGMine*>(target);
  688. return dailyIncomeMultiplier * (mine->producedResource == GameResID::GOLD ? 1000 : 75);
  689. }
  690. case Obj::MYSTICAL_GARDEN:
  691. case Obj::WINDMILL:
  692. return 100;
  693. case Obj::CAMPFIRE:
  694. return 800;
  695. case Obj::WAGON:
  696. return 100;
  697. case Obj::CREATURE_BANK:
  698. return getResourcesGoldReward(getCreatureBankResources(target, hero));
  699. case Obj::CRYPT:
  700. case Obj::DERELICT_SHIP:
  701. return 3000;
  702. case Obj::DRAGON_UTOPIA:
  703. return 10000;
  704. case Obj::SEA_CHEST:
  705. return 1500;
  706. case Obj::PANDORAS_BOX:
  707. return 2500;
  708. case Obj::PRISON:
  709. //Objectively saves us 2500 to hire hero
  710. return GameConstants::HERO_GOLD_COST;
  711. case Obj::HERO:
  712. return relations == PlayerRelations::ENEMIES
  713. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  714. : 0;
  715. default:
  716. break;
  717. }
  718. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  719. if(rewardable)
  720. {
  721. auto goldReward = 0;
  722. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  723. {
  724. auto & info = rewardable->configuration.info[index];
  725. goldReward += getResourcesGoldReward(info.reward.resources);
  726. }
  727. return goldReward;
  728. }
  729. return 0;
  730. }
  731. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  732. {
  733. public:
  734. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  735. {
  736. if(task->goalType != Goals::HERO_EXCHANGE)
  737. return;
  738. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  739. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength(evaluationContext.evaluator.ai);
  740. evaluationContext.addNonCriticalStrategicalValue(2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength());
  741. evaluationContext.conquestValue += 2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength();
  742. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroExchange.hero);
  743. }
  744. };
  745. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  746. {
  747. public:
  748. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  749. {
  750. if(task->goalType != Goals::ARMY_UPGRADE)
  751. return;
  752. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  753. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  754. evaluationContext.armyReward += upgradeValue;
  755. evaluationContext.addNonCriticalStrategicalValue(upgradeValue / (float)armyUpgrade.hero->getArmyStrength());
  756. }
  757. };
  758. class ExplorePointEvaluator : public IEvaluationContextBuilder
  759. {
  760. public:
  761. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  762. {
  763. if(task->goalType != Goals::EXPLORATION_POINT)
  764. return;
  765. int tilesDiscovered = task->value;
  766. evaluationContext.addNonCriticalStrategicalValue(0.03f * tilesDiscovered);
  767. }
  768. };
  769. class StayAtTownManaRecoveryEvaluator : public IEvaluationContextBuilder
  770. {
  771. public:
  772. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  773. {
  774. if(task->goalType != Goals::STAY_AT_TOWN)
  775. return;
  776. Goals::StayAtTown & stayAtTown = dynamic_cast<Goals::StayAtTown &>(*task);
  777. evaluationContext.armyReward += evaluationContext.evaluator.getManaRecoveryArmyReward(stayAtTown.getHero());
  778. evaluationContext.movementCostByRole[evaluationContext.heroRole] += stayAtTown.getMovementWasted();
  779. evaluationContext.movementCost += stayAtTown.getMovementWasted();
  780. }
  781. };
  782. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  783. {
  784. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  785. if(enemyDanger.danger)
  786. {
  787. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  788. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  789. vstd::amax(evaluationContext.threat, enemyDanger.threat);
  790. }
  791. }
  792. class DefendTownEvaluator : public IEvaluationContextBuilder
  793. {
  794. public:
  795. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  796. {
  797. if(task->goalType != Goals::DEFEND_TOWN)
  798. return;
  799. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  800. const CGTownInstance * town = defendTown.town;
  801. auto & treat = defendTown.getTreat();
  802. auto strategicalValue = evaluationContext.evaluator.getStrategicalValue(town);
  803. float multiplier = 1;
  804. if(treat.turn < defendTown.getTurn())
  805. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  806. multiplier /= 1.0f + treat.turn / 5.0f;
  807. if(defendTown.getTurn() > 0 && defendTown.isCounterAttack())
  808. {
  809. auto ourSpeed = defendTown.hero->movementPointsLimit(true);
  810. auto enemySpeed = treat.hero.get(evaluationContext.evaluator.ai->cb.get())->movementPointsLimit(true);
  811. if(enemySpeed > ourSpeed) multiplier *= 0.7f;
  812. }
  813. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  814. auto armyGrowth = evaluationContext.evaluator.townArmyGrowth(town);
  815. evaluationContext.armyGrowth += armyGrowth * multiplier;
  816. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  817. if(evaluationContext.evaluator.ai->buildAnalyzer->getDevelopmentInfo().size() == 1)
  818. vstd::amax(evaluationContext.strategicalValue, 2.5f * multiplier * strategicalValue);
  819. else
  820. evaluationContext.addNonCriticalStrategicalValue(1.7f * multiplier * strategicalValue);
  821. evaluationContext.defenseValue = town->fortLevel();
  822. evaluationContext.isDefend = true;
  823. evaluationContext.threatTurns = treat.turn;
  824. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  825. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  826. }
  827. };
  828. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  829. {
  830. private:
  831. const Nullkiller * ai;
  832. public:
  833. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  834. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  835. {
  836. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  837. return;
  838. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  839. const AIPath & path = chain.getPath();
  840. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  841. evaluationContext.movementCost += path.movementCost();
  842. evaluationContext.closestWayRatio = chain.closestWayRatio;
  843. evaluationContext.isChain = true;
  844. std::map<const CGHeroInstance *, float> costsPerHero;
  845. for(auto & node : path.nodes)
  846. {
  847. vstd::amax(costsPerHero[node.targetHero], node.cost);
  848. if (node.layer == EPathfindingLayer::SAIL)
  849. evaluationContext.involvesSailing = true;
  850. }
  851. for(auto pair : costsPerHero)
  852. {
  853. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  854. evaluationContext.movementCostByRole[role] += pair.second;
  855. }
  856. auto hero = task->hero;
  857. bool checkGold = evaluationContext.danger == 0;
  858. auto army = path.heroArmy;
  859. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  860. auto heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(hero);
  861. if(heroRole == HeroRole::MAIN)
  862. evaluationContext.heroRole = heroRole;
  863. if (target)
  864. {
  865. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  866. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  867. evaluationContext.armyGrowth += evaluationContext.evaluator.getArmyGrowth(target, hero, army);
  868. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, heroRole);
  869. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target));
  870. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  871. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  872. evaluationContext.armyInvolvement += army->getArmyCost();
  873. if (target->tempOwner != PlayerColor::NEUTRAL)
  874. evaluationContext.isEnemy = true;
  875. }
  876. vstd::amax(evaluationContext.armyLossPersentage, path.getTotalArmyLoss() / (double)path.getHeroStrength());
  877. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  878. vstd::amax(evaluationContext.turn, path.turn());
  879. }
  880. };
  881. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  882. {
  883. public:
  884. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  885. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  886. {
  887. if(task->goalType != Goals::UNLOCK_CLUSTER)
  888. return;
  889. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  890. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  891. auto hero = clusterGoal.hero;
  892. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(hero);
  893. std::vector<std::pair<ObjectInstanceID, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  894. std::sort(objects.begin(), objects.end(), [](std::pair<ObjectInstanceID, ClusterObjectInfo> o1, std::pair<ObjectInstanceID, ClusterObjectInfo> o2) -> bool
  895. {
  896. return o1.second.priority > o2.second.priority;
  897. });
  898. int boost = 1;
  899. for(auto & objInfo : objects)
  900. {
  901. auto target = evaluationContext.evaluator.ai->cb->getObj(objInfo.first);
  902. bool checkGold = objInfo.second.danger == 0;
  903. auto army = hero;
  904. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  905. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  906. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  907. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target) / boost);
  908. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  909. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  910. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  911. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  912. if (target->tempOwner != PlayerColor::NEUTRAL)
  913. evaluationContext.isEnemy = true;
  914. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  915. boost <<= 1;
  916. if(boost > 8)
  917. break;
  918. }
  919. }
  920. };
  921. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  922. {
  923. public:
  924. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  925. {
  926. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  927. return;
  928. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  929. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  930. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  931. {
  932. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  933. auto mpLeft = garrisonHero->movementPointsRemaining() / (float)garrisonHero->movementPointsLimit(true);
  934. evaluationContext.movementCost += mpLeft;
  935. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  936. evaluationContext.heroRole = defenderRole;
  937. }
  938. }
  939. };
  940. class DismissHeroContextBuilder : public IEvaluationContextBuilder
  941. {
  942. private:
  943. const Nullkiller * ai;
  944. public:
  945. DismissHeroContextBuilder(const Nullkiller * ai) : ai(ai) {}
  946. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  947. {
  948. if(task->goalType != Goals::DISMISS_HERO)
  949. return;
  950. Goals::DismissHero & dismissCommand = dynamic_cast<Goals::DismissHero &>(*task);
  951. const CGHeroInstance * dismissedHero = dismissCommand.getHero();
  952. auto role = ai->heroManager->getHeroRole(dismissedHero);
  953. auto mpLeft = dismissedHero->movementPointsRemaining();
  954. evaluationContext.movementCost += mpLeft;
  955. evaluationContext.movementCostByRole[role] += mpLeft;
  956. evaluationContext.goldCost += GameConstants::HERO_GOLD_COST + getArmyCost(dismissedHero);
  957. }
  958. };
  959. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  960. {
  961. public:
  962. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  963. {
  964. if(task->goalType != Goals::BUILD_STRUCTURE)
  965. return;
  966. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  967. auto & bi = buildThis.buildingInfo;
  968. evaluationContext.goldReward += 7 * bi.dailyIncome[EGameResID::GOLD] / 2; // 7 day income but half we already have
  969. evaluationContext.heroRole = HeroRole::MAIN;
  970. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  971. int32_t cost = bi.buildCostWithPrerequisites[EGameResID::GOLD];
  972. evaluationContext.goldCost += cost;
  973. evaluationContext.closestWayRatio = 1;
  974. evaluationContext.buildingCost += bi.buildCostWithPrerequisites;
  975. if (bi.id == BuildingID::MARKETPLACE || bi.dailyIncome[EGameResID::WOOD] > 0)
  976. evaluationContext.isTradeBuilding = true;
  977. logAi->trace("Building costs for %s : %s MarketValue: %d",bi.toString(), evaluationContext.buildingCost.toString(), evaluationContext.buildingCost.marketValue());
  978. if(bi.creatureID != CreatureID::NONE)
  979. {
  980. evaluationContext.addNonCriticalStrategicalValue(buildThis.townInfo.armyStrength / 50000.0);
  981. if(bi.baseCreatureID == bi.creatureID)
  982. {
  983. evaluationContext.addNonCriticalStrategicalValue((0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount);
  984. evaluationContext.armyReward += bi.armyStrength;
  985. }
  986. else
  987. {
  988. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  989. evaluationContext.addNonCriticalStrategicalValue(potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount);
  990. evaluationContext.armyReward += potentialUpgradeValue / (float)bi.prerequisitesCount;
  991. }
  992. int sameTownBonus = 0;
  993. for (auto town : evaluationContext.evaluator.ai->cb->getTownsInfo())
  994. {
  995. if (buildThis.town->getFaction() == town->getFaction())
  996. sameTownBonus+=town->getTownLevel();
  997. }
  998. evaluationContext.armyReward *= sameTownBonus;
  999. }
  1000. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  1001. {
  1002. evaluationContext.addNonCriticalStrategicalValue(buildThis.town->creatures.size() * 0.2f);
  1003. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  1004. }
  1005. else if(bi.id >= BuildingID::MAGES_GUILD_1 && bi.id <= BuildingID::MAGES_GUILD_5)
  1006. {
  1007. evaluationContext.skillReward += 2 * (bi.id - BuildingID::MAGES_GUILD_1);
  1008. for (auto hero : evaluationContext.evaluator.ai->cb->getHeroesInfo())
  1009. {
  1010. evaluationContext.armyInvolvement += hero->getArmyCost();
  1011. }
  1012. }
  1013. if(evaluationContext.goldReward)
  1014. {
  1015. auto goldPressure = evaluationContext.evaluator.ai->buildAnalyzer->getGoldPressure();
  1016. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPressure / 3500.0f / bi.prerequisitesCount);
  1017. }
  1018. if(bi.notEnoughRes && bi.prerequisitesCount == 1)
  1019. {
  1020. evaluationContext.strategicalValue /= 3;
  1021. evaluationContext.movementCostByRole[evaluationContext.heroRole] += 5;
  1022. evaluationContext.turn += 5;
  1023. }
  1024. }
  1025. };
  1026. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  1027. {
  1028. if(ai->buildAnalyzer->hasAnyBuilding(town->getFaction(), bi.id))
  1029. return 0;
  1030. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  1031. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  1032. return upgradedPower - creaturesToUpgrade.power;
  1033. }
  1034. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  1035. :ai(ai)
  1036. {
  1037. initVisitTile();
  1038. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  1039. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  1040. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  1041. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  1042. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  1043. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  1044. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  1045. evaluationContextBuilders.push_back(std::make_shared<DismissHeroContextBuilder>(ai));
  1046. evaluationContextBuilders.push_back(std::make_shared<StayAtTownManaRecoveryEvaluator>());
  1047. evaluationContextBuilders.push_back(std::make_shared<ExplorePointEvaluator>());
  1048. }
  1049. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  1050. {
  1051. Goals::TGoalVec parts;
  1052. EvaluationContext context(ai);
  1053. if(goal->goalType == Goals::COMPOSITION)
  1054. {
  1055. parts = goal->decompose(ai);
  1056. }
  1057. else
  1058. {
  1059. parts.push_back(goal);
  1060. }
  1061. for(auto subgoal : parts)
  1062. {
  1063. context.goldCost += subgoal->goldCost;
  1064. context.buildingCost += subgoal->buildingCost;
  1065. for(auto builder : evaluationContextBuilders)
  1066. {
  1067. builder->buildEvaluationContext(context, subgoal);
  1068. }
  1069. }
  1070. return context;
  1071. }
  1072. float PriorityEvaluator::evaluate(Goals::TSubgoal task, int priorityTier)
  1073. {
  1074. auto evaluationContext = buildEvaluationContext(task);
  1075. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  1076. + (evaluationContext.armyReward > 0 ? 1 : 0)
  1077. + (evaluationContext.skillReward > 0 ? 1 : 0)
  1078. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  1079. float goldRewardPerTurn = evaluationContext.goldReward / std::log2f(2 + evaluationContext.movementCost * 10);
  1080. double result = 0;
  1081. float fuzzyResult = 0;
  1082. try
  1083. {
  1084. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  1085. heroRoleVariable->setValue(evaluationContext.heroRole);
  1086. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  1087. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  1088. goldRewardVariable->setValue(goldRewardPerTurn);
  1089. armyRewardVariable->setValue(evaluationContext.armyReward);
  1090. armyGrowthVariable->setValue(evaluationContext.armyGrowth);
  1091. skillRewardVariable->setValue(evaluationContext.skillReward);
  1092. dangerVariable->setValue(evaluationContext.danger);
  1093. rewardTypeVariable->setValue(rewardType);
  1094. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  1095. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  1096. goldPressureVariable->setValue(ai->buildAnalyzer->getGoldPressure());
  1097. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  1098. turnVariable->setValue(evaluationContext.turn);
  1099. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  1100. engine->process();
  1101. fuzzyResult = value->getValue();
  1102. }
  1103. catch (fl::Exception& fe)
  1104. {
  1105. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  1106. }
  1107. if (ai->settings->isUseFuzzy())
  1108. {
  1109. result = fuzzyResult;
  1110. }
  1111. else
  1112. {
  1113. float score = 0;
  1114. float maxWillingToLose = ai->cb->getTownsInfo().empty() ? 1 : 0.25;
  1115. logAi->trace("BEFORE: priorityTier %d, Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, gold: %f, cost: %d, army gain: %f, army growth: %f skill: %f danger: %d, threatTurns: %d, threat: %d, role: %s, strategical value: %f, conquest value: %f cwr: %f, fear: %f, fuzzy: %f",
  1116. priorityTier,
  1117. task->toString(),
  1118. evaluationContext.armyLossPersentage,
  1119. (int)evaluationContext.turn,
  1120. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1121. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1122. goldRewardPerTurn,
  1123. evaluationContext.goldCost,
  1124. evaluationContext.armyReward,
  1125. evaluationContext.armyGrowth,
  1126. evaluationContext.skillReward,
  1127. evaluationContext.danger,
  1128. evaluationContext.threatTurns,
  1129. evaluationContext.threat,
  1130. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1131. evaluationContext.strategicalValue,
  1132. evaluationContext.conquestValue,
  1133. evaluationContext.closestWayRatio,
  1134. evaluationContext.enemyHeroDangerRatio,
  1135. fuzzyResult);
  1136. switch (priorityTier)
  1137. {
  1138. case 0: //Take towns
  1139. {
  1140. //score += evaluationContext.conquestValue * 1000;
  1141. if(evaluationContext.conquestValue > 0 || (evaluationContext.defenseValue >= CGTownInstance::EFortLevel::CITADEL && evaluationContext.turn <= 1 && evaluationContext.threat > evaluationContext.armyInvolvement && evaluationContext.threatTurns <= 1))
  1142. score = 1000;
  1143. if (evaluationContext.isEnemy && evaluationContext.turn > 0 && !ai->cb->getTownsInfo().empty())
  1144. return 0;
  1145. if (score == 0 || (evaluationContext.enemyHeroDangerRatio > 1 && evaluationContext.turn > 0 && !ai->cb->getTownsInfo().empty()))
  1146. return 0;
  1147. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1148. return 0;
  1149. score *= evaluationContext.closestWayRatio;
  1150. if (evaluationContext.movementCost > 0)
  1151. score /= evaluationContext.movementCost;
  1152. break;
  1153. }
  1154. case 1: //Collect unguarded stuff
  1155. {
  1156. if (evaluationContext.enemyHeroDangerRatio > 1)
  1157. return 0;
  1158. if (evaluationContext.isDefend)
  1159. return 0;
  1160. if (evaluationContext.armyLossPersentage > 0)
  1161. return 0;
  1162. if (evaluationContext.involvesSailing && evaluationContext.movementCostByRole[HeroRole::MAIN] > 0)
  1163. return 0;
  1164. if (evaluationContext.buildingCost.marketValue() > 0)
  1165. return 0;
  1166. if (evaluationContext.closestWayRatio < 1)
  1167. return 0;
  1168. score += evaluationContext.strategicalValue * 1000;
  1169. score += evaluationContext.goldReward;
  1170. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1171. score += evaluationContext.armyReward;
  1172. score += evaluationContext.armyGrowth;
  1173. if (score <= 0)
  1174. return 0;
  1175. else
  1176. score = 1000;
  1177. score *= evaluationContext.closestWayRatio;
  1178. if (evaluationContext.threat > evaluationContext.armyInvolvement && !evaluationContext.isDefend)
  1179. score *= evaluationContext.armyInvolvement / evaluationContext.threat;
  1180. if (evaluationContext.movementCost > 0)
  1181. score /= evaluationContext.movementCost;
  1182. break;
  1183. }
  1184. case 2: //Collect guarded stuff
  1185. {
  1186. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend)
  1187. return 0;
  1188. if (evaluationContext.buildingCost.marketValue() > 0)
  1189. return 0;
  1190. if (evaluationContext.isDefend && (evaluationContext.enemyHeroDangerRatio < 1 || evaluationContext.threatTurns > 0 || evaluationContext.turn > 0))
  1191. return 0;
  1192. score += evaluationContext.strategicalValue * 1000;
  1193. score += evaluationContext.goldReward;
  1194. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1195. score += evaluationContext.armyReward;
  1196. score += evaluationContext.armyGrowth;
  1197. score -= evaluationContext.goldCost;
  1198. score -= evaluationContext.armyInvolvement * evaluationContext.armyLossPersentage;
  1199. if (score > 0)
  1200. {
  1201. score *= evaluationContext.closestWayRatio;
  1202. if (evaluationContext.enemyHeroDangerRatio > 1)
  1203. score /= evaluationContext.enemyHeroDangerRatio;
  1204. if (evaluationContext.movementCost > 0)
  1205. score /= evaluationContext.movementCost;
  1206. score *= (maxWillingToLose - evaluationContext.armyLossPersentage);
  1207. }
  1208. break;
  1209. }
  1210. case 3: //For buildings and buying army
  1211. {
  1212. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1213. return 0;
  1214. score += evaluationContext.conquestValue * 1000;
  1215. score += evaluationContext.strategicalValue * 1000;
  1216. score += evaluationContext.goldReward;
  1217. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1218. score += evaluationContext.armyReward;
  1219. score += evaluationContext.armyGrowth;
  1220. if (evaluationContext.buildingCost.marketValue() > 0)
  1221. {
  1222. if (!evaluationContext.isTradeBuilding && ai->getFreeResources()[EGameResID::WOOD] - evaluationContext.buildingCost[EGameResID::WOOD] < 5 && ai->buildAnalyzer->getDailyIncome()[EGameResID::WOOD] < 1)
  1223. {
  1224. logAi->trace("Should make sure to build market-place instead of %s", task->toString());
  1225. for (auto town : ai->cb->getTownsInfo())
  1226. {
  1227. if (!town->hasBuiltSomeTradeBuilding())
  1228. return 0;
  1229. }
  1230. }
  1231. score += 1000;
  1232. auto resourcesAvailable = evaluationContext.evaluator.ai->getFreeResources();
  1233. auto income = ai->buildAnalyzer->getDailyIncome();
  1234. score /= evaluationContext.buildingCost.marketValue();
  1235. if (resourcesAvailable < evaluationContext.buildingCost)
  1236. {
  1237. TResources needed = evaluationContext.buildingCost - resourcesAvailable;
  1238. needed.positive();
  1239. int turnsTo = needed.div(income);
  1240. if (turnsTo == INT_MAX)
  1241. return 0;
  1242. else
  1243. score /= turnsTo;
  1244. }
  1245. }
  1246. else
  1247. {
  1248. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend && evaluationContext.conquestValue == 0)
  1249. return 0;
  1250. }
  1251. break;
  1252. }
  1253. }
  1254. result = score;
  1255. }
  1256. #if NKAI_TRACE_LEVEL >= 2
  1257. logAi->trace("priorityTier %d, Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, gold: %f, cost: %d, army gain: %f, army growth: %f skill: %f danger: %d, threatTurns: %d, threat: %d, role: %s, strategical value: %f, conquest value: %f cwr: %f, fear: %f, fuzzy: %f, result %f",
  1258. priorityTier,
  1259. task->toString(),
  1260. evaluationContext.armyLossPersentage,
  1261. (int)evaluationContext.turn,
  1262. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1263. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1264. goldRewardPerTurn,
  1265. evaluationContext.goldCost,
  1266. evaluationContext.armyReward,
  1267. evaluationContext.armyGrowth,
  1268. evaluationContext.skillReward,
  1269. evaluationContext.danger,
  1270. evaluationContext.threatTurns,
  1271. evaluationContext.threat,
  1272. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1273. evaluationContext.strategicalValue,
  1274. evaluationContext.conquestValue,
  1275. evaluationContext.closestWayRatio,
  1276. evaluationContext.enemyHeroDangerRatio,
  1277. fuzzyResult,
  1278. result);
  1279. #endif
  1280. return result;
  1281. }
  1282. }