CPathfinder.cpp 39 KB

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