PriorityEvaluator.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 "PriorityEvaluator.h"
  12. #include <limits>
  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 "../../../CCallback.h"
  20. #include "../../../lib/filesystem/Filesystem.h"
  21. #include "../VCAI.h"
  22. #include "../AIhelper.h"
  23. #include "../Engine/Nullkiller.h"
  24. #include "../Goals/ExecuteHeroChain.h"
  25. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  26. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  27. struct BankConfig;
  28. class CBankInfo;
  29. class Engine;
  30. class InputVariable;
  31. class CGTownInstance;
  32. extern boost::thread_specific_ptr<CCallback> cb;
  33. extern boost::thread_specific_ptr<VCAI> ai;
  34. PriorityEvaluator::~PriorityEvaluator()
  35. {
  36. delete engine;
  37. }
  38. void PriorityEvaluator::initVisitTile()
  39. {
  40. auto file = CResourceHandler::get()->load(ResourceID("config/ai/object-priorities.txt"))->readAll();
  41. std::string str = std::string((char *)file.first.get(), file.second);
  42. engine = fl::FllImporter().fromString(str);
  43. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  44. heroRoleVariable = engine->getInputVariable("heroRole");
  45. dangerVariable = engine->getInputVariable("danger");
  46. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  47. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  48. goldRewardVariable = engine->getInputVariable("goldReward");
  49. armyRewardVariable = engine->getInputVariable("armyReward");
  50. skillRewardVariable = engine->getInputVariable("skillReward");
  51. rewardTypeVariable = engine->getInputVariable("rewardType");
  52. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  53. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  54. value = engine->getOutputVariable("Value");
  55. }
  56. int32_t estimateTownIncome(const CGObjectInstance * target, const CGHeroInstance * hero)
  57. {
  58. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  59. if(relations != PlayerRelations::ENEMIES)
  60. return 0; // if we already own it, no additional reward will be received by just visiting it
  61. auto town = cb->getTown(target->id);
  62. auto isNeutral = target->tempOwner == PlayerColor::NEUTRAL;
  63. auto isProbablyDeveloped = !isNeutral && town->hasFort();
  64. return isProbablyDeveloped ? 1500 : 500;
  65. }
  66. TResources getCreatureBankResources(const CGObjectInstance * target, const CGHeroInstance * hero)
  67. {
  68. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  69. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  70. auto resources = bankInfo->getPossibleResourcesReward();
  71. return resources;
  72. }
  73. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  74. {
  75. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  76. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  77. auto creatures = bankInfo->getPossibleCreaturesReward();
  78. uint64_t result = 0;
  79. for(auto c : creatures)
  80. {
  81. result += c.type->AIValue * c.count;
  82. }
  83. return result;
  84. }
  85. uint64_t getDwellingScore(const CGObjectInstance * target, bool checkGold)
  86. {
  87. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  88. uint64_t score = 0;
  89. for(auto & creLevel : dwelling->creatures)
  90. {
  91. if(creLevel.first && creLevel.second.size())
  92. {
  93. auto creature = creLevel.second.back().toCreature();
  94. auto creaturesAreFree = creature->level == 1;
  95. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->cost * creLevel.first))
  96. continue;
  97. score += creature->AIValue * creLevel.first;
  98. }
  99. }
  100. return score;
  101. }
  102. uint64_t evaluateArtifactArmyValue(CArtifactInstance * art)
  103. {
  104. if(art->artType->id == ArtifactID::SPELL_SCROLL)
  105. return 1500;
  106. auto statsValue =
  107. 4 * art->valOfBonuses(Bonus::LAND_MOVEMENT)
  108. + 700 * art->valOfBonuses(Bonus::MORALE)
  109. + 700 * art->getAttack(false)
  110. + 700 * art->getDefence(false)
  111. + 700 * art->valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::KNOWLEDGE)
  112. + 700 * art->valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::SPELL_POWER)
  113. + 700 * art->getDefence(false)
  114. + 500 * art->valOfBonuses(Bonus::LUCK);
  115. auto classValue = 0;
  116. switch(art->artType->aClass)
  117. {
  118. case CArtifact::EartClass::ART_MINOR:
  119. classValue = 1000;
  120. break;
  121. case CArtifact::EartClass::ART_MAJOR:
  122. classValue = 3000;
  123. break;
  124. case CArtifact::EartClass::ART_RELIC:
  125. case CArtifact::EartClass::ART_SPECIAL:
  126. classValue = 8000;
  127. break;
  128. }
  129. return statsValue > classValue ? statsValue : classValue;
  130. }
  131. uint64_t getArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army, bool checkGold)
  132. {
  133. const float enemyArmyEliminationRewardRatio = 0.5f;
  134. if(!target)
  135. return 0;
  136. switch(target->ID)
  137. {
  138. case Obj::TOWN:
  139. return target->tempOwner == PlayerColor::NEUTRAL ? 1000 : 10000;
  140. case Obj::HILL_FORT:
  141. return ai->ah->calculateCreateresUpgrade(army, target, cb->getResourceAmount()).upgradeValue;
  142. case Obj::CREATURE_BANK:
  143. return getCreatureBankArmyReward(target, hero);
  144. case Obj::CREATURE_GENERATOR1:
  145. case Obj::CREATURE_GENERATOR2:
  146. case Obj::CREATURE_GENERATOR3:
  147. case Obj::CREATURE_GENERATOR4:
  148. return getDwellingScore(target, checkGold);
  149. case Obj::CRYPT:
  150. case Obj::SHIPWRECK:
  151. case Obj::SHIPWRECK_SURVIVOR:
  152. case Obj::WARRIORS_TOMB:
  153. return 1000;
  154. case Obj::ARTIFACT:
  155. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact);
  156. case Obj::DRAGON_UTOPIA:
  157. return 10000;
  158. case Obj::HERO:
  159. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  160. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  161. : 0;
  162. default:
  163. return 0;
  164. }
  165. }
  166. float getStrategicalValue(const CGObjectInstance * target);
  167. float getEnemyHeroStrategicalValue(const CGHeroInstance * enemy)
  168. {
  169. auto objectsUnderTreat = ai->nullkiller->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  170. float objectValue = 0;
  171. for(auto obj : objectsUnderTreat)
  172. {
  173. vstd::amax(objectValue, getStrategicalValue(obj));
  174. }
  175. return objectValue / 2.0f + enemy->level / 15.0f;
  176. }
  177. float getResourceRequirementStrength(int resType)
  178. {
  179. TResources requiredResources = ai->nullkiller->buildAnalyzer->getResourcesRequiredNow();
  180. TResources dailyIncome = ai->nullkiller->buildAnalyzer->getDailyIncome();
  181. if(requiredResources[resType] == 0)
  182. return 0;
  183. if(dailyIncome[resType] == 0)
  184. return 1;
  185. return (float)requiredResources[resType] / dailyIncome[resType] / 3;
  186. }
  187. float getTotalResourceRequirementStrength(int resType)
  188. {
  189. TResources requiredResources = ai->nullkiller->buildAnalyzer->getTotalResourcesRequired();
  190. TResources dailyIncome = ai->nullkiller->buildAnalyzer->getDailyIncome();
  191. if(requiredResources[resType] == 0)
  192. return 0;
  193. if(dailyIncome[resType] == 0)
  194. return requiredResources[resType] / 30;
  195. return (float)requiredResources[resType] / dailyIncome[resType] / 30;
  196. }
  197. float getStrategicalValue(const CGObjectInstance * target)
  198. {
  199. if(!target)
  200. return 0;
  201. switch(target->ID)
  202. {
  203. case Obj::MINE:
  204. return target->subID == Res::GOLD ? 0.8f : 0.05f + 0.3f * getTotalResourceRequirementStrength(target->subID) + 0.5f * getResourceRequirementStrength(target->subID);
  205. case Obj::RESOURCE:
  206. return target->subID == Res::GOLD ? 0 : 0.5f * getResourceRequirementStrength(target->subID);
  207. case Obj::TOWN:
  208. return target->tempOwner == PlayerColor::NEUTRAL ? 0.5 : 1;
  209. case Obj::HERO:
  210. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  211. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  212. : 0;
  213. default:
  214. return 0;
  215. }
  216. }
  217. float evaluateWitchHutSkillScore(const CGWitchHut * hut, const CGHeroInstance * hero, HeroRole role)
  218. {
  219. if(!hut->wasVisited(hero->tempOwner))
  220. return role == HeroRole::SCOUT ? 2 : 0;
  221. auto skill = SecondarySkill(hut->ability);
  222. if(hero->getSecSkillLevel(skill) != SecSkillLevel::NONE
  223. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  224. return 0;
  225. auto score = ai->ah->evaluateSecSkill(skill, hero);
  226. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  227. }
  228. float getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role)
  229. {
  230. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  231. if(!target)
  232. return 0;
  233. switch(target->ID)
  234. {
  235. case Obj::STAR_AXIS:
  236. case Obj::SCHOLAR:
  237. case Obj::SCHOOL_OF_MAGIC:
  238. case Obj::SCHOOL_OF_WAR:
  239. case Obj::GARDEN_OF_REVELATION:
  240. case Obj::MARLETTO_TOWER:
  241. case Obj::MERCENARY_CAMP:
  242. case Obj::SHRINE_OF_MAGIC_GESTURE:
  243. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  244. case Obj::TREE_OF_KNOWLEDGE:
  245. return 1;
  246. case Obj::LEARNING_STONE:
  247. return 1.0f / std::sqrtf(hero->level);
  248. case Obj::ARENA:
  249. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  250. return 2;
  251. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  252. return 8;
  253. case Obj::WITCH_HUT:
  254. return evaluateWitchHutSkillScore(dynamic_cast<const CGWitchHut *>(target), hero, role);
  255. case Obj::HERO:
  256. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  257. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  258. : 0;
  259. default:
  260. return 0;
  261. }
  262. }
  263. int32_t getArmyCost(const CArmedInstance * army)
  264. {
  265. int32_t value = 0;
  266. for(auto stack : army->Slots())
  267. {
  268. value += stack.second->getCreatureID().toCreature()->cost[Res::GOLD] * stack.second->count;
  269. }
  270. return value;
  271. }
  272. /// Gets aproximated reward in gold. Daily income is multiplied by 5
  273. int32_t getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  274. {
  275. if(!target)
  276. return 0;
  277. const int dailyIncomeMultiplier = 5;
  278. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  279. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  280. auto isGold = target->subID == Res::GOLD; // TODO: other resorces could be sold but need to evaluate market power
  281. switch(target->ID)
  282. {
  283. case Obj::RESOURCE:
  284. return isGold ? 600 : 100;
  285. case Obj::TREASURE_CHEST:
  286. return 1500;
  287. case Obj::WATER_WHEEL:
  288. return 1000;
  289. case Obj::TOWN:
  290. return dailyIncomeMultiplier * estimateTownIncome(target, hero);
  291. case Obj::MINE:
  292. case Obj::ABANDONED_MINE:
  293. return dailyIncomeMultiplier * (isGold ? 1000 : 75);
  294. case Obj::MYSTICAL_GARDEN:
  295. case Obj::WINDMILL:
  296. return 100;
  297. case Obj::CAMPFIRE:
  298. return 800;
  299. case Obj::WAGON:
  300. return 100;
  301. case Obj::CREATURE_BANK:
  302. return getCreatureBankResources(target, hero)[Res::GOLD];
  303. case Obj::CRYPT:
  304. case Obj::DERELICT_SHIP:
  305. return 3000;
  306. case Obj::DRAGON_UTOPIA:
  307. return 10000;
  308. case Obj::SEA_CHEST:
  309. return 1500;
  310. case Obj::HERO:
  311. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  312. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  313. : 0;
  314. default:
  315. return 0;
  316. }
  317. }
  318. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  319. {
  320. public:
  321. virtual Goals::EvaluationContext buildEvaluationContext(Goals::TSubgoal task) const override
  322. {
  323. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  324. auto evaluationContext = task->evaluationContext;
  325. auto heroPtr = task->hero;
  326. const CGObjectInstance * target = cb->getObj((ObjectInstanceID)task->objid, false);
  327. auto day = cb->getDate(Date::DAY);
  328. auto hero = heroPtr.get();
  329. bool checkGold = evaluationContext.danger == 0;
  330. evaluationContext.armyLossPersentage = task->evaluationContext.armyLoss / (double)task->evaluationContext.heroStrength;
  331. evaluationContext.heroRole = ai->ah->getHeroRole(heroPtr);
  332. evaluationContext.goldReward = getGoldReward(target, hero);
  333. evaluationContext.armyReward = getArmyReward(target, hero, chain.getPath().heroArmy, checkGold);
  334. evaluationContext.skillReward = getSkillReward(target, hero, evaluationContext.heroRole);
  335. evaluationContext.strategicalValue = getStrategicalValue(target);
  336. return evaluationContext;
  337. }
  338. };
  339. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  340. {
  341. public:
  342. virtual Goals::EvaluationContext buildEvaluationContext(Goals::TSubgoal task) const override
  343. {
  344. Goals::EvaluationContext evaluationContext;
  345. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  346. auto & bi = buildThis.buildingInfo;
  347. evaluationContext.goldReward = bi.dailyIncome[Res::GOLD] / 2;
  348. evaluationContext.heroRole = HeroRole::MAIN;
  349. evaluationContext.movementCostByRole[evaluationContext.heroRole] = bi.prerequisitesCount;
  350. evaluationContext.armyReward = 0;
  351. evaluationContext.strategicalValue = buildThis.townInfo.armyScore / 50000.0;
  352. if(bi.creatureID != CreatureID::NONE)
  353. {
  354. evaluationContext.strategicalValue += 0.5f + 0.1f * bi.creatureLevel;
  355. if(bi.baseCreatureID == bi.creatureID)
  356. {
  357. evaluationContext.armyReward = ai->ah->evaluateStackPower(bi.creatureID.toCreature(), bi.creatureGrows);
  358. }
  359. auto creaturesToUpgrade = ai->ah->getTotalCreaturesAvailable(bi.baseCreatureID);
  360. auto upgradedPower = ai->ah->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  361. evaluationContext.armyReward = upgradedPower - creaturesToUpgrade.power;
  362. }
  363. return evaluationContext;
  364. }
  365. };
  366. PriorityEvaluator::PriorityEvaluator()
  367. {
  368. initVisitTile();
  369. evaluationContextBuilders[Goals::EXECUTE_HERO_CHAIN] = std::make_shared<ExecuteHeroChainEvaluationContextBuilder>();
  370. evaluationContextBuilders[Goals::BUILD_STRUCTURE] = std::make_shared<BuildThisEvaluationContextBuilder>();
  371. }
  372. Goals::EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  373. {
  374. auto builder = evaluationContextBuilders.find(goal->goalType);
  375. if(builder == evaluationContextBuilders.end())
  376. return goal->evaluationContext;
  377. return builder->second->buildEvaluationContext(goal);
  378. }
  379. /// distance
  380. /// nearest hero?
  381. /// gold income
  382. /// army income
  383. /// hero strength - hero skills
  384. /// danger
  385. /// importance
  386. float PriorityEvaluator::evaluate(Goals::TSubgoal task)
  387. {
  388. if(task->priority > 0)
  389. return task->priority;
  390. auto evaluationContext = buildEvaluationContext(task);
  391. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  392. + (evaluationContext.armyReward > 0 ? 1 : 0)
  393. + (evaluationContext.skillReward > 0 ? 1 : 0)
  394. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  395. double result = 0;
  396. try
  397. {
  398. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  399. heroRoleVariable->setValue(evaluationContext.heroRole);
  400. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  401. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  402. goldRewardVariable->setValue(evaluationContext.goldReward);
  403. armyRewardVariable->setValue(evaluationContext.armyReward);
  404. skillRewardVariable->setValue(evaluationContext.skillReward);
  405. dangerVariable->setValue(evaluationContext.danger);
  406. rewardTypeVariable->setValue(rewardType);
  407. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  408. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  409. engine->process();
  410. //engine.process(VISIT_TILE); //TODO: Process only Visit_Tile
  411. result = value->getValue();
  412. }
  413. catch(fl::Exception & fe)
  414. {
  415. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  416. }
  417. assert(result >= 0);
  418. #ifdef VCMI_TRACE_PATHFINDER
  419. logAi->trace("Evaluated %s, loss: %f, turns main: %f, scout: %f, gold: %d, army gain: %d, danger: %d, role: %s, strategical value: %f, result %f",
  420. task->name(),
  421. evaluationContext.armyLossPersentage,
  422. evaluationContext.movementCostByRole[HeroRole::MAIN],
  423. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  424. evaluationContext.goldReward,
  425. evaluationContext.armyReward,
  426. evaluationContext.danger,
  427. evaluationContext.heroRole ? "scout" : "main",
  428. evaluationContext.strategicalValue,
  429. result);
  430. #endif
  431. return result;
  432. }