AINodeStorage.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. * AINodeStorage.h, 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. #pragma once
  11. #define NKAI_PATHFINDER_TRACE_LEVEL 0
  12. constexpr int NKAI_GRAPH_TRACE_LEVEL = 0;
  13. #define NKAI_TRACE_LEVEL 0
  14. #include "../../../lib/pathfinder/CGPathNode.h"
  15. #include "../../../lib/pathfinder/INodeStorage.h"
  16. #include "../../../lib/mapObjects/CGHeroInstance.h"
  17. #include "../AIUtility.h"
  18. #include "../Engine/FuzzyHelper.h"
  19. #include "../Goals/AbstractGoal.h"
  20. #include "Actions/SpecialAction.h"
  21. #include "Actors.h"
  22. #include <boost/container/small_vector.hpp>
  23. namespace NKAI
  24. {
  25. namespace AIPathfinding
  26. {
  27. const int BUCKET_COUNT = 3;
  28. const int BUCKET_SIZE = 7;
  29. const int NUM_CHAINS = BUCKET_COUNT * BUCKET_SIZE;
  30. const int CHAIN_MAX_DEPTH = 4;
  31. }
  32. enum DayFlags : ui8
  33. {
  34. NONE = 0,
  35. FLY_CAST = 1,
  36. WATER_WALK_CAST = 2
  37. };
  38. struct AIPathNode : public CGPathNode
  39. {
  40. uint64_t danger;
  41. uint64_t armyLoss;
  42. int16_t manaCost;
  43. DayFlags dayFlags;
  44. const AIPathNode * chainOther;
  45. std::shared_ptr<const SpecialAction> specialAction;
  46. const ChainActor * actor;
  47. uint64_t version;
  48. void addSpecialAction(std::shared_ptr<const SpecialAction> action);
  49. inline void reset(EPathfindingLayer layer, EPathAccessibility accessibility)
  50. {
  51. CGPathNode::reset();
  52. actor = nullptr;
  53. danger = 0;
  54. manaCost = 0;
  55. specialAction.reset();
  56. armyLoss = 0;
  57. chainOther = nullptr;
  58. dayFlags = DayFlags::NONE;
  59. this->layer = layer;
  60. accessible = accessibility;
  61. }
  62. };
  63. struct AIPathNodeInfo
  64. {
  65. float cost;
  66. uint8_t turns;
  67. int3 coord;
  68. EPathfindingLayer layer;
  69. uint64_t danger;
  70. const CGHeroInstance * targetHero;
  71. int parentIndex;
  72. uint64_t chainMask;
  73. std::shared_ptr<const SpecialAction> specialAction;
  74. bool actionIsBlocked;
  75. };
  76. struct AIPath
  77. {
  78. using NodesVector = boost::container::small_vector<AIPathNodeInfo, 16>;
  79. NodesVector nodes;
  80. uint64_t targetObjectDanger;
  81. uint64_t armyLoss;
  82. uint64_t targetObjectArmyLoss;
  83. const CGHeroInstance * targetHero;
  84. const CCreatureSet * heroArmy;
  85. uint64_t chainMask;
  86. uint8_t exchangeCount;
  87. AIPath();
  88. /// Gets danger of path excluding danger of visiting the target object like creature bank
  89. uint64_t getPathDanger() const;
  90. /// Gets danger of path including danger of visiting the target object like creature bank
  91. uint64_t getTotalDanger() const;
  92. /// Gets danger of path including danger of visiting the target object like creature bank
  93. uint64_t getTotalArmyLoss() const;
  94. int3 firstTileToGet() const;
  95. int3 targetTile() const;
  96. const AIPathNodeInfo & firstNode() const;
  97. const AIPathNodeInfo & targetNode() const;
  98. float movementCost() const;
  99. uint8_t turn() const;
  100. uint64_t getHeroStrength() const;
  101. std::string toString() const;
  102. std::shared_ptr<const SpecialAction> getFirstBlockedAction() const;
  103. bool containsHero(const CGHeroInstance * hero) const;
  104. };
  105. struct ExchangeCandidate : public AIPathNode
  106. {
  107. AIPathNode * carrierParent;
  108. AIPathNode * otherParent;
  109. };
  110. enum EHeroChainPass
  111. {
  112. INITIAL, // single heroes unlimited distance
  113. CHAIN, // chains with limited distance
  114. FINAL // same as SINGLE but for heroes from CHAIN pass
  115. };
  116. class AISharedStorage
  117. {
  118. // 1-3 - position on map[z][x][y]
  119. // 4 - chain + layer (normal, battle, spellcast and combinations, water, air)
  120. static std::shared_ptr<boost::multi_array<AIPathNode, 4>> shared;
  121. std::shared_ptr<boost::multi_array<AIPathNode, 4>> nodes;
  122. public:
  123. static boost::mutex locker;
  124. static uint64_t version;
  125. AISharedStorage(int3 mapSize);
  126. ~AISharedStorage();
  127. STRONG_INLINE
  128. boost::detail::multi_array::sub_array<AIPathNode, 1> get(int3 tile) const
  129. {
  130. return (*nodes)[tile.z][tile.x][tile.y];
  131. }
  132. };
  133. class AINodeStorage : public INodeStorage
  134. {
  135. private:
  136. int3 sizes;
  137. std::unique_ptr<boost::multi_array<EPathAccessibility, 4>> accessibility;
  138. const CPlayerSpecificInfoCallback * cb;
  139. const Nullkiller * ai;
  140. std::unique_ptr<FuzzyHelper> dangerEvaluator;
  141. AISharedStorage nodes;
  142. std::vector<std::shared_ptr<ChainActor>> actors;
  143. std::vector<CGPathNode *> heroChain;
  144. EHeroChainPass heroChainPass; // true if we need to calculate hero chain
  145. uint64_t chainMask;
  146. int heroChainTurn;
  147. int heroChainMaxTurns;
  148. PlayerColor playerID;
  149. uint8_t turnDistanceLimit[2];
  150. public:
  151. /// more than 1 chain layer for each hero allows us to have more than 1 path to each tile so we can chose more optimal one.
  152. AINodeStorage(const Nullkiller * ai, const int3 & sizes);
  153. ~AINodeStorage();
  154. void initialize(const PathfinderOptions & options, const CGameState * gs) override;
  155. bool increaseHeroChainTurnLimit();
  156. bool selectFirstActor();
  157. bool selectNextActor();
  158. std::vector<CGPathNode *> getInitialNodes() override;
  159. virtual void calculateNeighbours(
  160. std::vector<CGPathNode *> & result,
  161. const PathNodeInfo & source,
  162. EPathfindingLayer layer,
  163. const PathfinderConfig * pathfinderConfig,
  164. const CPathfinderHelper * pathfinderHelper) override;
  165. virtual std::vector<CGPathNode *> calculateTeleportations(
  166. const PathNodeInfo & source,
  167. const PathfinderConfig * pathfinderConfig,
  168. const CPathfinderHelper * pathfinderHelper) override;
  169. void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) override;
  170. void commit(
  171. AIPathNode * destination,
  172. const AIPathNode * source,
  173. EPathNodeAction action,
  174. int turn,
  175. int movementLeft,
  176. float cost,
  177. bool saveToCommitted = true) const;
  178. inline const AIPathNode * getAINode(const CGPathNode * node) const
  179. {
  180. return static_cast<const AIPathNode *>(node);
  181. }
  182. inline void updateAINode(CGPathNode * node, std::function<void (AIPathNode *)> updater)
  183. {
  184. auto * aiNode = static_cast<AIPathNode *>(node);
  185. updater(aiNode);
  186. }
  187. inline const CGHeroInstance * getHero(const CGPathNode * node) const
  188. {
  189. const auto * aiNode = getAINode(node);
  190. return aiNode->actor->hero;
  191. }
  192. inline bool blocked(const int3 & tile, EPathfindingLayer layer) const
  193. {
  194. EPathAccessibility accessible = getAccessibility(tile, layer);
  195. return accessible == EPathAccessibility::NOT_SET
  196. || accessible == EPathAccessibility::BLOCKED;
  197. }
  198. bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  199. bool hasBetterChain(const CGPathNode * source, const AIPathNode & candidateNode) const;
  200. template<class NodeRange>
  201. bool hasBetterChain(
  202. const CGPathNode * source,
  203. const AIPathNode & destinationNode,
  204. const NodeRange & chains) const;
  205. bool isOtherChainBetter(
  206. const CGPathNode * source,
  207. const AIPathNode & candidateNode,
  208. const AIPathNode & other) const;
  209. bool isMovementInefficient(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  210. {
  211. return hasBetterChain(source, destination);
  212. }
  213. bool isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  214. std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor);
  215. void calculateChainInfo(std::vector<AIPath> & result, const int3 & pos, bool isOnLand) const;
  216. bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const;
  217. void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes);
  218. void setScoutTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::SCOUT] = distanceLimit; }
  219. void setMainTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::MAIN] = distanceLimit; }
  220. void setTownsAndDwellings(
  221. const std::vector<const CGTownInstance *> & towns,
  222. const std::set<const CGObjectInstance *> & visitableObjs);
  223. const std::set<const CGHeroInstance *> getAllHeroes() const;
  224. void clear();
  225. bool calculateHeroChain();
  226. bool calculateHeroChainFinal();
  227. inline uint64_t evaluateDanger(const int3 & tile, const CGHeroInstance * hero, bool checkGuards) const
  228. {
  229. return dangerEvaluator->evaluateDanger(tile, hero, checkGuards);
  230. }
  231. uint64_t evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const;
  232. inline EPathAccessibility getAccessibility(const int3 & tile, EPathfindingLayer layer) const
  233. {
  234. return (*this->accessibility)[tile.z][tile.x][tile.y][layer];
  235. }
  236. inline void resetTile(const int3 & tile, EPathfindingLayer layer, EPathAccessibility tileAccessibility)
  237. {
  238. (*this->accessibility)[tile.z][tile.x][tile.y][layer] = tileAccessibility;
  239. }
  240. inline int getBucket(const ChainActor * actor) const
  241. {
  242. return ((uintptr_t)actor * 395) % AIPathfinding::BUCKET_COUNT;
  243. }
  244. void calculateTownPortalTeleportations(std::vector<CGPathNode *> & neighbours);
  245. void fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const;
  246. template<typename Fn>
  247. void iterateValidNodes(const int3 & pos, EPathfindingLayer layer, Fn fn)
  248. {
  249. if(blocked(pos, layer))
  250. return;
  251. auto chains = nodes.get(pos);
  252. for(AIPathNode & node : chains)
  253. {
  254. if(node.version != AISharedStorage::version || node.layer != layer)
  255. continue;
  256. fn(node);
  257. }
  258. }
  259. template<typename Fn>
  260. bool iterateValidNodesUntil(const int3 & pos, EPathfindingLayer layer, Fn predicate) const
  261. {
  262. if(blocked(pos, layer))
  263. return false;
  264. auto chains = nodes.get(pos);
  265. for(AIPathNode & node : chains)
  266. {
  267. if(node.version != AISharedStorage::version || node.layer != layer)
  268. continue;
  269. if(predicate(node))
  270. return true;
  271. }
  272. return false;
  273. }
  274. private:
  275. template<class TVector>
  276. void calculateTownPortal(
  277. const ChainActor * actor,
  278. const std::map<const CGHeroInstance *, int> & maskMap,
  279. const std::vector<CGPathNode *> & initialNodes,
  280. TVector & output);
  281. };
  282. }