CPathfinder.cpp 17 KB

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