CPathfinder.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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 "INodeStorage.h"
  13. #include "PathfinderOptions.h"
  14. #include "PathfindingRules.h"
  15. #include "TurnInfo.h"
  16. #include "../gameState/CGameState.h"
  17. #include "../CPlayerState.h"
  18. #include "../TerrainHandler.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../mapObjects/CGTownInstance.h"
  21. #include "../mapObjects/MiscObjects.h"
  22. #include "../mapping/CMap.h"
  23. #include "spells/CSpellHandler.h"
  24. VCMI_LIB_NAMESPACE_BEGIN
  25. bool CPathfinderHelper::canMoveFromNode(const PathNodeInfo & source) const
  26. {
  27. // we can always make the first step, even when standing on object
  28. if(source.node->theNodeBefore == nullptr)
  29. return true;
  30. if (!source.nodeObject)
  31. return true;
  32. if (!source.isNodeObjectVisitable())
  33. return true;
  34. // we can always move from visitable object if hero has teleported here (e.g. went through monolith)
  35. if (source.node->isTeleportAction())
  36. return true;
  37. // we can not go through teleporters since moving onto a teleport will teleport hero and may invalidate path (e.g. one-way teleport or enemy hero on other side)
  38. if (dynamic_cast<const CGTeleport*>(source.nodeObject) != nullptr)
  39. return false;
  40. return true;
  41. }
  42. void CPathfinderHelper::calculateNeighbourTiles(NeighbourTilesVector & result, const PathNodeInfo & source) const
  43. {
  44. result.clear();
  45. if (!canMoveFromNode(source))
  46. return;
  47. getNeighbours(
  48. *source.tile,
  49. source.node->coord,
  50. result,
  51. boost::logic::indeterminate,
  52. source.node->layer == EPathfindingLayer::SAIL);
  53. if(source.isNodeObjectVisitable())
  54. {
  55. vstd::erase_if(result, [&](const int3 & tile) -> bool
  56. {
  57. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  58. });
  59. }
  60. }
  61. CPathfinder::CPathfinder(CGameState * _gs, std::shared_ptr<PathfinderConfig> config):
  62. gamestate(_gs),
  63. config(std::move(config))
  64. {
  65. initializeGraph();
  66. }
  67. void CPathfinder::push(CGPathNode * node)
  68. {
  69. if(node && !node->inPQ())
  70. {
  71. node->pq = &this->pq;
  72. auto handle = pq.push(node);
  73. node->pqHandle = handle;
  74. }
  75. }
  76. CGPathNode * CPathfinder::topAndPop()
  77. {
  78. auto * node = pq.top();
  79. pq.pop();
  80. node->pq = nullptr;
  81. return node;
  82. }
  83. void CPathfinder::calculatePaths()
  84. {
  85. //logGlobal->info("Calculating paths for hero %s (address %d) of player %d", hero->name, hero , hero->tempOwner);
  86. //initial tile - set cost on 0 and add to the queue
  87. std::vector<CGPathNode *> initialNodes = config->nodeStorage->getInitialNodes();
  88. int counter = 0;
  89. for(auto * initialNode : initialNodes)
  90. {
  91. if(!gamestate->isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
  92. {
  93. logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
  94. throw std::runtime_error("Wrong checksum");
  95. }
  96. source.setNode(gamestate, initialNode);
  97. auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  98. if(hlp->isHeroPatrolLocked())
  99. continue;
  100. pq.push(initialNode);
  101. }
  102. std::vector<CGPathNode *> neighbourNodes;
  103. while(!pq.empty())
  104. {
  105. counter++;
  106. auto * node = topAndPop();
  107. source.setNode(gamestate, node);
  108. source.node->locked = true;
  109. int movement = source.node->moveRemains;
  110. uint8_t turn = source.node->turns;
  111. float cost = source.node->getCost();
  112. auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  113. hlp->updateTurnInfo(turn);
  114. if(movement == 0)
  115. {
  116. hlp->updateTurnInfo(++turn);
  117. movement = hlp->getMaxMovePoints(source.node->layer);
  118. if(!hlp->passOneTurnLimitCheck(source))
  119. continue;
  120. if(turn > hlp->options.turnLimit)
  121. continue;
  122. }
  123. source.isInitialPosition = source.nodeHero == hlp->hero;
  124. source.updateInfo(hlp, gamestate);
  125. //add accessible neighbouring nodes to the queue
  126. for(EPathfindingLayer layer = EPathfindingLayer::LAND; layer < EPathfindingLayer::NUM_LAYERS; layer.advance(1))
  127. {
  128. if(!hlp->isLayerAvailable(layer))
  129. continue;
  130. config->nodeStorage->calculateNeighbours(neighbourNodes, source, layer, config.get(), hlp);
  131. for(CGPathNode * neighbour : neighbourNodes)
  132. {
  133. if(neighbour->locked)
  134. continue;
  135. destination.setNode(gamestate, neighbour);
  136. hlp = config->getOrCreatePathfinderHelper(destination, gamestate);
  137. if(!hlp->isPatrolMovementAllowed(neighbour->coord))
  138. continue;
  139. /// Check transition without tile accessibility rules
  140. if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
  141. continue;
  142. destination.turn = turn;
  143. destination.movementLeft = movement;
  144. destination.cost = cost;
  145. destination.updateInfo(hlp, gamestate);
  146. destination.isGuardianTile = destination.guarded && isDestinationGuardian();
  147. for(const auto & rule : config->rules)
  148. {
  149. rule->process(source, destination, config.get(), hlp);
  150. if(destination.blocked)
  151. break;
  152. }
  153. if(!destination.blocked)
  154. push(destination.node);
  155. } //neighbours loop
  156. }
  157. //just add all passable teleport exits
  158. hlp = config->getOrCreatePathfinderHelper(source, gamestate);
  159. /// For now we disable teleports usage for patrol movement
  160. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  161. if(hlp->patrolState == CPathfinderHelper::PATROL_RADIUS)
  162. continue;
  163. auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp);
  164. for(CGPathNode * teleportNode : teleportationNodes)
  165. {
  166. if(teleportNode->locked)
  167. continue;
  168. /// TODO: We may consider use invisible exits on FoW border in future
  169. /// Useful for AI when at least one tile around exit is visible and passable
  170. /// Objects are usually visible on FoW border anyway so it's not cheating.
  171. ///
  172. /// For now it's disabled as it's will cause crashes in movement code.
  173. if(teleportNode->accessible == EPathAccessibility::BLOCKED)
  174. continue;
  175. destination.setNode(gamestate, teleportNode);
  176. destination.turn = turn;
  177. destination.movementLeft = movement;
  178. destination.cost = cost;
  179. if(destination.isBetterWay())
  180. {
  181. destination.action = getTeleportDestAction();
  182. config->nodeStorage->commit(destination, source);
  183. if(destination.node->action == EPathNodeAction::TELEPORT_NORMAL)
  184. push(destination.node);
  185. }
  186. }
  187. } //queue loop
  188. logAi->trace("CPathfinder finished with %s iterations", std::to_string(counter));
  189. }
  190. TeleporterTilesVector CPathfinderHelper::getAllowedTeleportChannelExits(const TeleportChannelID & channelID) const
  191. {
  192. TeleporterTilesVector allowedExits;
  193. for(const auto & objId : getTeleportChannelExits(channelID, hero->tempOwner))
  194. {
  195. const auto * obj = getObj(objId);
  196. if(dynamic_cast<const CGWhirlpool *>(obj))
  197. {
  198. auto pos = obj->getBlockedPos();
  199. for(const auto & p : pos)
  200. {
  201. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  202. allowedExits.push_back(p);
  203. }
  204. }
  205. else if(obj && CGTeleport::isExitPassable(gs, hero, obj))
  206. allowedExits.push_back(obj->visitablePos());
  207. }
  208. return allowedExits;
  209. }
  210. TeleporterTilesVector CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  211. {
  212. TeleporterTilesVector allowedExits;
  213. for(const auto & town : getPlayerState(hero->tempOwner)->getTowns())
  214. {
  215. if(town->id != source.nodeObject->id && town->visitingHero == nullptr
  216. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  217. {
  218. allowedExits.push_back(town->visitablePos());
  219. }
  220. }
  221. return allowedExits;
  222. }
  223. TeleporterTilesVector CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
  224. {
  225. TeleporterTilesVector teleportationExits;
  226. const auto * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
  227. if(isAllowedTeleportEntrance(objTeleport))
  228. {
  229. for(const auto & exit : getAllowedTeleportChannelExits(objTeleport->channel))
  230. {
  231. teleportationExits.push_back(exit);
  232. }
  233. }
  234. else if(options.useCastleGate && source.nodeObject->ID == Obj::TOWN && source.objectRelations != PlayerRelations::ENEMIES)
  235. {
  236. auto * town = dynamic_cast<const CGTownInstance *>(source.nodeObject);
  237. assert(town);
  238. if (town && town->getFactionID() == FactionID::INFERNO)
  239. {
  240. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  241. /// This may be handy if we allow to use teleportation to friendly towns
  242. for(const auto & exit : getCastleGates(source))
  243. {
  244. teleportationExits.push_back(exit);
  245. }
  246. }
  247. }
  248. return teleportationExits;
  249. }
  250. bool CPathfinderHelper::isHeroPatrolLocked() const
  251. {
  252. return patrolState == PATROL_LOCKED;
  253. }
  254. bool CPathfinderHelper::isPatrolMovementAllowed(const int3 & dst) const
  255. {
  256. if(patrolState == PATROL_RADIUS)
  257. {
  258. if(!vstd::contains(patrolTiles, dst))
  259. return false;
  260. }
  261. return true;
  262. }
  263. bool CPathfinder::isLayerTransitionPossible() const
  264. {
  265. ELayer destLayer = destination.node->layer;
  266. /// No layer transition allowed when previous node action is BATTLE
  267. if(!config->options.allowLayerTransitioningAfterBattle && source.node->action == EPathNodeAction::BATTLE)
  268. return false;
  269. switch(source.node->layer.toEnum())
  270. {
  271. case ELayer::LAND:
  272. if(destLayer == ELayer::AIR)
  273. {
  274. if(!config->options.lightweightFlyingMode || source.isInitialPosition)
  275. return true;
  276. }
  277. else if(destLayer == ELayer::SAIL)
  278. {
  279. if(destination.tile->isWater())
  280. return true;
  281. }
  282. else
  283. return true;
  284. break;
  285. case ELayer::SAIL:
  286. if(destLayer == ELayer::LAND && !destination.tile->isWater())
  287. return true;
  288. break;
  289. case ELayer::AIR:
  290. if(destLayer == ELayer::LAND)
  291. return true;
  292. break;
  293. case ELayer::WATER:
  294. if(destLayer == ELayer::LAND)
  295. return true;
  296. break;
  297. }
  298. return false;
  299. }
  300. EPathNodeAction CPathfinder::getTeleportDestAction() const
  301. {
  302. EPathNodeAction action = EPathNodeAction::TELEPORT_NORMAL;
  303. if(destination.isNodeObjectVisitable() && destination.nodeHero)
  304. {
  305. if(destination.heroRelations == PlayerRelations::ENEMIES)
  306. action = EPathNodeAction::TELEPORT_BATTLE;
  307. else
  308. action = EPathNodeAction::TELEPORT_BLOCKING_VISIT;
  309. }
  310. return action;
  311. }
  312. bool CPathfinder::isDestinationGuardian() const
  313. {
  314. return gamestate->guardingCreaturePosition(destination.node->coord) == destination.node->coord;
  315. }
  316. void CPathfinderHelper::initializePatrol()
  317. {
  318. auto state = PATROL_NONE;
  319. if(hero->patrol.patrolling && !getPlayerState(hero->tempOwner)->human)
  320. {
  321. if(hero->patrol.patrolRadius)
  322. {
  323. state = PATROL_RADIUS;
  324. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, ETileVisibility::REVEALED, std::optional<PlayerColor>(), int3::DIST_MANHATTAN);
  325. }
  326. else
  327. state = PATROL_LOCKED;
  328. }
  329. patrolState = state;
  330. }
  331. void CPathfinder::initializeGraph()
  332. {
  333. INodeStorage * nodeStorage = config->nodeStorage.get();
  334. nodeStorage->initialize(config->options, gamestate);
  335. }
  336. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  337. {
  338. return gs->checkForVisitableDir(a, b);
  339. }
  340. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  341. {
  342. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  343. return false;
  344. const auto * whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  345. if(whirlpool)
  346. {
  347. if(addTeleportWhirlpool(whirlpool))
  348. return true;
  349. }
  350. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  351. return true;
  352. return false;
  353. }
  354. bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
  355. {
  356. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  357. }
  358. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  359. {
  360. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  361. {
  362. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  363. if(passableExits.size() == 1)
  364. return true;
  365. }
  366. return false;
  367. }
  368. bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
  369. {
  370. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  371. {
  372. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  373. if(passableExits.size() > 1)
  374. return true;
  375. }
  376. return false;
  377. }
  378. bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
  379. {
  380. return options.useTeleportWhirlpool && (whirlpoolProtection || options.forceUseTeleportWhirlpool) && obj;
  381. }
  382. int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
  383. {
  384. return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
  385. }
  386. bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
  387. {
  388. if(!options.oneTurnSpecialLayersLimit)
  389. return true;
  390. if(source.node->layer == EPathfindingLayer::WATER)
  391. return false;
  392. if(source.node->layer == EPathfindingLayer::AIR)
  393. {
  394. return options.originalFlyRules && source.node->accessible == EPathAccessibility::ACCESSIBLE;
  395. }
  396. return true;
  397. }
  398. int CPathfinderHelper::getGuardiansCount(int3 tile) const
  399. {
  400. return getGuardingCreatures(tile).size();
  401. }
  402. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options):
  403. CGameInfoCallback(gs),
  404. turn(-1),
  405. hero(Hero),
  406. options(Options),
  407. owner(Hero->tempOwner)
  408. {
  409. turnsInfo.reserve(16);
  410. updateTurnInfo();
  411. initializePatrol();
  412. whirlpoolProtection = Hero->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION);
  413. SpellID flySpell = SpellID::FLY;
  414. canCastFly = Hero->canCastThisSpell(flySpell.toSpell());
  415. SpellID waterWalk = SpellID::WATER_WALK;
  416. canCastWaterWalk = Hero->canCastThisSpell(waterWalk.toSpell());
  417. }
  418. CPathfinderHelper::~CPathfinderHelper()
  419. {
  420. for(auto * ti : turnsInfo)
  421. delete ti;
  422. }
  423. void CPathfinderHelper::updateTurnInfo(const int Turn)
  424. {
  425. if(turn != Turn)
  426. {
  427. turn = Turn;
  428. if(turn >= turnsInfo.size())
  429. {
  430. auto * ti = new TurnInfo(hero, turn);
  431. turnsInfo.push_back(ti);
  432. }
  433. }
  434. }
  435. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
  436. {
  437. switch(layer.toEnum())
  438. {
  439. case EPathfindingLayer::AIR:
  440. if(!options.useFlying)
  441. return false;
  442. if(canCastFly && options.canUseCast)
  443. return true;
  444. break;
  445. case EPathfindingLayer::WATER:
  446. if(!options.useWaterWalking)
  447. return false;
  448. if(canCastWaterWalk && options.canUseCast)
  449. return true;
  450. break;
  451. }
  452. return turnsInfo[turn]->isLayerAvailable(layer);
  453. }
  454. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  455. {
  456. return turnsInfo[turn];
  457. }
  458. bool CPathfinderHelper::hasBonusOfType(const BonusType type) const
  459. {
  460. return turnsInfo[turn]->hasBonusOfType(type);
  461. }
  462. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
  463. {
  464. return turnsInfo[turn]->getMaxMovePoints(layer);
  465. }
  466. void CPathfinderHelper::getNeighbours(
  467. const TerrainTile & srcTile,
  468. const int3 & srcCoord,
  469. NeighbourTilesVector & vec,
  470. const boost::logic::tribool & onLand,
  471. const bool limitCoastSailing) const
  472. {
  473. CMap * map = gs->map;
  474. static const int3 dirs[] = {
  475. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  476. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  477. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  478. };
  479. for(const auto & dir : dirs)
  480. {
  481. const int3 destCoord = srcCoord + dir;
  482. if(!map->isInTheMap(destCoord))
  483. continue;
  484. const TerrainTile & destTile = map->getTile(destCoord);
  485. const TerrainType* terrain = destTile.getTerrain();
  486. if(!terrain->isPassable())
  487. continue;
  488. /// Following condition let us avoid diagonal movement over coast when sailing
  489. if(srcTile.isWater() && limitCoastSailing && terrain->isWater() && dir.x && dir.y) //diagonal move through water
  490. {
  491. const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
  492. const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
  493. if(map->getTile(horizontalNeighbour).isLand() || map->getTile(verticalNeighbour).isLand())
  494. continue;
  495. }
  496. if(indeterminate(onLand) || onLand == terrain->isLand())
  497. {
  498. vec.push_back(destCoord);
  499. }
  500. }
  501. }
  502. int CPathfinderHelper::getMovementCost(
  503. const PathNodeInfo & src,
  504. const PathNodeInfo & dst,
  505. const int remainingMovePoints,
  506. const bool checkLast) const
  507. {
  508. return getMovementCost(
  509. src.coord,
  510. dst.coord,
  511. src.tile,
  512. dst.tile,
  513. remainingMovePoints,
  514. checkLast,
  515. dst.node->layer == EPathfindingLayer::SAIL,
  516. dst.node->layer == EPathfindingLayer::WATER
  517. );
  518. }
  519. int CPathfinderHelper::getMovementCost(
  520. const int3 & src,
  521. const int3 & dst,
  522. const TerrainTile * ct,
  523. const TerrainTile * dt,
  524. const int remainingMovePoints,
  525. const bool checkLast,
  526. boost::logic::tribool isDstSailLayer,
  527. boost::logic::tribool isDstWaterLayer) const
  528. {
  529. if(src == dst) //same tile
  530. return 0;
  531. const auto * ti = getTurnInfo();
  532. if(ct == nullptr || dt == nullptr)
  533. {
  534. ct = hero->cb->getTile(src);
  535. dt = hero->cb->getTile(dst);
  536. }
  537. bool isSailLayer;
  538. if(indeterminate(isDstSailLayer))
  539. isSailLayer = hero->boat && hero->boat->layer == EPathfindingLayer::SAIL && dt->isWater();
  540. else
  541. isSailLayer = static_cast<bool>(isDstSailLayer);
  542. bool isWaterLayer;
  543. if(indeterminate(isDstWaterLayer))
  544. isWaterLayer = ((hero->boat && hero->boat->layer == EPathfindingLayer::WATER) || ti->hasBonusOfType(BonusType::WATER_WALKING)) && dt->isWater();
  545. else
  546. isWaterLayer = static_cast<bool>(isDstWaterLayer);
  547. bool isAirLayer = (hero->boat && hero->boat->layer == EPathfindingLayer::AIR) || ti->hasBonusOfType(BonusType::FLYING_MOVEMENT);
  548. int ret = hero->getTileMovementCost(*dt, *ct, ti);
  549. if(isSailLayer)
  550. {
  551. if(ct->hasFavorableWinds())
  552. ret = static_cast<int>(ret * 2.0 / 3);
  553. }
  554. else if(isAirLayer)
  555. vstd::amin(ret, GameConstants::BASE_MOVEMENT_COST + ti->valOfBonuses(BonusType::FLYING_MOVEMENT));
  556. else if(isWaterLayer && ti->hasBonusOfType(BonusType::WATER_WALKING))
  557. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(BonusType::WATER_WALKING)) / 100.0);
  558. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  559. {
  560. int old = ret;
  561. ret = static_cast<int>(ret * M_SQRT2);
  562. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  563. // https://heroes.thelazy.net/index.php/Movement#Diagonal_move_exception
  564. if(ret > remainingMovePoints && remainingMovePoints >= old)
  565. {
  566. return remainingMovePoints;
  567. }
  568. }
  569. const int left = remainingMovePoints - ret;
  570. constexpr auto maxCostOfOneStep = static_cast<int>(175 * M_SQRT2); // diagonal move on Swamp - 247 MP
  571. if(checkLast && left > 0 && left <= maxCostOfOneStep) //it might be the last tile - if no further move possible we take all move points
  572. {
  573. NeighbourTilesVector vec;
  574. getNeighbours(*dt, dst, vec, ct->isLand(), true);
  575. for(const auto & elem : vec)
  576. {
  577. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  578. if(fcost <= left)
  579. {
  580. return ret;
  581. }
  582. }
  583. ret = remainingMovePoints;
  584. }
  585. return ret;
  586. }
  587. VCMI_LIB_NAMESPACE_END