AINodeStorage.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. #define NKAI_TRACE_LEVEL 0
  13. #include "../../../lib/pathfinder/CGPathNode.h"
  14. #include "../../../lib/pathfinder/INodeStorage.h"
  15. #include "../../../lib/mapObjects/CGHeroInstance.h"
  16. #include "../AIUtility.h"
  17. #include "../Engine/FuzzyHelper.h"
  18. #include "../Goals/AbstractGoal.h"
  19. #include "Actions/SpecialAction.h"
  20. #include "Actors.h"
  21. namespace NKAI
  22. {
  23. const int SCOUT_TURN_DISTANCE_LIMIT = 5;
  24. const int MAIN_TURN_DISTANCE_LIMIT = 10;
  25. namespace AIPathfinding
  26. {
  27. #ifdef ENVIRONMENT64
  28. const int BUCKET_COUNT = 7;
  29. #else
  30. const int BUCKET_COUNT = 5;
  31. #endif // ENVIRONMENT64
  32. const int BUCKET_SIZE = 5;
  33. const int NUM_CHAINS = BUCKET_COUNT * BUCKET_SIZE;
  34. const int THREAD_COUNT = 8;
  35. const int CHAIN_MAX_DEPTH = 4;
  36. }
  37. struct AIPathNode : public CGPathNode
  38. {
  39. uint64_t danger;
  40. uint64_t armyLoss;
  41. int32_t manaCost;
  42. const AIPathNode * chainOther;
  43. std::shared_ptr<const SpecialAction> specialAction;
  44. const ChainActor * actor;
  45. STRONG_INLINE
  46. bool blocked() const
  47. {
  48. return accessible == EPathAccessibility::NOT_SET
  49. || accessible == EPathAccessibility::BLOCKED;
  50. }
  51. void addSpecialAction(std::shared_ptr<const SpecialAction> action);
  52. };
  53. struct AIPathNodeInfo
  54. {
  55. float cost;
  56. uint8_t turns;
  57. int3 coord;
  58. EPathfindingLayer layer;
  59. uint64_t danger;
  60. const CGHeroInstance * targetHero;
  61. int parentIndex;
  62. uint64_t chainMask;
  63. std::shared_ptr<const SpecialAction> specialAction;
  64. bool actionIsBlocked;
  65. };
  66. struct AIPath
  67. {
  68. std::vector<AIPathNodeInfo> nodes;
  69. uint64_t targetObjectDanger;
  70. uint64_t armyLoss;
  71. uint64_t targetObjectArmyLoss;
  72. const CGHeroInstance * targetHero;
  73. const CCreatureSet * heroArmy;
  74. uint64_t chainMask;
  75. uint8_t exchangeCount;
  76. AIPath();
  77. /// Gets danger of path excluding danger of visiting the target object like creature bank
  78. uint64_t getPathDanger() const;
  79. /// Gets danger of path including danger of visiting the target object like creature bank
  80. uint64_t getTotalDanger() const;
  81. /// Gets danger of path including danger of visiting the target object like creature bank
  82. uint64_t getTotalArmyLoss() const;
  83. int3 firstTileToGet() const;
  84. int3 targetTile() const;
  85. const AIPathNodeInfo & firstNode() const;
  86. const AIPathNodeInfo & targetNode() const;
  87. float movementCost() const;
  88. uint8_t turn() const;
  89. uint64_t getHeroStrength() const;
  90. std::string toString() const;
  91. std::shared_ptr<const SpecialAction> getFirstBlockedAction() const;
  92. bool containsHero(const CGHeroInstance * hero) const;
  93. };
  94. struct ExchangeCandidate : public AIPathNode
  95. {
  96. AIPathNode * carrierParent;
  97. AIPathNode * otherParent;
  98. };
  99. enum EHeroChainPass
  100. {
  101. INITIAL, // single heroes unlimited distance
  102. CHAIN, // chains with limited distance
  103. FINAL // same as SINGLE but for heroes from CHAIN pass
  104. };
  105. class AISharedStorage
  106. {
  107. // 1 - layer (air, water, land)
  108. // 2-4 - position on map[z][x][y]
  109. // 5 - chain (normal, battle, spellcast and combinations)
  110. static std::shared_ptr<boost::multi_array<AIPathNode, 5>> shared;
  111. std::shared_ptr<boost::multi_array<AIPathNode, 5>> nodes;
  112. public:
  113. static boost::mutex locker;
  114. AISharedStorage(int3 mapSize);
  115. ~AISharedStorage();
  116. STRONG_INLINE
  117. boost::detail::multi_array::sub_array<AIPathNode, 1> get(int3 tile, EPathfindingLayer layer) const
  118. {
  119. return (*nodes)[layer][tile.z][tile.x][tile.y];
  120. }
  121. };
  122. class AINodeStorage : public INodeStorage
  123. {
  124. private:
  125. int3 sizes;
  126. const CPlayerSpecificInfoCallback * cb;
  127. const Nullkiller * ai;
  128. std::unique_ptr<FuzzyHelper> dangerEvaluator;
  129. AISharedStorage nodes;
  130. std::vector<std::shared_ptr<ChainActor>> actors;
  131. std::vector<CGPathNode *> heroChain;
  132. EHeroChainPass heroChainPass; // true if we need to calculate hero chain
  133. uint64_t chainMask;
  134. int heroChainTurn;
  135. int heroChainMaxTurns;
  136. PlayerColor playerID;
  137. uint8_t turnDistanceLimit[2];
  138. public:
  139. /// 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.
  140. AINodeStorage(const Nullkiller * ai, const int3 & sizes);
  141. ~AINodeStorage();
  142. void initialize(const PathfinderOptions & options, const CGameState * gs) override;
  143. bool increaseHeroChainTurnLimit();
  144. bool selectFirstActor();
  145. bool selectNextActor();
  146. virtual std::vector<CGPathNode *> getInitialNodes() override;
  147. virtual std::vector<CGPathNode *> calculateNeighbours(
  148. const PathNodeInfo & source,
  149. const PathfinderConfig * pathfinderConfig,
  150. const CPathfinderHelper * pathfinderHelper) override;
  151. virtual std::vector<CGPathNode *> calculateTeleportations(
  152. const PathNodeInfo & source,
  153. const PathfinderConfig * pathfinderConfig,
  154. const CPathfinderHelper * pathfinderHelper) override;
  155. virtual void commit(CDestinationNodeInfo & destination, const PathNodeInfo & source) override;
  156. void commit(
  157. AIPathNode * destination,
  158. const AIPathNode * source,
  159. EPathNodeAction action,
  160. int turn,
  161. int movementLeft,
  162. float cost) const;
  163. inline const AIPathNode * getAINode(const CGPathNode * node) const
  164. {
  165. return static_cast<const AIPathNode *>(node);
  166. }
  167. inline void updateAINode(CGPathNode * node, std::function<void (AIPathNode *)> updater)
  168. {
  169. auto * aiNode = static_cast<AIPathNode *>(node);
  170. updater(aiNode);
  171. }
  172. inline const CGHeroInstance * getHero(const CGPathNode * node) const
  173. {
  174. const auto * aiNode = getAINode(node);
  175. return aiNode->actor->hero;
  176. }
  177. bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  178. bool isMovementIneficient(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  179. {
  180. return hasBetterChain(source, destination);
  181. }
  182. bool isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const;
  183. template<class NodeRange>
  184. bool hasBetterChain(
  185. const CGPathNode * source,
  186. const AIPathNode * destinationNode,
  187. const NodeRange & chains) const;
  188. std::optional<AIPathNode *> getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor);
  189. std::vector<AIPath> getChainInfo(const int3 & pos, bool isOnLand) const;
  190. bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const;
  191. void setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes);
  192. void setScoutTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::SCOUT] = distanceLimit; }
  193. void setMainTurnDistanceLimit(uint8_t distanceLimit) { turnDistanceLimit[HeroRole::MAIN] = distanceLimit; }
  194. void setTownsAndDwellings(
  195. const std::vector<const CGTownInstance *> & towns,
  196. const std::set<const CGObjectInstance *> & visitableObjs);
  197. const std::set<const CGHeroInstance *> getAllHeroes() const;
  198. void clear();
  199. bool calculateHeroChain();
  200. bool calculateHeroChainFinal();
  201. inline uint64_t evaluateDanger(const int3 & tile, const CGHeroInstance * hero, bool checkGuards) const
  202. {
  203. return dangerEvaluator->evaluateDanger(tile, hero, checkGuards);
  204. }
  205. inline uint64_t evaluateArmyLoss(const CGHeroInstance * hero, uint64_t armyValue, uint64_t danger) const
  206. {
  207. double ratio = (double)danger / (armyValue * hero->getFightingStrength());
  208. return (uint64_t)(armyValue * ratio * ratio);
  209. }
  210. STRONG_INLINE
  211. void resetTile(const int3 & tile, EPathfindingLayer layer, EPathAccessibility accessibility);
  212. STRONG_INLINE int getBucket(const ChainActor * actor) const
  213. {
  214. return ((uintptr_t)actor * 395) % AIPathfinding::BUCKET_COUNT;
  215. }
  216. void calculateTownPortalTeleportations(std::vector<CGPathNode *> & neighbours);
  217. void fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const;
  218. private:
  219. template<class TVector>
  220. void calculateTownPortal(
  221. const ChainActor * actor,
  222. const std::map<const CGHeroInstance *, int> & maskMap,
  223. const std::vector<CGPathNode *> & initialNodes,
  224. TVector & output);
  225. };
  226. }