CPathfinder.cpp 39 KB

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