CPathfinder.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /*
  2. * CPathfinder.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. #include "VCMI_Lib.h"
  12. #include "IGameCallback.h"
  13. #include "HeroBonus.h"
  14. #include "int3.h"
  15. #include <boost/heap/priority_queue.hpp>
  16. class CGHeroInstance;
  17. class CGObjectInstance;
  18. struct TerrainTile;
  19. class CPathfinderHelper;
  20. class CMap;
  21. class CGWhirlpool;
  22. struct DLL_LINKAGE CGPathNode
  23. {
  24. typedef EPathfindingLayer ELayer;
  25. enum ENodeAction : ui8
  26. {
  27. UNKNOWN = 0,
  28. EMBARK = 1,
  29. DISEMBARK,
  30. NORMAL,
  31. BATTLE,
  32. VISIT,
  33. BLOCKING_VISIT,
  34. TELEPORT_NORMAL,
  35. TELEPORT_BLOCKING_VISIT,
  36. TELEPORT_BATTLE
  37. };
  38. enum EAccessibility : ui8
  39. {
  40. NOT_SET = 0,
  41. ACCESSIBLE = 1, //tile can be entered and passed
  42. VISITABLE, //tile can be entered as the last tile in path
  43. BLOCKVIS, //visitable from neighbouring tile but not passable
  44. FLYABLE, //can only be accessed in air layer
  45. BLOCKED //tile can't be entered nor visited
  46. };
  47. CGPathNode * theNodeBefore;
  48. int3 coord; //coordinates
  49. ui32 moveRemains; //remaining tiles after hero reaches the tile
  50. ui8 turns; //how many turns we have to wait before reachng the tile - 0 means current turn
  51. ELayer layer;
  52. EAccessibility accessible;
  53. ENodeAction action;
  54. bool locked;
  55. CGPathNode();
  56. void reset();
  57. void update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible);
  58. bool reachable() const;
  59. };
  60. struct DLL_LINKAGE CGPath
  61. {
  62. std::vector<CGPathNode> nodes; //just get node by node
  63. int3 startPos() const; // start point
  64. int3 endPos() const; //destination point
  65. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  66. };
  67. struct DLL_LINKAGE CPathsInfo
  68. {
  69. typedef EPathfindingLayer ELayer;
  70. mutable boost::mutex pathMx;
  71. const CGHeroInstance * hero;
  72. int3 hpos;
  73. int3 sizes;
  74. boost::multi_array<CGPathNode, 4> nodes; //[w][h][level][layer]
  75. CPathsInfo(const int3 & Sizes);
  76. ~CPathsInfo();
  77. const CGPathNode * getPathInfo(const int3 & tile) const;
  78. bool getPath(CGPath & out, const int3 & dst) const;
  79. int getDistance(const int3 & tile) const;
  80. const CGPathNode * getNode(const int3 & coord) const;
  81. CGPathNode * getNode(const int3 & coord, const ELayer layer);
  82. };
  83. struct DLL_LINKAGE CPathNodeInfo
  84. {
  85. CGPathNode * node;
  86. const CGObjectInstance * nodeObject;
  87. const TerrainTile * tile;
  88. int3 coord;
  89. bool guarded;
  90. PlayerRelations::PlayerRelations objectRelations;
  91. CPathNodeInfo();
  92. virtual void setNode(CGameState * gs, CGPathNode * n, bool excludeTopObject = false);
  93. bool isNodeObjectVisitable() const;
  94. };
  95. struct DLL_LINKAGE CDestinationNodeInfo : public CPathNodeInfo
  96. {
  97. CGPathNode::ENodeAction action;
  98. int turn;
  99. int movementLeft;
  100. bool blocked;
  101. CDestinationNodeInfo();
  102. virtual void setNode(CGameState * gs, CGPathNode * n, bool excludeTopObject = false) override;
  103. virtual bool isBetterWay();
  104. };
  105. class CNodeStorage
  106. {
  107. public:
  108. virtual CGPathNode * getNode(const int3 & coord, const EPathfindingLayer layer) = 0;
  109. virtual CGPathNode * getInitialNode() = 0;
  110. virtual boost::mutex & getMutex() = 0;
  111. };
  112. class CPathfinderHelper;
  113. class CPathfinder;
  114. class CPathfinderConfig;
  115. class IPathfindingRule
  116. {
  117. public:
  118. virtual void process(
  119. CPathNodeInfo & source,
  120. CDestinationNodeInfo & destination,
  121. CPathfinderConfig * pathfinderConfig,
  122. CPathfinderHelper * pathfinderHelper) = 0;
  123. };
  124. class CMovementCostRule : public IPathfindingRule
  125. {
  126. public:
  127. virtual void process(
  128. CPathNodeInfo & source,
  129. CDestinationNodeInfo & destination,
  130. CPathfinderConfig * pathfinderConfig,
  131. CPathfinderHelper * pathfinderHelper) override;
  132. };
  133. class CPathfinderBlockingRule : public IPathfindingRule
  134. {
  135. public:
  136. virtual void process(
  137. CPathNodeInfo & source,
  138. CDestinationNodeInfo & destination,
  139. CPathfinderConfig * pathfinderConfig,
  140. CPathfinderHelper * pathfinderHelper) override
  141. {
  142. auto blockingReason = getBlockingReason(source, destination, pathfinderConfig, pathfinderHelper);
  143. destination.blocked = blockingReason != BlockingReason::NONE;
  144. }
  145. protected:
  146. enum class BlockingReason
  147. {
  148. NONE = 0,
  149. SOURCE_GUARDED = 1,
  150. DESTINATION_GUARDED = 2,
  151. SOURCE_BLOCKED = 3,
  152. DESTINATION_BLOCKED = 4,
  153. DESTINATION_BLOCKVIS = 5,
  154. DESTINATION_VISIT = 6
  155. };
  156. virtual BlockingReason getBlockingReason(
  157. CPathNodeInfo & source,
  158. CDestinationNodeInfo & destination,
  159. CPathfinderConfig * pathfinderConfig,
  160. CPathfinderHelper * pathfinderHelper) = 0;
  161. };
  162. class CMovementAfterDestinationRule : public CPathfinderBlockingRule
  163. {
  164. public:
  165. virtual void process(
  166. CPathNodeInfo & source,
  167. CDestinationNodeInfo & destination,
  168. CPathfinderConfig * pathfinderConfig,
  169. CPathfinderHelper * pathfinderHelper) override;
  170. protected:
  171. virtual BlockingReason getBlockingReason(
  172. CPathNodeInfo & source,
  173. CDestinationNodeInfo & destination,
  174. CPathfinderConfig * pathfinderConfig,
  175. CPathfinderHelper * pathfinderHelper) override;
  176. };
  177. class CMovementToDestinationRule : public CPathfinderBlockingRule
  178. {
  179. protected:
  180. virtual BlockingReason getBlockingReason(
  181. CPathNodeInfo & source,
  182. CDestinationNodeInfo & destination,
  183. CPathfinderConfig * pathfinderConfig,
  184. CPathfinderHelper * pathfinderHelper) override;
  185. };
  186. class CNeighbourFinder
  187. {
  188. public:
  189. CNeighbourFinder();
  190. virtual std::vector<CGPathNode *> calculateNeighbours(
  191. CPathNodeInfo & source,
  192. CPathfinderConfig * pathfinderConfig,
  193. CPathfinderHelper * pathfinderHelper) const;
  194. virtual std::vector<CGPathNode *> calculateTeleportations(
  195. CPathNodeInfo & source,
  196. CPathfinderConfig * pathfinderConfig,
  197. CPathfinderHelper * pathfinderHelper) const;
  198. protected:
  199. std::vector<int3> getNeighbourTiles(
  200. CPathNodeInfo & source,
  201. CPathfinderConfig * pathfinderConfig,
  202. CPathfinderHelper * pathfinderHelper) const;
  203. std::vector<int3> getTeleportExits(CPathNodeInfo & source,
  204. CPathfinderConfig * pathfinderConfig,
  205. CPathfinderHelper * pathfinderHelper) const;
  206. };
  207. struct DLL_LINKAGE PathfinderOptions
  208. {
  209. bool useFlying;
  210. bool useWaterWalking;
  211. bool useEmbarkAndDisembark;
  212. bool useTeleportTwoWay; // Two-way monoliths and Subterranean Gate
  213. bool useTeleportOneWay; // One-way monoliths with one known exit only
  214. bool useTeleportOneWayRandom; // One-way monoliths with more than one known exit
  215. bool useTeleportWhirlpool; // Force enabled if hero protected or unaffected (have one stack of one creature)
  216. /// TODO: Find out with client and server code, merge with normal teleporters.
  217. /// Likely proper implementation would require some refactoring of CGTeleport.
  218. /// So for now this is unfinished and disabled by default.
  219. bool useCastleGate;
  220. /// If true transition into air layer only possible from initial node.
  221. /// This is drastically decrease path calculation complexity (and time).
  222. /// Downside is less MP effective paths calculation.
  223. ///
  224. /// TODO: If this option end up useful for slow devices it's can be improved:
  225. /// - Allow transition into air layer not only from initial position, but also from teleporters.
  226. /// Movement into air can be also allowed when hero disembarked.
  227. /// - Other idea is to allow transition into air within certain radius of N tiles around hero.
  228. /// Patrol support need similar functionality so it's won't be ton of useless code.
  229. /// Such limitation could be useful as it's can be scaled depend on device performance.
  230. bool lightweightFlyingMode;
  231. /// This option enable one turn limitation for flying and water walking.
  232. /// So if we're out of MP while cp is blocked or water tile we won't add dest tile to queue.
  233. ///
  234. /// Following imitation is default H3 mechanics, but someone may want to disable it in mods.
  235. /// After all this limit should benefit performance on maps with tons of water or blocked tiles.
  236. ///
  237. /// TODO:
  238. /// - Behavior when option is disabled not implemented and will lead to crashes.
  239. bool oneTurnSpecialLayersLimit;
  240. /// VCMI have different movement rules to solve flaws original engine has.
  241. /// If this option enabled you'll able to do following things in fly:
  242. /// - Move from blocked tiles to visitable one
  243. /// - Move from guarded tiles to blockvis tiles without being attacked
  244. /// - Move from guarded tiles to guarded visitable tiles with being attacked after
  245. /// TODO:
  246. /// - Option should also allow same tile land <-> air layer transitions.
  247. /// Current implementation only allow go into (from) air layer only to neighbour tiles.
  248. /// I find it's reasonable limitation, but it's will make some movements more expensive than in H3.
  249. bool originalMovementRules;
  250. PathfinderOptions();
  251. };
  252. class CPathfinderConfig
  253. {
  254. public:
  255. std::shared_ptr<CNodeStorage> nodeStorage;
  256. std::shared_ptr<CNeighbourFinder> neighbourFinder;
  257. std::vector<std::shared_ptr<IPathfindingRule>> rules;
  258. PathfinderOptions options;
  259. CPathfinderConfig(
  260. std::shared_ptr<CNodeStorage> nodeStorage,
  261. std::shared_ptr<CNeighbourFinder> neighbourFinder,
  262. std::vector<std::shared_ptr<IPathfindingRule>> rules);
  263. };
  264. class CPathfinder : private CGameInfoCallback
  265. {
  266. public:
  267. friend class CPathfinderHelper;
  268. CPathfinder(CPathsInfo & _out, CGameState * _gs, const CGHeroInstance * _hero);
  269. CPathfinder(
  270. CGameState * _gs,
  271. const CGHeroInstance * _hero,
  272. std::shared_ptr<CPathfinderConfig> config);
  273. void calculatePaths(); //calculates possible paths for hero, uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists
  274. private:
  275. typedef EPathfindingLayer ELayer;
  276. const CGHeroInstance * hero;
  277. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  278. std::unique_ptr<CPathfinderHelper> hlp;
  279. std::shared_ptr<CPathfinderConfig> config;
  280. enum EPatrolState {
  281. PATROL_NONE = 0,
  282. PATROL_LOCKED = 1,
  283. PATROL_RADIUS
  284. } patrolState;
  285. std::unordered_set<int3, ShashInt3> patrolTiles;
  286. struct NodeComparer
  287. {
  288. bool operator()(const CGPathNode * lhs, const CGPathNode * rhs) const
  289. {
  290. if(rhs->turns > lhs->turns)
  291. return false;
  292. else if(rhs->turns == lhs->turns && rhs->moveRemains <= lhs->moveRemains)
  293. return false;
  294. return true;
  295. }
  296. };
  297. boost::heap::priority_queue<CGPathNode *, boost::heap::compare<NodeComparer> > pq;
  298. CPathNodeInfo source; //current (source) path node -> we took it from the queue
  299. CDestinationNodeInfo destination; //destination node -> it's a neighbour of source that we consider
  300. bool isHeroPatrolLocked() const;
  301. bool isPatrolMovementAllowed(const int3 & dst) const;
  302. bool isLayerTransitionPossible(const ELayer dstLayer) const;
  303. bool isLayerTransitionPossible() const;
  304. CGPathNode::ENodeAction getDestAction() const;
  305. CGPathNode::ENodeAction getTeleportDestAction() const;
  306. bool isSourceInitialPosition() const;
  307. bool isSourceGuarded() const;
  308. bool isDestinationGuarded() const;
  309. bool isDestinationGuardian() const;
  310. void initializePatrol();
  311. void initializeGraph();
  312. CGPathNode::EAccessibility evaluateAccessibility(const int3 & pos, const TerrainTile * tinfo, const ELayer layer) const;
  313. };
  314. struct DLL_LINKAGE TurnInfo
  315. {
  316. /// This is certainly not the best design ever and certainly can be improved
  317. /// Unfortunately for pathfinder that do hundreds of thousands calls onus system add too big overhead
  318. struct BonusCache {
  319. std::vector<bool> noTerrainPenalty;
  320. bool freeShipBoarding;
  321. bool flyingMovement;
  322. int flyingMovementVal;
  323. bool waterWalking;
  324. int waterWalkingVal;
  325. BonusCache(TBonusListPtr bonusList);
  326. };
  327. std::unique_ptr<BonusCache> bonusCache;
  328. const CGHeroInstance * hero;
  329. TBonusListPtr bonuses;
  330. mutable int maxMovePointsLand;
  331. mutable int maxMovePointsWater;
  332. int nativeTerrain;
  333. TurnInfo(const CGHeroInstance * Hero, const int Turn = 0);
  334. bool isLayerAvailable(const EPathfindingLayer layer) const;
  335. bool hasBonusOfType(const Bonus::BonusType type, const int subtype = -1) const;
  336. int valOfBonuses(const Bonus::BonusType type, const int subtype = -1) const;
  337. int getMaxMovePoints(const EPathfindingLayer layer) const;
  338. };
  339. class DLL_LINKAGE CPathfinderHelper : private CGameInfoCallback
  340. {
  341. public:
  342. int turn;
  343. const CGHeroInstance * hero;
  344. std::vector<TurnInfo *> turnsInfo;
  345. const PathfinderOptions & options;
  346. CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options);
  347. ~CPathfinderHelper();
  348. void updateTurnInfo(const int turn = 0);
  349. bool isLayerAvailable(const EPathfindingLayer layer) const;
  350. const TurnInfo * getTurnInfo() const;
  351. bool hasBonusOfType(const Bonus::BonusType type, const int subtype = -1) const;
  352. int getMaxMovePoints(const EPathfindingLayer layer) const;
  353. std::vector<int3> CPathfinderHelper::getCastleGates(CPathNodeInfo & source) const;
  354. bool isAllowedTeleportEntrance(const CGTeleport * obj) const;
  355. std::vector<int3> getAllowedTeleportChannelExits(TeleportChannelID channelID) const;
  356. bool addTeleportTwoWay(const CGTeleport * obj) const;
  357. bool addTeleportOneWay(const CGTeleport * obj) const;
  358. bool addTeleportOneWayRandom(const CGTeleport * obj) const;
  359. bool addTeleportWhirlpool(const CGWhirlpool * obj) const;
  360. bool canMoveBetween(const int3 & a, const int3 & b) const; //checks only for visitable objects that may make moving between tiles impossible, not other conditions (like tiles itself accessibility)
  361. void getNeighbours(const TerrainTile & srct, const int3 & tile, std::vector<int3> & vec, const boost::logic::tribool & onLand, const bool limitCoastSailing);
  362. int getMovementCost(
  363. const int3 & src,
  364. const int3 & dst,
  365. const TerrainTile * ct,
  366. const TerrainTile * dt,
  367. const int remainingMovePoints =- 1,
  368. const bool checkLast = true);
  369. int getMovementCost(
  370. const CPathNodeInfo & src,
  371. const CPathNodeInfo & dst,
  372. const int remainingMovePoints = -1,
  373. const bool checkLast = true)
  374. {
  375. return getMovementCost(
  376. src.coord,
  377. dst.coord,
  378. src.tile,
  379. dst.tile,
  380. remainingMovePoints,
  381. checkLast
  382. );
  383. }
  384. int getHeroMaxMovementPoints(EPathfindingLayer layer);
  385. int movementPointsAfterEmbark(int movement, int cost, int action);
  386. bool passOneTurnLimitCheck(CPathNodeInfo & source);
  387. };