CPathfinder.cpp 24 KB

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