CPathfinder.cpp 24 KB

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