GraphPaths.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. * GraphPaths.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 "GraphPaths.h"
  12. #include "AIPathfinderConfig.h"
  13. #include "../../../lib/CRandomGenerator.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapObjects/CQuest.h"
  16. #include "../../../lib/mapping/CMap.h"
  17. #include "../Engine/Nullkiller.h"
  18. #include "../../../lib/logging/VisualLogger.h"
  19. #include "Actions/QuestAction.h"
  20. #include "../pforeach.h"
  21. #include "Actions/BoatActions.h"
  22. namespace NKAI
  23. {
  24. bool GraphNodeComparer::operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const
  25. {
  26. return pathNodes.at(lhs.coord)[lhs.nodeType].cost > pathNodes.at(rhs.coord)[rhs.nodeType].cost;
  27. }
  28. GraphPaths::GraphPaths()
  29. : visualKey(""), graph(), pathNodes()
  30. {
  31. }
  32. std::shared_ptr<SpecialAction> getCompositeAction(
  33. const Nullkiller * ai,
  34. std::shared_ptr<ISpecialActionFactory> linkActionFactory,
  35. std::shared_ptr<SpecialAction> transitionAction)
  36. {
  37. if(!linkActionFactory)
  38. return transitionAction;
  39. auto linkAction = linkActionFactory->create(ai);
  40. if(!transitionAction)
  41. return linkAction;
  42. std::vector<std::shared_ptr<const SpecialAction>> actionsArray = {
  43. transitionAction,
  44. linkAction
  45. };
  46. return std::make_shared<CompositeAction>(actionsArray);
  47. }
  48. void GraphPaths::calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai, uint8_t scanDepth)
  49. {
  50. graph.copyFrom(*ai->baseGraph);
  51. graph.connectHeroes(ai);
  52. visualKey = std::to_string(ai->playerID) + ":" + targetHero->getNameTranslated();
  53. pathNodes.clear();
  54. GraphNodeComparer cmp(pathNodes);
  55. GraphPathNode::TFibHeap pq(cmp);
  56. pathNodes[targetHero->visitablePos()][GrapthPathNodeType::NORMAL].cost = 0;
  57. pq.emplace(GraphPathNodePointer(targetHero->visitablePos(), GrapthPathNodeType::NORMAL));
  58. while(!pq.empty())
  59. {
  60. GraphPathNodePointer pos = pq.top();
  61. pq.pop();
  62. auto & node = getOrCreateNode(pos);
  63. std::shared_ptr<SpecialAction> transitionAction;
  64. if(node.obj)
  65. {
  66. if(node.obj->ID == Obj::QUEST_GUARD
  67. || node.obj->ID == Obj::BORDERGUARD
  68. || node.obj->ID == Obj::BORDER_GATE)
  69. {
  70. auto questObj = dynamic_cast<const IQuestObject *>(node.obj);
  71. auto questInfo = QuestInfo(node.obj->id);
  72. if(node.obj->ID == Obj::QUEST_GUARD
  73. && questObj->getQuest().mission == Rewardable::Limiter{}
  74. && questObj->getQuest().killTarget == ObjectInstanceID::NONE)
  75. {
  76. continue;
  77. }
  78. auto questAction = std::make_shared<AIPathfinding::QuestAction>(questInfo);
  79. if(!questAction->canAct(ai, targetHero))
  80. {
  81. transitionAction = questAction;
  82. }
  83. }
  84. }
  85. node.isInQueue = false;
  86. graph.iterateConnections(pos.coord, [this, ai, &pos, &node, &transitionAction, &pq, scanDepth](int3 target, const ObjectLink & o)
  87. {
  88. auto compositeAction = getCompositeAction(ai, o.specialAction, transitionAction);
  89. auto targetNodeType = o.danger || compositeAction ? GrapthPathNodeType::BATTLE : pos.nodeType;
  90. auto targetPointer = GraphPathNodePointer(target, targetNodeType);
  91. auto & targetNode = getOrCreateNode(targetPointer);
  92. if(targetNode.tryUpdate(pos, node, o))
  93. {
  94. if(targetNode.cost > scanDepth)
  95. {
  96. return;
  97. }
  98. targetNode.specialAction = compositeAction;
  99. const auto & targetGraphNode = graph.getNode(target);
  100. if(targetGraphNode.objID.hasValue())
  101. {
  102. targetNode.obj = ai->cb->getObj(targetGraphNode.objID, false);
  103. if(targetNode.obj && targetNode.obj->ID == Obj::HERO)
  104. return;
  105. }
  106. if(targetNode.isInQueue)
  107. {
  108. pq.increase(targetNode.handle);
  109. }
  110. else
  111. {
  112. targetNode.handle = pq.emplace(targetPointer);
  113. targetNode.isInQueue = true;
  114. }
  115. }
  116. });
  117. }
  118. }
  119. void GraphPaths::dumpToLog() const
  120. {
  121. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  122. {
  123. for(auto & tile : pathNodes)
  124. {
  125. for(auto & node : tile.second)
  126. {
  127. if(!node.previous.valid())
  128. continue;
  129. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  130. {
  131. logAi->trace(
  132. "%s -> %s: %f !%d",
  133. node.previous.coord.toString(),
  134. tile.first.toString(),
  135. node.cost,
  136. node.linkDanger);
  137. }
  138. logBuilder.addLine(node.previous.coord, tile.first);
  139. }
  140. }
  141. });
  142. }
  143. bool GraphPathNode::tryUpdate(
  144. const GraphPathNodePointer & pos,
  145. const GraphPathNode & prev,
  146. const ObjectLink & link)
  147. {
  148. auto newCost = prev.cost + link.cost;
  149. if(newCost < cost)
  150. {
  151. previous = pos;
  152. linkDanger = link.danger;
  153. cost = newCost;
  154. return true;
  155. }
  156. return false;
  157. }
  158. void GraphPaths::addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  159. {
  160. auto nodes = pathNodes.find(tile);
  161. if(nodes == pathNodes.end())
  162. return;
  163. for(auto & node : nodes->second)
  164. {
  165. if(!node.reachable())
  166. continue;
  167. std::vector<GraphPathNodePointer> tilesToPass;
  168. uint64_t danger = node.linkDanger;
  169. float cost = node.cost;
  170. bool allowBattle = false;
  171. auto current = GraphPathNodePointer(nodes->first, node.nodeType);
  172. while(true)
  173. {
  174. auto currentTile = pathNodes.find(current.coord);
  175. if(currentTile == pathNodes.end())
  176. break;
  177. auto & currentNode = currentTile->second[current.nodeType];
  178. if(!currentNode.previous.valid())
  179. break;
  180. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  181. vstd::amax(danger, currentNode.linkDanger);
  182. vstd::amax(cost, currentNode.cost);
  183. tilesToPass.push_back(current);
  184. if(currentNode.cost < 2.0f)
  185. break;
  186. current = currentNode.previous;
  187. }
  188. if(tilesToPass.empty())
  189. continue;
  190. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  191. for(auto & path : entryPaths)
  192. {
  193. if(path.targetHero != hero)
  194. continue;
  195. uint64_t loss = 0;
  196. uint64_t strength = getHeroArmyStrengthWithCommander(path.targetHero, path.heroArmy);
  197. for(auto graphTile = ++tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  198. {
  199. AIPathNodeInfo n;
  200. auto & node = getNode(*graphTile);
  201. n.coord = graphTile->coord;
  202. n.cost = cost;
  203. n.turns = static_cast<ui8>(cost) + 1; // just in case lets select worst scenario
  204. n.danger = danger;
  205. n.targetHero = hero;
  206. n.parentIndex = -1;
  207. n.specialAction = node.specialAction;
  208. if(node.linkDanger > 0)
  209. {
  210. auto additionalLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, strength, node.linkDanger);
  211. loss += additionalLoss;
  212. if(strength > additionalLoss)
  213. strength -= additionalLoss;
  214. else
  215. {
  216. strength = 0;
  217. break;
  218. }
  219. }
  220. if(n.specialAction)
  221. {
  222. n.actionIsBlocked = !n.specialAction->canAct(ai, n);
  223. }
  224. for(auto & node : path.nodes)
  225. {
  226. node.parentIndex++;
  227. }
  228. path.nodes.insert(path.nodes.begin(), n);
  229. }
  230. if(strength == 0)
  231. {
  232. continue;
  233. }
  234. path.armyLoss += loss;
  235. path.targetObjectDanger = ai->dangerEvaluator->evaluateDanger(tile, path.targetHero, !allowBattle);
  236. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  237. paths.push_back(path);
  238. }
  239. }
  240. }
  241. void GraphPaths::quickAddChainInfoWithBlocker(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  242. {
  243. auto nodes = pathNodes.find(tile);
  244. if(nodes == pathNodes.end())
  245. return;
  246. for(auto & targetNode : nodes->second)
  247. {
  248. if(!targetNode.reachable())
  249. continue;
  250. std::vector<GraphPathNodePointer> tilesToPass;
  251. uint64_t danger = targetNode.linkDanger;
  252. float cost = targetNode.cost;
  253. bool allowBattle = false;
  254. auto current = GraphPathNodePointer(nodes->first, targetNode.nodeType);
  255. while(true)
  256. {
  257. auto currentTile = pathNodes.find(current.coord);
  258. if(currentTile == pathNodes.end())
  259. break;
  260. auto currentNode = currentTile->second[current.nodeType];
  261. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  262. vstd::amax(danger, currentNode.linkDanger);
  263. vstd::amax(cost, currentNode.cost);
  264. tilesToPass.push_back(current);
  265. if(currentNode.cost < 2.0f)
  266. break;
  267. current = currentNode.previous;
  268. }
  269. if(tilesToPass.empty())
  270. continue;
  271. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  272. for(auto & entryPath : entryPaths)
  273. {
  274. if(entryPath.targetHero != hero)
  275. continue;
  276. auto & path = paths.emplace_back();
  277. path.targetHero = entryPath.targetHero;
  278. path.heroArmy = entryPath.heroArmy;
  279. path.exchangeCount = entryPath.exchangeCount;
  280. path.armyLoss = entryPath.armyLoss + ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  281. path.targetObjectDanger = ai->dangerEvaluator->evaluateDanger(tile, path.targetHero, !allowBattle);
  282. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  283. AIPathNodeInfo n;
  284. n.targetHero = hero;
  285. n.parentIndex = -1;
  286. // final node
  287. n.coord = tile;
  288. n.cost = targetNode.cost;
  289. n.turns = static_cast<ui8>(targetNode.cost);
  290. n.danger = danger;
  291. n.parentIndex = path.nodes.size();
  292. path.nodes.push_back(n);
  293. for(auto entryNode = entryPath.nodes.rbegin(); entryNode != entryPath.nodes.rend(); entryNode++)
  294. {
  295. auto blocker = ai->objectClusterizer->getBlocker(*entryNode);
  296. if(blocker)
  297. {
  298. // blocker node
  299. path.nodes.push_back(*entryNode);
  300. path.nodes.back().parentIndex = path.nodes.size() - 1;
  301. break;
  302. }
  303. }
  304. if(path.nodes.size() > 1)
  305. continue;
  306. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  307. {
  308. auto & node = getNode(*graphTile);
  309. n.coord = graphTile->coord;
  310. n.cost = node.cost;
  311. n.turns = static_cast<ui8>(node.cost);
  312. n.danger = danger;
  313. n.specialAction = node.specialAction;
  314. n.parentIndex = path.nodes.size();
  315. if(n.specialAction)
  316. {
  317. n.actionIsBlocked = !n.specialAction->canAct(ai, n);
  318. }
  319. auto blocker = ai->objectClusterizer->getBlocker(n);
  320. if(!blocker)
  321. continue;
  322. // blocker node
  323. path.nodes.push_back(n);
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. }