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