CPathfinder.h 17 KB

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