CPathfinder.cpp 16 KB

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