CPathfinder.h 17 KB

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