2
0

CPathfinder.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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(static_cast<bool>(
  726. bl->getFirst(Selector::type(Bonus::NO_TERRAIN_PENALTY).And(Selector::subtype(i)))));
  727. }
  728. freeShipBoarding = static_cast<bool>(bl->getFirst(Selector::type(Bonus::FREE_SHIP_BOARDING)));
  729. flyingMovement = static_cast<bool>(bl->getFirst(Selector::type(Bonus::FLYING_MOVEMENT)));
  730. flyingMovementVal = bl->valOfBonuses(Selector::type(Bonus::FLYING_MOVEMENT));
  731. waterWalking = static_cast<bool>(bl->getFirst(Selector::type(Bonus::WATER_WALKING)));
  732. waterWalkingVal = bl->valOfBonuses(Selector::type(Bonus::WATER_WALKING));
  733. }
  734. TurnInfo::TurnInfo(const CGHeroInstance * Hero, const int turn)
  735. : hero(Hero), maxMovePointsLand(-1), maxMovePointsWater(-1)
  736. {
  737. std::stringstream cachingStr;
  738. cachingStr << "days_" << turn;
  739. bonuses = hero->getAllBonuses(Selector::days(turn), nullptr, nullptr, cachingStr.str());
  740. bonusCache = make_unique<BonusCache>(bonuses);
  741. nativeTerrain = hero->getNativeTerrain();
  742. }
  743. bool TurnInfo::isLayerAvailable(const EPathfindingLayer layer) const
  744. {
  745. switch(layer)
  746. {
  747. case EPathfindingLayer::AIR:
  748. if(!hasBonusOfType(Bonus::FLYING_MOVEMENT))
  749. return false;
  750. break;
  751. case EPathfindingLayer::WATER:
  752. if(!hasBonusOfType(Bonus::WATER_WALKING))
  753. return false;
  754. break;
  755. }
  756. return true;
  757. }
  758. bool TurnInfo::hasBonusOfType(Bonus::BonusType type, int subtype) const
  759. {
  760. switch(type)
  761. {
  762. case Bonus::FREE_SHIP_BOARDING:
  763. return bonusCache->freeShipBoarding;
  764. case Bonus::FLYING_MOVEMENT:
  765. return bonusCache->flyingMovement;
  766. case Bonus::WATER_WALKING:
  767. return bonusCache->waterWalking;
  768. case Bonus::NO_TERRAIN_PENALTY:
  769. return bonusCache->noTerrainPenalty[subtype];
  770. }
  771. return static_cast<bool>(
  772. bonuses->getFirst(Selector::type(type).And(Selector::subtype(subtype))));
  773. }
  774. int TurnInfo::valOfBonuses(Bonus::BonusType type, int subtype) const
  775. {
  776. switch(type)
  777. {
  778. case Bonus::FLYING_MOVEMENT:
  779. return bonusCache->flyingMovementVal;
  780. case Bonus::WATER_WALKING:
  781. return bonusCache->waterWalkingVal;
  782. }
  783. return bonuses->valOfBonuses(Selector::type(type).And(Selector::subtype(subtype)));
  784. }
  785. int TurnInfo::getMaxMovePoints(const EPathfindingLayer layer) const
  786. {
  787. if(maxMovePointsLand == -1)
  788. maxMovePointsLand = hero->maxMovePoints(true, this);
  789. if(maxMovePointsWater == -1)
  790. maxMovePointsWater = hero->maxMovePoints(false, this);
  791. return layer == EPathfindingLayer::SAIL ? maxMovePointsWater : maxMovePointsLand;
  792. }
  793. CPathfinderHelper::CPathfinderHelper(const CGHeroInstance * Hero, const CPathfinder::PathfinderOptions & Options)
  794. : turn(-1), hero(Hero), options(Options)
  795. {
  796. turnsInfo.reserve(16);
  797. updateTurnInfo();
  798. }
  799. CPathfinderHelper::~CPathfinderHelper()
  800. {
  801. for(auto ti : turnsInfo)
  802. delete ti;
  803. }
  804. void CPathfinderHelper::updateTurnInfo(const int Turn)
  805. {
  806. if(turn != Turn)
  807. {
  808. turn = Turn;
  809. if(turn >= turnsInfo.size())
  810. {
  811. auto ti = new TurnInfo(hero, turn);
  812. turnsInfo.push_back(ti);
  813. }
  814. }
  815. }
  816. bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer layer) const
  817. {
  818. switch(layer)
  819. {
  820. case EPathfindingLayer::AIR:
  821. if(!options.useFlying)
  822. return false;
  823. break;
  824. case EPathfindingLayer::WATER:
  825. if(!options.useWaterWalking)
  826. return false;
  827. break;
  828. }
  829. return turnsInfo[turn]->isLayerAvailable(layer);
  830. }
  831. const TurnInfo * CPathfinderHelper::getTurnInfo() const
  832. {
  833. return turnsInfo[turn];
  834. }
  835. bool CPathfinderHelper::hasBonusOfType(const Bonus::BonusType type, const int subtype) const
  836. {
  837. return turnsInfo[turn]->hasBonusOfType(type, subtype);
  838. }
  839. int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer layer) const
  840. {
  841. return turnsInfo[turn]->getMaxMovePoints(layer);
  842. }
  843. void CPathfinderHelper::getNeighbours(const CMap * map, const TerrainTile & srct, const int3 & tile, std::vector<int3> & vec, const boost::logic::tribool & onLand, const bool limitCoastSailing)
  844. {
  845. static const int3 dirs[] = {
  846. int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
  847. int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
  848. int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
  849. };
  850. for(auto & dir : dirs)
  851. {
  852. const int3 hlp = tile + dir;
  853. if(!map->isInTheMap(hlp))
  854. continue;
  855. const TerrainTile & hlpt = map->getTile(hlp);
  856. if(hlpt.terType == ETerrainType::ROCK)
  857. continue;
  858. // //we cannot visit things from blocked tiles
  859. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  860. // {
  861. // continue;
  862. // }
  863. /// Following condition let us avoid diagonal movement over coast when sailing
  864. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  865. {
  866. int3 hlp1 = tile,
  867. hlp2 = tile;
  868. hlp1.x += dir.x;
  869. hlp2.y += dir.y;
  870. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  871. continue;
  872. }
  873. if(indeterminate(onLand) || onLand == (hlpt.terType != ETerrainType::WATER))
  874. {
  875. vec.push_back(hlp);
  876. }
  877. }
  878. }
  879. 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)
  880. {
  881. if(src == dst) //same tile
  882. return 0;
  883. bool localTi = false;
  884. if(!ti)
  885. {
  886. localTi = true;
  887. ti = new TurnInfo(h);
  888. }
  889. if(ct == nullptr || dt == nullptr)
  890. {
  891. ct = h->cb->getTile(src);
  892. dt = h->cb->getTile(dst);
  893. }
  894. /// TODO: by the original game rules hero shouldn't be affected by terrain penalty while flying.
  895. /// Also flying movement only has penalty when player moving over blocked tiles.
  896. /// So if you only have base flying with 40% penalty you can still ignore terrain penalty while having zero flying penalty.
  897. int ret = h->getTileCost(*dt, *ct, ti);
  898. /// Unfortunately this can't be implemented yet as server don't know when player flying and when he's not.
  899. /// Difference in cost calculation on client and server is much worse than incorrect cost.
  900. /// So this one is waiting till server going to use pathfinder rules for path validation.
  901. if(dt->blocked && ti->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  902. {
  903. ret *= (100.0 + ti->valOfBonuses(Bonus::FLYING_MOVEMENT)) / 100.0;
  904. }
  905. else if(dt->terType == ETerrainType::WATER)
  906. {
  907. if(h->boat && ct->hasFavorableWinds() && dt->hasFavorableWinds())
  908. ret *= 0.666;
  909. else if(!h->boat && ti->hasBonusOfType(Bonus::WATER_WALKING))
  910. {
  911. ret *= (100.0 + ti->valOfBonuses(Bonus::WATER_WALKING)) / 100.0;
  912. }
  913. }
  914. if(src.x != dst.x && src.y != dst.y) //it's diagonal move
  915. {
  916. int old = ret;
  917. ret *= 1.414213;
  918. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  919. if(ret > remainingMovePoints && remainingMovePoints >= old)
  920. {
  921. if(localTi)
  922. delete ti;
  923. return remainingMovePoints;
  924. }
  925. }
  926. /// TODO: This part need rework in order to work properly with flying and water walking
  927. /// Currently it's only work properly for normal movement or sailing
  928. int left = remainingMovePoints-ret;
  929. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  930. {
  931. std::vector<int3> vec;
  932. vec.reserve(8); //optimization
  933. getNeighbours(h->cb->gameState()->map, *dt, dst, vec, ct->terType != ETerrainType::WATER, true);
  934. for(auto & elem : vec)
  935. {
  936. int fcost = getMovementCost(h, dst, elem, nullptr, nullptr, left, ti, false);
  937. if(fcost <= left)
  938. {
  939. if(localTi)
  940. delete ti;
  941. return ret;
  942. }
  943. }
  944. ret = remainingMovePoints;
  945. }
  946. if(localTi)
  947. delete ti;
  948. return ret;
  949. }
  950. int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & dst)
  951. {
  952. return getMovementCost(h, h->visitablePos(), dst, nullptr, nullptr, h->movement);
  953. }
  954. CGPathNode::CGPathNode()
  955. : coord(int3(-1, -1, -1)), layer(ELayer::WRONG)
  956. {
  957. reset();
  958. }
  959. void CGPathNode::reset()
  960. {
  961. locked = false;
  962. accessible = NOT_SET;
  963. moveRemains = 0;
  964. turns = 255;
  965. theNodeBefore = nullptr;
  966. action = UNKNOWN;
  967. }
  968. void CGPathNode::update(const int3 & Coord, const ELayer Layer, const EAccessibility Accessible)
  969. {
  970. if(layer == ELayer::WRONG)
  971. {
  972. coord = Coord;
  973. layer = Layer;
  974. }
  975. else
  976. reset();
  977. accessible = Accessible;
  978. }
  979. bool CGPathNode::reachable() const
  980. {
  981. return turns < 255;
  982. }
  983. int3 CGPath::startPos() const
  984. {
  985. return nodes[nodes.size()-1].coord;
  986. }
  987. int3 CGPath::endPos() const
  988. {
  989. return nodes[0].coord;
  990. }
  991. void CGPath::convert(ui8 mode)
  992. {
  993. if(mode==0)
  994. {
  995. for(auto & elem : nodes)
  996. {
  997. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  998. }
  999. }
  1000. }
  1001. CPathsInfo::CPathsInfo(const int3 & Sizes)
  1002. : sizes(Sizes)
  1003. {
  1004. hero = nullptr;
  1005. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][ELayer::NUM_LAYERS]);
  1006. }
  1007. CPathsInfo::~CPathsInfo()
  1008. {
  1009. }
  1010. const CGPathNode * CPathsInfo::getPathInfo(const int3 & tile) const
  1011. {
  1012. assert(vstd::iswithin(tile.x, 0, sizes.x));
  1013. assert(vstd::iswithin(tile.y, 0, sizes.y));
  1014. assert(vstd::iswithin(tile.z, 0, sizes.z));
  1015. boost::unique_lock<boost::mutex> pathLock(pathMx);
  1016. return getNode(tile);
  1017. }
  1018. bool CPathsInfo::getPath(CGPath & out, const int3 & dst) const
  1019. {
  1020. boost::unique_lock<boost::mutex> pathLock(pathMx);
  1021. out.nodes.clear();
  1022. const CGPathNode * curnode = getNode(dst);
  1023. if(!curnode->theNodeBefore)
  1024. return false;
  1025. while(curnode)
  1026. {
  1027. const CGPathNode cpn = * curnode;
  1028. curnode = curnode->theNodeBefore;
  1029. out.nodes.push_back(cpn);
  1030. }
  1031. return true;
  1032. }
  1033. int CPathsInfo::getDistance(const int3 & tile) const
  1034. {
  1035. boost::unique_lock<boost::mutex> pathLock(pathMx);
  1036. CGPath ret;
  1037. if(getPath(ret, tile))
  1038. return ret.nodes.size();
  1039. else
  1040. return 255;
  1041. }
  1042. const CGPathNode * CPathsInfo::getNode(const int3 & coord) const
  1043. {
  1044. auto landNode = &nodes[coord.x][coord.y][coord.z][ELayer::LAND];
  1045. if(landNode->reachable())
  1046. return landNode;
  1047. else
  1048. return &nodes[coord.x][coord.y][coord.z][ELayer::SAIL];
  1049. }
  1050. CGPathNode * CPathsInfo::getNode(const int3 & coord, const ELayer layer)
  1051. {
  1052. return &nodes[coord.x][coord.y][coord.z][layer];
  1053. }