AINodeStorage.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. std::shared_ptr<const SpecialAction> specialAction;
  41. const AIPathNode * chainOther;
  42. const ChainActor * actor;
  43. uint64_t danger;
  44. uint64_t armyLoss;
  45. uint32_t version;
  46. int16_t manaCost;
  47. DayFlags dayFlags;
  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 uint32_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. AISharedStorage nodes;
  141. std::vector<std::shared_ptr<ChainActor>> actors;
  142. std::vector<CGPathNode *> heroChain;
  143. EHeroChainPass heroChainPass; // true if we need to calculate hero chain
  144. uint64_t chainMask;
  145. int heroChainTurn;
  146. int heroChainMaxTurns;
  147. PlayerColor playerID;
  148. uint8_t turnDistanceLimit[2];
  149. public:
  150. /// 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.
  151. AINodeStorage(const Nullkiller * ai, const int3 & sizes);
  152. ~AINodeStorage();
  153. void initialize(const PathfinderOptions & options, const CGameState * gs) override;
  154. bool increaseHeroChainTurnLimit();
  155. bool selectFirstActor();
  156. bool selectNextActor();
  157. std::vector<CGPathNode *> getInitialNodes() override;
  158. virtual void calculateNeighbours(
  159. std::vector<CGPathNode *> & result,
  160. const PathNodeInfo & source,
  161. EPathfindingLayer layer,
  162. const PathfinderConfig * pathfinderConfig,
  163. const CPathfinderHelper * pathfinderHelper) override;
  164. virtual std::vector<CGPathNode *> calculateTeleportations(
  165. const PathNodeInfo & source,
  166. const PathfinderConfig * pathfinderConfig,
  167. const CPathfinderHelper * pathfinderHelper) override;
  168. void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) override;
  169. void commit(
  170. AIPathNode * destination,
  171. const AIPathNode * source,
  172. EPathNodeAction action,
  173. int turn,
  174. int movementLeft,
  175. float cost,
  176. bool saveToCommitted = true) const;
  177. inline const AIPathNode * getAINode(const CGPathNode * node) const
  178. {
  179. return static_cast<const AIPathNode *>(node);
  180. }
  181. inline void updateAINode(CGPathNode * node, std::function<void (AIPathNode *)> updater)
  182. {
  183. auto * aiNode = static_cast<AIPathNode *>(node);
  184. updater(aiNode);
  185. }
  186. inline const CGHeroInstance * getHero(const CGPathNode * node) const
  187. {
  188. const auto * aiNode = getAINode(node);
  189. return aiNode->actor->hero;
  190. }
  191. inline bool blocked(const int3 & tile, EPathfindingLayer layer) const
  192. {
  193. EPathAccessibility accessible = getAccessibility(tile, layer);
  194. return accessible == EPathAccessibility::NOT_SET
  195. || accessible == EPathAccessibility::BLOCKED;
  196. }
  197. bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  198. bool hasBetterChain(const CGPathNode * source, const AIPathNode & candidateNode) const;
  199. template<class NodeRange>
  200. bool hasBetterChain(
  201. const CGPathNode * source,
  202. const AIPathNode & destinationNode,
  203. const NodeRange & chains) const;
  204. bool isOtherChainBetter(
  205. const CGPathNode * source,
  206. const AIPathNode & candidateNode,
  207. const AIPathNode & other) const;
  208. bool isMovementInefficient(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  209. {
  210. return hasBetterChain(source, destination);
  211. }
  212. bool isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  213. std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor);
  214. void calculateChainInfo(std::vector<AIPath> & result, const int3 & pos, bool isOnLand) const;
  215. bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const;
  216. void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes);
  217. void setScoutTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::SCOUT] = distanceLimit; }
  218. void setMainTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::MAIN] = distanceLimit; }
  219. void setTownsAndDwellings(
  220. const std::vector<const CGTownInstance *> & towns,
  221. const std::set<const CGObjectInstance *> & visitableObjs);
  222. const std::set<const CGHeroInstance *> getAllHeroes() const;
  223. void clear();
  224. bool calculateHeroChain();
  225. bool calculateHeroChainFinal();
  226. uint64_t evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const;
  227. inline EPathAccessibility getAccessibility(const int3 & tile, EPathfindingLayer layer) const
  228. {
  229. return (*this->accessibility)[tile.z][tile.x][tile.y][layer];
  230. }
  231. inline void resetTile(const int3 & tile, EPathfindingLayer layer, EPathAccessibility tileAccessibility)
  232. {
  233. (*this->accessibility)[tile.z][tile.x][tile.y][layer] = tileAccessibility;
  234. }
  235. inline int getBucket(const ChainActor * actor) const
  236. {
  237. return ((uintptr_t)actor * 395) % AIPathfinding::BUCKET_COUNT;
  238. }
  239. void calculateTownPortalTeleportations(std::vector<CGPathNode *> & neighbours);
  240. void fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const;
  241. template<typename Fn>
  242. void iterateValidNodes(const int3 & pos, EPathfindingLayer layer, Fn fn)
  243. {
  244. if(blocked(pos, layer))
  245. return;
  246. auto chains = nodes.get(pos);
  247. for(AIPathNode & node : chains)
  248. {
  249. if(node.version != AISharedStorage::version || node.layer != layer)
  250. continue;
  251. fn(node);
  252. }
  253. }
  254. template<typename Fn>
  255. bool iterateValidNodesUntil(const int3 & pos, EPathfindingLayer layer, Fn predicate) const
  256. {
  257. if(blocked(pos, layer))
  258. return false;
  259. auto chains = nodes.get(pos);
  260. for(AIPathNode & node : chains)
  261. {
  262. if(node.version != AISharedStorage::version || node.layer != layer)
  263. continue;
  264. if(predicate(node))
  265. return true;
  266. }
  267. return false;
  268. }
  269. private:
  270. template<class TVector>
  271. void calculateTownPortal(
  272. const ChainActor * actor,
  273. const std::map<const CGHeroInstance *, int> & maskMap,
  274. const std::vector<CGPathNode *> & initialNodes,
  275. TVector & output);
  276. };
  277. }