PriorityEvaluator.cpp 56 KB

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