CPathfinder.h 15 KB

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