PriorityEvaluator.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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/mapObjectConstructors/AObjectTypeHandler.h"
  15. #include "../../../lib/mapObjectConstructors/CObjectClassesHandler.h"
  16. #include "../../../lib/mapObjects/CGResource.h"
  17. #include "../../../lib/mapping/TerrainTile.h"
  18. #include "../../../lib/RoadHandler.h"
  19. #include "../../../lib/CCreatureHandler.h"
  20. #include "../../../lib/GameLibrary.h"
  21. #include "../../../lib/StartInfo.h"
  22. #include "../../../lib/GameSettings.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 MAX_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. armyLossRatio(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, MAX_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. armyLossRatioVariable = 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 getDwellingArmyValue(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  130. {
  131. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  132. uint64_t score = 0;
  133. for(auto & creLevel : dwelling->creatures)
  134. {
  135. if(creLevel.first && creLevel.second.size())
  136. {
  137. auto creature = creLevel.second.back().toCreature();
  138. auto creaturesAreFree = creature->getLevel() == 1;
  139. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->getFullRecruitCost() * creLevel.first))
  140. continue;
  141. score += creature->getAIValue() * creLevel.first;
  142. }
  143. }
  144. return score;
  145. }
  146. uint64_t getDwellingArmyGrowth(CCallback * cb, const CGObjectInstance * target, PlayerColor myColor)
  147. {
  148. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  149. uint64_t score = 0;
  150. if(dwelling->getOwner() == myColor)
  151. return 0;
  152. for(auto & creLevel : dwelling->creatures)
  153. {
  154. if(creLevel.second.size())
  155. {
  156. auto creature = creLevel.second.back().toCreature();
  157. score += creature->getAIValue() * creature->getGrowth();
  158. }
  159. }
  160. return score;
  161. }
  162. int getDwellingArmyCost(const CGObjectInstance * target)
  163. {
  164. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  165. int cost = 0;
  166. for(auto & creLevel : dwelling->creatures)
  167. {
  168. if(creLevel.first && creLevel.second.size())
  169. {
  170. auto creature = creLevel.second.back().toCreature();
  171. auto creaturesAreFree = creature->getLevel() == 1;
  172. if(!creaturesAreFree)
  173. cost += creature->getFullRecruitCost().marketValue() * creLevel.first;
  174. }
  175. }
  176. return cost;
  177. }
  178. static uint64_t evaluateSpellScrollArmyValue(const SpellID &)
  179. {
  180. return 1500;
  181. }
  182. static uint64_t evaluateArtifactArmyValue(const CArtifact * art)
  183. {
  184. if(art->getId() == ArtifactID::SPELL_SCROLL)
  185. return 1500;
  186. return getPotentialArtifactScore(art);
  187. }
  188. uint64_t RewardEvaluator::getArmyReward(
  189. const CGObjectInstance * target,
  190. const CGHeroInstance * hero,
  191. const CCreatureSet * army,
  192. bool checkGold) const
  193. {
  194. const float enemyArmyEliminationRewardRatio = 0.5f;
  195. auto relations = ai->cb->getPlayerRelations(target->tempOwner, ai->playerID);
  196. if(!target)
  197. return 0;
  198. switch(target->ID)
  199. {
  200. case Obj::HILL_FORT:
  201. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  202. case Obj::CREATURE_GENERATOR1:
  203. case Obj::CREATURE_GENERATOR2:
  204. case Obj::CREATURE_GENERATOR3:
  205. case Obj::CREATURE_GENERATOR4:
  206. return getDwellingArmyValue(ai->cb.get(), target, checkGold);
  207. case Obj::SPELL_SCROLL:
  208. return evaluateSpellScrollArmyValue(dynamic_cast<const CGArtifact *>(target)->getArtifactInstance()->getScrollSpellID());
  209. case Obj::ARTIFACT:
  210. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->getArtifactInstance()->getType());
  211. case Obj::HERO:
  212. return relations == PlayerRelations::ENEMIES
  213. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  214. : 0;
  215. case Obj::PANDORAS_BOX:
  216. return 5000;
  217. case Obj::MAGIC_WELL:
  218. case Obj::MAGIC_SPRING:
  219. return getManaRecoveryArmyReward(hero);
  220. default:
  221. break;
  222. }
  223. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  224. if(rewardable)
  225. {
  226. auto totalValue = 0;
  227. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  228. {
  229. auto & info = rewardable->configuration.info[index];
  230. auto rewardValue = 0;
  231. for(auto artID : info.reward.grantedArtifacts)
  232. rewardValue += evaluateArtifactArmyValue(artID.toArtifact());
  233. for(auto scroll : info.reward.grantedScrolls)
  234. rewardValue += evaluateSpellScrollArmyValue(scroll);
  235. for(const auto & stackInfo : info.reward.creatures)
  236. rewardValue += stackInfo.getType()->getAIValue() * stackInfo.getCount();
  237. totalValue += rewardValue > 0 ? rewardValue / (info.reward.grantedArtifacts.size() + info.reward.creatures.size()) : 0;
  238. }
  239. return totalValue;
  240. }
  241. return 0;
  242. }
  243. uint64_t RewardEvaluator::getArmyGrowth(
  244. const CGObjectInstance * target,
  245. const CGHeroInstance * hero,
  246. const CCreatureSet * army) const
  247. {
  248. if(!target)
  249. return 0;
  250. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  251. if(relations != PlayerRelations::ENEMIES)
  252. return 0;
  253. switch(target->ID)
  254. {
  255. case Obj::TOWN:
  256. {
  257. auto town = dynamic_cast<const CGTownInstance *>(target);
  258. auto fortLevel = town->fortLevel();
  259. auto neutral = !town->getOwner().isValidPlayer();
  260. auto booster = isAnotherAi(town, *ai->cb) || neutral ? 1 : 2;
  261. if(fortLevel < CGTownInstance::CITADEL)
  262. return town->hasFort() ? booster * 500 : 0;
  263. else
  264. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  265. }
  266. case Obj::CREATURE_GENERATOR1:
  267. case Obj::CREATURE_GENERATOR2:
  268. case Obj::CREATURE_GENERATOR3:
  269. case Obj::CREATURE_GENERATOR4:
  270. return getDwellingArmyGrowth(ai->cb.get(), target, hero->getOwner());
  271. case Obj::ARTIFACT:
  272. // 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.
  273. return 0;
  274. default:
  275. return 0;
  276. }
  277. }
  278. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  279. {
  280. if(!target)
  281. return 0;
  282. if(auto * m = dynamic_cast<const IMarket *>(target))
  283. {
  284. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  285. return 2000;
  286. }
  287. switch(target->ID)
  288. {
  289. case Obj::HILL_FORT:
  290. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  291. case Obj::SCHOOL_OF_MAGIC:
  292. case Obj::SCHOOL_OF_WAR:
  293. return 1000;
  294. case Obj::CREATURE_GENERATOR1:
  295. case Obj::CREATURE_GENERATOR2:
  296. case Obj::CREATURE_GENERATOR3:
  297. case Obj::CREATURE_GENERATOR4:
  298. return getDwellingArmyCost(target);
  299. default:
  300. return 0;
  301. }
  302. }
  303. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  304. {
  305. auto objectsUnderThreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  306. float objectValue = 0;
  307. for(auto obj : objectsUnderThreat)
  308. {
  309. vstd::amax(objectValue, getStrategicalValue(obj));
  310. }
  311. /*
  312. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  313. Killing the hero is almost as important (0.9) as capturing the object itself.
  314. 2. The formula quickly approaches 1.0 as hero level increases,
  315. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  316. */
  317. return std::min(1.5f, objectValue * 0.9f + (1.5f - (1.5f / (1 + enemy->level))));
  318. }
  319. float RewardEvaluator::getResourceRequirementStrength(GameResID resType) const
  320. {
  321. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  322. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  323. if(requiredResources[resType] == 0)
  324. return 0;
  325. if(dailyIncome[resType] == 0)
  326. return 1.0f;
  327. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  328. return std::min(ratio, 1.0f);
  329. }
  330. float RewardEvaluator::getTotalResourceRequirementStrength(GameResID resType) const
  331. {
  332. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  333. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  334. if(requiredResources[resType] == 0)
  335. return 0;
  336. float ratio = dailyIncome[resType] == 0
  337. ? (float)requiredResources[resType] / 10.0f
  338. : (float)requiredResources[resType] / dailyIncome[resType] / 20.0f;
  339. return std::min(ratio, 2.0f);
  340. }
  341. uint64_t RewardEvaluator::townArmyGrowth(const CGTownInstance * town) const
  342. {
  343. uint64_t result = 0;
  344. for(auto creatureInfo : town->creatures)
  345. {
  346. if(creatureInfo.second.empty())
  347. continue;
  348. auto creature = creatureInfo.second.back().toCreature();
  349. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  350. }
  351. return result;
  352. }
  353. float RewardEvaluator::getManaRecoveryArmyReward(const CGHeroInstance * hero) const
  354. {
  355. return ai->heroManager->getMagicStrength(hero) * 10000 * (1.0f - std::sqrt(static_cast<float>(hero->mana) / hero->manaLimit()));
  356. }
  357. float RewardEvaluator::getResourceRequirementStrength(const TResources & res) const
  358. {
  359. float sum = 0.0f;
  360. for(TResources::nziterator it(res); it.valid(); it++)
  361. {
  362. //Evaluate resources used for construction. Gold is evaluated separately.
  363. if(it->resType != EGameResID::GOLD)
  364. {
  365. sum += 0.1f * it->resVal * getResourceRequirementStrength(it->resType)
  366. + 0.05f * it->resVal * getTotalResourceRequirementStrength(it->resType);
  367. }
  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. return mine->producedResource == EGameResID::GOLD
  381. ? 0.5f
  382. : 0.4f * getTotalResourceRequirementStrength(mine->producedResource) + 0.1f * getResourceRequirementStrength(mine->producedResource);
  383. }
  384. case Obj::RESOURCE:
  385. {
  386. auto resource = dynamic_cast<const CGResource *>(target);
  387. TResources res;
  388. res[resource->resourceID()] = resource->getAmount();
  389. return getResourceRequirementStrength(res);
  390. }
  391. case Obj::TOWN:
  392. {
  393. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  394. return 10.0f;
  395. auto town = dynamic_cast<const CGTownInstance *>(target);
  396. if(town->getOwner() == ai->playerID)
  397. {
  398. auto armyIncome = townArmyGrowth(town);
  399. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  400. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  401. }
  402. auto fortLevel = town->fortLevel();
  403. auto booster = isAnotherAi(town, *ai->cb) ? 0.4f : 1.0f;
  404. if(town->hasCapitol())
  405. return booster * 1.5;
  406. if(fortLevel < CGTownInstance::CITADEL)
  407. return booster * (town->hasFort() ? 1.0 : 0.8);
  408. else
  409. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  410. }
  411. case Obj::HERO:
  412. return ai->cb->getPlayerRelations(target->tempOwner, ai->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 += getResourceRequirementStrength(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() == ai->playerID)
  437. return 0;
  438. switch (target->ID)
  439. {
  440. case Obj::TOWN:
  441. {
  442. if (ai->buildAnalyzer->getDevelopmentInfo().empty())
  443. return 10.0f;
  444. auto town = dynamic_cast<const CGTownInstance*>(target);
  445. if (town->getOwner() == ai->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 ai->cb->getPlayerRelations(target->tempOwner, ai->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()) >= cb->getSettings().getInteger(EGameSettings::HEROES_SKILL_PER_HERO))
  477. return 0;
  478. auto score = ai->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 ai->cb->getPlayerRelations(target->tempOwner, ai->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 = ai->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 = ai->cb->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(ai->cb.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.ai);
  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.ai->heroManager->getHeroRole(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.ai->cb->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.ai->cb->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.hero.get(evaluationContext.evaluator.ai->cb.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.ai->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 * ai;
  755. public:
  756. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  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.ai->heroManager->getHeroRole(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 = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  793. auto heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(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] = ai->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() && ai->cb->getPlayerRelations(ai->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 * ai) {}
  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.ai->heroManager->getHeroRole(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.ai->cb->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.ai->cb->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.ai->heroManager->getHeroRole(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 * ai;
  920. public:
  921. DismissHeroContextBuilder(const Nullkiller * ai) : ai(ai) {}
  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 = ai->heroManager->getHeroRole(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.ai->cb->getTownsInfo())
  954. {
  955. if (town->hasBuilt(bi.id))
  956. alreadyOwn = true;
  957. if (evaluationContext.evaluator.ai->cb->canBuildStructure(town, BuildingID::MAGES_GUILD_5) != EBuildingState::FORBIDDEN)
  958. highestMageGuildPossible = BuildingID::MAGES_GUILD_5;
  959. else if (evaluationContext.evaluator.ai->cb->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 NKAI_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.ai->armyManager->evaluateStackPower(bi.baseCreatureID.toCreature(), bi.creatureGrows);
  981. else //This is for prerequisite-buildings
  982. evaluationContext.armyReward += evaluationContext.evaluator.ai->armyManager->evaluateStackPower(bi.baseCreatureID.toCreature(), bi.creatureGrows);
  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.ai->cb->canBuildStructure(buildThis.town, highestMageGuildPossible) != EBuildingState::FORBIDDEN)
  996. {
  997. for (auto hero : evaluationContext.evaluator.ai->cb->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.ai->cb->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.ai->buildAnalyzer->getGoldPressure();
  1015. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPressure / 3500.0f / bi.prerequisitesCount);
  1016. }
  1017. if(bi.notEnoughRes && 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(ai->buildAnalyzer->hasAnyBuilding(town->getFactionID(), bi.id))
  1028. return 0;
  1029. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  1030. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  1031. return upgradedPower - creaturesToUpgrade.power;
  1032. }
  1033. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  1034. :ai(ai)
  1035. {
  1036. initVisitTile();
  1037. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  1038. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  1039. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  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>(ai));
  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(ai);
  1052. if(goal->goalType == Goals::COMPOSITION)
  1053. {
  1054. parts = goal->decompose(ai);
  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 goldRewardPerTurn = evaluationContext.goldReward / std::log2f(2 + evaluationContext.movementCost * 10);
  1079. double result = 0;
  1080. if (ai->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. goldRewardVariable->setValue(goldRewardPerTurn);
  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(ai->buildAnalyzer->getGoldPressure());
  1098. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->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 = ai->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 == false)
  1121. {
  1122. #if NKAI_TRACE_LEVEL >= 2
  1123. logAi->trace("Skip FAR_HUNTER_GATHER because hero is not threatened.");
  1124. #endif
  1125. return 0;
  1126. }
  1127. const bool amIInDanger = ai->cb->getTownsInfo().empty();
  1128. const float maxWillingToLose = amIInDanger ? 1 : ai->settings->getMaxArmyLossTarget() * evaluationContext.powerRatio > 0 ? ai->settings->getMaxArmyLossTarget() * evaluationContext.powerRatio : 1.0;
  1129. float dangerThreshold = 1;
  1130. dangerThreshold *= evaluationContext.powerRatio > 0 ? evaluationContext.powerRatio : 1.0;
  1131. bool arriveNextWeek = false;
  1132. if (ai->cb->getDate(Date::DAY_OF_WEEK) + evaluationContext.turn > 7 && priorityTier < PriorityTier::FAR_KILL)
  1133. arriveNextWeek = true;
  1134. #if NKAI_TRACE_LEVEL >= 2
  1135. 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",
  1136. priorityTier,
  1137. task->toString(),
  1138. evaluationContext.armyLossRatio,
  1139. maxWillingToLose,
  1140. (int)evaluationContext.turn,
  1141. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1142. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1143. evaluationContext.armyInvolvement,
  1144. goldRewardPerTurn,
  1145. evaluationContext.goldCost,
  1146. evaluationContext.armyReward,
  1147. evaluationContext.armyGrowth,
  1148. evaluationContext.skillReward,
  1149. evaluationContext.danger,
  1150. evaluationContext.threatTurns,
  1151. evaluationContext.threat,
  1152. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1153. evaluationContext.strategicalValue,
  1154. evaluationContext.conquestValue,
  1155. evaluationContext.closestWayRatio,
  1156. evaluationContext.enemyHeroDangerRatio,
  1157. dangerThreshold,
  1158. evaluationContext.explorePriority,
  1159. evaluationContext.isDefend,
  1160. evaluationContext.isEnemy,
  1161. arriveNextWeek,
  1162. evaluationContext.powerRatio);
  1163. #endif
  1164. switch (priorityTier)
  1165. {
  1166. case PriorityTier::INSTAKILL: //Take towns / kill heroes in immediate reach
  1167. {
  1168. if (evaluationContext.turn > 0 || evaluationContext.isExchange)
  1169. return 0;
  1170. if (evaluationContext.movementCost >= 1)
  1171. return 0;
  1172. if (evaluationContext.defenseValue < 2 && evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1173. return 0;
  1174. if(evaluationContext.conquestValue > 0)
  1175. score = evaluationContext.armyInvolvement;
  1176. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > dangerThreshold && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !ai->cb->getTownsInfo().empty()))
  1177. return 0;
  1178. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1179. return 0;
  1180. if (evaluationContext.movementCost > 0)
  1181. score /= evaluationContext.movementCost;
  1182. break;
  1183. }
  1184. case PriorityTier::INSTADEFEND: //Defend immediately threatened towns
  1185. {
  1186. //No point defending if we don't have defensive-structures
  1187. if (evaluationContext.defenseValue < 2)
  1188. return 0;
  1189. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1190. return 0;
  1191. if (evaluationContext.closestWayRatio < 1.0)
  1192. return 0;
  1193. if (evaluationContext.isEnemy && evaluationContext.turn > 0)
  1194. return 0;
  1195. if (evaluationContext.isDefend && evaluationContext.threatTurns <= evaluationContext.turn)
  1196. {
  1197. const float OPTIMAL_PERCENTAGE = 0.75f; // We want army to be 75% of the threat
  1198. float optimalStrength = evaluationContext.threat * OPTIMAL_PERCENTAGE;
  1199. // Calculate how far the army is from optimal strength
  1200. float deviation = std::abs(evaluationContext.armyInvolvement - optimalStrength);
  1201. // Convert deviation to a percentage of the threat to normalize it
  1202. float deviationPercentage = deviation / evaluationContext.threat;
  1203. // Calculate score: 1.0 is perfect, decreasing as deviation increases
  1204. score = 1.0f / (1.0f + deviationPercentage);
  1205. // Apply turn penalty to still prefer earlier moves when scores are close
  1206. score = score / (evaluationContext.turn + 1);
  1207. }
  1208. break;
  1209. }
  1210. case PriorityTier::KILL: //Take towns / kill heroes that are further away
  1211. //FALL_THROUGH
  1212. case PriorityTier::FAR_KILL:
  1213. {
  1214. if (evaluationContext.defenseValue < 2 && evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1215. return 0;
  1216. if (evaluationContext.turn > 0 && evaluationContext.isHero)
  1217. return 0;
  1218. if (arriveNextWeek && evaluationContext.isEnemy)
  1219. return 0;
  1220. if (evaluationContext.conquestValue > 0)
  1221. score = evaluationContext.armyInvolvement;
  1222. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > dangerThreshold && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !ai->cb->getTownsInfo().empty()))
  1223. return 0;
  1224. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1225. return 0;
  1226. score *= evaluationContext.closestWayRatio;
  1227. if (evaluationContext.movementCost > 0)
  1228. score /= evaluationContext.movementCost;
  1229. break;
  1230. }
  1231. case PriorityTier::HIGH_PRIO_EXPLORE:
  1232. {
  1233. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1234. return 0;
  1235. if (evaluationContext.explorePriority != 1)
  1236. return 0;
  1237. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1238. return 0;
  1239. if (vstd::isAlmostZero(evaluationContext.armyLossRatio) && evaluationContext.closestWayRatio < 1.0)
  1240. return 0;
  1241. score = 1000;
  1242. if (evaluationContext.movementCost > 0)
  1243. score /= evaluationContext.movementCost;
  1244. break;
  1245. }
  1246. case PriorityTier::HUNTER_GATHER: //Collect guarded stuff
  1247. //FALL_THROUGH
  1248. case PriorityTier::FAR_HUNTER_GATHER:
  1249. {
  1250. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold && !evaluationContext.isDefend && priorityTier != PriorityTier::FAR_HUNTER_GATHER)
  1251. return 0;
  1252. if (evaluationContext.buildingCost.marketValue() > 0)
  1253. return 0;
  1254. if (priorityTier != PriorityTier::FAR_HUNTER_GATHER && evaluationContext.isDefend && (evaluationContext.enemyHeroDangerRatio > dangerThreshold || evaluationContext.threatTurns > 0 || evaluationContext.turn > 0))
  1255. return 0;
  1256. if (evaluationContext.explorePriority == 3)
  1257. return 0;
  1258. if (priorityTier != PriorityTier::FAR_HUNTER_GATHER && ((evaluationContext.enemyHeroDangerRatio > 0 && arriveNextWeek) || evaluationContext.enemyHeroDangerRatio > dangerThreshold))
  1259. return 0;
  1260. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1261. return 0;
  1262. if (vstd::isAlmostZero(evaluationContext.armyLossRatio) && evaluationContext.closestWayRatio < 1.0)
  1263. return 0;
  1264. score += evaluationContext.strategicalValue * 1000;
  1265. score += evaluationContext.goldReward;
  1266. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossRatio) * 0.05;
  1267. score += evaluationContext.armyReward;
  1268. score += evaluationContext.armyGrowth;
  1269. score -= evaluationContext.goldCost;
  1270. score -= evaluationContext.armyInvolvement * evaluationContext.armyLossRatio;
  1271. if (score > 0)
  1272. {
  1273. score = 1000;
  1274. if (evaluationContext.movementCost > 0)
  1275. score /= evaluationContext.movementCost;
  1276. if(priorityTier == PriorityTier::FAR_HUNTER_GATHER && evaluationContext.enemyHeroDangerRatio > 0)
  1277. score /= evaluationContext.enemyHeroDangerRatio;
  1278. }
  1279. break;
  1280. }
  1281. case PriorityTier::LOW_PRIO_EXPLORE:
  1282. {
  1283. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1284. return 0;
  1285. if (evaluationContext.explorePriority != 3)
  1286. return 0;
  1287. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1288. return 0;
  1289. if (evaluationContext.closestWayRatio < 1.0)
  1290. return 0;
  1291. score = 1000;
  1292. if (evaluationContext.movementCost > 0)
  1293. score /= evaluationContext.movementCost;
  1294. break;
  1295. }
  1296. case PriorityTier::DEFEND: //Defend whatever if nothing else is to do
  1297. {
  1298. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1299. return 0;
  1300. if (evaluationContext.isDefend || evaluationContext.isArmyUpgrade)
  1301. score = evaluationContext.armyInvolvement;
  1302. score /= (evaluationContext.turn + 1);
  1303. break;
  1304. }
  1305. case PriorityTier::BUILDINGS: //For buildings and buying army
  1306. {
  1307. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1308. return 0;
  1309. //If we already have locked resources, we don't look at other buildings
  1310. if (ai->getLockedResources().marketValue() > 0)
  1311. return 0;
  1312. score += evaluationContext.conquestValue * 1000;
  1313. score += evaluationContext.strategicalValue * 1000;
  1314. score += evaluationContext.goldReward;
  1315. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossRatio) * 0.05;
  1316. score += evaluationContext.armyReward;
  1317. score += evaluationContext.armyGrowth;
  1318. if (evaluationContext.buildingCost.marketValue() > 0)
  1319. {
  1320. if (!evaluationContext.isTradeBuilding && ai->getFreeResources()[EGameResID::WOOD] - evaluationContext.buildingCost[EGameResID::WOOD] < 5 && ai->buildAnalyzer->getDailyIncome()[EGameResID::WOOD] < 1)
  1321. {
  1322. logAi->trace("Should make sure to build market-place instead of %s", task->toString());
  1323. for (auto town : ai->cb->getTownsInfo())
  1324. {
  1325. if (!town->hasBuiltSomeTradeBuilding())
  1326. return 0;
  1327. }
  1328. }
  1329. score += 1000;
  1330. auto resourcesAvailable = evaluationContext.evaluator.ai->getFreeResources();
  1331. auto income = ai->buildAnalyzer->getDailyIncome();
  1332. if(ai->buildAnalyzer->isGoldPressureHigh())
  1333. score /= evaluationContext.buildingCost.marketValue();
  1334. if (!resourcesAvailable.canAfford(evaluationContext.buildingCost))
  1335. {
  1336. TResources needed = evaluationContext.buildingCost - resourcesAvailable;
  1337. needed.positive();
  1338. int turnsTo = needed.maxPurchasableCount(income);
  1339. bool haveEverythingButGold = true;
  1340. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1341. {
  1342. if (i != GameResID::GOLD && resourcesAvailable[i] < evaluationContext.buildingCost[i])
  1343. haveEverythingButGold = false;
  1344. }
  1345. if (turnsTo == INT_MAX)
  1346. return 0;
  1347. if (!haveEverythingButGold)
  1348. score /= turnsTo;
  1349. }
  1350. }
  1351. else
  1352. {
  1353. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend && vstd::isAlmostZero(evaluationContext.conquestValue))
  1354. return 0;
  1355. }
  1356. break;
  1357. }
  1358. }
  1359. result = score;
  1360. //TODO: Figure out the root cause for why evaluationContext.closestWayRatio has become -nan(ind).
  1361. if (std::isnan(result))
  1362. return 0;
  1363. }
  1364. #if NKAI_TRACE_LEVEL >= 2
  1365. 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",
  1366. priorityTier,
  1367. task->toString(),
  1368. evaluationContext.armyLossRatio,
  1369. (int)evaluationContext.turn,
  1370. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1371. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1372. evaluationContext.armyInvolvement,
  1373. goldRewardPerTurn,
  1374. evaluationContext.goldCost,
  1375. evaluationContext.armyReward,
  1376. evaluationContext.armyGrowth,
  1377. evaluationContext.skillReward,
  1378. evaluationContext.danger,
  1379. evaluationContext.threatTurns,
  1380. evaluationContext.threat,
  1381. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1382. evaluationContext.strategicalValue,
  1383. evaluationContext.conquestValue,
  1384. evaluationContext.closestWayRatio,
  1385. evaluationContext.enemyHeroDangerRatio,
  1386. result);
  1387. #endif
  1388. return result;
  1389. }
  1390. }