DefenceBehavior.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. * DefenceBehavior.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 "DefenceBehavior.h"
  12. #include "../VCAI.h"
  13. #include "../Engine/Nullkiller.h"
  14. #include "../AIUtility.h"
  15. #include "../Goals/BuyArmy.h"
  16. #include "../Goals/ExecuteHeroChain.h"
  17. #include "../Goals/RecruitHero.h"
  18. #include "../Goals/DismissHero.h"
  19. #include "../Goals/ExchangeSwapTownHeroes.h"
  20. #include "lib/mapping/CMap.h" //for victory conditions
  21. #include "lib/CPathfinder.h"
  22. extern boost::thread_specific_ptr<CCallback> cb;
  23. extern boost::thread_specific_ptr<VCAI> ai;
  24. using namespace Goals;
  25. std::string DefenceBehavior::toString() const
  26. {
  27. return "Defend towns";
  28. }
  29. Goals::TGoalVec DefenceBehavior::decompose() const
  30. {
  31. Goals::TGoalVec tasks;
  32. for(auto town : cb->getTownsInfo())
  33. {
  34. evaluateDefence(tasks, town);
  35. }
  36. return tasks;
  37. }
  38. uint64_t townArmyIncome(const CGTownInstance * town)
  39. {
  40. uint64_t result = 0;
  41. for(auto creatureInfo : town->creatures)
  42. {
  43. if(creatureInfo.second.empty())
  44. continue;
  45. auto creature = creatureInfo.second.back().toCreature();
  46. result += creature->AIValue * town->getGrowthInfo(creature->level).totalGrowth();
  47. }
  48. return result;
  49. }
  50. void DefenceBehavior::evaluateDefence(Goals::TGoalVec & tasks, const CGTownInstance * town) const
  51. {
  52. auto basicPriority = 0.3f + std::sqrt(townArmyIncome(town) / 40000.0f)
  53. + town->dailyIncome()[Res::GOLD] / 10000.0f;
  54. logAi->debug("Evaluating defence for %s, basic priority %f", town->name, basicPriority);
  55. auto treatNode = ai->nullkiller->dangerHitMap->getObjectTreat(town);
  56. auto treats = { treatNode.fastestDanger, treatNode.maximumDanger };
  57. if(!treatNode.fastestDanger.hero)
  58. {
  59. logAi->debug("No treat found for town %s", town->name);
  60. return;
  61. }
  62. int dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  63. if(town->garrisonHero)
  64. {
  65. if(!ai->nullkiller->isHeroLocked(town->garrisonHero.get()))
  66. {
  67. if(!town->visitingHero)
  68. {
  69. tasks.push_back(Goals::sptr(Goals::ExchangeSwapTownHeroes(town, nullptr).setpriority(5)));
  70. }
  71. return;
  72. }
  73. logAi->debug(
  74. "Hero %s in garrison of town %s is suposed to defend the town",
  75. town->garrisonHero->name,
  76. town->name);
  77. return;
  78. }
  79. uint64_t reinforcement = ai->nullkiller->armyManager->howManyReinforcementsCanBuy(town->getUpperArmy(), town);
  80. if(reinforcement)
  81. {
  82. logAi->debug("Town %s can buy defence army %lld", town->name, reinforcement);
  83. tasks.push_back(Goals::sptr(Goals::BuyArmy(town, reinforcement).setpriority(0.5f)));
  84. }
  85. auto paths = ai->nullkiller->pathfinder->getPathInfo(town->visitablePos());
  86. for(auto & treat : treats)
  87. {
  88. logAi->debug(
  89. "Town %s has treat %lld in %s turns, hero: %s",
  90. town->name,
  91. treat.danger,
  92. std::to_string(treat.turn),
  93. treat.hero->name);
  94. bool treatIsUnderControl = false;
  95. for(AIPath & path : paths)
  96. {
  97. if(path.getHeroStrength() > treat.danger)
  98. {
  99. if(path.turn() <= treat.turn && dayOfWeek + treat.turn < 6 && isSafeToVisit(path.targetHero, path.heroArmy, treat.danger)
  100. || path.exchangeCount == 1 && path.turn() < treat.turn
  101. || path.turn() < treat.turn - 1
  102. || path.turn() < treat.turn && treat.turn >= 2)
  103. {
  104. logAi->debug(
  105. "Hero %s can eliminate danger for town %s using path %s.",
  106. path.targetHero->name,
  107. town->name,
  108. path.toString());
  109. treatIsUnderControl = true;
  110. break;
  111. }
  112. }
  113. }
  114. if(treatIsUnderControl)
  115. continue;
  116. if(!town->visitingHero
  117. && town->hasBuilt(BuildingID::TAVERN)
  118. && cb->getResourceAmount(Res::GOLD) > GameConstants::HERO_GOLD_COST)
  119. {
  120. auto heroesInTavern = cb->getAvailableHeroes(town);
  121. for(auto hero : heroesInTavern)
  122. {
  123. if(hero->getTotalStrength() > treat.danger)
  124. {
  125. auto myHeroes = cb->getHeroesInfo();
  126. if(cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES)
  127. {
  128. logAi->debug("Hero %s can be recruited to defend %s", hero->name, town->name);
  129. tasks.push_back(Goals::sptr(Goals::RecruitHero(town, hero).setpriority(1)));
  130. continue;
  131. }
  132. else
  133. {
  134. const CGHeroInstance * weakestHero = nullptr;
  135. for(auto existingHero : myHeroes)
  136. {
  137. if(ai->nullkiller->isHeroLocked(existingHero)
  138. || existingHero->getArmyStrength() > hero->getArmyStrength()
  139. || ai->nullkiller->heroManager->getHeroRole(existingHero) == HeroRole::MAIN
  140. || existingHero->movement
  141. || existingHero->artifactsWorn.size() > (existingHero->hasSpellbook() ? 2 : 1))
  142. continue;
  143. if(!weakestHero || weakestHero->getFightingStrength() > existingHero->getFightingStrength())
  144. {
  145. weakestHero = existingHero;
  146. }
  147. if(weakestHero)
  148. {
  149. tasks.push_back(Goals::sptr(Goals::DismissHero(weakestHero)));
  150. }
  151. }
  152. }
  153. }
  154. }
  155. }
  156. if(paths.empty())
  157. {
  158. logAi->debug("No ways to defend town %s", town->name);
  159. continue;
  160. }
  161. std::vector<Goals::ExecuteHeroChain> pathsToDefend;
  162. std::map<const CGHeroInstance *, std::vector<AIPath>> defferedPaths;
  163. for(AIPath & path : paths)
  164. {
  165. #if AI_TRACE_LEVEL >= 1
  166. logAi->trace(
  167. "Hero %s can defend town with force %lld in %s turns, cost: %f, path: %s",
  168. path.targetHero->name,
  169. path.getHeroStrength(),
  170. std::to_string(path.turn()),
  171. path.movementCost(),
  172. path.toString());
  173. #endif
  174. if(path.turn() <= treat.turn - 2)
  175. {
  176. logAi->trace("Deffer defence of %s by %s because he has enough time to rich the town next trun",
  177. town->name,
  178. path.targetHero->name);
  179. defferedPaths[path.targetHero].push_back(path);
  180. continue;
  181. }
  182. float priority = basicPriority * std::min(SAFE_ATTACK_CONSTANT, (float)path.getHeroStrength() / treat.danger)
  183. - treat.turn * 0.2f;
  184. if(treat.turn < path.turn())
  185. priority /= (path.turn() - treat.turn) * 2;
  186. if(path.targetHero == town->visitingHero && path.exchangeCount == 1)
  187. {
  188. #if AI_TRACE_LEVEL >= 1
  189. logAi->trace("Put %s to garrison of town %s with priority %f",
  190. path.targetHero->name,
  191. town->name,
  192. priority);
  193. #endif
  194. tasks.push_back(Goals::sptr(Goals::ExchangeSwapTownHeroes(town, town->visitingHero.get(), HeroLockedReason::DEFENCE).setpriority(priority)));
  195. continue;
  196. }
  197. if(treat.turn == 0 || path.turn() <= treat.turn && path.getHeroStrength() * SAFE_ATTACK_CONSTANT >= treat.danger)
  198. {
  199. if(ai->nullkiller->arePathHeroesLocked(path))
  200. {
  201. #if AI_TRACE_LEVEL >= 1
  202. logAi->trace("Can not move %s to defend town %s with priority %f. Path is locked.",
  203. path.targetHero->name,
  204. town->name,
  205. priority);
  206. #endif
  207. continue;
  208. }
  209. pathsToDefend.push_back(Goals::ExecuteHeroChain(path, town).setpriority(priority));
  210. }
  211. }
  212. for(Goals::ExecuteHeroChain & chain : pathsToDefend)
  213. {
  214. auto path = chain.getPath();
  215. for(AIPath & defferedPath : defferedPaths[path.targetHero])
  216. {
  217. if(defferedPath.getHeroStrength() >= path.getHeroStrength()
  218. && defferedPath.turn() <= path.turn())
  219. {
  220. continue;
  221. }
  222. }
  223. #if AI_TRACE_LEVEL >= 1
  224. logAi->trace("Move %s to defend town %s with priority %f",
  225. path.targetHero->name,
  226. town->name,
  227. chain.priority);
  228. #endif
  229. tasks.push_back(Goals::sptr(chain));
  230. }
  231. }
  232. logAi->debug("Found %d tasks", tasks.size());
  233. }