CPathfinder.cpp 23 KB

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