distance_map.hpp
Go to the documentation of this file.
1 // Copyright 2022-2023 Ekumen, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef BELUGA_ALGORITHM_DISTANCE_MAP_HPP
16 #define BELUGA_ALGORITHM_DISTANCE_MAP_HPP
17 
18 #include <queue>
19 #include <vector>
20 
21 #include <range/v3/range/access.hpp>
22 #include <range/v3/range/primitives.hpp>
23 #include <range/v3/view/enumerate.hpp>
24 
30 namespace beluga {
31 
33 
53 template <class Range, class DistanceFunction, class NeighborsFunction>
55  Range&& obstacle_map,
56  DistanceFunction&& distance_function,
57  NeighborsFunction&& neighbors_function) {
58  struct IndexPair {
59  std::size_t nearest_obstacle_index;
60  std::size_t index;
61  };
62 
63  using DistanceType = std::invoke_result_t<DistanceFunction, std::size_t, std::size_t>;
64  auto distance_map = std::vector<DistanceType>(ranges::size(obstacle_map));
65  auto visited = std::vector<bool>(ranges::size(obstacle_map), false);
66 
67  auto compare = [&distance_map](const IndexPair& first, const IndexPair& second) {
68  return distance_map[first.index] > distance_map[second.index];
69  };
70  auto queue = std::priority_queue<IndexPair, std::vector<IndexPair>, decltype(compare)>{compare};
71 
72  for (auto [index, is_obstacle] : ranges::views::enumerate(obstacle_map)) {
73  if (is_obstacle) {
74  visited[index] = true;
75  distance_map[index] = 0;
76  queue.push(IndexPair{index, index}); // The nearest obstacle is itself
77  }
78  }
79 
80  while (!queue.empty()) {
81  auto parent = queue.top();
82  queue.pop();
83  for (const std::size_t index : neighbors_function(parent.index)) {
84  if (!visited[index]) {
85  visited[index] = true;
86  distance_map[index] = distance_function(parent.nearest_obstacle_index, index);
87  queue.push(IndexPair{parent.nearest_obstacle_index, index});
88  }
89  }
90  }
91 
92  return distance_map;
93 }
94 
95 } // namespace beluga
96 
97 #endif
beluga::nearest_obstacle_distance_map
auto nearest_obstacle_distance_map(Range &&obstacle_map, DistanceFunction &&distance_function, NeighborsFunction &&neighbors_function)
Returns a map where the value of each cell is the distance to the nearest obstacle.
Definition: distance_map.hpp:54
beluga
The main Beluga namespace.
Definition: 3d_embedding.hpp:21


beluga
Author(s):
autogenerated on Tue Jul 16 2024 02:59:53