GraphPaths.cpp 10 KB

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