CPathfinder.cpp 23 KB

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