Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
costmap_scorer.cpp
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 #include <memory>
16 #include <mutex>
17 #include <string>
18 
19 #include "nav2_route/plugins/edge_cost_functions/costmap_scorer.hpp"
20 #include "nav2_ros_common/tf2_factories.hpp"
21 
22 namespace nav2_route
23 {
24 
26  const nav2::LifecycleNode::SharedPtr node,
27  const nav2::TransformBuffer::SharedPtr/* tf_buffer */,
28  std::shared_ptr<nav2_costmap_2d::CostmapSubscriber> costmap_subscriber,
29  const std::string & name)
30 {
31  RCLCPP_INFO(node->get_logger(), "Configuring costmap scorer.");
32  name_ = name;
33  logger_ = node->get_logger();
34  clock_ = node->get_clock();
35 
36  // Find whether to use average or maximum cost values
37  use_max_ = node->declare_or_get_parameter(getName() + ".use_maximum", true);
38 
39  // Edge is invalid if its in collision
40  invalid_on_collision_ = node->declare_or_get_parameter(
41  getName() + ".invalid_on_collision", true);
42 
43  // Edge is invalid if edge is off the costmap
44  invalid_off_map_ = node->declare_or_get_parameter(
45  getName() + ".invalid_off_map", true);
46 
47  // Max cost to be considered valid
48  max_cost_ = static_cast<float>(
49  node->declare_or_get_parameter(getName() + ".max_cost", 253.0));
50 
51  // Resolution to check the costmap over (1=every cell, 2=every other cell, etc.)
52  check_resolution_ = static_cast<unsigned int>(
53  node->declare_or_get_parameter(getName() + ".check_resolution", 2));
54 
55  // Create costmap subscriber if not the same as the server costmap
56  std::string server_costmap_topic = node->get_parameter("costmap_topic").as_string();
57  std::string costmap_topic = node->declare_or_get_parameter(
58  getName() + ".costmap_topic", std::string("global_costmap/costmap_raw"));
59  if (costmap_topic != server_costmap_topic) {
60  costmap_subscriber_ = std::make_shared<nav2_costmap_2d::CostmapSubscriber>(
61  node, costmap_topic);
62  RCLCPP_INFO(
63  node->get_logger(),
64  "Using costmap topic: %s instead of server costmap topic: %s for CostmapScorer.",
65  costmap_topic.c_str(), server_costmap_topic.c_str());
66  } else {
67  costmap_subscriber_ = costmap_subscriber;
68  }
69 
70  // Find the proportional weight to apply, if multiple cost functions
71  weight_ = static_cast<float>(
72  node->declare_or_get_parameter(getName() + ".weight", 1.0));
73 }
74 
76 {
77  try {
78  costmap_ = costmap_subscriber_->getCostmap();
79  } catch (...) {
80  costmap_.reset();
81  }
82 }
83 
85  const EdgePtr edge,
86  const RouteRequest & /* route_request */,
87  const EdgeType & /* edge_type */, float & cost)
88 {
89  if (!costmap_) {
90  RCLCPP_WARN_THROTTLE(logger_, *clock_, 1000, "No costmap yet received!");
91  return false;
92  }
93 
94  std::lock_guard<nav2_costmap_2d::Costmap2D::mutex_t> lock(*costmap_->getMutex());
95 
96  float largest_cost = 0.0, running_cost = 0.0, point_cost = 0.0;
97  unsigned int x0, y0, x1, y1, idx = 0;
98  if (!costmap_->worldToMap(edge->start->coords.x, edge->start->coords.y, x0, y0) ||
99  !costmap_->worldToMap(edge->end->coords.x, edge->end->coords.y, x1, y1))
100  {
101  if (invalid_off_map_) {
102  // Edge is invalid if it is off the costmap
103  return false;
104  }
105  return true;
106  }
107 
108  for (nav2_util::LineIterator iter(x0, y0, x1, y1); iter.isValid(); ) {
109  point_cost = static_cast<float>(costmap_->getCost(iter.getX(), iter.getY()));
110  if (point_cost >= max_cost_ && max_cost_ != 255.0f /*Unknown*/ && invalid_on_collision_) {
111  // Edge is invalid if it is in collision or higher than max allowed cost
112  return false;
113  }
114 
115  idx++;
116  running_cost += point_cost;
117  if (largest_cost < point_cost && point_cost != 255.0) {
118  largest_cost = point_cost;
119  }
120 
121  // Advance the iterator by the check resolution on the edge, pruning to a coarse resolution
122  for (unsigned int i = 0; i < check_resolution_; i++) {
123  iter.advance();
124  }
125  }
126 
127  if (use_max_) {
128  cost = weight_ * largest_cost / max_cost_;
129  } else {
130  cost = weight_ * running_cost / (static_cast<float>(idx) * max_cost_);
131  }
132 
133  return true;
134 }
135 
137 {
138  return name_;
139 }
140 
141 } // namespace nav2_route
142 
143 #include "pluginlib/class_list_macros.hpp"
Scores edges by the average or maximum cost found while iterating over the edge's line segment in the...
std::string getName() override
Get name of the plugin for parameter scope mapping.
void prepare() override
Prepare for a new cycle, by resetting state, grabbing data to use for all immediate requests,...
void configure(const nav2::LifecycleNode::SharedPtr node, const nav2::TransformBuffer::SharedPtr tf_buffer, std::shared_ptr< nav2_costmap_2d::CostmapSubscriber > costmap_subscriber, const std::string &name) override
Configure.
bool score(const EdgePtr edge, const RouteRequest &route_request, const EdgeType &edge_type, float &cost) override
Main scoring plugin API.
A plugin interface to score edges during graph search to modify the lowest cost path (e....
An iterator implementing Bresenham Ray-Tracing.
bool isValid() const
If the iterator is valid.
An object representing edges between nodes.
Definition: types.hpp:134
An object to store salient features of the route request including its start and goal node ids,...
Definition: types.hpp:224