CPathfinder.cpp 24 KB

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