CPathfinder.cpp 39 KB

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