2
0

CPathfinder.cpp 25 KB

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