ReachabilityInfo.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * ReachabilityInfo.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "ReachabilityInfo.h"
  12. #include "Unit.h"
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. ReachabilityInfo::Parameters::Parameters(const battle::Unit * Stack, const BattleHex & StartPosition):
  15. perspective(static_cast<BattleSide>(Stack->unitSide())),
  16. startPosition(StartPosition),
  17. doubleWide(Stack->doubleWide()),
  18. side(Stack->unitSide()),
  19. flying(Stack->hasBonusOfType(BonusType::FLYING))
  20. {
  21. knownAccessible = & battle::Unit::getHexes(startPosition, doubleWide, side);
  22. destructibleEnemyTurns.fill(-1);
  23. }
  24. ReachabilityInfo::ReachabilityInfo()
  25. {
  26. distances.fill(INFINITE_DIST);
  27. predecessors.fill(BattleHex::INVALID);
  28. }
  29. bool ReachabilityInfo::isReachable(const BattleHex & hex) const
  30. {
  31. return distances[hex.toInt()] < INFINITE_DIST;
  32. }
  33. uint32_t ReachabilityInfo::distToNearestNeighbour(
  34. const BattleHexArray & targetHexes,
  35. BattleHex * chosenHex) const
  36. {
  37. uint32_t ret = 1000000;
  38. for(const auto & targetHex : targetHexes)
  39. {
  40. for(auto & n : targetHex.getNeighbouringTiles())
  41. {
  42. if(distances[n.toInt()] < ret)
  43. {
  44. ret = distances[n.toInt()];
  45. if(chosenHex)
  46. *chosenHex = n;
  47. }
  48. }
  49. }
  50. return ret;
  51. }
  52. uint32_t ReachabilityInfo::distToNearestNeighbour(
  53. const battle::Unit * attacker,
  54. const battle::Unit * defender,
  55. BattleHex * chosenHex) const
  56. {
  57. auto attackableHexes = defender->getHexes();
  58. if(attacker->doubleWide())
  59. {
  60. if(defender->doubleWide())
  61. {
  62. // It can be back to back attack o==o or head to head =oo=.
  63. // In case of back-to-back the distance between heads (unit positions) may be up to 3 tiles
  64. attackableHexes.insert(battle::Unit::getHexes(defender->occupiedHex(), true, defender->unitSide()));
  65. }
  66. else
  67. {
  68. attackableHexes.insert(battle::Unit::getHexes(defender->getPosition(), true, defender->unitSide()));
  69. }
  70. }
  71. attackableHexes.eraseIf([defender](const BattleHex & h) -> bool
  72. {
  73. return h.getY() != defender->getPosition().getY() || !h.isAvailable();
  74. });
  75. return distToNearestNeighbour(attackableHexes, chosenHex);
  76. }
  77. VCMI_LIB_NAMESPACE_END