CPathfinder.cpp 31 KB

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