CPathfinder.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. /*
  2. * CPathfinder.cpp, 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. #include "StdInc.h"
  11. #include "CPathfinder.h"
  12. #include "CHeroHandler.h"
  13. #include "mapping/CMap.h"
  14. #include "CGameState.h"
  15. #include "mapObjects/CGHeroInstance.h"
  16. #include "GameConstants.h"
  17. #include "CStopWatch.h"
  18. #include "CConfigHandler.h"
  19. #include "CPlayerState.h"
  20. #include "PathfinderUtil.h"
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. bool canSeeObj(const CGObjectInstance * obj)
  23. {
  24. /// Pathfinder should ignore placed events
  25. return obj != nullptr && obj->ID != Obj::EVENT;
  26. }
  27. void NodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  28. {
  29. //TODO: fix this code duplication with AINodeStorage::initialize, problem is to keep `resetTile` inline
  30. int3 pos;
  31. const PlayerColor player = out.hero->tempOwner;
  32. const int3 sizes = gs->getMapSize();
  33. const auto fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  34. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  35. const bool useFlying = options.useFlying;
  36. const bool useWaterWalking = options.useWaterWalking;
  37. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  38. {
  39. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  40. {
  41. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  42. {
  43. const TerrainTile tile = gs->map->getTile(pos);
  44. if(tile.terType->isWater())
  45. {
  46. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  47. if(useFlying)
  48. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  49. if(useWaterWalking)
  50. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  51. }
  52. if(tile.terType->isLand())
  53. {
  54. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  55. if(useFlying)
  56. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  57. }
  58. }
  59. }
  60. }
  61. }
  62. std::vector<CGPathNode *> NodeStorage::calculateNeighbours(
  63. const PathNodeInfo & source,
  64. const PathfinderConfig * pathfinderConfig,
  65. const CPathfinderHelper * pathfinderHelper)
  66. {
  67. std::vector<CGPathNode *> neighbours;
  68. neighbours.reserve(16);
  69. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  70. for(auto & neighbour : accessibleNeighbourTiles)
  71. {
  72. for(EPathfindingLayer i = EPathfindingLayer::LAND; i < EPathfindingLayer::NUM_LAYERS; i.advance(1))
  73. {
  74. auto * node = getNode(neighbour, i);
  75. if(node->accessible == CGPathNode::NOT_SET)
  76. continue;
  77. neighbours.push_back(node);
  78. }
  79. }
  80. return neighbours;
  81. }
  82. std::vector<CGPathNode *> NodeStorage::calculateTeleportations(
  83. const PathNodeInfo & source,
  84. const PathfinderConfig * pathfinderConfig,
  85. const CPathfinderHelper * pathfinderHelper)
  86. {
  87. std::vector<CGPathNode *> neighbours;
  88. if(!source.isNodeObjectVisitable())
  89. return neighbours;
  90. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  91. for(auto & neighbour : accessibleExits)
  92. {
  93. auto * node = getNode(neighbour, source.node->layer);
  94. neighbours.push_back(node);
  95. }
  96. return neighbours;
  97. }
  98. std::vector<int3> CPathfinderHelper::getNeighbourTiles(const PathNodeInfo & source) const
  99. {
  100. std::vector<int3> neighbourTiles;
  101. neighbourTiles.reserve(8);
  102. getNeighbours(
  103. *source.tile,
  104. source.node->coord,
  105. neighbourTiles,
  106. boost::logic::indeterminate,
  107. source.node->layer == EPathfindingLayer::SAIL);
  108. if(source.isNodeObjectVisitable())
  109. {
  110. vstd::erase_if(neighbourTiles, [&](const int3 & tile) -> bool
  111. {
  112. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  113. });
  114. }
  115. return neighbourTiles;
  116. }
  117. NodeStorage::NodeStorage(CPathsInfo & pathsInfo, const CGHeroInstance * hero)
  118. :out(pathsInfo)
  119. {
  120. out.hero = hero;
  121. out.hpos = hero->visitablePos();
  122. }
  123. void NodeStorage::resetTile(const int3 & tile, const EPathfindingLayer & layer, CGPathNode::EAccessibility accessibility)
  124. {
  125. getNode(tile, layer)->update(tile, layer, accessibility);
  126. }
  127. std::vector<CGPathNode *> NodeStorage::getInitialNodes()
  128. {
  129. auto * initialNode = getNode(out.hpos, out.hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  130. initialNode->turns = 0;
  131. initialNode->moveRemains = out.hero->movement;
  132. initialNode->setCost(0.0);
  133. if(!initialNode->coord.valid())
  134. {
  135. initialNode->coord = out.hpos;
  136. }
  137. return std::vector<CGPathNode *> { initialNode };
  138. }
  139. void NodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  140. {
  141. assert(destination.node != source.node->theNodeBefore); //two tiles can't point to each other
  142. destination.node->setCost(destination.cost);
  143. destination.node->moveRemains = destination.movementLeft;
  144. destination.node->turns = destination.turn;
  145. destination.node->theNodeBefore = source.node;
  146. destination.node->action = destination.action;
  147. }
  148. PathfinderOptions::PathfinderOptions()
  149. {
  150. useFlying = settings["pathfinder"]["layers"]["flying"].Bool();
  151. useWaterWalking = settings["pathfinder"]["layers"]["waterWalking"].Bool();
  152. useEmbarkAndDisembark = settings["pathfinder"]["layers"]["sailing"].Bool();
  153. useTeleportTwoWay = settings["pathfinder"]["teleports"]["twoWay"].Bool();
  154. useTeleportOneWay = settings["pathfinder"]["teleports"]["oneWay"].Bool();
  155. useTeleportOneWayRandom = settings["pathfinder"]["teleports"]["oneWayRandom"].Bool();
  156. useTeleportWhirlpool = settings["pathfinder"]["teleports"]["whirlpool"].Bool();
  157. useCastleGate = settings["pathfinder"]["teleports"]["castleGate"].Bool();
  158. lightweightFlyingMode = settings["pathfinder"]["lightweightFlyingMode"].Bool();
  159. oneTurnSpecialLayersLimit = settings["pathfinder"]["oneTurnSpecialLayersLimit"].Bool();
  160. originalMovementRules = settings["pathfinder"]["originalMovementRules"].Bool();
  161. }
  162. void MovementCostRule::process(
  163. const PathNodeInfo & source,
  164. CDestinationNodeInfo & destination,
  165. const PathfinderConfig * pathfinderConfig,
  166. CPathfinderHelper * pathfinderHelper) const
  167. {
  168. float costAtNextTile = destination.cost;
  169. int turnAtNextTile = destination.turn;
  170. int moveAtNextTile = destination.movementLeft;
  171. int cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile);
  172. int remains = moveAtNextTile - cost;
  173. int sourceLayerMaxMovePoints = pathfinderHelper->getMaxMovePoints(source.node->layer);
  174. if(remains < 0)
  175. {
  176. //occurs rarely, when hero with low movepoints tries to leave the road
  177. costAtNextTile += static_cast<float>(moveAtNextTile) / sourceLayerMaxMovePoints;//we spent all points of current turn
  178. pathfinderHelper->updateTurnInfo(++turnAtNextTile);
  179. int destinationLayerMaxMovePoints = pathfinderHelper->getMaxMovePoints(destination.node->layer);
  180. moveAtNextTile = destinationLayerMaxMovePoints;
  181. cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile); //cost must be updated, movement points changed :(
  182. remains = moveAtNextTile - cost;
  183. }
  184. if(destination.action == CGPathNode::EMBARK || destination.action == CGPathNode::DISEMBARK)
  185. {
  186. /// FREE_SHIP_BOARDING bonus only remove additional penalty
  187. /// land <-> sail transition still cost movement points as normal movement
  188. remains = pathfinderHelper->movementPointsAfterEmbark(moveAtNextTile, cost, (destination.action == CGPathNode::DISEMBARK));
  189. cost = moveAtNextTile - remains;
  190. }
  191. costAtNextTile += static_cast<float>(cost) / sourceLayerMaxMovePoints;
  192. destination.cost = costAtNextTile;
  193. destination.turn = turnAtNextTile;
  194. destination.movementLeft = remains;
  195. if(destination.isBetterWay() &&
  196. ((source.node->turns == turnAtNextTile && remains) || pathfinderHelper->passOneTurnLimitCheck(source)))
  197. {
  198. pathfinderConfig->nodeStorage->commit(destination, source);
  199. return;
  200. }
  201. destination.blocked = true;
  202. }
  203. PathfinderConfig::PathfinderConfig(std::shared_ptr<INodeStorage> nodeStorage, std::vector<std::shared_ptr<IPathfindingRule>> rules):
  204. nodeStorage(std::move(nodeStorage)),
  205. rules(std::move(rules))
  206. {
  207. }
  208. std::vector<std::shared_ptr<IPathfindingRule>> SingleHeroPathfinderConfig::buildRuleSet()
  209. {
  210. return std::vector<std::shared_ptr<IPathfindingRule>>{
  211. std::make_shared<LayerTransitionRule>(),
  212. std::make_shared<DestinationActionRule>(),
  213. std::make_shared<MovementToDestinationRule>(),
  214. std::make_shared<MovementCostRule>(),
  215. std::make_shared<MovementAfterDestinationRule>()
  216. };
  217. }
  218. SingleHeroPathfinderConfig::SingleHeroPathfinderConfig(CPathsInfo & out, CGameState * gs, const CGHeroInstance * hero)
  219. : PathfinderConfig(std::make_shared<NodeStorage>(out, hero), buildRuleSet())
  220. {
  221. pathfinderHelper = std::make_unique<CPathfinderHelper>(gs, hero, options);
  222. }
  223. CPathfinderHelper * SingleHeroPathfinderConfig::getOrCreatePathfinderHelper(const PathNodeInfo & source, CGameState * gs)
  224. {
  225. return pathfinderHelper.get();
  226. }
  227. CPathfinder::CPathfinder(CGameState * _gs, std::shared_ptr<PathfinderConfig> config):
  228. gamestate(_gs),
  229. config(std::move(config))
  230. {
  231. initializeGraph();
  232. }
  233. void CPathfinder::push(CGPathNode * node)
  234. {
  235. if(node && !node->inPQ)
  236. {
  237. node->inPQ = true;
  238. node->pq = &this->pq;
  239. auto handle = pq.push(node);
  240. node->pqHandle = handle;
  241. }
  242. }
  243. CGPathNode * CPathfinder::topAndPop()
  244. {
  245. auto * node = pq.top();
  246. pq.pop();
  247. node->inPQ = false;
  248. node->pq = nullptr;
  249. return node;
  250. }
  251. void CPathfinder::calculatePaths()
  252. {
  253. //logGlobal->info("Calculating paths for hero %s (adress %d) of player %d", hero->name, hero , hero->tempOwner);
  254. //initial tile - set cost on 0 and add to the queue
  255. std::vector<CGPathNode *> initialNodes = config->nodeStorage->getInitialNodes();
  256. int counter = 0;
  257. for(auto * initialNode : initialNodes)
  258. {
  259. if(!gamestate->isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
  260. {
  261. logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
  262. throw std::runtime_error("Wrong checksum");
  263. }
  264. source.setNode(gamestate, initialNode);
  265. auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  266. if(hlp->isHeroPatrolLocked())
  267. continue;
  268. pq.push(initialNode);
  269. }
  270. while(!pq.empty())
  271. {
  272. counter++;
  273. auto * node = topAndPop();
  274. source.setNode(gamestate, node);
  275. source.node->locked = true;
  276. int movement = source.node->moveRemains;
  277. uint8_t turn = source.node->turns;
  278. float cost = source.node->getCost();
  279. auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  280. hlp->updateTurnInfo(turn);
  281. if(!movement)
  282. {
  283. hlp->updateTurnInfo(++turn);
  284. movement = hlp->getMaxMovePoints(source.node->layer);
  285. if(!hlp->passOneTurnLimitCheck(source))
  286. continue;
  287. }
  288. source.isInitialPosition = source.nodeHero == hlp->hero;
  289. source.updateInfo(hlp, gamestate);
  290. //add accessible neighbouring nodes to the queue
  291. auto neighbourNodes = config->nodeStorage->calculateNeighbours(source, config.get(), hlp);
  292. for(CGPathNode * neighbour : neighbourNodes)
  293. {
  294. if(neighbour->locked)
  295. continue;
  296. if(!hlp->isLayerAvailable(neighbour->layer))
  297. continue;
  298. destination.setNode(gamestate, neighbour);
  299. hlp = config->getOrCreatePathfinderHelper(destination, gamestate);
  300. if(!hlp->isPatrolMovementAllowed(neighbour->coord))
  301. continue;
  302. /// Check transition without tile accessability rules
  303. if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
  304. continue;
  305. destination.turn = turn;
  306. destination.movementLeft = movement;
  307. destination.cost = cost;
  308. destination.updateInfo(hlp, gamestate);
  309. destination.isGuardianTile = destination.guarded && isDestinationGuardian();
  310. for(const auto & rule : config->rules)
  311. {
  312. rule->process(source, destination, config.get(), hlp);
  313. if(destination.blocked)
  314. break;
  315. }
  316. if(!destination.blocked)
  317. push(destination.node);
  318. } //neighbours loop
  319. //just add all passable teleport exits
  320. hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  321. /// For now we disable teleports usage for patrol movement
  322. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  323. if(hlp->patrolState == CPathfinderHelper::PATROL_RADIUS)
  324. continue;
  325. auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp);
  326. for(CGPathNode * teleportNode : teleportationNodes)
  327. {
  328. if(teleportNode->locked)
  329. continue;
  330. /// TODO: We may consider use invisible exits on FoW border in future
  331. /// Useful for AI when at least one tile around exit is visible and passable
  332. /// Objects are usually visible on FoW border anyway so it's not cheating.
  333. ///
  334. /// For now it's disabled as it's will cause crashes in movement code.
  335. if(teleportNode->accessible == CGPathNode::BLOCKED)
  336. continue;
  337. destination.setNode(gamestate, teleportNode);
  338. destination.turn = turn;
  339. destination.movementLeft = movement;
  340. destination.cost = cost;
  341. if(destination.isBetterWay())
  342. {
  343. destination.action = getTeleportDestAction();
  344. config->nodeStorage->commit(destination, source);
  345. if(destination.node->action == CGPathNode::TELEPORT_NORMAL)
  346. push(destination.node);
  347. }
  348. }
  349. } //queue loop
  350. logAi->trace("CPathfinder finished with %s iterations", std::to_string(counter));
  351. }
  352. std::vector<int3> CPathfinderHelper::getAllowedTeleportChannelExits(const TeleportChannelID & channelID) const
  353. {
  354. std::vector<int3> allowedExits;
  355. for(const auto & objId : getTeleportChannelExits(channelID, hero->tempOwner))
  356. {
  357. const auto * obj = getObj(objId);
  358. if(dynamic_cast<const CGWhirlpool *>(obj))
  359. {
  360. auto pos = obj->getBlockedPos();
  361. for(const auto & p : pos)
  362. {
  363. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  364. allowedExits.push_back(p);
  365. }
  366. }
  367. else if(obj && CGTeleport::isExitPassable(gs, hero, obj))
  368. allowedExits.push_back(obj->visitablePos());
  369. }
  370. return allowedExits;
  371. }
  372. std::vector<int3> CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  373. {
  374. std::vector<int3> allowedExits;
  375. auto towns = getPlayerState(hero->tempOwner)->towns;
  376. for(const auto & town : towns)
  377. {
  378. if(town->id != source.nodeObject->id && town->visitingHero == nullptr
  379. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  380. {
  381. allowedExits.push_back(town->visitablePos());
  382. }
  383. }
  384. return allowedExits;
  385. }
  386. std::vector<int3> CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
  387. {
  388. std::vector<int3> teleportationExits;
  389. const auto * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
  390. if(isAllowedTeleportEntrance(objTeleport))
  391. {
  392. for(const auto & exit : getAllowedTeleportChannelExits(objTeleport->channel))
  393. {
  394. teleportationExits.push_back(exit);
  395. }
  396. }
  397. else if(options.useCastleGate
  398. && (source.nodeObject->ID == Obj::TOWN && source.nodeObject->subID == ETownType::INFERNO
  399. && source.objectRelations != PlayerRelations::ENEMIES))
  400. {
  401. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  402. /// This may be handy if we allow to use teleportation to friendly towns
  403. for(const auto & exit : getCastleGates(source))
  404. {
  405. teleportationExits.push_back(exit);
  406. }
  407. }
  408. return teleportationExits;
  409. }
  410. bool CPathfinderHelper::isHeroPatrolLocked() const
  411. {
  412. return patrolState == PATROL_LOCKED;
  413. }
  414. bool CPathfinderHelper::isPatrolMovementAllowed(const int3 & dst) const
  415. {
  416. if(patrolState == PATROL_RADIUS)
  417. {
  418. if(!vstd::contains(patrolTiles, dst))
  419. return false;
  420. }
  421. return true;
  422. }
  423. bool CPathfinder::isLayerTransitionPossible() const
  424. {
  425. ELayer destLayer = destination.node->layer;
  426. /// No layer transition allowed when previous node action is BATTLE
  427. if(source.node->action == CGPathNode::BATTLE)
  428. return false;
  429. switch(source.node->layer)
  430. {
  431. case ELayer::LAND:
  432. if(destLayer == ELayer::AIR)
  433. {
  434. if(!config->options.lightweightFlyingMode || source.isInitialPosition)
  435. return true;
  436. }
  437. else if(destLayer == ELayer::SAIL)
  438. {
  439. if(destination.tile->isWater())
  440. return true;
  441. }
  442. else
  443. return true;
  444. break;
  445. case ELayer::SAIL:
  446. if(destLayer == ELayer::LAND && !destination.tile->isWater())
  447. return true;
  448. break;
  449. case ELayer::AIR:
  450. if(destLayer == ELayer::LAND)
  451. return true;
  452. break;
  453. case ELayer::WATER:
  454. if(destLayer == ELayer::LAND)
  455. return true;
  456. break;
  457. }
  458. return false;
  459. }
  460. void LayerTransitionRule::process(
  461. const PathNodeInfo & source,
  462. CDestinationNodeInfo & destination,
  463. const PathfinderConfig * pathfinderConfig,
  464. CPathfinderHelper * pathfinderHelper) const
  465. {
  466. if(source.node->layer == destination.node->layer)
  467. return;
  468. switch(source.node->layer)
  469. {
  470. case EPathfindingLayer::LAND:
  471. if(destination.node->layer == EPathfindingLayer::SAIL)
  472. {
  473. /// Cannot enter empty water tile from land -> it has to be visitable
  474. if(destination.node->accessible == CGPathNode::ACCESSIBLE)
  475. destination.blocked = true;
  476. }
  477. break;
  478. case EPathfindingLayer::SAIL:
  479. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  480. if((destination.node->accessible != CGPathNode::ACCESSIBLE && (destination.node->accessible != CGPathNode::BLOCKVIS || destination.tile->blocked))
  481. || destination.tile->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  482. {
  483. destination.blocked = true;
  484. }
  485. break;
  486. case EPathfindingLayer::AIR:
  487. if(pathfinderConfig->options.originalMovementRules)
  488. {
  489. if((source.node->accessible != CGPathNode::ACCESSIBLE &&
  490. source.node->accessible != CGPathNode::VISITABLE) &&
  491. (destination.node->accessible != CGPathNode::VISITABLE &&
  492. destination.node->accessible != CGPathNode::ACCESSIBLE))
  493. {
  494. destination.blocked = true;
  495. }
  496. }
  497. else if(destination.node->accessible != CGPathNode::ACCESSIBLE)
  498. {
  499. /// Hero that fly can only land on accessible tiles
  500. if(destination.nodeObject)
  501. destination.blocked = true;
  502. }
  503. break;
  504. case EPathfindingLayer::WATER:
  505. if(destination.node->accessible != CGPathNode::ACCESSIBLE && destination.node->accessible != CGPathNode::VISITABLE)
  506. {
  507. /// Hero that walking on water can transit to accessible and visitable tiles
  508. /// Though hero can't interact with blocking visit objects while standing on water
  509. destination.blocked = true;
  510. }
  511. break;
  512. }
  513. }
  514. PathfinderBlockingRule::BlockingReason MovementToDestinationRule::getBlockingReason(
  515. const PathNodeInfo & source,
  516. const CDestinationNodeInfo & destination,
  517. const PathfinderConfig * pathfinderConfig,
  518. const CPathfinderHelper * pathfinderHelper) const
  519. {
  520. if(destination.node->accessible == CGPathNode::BLOCKED)
  521. return BlockingReason::DESTINATION_BLOCKED;
  522. switch(destination.node->layer)
  523. {
  524. case EPathfindingLayer::LAND:
  525. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  526. return BlockingReason::DESTINATION_BLOCKED;
  527. if(source.guarded)
  528. {
  529. if(!(pathfinderConfig->options.originalMovementRules && source.node->layer == EPathfindingLayer::AIR) &&
  530. !destination.isGuardianTile) // Can step into tile of guard
  531. {
  532. return BlockingReason::SOURCE_GUARDED;
  533. }
  534. }
  535. break;
  536. case EPathfindingLayer::SAIL:
  537. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  538. return BlockingReason::DESTINATION_BLOCKED;
  539. if(source.guarded)
  540. {
  541. // Hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  542. if(source.node->action != CGPathNode::EMBARK && !destination.isGuardianTile)
  543. return BlockingReason::SOURCE_GUARDED;
  544. }
  545. if(source.node->layer == EPathfindingLayer::LAND)
  546. {
  547. if(!destination.isNodeObjectVisitable())
  548. return BlockingReason::DESTINATION_BLOCKED;
  549. if(destination.nodeObject->ID != Obj::BOAT && !destination.nodeHero)
  550. return BlockingReason::DESTINATION_BLOCKED;
  551. }
  552. else if(destination.isNodeObjectVisitable() && destination.nodeObject->ID == Obj::BOAT)
  553. {
  554. /// Hero in boat can't visit empty boats
  555. return BlockingReason::DESTINATION_BLOCKED;
  556. }
  557. break;
  558. case EPathfindingLayer::WATER:
  559. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord)
  560. || destination.node->accessible != CGPathNode::ACCESSIBLE)
  561. {
  562. return BlockingReason::DESTINATION_BLOCKED;
  563. }
  564. if(destination.guarded)
  565. return BlockingReason::DESTINATION_BLOCKED;
  566. break;
  567. }
  568. return BlockingReason::NONE;
  569. }
  570. void MovementAfterDestinationRule::process(
  571. const PathNodeInfo & source,
  572. CDestinationNodeInfo & destination,
  573. const PathfinderConfig * config,
  574. CPathfinderHelper * pathfinderHelper) const
  575. {
  576. auto blocker = getBlockingReason(source, destination, config, pathfinderHelper);
  577. if(blocker == BlockingReason::DESTINATION_GUARDED && destination.action == CGPathNode::ENodeAction::BATTLE)
  578. {
  579. return; // allow bypass guarded tile but only in direction of guard, a bit UI related thing
  580. }
  581. destination.blocked = blocker != BlockingReason::NONE;
  582. }
  583. PathfinderBlockingRule::BlockingReason MovementAfterDestinationRule::getBlockingReason(
  584. const PathNodeInfo & source,
  585. const CDestinationNodeInfo & destination,
  586. const PathfinderConfig * config,
  587. const CPathfinderHelper * pathfinderHelper) const
  588. {
  589. switch(destination.action)
  590. {
  591. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  592. /// Likely in many cases we don't need to add visitable tile to queue when hero doesn't fly
  593. case CGPathNode::VISIT:
  594. {
  595. /// For now we only add visitable tile into queue when it's teleporter that allow transit
  596. /// Movement from visitable tile when hero is standing on it is possible into any layer
  597. const auto * objTeleport = dynamic_cast<const CGTeleport *>(destination.nodeObject);
  598. if(pathfinderHelper->isAllowedTeleportEntrance(objTeleport))
  599. {
  600. /// For now we'll always allow transit over teleporters
  601. /// Transit over whirlpools only allowed when hero is protected
  602. return BlockingReason::NONE;
  603. }
  604. else if(destination.nodeObject->ID == Obj::GARRISON
  605. || destination.nodeObject->ID == Obj::GARRISON2
  606. || destination.nodeObject->ID == Obj::BORDER_GATE)
  607. {
  608. /// Transit via unguarded garrisons is always possible
  609. return BlockingReason::NONE;
  610. }
  611. return BlockingReason::DESTINATION_VISIT;
  612. }
  613. case CGPathNode::BLOCKING_VISIT:
  614. return destination.guarded
  615. ? BlockingReason::DESTINATION_GUARDED
  616. : BlockingReason::DESTINATION_BLOCKVIS;
  617. case CGPathNode::NORMAL:
  618. return BlockingReason::NONE;
  619. case CGPathNode::EMBARK:
  620. if(pathfinderHelper->options.useEmbarkAndDisembark)
  621. return BlockingReason::NONE;
  622. return BlockingReason::DESTINATION_BLOCKED;
  623. case CGPathNode::DISEMBARK:
  624. if(pathfinderHelper->options.useEmbarkAndDisembark)
  625. return destination.guarded ? BlockingReason::DESTINATION_GUARDED : BlockingReason::NONE;
  626. return BlockingReason::DESTINATION_BLOCKED;
  627. case CGPathNode::BATTLE:
  628. /// Movement after BATTLE action only possible from guarded tile to guardian tile
  629. if(destination.guarded)
  630. return BlockingReason::DESTINATION_GUARDED;
  631. break;
  632. }
  633. return BlockingReason::DESTINATION_BLOCKED;
  634. }
  635. void DestinationActionRule::process(
  636. const PathNodeInfo & source,
  637. CDestinationNodeInfo & destination,
  638. const PathfinderConfig * pathfinderConfig,
  639. CPathfinderHelper * pathfinderHelper) const
  640. {
  641. if(destination.action != CGPathNode::ENodeAction::UNKNOWN)
  642. {
  643. #ifdef VCMI_TRACE_PATHFINDER
  644. logAi->trace("Accepted precalculated action at %s", destination.coord.toString());
  645. #endif
  646. return;
  647. }
  648. CGPathNode::ENodeAction action = CGPathNode::NORMAL;
  649. const auto * hero = pathfinderHelper->hero;
  650. switch(destination.node->layer)
  651. {
  652. case EPathfindingLayer::LAND:
  653. if(source.node->layer == EPathfindingLayer::SAIL)
  654. {
  655. // TODO: Handle dismebark into guarded areaa
  656. action = CGPathNode::DISEMBARK;
  657. break;
  658. }
  659. /// don't break - next case shared for both land and sail layers
  660. FALLTHROUGH
  661. case EPathfindingLayer::SAIL:
  662. if(destination.isNodeObjectVisitable())
  663. {
  664. auto objRel = destination.objectRelations;
  665. if(destination.nodeObject->ID == Obj::BOAT)
  666. action = CGPathNode::EMBARK;
  667. else if(destination.nodeHero)
  668. {
  669. if(destination.heroRelations == PlayerRelations::ENEMIES)
  670. action = CGPathNode::BATTLE;
  671. else
  672. action = CGPathNode::BLOCKING_VISIT;
  673. }
  674. else if(destination.nodeObject->ID == Obj::TOWN)
  675. {
  676. if(destination.nodeObject->passableFor(hero->tempOwner))
  677. action = CGPathNode::VISIT;
  678. else if(objRel == PlayerRelations::ENEMIES)
  679. action = CGPathNode::BATTLE;
  680. }
  681. else if(destination.nodeObject->ID == Obj::GARRISON || destination.nodeObject->ID == Obj::GARRISON2)
  682. {
  683. if(destination.nodeObject->passableFor(hero->tempOwner))
  684. {
  685. if(destination.guarded)
  686. action = CGPathNode::BATTLE;
  687. }
  688. else if(objRel == PlayerRelations::ENEMIES)
  689. action = CGPathNode::BATTLE;
  690. }
  691. else if(destination.nodeObject->ID == Obj::BORDER_GATE)
  692. {
  693. if(destination.nodeObject->passableFor(hero->tempOwner))
  694. {
  695. if(destination.guarded)
  696. action = CGPathNode::BATTLE;
  697. }
  698. else
  699. action = CGPathNode::BLOCKING_VISIT;
  700. }
  701. else if(destination.isGuardianTile)
  702. action = CGPathNode::BATTLE;
  703. else if(destination.nodeObject->blockVisit && !(pathfinderConfig->options.useCastleGate && destination.nodeObject->ID == Obj::TOWN))
  704. action = CGPathNode::BLOCKING_VISIT;
  705. if(action == CGPathNode::NORMAL)
  706. {
  707. if(destination.guarded)
  708. action = CGPathNode::BATTLE;
  709. else
  710. action = CGPathNode::VISIT;
  711. }
  712. }
  713. else if(destination.guarded)
  714. action = CGPathNode::BATTLE;
  715. break;
  716. }
  717. destination.action = action;
  718. }
  719. CGPathNode::ENodeAction CPathfinder::getTeleportDestAction() const
  720. {
  721. CGPathNode::ENodeAction action = CGPathNode::TELEPORT_NORMAL;
  722. if(destination.isNodeObjectVisitable() && destination.nodeHero)
  723. {
  724. if(destination.heroRelations == PlayerRelations::ENEMIES)
  725. action = CGPathNode::TELEPORT_BATTLE;
  726. else
  727. action = CGPathNode::TELEPORT_BLOCKING_VISIT;
  728. }
  729. return action;
  730. }
  731. bool CPathfinder::isDestinationGuardian() const
  732. {
  733. return gamestate->guardingCreaturePosition(destination.node->coord) == destination.node->coord;
  734. }
  735. void CPathfinderHelper::initializePatrol()
  736. {
  737. auto state = PATROL_NONE;
  738. if(hero->patrol.patrolling && !getPlayerState(hero->tempOwner)->human)
  739. {
  740. if(hero->patrol.patrolRadius)
  741. {
  742. state = PATROL_RADIUS;
  743. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, boost::optional<PlayerColor>(), 0, int3::DIST_MANHATTAN);
  744. }
  745. else
  746. state = PATROL_LOCKED;
  747. }
  748. patrolState = state;
  749. }
  750. void CPathfinder::initializeGraph()
  751. {
  752. INodeStorage * nodeStorage = config->nodeStorage.get();
  753. nodeStorage->initialize(config->options, gamestate);
  754. }
  755. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  756. {
  757. return gs->checkForVisitableDir(a, b);
  758. }
  759. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  760. {
  761. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  762. return false;
  763. const auto * whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  764. if(whirlpool)
  765. {
  766. if(addTeleportWhirlpool(whirlpool))
  767. return true;
  768. }
  769. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  770. return true;
  771. return false;
  772. }
  773. bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
  774. {
  775. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  776. }
  777. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  778. {
  779. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  780. {
  781. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  782. if(passableExits.size() == 1)
  783. return true;
  784. }
  785. return false;
  786. }
  787. bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
  788. {
  789. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  790. {
  791. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  792. if(passableExits.size() > 1)
  793. return true;
  794. }
  795. return false;
  796. }
  797. bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
  798. {
  799. return options.useTeleportWhirlpool && hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  800. }
  801. int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
  802. {
  803. return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
  804. }
  805. bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
  806. {
  807. if(!options.oneTurnSpecialLayersLimit)
  808. return true;
  809. if(source.node->layer == EPathfindingLayer::WATER)
  810. return false;
  811. if(source.node->layer == EPathfindingLayer::AIR)
  812. {
  813. return options.originalMovementRules && source.node->accessible == CGPathNode::ACCESSIBLE;
  814. }
  815. return true;
  816. }
  817. TurnInfo::BonusCache::BonusCache(const TConstBonusListPtr & bl)
  818. {
  819. for(const auto & terrain : VLC->terrainTypeHandler->objects)
  820. {
  821. noTerrainPenalty.push_back(static_cast<bool>(
  822. bl->getFirst(Selector::type()(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype()(terrain->getIndex())))));
  823. }
  824. freeShipBoarding = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FREE_SHIP_BOARDING)));
  825. flyingMovement = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FLYING_MOVEMENT)));
  826. flyingMovementVal = bl->valOfBonuses(Selector::type()(Bonus::FLYING_MOVEMENT));
  827. waterWalking = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::WATER_WALKING)));
  828. waterWalkingVal = bl->valOfBonuses(Selector::type()(Bonus::WATER_WALKING));
  829. pathfindingVal = bl->valOfBonuses(Selector::type()(Bonus::ROUGH_TERRAIN_DISCOUNT));
  830. }
  831. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn):
  832. hero(Hero),
  833. maxMovePointsLand(-1),
  834. maxMovePointsWater(-1),
  835. turn(turn)
  836. {
  837. bonuses = hero->getAllBonuses(Selector::days(turn), Selector::all, nullptr, "");
  838. bonusCache = std::make_unique<BonusCache>(bonuses);
  839. nativeTerrain = hero->getNativeTerrain();
  840. }
  841. bool TurnInfo::isLayerAvailable(const EPathfindingLayer & layer) const
  842. {
  843. switch(layer)
  844. {
  845. case EPathfindingLayer::AIR:
  846. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  847. return false;
  848. break;
  849. case EPathfindingLayer::WATER:
  850. if(!hasBonusOfType(Bonus::WATER_WALKING))
  851. return false;
  852. break;
  853. }
  854. return true;
  855. }
  856. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  857. {
  858. switch(type)
  859. {
  860. case Bonus::FREE_SHIP_BOARDING:
  861. return bonusCache->freeShipBoarding;
  862. case Bonus::FLYING_MOVEMENT:
  863. return bonusCache->flyingMovement;
  864. case Bonus::WATER_WALKING:
  865. return bonusCache->waterWalking;
  866. case Bonus::NO_TERRAIN_PENALTY:
  867. return bonusCache->noTerrainPenalty[subtype];
  868. }
  869. return static_cast<bool>(
  870. bonuses->getFirst(Selector::type()(type).And(Selector::subtype()(subtype))));
  871. }
  872. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  873. {
  874. switch(type)
  875. {
  876. case Bonus::FLYING_MOVEMENT:
  877. return bonusCache->flyingMovementVal;
  878. case Bonus::WATER_WALKING:
  879. return bonusCache->waterWalkingVal;
  880. case Bonus::ROUGH_TERRAIN_DISCOUNT:
  881. return bonusCache->pathfindingVal;
  882. }
  883. return bonuses->valOfBonuses(Selector::type()(type).And(Selector::subtype()(subtype)));
  884. }
  885. int TurnInfo::getMaxMovePoints(const EPathfindingLayer & layer) const
  886. {
  887. if(maxMovePointsLand == -1)
  888. maxMovePointsLand = hero->maxMovePointsCached(true, this);
  889. if(maxMovePointsWater == -1)
  890. maxMovePointsWater = hero->maxMovePointsCached(false, this);
  891. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  892. }
  893. void TurnInfo::updateHeroBonuses(Bonus::BonusType type, const CSelector& sel) const
  894. {
  895. switch(type)
  896. {
  897. case Bonus::FREE_SHIP_BOARDING:
  898. bonusCache->freeShipBoarding = static_cast<bool>(bonuses->getFirst(Selector::type()(Bonus::FREE_SHIP_BOARDING)));
  899. break;
  900. case Bonus::FLYING_MOVEMENT:
  901. bonusCache->flyingMovement = static_cast<bool>(bonuses->getFirst(Selector::type()(Bonus::FLYING_MOVEMENT)));
  902. bonusCache->flyingMovementVal = bonuses->valOfBonuses(Selector::type()(Bonus::FLYING_MOVEMENT));
  903. break;
  904. case Bonus::WATER_WALKING:
  905. bonusCache->waterWalking = static_cast<bool>(bonuses->getFirst(Selector::type()(Bonus::WATER_WALKING)));
  906. bonusCache->waterWalkingVal = bonuses->valOfBonuses(Selector::type()(Bonus::WATER_WALKING));
  907. break;
  908. case Bonus::ROUGH_TERRAIN_DISCOUNT:
  909. bonusCache->pathfindingVal = bonuses->valOfBonuses(Selector::type()(Bonus::ROUGH_TERRAIN_DISCOUNT));
  910. break;
  911. default:
  912. bonuses = hero->getAllBonuses(Selector::days(turn), Selector::all, nullptr, "");
  913. }
  914. }
  915. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options)
  916. : CGameInfoCallback(gs, boost::optional<PlayerColor>()), turn(-1), hero(Hero), options(Options), owner(Hero->tempOwner)
  917. {
  918. turnsInfo.reserve(16);
  919. updateTurnInfo();
  920. initializePatrol();
  921. }
  922. CPathfinderHelper::~CPathfinderHelper()
  923. {
  924. for(auto * ti : turnsInfo)
  925. delete ti;
  926. }
  927. void CPathfinderHelper::updateTurnInfo(const int Turn)
  928. {
  929. if(turn != Turn)
  930. {
  931. turn = Turn;
  932. if(turn >= turnsInfo.size())
  933. {
  934. auto * ti = new TurnInfo(hero, turn);
  935. turnsInfo.push_back(ti);
  936. }
  937. }
  938. }
  939. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
  940. {
  941. switch(layer)
  942. {
  943. case EPathfindingLayer::AIR:
  944. if(!options.useFlying)
  945. return false;
  946. break;
  947. case EPathfindingLayer::WATER:
  948. if(!options.useWaterWalking)
  949. return false;
  950. break;
  951. }
  952. return turnsInfo[turn]->isLayerAvailable(layer);
  953. }
  954. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  955. {
  956. return turnsInfo[turn];
  957. }
  958. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  959. {
  960. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  961. }
  962. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
  963. {
  964. return turnsInfo[turn]->getMaxMovePoints(layer);
  965. }
  966. void CPathfinderHelper::getNeighbours(
  967. const TerrainTile & srcTile,
  968. const int3 & srcCoord,
  969. std::vector<int3> & vec,
  970. const boost::logic::tribool & onLand,
  971. const bool limitCoastSailing) const
  972. {
  973. CMap * map = gs->map;
  974. static const int3 dirs[] = {
  975. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  976. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  977. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  978. };
  979. for(const auto & dir : dirs)
  980. {
  981. const int3 destCoord = srcCoord + dir;
  982. if(!map->isInTheMap(destCoord))
  983. continue;
  984. const TerrainTile & destTile = map->getTile(destCoord);
  985. if(!destTile.terType->isPassable())
  986. continue;
  987. // //we cannot visit things from blocked tiles
  988. // if(srcTile.blocked && !srcTile.visitable && destTile.visitable && srcTile.blockingObjects.front()->ID != HEROI_TYPE)
  989. // {
  990. // continue;
  991. // }
  992. /// Following condition let us avoid diagonal movement over coast when sailing
  993. if(srcTile.terType->isWater() && limitCoastSailing && destTile.terType->isWater() && dir.x && dir.y) //diagonal move through water
  994. {
  995. const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
  996. const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
  997. if(map->getTile(horizontalNeighbour).terType->isLand() || map->getTile(verticalNeighbour).terType->isLand())
  998. continue;
  999. }
  1000. if(indeterminate(onLand) || onLand == destTile.terType->isLand())
  1001. {
  1002. vec.push_back(destCoord);
  1003. }
  1004. }
  1005. }
  1006. int CPathfinderHelper::getMovementCost(
  1007. const int3 & src,
  1008. const int3 & dst,
  1009. const TerrainTile * ct,
  1010. const TerrainTile * dt,
  1011. const int remainingMovePoints,
  1012. const bool checkLast,
  1013. boost::logic::tribool isDstSailLayer,
  1014. boost::logic::tribool isDstWaterLayer) const
  1015. {
  1016. if(src == dst) //same tile
  1017. return 0;
  1018. const auto * ti = getTurnInfo();
  1019. if(ct == nullptr || dt == nullptr)
  1020. {
  1021. ct = hero->cb->getTile(src);
  1022. dt = hero->cb->getTile(dst);
  1023. }
  1024. bool isSailLayer;
  1025. if(indeterminate(isDstSailLayer))
  1026. isSailLayer = hero->boat != nullptr && dt->terType->isWater();
  1027. else
  1028. isSailLayer = static_cast<bool>(isDstSailLayer);
  1029. bool isWaterLayer;
  1030. if(indeterminate(isDstWaterLayer))
  1031. isWaterLayer = dt->terType->isWater();
  1032. else
  1033. isWaterLayer = static_cast<bool>(isDstWaterLayer);
  1034. int ret = hero->getTileCost(*dt, *ct, ti);
  1035. if(isSailLayer)
  1036. {
  1037. if(ct->hasFavorableWinds())
  1038. ret = static_cast<int>(ret * 2.0 / 3);
  1039. }
  1040. else if(ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1041. vstd::amin(ret, GameConstants::BASE_MOVEMENT_COST + ti->valOfBonuses(Bonus::FLYING_MOVEMENT));
  1042. else if(isWaterLayer && ti->hasBonusOfType(Bonus::WATER_WALKING))
  1043. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0);
  1044. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  1045. {
  1046. int old = ret;
  1047. ret = static_cast<int>(ret * M_SQRT2);
  1048. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1049. // https://heroes.thelazy.net/index.php/Movement#Diagonal_move_exception
  1050. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1051. {
  1052. return remainingMovePoints;
  1053. }
  1054. }
  1055. const int left = remainingMovePoints - ret;
  1056. constexpr auto maxCostOfOneStep = static_cast<int>(175 * M_SQRT2); // diagonal move on Swamp - 247 MP
  1057. if(checkLast && left > 0 && left <= maxCostOfOneStep) //it might be the last tile - if no further move possible we take all move points
  1058. {
  1059. std::vector<int3> vec;
  1060. vec.reserve(8); //optimization
  1061. getNeighbours(*dt, dst, vec, ct->terType->isLand(), true);
  1062. for(const auto & elem : vec)
  1063. {
  1064. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  1065. if(fcost <= left)
  1066. {
  1067. return ret;
  1068. }
  1069. }
  1070. ret = remainingMovePoints;
  1071. }
  1072. return ret;
  1073. }
  1074. int3 CGPath::startPos() const
  1075. {
  1076. return nodes[nodes.size()-1].coord;
  1077. }
  1078. int3 CGPath::endPos() const
  1079. {
  1080. return nodes[0].coord;
  1081. }
  1082. CPathsInfo::CPathsInfo(const int3 & Sizes, const CGHeroInstance * hero_)
  1083. : sizes(Sizes), hero(hero_)
  1084. {
  1085. nodes.resize(boost::extents[ELayer::NUM_LAYERS][sizes.z][sizes.x][sizes.y]);
  1086. }
  1087. CPathsInfo::~CPathsInfo() = default;
  1088. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  1089. {
  1090. assert(vstd::iswithin(tile.x, 0, sizes.x));
  1091. assert(vstd::iswithin(tile.y, 0, sizes.y));
  1092. assert(vstd::iswithin(tile.z, 0, sizes.z));
  1093. return getNode(tile);
  1094. }
  1095. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  1096. {
  1097. out.nodes.clear();
  1098. const CGPathNode * curnode = getNode(dst);
  1099. if(!curnode->theNodeBefore)
  1100. return false;
  1101. while(curnode)
  1102. {
  1103. const CGPathNode cpn = * curnode;
  1104. curnode = curnode->theNodeBefore;
  1105. out.nodes.push_back(cpn);
  1106. }
  1107. return true;
  1108. }
  1109. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  1110. {
  1111. const auto * landNode = &nodes[ELayer::LAND][coord.z][coord.x][coord.y];
  1112. if(landNode->reachable())
  1113. return landNode;
  1114. else
  1115. return &nodes[ELayer::SAIL][coord.z][coord.x][coord.y];
  1116. }
  1117. PathNodeInfo::PathNodeInfo()
  1118. : node(nullptr), nodeObject(nullptr), tile(nullptr), coord(-1, -1, -1), guarded(false), isInitialPosition(false)
  1119. {
  1120. }
  1121. void PathNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1122. {
  1123. node = n;
  1124. if(coord != node->coord)
  1125. {
  1126. assert(node->coord.valid());
  1127. coord = node->coord;
  1128. tile = gs->getTile(coord);
  1129. nodeObject = tile->topVisitableObj();
  1130. if(nodeObject && nodeObject->ID == Obj::HERO)
  1131. {
  1132. nodeHero = dynamic_cast<const CGHeroInstance *>(nodeObject);
  1133. nodeObject = tile->topVisitableObj(true);
  1134. if(!nodeObject)
  1135. nodeObject = nodeHero;
  1136. }
  1137. else
  1138. {
  1139. nodeHero = nullptr;
  1140. }
  1141. }
  1142. guarded = false;
  1143. }
  1144. void PathNodeInfo::updateInfo(CPathfinderHelper * hlp, CGameState * gs)
  1145. {
  1146. if(gs->guardingCreaturePosition(node->coord).valid() && !isInitialPosition)
  1147. {
  1148. guarded = true;
  1149. }
  1150. if(nodeObject)
  1151. {
  1152. objectRelations = gs->getPlayerRelations(hlp->owner, nodeObject->tempOwner);
  1153. }
  1154. if(nodeHero)
  1155. {
  1156. heroRelations = gs->getPlayerRelations(hlp->owner, nodeHero->tempOwner);
  1157. }
  1158. }
  1159. CDestinationNodeInfo::CDestinationNodeInfo():
  1160. blocked(false),
  1161. action(CGPathNode::ENodeAction::UNKNOWN)
  1162. {
  1163. }
  1164. void CDestinationNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1165. {
  1166. PathNodeInfo::setNode(gs, n);
  1167. blocked = false;
  1168. action = CGPathNode::ENodeAction::UNKNOWN;
  1169. }
  1170. bool CDestinationNodeInfo::isBetterWay() const
  1171. {
  1172. if(node->turns == 0xff) //we haven't been here before
  1173. return true;
  1174. else
  1175. return cost < node->getCost(); //this route is faster
  1176. }
  1177. bool PathNodeInfo::isNodeObjectVisitable() const
  1178. {
  1179. /// Hero can't visit objects while walking on water or flying
  1180. return (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1181. && (canSeeObj(nodeObject) || canSeeObj(nodeHero));
  1182. }
  1183. VCMI_LIB_NAMESPACE_END