Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
costmap.cpp
1 // Copyright (c) 2025 Angsa Robotics
2 // Copyright (c) 2025 lotusymt
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include "nav2_msgs/msg/costmap.hpp"
18 #include <cmath>
19 #include <tf2/time.hpp>
20 #include <tf2_ros/buffer.hpp>
21 #include <tf2_ros/transform_listener.hpp>
22 #include <nav2_ros_common/node_utils.hpp>
23 #include <nav2_ros_common/qos_profiles.hpp>
24 #include <nav2_costmap_2d/cost_values.hpp>
25 #include "nav2_ros_common/tf2_factories.hpp"
26 
27 namespace nav2_collision_monitor
28 {
29 
31  const nav2::LifecycleNode::WeakPtr & node,
32  const std::string & source_name,
33  const nav2::TransformBuffer::SharedPtr tf_buffer,
34  const std::string & base_frame_id,
35  const std::string & global_frame_id,
36  const tf2::Duration & transform_tolerance,
37  const rclcpp::Duration & source_timeout,
38  const bool base_shift_correction)
39 : Source(
40  node, source_name, tf_buffer, base_frame_id, global_frame_id,
41  transform_tolerance, source_timeout, base_shift_correction),
42  data_(nullptr)
43 {
44  RCLCPP_INFO(logger_, "[%s]: Creating CostmapSource", source_name_.c_str());
45 }
46 
48 {
49  RCLCPP_INFO(logger_, "[%s]: Destroying CostmapSource", source_name_.c_str());
50  data_sub_.reset();
51 }
52 
54 {
55  if (!Source::configure()) {
56  return false;
57  }
58  auto node = node_.lock();
59  if (!node) {
60  throw std::runtime_error{"Failed to lock node"};
61  }
62  std::string source_topic;
63  getParameters(source_topic);
64  data_sub_ = node->create_subscription<nav2_msgs::msg::Costmap>(
65  source_topic,
66  std::bind(&CostmapSource::dataCallback, this, std::placeholders::_1),
68 
69  return true;
70 }
71 
73  const rclcpp::Time & curr_time,
74  std::vector<Point> & data)
75 {
76  auto node = node_.lock();
77  if (data_ == nullptr) {
78  return false;
79  }
80 
81  if (!sourceValid(data_->header.stamp, curr_time)) {
82  return false;
83  }
84  tf2::Transform tf_transform; tf_transform.setIdentity();
85  const std::string src = data_->header.frame_id;
86 
87  if (src != base_frame_id_) {
88  if (!getTransform(curr_time, data_->header, tf_transform)) {
89  RCLCPP_WARN(logger_, "[%s] TF %s->%s unavailable at t=%.3f",
90  source_name_.c_str(), src.c_str(), base_frame_id_.c_str(), curr_time.seconds());
91  return false;
92  }
93  }
94 
95  // Extract lethal/inscribed cells and transform to base frame
96  const auto & cm = *data_;
97  const auto & meta = cm.metadata;
98 
99  for (unsigned int y = 0; y < meta.size_y; ++y) {
100  for (unsigned int x = 0; x < meta.size_x; ++x) {
101  const int idx = y * meta.size_x + x;
102  const uint8_t cell_cost = cm.data[idx];
103  const bool is_obstacle =
104  (cell_cost >= cost_threshold_ && cell_cost < nav2_costmap_2d::NO_INFORMATION) ||
105  (treat_unknown_as_obstacle_ && cell_cost == nav2_costmap_2d::NO_INFORMATION);
106  if (is_obstacle) {
107  const double wx = meta.origin.position.x + (x + 0.5) * meta.resolution;
108  const double wy = meta.origin.position.y + (y + 0.5) * meta.resolution;
109  tf2::Vector3 p_v3_s(wx, wy, 0.0);
110  tf2::Vector3 p_v3_b = tf_transform * p_v3_s;
111  data.push_back({p_v3_b.x(), p_v3_b.y(), p_v3_b.z(), source_name_});
112  RCLCPP_DEBUG_THROTTLE(
113  logger_, *node->get_clock(), 2000 /*ms*/,
114  "[%s] Found obstacles in costmap", source_name_.c_str());
115  }
116  }
117  }
118 
119  return true;
120 }
121 
122 void CostmapSource::getParameters(std::string & source_topic)
123 {
124  auto node = node_.lock();
125  if (!node) {
126  throw std::runtime_error{"Failed to lock node"};
127  }
128  getCommonParameters(source_topic);
129 
130  // Cost threshold (0–255). 253 = inscribed 254 = lethal; 255 = NO_INFORMATION.
131  const auto thresh_name = source_name_ + ".cost_threshold";
132  // Minimal change (no range descriptor)
133  int v = node->declare_or_get_parameter<int>(thresh_name, 253); // declare if missing, else get
134  v = std::max(0, std::min(255, v)); // clamp
135  if (v != node->get_parameter(thresh_name).as_int()) {
136  RCLCPP_WARN(node->get_logger(), "Clamping %s to %d", thresh_name.c_str(), v);
137  }
138  cost_threshold_ = v;
139 
140  // Whether 255 (NO_INFORMATION) should be treated as an obstacle.
141  const auto unk_name = source_name_ + ".treat_unknown_as_obstacle";
142  treat_unknown_as_obstacle_ = node->declare_or_get_parameter<bool>(unk_name, true);
143 }
144 
145 void CostmapSource::dataCallback(nav2_msgs::msg::Costmap::ConstSharedPtr msg)
146 {
147  data_ = msg;
148 }
149 
150 } // namespace nav2_collision_monitor
A QoS profile for standard reliable topics with a history of 10 messages.
bool configure()
Declare and get parameters; create the subscription.
Definition: costmap.cpp:53
void getParameters(std::string &source_topic)
Read parameters specific to the costmap source.
Definition: costmap.cpp:122
bool getSourceData(const rclcpp::Time &curr_time, std::vector< Point > &data) override
Produce current obstacle points from the latest costmap.
Definition: costmap.cpp:72
CostmapSource(const nav2::LifecycleNode::WeakPtr &node, const std::string &source_name, const nav2::TransformBuffer::SharedPtr tf_buffer, const std::string &base_frame_id, const std::string &global_frame_id, const tf2::Duration &transform_tolerance, const rclcpp::Duration &source_timeout, const bool base_shift_correction)
Construct a CostmapSource.
Definition: costmap.cpp:30
Basic data source class.
Definition: source.hpp:44
nav2::LifecycleNode::WeakPtr node_
Collision Monitor node.
Definition: source.hpp:205
rclcpp::Logger logger_
Collision monitor node logger stored for further usage.
Definition: source.hpp:207
std::string base_frame_id_
Robot base frame ID.
Definition: source.hpp:221
bool getTransform(const rclcpp::Time &curr_time, const std_msgs::msg::Header &data_header, tf2::Transform &tf_transform) const
Obtain the transform to get data from source frame and time where it was received to the base frame a...
Definition: source.cpp:325
void getCommonParameters(std::string &source_topic)
Supporting routine obtaining ROS-parameters common for all data sources.
Definition: source.cpp:160
bool configure()
Source configuration routine.
Definition: source.cpp:62
std::string source_name_
Name of data source.
Definition: source.hpp:215
bool sourceValid(const rclcpp::Time &source_time, const rclcpp::Time &curr_time) const
Checks whether the source data might be considered as valid.
Definition: source.cpp:179
Observation source that converts a Nav2 costmap topic into 2D points for Collision Monitor.