PriorityEvaluator.cpp 55 KB

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