CaptureObjectsBehavior.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /*
  2. * CaptureObjectsBehavior.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 "../AIGateway.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../Goals/Composition.h"
  14. #include "../Goals/ExecuteHeroChain.h"
  15. #include "../Goals/Invalid.h"
  16. #include "CaptureObjectsBehavior.h"
  17. #include "../AIUtility.h"
  18. namespace NKAI
  19. {
  20. using namespace Goals;
  21. template <typename T>
  22. bool vectorEquals(const std::vector<T> & v1, const std::vector<T> & v2)
  23. {
  24. return vstd::contains_if(v1, [&](T o) -> bool
  25. {
  26. return vstd::contains(v2, o);
  27. });
  28. }
  29. std::string CaptureObjectsBehavior::toString() const
  30. {
  31. return "Capture objects";
  32. }
  33. bool CaptureObjectsBehavior::operator==(const CaptureObjectsBehavior & other) const
  34. {
  35. if(specificObjects != other.specificObjects)
  36. return false;
  37. if(specificObjects)
  38. return vectorEquals(objectsToCapture, other.objectsToCapture);
  39. return vectorEquals(objectTypes, other.objectTypes)
  40. && vectorEquals(objectSubTypes, other.objectSubTypes);
  41. }
  42. Goals::TGoalVec CaptureObjectsBehavior::getVisitGoals(
  43. const std::vector<AIPath> & paths,
  44. const Nullkiller * nullkiller,
  45. const CGObjectInstance * objToVisit,
  46. bool force)
  47. {
  48. Goals::TGoalVec tasks;
  49. tasks.reserve(paths.size());
  50. std::unordered_map<HeroRole, const AIPath *> closestWaysByRole;
  51. std::vector<ExecuteHeroChain *> waysToVisitObj;
  52. for(auto & path : paths)
  53. {
  54. tasks.push_back(sptr(Goals::Invalid()));
  55. #if NKAI_TRACE_LEVEL >= 2
  56. logAi->trace("Path found %s", path.toString());
  57. #endif
  58. if(objToVisit && !force && !shouldVisit(nullkiller, path.targetHero, objToVisit))
  59. {
  60. #if NKAI_TRACE_LEVEL >= 2
  61. logAi->trace("Ignore path. Hero %s should not visit obj %s", path.targetHero->getNameTranslated(), objToVisit->getObjectName());
  62. #endif
  63. continue;
  64. }
  65. auto hero = path.targetHero;
  66. auto danger = path.getTotalDanger();
  67. if(nullkiller->heroManager->getHeroRole(hero) == HeroRole::SCOUT
  68. && (path.getTotalDanger() == 0 || path.turn() > 0)
  69. && path.exchangeCount > 1)
  70. {
  71. #if NKAI_TRACE_LEVEL >= 2
  72. logAi->trace("Ignore path. Hero %s is SCOUT, chain used and no danger", path.targetHero->getNameTranslated());
  73. #endif
  74. continue;
  75. }
  76. auto firstBlockedAction = path.getFirstBlockedAction();
  77. if(firstBlockedAction)
  78. {
  79. auto subGoal = firstBlockedAction->decompose(nullkiller, path.targetHero);
  80. #if NKAI_TRACE_LEVEL >= 2
  81. logAi->trace("Decomposing special action %s returns %s", firstBlockedAction->toString(), subGoal->toString());
  82. #endif
  83. if(!subGoal->invalid())
  84. {
  85. Composition composition;
  86. composition.addNext(ExecuteHeroChain(path, objToVisit));
  87. composition.addNext(subGoal);
  88. tasks[tasks.size() - 1] = sptr(composition);
  89. }
  90. continue;
  91. }
  92. auto isSafe = isSafeToVisit(hero, path.heroArmy, danger);
  93. #if NKAI_TRACE_LEVEL >= 2
  94. logAi->trace(
  95. "It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
  96. isSafe ? "safe" : "not safe",
  97. objToVisit ? objToVisit->getObjectName() : path.targetTile().toString(),
  98. hero->getObjectName(),
  99. path.getHeroStrength(),
  100. danger,
  101. path.getTotalArmyLoss());
  102. #endif
  103. if(isSafe)
  104. {
  105. auto newWay = new ExecuteHeroChain(path, objToVisit);
  106. TSubgoal sharedPtr;
  107. sharedPtr.reset(newWay);
  108. auto heroRole = nullkiller->heroManager->getHeroRole(path.targetHero);
  109. auto & closestWay = closestWaysByRole[heroRole];
  110. if(!closestWay || closestWay->movementCost() > path.movementCost())
  111. {
  112. closestWay = &path;
  113. }
  114. if(!nullkiller->arePathHeroesLocked(path))
  115. {
  116. waysToVisitObj.push_back(newWay);
  117. tasks[tasks.size() - 1] = sharedPtr;
  118. }
  119. }
  120. }
  121. for(auto way : waysToVisitObj)
  122. {
  123. auto heroRole = nullkiller->heroManager->getHeroRole(way->getPath().targetHero);
  124. auto closestWay = closestWaysByRole[heroRole];
  125. if(closestWay)
  126. {
  127. way->closestWayRatio
  128. = closestWay->movementCost() / way->getPath().movementCost();
  129. }
  130. }
  131. return tasks;
  132. }
  133. void CaptureObjectsBehavior::decomposeObjects(
  134. Goals::TGoalVec & result,
  135. const std::vector<const CGObjectInstance *> & objs,
  136. const Nullkiller * nullkiller) const
  137. {
  138. if(objs.empty())
  139. {
  140. return;
  141. }
  142. std::mutex sync;
  143. logAi->debug("Scanning objects, count %d", objs.size());
  144. // tbb::blocked_range<size_t> r(0, objs.size());
  145. tbb::parallel_for(
  146. tbb::blocked_range<size_t>(0, objs.size()),
  147. [this, &objs, &sync, &result, nullkiller](const tbb::blocked_range<size_t> & r)
  148. {
  149. std::vector<AIPath> paths;
  150. Goals::TGoalVec tasksLocal;
  151. for(auto i = r.begin(); i != r.end(); i++)
  152. {
  153. auto objToVisit = objs[i];
  154. if(!objectMatchesFilter(objToVisit))
  155. continue;
  156. #if NKAI_TRACE_LEVEL >= 1
  157. logAi->trace("Checking object %s, %s", objToVisit->getObjectName(), objToVisit->visitablePos().toString());
  158. #endif
  159. nullkiller->pathfinder->calculatePathInfo(paths, objToVisit->visitablePos(), nullkiller->isObjectGraphAllowed());
  160. #if NKAI_TRACE_LEVEL >= 1
  161. logAi->trace("Found %d paths", paths.size());
  162. #endif
  163. vstd::concatenate(tasksLocal, getVisitGoals(paths, nullkiller, objToVisit, specificObjects));
  164. }
  165. std::lock_guard lock(sync); // FIXME: consider using tbb::parallel_reduce instead to avoid mutex overhead
  166. vstd::concatenate(result, tasksLocal);
  167. });
  168. }
  169. Goals::TGoalVec CaptureObjectsBehavior::decompose(const Nullkiller * ai) const
  170. {
  171. Goals::TGoalVec tasks;
  172. vstd::erase_if(tasks, [](TSubgoal task) -> bool
  173. {
  174. return task->invalid();
  175. });
  176. if(specificObjects)
  177. {
  178. decomposeObjects(tasks, objectsToCapture, ai);
  179. }
  180. else if(objectTypes.size())
  181. {
  182. decomposeObjects(
  183. tasks,
  184. std::vector<const CGObjectInstance *>(
  185. ai->memory->visitableObjs.begin(),
  186. ai->memory->visitableObjs.end()),
  187. ai);
  188. }
  189. else
  190. {
  191. decomposeObjects(tasks, ai->objectClusterizer->getNearbyObjects(), ai);
  192. if(tasks.empty() || ai->getScanDepth() != ScanDepth::SMALL)
  193. decomposeObjects(tasks, ai->objectClusterizer->getFarObjects(), ai);
  194. }
  195. return tasks;
  196. }
  197. bool CaptureObjectsBehavior::objectMatchesFilter(const CGObjectInstance * obj) const
  198. {
  199. if(objectTypes.size() && !vstd::contains(objectTypes, obj->ID.num))
  200. {
  201. return false;
  202. }
  203. if(objectSubTypes.size() && !vstd::contains(objectSubTypes, obj->subID))
  204. {
  205. return false;
  206. }
  207. return true;
  208. }
  209. }