ObjectClusterizer.cpp 8.6 KB

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