PriorityEvaluator.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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/mapObjects/MapObjects.h"
  14. #include "../../../lib/mapObjects/CommonConstructors.h"
  15. #include "../../../lib/CCreatureHandler.h"
  16. #include "../../../lib/CPathfinder.h"
  17. #include "../../../lib/CGameStateFwd.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/ExchangeSwapTownHeroes.h"
  25. #include "../Markers/UnlockCluster.h"
  26. #include "../Markers/HeroExchange.h"
  27. #include "../Markers/ArmyUpgrade.h"
  28. #include "../Markers/DefendTown.h"
  29. namespace NKAI
  30. {
  31. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  32. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  33. EvaluationContext::EvaluationContext(const Nullkiller * ai)
  34. : movementCost(0.0),
  35. manaCost(0),
  36. danger(0),
  37. closestWayRatio(1),
  38. movementCostByRole(),
  39. skillReward(0),
  40. goldReward(0),
  41. goldCost(0),
  42. armyReward(0),
  43. armyLossPersentage(0),
  44. heroRole(HeroRole::SCOUT),
  45. turn(0),
  46. strategicalValue(0),
  47. evaluator(ai),
  48. enemyHeroDangerRatio(0)
  49. {
  50. }
  51. PriorityEvaluator::~PriorityEvaluator()
  52. {
  53. delete engine;
  54. }
  55. void PriorityEvaluator::initVisitTile()
  56. {
  57. auto file = CResourceHandler::get()->load(ResourceID("config/ai/object-priorities.txt"))->readAll();
  58. std::string str = std::string((char *)file.first.get(), file.second);
  59. engine = fl::FllImporter().fromString(str);
  60. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  61. heroRoleVariable = engine->getInputVariable("heroRole");
  62. dangerVariable = engine->getInputVariable("danger");
  63. turnVariable = engine->getInputVariable("turn");
  64. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  65. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  66. goldRewardVariable = engine->getInputVariable("goldReward");
  67. armyRewardVariable = engine->getInputVariable("armyReward");
  68. skillRewardVariable = engine->getInputVariable("skillReward");
  69. rewardTypeVariable = engine->getInputVariable("rewardType");
  70. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  71. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  72. goldPreasureVariable = engine->getInputVariable("goldPreasure");
  73. goldCostVariable = engine->getInputVariable("goldCost");
  74. fearVariable = engine->getInputVariable("fear");
  75. value = engine->getOutputVariable("Value");
  76. }
  77. bool isAnotherAi(const CGObjectInstance * obj, const CPlayerSpecificInfoCallback & cb)
  78. {
  79. return obj->getOwner().isValidPlayer()
  80. && cb.getStartInfo()->getIthPlayersSettings(obj->getOwner()).isControlledByAI();
  81. }
  82. int32_t estimateTownIncome(CCallback * cb, const CGObjectInstance * target, const CGHeroInstance * hero)
  83. {
  84. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  85. if(relations != PlayerRelations::ENEMIES)
  86. return 0; // if we already own it, no additional reward will be received by just visiting it
  87. auto booster = isAnotherAi(target, *cb) ? 1 : 2;
  88. auto town = cb->getTown(target->id);
  89. auto fortLevel = town->fortLevel();
  90. if(town->hasCapitol()) return booster * 2000;
  91. // probably well developed town will have city hall
  92. if(fortLevel == CGTownInstance::CASTLE) return booster * 750;
  93. return booster * (town->hasFort() && town->tempOwner != PlayerColor::NEUTRAL ? booster * 500 : 250);
  94. }
  95. TResources getCreatureBankResources(const CGObjectInstance * target, const CGHeroInstance * hero)
  96. {
  97. //Fixme: unused variable hero
  98. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  99. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  100. auto resources = bankInfo->getPossibleResourcesReward();
  101. TResources result = TResources();
  102. int sum = 0;
  103. for(auto & reward : resources)
  104. {
  105. result += reward.data * reward.chance;
  106. sum += reward.chance;
  107. }
  108. return sum > 1 ? result / sum : result;
  109. }
  110. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  111. {
  112. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  113. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  114. auto creatures = bankInfo->getPossibleCreaturesReward();
  115. uint64_t result = 0;
  116. const auto& slots = hero->Slots();
  117. ui64 weakestStackPower = 0;
  118. if (slots.size() >= GameConstants::ARMY_SIZE)
  119. {
  120. //No free slot, we might discard our weakest stack
  121. weakestStackPower = std::numeric_limits<ui64>().max();
  122. for (const auto & stack : slots)
  123. {
  124. vstd::amin(weakestStackPower, stack.second->getPower());
  125. }
  126. }
  127. for (auto c : creatures)
  128. {
  129. //Only if hero has slot for this creature in the army
  130. if (hero->getSlotFor(c.data.type).validSlot())
  131. {
  132. result += (c.data.type->AIValue * c.data.count) * c.chance;
  133. }
  134. else
  135. {
  136. //we will need to discard the weakest stack
  137. result += (c.data.type->AIValue * c.data.count - weakestStackPower) * c.chance;
  138. }
  139. }
  140. result /= 100; //divide by total chance
  141. return result;
  142. }
  143. uint64_t getDwellingScore(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  144. {
  145. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  146. uint64_t score = 0;
  147. for(auto & creLevel : dwelling->creatures)
  148. {
  149. if(creLevel.first && creLevel.second.size())
  150. {
  151. auto creature = creLevel.second.back().toCreature();
  152. auto creaturesAreFree = creature->level == 1;
  153. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->cost * creLevel.first))
  154. continue;
  155. score += creature->AIValue * creLevel.first;
  156. }
  157. }
  158. return score;
  159. }
  160. int getDwellingArmyCost(const CGObjectInstance * target)
  161. {
  162. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  163. int cost = 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->level == 1;
  170. if(!creaturesAreFree)
  171. cost += creature->cost[Res::GOLD] * creLevel.first;
  172. }
  173. }
  174. return cost;
  175. }
  176. uint64_t evaluateArtifactArmyValue(CArtifactInstance * art)
  177. {
  178. if(art->artType->getId() == ArtifactID::SPELL_SCROLL)
  179. return 1500;
  180. auto statsValue =
  181. 10 * art->valOfBonuses(Bonus::LAND_MOVEMENT)
  182. + 1200 * art->valOfBonuses(Bonus::STACKS_SPEED)
  183. + 700 * art->valOfBonuses(Bonus::MORALE)
  184. + 700 * art->getAttack(false)
  185. + 700 * art->getDefense(false)
  186. + 700 * art->valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::KNOWLEDGE)
  187. + 700 * art->valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::SPELL_POWER)
  188. + 500 * art->valOfBonuses(Bonus::LUCK);
  189. auto classValue = 0;
  190. switch(art->artType->aClass)
  191. {
  192. case CArtifact::EartClass::ART_MINOR:
  193. classValue = 1000;
  194. break;
  195. case CArtifact::EartClass::ART_MAJOR:
  196. classValue = 3000;
  197. break;
  198. case CArtifact::EartClass::ART_RELIC:
  199. case CArtifact::EartClass::ART_SPECIAL:
  200. classValue = 8000;
  201. break;
  202. }
  203. return statsValue > classValue ? statsValue : classValue;
  204. }
  205. uint64_t RewardEvaluator::getArmyReward(
  206. const CGObjectInstance * target,
  207. const CGHeroInstance * hero,
  208. const CCreatureSet * army,
  209. bool checkGold) const
  210. {
  211. const float enemyArmyEliminationRewardRatio = 0.5f;
  212. if(!target)
  213. return 0;
  214. switch(target->ID)
  215. {
  216. case Obj::TOWN:
  217. {
  218. auto town = dynamic_cast<const CGTownInstance *>(target);
  219. auto fortLevel = town->fortLevel();
  220. auto booster = isAnotherAi(town, *ai->cb) ? 1 : 2;
  221. if(fortLevel < CGTownInstance::CITADEL)
  222. return town->hasFort() ? booster * 500 : 0;
  223. else
  224. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  225. }
  226. case Obj::HILL_FORT:
  227. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  228. case Obj::CREATURE_BANK:
  229. return getCreatureBankArmyReward(target, hero);
  230. case Obj::CREATURE_GENERATOR1:
  231. case Obj::CREATURE_GENERATOR2:
  232. case Obj::CREATURE_GENERATOR3:
  233. case Obj::CREATURE_GENERATOR4:
  234. return getDwellingScore(ai->cb.get(), target, checkGold);
  235. case Obj::CRYPT:
  236. case Obj::SHIPWRECK:
  237. case Obj::SHIPWRECK_SURVIVOR:
  238. case Obj::WARRIORS_TOMB:
  239. return 1000;
  240. case Obj::ARTIFACT:
  241. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact);
  242. case Obj::DRAGON_UTOPIA:
  243. return 10000;
  244. case Obj::HERO:
  245. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  246. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  247. : 0;
  248. case Obj::PANDORAS_BOX:
  249. return 5000;
  250. default:
  251. return 0;
  252. }
  253. }
  254. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  255. {
  256. if(!target)
  257. return 0;
  258. switch(target->ID)
  259. {
  260. case Obj::HILL_FORT:
  261. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[Res::GOLD];
  262. case Obj::SCHOOL_OF_MAGIC:
  263. case Obj::SCHOOL_OF_WAR:
  264. return 1000;
  265. case Obj::UNIVERSITY:
  266. return 2000;
  267. case Obj::CREATURE_GENERATOR1:
  268. case Obj::CREATURE_GENERATOR2:
  269. case Obj::CREATURE_GENERATOR3:
  270. case Obj::CREATURE_GENERATOR4:
  271. return getDwellingArmyCost(target);
  272. default:
  273. return 0;
  274. }
  275. }
  276. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  277. {
  278. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  279. float objectValue = 0;
  280. for(auto obj : objectsUnderTreat)
  281. {
  282. vstd::amax(objectValue, getStrategicalValue(obj));
  283. }
  284. /*
  285. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  286. Killing the hero is almost as important (0.9) as capturing the object itself.
  287. 2. The formula quickly approaches 1.0 as hero level increases,
  288. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  289. */
  290. return std::min(1.0f, objectValue * 0.9f + (1.0f - (1.0f / (1 + enemy->level))));
  291. }
  292. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  293. {
  294. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  295. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  296. if(requiredResources[resType] == 0)
  297. return 0;
  298. if(dailyIncome[resType] == 0)
  299. return 1.0f;
  300. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  301. return std::min(ratio, 1.0f);
  302. }
  303. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  304. {
  305. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  306. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  307. if(requiredResources[resType] == 0)
  308. return 0;
  309. float ratio = dailyIncome[resType] == 0
  310. ? requiredResources[resType] / 50
  311. : (float)requiredResources[resType] / dailyIncome[resType] / 50;
  312. return std::min(ratio, 1.0f);
  313. }
  314. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target) const
  315. {
  316. if(!target)
  317. return 0;
  318. switch(target->ID)
  319. {
  320. case Obj::MINE:
  321. return target->subID == Res::GOLD
  322. ? 0.5f
  323. : 0.02f * getTotalResourceRequirementStrength(target->subID) + 0.02f * getResourceRequirementStrength(target->subID);
  324. case Obj::RESOURCE:
  325. return target->subID == Res::GOLD ? 0 : 0.1f * getResourceRequirementStrength(target->subID);
  326. case Obj::CREATURE_BANK:
  327. {
  328. auto resourceReward = getCreatureBankResources(target, nullptr);
  329. float sum = 0.0f;
  330. for (TResources::nziterator it (resourceReward); it.valid(); it++)
  331. {
  332. //Evaluate resources used for construction. Gold is evaluated separately.
  333. if (it->resType != Res::GOLD)
  334. {
  335. sum += 0.1f * getResourceRequirementStrength(it->resType);
  336. }
  337. }
  338. return sum;
  339. }
  340. case Obj::TOWN:
  341. {
  342. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  343. return 1;
  344. auto town = dynamic_cast<const CGTownInstance *>(target);
  345. auto fortLevel = town->fortLevel();
  346. auto booster = isAnotherAi(town, *ai->cb) ? 0.3 : 1;
  347. if(town->hasCapitol()) return 1;
  348. if(fortLevel < CGTownInstance::CITADEL)
  349. return booster * (town->hasFort() ? 0.6 : 0.4);
  350. else
  351. return booster * (fortLevel == CGTownInstance::CASTLE ? 0.9 : 0.8);
  352. }
  353. case Obj::HERO:
  354. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  355. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  356. : 0;
  357. default:
  358. return 0;
  359. }
  360. }
  361. float RewardEvaluator::evaluateWitchHutSkillScore(const CGWitchHut * hut, const CGHeroInstance * hero, HeroRole role) const
  362. {
  363. if(!hut->wasVisited(hero->tempOwner))
  364. return role == HeroRole::SCOUT ? 2 : 0;
  365. auto skill = SecondarySkill(hut->ability);
  366. if(hero->getSecSkillLevel(skill) != SecSkillLevel::NONE
  367. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  368. return 0;
  369. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  370. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  371. }
  372. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  373. {
  374. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  375. if(!target)
  376. return 0;
  377. switch(target->ID)
  378. {
  379. case Obj::STAR_AXIS:
  380. case Obj::SCHOLAR:
  381. case Obj::SCHOOL_OF_MAGIC:
  382. case Obj::SCHOOL_OF_WAR:
  383. case Obj::GARDEN_OF_REVELATION:
  384. case Obj::MARLETTO_TOWER:
  385. case Obj::MERCENARY_CAMP:
  386. case Obj::SHRINE_OF_MAGIC_GESTURE:
  387. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  388. case Obj::TREE_OF_KNOWLEDGE:
  389. return 1;
  390. case Obj::LEARNING_STONE:
  391. return 1.0f / std::sqrt(hero->level);
  392. case Obj::ARENA:
  393. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  394. return 2;
  395. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  396. return 8;
  397. case Obj::WITCH_HUT:
  398. return evaluateWitchHutSkillScore(dynamic_cast<const CGWitchHut *>(target), hero, role);
  399. case Obj::PANDORAS_BOX:
  400. //Can contains experience, spells, or skills (only on custom maps)
  401. return 2.5f;
  402. case Obj::HERO:
  403. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  404. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  405. : 0;
  406. default:
  407. return 0;
  408. }
  409. }
  410. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  411. {
  412. auto & treatNode = ai->dangerHitMap->getTileTreat(tile);
  413. if(treatNode.maximumDanger.danger == 0)
  414. return HitMapInfo::NoTreat;
  415. if(treatNode.maximumDanger.turn <= turn)
  416. return treatNode.maximumDanger;
  417. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoTreat;
  418. }
  419. int32_t getArmyCost(const CArmedInstance * army)
  420. {
  421. int32_t value = 0;
  422. for(auto stack : army->Slots())
  423. {
  424. value += stack.second->getCreatureID().toCreature()->cost[Res::GOLD] * stack.second->count;
  425. }
  426. return value;
  427. }
  428. /// Gets aproximated reward in gold. Daily income is multiplied by 5
  429. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  430. {
  431. if(!target)
  432. return 0;
  433. const int dailyIncomeMultiplier = 5;
  434. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  435. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  436. auto isGold = target->subID == Res::GOLD; // TODO: other resorces could be sold but need to evaluate market power
  437. switch(target->ID)
  438. {
  439. case Obj::RESOURCE:
  440. return isGold ? 600 : 100;
  441. case Obj::TREASURE_CHEST:
  442. return 1500;
  443. case Obj::WATER_WHEEL:
  444. return 1000;
  445. case Obj::TOWN:
  446. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  447. case Obj::MINE:
  448. case Obj::ABANDONED_MINE:
  449. return dailyIncomeMultiplier * (isGold ? 1000 : 75);
  450. case Obj::MYSTICAL_GARDEN:
  451. case Obj::WINDMILL:
  452. return 100;
  453. case Obj::CAMPFIRE:
  454. return 800;
  455. case Obj::WAGON:
  456. return 100;
  457. case Obj::CREATURE_BANK:
  458. return getCreatureBankResources(target, hero)[Res::GOLD];
  459. case Obj::CRYPT:
  460. case Obj::DERELICT_SHIP:
  461. return 3000;
  462. case Obj::DRAGON_UTOPIA:
  463. return 10000;
  464. case Obj::SEA_CHEST:
  465. return 1500;
  466. case Obj::PANDORAS_BOX:
  467. return 5000;
  468. case Obj::PRISON:
  469. //Objectively saves us 2500 to hire hero
  470. return GameConstants::HERO_GOLD_COST;
  471. case Obj::HERO:
  472. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  473. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  474. : 0;
  475. default:
  476. return 0;
  477. }
  478. }
  479. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  480. {
  481. public:
  482. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  483. {
  484. if(task->goalType != Goals::HERO_EXCHANGE)
  485. return;
  486. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  487. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength();
  488. evaluationContext.strategicalValue += 0.5f * armyStrength / heroExchange.hero.get()->getArmyStrength();
  489. }
  490. };
  491. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  492. {
  493. public:
  494. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  495. {
  496. if(task->goalType != Goals::ARMY_UPGRADE)
  497. return;
  498. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  499. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  500. evaluationContext.armyReward += upgradeValue;
  501. evaluationContext.strategicalValue += upgradeValue / armyUpgrade.hero->getTotalStrength();
  502. }
  503. };
  504. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  505. {
  506. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  507. if(enemyDanger.danger)
  508. {
  509. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  510. auto enemyHero = evaluationContext.evaluator.ai->cb->getObj(enemyDanger.hero.hid, false);
  511. bool isAI = enemyHero && isAnotherAi(enemyHero, *evaluationContext.evaluator.ai->cb);
  512. if(isAI)
  513. {
  514. dangerRatio *= 1.5; // lets make AI bit more afraid of other AI.
  515. }
  516. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  517. }
  518. }
  519. class DefendTownEvaluator : public IEvaluationContextBuilder
  520. {
  521. private:
  522. uint64_t townArmyIncome(const CGTownInstance * town) const
  523. {
  524. uint64_t result = 0;
  525. for(auto creatureInfo : town->creatures)
  526. {
  527. if(creatureInfo.second.empty())
  528. continue;
  529. auto creature = creatureInfo.second.back().toCreature();
  530. result += creature->AIValue * town->getGrowthInfo(creature->level).totalGrowth();
  531. }
  532. return result;
  533. }
  534. public:
  535. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  536. {
  537. if(task->goalType != Goals::DEFEND_TOWN)
  538. return;
  539. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  540. const CGTownInstance * town = defendTown.town;
  541. auto & treat = defendTown.getTreat();
  542. auto armyIncome = townArmyIncome(town);
  543. auto dailyIncome = town->dailyIncome()[Res::GOLD];
  544. auto strategicalValue = std::sqrt(armyIncome / 20000.0f) + dailyIncome / 3000.0f;
  545. float multiplier = 1;
  546. if(treat.turn < defendTown.getTurn())
  547. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  548. evaluationContext.armyReward += armyIncome * multiplier;
  549. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  550. evaluationContext.strategicalValue += strategicalValue * multiplier;
  551. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  552. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  553. }
  554. };
  555. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  556. {
  557. private:
  558. const Nullkiller * ai;
  559. public:
  560. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  561. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  562. {
  563. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  564. return;
  565. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  566. const AIPath & path = chain.getPath();
  567. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  568. evaluationContext.movementCost += path.movementCost();
  569. evaluationContext.closestWayRatio = chain.closestWayRatio;
  570. std::map<const CGHeroInstance *, float> costsPerHero;
  571. for(auto & node : path.nodes)
  572. {
  573. vstd::amax(costsPerHero[node.targetHero], node.cost);
  574. }
  575. for(auto pair : costsPerHero)
  576. {
  577. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  578. evaluationContext.movementCostByRole[role] += pair.second;
  579. }
  580. auto heroPtr = task->hero;
  581. auto hero = heroPtr.get(ai->cb.get());
  582. bool checkGold = evaluationContext.danger == 0;
  583. auto army = path.heroArmy;
  584. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  585. if (target && ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner) == PlayerRelations::ENEMIES)
  586. {
  587. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  588. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  589. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, evaluationContext.heroRole);
  590. evaluationContext.strategicalValue += evaluationContext.evaluator.getStrategicalValue(target);
  591. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  592. }
  593. vstd::amax(evaluationContext.armyLossPersentage, path.getTotalArmyLoss() / (double)path.getHeroStrength());
  594. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroPtr);
  595. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  596. vstd::amax(evaluationContext.turn, path.turn());
  597. }
  598. };
  599. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  600. {
  601. public:
  602. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  603. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  604. {
  605. if(task->goalType != Goals::UNLOCK_CLUSTER)
  606. return;
  607. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  608. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  609. auto hero = clusterGoal.hero.get();
  610. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(clusterGoal.hero);
  611. std::vector<std::pair<const CGObjectInstance *, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  612. std::sort(objects.begin(), objects.end(), [](std::pair<const CGObjectInstance *, ClusterObjectInfo> o1, std::pair<const CGObjectInstance *, ClusterObjectInfo> o2) -> bool
  613. {
  614. return o1.second.priority > o2.second.priority;
  615. });
  616. int boost = 1;
  617. for(auto objInfo : objects)
  618. {
  619. auto target = objInfo.first;
  620. bool checkGold = objInfo.second.danger == 0;
  621. auto army = hero;
  622. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  623. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  624. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  625. evaluationContext.strategicalValue += evaluationContext.evaluator.getStrategicalValue(target) / boost;
  626. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  627. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  628. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  629. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  630. boost <<= 1;
  631. if(boost > 8)
  632. break;
  633. }
  634. }
  635. };
  636. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  637. {
  638. public:
  639. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  640. {
  641. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  642. return;
  643. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  644. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  645. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  646. {
  647. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  648. evaluationContext.movementCost += garrisonHero->movement;
  649. evaluationContext.movementCostByRole[defenderRole] += garrisonHero->movement;
  650. }
  651. }
  652. };
  653. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  654. {
  655. public:
  656. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  657. {
  658. if(task->goalType != Goals::BUILD_STRUCTURE)
  659. return;
  660. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  661. auto & bi = buildThis.buildingInfo;
  662. evaluationContext.goldReward += 7 * bi.dailyIncome[Res::GOLD] / 2; // 7 day income but half we already have
  663. evaluationContext.heroRole = HeroRole::MAIN;
  664. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  665. evaluationContext.strategicalValue += buildThis.townInfo.armyStrength / 50000.0;
  666. evaluationContext.goldCost += bi.buildCostWithPrerequisits[Res::GOLD];
  667. if(bi.creatureID != CreatureID::NONE)
  668. {
  669. if(bi.baseCreatureID == bi.creatureID)
  670. {
  671. evaluationContext.strategicalValue += 0.5f + 0.1f * bi.creatureLevel / (float)bi.prerequisitesCount;
  672. evaluationContext.armyReward += bi.armyStrength;
  673. }
  674. else
  675. {
  676. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  677. //evaluationContext.strategicalValue += 0.05f * bi.creatureLevel / (float)bi.prerequisitesCount;
  678. evaluationContext.armyReward += 0.3f * potentialUpgradeValue / (float)bi.prerequisitesCount;
  679. }
  680. }
  681. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  682. {
  683. evaluationContext.strategicalValue += buildThis.town->creatures.size() * 0.2f;
  684. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  685. }
  686. else
  687. {
  688. evaluationContext.strategicalValue += evaluationContext.evaluator.ai->buildAnalyzer->getGoldPreasure() * evaluationContext.goldReward / 2200.0f;
  689. }
  690. }
  691. };
  692. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  693. {
  694. if(ai->buildAnalyzer->hasAnyBuilding(town->alignment, bi.id))
  695. return 0;
  696. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  697. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  698. return upgradedPower - creaturesToUpgrade.power;
  699. }
  700. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  701. :ai(ai)
  702. {
  703. initVisitTile();
  704. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  705. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  706. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  707. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  708. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  709. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  710. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  711. }
  712. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  713. {
  714. Goals::TGoalVec parts;
  715. EvaluationContext context(ai);
  716. if(goal->goalType == Goals::COMPOSITION)
  717. {
  718. parts = goal->decompose();
  719. }
  720. else
  721. {
  722. parts.push_back(goal);
  723. }
  724. for(auto subgoal : parts)
  725. {
  726. context.goldCost += subgoal->goldCost;
  727. for(auto builder : evaluationContextBuilders)
  728. {
  729. builder->buildEvaluationContext(context, subgoal);
  730. }
  731. }
  732. return context;
  733. }
  734. float PriorityEvaluator::evaluate(Goals::TSubgoal task)
  735. {
  736. auto evaluationContext = buildEvaluationContext(task);
  737. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  738. + (evaluationContext.armyReward > 0 ? 1 : 0)
  739. + (evaluationContext.skillReward > 0 ? 1 : 0)
  740. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  741. double result = 0;
  742. try
  743. {
  744. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  745. heroRoleVariable->setValue(evaluationContext.heroRole);
  746. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  747. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  748. goldRewardVariable->setValue(evaluationContext.goldReward);
  749. armyRewardVariable->setValue(evaluationContext.armyReward);
  750. skillRewardVariable->setValue(evaluationContext.skillReward);
  751. dangerVariable->setValue(evaluationContext.danger);
  752. rewardTypeVariable->setValue(rewardType);
  753. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  754. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  755. goldPreasureVariable->setValue(ai->buildAnalyzer->getGoldPreasure());
  756. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[Res::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[Res::GOLD] + 1.0f));
  757. turnVariable->setValue(evaluationContext.turn);
  758. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  759. engine->process();
  760. result = value->getValue();
  761. }
  762. catch(fl::Exception & fe)
  763. {
  764. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  765. }
  766. #if NKAI_TRACE_LEVEL >= 2
  767. logAi->trace("Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, gold: %d, cost: %d, army gain: %d, danger: %d, role: %s, strategical value: %f, cwr: %f, fear: %f, result %f",
  768. task->toString(),
  769. evaluationContext.armyLossPersentage,
  770. (int)evaluationContext.turn,
  771. evaluationContext.movementCostByRole[HeroRole::MAIN],
  772. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  773. evaluationContext.goldReward,
  774. evaluationContext.goldCost,
  775. evaluationContext.armyReward,
  776. evaluationContext.danger,
  777. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  778. evaluationContext.strategicalValue,
  779. evaluationContext.closestWayRatio,
  780. evaluationContext.enemyHeroDangerRatio,
  781. result);
  782. #endif
  783. return result;
  784. }
  785. }