PriorityEvaluator.cpp 54 KB

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