PriorityEvaluator.cpp 58 KB

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