CPathfinder.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. #include "StdInc.h"
  2. #include "CPathfinder.h"
  3. #include "CHeroHandler.h"
  4. #include "mapping/CMap.h"
  5. #include "CGameState.h"
  6. #include "mapObjects/CGHeroInstance.h"
  7. #include "GameConstants.h"
  8. #include "CStopWatch.h"
  9. #include "CConfigHandler.h"
  10. #include "../lib/CPlayerState.h"
  11. /*
  12. * CPathfinder.cpp, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. CPathfinder::PathfinderOptions::PathfinderOptions()
  21. {
  22. useFlying = settings["pathfinder"]["layers"]["flying"].Bool();
  23. useWaterWalking = settings["pathfinder"]["layers"]["waterWalking"].Bool();
  24. useEmbarkAndDisembark = settings["pathfinder"]["layers"]["sailing"].Bool();
  25. useTeleportTwoWay = settings["pathfinder"]["teleports"]["twoWay"].Bool();
  26. useTeleportOneWay = settings["pathfinder"]["teleports"]["oneWay"].Bool();
  27. useTeleportOneWayRandom = settings["pathfinder"]["teleports"]["oneWayRandom"].Bool();
  28. useTeleportWhirlpool = settings["pathfinder"]["teleports"]["whirlpool"].Bool();
  29. useCastleGate = settings["pathfinder"]["teleports"]["castleGate"].Bool();
  30. lightweightFlyingMode = settings["pathfinder"]["lightweightFlyingMode"].Bool();
  31. oneTurnSpecialLayersLimit = settings["pathfinder"]["oneTurnSpecialLayersLimit"].Bool();
  32. originalMovementRules = settings["pathfinder"]["originalMovementRules"].Bool();
  33. }
  34. CPathfinder::CPathfinder(CPathsInfo & _out, CGameState * _gs, const CGHeroInstance * _hero)
  35. : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap), patrolTiles({})
  36. {
  37. assert(hero);
  38. assert(hero == getHero(hero->id));
  39. out.hero = hero;
  40. out.hpos = hero->getPosition(false);
  41. if(!isInTheMap(out.hpos)/* || !gs->map->isInTheMap(dest)*/) //check input
  42. {
  43. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  44. throw std::runtime_error("Wrong checksum");
  45. }
  46. hlp = make_unique<CPathfinderHelper>(hero, options);
  47. initializePatrol();
  48. initializeGraph();
  49. neighbourTiles.reserve(8);
  50. neighbours.reserve(16);
  51. }
  52. void CPathfinder::calculatePaths()
  53. {
  54. auto passOneTurnLimitCheck = [&]() -> bool
  55. {
  56. if(!options.oneTurnSpecialLayersLimit)
  57. return true;
  58. if(cp->layer == ELayer::WATER)
  59. return false;
  60. if(cp->layer == ELayer::AIR)
  61. {
  62. if(options.originalMovementRules && cp->accessible == CGPathNode::ACCESSIBLE)
  63. return true;
  64. else
  65. return false;
  66. }
  67. return true;
  68. };
  69. auto isBetterWay = [&](int remains, int turn) -> bool
  70. {
  71. if(dp->turns == 0xff) //we haven't been here before
  72. return true;
  73. else if(dp->turns > turn)
  74. return true;
  75. else if(dp->turns >= turn && dp->moveRemains < remains) //this route is faster
  76. return true;
  77. return false;
  78. };
  79. //logGlobal->infoStream() << boost::format("Calculating paths for hero %s (adress %d) of player %d") % hero->name % hero % hero->tempOwner;
  80. //initial tile - set cost on 0 and add to the queue
  81. CGPathNode * initialNode = out.getNode(out.hpos, hero->boat ? ELayer::SAIL : ELayer::LAND);
  82. initialNode->turns = 0;
  83. initialNode->moveRemains = hero->movement;
  84. if(isHeroPatrolLocked())
  85. return;
  86. pq.push(initialNode);
  87. while(!pq.empty())
  88. {
  89. cp = pq.top();
  90. pq.pop();
  91. cp->locked = true;
  92. int movement = cp->moveRemains, turn = cp->turns;
  93. hlp->updateTurnInfo(turn);
  94. if(!movement)
  95. {
  96. hlp->updateTurnInfo(++turn);
  97. movement = hlp->getMaxMovePoints(cp->layer);
  98. if(!passOneTurnLimitCheck())
  99. continue;
  100. }
  101. ct = &gs->map->getTile(cp->coord);
  102. ctObj = ct->topVisitableObj(isSourceInitialPosition());
  103. //add accessible neighbouring nodes to the queue
  104. addNeighbours();
  105. for(auto & neighbour : neighbours)
  106. {
  107. if(!isPatrolMovementAllowed(neighbour))
  108. continue;
  109. dt = &gs->map->getTile(neighbour);
  110. dtObj = dt->topVisitableObj();
  111. for(ELayer i = ELayer::LAND; i <= ELayer::AIR; i.advance(1))
  112. {
  113. if(!hlp->isLayerAvailable(i))
  114. continue;
  115. if(cp->layer != i && !isLayerTransitionPossible(i))
  116. continue;
  117. dp = out.getNode(neighbour, i);
  118. if(dp->locked)
  119. continue;
  120. if(dp->accessible == CGPathNode::NOT_SET)
  121. continue;
  122. if(cp->layer != i && !isLayerTransitionPossible())
  123. continue;
  124. if(!isMovementToDestPossible())
  125. continue;
  126. destAction = getDestAction();
  127. int cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, ct, dt, movement, hlp->getTurnInfo());
  128. int remains = movement - cost;
  129. if(destAction == CGPathNode::EMBARK || destAction == CGPathNode::DISEMBARK)
  130. {
  131. remains = hero->movementPointsAfterEmbark(movement, cost, destAction - 1, hlp->getTurnInfo());
  132. cost = movement - remains;
  133. }
  134. int turnAtNextTile = turn;
  135. if(remains < 0)
  136. {
  137. //occurs rarely, when hero with low movepoints tries to leave the road
  138. hlp->updateTurnInfo(++turnAtNextTile);
  139. int moveAtNextTile = hlp->getMaxMovePoints(i);
  140. cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, ct, dt, moveAtNextTile, hlp->getTurnInfo()); //cost must be updated, movement points changed :(
  141. remains = moveAtNextTile - cost;
  142. }
  143. if(isBetterWay(remains, turnAtNextTile) &&
  144. ((cp->turns == turnAtNextTile && remains) || passOneTurnLimitCheck()))
  145. {
  146. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  147. dp->moveRemains = remains;
  148. dp->turns = turnAtNextTile;
  149. dp->theNodeBefore = cp;
  150. dp->action = destAction;
  151. if(isMovementAfterDestPossible())
  152. pq.push(dp);
  153. }
  154. }
  155. } //neighbours loop
  156. //just add all passable teleport exits
  157. addTeleportExits();
  158. for(auto & neighbour : neighbours)
  159. {
  160. dp = out.getNode(neighbour, cp->layer);
  161. if(dp->locked)
  162. continue;
  163. if(isBetterWay(movement, turn))
  164. {
  165. dp->moveRemains = movement;
  166. dp->turns = turn;
  167. dp->theNodeBefore = cp;
  168. dp->action = CGPathNode::NORMAL;
  169. pq.push(dp);
  170. }
  171. }
  172. } //queue loop
  173. }
  174. void CPathfinder::addNeighbours()
  175. {
  176. neighbours.clear();
  177. neighbourTiles.clear();
  178. CPathfinderHelper::getNeighbours(gs->map, *ct, cp->coord, neighbourTiles, boost::logic::indeterminate, cp->layer == ELayer::SAIL);
  179. if(isSourceVisitableObj())
  180. {
  181. for(int3 tile: neighbourTiles)
  182. {
  183. if(canMoveBetween(tile, ctObj->visitablePos()))
  184. neighbours.push_back(tile);
  185. }
  186. }
  187. else
  188. vstd::concatenate(neighbours, neighbourTiles);
  189. }
  190. void CPathfinder::addTeleportExits()
  191. {
  192. neighbours.clear();
  193. /// For now we disable teleports usage for patrol movement
  194. /// VCAI not aware about patrol and may stuck while attempt to use teleport
  195. if(!isSourceVisitableObj() || patrolState == PATROL_RADIUS)
  196. return;
  197. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(ctObj);
  198. if(isAllowedTeleportEntrance(objTeleport))
  199. {
  200. for(auto objId : getTeleportChannelExits(objTeleport->channel, hero->tempOwner))
  201. {
  202. auto obj = getObj(objId);
  203. if(dynamic_cast<const CGWhirlpool *>(obj))
  204. {
  205. auto pos = obj->getBlockedPos();
  206. for(auto p : pos)
  207. {
  208. if(gs->map->getTile(p).topVisitableId() == obj->ID)
  209. neighbours.push_back(p);
  210. }
  211. }
  212. else if(CGTeleport::isExitPassable(gs, hero, obj))
  213. neighbours.push_back(obj->visitablePos());
  214. }
  215. }
  216. if(options.useCastleGate
  217. && (ctObj->ID == Obj::TOWN && ctObj->subID == ETownType::INFERNO
  218. && getPlayerRelations(hero->tempOwner, ctObj->tempOwner) != PlayerRelations::ENEMIES))
  219. {
  220. /// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
  221. /// This may be handy if we allow to use teleportation to friendly towns
  222. auto towns = getPlayer(hero->tempOwner)->towns;
  223. for(const auto & town : towns)
  224. {
  225. if(town->id != ctObj->id && town->visitingHero == nullptr
  226. && town->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  227. {
  228. neighbours.push_back(town->visitablePos());
  229. }
  230. }
  231. }
  232. }
  233. bool CPathfinder::isHeroPatrolLocked() const
  234. {
  235. return patrolState == PATROL_LOCKED;
  236. }
  237. bool CPathfinder::isPatrolMovementAllowed(const int3 & dst) const
  238. {
  239. if(patrolState == PATROL_RADIUS)
  240. {
  241. if(!vstd::contains(patrolTiles, dst))
  242. return false;
  243. }
  244. return true;
  245. }
  246. bool CPathfinder::isLayerTransitionPossible(const ELayer destLayer) const
  247. {
  248. /// No layer transition allowed when previous node action is BATTLE
  249. if(cp->action == CGPathNode::BATTLE)
  250. return false;
  251. switch(cp->layer)
  252. {
  253. case ELayer::LAND:
  254. if(destLayer != ELayer::AIR)
  255. return true;
  256. if(!options.lightweightFlyingMode || isSourceInitialPosition())
  257. return true;
  258. break;
  259. case ELayer::SAIL:
  260. if(destLayer == ELayer::LAND && dt->isCoastal())
  261. return true;
  262. break;
  263. case ELayer::AIR:
  264. if(destLayer == ELayer::LAND)
  265. return true;
  266. break;
  267. case ELayer::WATER:
  268. if(destLayer == ELayer::LAND)
  269. return true;
  270. break;
  271. }
  272. return false;
  273. }
  274. bool CPathfinder::isLayerTransitionPossible() const
  275. {
  276. switch(cp->layer)
  277. {
  278. case ELayer::LAND:
  279. if(dp->layer == ELayer::SAIL)
  280. {
  281. /// Cannot enter empty water tile from land -> it has to be visitable
  282. if(dp->accessible == CGPathNode::ACCESSIBLE)
  283. return false;
  284. }
  285. break;
  286. case ELayer::SAIL:
  287. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  288. if((dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  289. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  290. {
  291. return false;
  292. }
  293. break;
  294. case ELayer::AIR:
  295. if(options.originalMovementRules)
  296. {
  297. if((cp->accessible != CGPathNode::ACCESSIBLE &&
  298. cp->accessible != CGPathNode::VISITABLE) &&
  299. (dp->accessible != CGPathNode::VISITABLE &&
  300. dp->accessible != CGPathNode::ACCESSIBLE))
  301. {
  302. return false;
  303. }
  304. }
  305. else if(cp->accessible != CGPathNode::ACCESSIBLE && dp->accessible != CGPathNode::ACCESSIBLE)
  306. {
  307. /// Hero that fly can only land on accessible tiles
  308. return false;
  309. }
  310. break;
  311. }
  312. return true;
  313. }
  314. bool CPathfinder::isMovementToDestPossible() const
  315. {
  316. if(dp->accessible == CGPathNode::BLOCKED)
  317. return false;
  318. switch(dp->layer)
  319. {
  320. case ELayer::LAND:
  321. if(!canMoveBetween(cp->coord, dp->coord))
  322. return false;
  323. if(isSourceGuarded())
  324. {
  325. if(!(options.originalMovementRules && cp->layer == ELayer::AIR) &&
  326. !isDestinationGuardian()) // Can step into tile of guard
  327. {
  328. return false;
  329. }
  330. }
  331. break;
  332. case ELayer::SAIL:
  333. if(!canMoveBetween(cp->coord, dp->coord))
  334. return false;
  335. if(isSourceGuarded())
  336. {
  337. // Hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  338. if(cp->action != CGPathNode::EMBARK && !isDestinationGuardian())
  339. return false;
  340. }
  341. if(cp->layer == ELayer::LAND)
  342. {
  343. if(!isDestVisitableObj())
  344. return false;
  345. if(dtObj->ID != Obj::BOAT && dtObj->ID != Obj::HERO)
  346. return false;
  347. }
  348. else if(isDestVisitableObj() && dtObj->ID == Obj::BOAT)
  349. {
  350. /// Hero in boat can't visit empty boats
  351. return false;
  352. }
  353. break;
  354. case ELayer::WATER:
  355. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible != CGPathNode::ACCESSIBLE)
  356. return false;
  357. if(isDestinationGuarded())
  358. return false;
  359. break;
  360. }
  361. return true;
  362. }
  363. bool CPathfinder::isMovementAfterDestPossible() const
  364. {
  365. switch(destAction)
  366. {
  367. /// TODO: Investigate what kind of limitation is possible to apply on movement from visitable tiles
  368. /// Likely in many cases we don't need to add visitable tile to queue when hero don't fly
  369. case CGPathNode::VISIT:
  370. {
  371. /// For now we only add visitable tile into queue when it's teleporter that allow transit
  372. /// Movement from visitable tile when hero is standing on it is possible into any layer
  373. const CGTeleport * objTeleport = dynamic_cast<const CGTeleport *>(dtObj);
  374. if(isAllowedTeleportEntrance(objTeleport))
  375. {
  376. /// For now we'll always allow transit over teleporters
  377. /// Transit over whirlpools only allowed when hero protected
  378. return true;
  379. }
  380. else if(dtObj->ID == Obj::GARRISON || dtObj->ID == Obj::GARRISON2)
  381. {
  382. /// Transit via unguarded garrisons is always possible
  383. return true;
  384. }
  385. break;
  386. }
  387. case CGPathNode::NORMAL:
  388. return true;
  389. case CGPathNode::EMBARK:
  390. if(options.useEmbarkAndDisembark)
  391. return true;
  392. break;
  393. case CGPathNode::DISEMBARK:
  394. if(options.useEmbarkAndDisembark && !isDestinationGuarded())
  395. return true;
  396. break;
  397. case CGPathNode::BATTLE:
  398. /// Movement after BATTLE action only possible from guarded tile to guardian tile
  399. if(isDestinationGuarded())
  400. return true;
  401. break;
  402. }
  403. return false;
  404. }
  405. CGPathNode::ENodeAction CPathfinder::getDestAction() const
  406. {
  407. CGPathNode::ENodeAction action = CGPathNode::NORMAL;
  408. switch(dp->layer)
  409. {
  410. case ELayer::LAND:
  411. if(cp->layer == ELayer::SAIL)
  412. {
  413. // TODO: Handle dismebark into guarded areaa
  414. action = CGPathNode::DISEMBARK;
  415. break;
  416. }
  417. /// don't break - next case shared for both land and sail layers
  418. case ELayer::SAIL:
  419. if(isDestVisitableObj())
  420. {
  421. auto objRel = getPlayerRelations(dtObj->tempOwner, hero->tempOwner);
  422. if(dtObj->ID == Obj::BOAT)
  423. action = CGPathNode::EMBARK;
  424. else if(dtObj->ID == Obj::HERO)
  425. {
  426. if(objRel == PlayerRelations::ENEMIES)
  427. action = CGPathNode::BATTLE;
  428. else
  429. action = CGPathNode::BLOCKING_VISIT;
  430. }
  431. else if(dtObj->ID == Obj::TOWN && objRel == PlayerRelations::ENEMIES)
  432. {
  433. const CGTownInstance * townObj = dynamic_cast<const CGTownInstance *>(dtObj);
  434. if(townObj->armedGarrison())
  435. action = CGPathNode::BATTLE;
  436. }
  437. else if(dtObj->ID == Obj::GARRISON || dtObj->ID == Obj::GARRISON2)
  438. {
  439. const CGGarrison * garrisonObj = dynamic_cast<const CGGarrison *>(dtObj);
  440. if((garrisonObj->stacksCount() && objRel == PlayerRelations::ENEMIES) || isDestinationGuarded(true))
  441. action = CGPathNode::BATTLE;
  442. }
  443. else if(isDestinationGuardian())
  444. action = CGPathNode::BATTLE;
  445. else if(dtObj->blockVisit && !(options.useCastleGate && dtObj->ID == Obj::TOWN))
  446. action = CGPathNode::BLOCKING_VISIT;
  447. if(action == CGPathNode::NORMAL)
  448. {
  449. if(options.originalMovementRules && isDestinationGuarded())
  450. action = CGPathNode::BATTLE;
  451. else
  452. action = CGPathNode::VISIT;
  453. }
  454. }
  455. else if(isDestinationGuarded())
  456. action = CGPathNode::BATTLE;
  457. break;
  458. }
  459. return action;
  460. }
  461. bool CPathfinder::isSourceInitialPosition() const
  462. {
  463. return cp->coord == out.hpos;
  464. }
  465. bool CPathfinder::isSourceVisitableObj() const
  466. {
  467. return isVisitableObj(ctObj, cp->layer);
  468. }
  469. bool CPathfinder::isSourceGuarded() const
  470. {
  471. /// Hero can move from guarded tile if movement started on that tile
  472. /// It's possible at least in these cases:
  473. /// - Map start with hero on guarded tile
  474. /// - Dimention door used
  475. /// TODO: check what happen when there is several guards
  476. if(gs->guardingCreaturePosition(cp->coord).valid() && !isSourceInitialPosition())
  477. {
  478. return true;
  479. }
  480. return false;
  481. }
  482. bool CPathfinder::isDestVisitableObj() const
  483. {
  484. return isVisitableObj(dtObj, dp->layer);
  485. }
  486. bool CPathfinder::isDestinationGuarded(const bool ignoreAccessibility) const
  487. {
  488. /// isDestinationGuarded is exception needed for garrisons.
  489. /// When monster standing behind garrison it's visitable and guarded at the same time.
  490. if(gs->guardingCreaturePosition(dp->coord).valid()
  491. && (ignoreAccessibility || dp->accessible == CGPathNode::BLOCKVIS))
  492. {
  493. return true;
  494. }
  495. return false;
  496. }
  497. bool CPathfinder::isDestinationGuardian() const
  498. {
  499. return gs->guardingCreaturePosition(cp->coord) == dp->coord;
  500. }
  501. void CPathfinder::initializePatrol()
  502. {
  503. auto state = PATROL_NONE;
  504. if(hero->patrol.patrolling && !getPlayer(hero->tempOwner)->human)
  505. {
  506. if(hero->patrol.patrolRadious)
  507. {
  508. state = PATROL_RADIUS;
  509. gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadious, boost::optional<PlayerColor>(), 0, true);
  510. }
  511. else
  512. state = PATROL_LOCKED;
  513. }
  514. patrolState = state;
  515. }
  516. void CPathfinder::initializeGraph()
  517. {
  518. auto updateNode = [&](int3 pos, ELayer layer, const TerrainTile * tinfo)
  519. {
  520. auto node = out.getNode(pos, layer);
  521. auto accessibility = evaluateAccessibility(pos, tinfo, layer);
  522. node->update(pos, layer, accessibility);
  523. };
  524. int3 pos;
  525. for(pos.x=0; pos.x < out.sizes.x; ++pos.x)
  526. {
  527. for(pos.y=0; pos.y < out.sizes.y; ++pos.y)
  528. {
  529. for(pos.z=0; pos.z < out.sizes.z; ++pos.z)
  530. {
  531. const TerrainTile * tinfo = &gs->map->getTile(pos);
  532. switch(tinfo->terType)
  533. {
  534. case ETerrainType::ROCK:
  535. break;
  536. case ETerrainType::WATER:
  537. updateNode(pos, ELayer::SAIL, tinfo);
  538. if(options.useFlying)
  539. updateNode(pos, ELayer::AIR, tinfo);
  540. if(options.useWaterWalking)
  541. updateNode(pos, ELayer::WATER, tinfo);
  542. break;
  543. default:
  544. updateNode(pos, ELayer::LAND, tinfo);
  545. if(options.useFlying)
  546. updateNode(pos, ELayer::AIR, tinfo);
  547. break;
  548. }
  549. }
  550. }
  551. }
  552. }
  553. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const int3 & pos, const TerrainTile * tinfo, const ELayer layer) const
  554. {
  555. if(tinfo->terType == ETerrainType::ROCK || !FoW[pos.x][pos.y][pos.z])
  556. return CGPathNode::BLOCKED;
  557. switch(layer)
  558. {
  559. case ELayer::LAND:
  560. case ELayer::SAIL:
  561. if(tinfo->visitable)
  562. {
  563. 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
  564. {
  565. return CGPathNode::BLOCKED;
  566. }
  567. else
  568. {
  569. for(const CGObjectInstance * obj : tinfo->visitableObjects)
  570. {
  571. if(obj->blockVisit)
  572. {
  573. return CGPathNode::BLOCKVIS;
  574. }
  575. else if(obj->passableFor(hero->tempOwner))
  576. {
  577. return CGPathNode::ACCESSIBLE;
  578. }
  579. else if(canSeeObj(obj))
  580. {
  581. return CGPathNode::VISITABLE;
  582. }
  583. }
  584. }
  585. }
  586. else if(tinfo->blocked)
  587. {
  588. return CGPathNode::BLOCKED;
  589. }
  590. else if(gs->guardingCreaturePosition(pos).valid())
  591. {
  592. // Monster close by; blocked visit for battle
  593. return CGPathNode::BLOCKVIS;
  594. }
  595. break;
  596. case ELayer::WATER:
  597. if(tinfo->blocked || tinfo->terType != ETerrainType::WATER)
  598. return CGPathNode::BLOCKED;
  599. break;
  600. case ELayer::AIR:
  601. if(tinfo->blocked || tinfo->terType == ETerrainType::WATER)
  602. return CGPathNode::FLYABLE;
  603. break;
  604. }
  605. return CGPathNode::ACCESSIBLE;
  606. }
  607. bool CPathfinder::isVisitableObj(const CGObjectInstance * obj, const ELayer layer) const
  608. {
  609. /// Hero can't visit objects while walking on water or flying
  610. return canSeeObj(obj) && (layer == ELayer::LAND || layer == ELayer::SAIL);
  611. }
  612. bool CPathfinder::canSeeObj(const CGObjectInstance * obj) const
  613. {
  614. /// Pathfinder should ignore placed events
  615. return obj != nullptr && obj->ID != Obj::EVENT;
  616. }
  617. bool CPathfinder::canMoveBetween(const int3 & a, const int3 & b) const
  618. {
  619. return gs->checkForVisitableDir(a, b);
  620. }
  621. bool CPathfinder::isAllowedTeleportEntrance(const CGTeleport * obj) const
  622. {
  623. if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
  624. return false;
  625. auto whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
  626. if(whirlpool)
  627. {
  628. if(addTeleportWhirlpool(whirlpool))
  629. return true;
  630. }
  631. else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
  632. return true;
  633. return false;
  634. }
  635. bool CPathfinder::addTeleportTwoWay(const CGTeleport * obj) const
  636. {
  637. return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
  638. }
  639. bool CPathfinder::addTeleportOneWay(const CGTeleport * obj) const
  640. {
  641. if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  642. {
  643. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  644. if(passableExits.size() == 1)
  645. return true;
  646. }
  647. return false;
  648. }
  649. bool CPathfinder::addTeleportOneWayRandom(const CGTeleport * obj) const
  650. {
  651. if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
  652. {
  653. auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
  654. if(passableExits.size() > 1)
  655. return true;
  656. }
  657. return false;
  658. }
  659. bool CPathfinder::addTeleportWhirlpool(const CGWhirlpool * obj) const
  660. {
  661. return options.useTeleportWhirlpool && hlp->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) && obj;
  662. }
  663. TurnInfo::BonusCache::BonusCache(TBonusListPtr bl)
  664. {
  665. noTerrainPenalty.reserve(ETerrainType::ROCK);
  666. for(int i = 0; i < ETerrainType::ROCK; i++)
  667. {
  668. noTerrainPenalty.push_back(bl->getFirst(Selector::type(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype(i))));
  669. }
  670. freeShipBoarding = bl->getFirst(Selector::type(Bonus::FREE_SHIP_BOARDING));
  671. flyingMovement = bl->getFirst(Selector::type(Bonus::FLYING_MOVEMENT));
  672. flyingMovementVal = bl->valOfBonuses(Selector::type(Bonus::FLYING_MOVEMENT));
  673. waterWalking = bl->getFirst(Selector::type(Bonus::WATER_WALKING));
  674. waterWalkingVal = bl->valOfBonuses(Selector::type(Bonus::WATER_WALKING));
  675. }
  676. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  677. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  678. {
  679. std::stringstream cachingStr;
  680. cachingStr << "days_" << turn;
  681. bonuses = hero->getAllBonuses(Selector::days(turn), nullptr, nullptr, cachingStr.str());
  682. bonusCache = make_unique<BonusCache>(bonuses);
  683. nativeTerrain = hero->getNativeTerrain();
  684. }
  685. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  686. {
  687. switch(layer)
  688. {
  689. case EPathfindingLayer::AIR:
  690. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  691. return false;
  692. break;
  693. case EPathfindingLayer::WATER:
  694. if(!hasBonusOfType(Bonus::WATER_WALKING))
  695. return false;
  696. break;
  697. }
  698. return true;
  699. }
  700. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  701. {
  702. switch(type)
  703. {
  704. case Bonus::FREE_SHIP_BOARDING:
  705. return bonusCache->freeShipBoarding;
  706. case Bonus::FLYING_MOVEMENT:
  707. return bonusCache->flyingMovement;
  708. case Bonus::WATER_WALKING:
  709. return bonusCache->waterWalking;
  710. case Bonus::NO_TERRAIN_PENALTY:
  711. return bonusCache->noTerrainPenalty[subtype];
  712. }
  713. return bonuses->getFirst(Selector::type(type).And(Selector::subtype(subtype)));
  714. }
  715. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  716. {
  717. switch(type)
  718. {
  719. case Bonus::FLYING_MOVEMENT:
  720. return bonusCache->flyingMovementVal;
  721. case Bonus::WATER_WALKING:
  722. return bonusCache->waterWalkingVal;
  723. }
  724. return bonuses->valOfBonuses(Selector::type(type).And(Selector::subtype(subtype)));
  725. }
  726. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  727. {
  728. if(maxMovePointsLand == -1)
  729. maxMovePointsLand = hero->maxMovePoints(true, this);
  730. if(maxMovePointsWater == -1)
  731. maxMovePointsWater = hero->maxMovePoints(false, this);
  732. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  733. }
  734. CPathfinderHelper::CPathfinderHelper(const CGHeroInstance * Hero, const CPathfinder::PathfinderOptions & Options)
  735. : turn(-1), hero(Hero), options(Options)
  736. {
  737. turnsInfo.reserve(16);
  738. updateTurnInfo();
  739. }
  740. void CPathfinderHelper::updateTurnInfo(const int Turn)
  741. {
  742. if(turn != Turn)
  743. {
  744. turn = Turn;
  745. if(turn >= turnsInfo.size())
  746. {
  747. auto ti = new TurnInfo(hero, turn);
  748. turnsInfo.push_back(ti);
  749. }
  750. }
  751. }
  752. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  753. {
  754. switch(layer)
  755. {
  756. case EPathfindingLayer::AIR:
  757. if(!options.useFlying)
  758. return false;
  759. break;
  760. case EPathfindingLayer::WATER:
  761. if(!options.useWaterWalking)
  762. return false;
  763. break;
  764. }
  765. return turnsInfo[turn]->isLayerAvailable(layer);
  766. }
  767. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  768. {
  769. return turnsInfo[turn];
  770. }
  771. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  772. {
  773. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  774. }
  775. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  776. {
  777. return turnsInfo[turn]->getMaxMovePoints(layer);
  778. }
  779. void CPathfinderHelper::getNeighbours(const CMap * map, const TerrainTile & srct, const int3 & tile, std::vector<int3> & vec, const boost::logic::tribool & onLand, const bool limitCoastSailing)
  780. {
  781. static const int3 dirs[] = {
  782. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  783. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  784. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  785. };
  786. for(auto & dir : dirs)
  787. {
  788. const int3 hlp = tile + dir;
  789. if(!map->isInTheMap(hlp))
  790. continue;
  791. const TerrainTile & hlpt = map->getTile(hlp);
  792. if(hlpt.terType == ETerrainType::ROCK)
  793. continue;
  794. // //we cannot visit things from blocked tiles
  795. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  796. // {
  797. // continue;
  798. // }
  799. /// Following condition let us avoid diagonal movement over coast when sailing
  800. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  801. {
  802. int3 hlp1 = tile,
  803. hlp2 = tile;
  804. hlp1.x += dir.x;
  805. hlp2.y += dir.y;
  806. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  807. continue;
  808. }
  809. if(indeterminate(onLand) || onLand == (hlpt.terType != ETerrainType::WATER))
  810. {
  811. vec.push_back(hlp);
  812. }
  813. }
  814. }
  815. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & src, const int3 & dst, const TerrainTile * ct, const TerrainTile * dt, const int remainingMovePoints, const TurnInfo * ti, const bool checkLast)
  816. {
  817. if(src == dst) //same tile
  818. return 0;
  819. if(!ti)
  820. ti = new TurnInfo(h);
  821. if(ct == nullptr || dt == nullptr)
  822. {
  823. ct = h->cb->getTile(src);
  824. dt = h->cb->getTile(dst);
  825. }
  826. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  827. /// Also flying movement only has penalty when player moving over blocked tiles.
  828. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  829. int ret = h->getTileCost(*dt, *ct, ti);
  830. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  831. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  832. /// So this one is waiting till server going to use pathfinder rules for path validation.
  833. if(dt->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  834. {
  835. ret *= (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0;
  836. }
  837. else if(dt->terType == ETerrainType::WATER)
  838. {
  839. if(h->boat && ct->hasFavourableWinds() && dt->hasFavourableWinds()) //Favourable Winds
  840. ret *= 0.666;
  841. else if(!h->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  842. {
  843. ret *= (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0;
  844. }
  845. }
  846. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  847. {
  848. int old = ret;
  849. ret *= 1.414213;
  850. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  851. if(ret > remainingMovePoints && remainingMovePoints >= old)
  852. return remainingMovePoints;
  853. }
  854. /// TODO: This part need rework in order to work properly with flying and water walking
  855. /// Currently it's only work properly for normal movement or sailing
  856. int left = remainingMovePoints-ret;
  857. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  858. {
  859. std::vector<int3> vec;
  860. vec.reserve(8); //optimization
  861. getNeighbours(h->cb->gameState()->map, *dt, dst, vec, ct->terType != ETerrainType::WATER, true);
  862. for(auto & elem : vec)
  863. {
  864. int fcost = getMovementCost(h, dst, elem, nullptr, nullptr, left, ti, false);
  865. if(fcost <= left)
  866. return ret;
  867. }
  868. ret = remainingMovePoints;
  869. }
  870. return ret;
  871. }
  872. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & dst)
  873. {
  874. return getMovementCost(h, h->visitablePos(), dst, nullptr, nullptr, h->movement);
  875. }
  876. CGPathNode::CGPathNode()
  877. : coord(int3(-1, -1, -1)), layer(ELayer::WRONG)
  878. {
  879. reset();
  880. }
  881. void CGPathNode::reset()
  882. {
  883. locked = false;
  884. accessible = NOT_SET;
  885. moveRemains = 0;
  886. turns = 255;
  887. theNodeBefore = nullptr;
  888. action = UNKNOWN;
  889. }
  890. void CGPathNode::update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible)
  891. {
  892. if(layer == ELayer::WRONG)
  893. {
  894. coord = Coord;
  895. layer = Layer;
  896. }
  897. else
  898. reset();
  899. accessible = Accessible;
  900. }
  901. bool CGPathNode::reachable() const
  902. {
  903. return turns < 255;
  904. }
  905. int3 CGPath::startPos() const
  906. {
  907. return nodes[nodes.size()-1].coord;
  908. }
  909. int3 CGPath::endPos() const
  910. {
  911. return nodes[0].coord;
  912. }
  913. void CGPath::convert(ui8 mode)
  914. {
  915. if(mode==0)
  916. {
  917. for(auto & elem : nodes)
  918. {
  919. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  920. }
  921. }
  922. }
  923. CPathsInfo::CPathsInfo(const int3 & Sizes)
  924. : sizes(Sizes)
  925. {
  926. hero = nullptr;
  927. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  928. }
  929. CPathsInfo::~CPathsInfo()
  930. {
  931. }
  932. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  933. {
  934. assert(vstd::iswithin(tile.x, 0, sizes.x));
  935. assert(vstd::iswithin(tile.y, 0, sizes.y));
  936. assert(vstd::iswithin(tile.z, 0, sizes.z));
  937. boost::unique_lock<boost::mutex> pathLock(pathMx);
  938. return getNode(tile);
  939. }
  940. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  941. {
  942. boost::unique_lock<boost::mutex> pathLock(pathMx);
  943. out.nodes.clear();
  944. const CGPathNode * curnode = getNode(dst);
  945. if(!curnode->theNodeBefore)
  946. return false;
  947. while(curnode)
  948. {
  949. const CGPathNode cpn = * curnode;
  950. curnode = curnode->theNodeBefore;
  951. out.nodes.push_back(cpn);
  952. }
  953. return true;
  954. }
  955. int CPathsInfo::getDistance(const int3 & tile) const
  956. {
  957. boost::unique_lock<boost::mutex> pathLock(pathMx);
  958. CGPath ret;
  959. if(getPath(ret, tile))
  960. return ret.nodes.size();
  961. else
  962. return 255;
  963. }
  964. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  965. {
  966. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  967. if(landNode->reachable())
  968. return landNode;
  969. else
  970. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  971. }
  972. CGPathNode * CPathsInfo::getNode(const int3 & coord, const ELayer layer)
  973. {
  974. return &nodes[coord.x][coord.y][coord.z][layer];
  975. }