CPathfinder.cpp 24 KB

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