CPathfinder.cpp 39 KB

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