Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
node_spatial_tree.hpp
1 // Copyright (c) 2025 Open Navigation LLC
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 NAV2_ROUTE__NODE_SPATIAL_TREE_HPP_
16 #define NAV2_ROUTE__NODE_SPATIAL_TREE_HPP_
17 
18 #include <string>
19 #include <memory>
20 #include <vector>
21 #include <nanoflann.hpp>
22 
23 #include "nav2_ros_common/lifecycle_node.hpp"
24 #include "nav2_route/types.hpp"
25 #include "nav2_route/utils.hpp"
26 
27 namespace nav2_route
28 {
29 
30 // Search in XY dimension for nearest neighbors
31 const size_t DIMENSION = 2;
32 
38 {
39  explicit GraphAdaptor(const Graph & obj_)
40  : obj(obj_) {}
41 
42  inline size_t kdtree_get_point_count() const {return obj.size();}
43 
44  inline double kdtree_get_pt(const size_t idx, const size_t dim) const
45  {
46  if (dim == 0) {
47  return obj[idx].coords.x;
48  }
49  return obj[idx].coords.y;
50  }
51 
52  template<class BBOX> bool kdtree_get_bbox(BBOX & /*bb*/) const {return false;}
53 
54  const Graph & obj;
55 };
56 
57 typedef nanoflann::KDTreeSingleIndexAdaptor<
58  nanoflann::L2_Simple_Adaptor<double, GraphAdaptor>, GraphAdaptor, DIMENSION,
59  unsigned int>
60  kd_tree_t;
61 
70 {
71 public:
75  NodeSpatialTree() = default;
76 
81 
86  void computeTree(Graph & graph);
87 
95  const geometry_msgs::msg::PoseStamped & pose_in,
96  std::vector<unsigned int> & node_ids);
97 
102  void setNumOfNearestNodes(int num_of_nearest_nodes);
103 
104 protected:
105  kd_tree_t * kdtree_;
106  GraphAdaptor * adaptor_;
107  Graph * graph_;
108  int num_of_nearest_nodes_{3};
109 };
110 
111 } // namespace nav2_route
112 
113 #endif // NAV2_ROUTE__NODE_SPATIAL_TREE_HPP_
An object to find kNNs of the graph to determining the start and end nodes to utilize for planning in...
bool findNearestGraphNodesToPose(const geometry_msgs::msg::PoseStamped &pose_in, std::vector< unsigned int > &node_ids)
Find the closest node to a given pose.
NodeSpatialTree()=default
Constructor.
void setNumOfNearestNodes(int num_of_nearest_nodes)
Set the number of nodes to search in local area for.
void computeTree(Graph &graph)
Compute the kd-tree based on the graph node information.
An adaptor for Nanoflann to operate on our graph object without copying.