ObjectClusterizer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * DangerHitMapAnalyzer.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 "ObjectClusterizer.h"
  12. #include "../Goals/ExecuteHeroChain.h"
  13. #include "../AIGateway.h"
  14. #include "../Engine/Nullkiller.h"
  15. namespace NKAI
  16. {
  17. void ObjectCluster::addObject(const CGObjectInstance * obj, const AIPath & path, float priority)
  18. {
  19. ClusterObjects::accessor info;
  20. objects.insert(info, ClusterObjects::value_type(obj, ClusterObjectInfo()));
  21. if(info->second.priority < priority)
  22. {
  23. info->second.priority = priority;
  24. info->second.movementCost = path.movementCost() - path.firstNode().cost;
  25. info->second.danger = path.targetObjectDanger;
  26. info->second.turn = path.turn();
  27. }
  28. }
  29. const CGObjectInstance * ObjectCluster::calculateCenter() const
  30. {
  31. auto v = getObjects();
  32. auto tile = int3(0);
  33. float priority = 0;
  34. for(auto pair : objects)
  35. {
  36. auto newPoint = pair.first->visitablePos();
  37. float newPriority = std::pow(pair.second.priority, 4); // lets make high priority targets more weghtful
  38. int3 direction = newPoint - tile;
  39. float priorityRatio = newPriority / (priority + newPriority);
  40. tile += direction * priorityRatio;
  41. priority += newPriority;
  42. }
  43. auto closestPair = *vstd::minElementByFun(objects, [&](const std::pair<const CGObjectInstance *, ClusterObjectInfo> & pair) -> int
  44. {
  45. return pair.first->visitablePos().dist2dSQ(tile);
  46. });
  47. return closestPair.first;
  48. }
  49. std::vector<const CGObjectInstance *> ObjectCluster::getObjects() const
  50. {
  51. std::vector<const CGObjectInstance *> result;
  52. for(auto pair : objects)
  53. {
  54. result.push_back(pair.first);
  55. }
  56. return result;
  57. }
  58. std::vector<const CGObjectInstance *> ObjectClusterizer::getNearbyObjects() const
  59. {
  60. return nearObjects.getObjects();
  61. }
  62. std::vector<const CGObjectInstance *> ObjectClusterizer::getFarObjects() const
  63. {
  64. return farObjects.getObjects();
  65. }
  66. std::vector<std::shared_ptr<ObjectCluster>> ObjectClusterizer::getLockedClusters() const
  67. {
  68. std::vector<std::shared_ptr<ObjectCluster>> result;
  69. for(auto pair : blockedObjects)
  70. {
  71. result.push_back(pair.second);
  72. }
  73. return result;
  74. }
  75. std::optional<const CGObjectInstance *> ObjectClusterizer::getBlocker(const AIPathNodeInfo & node) const
  76. {
  77. std::vector<const CGObjectInstance *> blockers = {};
  78. if(node.layer == EPathfindingLayer::LAND || node.layer == EPathfindingLayer::SAIL)
  79. {
  80. auto guardPos = ai->cb->getGuardingCreaturePosition(node.coord);
  81. blockers = ai->cb->getVisitableObjs(node.coord);
  82. if(guardPos.valid())
  83. {
  84. auto guard = ai->cb->getTopObj(ai->cb->getGuardingCreaturePosition(node.coord));
  85. if(guard)
  86. {
  87. blockers.insert(blockers.begin(), guard);
  88. }
  89. }
  90. }
  91. if(node.specialAction && node.actionIsBlocked)
  92. {
  93. auto blockerObject = node.specialAction->targetObject();
  94. if(blockerObject)
  95. {
  96. blockers.insert(blockers.begin(), blockerObject);
  97. }
  98. }
  99. if(blockers.empty())
  100. return std::optional< const CGObjectInstance *>();
  101. auto blocker = blockers.front();
  102. if(isObjectPassable(ai, blocker))
  103. return std::optional< const CGObjectInstance *>();
  104. if(blocker->ID == Obj::GARRISON
  105. || blocker->ID == Obj::GARRISON2)
  106. {
  107. if(dynamic_cast<const CArmedInstance *>(blocker)->getArmyStrength() == 0)
  108. return std::optional< const CGObjectInstance *>();
  109. else
  110. return blocker;
  111. }
  112. if(blocker->ID == Obj::MONSTER
  113. || blocker->ID == Obj::BORDERGUARD
  114. || blocker->ID == Obj::BORDER_GATE
  115. || blocker->ID == Obj::SHIPYARD
  116. || (blocker->ID == Obj::QUEST_GUARD && node.actionIsBlocked))
  117. {
  118. return blocker;
  119. }
  120. return std::optional< const CGObjectInstance *>();
  121. }
  122. const CGObjectInstance * ObjectClusterizer::getBlocker(const AIPath & path) const
  123. {
  124. for(auto node = path.nodes.rbegin(); node != path.nodes.rend(); node++)
  125. {
  126. auto blocker = getBlocker(*node);
  127. if(blocker)
  128. return *blocker;
  129. }
  130. return nullptr;
  131. }
  132. bool ObjectClusterizer::shouldVisitObject(const CGObjectInstance * obj) const
  133. {
  134. if(isObjectRemovable(obj))
  135. {
  136. return true;
  137. }
  138. const int3 pos = obj->visitablePos();
  139. if((obj->ID != Obj::CREATURE_GENERATOR1 && vstd::contains(ai->memory->alreadyVisited, obj))
  140. || obj->wasVisited(ai->playerID))
  141. {
  142. return false;
  143. }
  144. auto playerRelations = ai->cb->getPlayerRelations(ai->playerID, obj->tempOwner);
  145. if(playerRelations != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  146. {
  147. return false;
  148. }
  149. //it may be hero visiting this obj
  150. //we don't try visiting object on which allied or owned hero stands
  151. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  152. const CGObjectInstance * topObj = ai->cb->getTopObj(pos);
  153. if(!topObj)
  154. return false; // partly visible obj but its visitable pos is not visible.
  155. if(topObj->ID == Obj::HERO && ai->cb->getPlayerRelations(ai->playerID, topObj->tempOwner) != PlayerRelations::ENEMIES)
  156. return false;
  157. else
  158. return true; //all of the following is met
  159. }
  160. Obj ObjectClusterizer::IgnoredObjectTypes[] = {
  161. Obj::BOAT,
  162. Obj::EYE_OF_MAGI,
  163. Obj::MONOLITH_ONE_WAY_ENTRANCE,
  164. Obj::MONOLITH_ONE_WAY_EXIT,
  165. Obj::MONOLITH_TWO_WAY,
  166. Obj::SUBTERRANEAN_GATE,
  167. Obj::WHIRLPOOL,
  168. Obj::BUOY,
  169. Obj::SIGN,
  170. Obj::GARRISON,
  171. Obj::MONSTER,
  172. Obj::GARRISON2,
  173. Obj::BORDERGUARD,
  174. Obj::QUEST_GUARD,
  175. Obj::BORDER_GATE,
  176. Obj::REDWOOD_OBSERVATORY,
  177. Obj::CARTOGRAPHER,
  178. Obj::PILLAR_OF_FIRE
  179. };
  180. void ObjectClusterizer::clusterize()
  181. {
  182. auto start = std::chrono::high_resolution_clock::now();
  183. nearObjects.reset();
  184. farObjects.reset();
  185. blockedObjects.clear();
  186. logAi->debug("Begin object clusterization");
  187. std::vector<const CGObjectInstance *> objs(
  188. ai->memory->visitableObjs.begin(),
  189. ai->memory->visitableObjs.end());
  190. #if NKAI_TRACE_LEVEL == 0
  191. tbb::parallel_for(tbb::blocked_range<size_t>(0, objs.size()), [&](const tbb::blocked_range<size_t> & r) {
  192. #else
  193. tbb::blocked_range<size_t> r(0, objs.size());
  194. #endif
  195. auto priorityEvaluator = ai->priorityEvaluators->acquire();
  196. auto heroes = ai->cb->getHeroesInfo();
  197. std::vector<AIPath> pathCache;
  198. for(int i = r.begin(); i != r.end(); i++)
  199. {
  200. clusterizeObject(objs[i], priorityEvaluator.get(), pathCache, heroes);
  201. }
  202. #if NKAI_TRACE_LEVEL == 0
  203. });
  204. #endif
  205. logAi->trace("Near objects count: %i", nearObjects.objects.size());
  206. logAi->trace("Far objects count: %i", farObjects.objects.size());
  207. for(auto pair : blockedObjects)
  208. {
  209. logAi->trace("Cluster %s %s count: %i", pair.first->getObjectName(), pair.first->visitablePos().toString(), pair.second->objects.size());
  210. #if NKAI_TRACE_LEVEL >= 1
  211. for(auto obj : pair.second->getObjects())
  212. {
  213. logAi->trace("Object %s %s", obj->getObjectName(), obj->visitablePos().toString());
  214. }
  215. #endif
  216. }
  217. logAi->trace("Clusterization complete in %ld", timeElapsed(start));
  218. }
  219. void ObjectClusterizer::clusterizeObject(
  220. const CGObjectInstance * obj,
  221. PriorityEvaluator * priorityEvaluator,
  222. std::vector<AIPath> & pathCache,
  223. std::vector<const CGHeroInstance *> & heroes)
  224. {
  225. if(!shouldVisitObject(obj))
  226. {
  227. #if NKAI_TRACE_LEVEL >= 2
  228. logAi->trace("Skip object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
  229. #endif
  230. return;
  231. }
  232. #if NKAI_TRACE_LEVEL >= 2
  233. logAi->trace("Check object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
  234. #endif
  235. if(ai->settings->isObjectGraphAllowed())
  236. {
  237. ai->pathfinder->calculateQuickPathsWithBlocker(pathCache, heroes, obj->visitablePos());
  238. }
  239. else
  240. ai->pathfinder->calculatePathInfo(pathCache, obj->visitablePos(), false);
  241. if(pathCache.empty())
  242. {
  243. #if NKAI_TRACE_LEVEL >= 2
  244. logAi->trace("No paths found.");
  245. #endif
  246. return;
  247. }
  248. std::sort(pathCache.begin(), pathCache.end(), [](const AIPath & p1, const AIPath & p2) -> bool
  249. {
  250. return p1.movementCost() < p2.movementCost();
  251. });
  252. if(vstd::contains(IgnoredObjectTypes, obj->ID))
  253. {
  254. farObjects.addObject(obj, pathCache.front(), 0);
  255. #if NKAI_TRACE_LEVEL >= 2
  256. logAi->trace("Object ignored. Moved to far objects with path %s", pathCache.front().toString());
  257. #endif
  258. return;
  259. }
  260. std::set<const CGHeroInstance *> heroesProcessed;
  261. for(auto & path : pathCache)
  262. {
  263. #if NKAI_TRACE_LEVEL >= 2
  264. logAi->trace("Checking path %s", path.toString());
  265. #endif
  266. if(ai->heroManager->getHeroRole(path.targetHero) == HeroRole::SCOUT)
  267. {
  268. if(path.movementCost() > 2.0f)
  269. {
  270. #if NKAI_TRACE_LEVEL >= 2
  271. logAi->trace("Path is too far %f", path.movementCost());
  272. #endif
  273. continue;
  274. }
  275. }
  276. else if(path.movementCost() > 4.0f && obj->ID != Obj::TOWN)
  277. {
  278. auto strategicalValue = valueEvaluator.getStrategicalValue(obj);
  279. if(strategicalValue < 0.3f)
  280. {
  281. #if NKAI_TRACE_LEVEL >= 2
  282. logAi->trace("Object value is too low %f", strategicalValue);
  283. #endif
  284. continue;
  285. }
  286. }
  287. if(!shouldVisit(ai, path.targetHero, obj))
  288. {
  289. #if NKAI_TRACE_LEVEL >= 2
  290. logAi->trace("Hero %s does not need to visit %s", path.targetHero->getObjectName(), obj->getObjectName());
  291. #endif
  292. continue;
  293. }
  294. if(path.nodes.size() > 1)
  295. {
  296. auto blocker = getBlocker(path);
  297. if(blocker)
  298. {
  299. if(vstd::contains(heroesProcessed, path.targetHero))
  300. {
  301. #if NKAI_TRACE_LEVEL >= 2
  302. logAi->trace("Hero %s is already processed.", path.targetHero->getObjectName());
  303. #endif
  304. continue;
  305. }
  306. heroesProcessed.insert(path.targetHero);
  307. float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
  308. if(priority < MIN_PRIORITY)
  309. continue;
  310. ClusterMap::accessor cluster;
  311. blockedObjects.insert(
  312. cluster,
  313. ClusterMap::value_type(blocker, std::make_shared<ObjectCluster>(blocker)));
  314. cluster->second->addObject(obj, path, priority);
  315. #if NKAI_TRACE_LEVEL >= 2
  316. logAi->trace("Path added to cluster %s%s", blocker->getObjectName(), blocker->visitablePos().toString());
  317. #endif
  318. continue;
  319. }
  320. }
  321. heroesProcessed.insert(path.targetHero);
  322. float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
  323. if(priority < MIN_PRIORITY)
  324. continue;
  325. bool interestingObject = path.turn() <= 2 || priority > 0.5f;
  326. if(interestingObject)
  327. {
  328. nearObjects.addObject(obj, path, priority);
  329. }
  330. else
  331. {
  332. farObjects.addObject(obj, path, priority);
  333. }
  334. #if NKAI_TRACE_LEVEL >= 2
  335. logAi->trace("Path %s added to %s objects. Turn: %d, priority: %f",
  336. path.toString(),
  337. interestingObject ? "near" : "far",
  338. path.turn(),
  339. priority);
  340. #endif
  341. }
  342. }
  343. }