PriorityEvaluator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. #include "../Goals/UnlockCluster.h"
  26. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  27. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  28. struct BankConfig;
  29. class CBankInfo;
  30. class Engine;
  31. class InputVariable;
  32. class CGTownInstance;
  33. extern boost::thread_specific_ptr<CCallback> cb;
  34. extern boost::thread_specific_ptr<VCAI> ai;
  35. EvaluationContext::EvaluationContext()
  36. : movementCost(0.0),
  37. manaCost(0),
  38. danger(0),
  39. closestWayRatio(1),
  40. movementCostByRole(),
  41. skillReward(0),
  42. goldReward(0),
  43. goldCost(0),
  44. armyReward(0),
  45. armyLossPersentage(0),
  46. heroRole(HeroRole::SCOUT),
  47. turn(0),
  48. strategicalValue(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. value = engine->getOutputVariable("Value");
  75. }
  76. int32_t estimateTownIncome(const CGObjectInstance * target, const CGHeroInstance * hero)
  77. {
  78. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  79. if(relations != PlayerRelations::ENEMIES)
  80. return 0; // if we already own it, no additional reward will be received by just visiting it
  81. auto town = cb->getTown(target->id);
  82. auto isNeutral = target->tempOwner == PlayerColor::NEUTRAL;
  83. auto isProbablyDeveloped = !isNeutral && town->hasFort();
  84. return isProbablyDeveloped ? 1500 : 500;
  85. }
  86. TResources getCreatureBankResources(const CGObjectInstance * target, const CGHeroInstance * hero)
  87. {
  88. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  89. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  90. auto resources = bankInfo->getPossibleResourcesReward();
  91. return resources;
  92. }
  93. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  94. {
  95. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  96. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  97. auto creatures = bankInfo->getPossibleCreaturesReward();
  98. uint64_t result = 0;
  99. for(auto c : creatures)
  100. {
  101. result += c.type->AIValue * c.count;
  102. }
  103. return result;
  104. }
  105. uint64_t getDwellingScore(const CGObjectInstance * target, bool checkGold)
  106. {
  107. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  108. uint64_t score = 0;
  109. for(auto & creLevel : dwelling->creatures)
  110. {
  111. if(creLevel.first && creLevel.second.size())
  112. {
  113. auto creature = creLevel.second.back().toCreature();
  114. auto creaturesAreFree = creature->level == 1;
  115. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->cost * creLevel.first))
  116. continue;
  117. score += creature->AIValue * creLevel.first;
  118. }
  119. }
  120. return score;
  121. }
  122. int getDwellingArmyCost(const CGObjectInstance * target)
  123. {
  124. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  125. int cost = 0;
  126. for(auto & creLevel : dwelling->creatures)
  127. {
  128. if(creLevel.first && creLevel.second.size())
  129. {
  130. auto creature = creLevel.second.back().toCreature();
  131. auto creaturesAreFree = creature->level == 1;
  132. if(!creaturesAreFree)
  133. cost += creature->cost[Res::GOLD] * creLevel.first;
  134. }
  135. }
  136. return cost;
  137. }
  138. uint64_t evaluateArtifactArmyValue(CArtifactInstance * art)
  139. {
  140. if(art->artType->id == ArtifactID::SPELL_SCROLL)
  141. return 1500;
  142. auto statsValue =
  143. 4 * art->valOfBonuses(Bonus::LAND_MOVEMENT)
  144. + 700 * art->valOfBonuses(Bonus::MORALE)
  145. + 700 * art->getAttack(false)
  146. + 700 * art->getDefence(false)
  147. + 700 * art->valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::KNOWLEDGE)
  148. + 700 * art->valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::SPELL_POWER)
  149. + 700 * art->getDefence(false)
  150. + 500 * art->valOfBonuses(Bonus::LUCK);
  151. auto classValue = 0;
  152. switch(art->artType->aClass)
  153. {
  154. case CArtifact::EartClass::ART_MINOR:
  155. classValue = 1000;
  156. break;
  157. case CArtifact::EartClass::ART_MAJOR:
  158. classValue = 3000;
  159. break;
  160. case CArtifact::EartClass::ART_RELIC:
  161. case CArtifact::EartClass::ART_SPECIAL:
  162. classValue = 8000;
  163. break;
  164. }
  165. return statsValue > classValue ? statsValue : classValue;
  166. }
  167. uint64_t getArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army, bool checkGold)
  168. {
  169. const float enemyArmyEliminationRewardRatio = 0.5f;
  170. if(!target)
  171. return 0;
  172. switch(target->ID)
  173. {
  174. case Obj::TOWN:
  175. return target->tempOwner == PlayerColor::NEUTRAL ? 1000 : 10000;
  176. case Obj::HILL_FORT:
  177. return ai->ah->calculateCreateresUpgrade(army, target, cb->getResourceAmount()).upgradeValue;
  178. case Obj::CREATURE_BANK:
  179. return getCreatureBankArmyReward(target, hero);
  180. case Obj::CREATURE_GENERATOR1:
  181. case Obj::CREATURE_GENERATOR2:
  182. case Obj::CREATURE_GENERATOR3:
  183. case Obj::CREATURE_GENERATOR4:
  184. return getDwellingScore(target, checkGold);
  185. case Obj::CRYPT:
  186. case Obj::SHIPWRECK:
  187. case Obj::SHIPWRECK_SURVIVOR:
  188. case Obj::WARRIORS_TOMB:
  189. return 1000;
  190. case Obj::ARTIFACT:
  191. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact);
  192. case Obj::DRAGON_UTOPIA:
  193. return 10000;
  194. case Obj::HERO:
  195. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  196. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  197. : 0;
  198. default:
  199. return 0;
  200. }
  201. }
  202. int getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army)
  203. {
  204. if(!target)
  205. return 0;
  206. switch(target->ID)
  207. {
  208. case Obj::HILL_FORT:
  209. return ai->ah->calculateCreateresUpgrade(army, target, cb->getResourceAmount()).upgradeCost[Res::GOLD];
  210. case Obj::SCHOOL_OF_MAGIC:
  211. case Obj::SCHOOL_OF_WAR:
  212. return 1000;
  213. case Obj::UNIVERSITY:
  214. return 2000;
  215. case Obj::CREATURE_GENERATOR1:
  216. case Obj::CREATURE_GENERATOR2:
  217. case Obj::CREATURE_GENERATOR3:
  218. case Obj::CREATURE_GENERATOR4:
  219. return getDwellingArmyCost(target);
  220. default:
  221. return 0;
  222. }
  223. }
  224. float getStrategicalValue(const CGObjectInstance * target);
  225. float getEnemyHeroStrategicalValue(const CGHeroInstance * enemy)
  226. {
  227. auto objectsUnderTreat = ai->nullkiller->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  228. float objectValue = 0;
  229. for(auto obj : objectsUnderTreat)
  230. {
  231. vstd::amax(objectValue, getStrategicalValue(obj));
  232. }
  233. return objectValue / 2.0f + enemy->level / 15.0f;
  234. }
  235. float getResourceRequirementStrength(int resType)
  236. {
  237. TResources requiredResources = ai->nullkiller->buildAnalyzer->getResourcesRequiredNow();
  238. TResources dailyIncome = ai->nullkiller->buildAnalyzer->getDailyIncome();
  239. if(requiredResources[resType] == 0)
  240. return 0;
  241. if(dailyIncome[resType] == 0)
  242. return 1.0f;
  243. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  244. return std::min(ratio, 1.0f);
  245. }
  246. float getTotalResourceRequirementStrength(int resType)
  247. {
  248. TResources requiredResources = ai->nullkiller->buildAnalyzer->getTotalResourcesRequired();
  249. TResources dailyIncome = ai->nullkiller->buildAnalyzer->getDailyIncome();
  250. if(requiredResources[resType] == 0)
  251. return 0;
  252. float ratio = dailyIncome[resType] == 0
  253. ? requiredResources[resType] / 50
  254. : (float)requiredResources[resType] / dailyIncome[resType] / 50;
  255. return std::min(ratio, 1.0f);
  256. }
  257. float getStrategicalValue(const CGObjectInstance * target)
  258. {
  259. if(!target)
  260. return 0;
  261. switch(target->ID)
  262. {
  263. case Obj::MINE:
  264. return target->subID == Res::GOLD ? 0.5f : 0.02f * getTotalResourceRequirementStrength(target->subID) + 0.02f * getResourceRequirementStrength(target->subID);
  265. case Obj::RESOURCE:
  266. return target->subID == Res::GOLD ? 0 : 0.1f * getResourceRequirementStrength(target->subID);
  267. case Obj::TOWN:
  268. return dynamic_cast<const CGTownInstance *>(target)->hasFort()
  269. ? (target->tempOwner == PlayerColor::NEUTRAL ? 0.8f : 1.0f)
  270. : 0.5f;
  271. case Obj::HERO:
  272. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  273. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  274. : 0;
  275. default:
  276. return 0;
  277. }
  278. }
  279. float evaluateWitchHutSkillScore(const CGWitchHut * hut, const CGHeroInstance * hero, HeroRole role)
  280. {
  281. if(!hut->wasVisited(hero->tempOwner))
  282. return role == HeroRole::SCOUT ? 2 : 0;
  283. auto skill = SecondarySkill(hut->ability);
  284. if(hero->getSecSkillLevel(skill) != SecSkillLevel::NONE
  285. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  286. return 0;
  287. auto score = ai->ah->evaluateSecSkill(skill, hero);
  288. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  289. }
  290. float getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role)
  291. {
  292. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  293. if(!target)
  294. return 0;
  295. switch(target->ID)
  296. {
  297. case Obj::STAR_AXIS:
  298. case Obj::SCHOLAR:
  299. case Obj::SCHOOL_OF_MAGIC:
  300. case Obj::SCHOOL_OF_WAR:
  301. case Obj::GARDEN_OF_REVELATION:
  302. case Obj::MARLETTO_TOWER:
  303. case Obj::MERCENARY_CAMP:
  304. case Obj::SHRINE_OF_MAGIC_GESTURE:
  305. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  306. case Obj::TREE_OF_KNOWLEDGE:
  307. return 1;
  308. case Obj::LEARNING_STONE:
  309. return 1.0f / std::sqrt(hero->level);
  310. case Obj::ARENA:
  311. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  312. return 2;
  313. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  314. return 8;
  315. case Obj::WITCH_HUT:
  316. return evaluateWitchHutSkillScore(dynamic_cast<const CGWitchHut *>(target), hero, role);
  317. case Obj::HERO:
  318. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  319. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  320. : 0;
  321. default:
  322. return 0;
  323. }
  324. }
  325. int32_t getArmyCost(const CArmedInstance * army)
  326. {
  327. int32_t value = 0;
  328. for(auto stack : army->Slots())
  329. {
  330. value += stack.second->getCreatureID().toCreature()->cost[Res::GOLD] * stack.second->count;
  331. }
  332. return value;
  333. }
  334. /// Gets aproximated reward in gold. Daily income is multiplied by 5
  335. int32_t getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  336. {
  337. if(!target)
  338. return 0;
  339. const int dailyIncomeMultiplier = 5;
  340. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  341. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  342. auto isGold = target->subID == Res::GOLD; // TODO: other resorces could be sold but need to evaluate market power
  343. switch(target->ID)
  344. {
  345. case Obj::RESOURCE:
  346. return isGold ? 600 : 100;
  347. case Obj::TREASURE_CHEST:
  348. return 1500;
  349. case Obj::WATER_WHEEL:
  350. return 1000;
  351. case Obj::TOWN:
  352. return dailyIncomeMultiplier * estimateTownIncome(target, hero);
  353. case Obj::MINE:
  354. case Obj::ABANDONED_MINE:
  355. return dailyIncomeMultiplier * (isGold ? 1000 : 75);
  356. case Obj::MYSTICAL_GARDEN:
  357. case Obj::WINDMILL:
  358. return 100;
  359. case Obj::CAMPFIRE:
  360. return 800;
  361. case Obj::WAGON:
  362. return 100;
  363. case Obj::CREATURE_BANK:
  364. return getCreatureBankResources(target, hero)[Res::GOLD];
  365. case Obj::CRYPT:
  366. case Obj::DERELICT_SHIP:
  367. return 3000;
  368. case Obj::DRAGON_UTOPIA:
  369. return 10000;
  370. case Obj::SEA_CHEST:
  371. return 1500;
  372. case Obj::HERO:
  373. return cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  374. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  375. : 0;
  376. default:
  377. return 0;
  378. }
  379. }
  380. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  381. {
  382. public:
  383. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  384. {
  385. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  386. return;
  387. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  388. const AIPath & path = chain.getPath();
  389. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  390. evaluationContext.movementCost += path.movementCost();
  391. evaluationContext.closestWayRatio = chain.closestWayRatio;
  392. std::map<const CGHeroInstance *, float> costsPerHero;
  393. for(auto & node : path.nodes)
  394. {
  395. vstd::amax(costsPerHero[node.targetHero], node.cost);
  396. }
  397. for(auto pair : costsPerHero)
  398. {
  399. auto role = ai->ah->getHeroRole(pair.first);
  400. evaluationContext.movementCostByRole[role] += pair.second;
  401. }
  402. auto heroPtr = task->hero;
  403. const CGObjectInstance * target = cb->getObj((ObjectInstanceID)task->objid, false);
  404. auto day = cb->getDate(Date::DAY);
  405. auto hero = heroPtr.get();
  406. bool checkGold = evaluationContext.danger == 0;
  407. auto army = path.heroArmy;
  408. vstd::amax(evaluationContext.armyLossPersentage, path.getTotalArmyLoss() / (double)path.getHeroStrength());
  409. evaluationContext.heroRole = ai->ah->getHeroRole(heroPtr);
  410. evaluationContext.goldReward += getGoldReward(target, hero);
  411. evaluationContext.armyReward += getArmyReward(target, hero, army, checkGold);
  412. evaluationContext.skillReward += getSkillReward(target, hero, evaluationContext.heroRole);
  413. evaluationContext.strategicalValue += getStrategicalValue(target);
  414. evaluationContext.goldCost += getGoldCost(target, hero, army);
  415. vstd::amax(evaluationContext.turn, path.turn());
  416. }
  417. };
  418. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  419. {
  420. public:
  421. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  422. {
  423. if(task->goalType != Goals::UNLOCK_CLUSTER)
  424. return;
  425. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  426. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  427. auto hero = clusterGoal.hero.get();
  428. auto role = ai->ah->getHeroRole(clusterGoal.hero);
  429. std::vector<std::pair<const CGObjectInstance *, ObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  430. std::sort(objects.begin(), objects.end(), [](std::pair<const CGObjectInstance *, ObjectInfo> o1, std::pair<const CGObjectInstance *, ObjectInfo> o2) -> bool
  431. {
  432. return o1.second.priority > o2.second.priority;
  433. });
  434. int boost = 1;
  435. for(auto objInfo : objects)
  436. {
  437. auto target = objInfo.first;
  438. auto day = cb->getDate(Date::DAY);
  439. bool checkGold = objInfo.second.danger == 0;
  440. auto army = hero;
  441. evaluationContext.goldReward += getGoldReward(target, hero) / boost;
  442. evaluationContext.armyReward += getArmyReward(target, hero, army, checkGold) / boost;
  443. evaluationContext.skillReward += getSkillReward(target, hero, role) / boost;
  444. evaluationContext.strategicalValue += getStrategicalValue(target) / boost;
  445. evaluationContext.goldCost += getGoldCost(target, hero, army) / boost;
  446. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  447. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  448. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  449. boost <<= 1;
  450. if(boost > 8)
  451. break;
  452. }
  453. const AIPath & pathToCenter = clusterGoal.getPathToCenter();
  454. }
  455. };
  456. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  457. {
  458. public:
  459. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  460. {
  461. if(task->goalType != Goals::BUILD_STRUCTURE)
  462. return;
  463. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  464. auto & bi = buildThis.buildingInfo;
  465. evaluationContext.goldReward += 7 * bi.dailyIncome[Res::GOLD] / 2; // 7 day income but half we already have
  466. evaluationContext.heroRole = HeroRole::MAIN;
  467. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  468. evaluationContext.strategicalValue += buildThis.townInfo.armyScore / 50000.0;
  469. evaluationContext.goldCost += bi.buildCostWithPrerequisits[Res::GOLD];
  470. if(bi.creatureID != CreatureID::NONE)
  471. {
  472. if(bi.baseCreatureID == bi.creatureID)
  473. {
  474. evaluationContext.strategicalValue += 0.5f + 0.1f * bi.creatureLevel / (float)bi.prerequisitesCount;
  475. evaluationContext.armyReward += ai->ah->evaluateStackPower(bi.creatureID.toCreature(), bi.creatureGrows);
  476. }
  477. else
  478. {
  479. auto creaturesToUpgrade = ai->ah->getTotalCreaturesAvailable(bi.baseCreatureID);
  480. auto upgradedPower = ai->ah->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  481. evaluationContext.strategicalValue += 0.05f * bi.creatureLevel / (float)bi.prerequisitesCount;
  482. if(!ai->nullkiller->buildAnalyzer->hasAnyBuilding(buildThis.town->alignment, bi.id))
  483. evaluationContext.armyReward += upgradedPower - creaturesToUpgrade.power;
  484. }
  485. }
  486. else
  487. {
  488. evaluationContext.strategicalValue += ai->nullkiller->buildAnalyzer->getGoldPreasure() * evaluationContext.goldReward / 2200.0f;
  489. }
  490. }
  491. };
  492. PriorityEvaluator::PriorityEvaluator()
  493. {
  494. initVisitTile();
  495. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>());
  496. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  497. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>());
  498. }
  499. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  500. {
  501. Goals::TGoalVec parts;
  502. EvaluationContext context;
  503. if(goal->goalType == Goals::COMPOSITION)
  504. {
  505. parts = goal->decompose();
  506. }
  507. else
  508. {
  509. parts.push_back(goal);
  510. }
  511. for(auto subgoal : parts)
  512. {
  513. context.strategicalValue += subgoal->strategicalValue;
  514. context.goldCost += subgoal->goldCost;
  515. for(auto builder : evaluationContextBuilders)
  516. {
  517. builder->buildEvaluationContext(context, subgoal);
  518. }
  519. }
  520. return context;
  521. }
  522. /// distance
  523. /// nearest hero?
  524. /// gold income
  525. /// army income
  526. /// hero strength - hero skills
  527. /// danger
  528. /// importance
  529. float PriorityEvaluator::evaluate(Goals::TSubgoal task)
  530. {
  531. auto evaluationContext = buildEvaluationContext(task);
  532. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  533. + (evaluationContext.armyReward > 0 ? 1 : 0)
  534. + (evaluationContext.skillReward > 0 ? 1 : 0)
  535. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  536. double result = 0;
  537. try
  538. {
  539. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  540. heroRoleVariable->setValue(evaluationContext.heroRole);
  541. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  542. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  543. goldRewardVariable->setValue(evaluationContext.goldReward);
  544. armyRewardVariable->setValue(evaluationContext.armyReward);
  545. skillRewardVariable->setValue(evaluationContext.skillReward);
  546. dangerVariable->setValue(evaluationContext.danger);
  547. rewardTypeVariable->setValue(rewardType);
  548. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  549. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  550. goldPreasureVariable->setValue(ai->nullkiller->buildAnalyzer->getGoldPreasure());
  551. goldCostVariable->setValue(evaluationContext.goldCost / ((float)cb->getResourceAmount(Res::GOLD) + (float)ai->nullkiller->buildAnalyzer->getDailyIncome()[Res::GOLD] + 1.0f));
  552. turnVariable->setValue(evaluationContext.turn);
  553. engine->process();
  554. //engine.process(VISIT_TILE); //TODO: Process only Visit_Tile
  555. result = value->getValue();
  556. }
  557. catch(fl::Exception & fe)
  558. {
  559. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  560. }
  561. assert(result >= 0);
  562. #ifdef AI_TRACE_LEVEL >= 1
  563. 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, result %f",
  564. task->toString(),
  565. evaluationContext.armyLossPersentage,
  566. (int)evaluationContext.turn,
  567. evaluationContext.movementCostByRole[HeroRole::MAIN],
  568. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  569. evaluationContext.goldReward,
  570. evaluationContext.goldCost,
  571. evaluationContext.armyReward,
  572. evaluationContext.danger,
  573. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  574. evaluationContext.strategicalValue,
  575. evaluationContext.closestWayRatio,
  576. result);
  577. #endif
  578. return result;
  579. }