CPathfinder.cpp 32 KB

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