CPathfinder.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. #include "StdInc.h"
  2. #include "CPathfinder.h"
  3. #include "CHeroHandler.h"
  4. #include "mapping/CMap.h"
  5. #include "CGameState.h"
  6. #include "mapObjects/CGHeroInstance.h"
  7. #include "GameConstants.h"
  8. #include "CStopWatch.h"
  9. /*
  10. * CPathfinder.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. CPathfinder::PathfinderOptions::PathfinderOptions()
  19. {
  20. useFlying = false;
  21. useWaterWalking = false;
  22. useEmbarkAndDisembark = true;
  23. useTeleportTwoWay = true;
  24. useTeleportOneWay = true;
  25. useTeleportOneWayRandom = false;
  26. useTeleportWhirlpool = false;
  27. lightweightFlyingMode = false;
  28. }
  29. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero)
  30. : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero)
  31. {
  32. assert(hero);
  33. assert(hero == getHero(hero->id));
  34. out.hero = hero;
  35. out.hpos = hero->getPosition(false);
  36. if(!gs->map->isInTheMap(out.hpos)/* || !gs->map->isInTheMap(dest)*/) //check input
  37. {
  38. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  39. throw std::runtime_error("Wrong checksum");
  40. }
  41. if(hero->canFly())
  42. options.useFlying = true;
  43. if(hero->canWalkOnSea())
  44. options.useWaterWalking = true;
  45. if(CGWhirlpool::isProtected(hero))
  46. options.useTeleportWhirlpool = true;
  47. initializeGraph();
  48. neighbours.reserve(16);
  49. }
  50. void CPathfinder::calculatePaths()
  51. {
  52. int maxMovePointsLand = hero->maxMovePoints(true);
  53. int maxMovePointsWater = hero->maxMovePoints(false);
  54. auto maxMovePoints = [&](CGPathNode *cp) -> int
  55. {
  56. return cp->land ? maxMovePointsLand : maxMovePointsWater;
  57. };
  58. auto isBetterWay = [&](int remains, int turn) -> bool
  59. {
  60. if(dp->turns == 0xff) //we haven't been here before
  61. return true;
  62. else if(dp->turns > turn)
  63. return true;
  64. else if(dp->turns >= turn && dp->moveRemains < remains) //this route is faster
  65. return true;
  66. return false;
  67. };
  68. //logGlobal->infoStream() << boost::format("Calculating paths for hero %s (adress %d) of player %d") % hero->name % hero % hero->tempOwner;
  69. //initial tile - set cost on 0 and add to the queue
  70. CGPathNode *initialNode = out.getNode(out.hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  71. initialNode->turns = 0;
  72. initialNode->moveRemains = hero->movement;
  73. pq.push(initialNode);
  74. while(!pq.empty())
  75. {
  76. cp = pq.top();
  77. pq.pop();
  78. cp->locked = true;
  79. int movement = cp->moveRemains, turn = cp->turns;
  80. if(!movement)
  81. {
  82. movement = maxMovePoints(cp);
  83. turn++;
  84. }
  85. //add accessible neighbouring nodes to the queue
  86. addNeighbours(cp->coord);
  87. for(auto & neighbour : neighbours)
  88. {
  89. dt = &gs->map->getTile(neighbour);
  90. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  91. {
  92. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  93. dp = out.getNode(neighbour, i);
  94. if(dp->accessible == CGPathNode::NOT_SET)
  95. continue;
  96. if(dp->locked)
  97. continue;
  98. if(cp->layer != i && !isLayerTransitionPossible())
  99. continue;
  100. if(!isMovementToDestPossible())
  101. continue;
  102. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  103. int remains = movement - cost;
  104. if(useEmbarkCost)
  105. {
  106. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  107. cost = movement - remains;
  108. }
  109. int turnAtNextTile = turn;
  110. if(remains < 0)
  111. {
  112. //occurs rarely, when hero with low movepoints tries to leave the road
  113. turnAtNextTile++;
  114. int moveAtNextTile = maxMovePoints(cp);
  115. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  116. remains = moveAtNextTile - cost;
  117. }
  118. if(isBetterWay(remains, turnAtNextTile))
  119. {
  120. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  121. dp->moveRemains = remains;
  122. dp->turns = turnAtNextTile;
  123. dp->theNodeBefore = cp;
  124. if(isMovementAfterDestPossible())
  125. pq.push(dp);
  126. }
  127. }
  128. } //neighbours loop
  129. //just add all passable teleport exits
  130. if(sTileObj && canVisitObject())
  131. {
  132. addTeleportExits();
  133. for(auto & neighbour : neighbours)
  134. {
  135. dp = out.getNode(neighbour, cp->layer);
  136. if(dp->locked)
  137. continue;
  138. if(isBetterWay(movement, turn))
  139. {
  140. dp->moveRemains = movement;
  141. dp->turns = turn;
  142. dp->theNodeBefore = cp;
  143. pq.push(dp);
  144. }
  145. }
  146. }
  147. } //queue loop
  148. }
  149. void CPathfinder::addNeighbours(const int3 &coord)
  150. {
  151. neighbours.clear();
  152. ct = &gs->map->getTile(coord);
  153. std::vector<int3> tiles;
  154. gs->getNeighbours(*ct, coord, tiles, boost::logic::indeterminate, !cp->land);
  155. sTileObj = ct->topVisitableObj(coord == out.hpos);
  156. if(canVisitObject())
  157. {
  158. if(sTileObj)
  159. {
  160. for(int3 tile: tiles)
  161. {
  162. if(canMoveBetween(tile, sTileObj->visitablePos()))
  163. neighbours.push_back(tile);
  164. }
  165. }
  166. else
  167. vstd::concatenate(neighbours, tiles);
  168. }
  169. else
  170. vstd::concatenate(neighbours, tiles);
  171. }
  172. void CPathfinder::addTeleportExits(bool noTeleportExcludes)
  173. {
  174. assert(sTileObj);
  175. neighbours.clear();
  176. auto isAllowedTeleportEntrance = [&](const CGTeleport * obj) -> bool
  177. {
  178. if(!gs->isTeleportEntrancePassable(obj, hero->tempOwner))
  179. return false;
  180. if(noTeleportExcludes)
  181. return true;
  182. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  183. if(whirlpool)
  184. {
  185. if(addTeleportWhirlpool(whirlpool))
  186. return true;
  187. }
  188. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  189. return true;
  190. return false;
  191. };
  192. const CGTeleport *sTileTeleport = dynamic_cast<const CGTeleport *>(sTileObj);
  193. if(isAllowedTeleportEntrance(sTileTeleport))
  194. {
  195. for(auto objId : gs->getTeleportChannelExits(sTileTeleport->channel, hero->tempOwner))
  196. {
  197. auto obj = getObj(objId);
  198. if(CGTeleport::isExitPassable(gs, hero, obj))
  199. neighbours.push_back(obj->visitablePos());
  200. }
  201. }
  202. }
  203. bool CPathfinder::isLayerTransitionPossible()
  204. {
  205. if((cp->layer == EPathfindingLayer::AIR || cp->layer == EPathfindingLayer::WATER)
  206. && dp->layer != EPathfindingLayer::LAND)
  207. {
  208. return false;
  209. }
  210. else if(cp->layer == EPathfindingLayer::LAND && dp->layer == EPathfindingLayer::AIR)
  211. {
  212. if(options.lightweightFlyingMode && !isSourceInitialPosition())
  213. return false;
  214. }
  215. else if(cp->layer == EPathfindingLayer::SAIL && dp->layer != EPathfindingLayer::LAND)
  216. return false;
  217. else if(cp->layer == EPathfindingLayer::SAIL && dp->layer == EPathfindingLayer::LAND)
  218. {
  219. if(!dt->isCoastal())
  220. return false;
  221. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  222. if((dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  223. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  224. return false;
  225. useEmbarkCost = 2;
  226. }
  227. else if(cp->layer == EPathfindingLayer::LAND && dp->layer == EPathfindingLayer::SAIL)
  228. {
  229. Obj destTopVisObjID = dt->topVisitableId();
  230. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  231. return false;
  232. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  233. return false;
  234. if(destTopVisObjID == Obj::BOAT)
  235. useEmbarkCost = 1;
  236. }
  237. return true;
  238. }
  239. bool CPathfinder::isMovementToDestPossible()
  240. {
  241. switch(dp->layer)
  242. {
  243. case EPathfindingLayer::LAND:
  244. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED)
  245. return false;
  246. if(isSourceGuarded() && !isDestinationGuardian()) // Can step into tile of guard
  247. return false;
  248. break;
  249. case EPathfindingLayer::SAIL:
  250. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED)
  251. return false;
  252. if(isSourceGuarded() && !isDestinationGuardian()) // Can step into tile of guard
  253. return false;
  254. break;
  255. case EPathfindingLayer::AIR:
  256. //if(!canMoveBetween(cp->coord, dp->coord))
  257. // return false;
  258. break;
  259. case EPathfindingLayer::WATER:
  260. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible != CGPathNode::ACCESSIBLE)
  261. return false;
  262. if(isDestinationGuarded())
  263. return false;
  264. break;
  265. }
  266. return true;
  267. }
  268. bool CPathfinder::isMovementAfterDestPossible()
  269. {
  270. switch(dp->layer)
  271. {
  272. case EPathfindingLayer::LAND:
  273. case EPathfindingLayer::SAIL:
  274. if(dp->accessible == CGPathNode::ACCESSIBLE)
  275. return true;
  276. if(dp->coord == out.hpos)
  277. return true; // This one is tricky, we can ignore fact that tile is not ACCESSIBLE in case if it's our hero block it. Though this need investigation
  278. if(dp->accessible == CGPathNode::VISITABLE && CGTeleport::isTeleport(dt->topVisitableObj()))
  279. {
  280. /// For now we'll always allow transit over teleporters
  281. /// Transit over whirlpools only allowed when hero protected
  282. auto whirlpool = dynamic_cast<const CGWhirlpool *>(dt->topVisitableObj());
  283. if(!whirlpool || options.useTeleportWhirlpool)
  284. return true;
  285. }
  286. if(useEmbarkCost && options.useEmbarkAndDisembark)
  287. return true;
  288. break;
  289. case EPathfindingLayer::AIR:
  290. case EPathfindingLayer::WATER:
  291. return true;
  292. break;
  293. }
  294. return false;
  295. }
  296. bool CPathfinder::isSourceInitialPosition()
  297. {
  298. return cp->coord == out.hpos;
  299. }
  300. int3 CPathfinder::getSourceGuardPosition()
  301. {
  302. return gs->map->guardingCreaturePositions[cp->coord.x][cp->coord.y][cp->coord.z];
  303. }
  304. bool CPathfinder::isSourceGuarded()
  305. {
  306. //map can start with hero on guarded tile or teleport there using dimension door
  307. //so threat tile hero standing on like it's not guarded because it's should be possible to move out of here
  308. if(getSourceGuardPosition() != int3(-1, -1, -1) && !isSourceInitialPosition())
  309. {
  310. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  311. if(cp->accessible != CGPathNode::VISITABLE
  312. || !cp->theNodeBefore->land
  313. || ct->topVisitableId() != Obj::BOAT)
  314. {
  315. return true;
  316. }
  317. }
  318. return false;
  319. }
  320. bool CPathfinder::isDestinationGuarded()
  321. {
  322. if(gs->map->guardingCreaturePositions[dp->coord.x][dp->coord.y][dp->coord.z].valid()
  323. && dp->accessible == CGPathNode::BLOCKVIS)
  324. {
  325. return true;
  326. }
  327. return false;
  328. }
  329. bool CPathfinder::isDestinationGuardian()
  330. {
  331. return getSourceGuardPosition() == dp->coord;
  332. }
  333. void CPathfinder::initializeGraph()
  334. {
  335. auto updateNode = [&](int3 pos, EPathfindingLayer layer, const TerrainTile *tinfo)
  336. {
  337. auto node = out.getNode(pos, layer);
  338. node->reset();
  339. node->accessible = evaluateAccessibility(pos, tinfo);
  340. node->land = tinfo->terType != ETerrainType::WATER;
  341. };
  342. int3 pos;
  343. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  344. {
  345. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  346. {
  347. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  348. {
  349. const TerrainTile *tinfo = &gs->map->getTile(pos);
  350. switch(tinfo->terType)
  351. {
  352. case ETerrainType::ROCK:
  353. break;
  354. case ETerrainType::WATER:
  355. updateNode(pos, EPathfindingLayer::SAIL, tinfo);
  356. if(options.useFlying)
  357. updateNode(pos, EPathfindingLayer::AIR, tinfo);
  358. if(options.useWaterWalking)
  359. updateNode(pos, EPathfindingLayer::WATER, tinfo);
  360. break;
  361. default:
  362. updateNode(pos, EPathfindingLayer::LAND, tinfo);
  363. if(options.useFlying)
  364. updateNode(pos, EPathfindingLayer::AIR, tinfo);
  365. break;
  366. }
  367. }
  368. }
  369. }
  370. }
  371. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 &pos, const TerrainTile *tinfo) const
  372. {
  373. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  374. if(tinfo->terType == ETerrainType::ROCK || !isVisible(pos, hero->tempOwner))
  375. return CGPathNode::BLOCKED;
  376. if(tinfo->visitable)
  377. {
  378. if(tinfo->visitableObjects.front()->ID == Obj::SANCTUARY && tinfo->visitableObjects.back()->ID == Obj::HERO && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  379. {
  380. return CGPathNode::BLOCKED;
  381. }
  382. else
  383. {
  384. for(const CGObjectInstance *obj : tinfo->visitableObjects)
  385. {
  386. if(obj->passableFor(hero->tempOwner))
  387. {
  388. ret = CGPathNode::ACCESSIBLE;
  389. }
  390. else if(obj->blockVisit)
  391. {
  392. return CGPathNode::BLOCKVIS;
  393. }
  394. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  395. {
  396. ret = CGPathNode::VISITABLE;
  397. }
  398. }
  399. }
  400. }
  401. else if(gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z].valid()
  402. && !tinfo->blocked)
  403. {
  404. // Monster close by; blocked visit for battle.
  405. return CGPathNode::BLOCKVIS;
  406. }
  407. return ret;
  408. }
  409. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  410. {
  411. return gs->checkForVisitableDir(a, b);
  412. }
  413. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  414. {
  415. return options.useTeleportTwoWay && gs->isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  416. }
  417. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  418. {
  419. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  420. {
  421. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  422. if(passableExits.size() == 1)
  423. return true;
  424. }
  425. return false;
  426. }
  427. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  428. {
  429. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  430. {
  431. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  432. if(passableExits.size() > 1)
  433. return true;
  434. }
  435. return false;
  436. }
  437. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  438. {
  439. return options.useTeleportWhirlpool && obj;
  440. }
  441. bool CPathfinder::canVisitObject() const
  442. {
  443. //hero can't visit objects while walking on water or flying
  444. return cp->layer == EPathfindingLayer::LAND || cp->layer == EPathfindingLayer::SAIL;
  445. }
  446. CGPathNode::CGPathNode(int3 Coord, EPathfindingLayer Layer)
  447. : coord(Coord), layer(Layer)
  448. {
  449. reset();
  450. }
  451. void CGPathNode::reset()
  452. {
  453. locked = false;
  454. accessible = NOT_SET;
  455. land = 0;
  456. moveRemains = 0;
  457. turns = 255;
  458. theNodeBefore = nullptr;
  459. }
  460. bool CGPathNode::reachable() const
  461. {
  462. return turns < 255;
  463. }
  464. int3 CGPath::startPos() const
  465. {
  466. return nodes[nodes.size()-1].coord;
  467. }
  468. int3 CGPath::endPos() const
  469. {
  470. return nodes[0].coord;
  471. }
  472. void CGPath::convert(ui8 mode)
  473. {
  474. if(mode==0)
  475. {
  476. for(auto & elem : nodes)
  477. {
  478. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  479. }
  480. }
  481. }
  482. CPathsInfo::CPathsInfo(const int3 &Sizes)
  483. : sizes(Sizes)
  484. {
  485. hero = nullptr;
  486. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS]);
  487. for(int i = 0; i < sizes.x; i++)
  488. for(int j = 0; j < sizes.y; j++)
  489. for(int z = 0; z < sizes.z; z++)
  490. for(int l = 0; l < EPathfindingLayer::NUM_LAYERS; l++)
  491. nodes[i][j][z][l] = new CGPathNode(int3(i, j, z), static_cast<EPathfindingLayer>(l));
  492. }
  493. CPathsInfo::~CPathsInfo()
  494. {
  495. }
  496. const CGPathNode * CPathsInfo::getPathInfo(const int3 &tile, const EPathfindingLayer &layer) const
  497. {
  498. boost::unique_lock<boost::mutex> pathLock(pathMx);
  499. if(tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z || layer >= EPathfindingLayer::NUM_LAYERS)
  500. return nullptr;
  501. return getNode(tile, layer);
  502. }
  503. bool CPathsInfo::getPath(CGPath &out, const int3 &dst, const EPathfindingLayer &layer) const
  504. {
  505. boost::unique_lock<boost::mutex> pathLock(pathMx);
  506. out.nodes.clear();
  507. const CGPathNode *curnode = getNode(dst, layer);
  508. if(!curnode->theNodeBefore)
  509. return false;
  510. while(curnode)
  511. {
  512. CGPathNode cpn = *curnode;
  513. curnode = curnode->theNodeBefore;
  514. out.nodes.push_back(cpn);
  515. }
  516. return true;
  517. }
  518. int CPathsInfo::getDistance(const int3 &tile, const EPathfindingLayer &layer) const
  519. {
  520. boost::unique_lock<boost::mutex> pathLock(pathMx);
  521. CGPath ret;
  522. if(getPath(ret, tile, layer))
  523. return ret.nodes.size();
  524. else
  525. return 255;
  526. }
  527. CGPathNode *CPathsInfo::getNode(const int3 &coord, const EPathfindingLayer &layer) const
  528. {
  529. if(layer != EPathfindingLayer::AUTO)
  530. return nodes[coord.x][coord.y][coord.z][layer];
  531. auto landNode = nodes[coord.x][coord.y][coord.z][EPathfindingLayer::LAND];
  532. if(landNode->theNodeBefore)
  533. return landNode;
  534. else
  535. return nodes[coord.x][coord.y][coord.z][EPathfindingLayer::SAIL];
  536. }