CPathfinder.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. useCastleGate = false;
  28. lightweightFlyingMode = false;
  29. oneTurnSpecialLayersLimit = true;
  30. }
  31. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero)
  32. : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero)
  33. {
  34. assert(hero);
  35. assert(hero == getHero(hero->id));
  36. out.hero = hero;
  37. out.hpos = hero->getPosition(false);
  38. if(!gs->map->isInTheMap(out.hpos)/* || !gs->map->isInTheMap(dest)*/) //check input
  39. {
  40. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  41. throw std::runtime_error("Wrong checksum");
  42. }
  43. if(hero->getBonusAtTurn(Bonus::FLYING_MOVEMENT))
  44. options.useFlying = true;
  45. if(hero->getBonusAtTurn(Bonus::WATER_WALKING))
  46. options.useWaterWalking = true;
  47. if(CGWhirlpool::isProtected(hero))
  48. options.useTeleportWhirlpool = true;
  49. initializeGraph();
  50. neighbours.reserve(16);
  51. }
  52. void CPathfinder::calculatePaths()
  53. {
  54. int maxMovePointsLand = hero->maxMovePoints(true);
  55. int maxMovePointsWater = hero->maxMovePoints(false);
  56. auto maxMovePoints = [&](CGPathNode *cp) -> int
  57. {
  58. return cp->layer == ELayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  59. };
  60. auto passOneTurnLimitCheck = [&](bool shouldCheck) -> bool
  61. {
  62. if(options.oneTurnSpecialLayersLimit && shouldCheck)
  63. {
  64. if((cp->layer == ELayer::AIR || cp->layer == ELayer::WATER)
  65. && cp->accessible != CGPathNode::ACCESSIBLE)
  66. {
  67. return false;
  68. }
  69. }
  70. return true;
  71. };
  72. auto isBetterWay = [&](int remains, int turn) -> bool
  73. {
  74. if(dp->turns == 0xff) //we haven't been here before
  75. return true;
  76. else if(dp->turns > turn)
  77. return true;
  78. else if(dp->turns >= turn && dp->moveRemains < remains) //this route is faster
  79. return true;
  80. return false;
  81. };
  82. //logGlobal->infoStream() << boost::format("Calculating paths for hero %s (adress %d) of player %d") % hero->name % hero % hero->tempOwner;
  83. //initial tile - set cost on 0 and add to the queue
  84. CGPathNode *initialNode = out.getNode(out.hpos, hero->boat ? ELayer::SAIL : ELayer::LAND);
  85. initialNode->turns = 0;
  86. initialNode->moveRemains = hero->movement;
  87. pq.push(initialNode);
  88. while(!pq.empty())
  89. {
  90. cp = pq.top();
  91. pq.pop();
  92. cp->locked = true;
  93. int movement = cp->moveRemains, turn = cp->turns;
  94. if(!movement)
  95. {
  96. movement = maxMovePoints(cp);
  97. turn++;
  98. }
  99. //add accessible neighbouring nodes to the queue
  100. addNeighbours(cp->coord);
  101. for(auto & neighbour : neighbours)
  102. {
  103. dt = &gs->map->getTile(neighbour);
  104. for(ELayer i = ELayer::LAND; i <= ELayer::AIR; i.advance(1))
  105. {
  106. dp = out.getNode(neighbour, i);
  107. if(dp->accessible == CGPathNode::NOT_SET)
  108. continue;
  109. if(dp->locked)
  110. continue;
  111. if(!passOneTurnLimitCheck(cp->turns != turn))
  112. continue;
  113. if(!isLayerAvailable(i, turn))
  114. continue;
  115. if(cp->layer != i && !isLayerTransitionPossible())
  116. continue;
  117. destAction = CGPathNode::UNKNOWN;
  118. if(!isMovementToDestPossible())
  119. continue;
  120. int cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, movement);
  121. int remains = movement - cost;
  122. if(destAction == CGPathNode::EMBARK || destAction == CGPathNode::DISEMBARK)
  123. {
  124. remains = hero->movementPointsAfterEmbark(movement, cost, destAction - 1);
  125. cost = movement - remains;
  126. }
  127. int turnAtNextTile = turn;
  128. if(remains < 0)
  129. {
  130. //occurs rarely, when hero with low movepoints tries to leave the road
  131. turnAtNextTile++;
  132. int moveAtNextTile = maxMovePoints(cp);
  133. cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  134. remains = moveAtNextTile - cost;
  135. }
  136. if(isBetterWay(remains, turnAtNextTile)
  137. && passOneTurnLimitCheck(cp->turns != turnAtNextTile || !remains))
  138. {
  139. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  140. dp->moveRemains = remains;
  141. dp->turns = turnAtNextTile;
  142. dp->theNodeBefore = cp;
  143. dp->action = destAction;
  144. if(isMovementAfterDestPossible())
  145. pq.push(dp);
  146. }
  147. }
  148. } //neighbours loop
  149. //just add all passable teleport exits
  150. if(sTileObj && canVisitObject())
  151. {
  152. addTeleportExits();
  153. for(auto & neighbour : neighbours)
  154. {
  155. dp = out.getNode(neighbour, cp->layer);
  156. if(dp->locked)
  157. continue;
  158. if(isBetterWay(movement, turn))
  159. {
  160. dp->moveRemains = movement;
  161. dp->turns = turn;
  162. dp->theNodeBefore = cp;
  163. dp->action = CGPathNode::NORMAL;
  164. pq.push(dp);
  165. }
  166. }
  167. }
  168. } //queue loop
  169. }
  170. void CPathfinder::addNeighbours(const int3 &coord)
  171. {
  172. neighbours.clear();
  173. ct = &gs->map->getTile(coord);
  174. std::vector<int3> tiles;
  175. CPathfinderHelper::getNeighbours(gs, *ct, coord, tiles, boost::logic::indeterminate, cp->layer == ELayer::SAIL); // TODO: find out if we still need "limitCoastSailing" option
  176. sTileObj = ct->topVisitableObj(coord == out.hpos);
  177. if(canVisitObject())
  178. {
  179. if(sTileObj)
  180. {
  181. for(int3 tile: tiles)
  182. {
  183. if(canMoveBetween(tile, sTileObj->visitablePos()))
  184. neighbours.push_back(tile);
  185. }
  186. }
  187. else
  188. vstd::concatenate(neighbours, tiles);
  189. }
  190. else
  191. vstd::concatenate(neighbours, tiles);
  192. }
  193. void CPathfinder::addTeleportExits(bool noTeleportExcludes)
  194. {
  195. assert(sTileObj);
  196. neighbours.clear();
  197. auto isAllowedTeleportEntrance = [&](const CGTeleport * obj) -> bool
  198. {
  199. if(!gs->isTeleportEntrancePassable(obj, hero->tempOwner))
  200. return false;
  201. if(noTeleportExcludes)
  202. return true;
  203. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  204. if(whirlpool)
  205. {
  206. if(addTeleportWhirlpool(whirlpool))
  207. return true;
  208. }
  209. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  210. return true;
  211. return false;
  212. };
  213. const CGTeleport *sTileTeleport = dynamic_cast<const CGTeleport *>(sTileObj);
  214. if(isAllowedTeleportEntrance(sTileTeleport))
  215. {
  216. for(auto objId : gs->getTeleportChannelExits(sTileTeleport->channel, hero->tempOwner))
  217. {
  218. auto obj = getObj(objId);
  219. if(CGTeleport::isExitPassable(gs, hero, obj))
  220. neighbours.push_back(obj->visitablePos());
  221. }
  222. }
  223. if(options.useCastleGate
  224. && (sTileObj->ID == Obj::TOWN && sTileObj->subID == ETownType::INFERNO
  225. && getPlayerRelations(hero->tempOwner, sTileObj->tempOwner) != PlayerRelations::ENEMIES))
  226. {
  227. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  228. /// This may be handy if we allow to use teleportation to friendly towns
  229. auto towns = gs->getPlayer(hero->tempOwner)->towns;
  230. for(const auto & town : towns)
  231. {
  232. if(town->id != sTileObj->id && town->visitingHero == nullptr
  233. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  234. {
  235. neighbours.push_back(town->visitablePos());
  236. }
  237. }
  238. }
  239. }
  240. bool CPathfinder::isLayerAvailable(const ELayer &layer, const int &turn) const
  241. {
  242. switch(layer)
  243. {
  244. case ELayer::AIR:
  245. if(!hero->getBonusAtTurn(Bonus::FLYING_MOVEMENT, turn))
  246. return false;
  247. break;
  248. case ELayer::WATER:
  249. if(!hero->getBonusAtTurn(Bonus::WATER_WALKING, turn))
  250. return false;
  251. break;
  252. }
  253. return true;
  254. }
  255. bool CPathfinder::isLayerTransitionPossible() const
  256. {
  257. if((cp->layer == ELayer::AIR || cp->layer == ELayer::WATER)
  258. && dp->layer != ELayer::LAND)
  259. {
  260. return false;
  261. }
  262. else if(cp->layer == ELayer::LAND && dp->layer == ELayer::AIR)
  263. {
  264. if(options.lightweightFlyingMode && !isSourceInitialPosition())
  265. return false;
  266. }
  267. else if(cp->layer == ELayer::SAIL && dp->layer != ELayer::LAND)
  268. return false;
  269. else if(cp->layer == ELayer::SAIL && dp->layer == ELayer::LAND)
  270. {
  271. if(!dt->isCoastal())
  272. return false;
  273. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  274. if((dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  275. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  276. return false;
  277. }
  278. else if(cp->layer == ELayer::LAND && dp->layer == ELayer::SAIL)
  279. {
  280. if(dp->accessible == CGPathNode::ACCESSIBLE) //cannot enter empty water tile from land -> it has to be visitable
  281. return false;
  282. }
  283. return true;
  284. }
  285. bool CPathfinder::isMovementToDestPossible()
  286. {
  287. auto obj = dt->topVisitableObj();
  288. switch(dp->layer)
  289. {
  290. case ELayer::LAND:
  291. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED)
  292. return false;
  293. if(isSourceGuarded() && !isDestinationGuardian()) // Can step into tile of guard
  294. return false;
  295. if(cp->layer == ELayer::SAIL)
  296. destAction = CGPathNode::DISEMBARK;
  297. break;
  298. case ELayer::SAIL:
  299. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED)
  300. return false;
  301. if(isSourceGuarded() && !isDestinationGuardian()) // Can step into tile of guard
  302. return false;
  303. if(cp->layer == ELayer::LAND)
  304. {
  305. if(!obj)
  306. return false;
  307. if(obj->ID == Obj::BOAT)
  308. destAction = CGPathNode::EMBARK;
  309. else if(obj->ID != Obj::HERO)
  310. return false;
  311. }
  312. break;
  313. case ELayer::AIR:
  314. //if(!canMoveBetween(cp->coord, dp->coord))
  315. // return false;
  316. break;
  317. case ELayer::WATER:
  318. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible != CGPathNode::ACCESSIBLE)
  319. return false;
  320. if(isDestinationGuarded())
  321. return false;
  322. break;
  323. }
  324. if(destAction == CGPathNode::UNKNOWN)
  325. {
  326. destAction = CGPathNode::NORMAL;
  327. if(dp->layer == ELayer::LAND || dp->layer == ELayer::SAIL)
  328. {
  329. if(obj)
  330. {
  331. auto objRel = getPlayerRelations(obj->tempOwner, hero->tempOwner);
  332. if(obj->ID == Obj::HERO)
  333. {
  334. if(objRel == PlayerRelations::ENEMIES)
  335. destAction = CGPathNode::BATTLE;
  336. else
  337. destAction = CGPathNode::BLOCKING_VISIT;
  338. }
  339. else if(obj->ID == Obj::TOWN && objRel == PlayerRelations::ENEMIES)
  340. {
  341. const CGTownInstance * townObj = dynamic_cast<const CGTownInstance *>(obj);
  342. if (townObj->armedGarrison())
  343. destAction = CGPathNode::BATTLE;
  344. }
  345. else if(obj->ID == Obj::GARRISON || obj->ID == Obj::GARRISON2)
  346. {
  347. const CGGarrison * garrisonObj = dynamic_cast<const CGGarrison *>(obj);
  348. if((garrisonObj->stacksCount() && objRel == PlayerRelations::ENEMIES) || isDestinationGuarded(true))
  349. destAction = CGPathNode::BATTLE;
  350. }
  351. else if(isDestinationGuardian())
  352. destAction = CGPathNode::BATTLE;
  353. else if(obj->blockVisit && (!options.useCastleGate || obj->ID != Obj::TOWN))
  354. destAction = CGPathNode::BLOCKING_VISIT;
  355. if(destAction == CGPathNode::NORMAL)
  356. destAction = CGPathNode::VISIT;
  357. }
  358. else if(isDestinationGuarded())
  359. destAction = CGPathNode::BATTLE;
  360. }
  361. }
  362. return true;
  363. }
  364. bool CPathfinder::isMovementAfterDestPossible() const
  365. {
  366. switch(destAction)
  367. {
  368. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  369. /// Likely in many cases we don't need to add visitable tile to queue when hero don't fly
  370. case CGPathNode::VISIT:
  371. if(CGTeleport::isTeleport(dt->topVisitableObj()))
  372. {
  373. /// For now we'll always allow transit over teleporters
  374. /// Transit over whirlpools only allowed when hero protected
  375. auto whirlpool = dynamic_cast<const CGWhirlpool *>(dt->topVisitableObj());
  376. if(!whirlpool || options.useTeleportWhirlpool)
  377. return true;
  378. }
  379. else
  380. return true;
  381. case CGPathNode::NORMAL:
  382. return true;
  383. case CGPathNode::EMBARK:
  384. if(options.useEmbarkAndDisembark)
  385. return true;
  386. case CGPathNode::DISEMBARK:
  387. if(options.useEmbarkAndDisembark && !isDestinationGuarded())
  388. return true;
  389. }
  390. return false;
  391. }
  392. bool CPathfinder::isSourceInitialPosition() const
  393. {
  394. return cp->coord == out.hpos;
  395. }
  396. int3 CPathfinder::getSourceGuardPosition() const
  397. {
  398. return gs->map->guardingCreaturePositions[cp->coord.x][cp->coord.y][cp->coord.z];
  399. }
  400. bool CPathfinder::isSourceGuarded() const
  401. {
  402. //map can start with hero on guarded tile or teleport there using dimension door
  403. //so threat tile hero standing on like it's not guarded because it's should be possible to move out of here
  404. if(getSourceGuardPosition() != int3(-1, -1, -1) && !isSourceInitialPosition())
  405. {
  406. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  407. if(cp->accessible != CGPathNode::VISITABLE
  408. || cp->theNodeBefore->layer == ELayer::LAND
  409. || ct->topVisitableId() != Obj::BOAT)
  410. {
  411. return true;
  412. }
  413. }
  414. return false;
  415. }
  416. bool CPathfinder::isDestinationGuarded(const bool ignoreAccessibility) const
  417. {
  418. if(gs->map->guardingCreaturePositions[dp->coord.x][dp->coord.y][dp->coord.z].valid()
  419. && (ignoreAccessibility || dp->accessible == CGPathNode::BLOCKVIS))
  420. {
  421. return true;
  422. }
  423. return false;
  424. }
  425. bool CPathfinder::isDestinationGuardian() const
  426. {
  427. return getSourceGuardPosition() == dp->coord;
  428. }
  429. void CPathfinder::initializeGraph()
  430. {
  431. auto updateNode = [&](int3 pos, ELayer layer, const TerrainTile *tinfo, bool blockNotAccessible)
  432. {
  433. auto node = out.getNode(pos, layer);
  434. node->reset();
  435. auto accessibility = evaluateAccessibility(pos, tinfo);
  436. if(blockNotAccessible
  437. && (accessibility != CGPathNode::ACCESSIBLE || tinfo->terType == ETerrainType::WATER))
  438. accessibility = CGPathNode::BLOCKED;
  439. node->accessible = accessibility;
  440. };
  441. int3 pos;
  442. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  443. {
  444. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  445. {
  446. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  447. {
  448. const TerrainTile *tinfo = &gs->map->getTile(pos);
  449. switch(tinfo->terType)
  450. {
  451. case ETerrainType::ROCK:
  452. break;
  453. case ETerrainType::WATER:
  454. updateNode(pos, ELayer::SAIL, tinfo, false);
  455. if(options.useFlying)
  456. updateNode(pos, ELayer::AIR, tinfo, true);
  457. if(options.useWaterWalking)
  458. updateNode(pos, ELayer::WATER, tinfo, true);
  459. break;
  460. default:
  461. updateNode(pos, ELayer::LAND, tinfo, false);
  462. if(options.useFlying)
  463. updateNode(pos, ELayer::AIR, tinfo, true);
  464. break;
  465. }
  466. }
  467. }
  468. }
  469. }
  470. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 &pos, const TerrainTile *tinfo) const
  471. {
  472. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  473. if(tinfo->terType == ETerrainType::ROCK || !isVisible(pos, hero->tempOwner))
  474. return CGPathNode::BLOCKED;
  475. if(tinfo->visitable)
  476. {
  477. 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
  478. {
  479. return CGPathNode::BLOCKED;
  480. }
  481. else
  482. {
  483. for(const CGObjectInstance *obj : tinfo->visitableObjects)
  484. {
  485. if(obj->passableFor(hero->tempOwner))
  486. {
  487. ret = CGPathNode::ACCESSIBLE;
  488. }
  489. else if(obj->blockVisit)
  490. {
  491. return CGPathNode::BLOCKVIS;
  492. }
  493. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  494. {
  495. ret = CGPathNode::VISITABLE;
  496. }
  497. }
  498. }
  499. }
  500. else if(gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z].valid()
  501. && !tinfo->blocked)
  502. {
  503. // Monster close by; blocked visit for battle.
  504. return CGPathNode::BLOCKVIS;
  505. }
  506. return ret;
  507. }
  508. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  509. {
  510. return gs->checkForVisitableDir(a, b);
  511. }
  512. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  513. {
  514. return options.useTeleportTwoWay && gs->isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  515. }
  516. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  517. {
  518. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  519. {
  520. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  521. if(passableExits.size() == 1)
  522. return true;
  523. }
  524. return false;
  525. }
  526. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  527. {
  528. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  529. {
  530. auto passableExits = CGTeleport::getPassableExits(gs, hero, gs->getTeleportChannelExits(obj->channel, hero->tempOwner));
  531. if(passableExits.size() > 1)
  532. return true;
  533. }
  534. return false;
  535. }
  536. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  537. {
  538. return options.useTeleportWhirlpool && obj;
  539. }
  540. bool CPathfinder::canVisitObject() const
  541. {
  542. //hero can't visit objects while walking on water or flying
  543. return cp->layer == ELayer::LAND || cp->layer == ELayer::SAIL;
  544. }
  545. void CPathfinderHelper::getNeighbours(CGameState * gs, const TerrainTile &srct, const int3 &tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, const bool &limitCoastSailing)
  546. {
  547. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  548. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  549. //vec.reserve(8); //optimization
  550. for (auto & dir : dirs)
  551. {
  552. const int3 hlp = tile + dir;
  553. if(!gs->isInTheMap(hlp))
  554. continue;
  555. const TerrainTile &hlpt = gs->map->getTile(hlp);
  556. // //we cannot visit things from blocked tiles
  557. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  558. // {
  559. // continue;
  560. // }
  561. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  562. {
  563. int3 hlp1 = tile,
  564. hlp2 = tile;
  565. hlp1.x += dir.x;
  566. hlp2.y += dir.y;
  567. if(gs->map->getTile(hlp1).terType != ETerrainType::WATER || gs->map->getTile(hlp2).terType != ETerrainType::WATER)
  568. continue;
  569. }
  570. if((indeterminate(onLand) || onLand == (hlpt.terType!=ETerrainType::WATER) )
  571. && hlpt.terType != ETerrainType::ROCK)
  572. {
  573. vec.push_back(hlp);
  574. }
  575. }
  576. }
  577. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 &src, const int3 &dst, const int &remainingMovePoints, const int &turn, const bool &checkLast)
  578. {
  579. if(src == dst) //same tile
  580. return 0;
  581. auto s = h->cb->getTile(src), d = h->cb->getTile(dst);
  582. int ret = h->getTileCost(*d, *s, turn);
  583. auto flyBonus = h->getBonusAtTurn(Bonus::FLYING_MOVEMENT, turn);
  584. auto waterWalkingBonus = h->getBonusAtTurn(Bonus::WATER_WALKING, turn);
  585. if(d->blocked && flyBonus)
  586. {
  587. ret *= (100.0 + flyBonus->val) / 100.0;
  588. }
  589. else if(d->terType == ETerrainType::WATER)
  590. {
  591. if(h->boat && s->hasFavourableWinds() && d->hasFavourableWinds()) //Favourable Winds
  592. ret *= 0.666;
  593. else if(!h->boat && waterWalkingBonus)
  594. {
  595. ret *= (100.0 + waterWalkingBonus->val) / 100.0;
  596. }
  597. }
  598. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  599. {
  600. int old = ret;
  601. ret *= 1.414213;
  602. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  603. if(ret > remainingMovePoints && remainingMovePoints >= old)
  604. return remainingMovePoints;
  605. }
  606. int left = remainingMovePoints-ret;
  607. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  608. {
  609. std::vector<int3> vec;
  610. vec.reserve(8); //optimization
  611. getNeighbours(h->cb->gameState(), *d, dst, vec, s->terType != ETerrainType::WATER, true);
  612. for(auto & elem : vec)
  613. {
  614. int fcost = getMovementCost(h, dst, elem, left, turn, false);
  615. if(fcost <= left)
  616. return ret;
  617. }
  618. ret = remainingMovePoints;
  619. }
  620. return ret;
  621. }
  622. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 &dst)
  623. {
  624. return getMovementCost(h, h->visitablePos(), dst, h->movement);
  625. }
  626. CGPathNode::CGPathNode(int3 Coord, ELayer Layer)
  627. : coord(Coord), layer(Layer)
  628. {
  629. reset();
  630. }
  631. void CGPathNode::reset()
  632. {
  633. locked = false;
  634. accessible = NOT_SET;
  635. moveRemains = 0;
  636. turns = 255;
  637. theNodeBefore = nullptr;
  638. action = UNKNOWN;
  639. }
  640. bool CGPathNode::reachable() const
  641. {
  642. return turns < 255;
  643. }
  644. int3 CGPath::startPos() const
  645. {
  646. return nodes[nodes.size()-1].coord;
  647. }
  648. int3 CGPath::endPos() const
  649. {
  650. return nodes[0].coord;
  651. }
  652. void CGPath::convert(ui8 mode)
  653. {
  654. if(mode==0)
  655. {
  656. for(auto & elem : nodes)
  657. {
  658. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  659. }
  660. }
  661. }
  662. CPathsInfo::CPathsInfo(const int3 &Sizes)
  663. : sizes(Sizes)
  664. {
  665. hero = nullptr;
  666. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  667. for(int i = 0; i < sizes.x; i++)
  668. for(int j = 0; j < sizes.y; j++)
  669. for(int z = 0; z < sizes.z; z++)
  670. for(int l = 0; l < ELayer::NUM_LAYERS; l++)
  671. nodes[i][j][z][l] = new CGPathNode(int3(i, j, z), static_cast<ELayer>(l));
  672. }
  673. CPathsInfo::~CPathsInfo()
  674. {
  675. }
  676. const CGPathNode * CPathsInfo::getPathInfo(const int3 &tile, const ELayer &layer) const
  677. {
  678. boost::unique_lock<boost::mutex> pathLock(pathMx);
  679. if(tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z || layer >= ELayer::NUM_LAYERS)
  680. return nullptr;
  681. return getNode(tile, layer);
  682. }
  683. bool CPathsInfo::getPath(CGPath &out, const int3 &dst, const ELayer &layer) const
  684. {
  685. boost::unique_lock<boost::mutex> pathLock(pathMx);
  686. out.nodes.clear();
  687. const CGPathNode *curnode = getNode(dst, layer);
  688. if(!curnode->theNodeBefore)
  689. return false;
  690. while(curnode)
  691. {
  692. CGPathNode cpn = *curnode;
  693. curnode = curnode->theNodeBefore;
  694. out.nodes.push_back(cpn);
  695. }
  696. return true;
  697. }
  698. int CPathsInfo::getDistance(const int3 &tile, const ELayer &layer) const
  699. {
  700. boost::unique_lock<boost::mutex> pathLock(pathMx);
  701. CGPath ret;
  702. if(getPath(ret, tile, layer))
  703. return ret.nodes.size();
  704. else
  705. return 255;
  706. }
  707. CGPathNode *CPathsInfo::getNode(const int3 &coord, const ELayer &layer) const
  708. {
  709. if(layer != ELayer::AUTO)
  710. return nodes[coord.x][coord.y][coord.z][layer];
  711. auto landNode = nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  712. if(landNode->theNodeBefore)
  713. return landNode;
  714. else
  715. return nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  716. }