CPathfinder.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. /*
  2. * CPathfinder.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CPathfinder.h"
  12. #include "CHeroHandler.h"
  13. #include "mapping/CMap.h"
  14. #include "CGameState.h"
  15. #include "mapObjects/CGHeroInstance.h"
  16. #include "GameConstants.h"
  17. #include "CStopWatch.h"
  18. #include "CConfigHandler.h"
  19. #include "CPlayerState.h"
  20. #include "PathfinderUtil.h"
  21. bool canSeeObj(const CGObjectInstance * obj)
  22. {
  23. /// Pathfinder should ignore placed events
  24. return obj != nullptr && obj->ID != Obj::EVENT;
  25. }
  26. void NodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  27. {
  28. //TODO: fix this code duplication with AINodeStorage::initialize, problem is to keep `resetTile` inline
  29. int3 pos;
  30. const PlayerColor player = out.hero->tempOwner;
  31. const int3 sizes = gs->getMapSize();
  32. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  33. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  34. const bool useFlying = options.useFlying;
  35. const bool useWaterWalking = options.useWaterWalking;
  36. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  37. {
  38. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  39. {
  40. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  41. {
  42. const TerrainTile * tile = &gs->map->getTile(pos);
  43. if(tile->terType.isWater())
  44. {
  45. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  46. if(useFlying)
  47. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  48. if(useWaterWalking)
  49. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  50. }
  51. if(tile->terType.isLand())
  52. {
  53. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  54. if(useFlying)
  55. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  56. }
  57. }
  58. }
  59. }
  60. }
  61. std::vector<CGPathNode *> NodeStorage::calculateNeighbours(
  62. const PathNodeInfo & source,
  63. const PathfinderConfig * pathfinderConfig,
  64. const CPathfinderHelper * pathfinderHelper)
  65. {
  66. std::vector<CGPathNode *> neighbours;
  67. neighbours.reserve(16);
  68. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  69. for(auto & neighbour : accessibleNeighbourTiles)
  70. {
  71. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  72. {
  73. auto node = getNode(neighbour, i);
  74. if(node->accessible == CGPathNode::NOT_SET)
  75. continue;
  76. neighbours.push_back(node);
  77. }
  78. }
  79. return neighbours;
  80. }
  81. std::vector<CGPathNode *> NodeStorage::calculateTeleportations(
  82. const PathNodeInfo & source,
  83. const PathfinderConfig * pathfinderConfig,
  84. const CPathfinderHelper * pathfinderHelper)
  85. {
  86. std::vector<CGPathNode *> neighbours;
  87. if(!source.isNodeObjectVisitable())
  88. return neighbours;
  89. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  90. for(auto & neighbour : accessibleExits)
  91. {
  92. auto node = getNode(neighbour, source.node->layer);
  93. neighbours.push_back(node);
  94. }
  95. return neighbours;
  96. }
  97. std::vector<int3> CPathfinderHelper::getNeighbourTiles(const PathNodeInfo & source) const
  98. {
  99. std::vector<int3> neighbourTiles;
  100. neighbourTiles.reserve(16);
  101. getNeighbours(
  102. *source.tile,
  103. source.node->coord,
  104. neighbourTiles,
  105. boost::logic::indeterminate,
  106. source.node->layer == EPathfindingLayer::SAIL);
  107. if(source.isNodeObjectVisitable())
  108. {
  109. vstd::erase_if(neighbourTiles, [&](int3 tile) -> bool
  110. {
  111. return !canMoveBetween(tile, source.nodeObject->visitablePos());
  112. });
  113. }
  114. return neighbourTiles;
  115. }
  116. NodeStorage::NodeStorage(CPathsInfo & pathsInfo, const CGHeroInstance * hero)
  117. :out(pathsInfo)
  118. {
  119. out.hero = hero;
  120. out.hpos = hero->getPosition(false);
  121. }
  122. void NodeStorage::resetTile(
  123. const int3 & tile,
  124. EPathfindingLayer layer,
  125. CGPathNode::EAccessibility accessibility)
  126. {
  127. getNode(tile, layer)->update(tile, layer, accessibility);
  128. }
  129. std::vector<CGPathNode *> NodeStorage::getInitialNodes()
  130. {
  131. auto initialNode = getNode(out.hpos, out.hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
  132. initialNode->turns = 0;
  133. initialNode->moveRemains = out.hero->movement;
  134. initialNode->setCost(0.0);
  135. if(!initialNode->coord.valid())
  136. {
  137. initialNode->coord = out.hpos;
  138. }
  139. return std::vector<CGPathNode *> { initialNode };
  140. }
  141. void NodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  142. {
  143. assert(destination.node != source.node->theNodeBefore); //two tiles can't point to each other
  144. destination.node->setCost(destination.cost);
  145. destination.node->moveRemains = destination.movementLeft;
  146. destination.node->turns = destination.turn;
  147. destination.node->theNodeBefore = source.node;
  148. destination.node->action = destination.action;
  149. }
  150. PathfinderOptions::PathfinderOptions()
  151. {
  152. useFlying = settings["pathfinder"]["layers"]["flying"].Bool();
  153. useWaterWalking = settings["pathfinder"]["layers"]["waterWalking"].Bool();
  154. useEmbarkAndDisembark = settings["pathfinder"]["layers"]["sailing"].Bool();
  155. useTeleportTwoWay = settings["pathfinder"]["teleports"]["twoWay"].Bool();
  156. useTeleportOneWay = settings["pathfinder"]["teleports"]["oneWay"].Bool();
  157. useTeleportOneWayRandom = settings["pathfinder"]["teleports"]["oneWayRandom"].Bool();
  158. useTeleportWhirlpool = settings["pathfinder"]["teleports"]["whirlpool"].Bool();
  159. useCastleGate = settings["pathfinder"]["teleports"]["castleGate"].Bool();
  160. lightweightFlyingMode = settings["pathfinder"]["lightweightFlyingMode"].Bool();
  161. oneTurnSpecialLayersLimit = settings["pathfinder"]["oneTurnSpecialLayersLimit"].Bool();
  162. originalMovementRules = settings["pathfinder"]["originalMovementRules"].Bool();
  163. }
  164. void MovementCostRule::process(
  165. const PathNodeInfo & source,
  166. CDestinationNodeInfo & destination,
  167. const PathfinderConfig * pathfinderConfig,
  168. CPathfinderHelper * pathfinderHelper) const
  169. {
  170. float costAtNextTile = destination.cost;
  171. int turnAtNextTile = destination.turn;
  172. int moveAtNextTile = destination.movementLeft;
  173. int cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile);
  174. int remains = moveAtNextTile - cost;
  175. int sourceLayerMaxMovePoints = pathfinderHelper->getMaxMovePoints(source.node->layer);
  176. if(remains < 0)
  177. {
  178. //occurs rarely, when hero with low movepoints tries to leave the road
  179. costAtNextTile += static_cast<float>(moveAtNextTile) / sourceLayerMaxMovePoints;//we spent all points of current turn
  180. pathfinderHelper->updateTurnInfo(++turnAtNextTile);
  181. int destinationLayerMaxMovePoints = pathfinderHelper->getMaxMovePoints(destination.node->layer);
  182. moveAtNextTile = destinationLayerMaxMovePoints;
  183. cost = pathfinderHelper->getMovementCost(source, destination, moveAtNextTile); //cost must be updated, movement points changed :(
  184. remains = moveAtNextTile - cost;
  185. }
  186. if(destination.action == CGPathNode::EMBARK || destination.action == CGPathNode::DISEMBARK)
  187. {
  188. /// FREE_SHIP_BOARDING bonus only remove additional penalty
  189. /// land <-> sail transition still cost movement points as normal movement
  190. remains = pathfinderHelper->movementPointsAfterEmbark(moveAtNextTile, cost, (destination.action == CGPathNode::DISEMBARK));
  191. cost = moveAtNextTile - remains;
  192. }
  193. costAtNextTile += static_cast<float>(cost) / sourceLayerMaxMovePoints;
  194. destination.cost = costAtNextTile;
  195. destination.turn = turnAtNextTile;
  196. destination.movementLeft = remains;
  197. if(destination.isBetterWay() &&
  198. ((source.node->turns == turnAtNextTile && remains) || pathfinderHelper->passOneTurnLimitCheck(source)))
  199. {
  200. pathfinderConfig->nodeStorage->commit(destination, source);
  201. return;
  202. }
  203. destination.blocked = true;
  204. }
  205. PathfinderConfig::PathfinderConfig(
  206. std::shared_ptr<INodeStorage> nodeStorage,
  207. std::vector<std::shared_ptr<IPathfindingRule>> rules)
  208. : nodeStorage(nodeStorage), rules(rules), options()
  209. {
  210. }
  211. CPathfinder::CPathfinder(
  212. CPathsInfo & _out,
  213. CGameState * _gs,
  214. const CGHeroInstance * _hero)
  215. : CPathfinder(
  216. _gs,
  217. std::make_shared<SingleHeroPathfinderConfig>(_out, _gs, _hero))
  218. {
  219. }
  220. std::vector<std::shared_ptr<IPathfindingRule>> SingleHeroPathfinderConfig::buildRuleSet()
  221. {
  222. return std::vector<std::shared_ptr<IPathfindingRule>>{
  223. std::make_shared<LayerTransitionRule>(),
  224. std::make_shared<DestinationActionRule>(),
  225. std::make_shared<MovementToDestinationRule>(),
  226. std::make_shared<MovementCostRule>(),
  227. std::make_shared<MovementAfterDestinationRule>()
  228. };
  229. }
  230. SingleHeroPathfinderConfig::SingleHeroPathfinderConfig(CPathsInfo & out, CGameState * gs, const CGHeroInstance * hero)
  231. : PathfinderConfig(std::make_shared<NodeStorage>(out, hero), buildRuleSet())
  232. {
  233. pathfinderHelper.reset(new CPathfinderHelper(gs, hero, options));
  234. }
  235. CPathfinderHelper * SingleHeroPathfinderConfig::getOrCreatePathfinderHelper(const PathNodeInfo & source, CGameState * gs)
  236. {
  237. return pathfinderHelper.get();
  238. }
  239. CPathfinder::CPathfinder(
  240. CGameState * _gs,
  241. std::shared_ptr<PathfinderConfig> config)
  242. : CGameInfoCallback(_gs, boost::optional<PlayerColor>())
  243. , config(config)
  244. , source()
  245. , destination()
  246. {
  247. initializeGraph();
  248. }
  249. void CPathfinder::push(CGPathNode * node)
  250. {
  251. if(node && !node->inPQ)
  252. {
  253. node->inPQ = true;
  254. node->pq = &this->pq;
  255. auto handle = pq.push(node);
  256. node->pqHandle = handle;
  257. }
  258. }
  259. CGPathNode * CPathfinder::topAndPop()
  260. {
  261. auto node = pq.top();
  262. pq.pop();
  263. node->inPQ = false;
  264. node->pq = nullptr;
  265. return node;
  266. }
  267. void CPathfinder::calculatePaths()
  268. {
  269. //logGlobal->info("Calculating paths for hero %s (adress %d) of player %d", hero->name, hero , hero->tempOwner);
  270. //initial tile - set cost on 0 and add to the queue
  271. std::vector<CGPathNode *> initialNodes = config->nodeStorage->getInitialNodes();
  272. int counter = 0;
  273. for(auto initialNode : initialNodes)
  274. {
  275. if(!isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
  276. {
  277. logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
  278. throw std::runtime_error("Wrong checksum");
  279. }
  280. source.setNode(gs, initialNode);
  281. auto hlp = config->getOrCreatePathfinderHelper(source, gs);
  282. if(hlp->isHeroPatrolLocked())
  283. break;
  284. pq.push(initialNode);
  285. }
  286. while(!pq.empty())
  287. {
  288. counter++;
  289. auto node = topAndPop();
  290. source.setNode(gs, node);
  291. source.node->locked = true;
  292. int movement = source.node->moveRemains;
  293. uint8_t turn = source.node->turns;
  294. float cost = source.node->getCost();
  295. auto hlp = config->getOrCreatePathfinderHelper(source, gs);
  296. hlp->updateTurnInfo(turn);
  297. if(!movement)
  298. {
  299. hlp->updateTurnInfo(++turn);
  300. movement = hlp->getMaxMovePoints(source.node->layer);
  301. if(!hlp->passOneTurnLimitCheck(source))
  302. continue;
  303. }
  304. source.isInitialPosition = source.nodeHero == hlp->hero;
  305. source.updateInfo(hlp, gs);
  306. //add accessible neighbouring nodes to the queue
  307. auto neighbourNodes = config->nodeStorage->calculateNeighbours(source, config.get(), hlp);
  308. for(CGPathNode * neighbour : neighbourNodes)
  309. {
  310. if(neighbour->locked)
  311. continue;
  312. if(!hlp->isLayerAvailable(neighbour->layer))
  313. continue;
  314. destination.setNode(gs, neighbour);
  315. hlp = config->getOrCreatePathfinderHelper(destination, gs);
  316. if(!hlp->isPatrolMovementAllowed(neighbour->coord))
  317. continue;
  318. /// Check transition without tile accessability rules
  319. if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
  320. continue;
  321. destination.turn = turn;
  322. destination.movementLeft = movement;
  323. destination.cost = cost;
  324. destination.updateInfo(hlp, gs);
  325. destination.isGuardianTile = destination.guarded && isDestinationGuardian();
  326. for(auto rule : config->rules)
  327. {
  328. rule->process(source, destination, config.get(), hlp);
  329. if(destination.blocked)
  330. break;
  331. }
  332. if(!destination.blocked)
  333. push(destination.node);
  334. } //neighbours loop
  335. //just add all passable teleport exits
  336. hlp = config->getOrCreatePathfinderHelper(source, gs);
  337. /// For now we disable teleports usage for patrol movement
  338. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  339. if(hlp->patrolState == CPathfinderHelper::PATROL_RADIUS)
  340. continue;
  341. auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp);
  342. for(CGPathNode * teleportNode : teleportationNodes)
  343. {
  344. if(teleportNode->locked)
  345. continue;
  346. /// TODO: We may consider use invisible exits on FoW border in future
  347. /// Useful for AI when at least one tile around exit is visible and passable
  348. /// Objects are usually visible on FoW border anyway so it's not cheating.
  349. ///
  350. /// For now it's disabled as it's will cause crashes in movement code.
  351. if(teleportNode->accessible == CGPathNode::BLOCKED)
  352. continue;
  353. destination.setNode(gs, teleportNode);
  354. destination.turn = turn;
  355. destination.movementLeft = movement;
  356. destination.cost = cost;
  357. if(destination.isBetterWay())
  358. {
  359. destination.action = getTeleportDestAction();
  360. config->nodeStorage->commit(destination, source);
  361. if(destination.node->action == CGPathNode::TELEPORT_NORMAL)
  362. push(destination.node);
  363. }
  364. }
  365. } //queue loop
  366. logAi->trace("CPathfinder finished with %s iterations", std::to_string(counter));
  367. }
  368. std::vector<int3> CPathfinderHelper::getAllowedTeleportChannelExits(TeleportChannelID channelID) const
  369. {
  370. std::vector<int3> allowedExits;
  371. for(auto objId : getTeleportChannelExits(channelID, hero->tempOwner))
  372. {
  373. auto obj = getObj(objId);
  374. if(dynamic_cast<const CGWhirlpool *>(obj))
  375. {
  376. auto pos = obj->getBlockedPos();
  377. for(auto p : pos)
  378. {
  379. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  380. allowedExits.push_back(p);
  381. }
  382. }
  383. else if(CGTeleport::isExitPassable(gs, hero, obj))
  384. allowedExits.push_back(obj->visitablePos());
  385. }
  386. return allowedExits;
  387. }
  388. std::vector<int3> CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
  389. {
  390. std::vector<int3> allowedExits;
  391. auto towns = getPlayerState(hero->tempOwner)->towns;
  392. for(const auto & town : towns)
  393. {
  394. if(town->id != source.nodeObject->id && town->visitingHero == nullptr
  395. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  396. {
  397. allowedExits.push_back(town->visitablePos());
  398. }
  399. }
  400. return allowedExits;
  401. }
  402. std::vector<int3> CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
  403. {
  404. std::vector<int3> teleportationExits;
  405. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
  406. if(isAllowedTeleportEntrance(objTeleport))
  407. {
  408. for(auto exit : getAllowedTeleportChannelExits(objTeleport->channel))
  409. {
  410. teleportationExits.push_back(exit);
  411. }
  412. }
  413. else if(options.useCastleGate
  414. && (source.nodeObject->ID == Obj::TOWN && source.nodeObject->subID == ETownType::INFERNO
  415. && source.objectRelations != PlayerRelations::ENEMIES))
  416. {
  417. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  418. /// This may be handy if we allow to use teleportation to friendly towns
  419. for(auto exit : getCastleGates(source))
  420. {
  421. teleportationExits.push_back(exit);
  422. }
  423. }
  424. return teleportationExits;
  425. }
  426. bool CPathfinderHelper::isHeroPatrolLocked() const
  427. {
  428. return patrolState == PATROL_LOCKED;
  429. }
  430. bool CPathfinderHelper::isPatrolMovementAllowed(const int3 & dst) const
  431. {
  432. if(patrolState == PATROL_RADIUS)
  433. {
  434. if(!vstd::contains(patrolTiles, dst))
  435. return false;
  436. }
  437. return true;
  438. }
  439. bool CPathfinder::isLayerTransitionPossible() const
  440. {
  441. ELayer destLayer = destination.node->layer;
  442. /// No layer transition allowed when previous node action is BATTLE
  443. if(source.node->action == CGPathNode::BATTLE)
  444. return false;
  445. switch(source.node->layer)
  446. {
  447. case ELayer::LAND:
  448. if(destLayer == ELayer::AIR)
  449. {
  450. if(!config->options.lightweightFlyingMode || source.isInitialPosition)
  451. return true;
  452. }
  453. else if(destLayer == ELayer::SAIL)
  454. {
  455. if(destination.tile->isWater())
  456. return true;
  457. }
  458. else
  459. return true;
  460. break;
  461. case ELayer::SAIL:
  462. if(destLayer == ELayer::LAND && !destination.tile->isWater())
  463. return true;
  464. break;
  465. case ELayer::AIR:
  466. if(destLayer == ELayer::LAND)
  467. return true;
  468. break;
  469. case ELayer::WATER:
  470. if(destLayer == ELayer::LAND)
  471. return true;
  472. break;
  473. }
  474. return false;
  475. }
  476. void LayerTransitionRule::process(
  477. const PathNodeInfo & source,
  478. CDestinationNodeInfo & destination,
  479. const PathfinderConfig * pathfinderConfig,
  480. CPathfinderHelper * pathfinderHelper) const
  481. {
  482. if(source.node->layer == destination.node->layer)
  483. return;
  484. switch(source.node->layer)
  485. {
  486. case EPathfindingLayer::LAND:
  487. if(destination.node->layer == EPathfindingLayer::SAIL)
  488. {
  489. /// Cannot enter empty water tile from land -> it has to be visitable
  490. if(destination.node->accessible == CGPathNode::ACCESSIBLE)
  491. destination.blocked = true;
  492. }
  493. break;
  494. case EPathfindingLayer::SAIL:
  495. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  496. if((destination.node->accessible != CGPathNode::ACCESSIBLE && (destination.node->accessible != CGPathNode::BLOCKVIS || destination.tile->blocked))
  497. || destination.tile->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  498. {
  499. destination.blocked = true;
  500. }
  501. break;
  502. case EPathfindingLayer::AIR:
  503. if(pathfinderConfig->options.originalMovementRules)
  504. {
  505. if((source.node->accessible != CGPathNode::ACCESSIBLE &&
  506. source.node->accessible != CGPathNode::VISITABLE) &&
  507. (destination.node->accessible != CGPathNode::VISITABLE &&
  508. destination.node->accessible != CGPathNode::ACCESSIBLE))
  509. {
  510. destination.blocked = true;
  511. }
  512. }
  513. else if(destination.node->accessible != CGPathNode::ACCESSIBLE)
  514. {
  515. /// Hero that fly can only land on accessible tiles
  516. if(!destination.isGuardianTile && destination.nodeObject)
  517. destination.blocked = true;
  518. }
  519. break;
  520. case EPathfindingLayer::WATER:
  521. if(destination.node->accessible != CGPathNode::ACCESSIBLE && destination.node->accessible != CGPathNode::VISITABLE)
  522. {
  523. /// Hero that walking on water can transit to accessible and visitable tiles
  524. /// Though hero can't interact with blocking visit objects while standing on water
  525. destination.blocked = true;
  526. }
  527. break;
  528. }
  529. }
  530. PathfinderBlockingRule::BlockingReason MovementToDestinationRule::getBlockingReason(
  531. const PathNodeInfo & source,
  532. const CDestinationNodeInfo & destination,
  533. const PathfinderConfig * pathfinderConfig,
  534. const CPathfinderHelper * pathfinderHelper) const
  535. {
  536. if(destination.node->accessible == CGPathNode::BLOCKED)
  537. return BlockingReason::DESTINATION_BLOCKED;
  538. switch(destination.node->layer)
  539. {
  540. case EPathfindingLayer::LAND:
  541. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  542. return BlockingReason::DESTINATION_BLOCKED;
  543. if(source.guarded)
  544. {
  545. if(!(pathfinderConfig->options.originalMovementRules && source.node->layer == EPathfindingLayer::AIR) &&
  546. !destination.isGuardianTile) // Can step into tile of guard
  547. {
  548. return BlockingReason::SOURCE_GUARDED;
  549. }
  550. }
  551. break;
  552. case EPathfindingLayer::SAIL:
  553. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord))
  554. return BlockingReason::DESTINATION_BLOCKED;
  555. if(source.guarded)
  556. {
  557. // Hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  558. if(source.node->action != CGPathNode::EMBARK && !destination.isGuardianTile)
  559. return BlockingReason::SOURCE_GUARDED;
  560. }
  561. if(source.node->layer == EPathfindingLayer::LAND)
  562. {
  563. if(!destination.isNodeObjectVisitable())
  564. return BlockingReason::DESTINATION_BLOCKED;
  565. if(destination.nodeObject->ID != Obj::BOAT && !destination.nodeHero)
  566. return BlockingReason::DESTINATION_BLOCKED;
  567. }
  568. else if(destination.isNodeObjectVisitable() && destination.nodeObject->ID == Obj::BOAT)
  569. {
  570. /// Hero in boat can't visit empty boats
  571. return BlockingReason::DESTINATION_BLOCKED;
  572. }
  573. break;
  574. case EPathfindingLayer::WATER:
  575. if(!pathfinderHelper->canMoveBetween(source.coord, destination.coord)
  576. || destination.node->accessible != CGPathNode::ACCESSIBLE)
  577. {
  578. return BlockingReason::DESTINATION_BLOCKED;
  579. }
  580. if(destination.guarded)
  581. return BlockingReason::DESTINATION_BLOCKED;
  582. break;
  583. }
  584. return BlockingReason::NONE;
  585. }
  586. void MovementAfterDestinationRule::process(
  587. const PathNodeInfo & source,
  588. CDestinationNodeInfo & destination,
  589. const PathfinderConfig * config,
  590. CPathfinderHelper * pathfinderHelper) const
  591. {
  592. auto blocker = getBlockingReason(source, destination, config, pathfinderHelper);
  593. if(blocker == BlockingReason::DESTINATION_GUARDED && destination.action == CGPathNode::ENodeAction::BATTLE)
  594. {
  595. return; // allow bypass guarded tile but only in direction of guard, a bit UI related thing
  596. }
  597. destination.blocked = blocker != BlockingReason::NONE;
  598. }
  599. PathfinderBlockingRule::BlockingReason MovementAfterDestinationRule::getBlockingReason(
  600. const PathNodeInfo & source,
  601. const CDestinationNodeInfo & destination,
  602. const PathfinderConfig * config,
  603. const CPathfinderHelper * pathfinderHelper) const
  604. {
  605. switch(destination.action)
  606. {
  607. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  608. /// Likely in many cases we don't need to add visitable tile to queue when hero don't fly
  609. case CGPathNode::VISIT:
  610. {
  611. /// For now we only add visitable tile into queue when it's teleporter that allow transit
  612. /// Movement from visitable tile when hero is standing on it is possible into any layer
  613. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(destination.nodeObject);
  614. if(pathfinderHelper->isAllowedTeleportEntrance(objTeleport))
  615. {
  616. /// For now we'll always allow transit over teleporters
  617. /// Transit over whirlpools only allowed when hero protected
  618. return BlockingReason::NONE;
  619. }
  620. else if(destination.nodeObject->ID == Obj::GARRISON
  621. || destination.nodeObject->ID == Obj::GARRISON2
  622. || destination.nodeObject->ID == Obj::BORDER_GATE)
  623. {
  624. /// Transit via unguarded garrisons is always possible
  625. return BlockingReason::NONE;
  626. }
  627. return BlockingReason::DESTINATION_VISIT;
  628. }
  629. case CGPathNode::BLOCKING_VISIT:
  630. return destination.guarded
  631. ? BlockingReason::DESTINATION_GUARDED
  632. : BlockingReason::DESTINATION_BLOCKVIS;
  633. case CGPathNode::NORMAL:
  634. return BlockingReason::NONE;
  635. case CGPathNode::EMBARK:
  636. if(pathfinderHelper->options.useEmbarkAndDisembark)
  637. return BlockingReason::NONE;
  638. return BlockingReason::DESTINATION_BLOCKED;
  639. case CGPathNode::DISEMBARK:
  640. if(pathfinderHelper->options.useEmbarkAndDisembark)
  641. return destination.guarded ? BlockingReason::DESTINATION_GUARDED : BlockingReason::NONE;
  642. return BlockingReason::DESTINATION_BLOCKED;
  643. case CGPathNode::BATTLE:
  644. /// Movement after BATTLE action only possible from guarded tile to guardian tile
  645. if(destination.guarded)
  646. return BlockingReason::DESTINATION_GUARDED;
  647. break;
  648. }
  649. return BlockingReason::DESTINATION_BLOCKED;
  650. }
  651. void DestinationActionRule::process(
  652. const PathNodeInfo & source,
  653. CDestinationNodeInfo & destination,
  654. const PathfinderConfig * pathfinderConfig,
  655. CPathfinderHelper * pathfinderHelper) const
  656. {
  657. if(destination.action != CGPathNode::ENodeAction::UNKNOWN)
  658. {
  659. #ifdef VCMI_TRACE_PATHFINDER
  660. logAi->trace("Accepted precalculated action at %s", destination.coord.toString());
  661. #endif
  662. return;
  663. }
  664. CGPathNode::ENodeAction action = CGPathNode::NORMAL;
  665. auto hero = pathfinderHelper->hero;
  666. switch(destination.node->layer)
  667. {
  668. case EPathfindingLayer::LAND:
  669. if(source.node->layer == EPathfindingLayer::SAIL)
  670. {
  671. // TODO: Handle dismebark into guarded areaa
  672. action = CGPathNode::DISEMBARK;
  673. break;
  674. }
  675. /// don't break - next case shared for both land and sail layers
  676. FALLTHROUGH
  677. case EPathfindingLayer::SAIL:
  678. if(destination.isNodeObjectVisitable())
  679. {
  680. auto objRel = destination.objectRelations;
  681. if(destination.nodeObject->ID == Obj::BOAT)
  682. action = CGPathNode::EMBARK;
  683. else if(destination.nodeHero)
  684. {
  685. if(destination.heroRelations == PlayerRelations::ENEMIES)
  686. action = CGPathNode::BATTLE;
  687. else
  688. action = CGPathNode::BLOCKING_VISIT;
  689. }
  690. else if(destination.nodeObject->ID == Obj::TOWN)
  691. {
  692. if(destination.nodeObject->passableFor(hero->tempOwner))
  693. action = CGPathNode::VISIT;
  694. else if(objRel == PlayerRelations::ENEMIES)
  695. action = CGPathNode::BATTLE;
  696. }
  697. else if(destination.nodeObject->ID == Obj::GARRISON || destination.nodeObject->ID == Obj::GARRISON2)
  698. {
  699. if(destination.nodeObject->passableFor(hero->tempOwner))
  700. {
  701. if(destination.guarded)
  702. action = CGPathNode::BATTLE;
  703. }
  704. else if(objRel == PlayerRelations::ENEMIES)
  705. action = CGPathNode::BATTLE;
  706. }
  707. else if(destination.nodeObject->ID == Obj::BORDER_GATE)
  708. {
  709. if(destination.nodeObject->passableFor(hero->tempOwner))
  710. {
  711. if(destination.guarded)
  712. action = CGPathNode::BATTLE;
  713. }
  714. else
  715. action = CGPathNode::BLOCKING_VISIT;
  716. }
  717. else if(destination.isGuardianTile)
  718. action = CGPathNode::BATTLE;
  719. else if(destination.nodeObject->blockVisit && !(pathfinderConfig->options.useCastleGate && destination.nodeObject->ID == Obj::TOWN))
  720. action = CGPathNode::BLOCKING_VISIT;
  721. if(action == CGPathNode::NORMAL)
  722. {
  723. if(destination.guarded)
  724. action = CGPathNode::BATTLE;
  725. else
  726. action = CGPathNode::VISIT;
  727. }
  728. }
  729. else if(destination.guarded)
  730. action = CGPathNode::BATTLE;
  731. break;
  732. }
  733. destination.action = action;
  734. }
  735. CGPathNode::ENodeAction CPathfinder::getTeleportDestAction() const
  736. {
  737. CGPathNode::ENodeAction action = CGPathNode::TELEPORT_NORMAL;
  738. if(destination.isNodeObjectVisitable() && destination.nodeHero)
  739. {
  740. if(destination.heroRelations == PlayerRelations::ENEMIES)
  741. action = CGPathNode::TELEPORT_BATTLE;
  742. else
  743. action = CGPathNode::TELEPORT_BLOCKING_VISIT;
  744. }
  745. return action;
  746. }
  747. bool CPathfinder::isDestinationGuardian() const
  748. {
  749. return gs->guardingCreaturePosition(source.node->coord) == destination.node->coord;
  750. }
  751. void CPathfinderHelper::initializePatrol()
  752. {
  753. auto state = PATROL_NONE;
  754. if(hero->patrol.patrolling && !getPlayerState(hero->tempOwner)->human)
  755. {
  756. if(hero->patrol.patrolRadius)
  757. {
  758. state = PATROL_RADIUS;
  759. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, boost::optional<PlayerColor>(), 0, int3::DIST_MANHATTAN);
  760. }
  761. else
  762. state = PATROL_LOCKED;
  763. }
  764. patrolState = state;
  765. }
  766. void CPathfinder::initializeGraph()
  767. {
  768. INodeStorage * nodeStorage = config->nodeStorage.get();
  769. nodeStorage->initialize(config->options, gs);
  770. }
  771. bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
  772. {
  773. return gs->checkForVisitableDir(a, b);
  774. }
  775. bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
  776. {
  777. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  778. return false;
  779. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  780. if(whirlpool)
  781. {
  782. if(addTeleportWhirlpool(whirlpool))
  783. return true;
  784. }
  785. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  786. return true;
  787. return false;
  788. }
  789. bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
  790. {
  791. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  792. }
  793. bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
  794. {
  795. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  796. {
  797. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  798. if(passableExits.size() == 1)
  799. return true;
  800. }
  801. return false;
  802. }
  803. bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
  804. {
  805. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  806. {
  807. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  808. if(passableExits.size() > 1)
  809. return true;
  810. }
  811. return false;
  812. }
  813. bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
  814. {
  815. return options.useTeleportWhirlpool && hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  816. }
  817. int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
  818. {
  819. return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
  820. }
  821. bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
  822. {
  823. if(!options.oneTurnSpecialLayersLimit)
  824. return true;
  825. if(source.node->layer == EPathfindingLayer::WATER)
  826. return false;
  827. if(source.node->layer == EPathfindingLayer::AIR)
  828. {
  829. if(options.originalMovementRules && source.node->accessible == CGPathNode::ACCESSIBLE)
  830. return true;
  831. else
  832. return false;
  833. }
  834. return true;
  835. }
  836. TurnInfo::BonusCache::BonusCache(TConstBonusListPtr bl)
  837. {
  838. for(int i = 0; i < Terrain::Manager::terrains().size(); ++i)
  839. {
  840. noTerrainPenalty.push_back(static_cast<bool>(
  841. bl->getFirst(Selector::type()(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype()(i)))));
  842. }
  843. freeShipBoarding = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FREE_SHIP_BOARDING)));
  844. flyingMovement = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::FLYING_MOVEMENT)));
  845. flyingMovementVal = bl->valOfBonuses(Selector::type()(Bonus::FLYING_MOVEMENT));
  846. waterWalking = static_cast<bool>(bl->getFirst(Selector::type()(Bonus::WATER_WALKING)));
  847. waterWalkingVal = bl->valOfBonuses(Selector::type()(Bonus::WATER_WALKING));
  848. }
  849. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  850. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  851. {
  852. bonuses = hero->getAllBonuses(Selector::days(turn), Selector::all, nullptr, "");
  853. bonusCache = make_unique<BonusCache>(bonuses);
  854. nativeTerrain = hero->getNativeTerrain();
  855. }
  856. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  857. {
  858. switch(layer)
  859. {
  860. case EPathfindingLayer::AIR:
  861. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  862. return false;
  863. break;
  864. case EPathfindingLayer::WATER:
  865. if(!hasBonusOfType(Bonus::WATER_WALKING))
  866. return false;
  867. break;
  868. }
  869. return true;
  870. }
  871. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  872. {
  873. switch(type)
  874. {
  875. case Bonus::FREE_SHIP_BOARDING:
  876. return bonusCache->freeShipBoarding;
  877. case Bonus::FLYING_MOVEMENT:
  878. return bonusCache->flyingMovement;
  879. case Bonus::WATER_WALKING:
  880. return bonusCache->waterWalking;
  881. case Bonus::NO_TERRAIN_PENALTY:
  882. return bonusCache->noTerrainPenalty[subtype];
  883. }
  884. return static_cast<bool>(
  885. bonuses->getFirst(Selector::type()(type).And(Selector::subtype()(subtype))));
  886. }
  887. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  888. {
  889. switch(type)
  890. {
  891. case Bonus::FLYING_MOVEMENT:
  892. return bonusCache->flyingMovementVal;
  893. case Bonus::WATER_WALKING:
  894. return bonusCache->waterWalkingVal;
  895. }
  896. return bonuses->valOfBonuses(Selector::type()(type).And(Selector::subtype()(subtype)));
  897. }
  898. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  899. {
  900. if(maxMovePointsLand == -1)
  901. maxMovePointsLand = hero->maxMovePointsCached(true, this);
  902. if(maxMovePointsWater == -1)
  903. maxMovePointsWater = hero->maxMovePointsCached(false, this);
  904. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  905. }
  906. CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options)
  907. : CGameInfoCallback(gs, boost::optional<PlayerColor>()), turn(-1), hero(Hero), options(Options), owner(Hero->tempOwner)
  908. {
  909. turnsInfo.reserve(16);
  910. updateTurnInfo();
  911. initializePatrol();
  912. }
  913. CPathfinderHelper::~CPathfinderHelper()
  914. {
  915. for(auto ti : turnsInfo)
  916. delete ti;
  917. }
  918. void CPathfinderHelper::updateTurnInfo(const int Turn)
  919. {
  920. if(turn != Turn)
  921. {
  922. turn = Turn;
  923. if(turn >= turnsInfo.size())
  924. {
  925. auto ti = new TurnInfo(hero, turn);
  926. turnsInfo.push_back(ti);
  927. }
  928. }
  929. }
  930. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  931. {
  932. switch(layer)
  933. {
  934. case EPathfindingLayer::AIR:
  935. if(!options.useFlying)
  936. return false;
  937. break;
  938. case EPathfindingLayer::WATER:
  939. if(!options.useWaterWalking)
  940. return false;
  941. break;
  942. }
  943. return turnsInfo[turn]->isLayerAvailable(layer);
  944. }
  945. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  946. {
  947. return turnsInfo[turn];
  948. }
  949. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  950. {
  951. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  952. }
  953. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  954. {
  955. return turnsInfo[turn]->getMaxMovePoints(layer);
  956. }
  957. void CPathfinderHelper::getNeighbours(
  958. const TerrainTile & srct,
  959. const int3 & tile,
  960. std::vector<int3> & vec,
  961. const boost::logic::tribool & onLand,
  962. const bool limitCoastSailing) const
  963. {
  964. CMap * map = gs->map;
  965. static const int3 dirs[] = {
  966. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  967. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  968. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  969. };
  970. for(auto & dir : dirs)
  971. {
  972. const int3 hlp = tile + dir;
  973. if(!map->isInTheMap(hlp))
  974. continue;
  975. const TerrainTile & hlpt = map->getTile(hlp);
  976. if(!hlpt.terType.isPassable())
  977. continue;
  978. // //we cannot visit things from blocked tiles
  979. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  980. // {
  981. // continue;
  982. // }
  983. /// Following condition let us avoid diagonal movement over coast when sailing
  984. if(srct.terType.isWater() && limitCoastSailing && hlpt.terType.isWater() && dir.x && dir.y) //diagonal move through water
  985. {
  986. int3 hlp1 = tile,
  987. hlp2 = tile;
  988. hlp1.x += dir.x;
  989. hlp2.y += dir.y;
  990. if(map->getTile(hlp1).terType.isLand() || map->getTile(hlp2).terType.isLand())
  991. continue;
  992. }
  993. if(indeterminate(onLand) || onLand == hlpt.terType.isLand())
  994. {
  995. vec.push_back(hlp);
  996. }
  997. }
  998. }
  999. int CPathfinderHelper::getMovementCost(
  1000. const int3 & src,
  1001. const int3 & dst,
  1002. const TerrainTile * ct,
  1003. const TerrainTile * dt,
  1004. const int remainingMovePoints,
  1005. const bool checkLast) const
  1006. {
  1007. if(src == dst) //same tile
  1008. return 0;
  1009. auto ti = getTurnInfo();
  1010. if(ct == nullptr || dt == nullptr)
  1011. {
  1012. ct = hero->cb->getTile(src);
  1013. dt = hero->cb->getTile(dst);
  1014. }
  1015. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  1016. /// Also flying movement only has penalty when player moving over blocked tiles.
  1017. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  1018. ui32 ret = hero->getTileCost(*dt, *ct, ti);
  1019. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  1020. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  1021. /// So this one is waiting till server going to use pathfinder rules for path validation.
  1022. if(dt->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1023. {
  1024. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0);
  1025. }
  1026. else if(dt->terType.isWater())
  1027. {
  1028. if(hero->boat && ct->hasFavorableWinds() && dt->hasFavorableWinds())
  1029. ret = static_cast<int>(ret * 0.666);
  1030. else if(!hero->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  1031. {
  1032. ret = static_cast<int>(ret * (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0);
  1033. }
  1034. }
  1035. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  1036. {
  1037. int old = ret;
  1038. ret = static_cast < int>(ret * 1.414213);
  1039. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1040. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1041. {
  1042. return remainingMovePoints;
  1043. }
  1044. }
  1045. /// TODO: This part need rework in order to work properly with flying and water walking
  1046. /// Currently it's only work properly for normal movement or sailing
  1047. int left = remainingMovePoints-ret;
  1048. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1049. {
  1050. std::vector<int3> vec;
  1051. vec.reserve(8); //optimization
  1052. getNeighbours(*dt, dst, vec, ct->terType.isLand(), true);
  1053. for(auto & elem : vec)
  1054. {
  1055. int fcost = getMovementCost(dst, elem, nullptr, nullptr, left, false);
  1056. if(fcost <= left)
  1057. {
  1058. return ret;
  1059. }
  1060. }
  1061. ret = remainingMovePoints;
  1062. }
  1063. return ret;
  1064. }
  1065. int3 CGPath::startPos() const
  1066. {
  1067. return nodes[nodes.size()-1].coord;
  1068. }
  1069. int3 CGPath::endPos() const
  1070. {
  1071. return nodes[0].coord;
  1072. }
  1073. void CGPath::convert(ui8 mode)
  1074. {
  1075. if(mode==0)
  1076. {
  1077. for(auto & elem : nodes)
  1078. {
  1079. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  1080. }
  1081. }
  1082. }
  1083. CPathsInfo::CPathsInfo(const int3 & Sizes, const CGHeroInstance * hero_)
  1084. : sizes(Sizes), hero(hero_)
  1085. {
  1086. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  1087. }
  1088. CPathsInfo::~CPathsInfo() = default;
  1089. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  1090. {
  1091. assert(vstd::iswithin(tile.x, 0, sizes.x));
  1092. assert(vstd::iswithin(tile.y, 0, sizes.y));
  1093. assert(vstd::iswithin(tile.z, 0, sizes.z));
  1094. return getNode(tile);
  1095. }
  1096. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  1097. {
  1098. out.nodes.clear();
  1099. const CGPathNode * curnode = getNode(dst);
  1100. if(!curnode->theNodeBefore)
  1101. return false;
  1102. while(curnode)
  1103. {
  1104. const CGPathNode cpn = * curnode;
  1105. curnode = curnode->theNodeBefore;
  1106. out.nodes.push_back(cpn);
  1107. }
  1108. return true;
  1109. }
  1110. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  1111. {
  1112. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  1113. if(landNode->reachable())
  1114. return landNode;
  1115. else
  1116. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  1117. }
  1118. PathNodeInfo::PathNodeInfo()
  1119. : node(nullptr), nodeObject(nullptr), tile(nullptr), coord(-1, -1, -1), guarded(false), isInitialPosition(false)
  1120. {
  1121. }
  1122. void PathNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1123. {
  1124. node = n;
  1125. if(coord != node->coord)
  1126. {
  1127. assert(node->coord.valid());
  1128. coord = node->coord;
  1129. tile = gs->getTile(coord);
  1130. nodeObject = tile->topVisitableObj();
  1131. if(nodeObject && nodeObject->ID == Obj::HERO)
  1132. {
  1133. nodeHero = dynamic_cast<const CGHeroInstance *>(nodeObject);
  1134. nodeObject = tile->topVisitableObj(true);
  1135. if(!nodeObject)
  1136. nodeObject = nodeHero;
  1137. }
  1138. else
  1139. {
  1140. nodeHero = nullptr;
  1141. }
  1142. }
  1143. guarded = false;
  1144. }
  1145. void PathNodeInfo::updateInfo(CPathfinderHelper * hlp, CGameState * gs)
  1146. {
  1147. if(gs->guardingCreaturePosition(node->coord).valid() && !isInitialPosition)
  1148. {
  1149. guarded = true;
  1150. }
  1151. if(nodeObject)
  1152. {
  1153. objectRelations = gs->getPlayerRelations(hlp->owner, nodeObject->tempOwner);
  1154. }
  1155. if(nodeHero)
  1156. {
  1157. heroRelations = gs->getPlayerRelations(hlp->owner, nodeHero->tempOwner);
  1158. }
  1159. }
  1160. CDestinationNodeInfo::CDestinationNodeInfo()
  1161. : PathNodeInfo(),
  1162. blocked(false),
  1163. action(CGPathNode::ENodeAction::UNKNOWN)
  1164. {
  1165. }
  1166. void CDestinationNodeInfo::setNode(CGameState * gs, CGPathNode * n)
  1167. {
  1168. PathNodeInfo::setNode(gs, n);
  1169. blocked = false;
  1170. action = CGPathNode::ENodeAction::UNKNOWN;
  1171. }
  1172. bool CDestinationNodeInfo::isBetterWay() const
  1173. {
  1174. if(node->turns == 0xff) //we haven't been here before
  1175. return true;
  1176. else
  1177. return cost < node->getCost(); //this route is faster
  1178. }
  1179. bool PathNodeInfo::isNodeObjectVisitable() const
  1180. {
  1181. /// Hero can't visit objects while walking on water or flying
  1182. return (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1183. && (canSeeObj(nodeObject) || canSeeObj(nodeHero));
  1184. }