PriorityEvaluator.cpp 48 KB

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