add humble-navigation2
This commit is contained in:
1 parent
974abb5e1e
commit
e74ec539c2
1280 files changed
+204114
No files matched your search
@@ -0,0 +1,7 @@
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
Changelog for package nav2_costmap_2d
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
(2018-10-9)
|
||||
-------------------
|
||||
* Port nav2_costmap_2d from costmap_2d version 1.16.2 (2018-07-31)
|
||||
@@ -0,0 +1,194 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
project(nav2_costmap_2d)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(geometry_msgs REQUIRED)
|
||||
find_package(laser_geometry REQUIRED)
|
||||
find_package(map_msgs REQUIRED)
|
||||
find_package(message_filters REQUIRED)
|
||||
find_package(nav2_common REQUIRED)
|
||||
find_package(nav2_msgs REQUIRED)
|
||||
find_package(nav2_util)
|
||||
find_package(nav2_voxel_grid REQUIRED)
|
||||
find_package(nav_msgs REQUIRED)
|
||||
find_package(pluginlib REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
find_package(rclcpp_lifecycle REQUIRED)
|
||||
find_package(rmw REQUIRED)
|
||||
find_package(sensor_msgs REQUIRED)
|
||||
find_package(std_msgs REQUIRED)
|
||||
find_package(std_srvs REQUIRED)
|
||||
find_package(tf2_geometry_msgs REQUIRED)
|
||||
find_package(tf2 REQUIRED)
|
||||
find_package(tf2_ros REQUIRED)
|
||||
find_package(tf2_sensor_msgs REQUIRED)
|
||||
find_package(visualization_msgs REQUIRED)
|
||||
find_package(angles REQUIRED)
|
||||
|
||||
remove_definitions(-DDISABLE_LIBUSB-1.0)
|
||||
find_package(Eigen3 3.3 REQUIRED)
|
||||
|
||||
nav2_package()
|
||||
|
||||
add_library(nav2_costmap_2d_core SHARED
|
||||
src/array_parser.cpp
|
||||
src/costmap_2d.cpp
|
||||
src/layer.cpp
|
||||
src/layered_costmap.cpp
|
||||
src/costmap_2d_ros.cpp
|
||||
src/costmap_2d_publisher.cpp
|
||||
src/costmap_math.cpp
|
||||
src/footprint.cpp
|
||||
src/costmap_layer.cpp
|
||||
src/observation_buffer.cpp
|
||||
src/clear_costmap_service.cpp
|
||||
src/footprint_collision_checker.cpp
|
||||
plugins/costmap_filters/costmap_filter.cpp
|
||||
)
|
||||
add_library(${PROJECT_NAME}::nav2_costmap_2d_core ALIAS nav2_costmap_2d_core)
|
||||
|
||||
target_include_directories(nav2_costmap_2d_core
|
||||
PUBLIC
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:include/${PROJECT_NAME}>"
|
||||
)
|
||||
|
||||
set(dependencies
|
||||
geometry_msgs
|
||||
laser_geometry
|
||||
map_msgs
|
||||
message_filters
|
||||
nav2_msgs
|
||||
nav2_util
|
||||
nav2_voxel_grid
|
||||
nav_msgs
|
||||
pluginlib
|
||||
rclcpp
|
||||
rclcpp_lifecycle
|
||||
sensor_msgs
|
||||
std_msgs
|
||||
std_srvs
|
||||
tf2
|
||||
tf2_geometry_msgs
|
||||
tf2_ros
|
||||
tf2_sensor_msgs
|
||||
visualization_msgs
|
||||
angles
|
||||
)
|
||||
|
||||
ament_target_dependencies(nav2_costmap_2d_core
|
||||
${dependencies}
|
||||
)
|
||||
target_link_libraries(nav2_costmap_2d_core Eigen3::Eigen)
|
||||
|
||||
add_library(layers SHARED
|
||||
plugins/inflation_layer.cpp
|
||||
plugins/static_layer.cpp
|
||||
plugins/obstacle_layer.cpp
|
||||
src/observation_buffer.cpp
|
||||
plugins/voxel_layer.cpp
|
||||
plugins/range_sensor_layer.cpp
|
||||
plugins/denoise_layer.cpp
|
||||
)
|
||||
add_library(${PROJECT_NAME}::layers ALIAS layers)
|
||||
ament_target_dependencies(layers
|
||||
${dependencies}
|
||||
)
|
||||
target_link_libraries(layers
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
add_library(filters SHARED
|
||||
plugins/costmap_filters/keepout_filter.cpp
|
||||
plugins/costmap_filters/speed_filter.cpp
|
||||
plugins/costmap_filters/binary_filter.cpp
|
||||
)
|
||||
add_library(${PROJECT_NAME}::filters ALIAS filters)
|
||||
|
||||
|
||||
ament_target_dependencies(filters
|
||||
${dependencies}
|
||||
)
|
||||
target_link_libraries(filters
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
add_library(nav2_costmap_2d_client SHARED
|
||||
src/footprint_subscriber.cpp
|
||||
src/costmap_subscriber.cpp
|
||||
src/costmap_topic_collision_checker.cpp
|
||||
)
|
||||
add_library(${PROJECT_NAME}::nav2_costmap_2d_client ALIAS nav2_costmap_2d_client)
|
||||
|
||||
ament_target_dependencies(nav2_costmap_2d_client
|
||||
${dependencies}
|
||||
)
|
||||
|
||||
target_link_libraries(nav2_costmap_2d_client
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
add_executable(nav2_costmap_2d_markers src/costmap_2d_markers.cpp)
|
||||
target_link_libraries(nav2_costmap_2d_markers
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_target_dependencies(nav2_costmap_2d_markers
|
||||
${dependencies}
|
||||
)
|
||||
|
||||
add_executable(nav2_costmap_2d_cloud src/costmap_2d_cloud.cpp)
|
||||
target_link_libraries(nav2_costmap_2d_cloud
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
add_executable(nav2_costmap_2d src/costmap_2d_node.cpp)
|
||||
ament_target_dependencies(nav2_costmap_2d
|
||||
${dependencies}
|
||||
)
|
||||
|
||||
target_link_libraries(nav2_costmap_2d
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::layers
|
||||
${PROJECT_NAME}::filters
|
||||
)
|
||||
|
||||
install(TARGETS
|
||||
layers
|
||||
filters
|
||||
nav2_costmap_2d_core
|
||||
nav2_costmap_2d_client
|
||||
EXPORT export_${PROJECT_NAME}
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
install(TARGETS nav2_costmap_2d_markers nav2_costmap_2d_cloud nav2_costmap_2d
|
||||
DESTINATION lib/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
install(FILES costmap_plugins.xml
|
||||
DESTINATION share/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
install(DIRECTORY include/
|
||||
DESTINATION include/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
find_package(ament_lint_auto REQUIRED)
|
||||
# the following line skips the linter which checks for copyrights
|
||||
set(ament_cmake_copyright_FOUND TRUE)
|
||||
set(ament_cmake_cpplint_FOUND TRUE)
|
||||
ament_lint_auto_find_test_dependencies()
|
||||
|
||||
find_package(ament_cmake_gtest REQUIRED)
|
||||
add_subdirectory(test)
|
||||
pluginlib_export_plugin_description_file(nav2_costmap_2d test/regression/order_layer.xml)
|
||||
endif()
|
||||
|
||||
ament_export_targets(export_${PROJECT_NAME} HAS_LIBRARY_TARGET)
|
||||
ament_export_dependencies(${dependencies})
|
||||
pluginlib_export_plugin_description_file(nav2_costmap_2d costmap_plugins.xml)
|
||||
ament_package()
|
||||
@@ -0,0 +1,27 @@
|
||||
# Nav2 Costmap_2d
|
||||
|
||||
The costmap_2d package is responsible for building a 2D costmap of the environment, consisting of several "layers" of data about the environment. It can be initialized via the map server or a local rolling window and updates the layers by taking observations from sensors. A plugin interface allows for the layers to be combined into the costmap and finally inflated via an inflation radius based on the robot footprint. The nav2 version of the costmap_2d package is mostly a direct ROS2 port of the ROS1 navigation stack version, with minimal noteable changes necessary due to support in ROS2.
|
||||
|
||||
See its [Configuration Guide Page](https://navigation.ros.org/configuration/packages/configuring-costmaps.html) for additional parameter descriptions for the costmap and its included plugins. The [tutorials](https://navigation.ros.org/tutorials/index.html) and [first-time setup guides](https://navigation.ros.org/setup_guides/index.html) also provide helpful context for working with the costmap 2D package and its layers. A [tutorial](https://navigation.ros.org/plugin_tutorials/docs/writing_new_costmap2d_plugin.html) is also provided to explain how to create costmap plugins.
|
||||
|
||||
See the [Navigation Plugin list](https://navigation.ros.org/plugins/index.html) for a list of the currently known and available planner plugins.
|
||||
|
||||
## To visualize the voxels in RVIZ:
|
||||
- Make sure `publish_voxel_map` in `voxel_layer` param's scope is set to `True`.
|
||||
- Open a new terminal and run:
|
||||
```ros2 run nav2_costmap_2d nav2_costmap_2d_markers voxel_grid:=/local_costmap/voxel_grid visualization_marker:=/my_marker```
|
||||
Here you can change `my_marker` to any topic name you like for the markers to be published on.
|
||||
|
||||
- Then add `my_marker` to RVIZ using the GUI.
|
||||
|
||||
|
||||
### Errata:
|
||||
- To see the markers in 3D, you will need to change the _view_ in RVIZ to a 3 dimensional view (e.g. orbit) from the RVIZ GUI.
|
||||
- Currently due to some bug in rviz, you need to set the `fixed_frame` in the rviz display, to `odom` frame.
|
||||
- Using pointcloud data from a saved bag file while using gazebo simulation can be troublesome due to the clock time skipping to an earlier time.
|
||||
|
||||
## Costmap Filters
|
||||
|
||||
### Overview
|
||||
|
||||
Costmap Filters - is a costmap layer-based instrument which provides an ability to apply to map spatial-dependent raster features named as filter-masks. These features are used in plugin algorithms when filling costmaps in order to allow robots to change their trajectory, behavior or speed when a robot enters/leaves an area marked in a filter masks. Examples of costmap filters include keep-out/safety zones where robots will never enter, speed restriction areas, preferred lanes for robots moving in industries and warehouses. More information about design, architecture of the feature and how it works could be found on Nav2 website: https://navigation.ros.org.
|
||||
@@ -0,0 +1,35 @@
|
||||
<class_libraries>
|
||||
<library path="layers">
|
||||
<class type="nav2_costmap_2d::InflationLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Inflates obstacles to speed collision checking and to make robot prefer to stay away from obstacles.</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::ObstacleLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Listens to laser scan and point cloud messages and marks and clears grid cells.</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::StaticLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Listens to OccupancyGrid messages and copies them in, like from map_server.</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::VoxelLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Similar to obstacle costmap, but uses 3D voxel grid to store data.</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::RangeSensorLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>A range-sensor (sonar, IR) based obstacle layer for costmap_2d</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::DenoiseLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Filters noise-induced freestanding obstacles or small obstacles groups</description>
|
||||
</class>
|
||||
</library>
|
||||
|
||||
<library path="filters">
|
||||
<class type="nav2_costmap_2d::KeepoutFilter" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Prevents the robot from appearing in keepout zones marked on map.</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::SpeedFilter" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Restricts maximum speed of robot in speed-limit zones marked on map.</description>
|
||||
</class>
|
||||
<class type="nav2_costmap_2d::BinaryFilter" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Binary flip filter.</description>
|
||||
</class>
|
||||
</library>
|
||||
</class_libraries>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright (c) 2012, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* author: Dave Hershberger
|
||||
*/
|
||||
#ifndef NAV2_COSTMAP_2D__ARRAY_PARSER_HPP_
|
||||
#define NAV2_COSTMAP_2D__ARRAY_PARSER_HPP_
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief Parse a vector of vectors of floats from a string.
|
||||
* @param error_return If no error, error_return is set to "". If
|
||||
* error, error_return will describe the error.
|
||||
* Syntax is [[1.0, 2.0], [3.3, 4.4, 5.5], ...]
|
||||
*
|
||||
* On error, error_return is set and the return value could be
|
||||
* anything, like part of a successful parse. */
|
||||
std::vector<std::vector<float>> parseVVF(const std::string & input, std::string & error_return);
|
||||
|
||||
} // end namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__ARRAY_PARSER_HPP_
|
||||
@@ -0,0 +1,119 @@
|
||||
// Copyright (c) 2018 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__CLEAR_COSTMAP_SERVICE_HPP_
|
||||
#define NAV2_COSTMAP_2D__CLEAR_COSTMAP_SERVICE_HPP_
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_msgs/srv/clear_costmap_except_region.hpp"
|
||||
#include "nav2_msgs/srv/clear_costmap_around_robot.hpp"
|
||||
#include "nav2_msgs/srv/clear_entire_costmap.hpp"
|
||||
#include "nav2_costmap_2d/costmap_layer.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
class Costmap2DROS;
|
||||
|
||||
/**
|
||||
* @class ClearCostmapService
|
||||
* @brief Exposes services to clear costmap objects in inclusive/exclusive regions or completely
|
||||
*/
|
||||
class ClearCostmapService
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
ClearCostmapService(const nav2_util::LifecycleNode::WeakPtr & parent, Costmap2DROS & costmap);
|
||||
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
ClearCostmapService() = delete;
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~ClearCostmapService();
|
||||
|
||||
/**
|
||||
* @brief Clears the region outside of a user-specified area reverting to the static map
|
||||
*/
|
||||
void clearRegion(double reset_distance, bool invert);
|
||||
|
||||
/**
|
||||
* @brief Clears all layers
|
||||
*/
|
||||
void clearEntirely();
|
||||
|
||||
private:
|
||||
// The Logger object for logging
|
||||
rclcpp::Logger logger_{rclcpp::get_logger("nav2_costmap_2d")};
|
||||
|
||||
// The costmap to clear
|
||||
Costmap2DROS & costmap_;
|
||||
|
||||
// Clearing parameters
|
||||
unsigned char reset_value_;
|
||||
|
||||
// Server for clearing the costmap
|
||||
rclcpp::Service<nav2_msgs::srv::ClearCostmapExceptRegion>::SharedPtr clear_except_service_;
|
||||
/**
|
||||
* @brief Callback to clear costmap except in a given region
|
||||
*/
|
||||
void clearExceptRegionCallback(
|
||||
const std::shared_ptr<rmw_request_id_t> request_header,
|
||||
const std::shared_ptr<nav2_msgs::srv::ClearCostmapExceptRegion::Request> request,
|
||||
const std::shared_ptr<nav2_msgs::srv::ClearCostmapExceptRegion::Response> response);
|
||||
|
||||
rclcpp::Service<nav2_msgs::srv::ClearCostmapAroundRobot>::SharedPtr clear_around_service_;
|
||||
/**
|
||||
* @brief Callback to clear costmap in a given region
|
||||
*/
|
||||
void clearAroundRobotCallback(
|
||||
const std::shared_ptr<rmw_request_id_t> request_header,
|
||||
const std::shared_ptr<nav2_msgs::srv::ClearCostmapAroundRobot::Request> request,
|
||||
const std::shared_ptr<nav2_msgs::srv::ClearCostmapAroundRobot::Response> response);
|
||||
|
||||
rclcpp::Service<nav2_msgs::srv::ClearEntireCostmap>::SharedPtr clear_entire_service_;
|
||||
/**
|
||||
* @brief Callback to clear costmap
|
||||
*/
|
||||
void clearEntireCallback(
|
||||
const std::shared_ptr<rmw_request_id_t> request_header,
|
||||
const std::shared_ptr<nav2_msgs::srv::ClearEntireCostmap::Request> request,
|
||||
const std::shared_ptr<nav2_msgs::srv::ClearEntireCostmap::Response> response);
|
||||
|
||||
/**
|
||||
* @brief Function used to clear a given costmap layer
|
||||
*/
|
||||
void clearLayerRegion(
|
||||
std::shared_ptr<CostmapLayer> & costmap, double pose_x, double pose_y, double reset_distance,
|
||||
bool invert);
|
||||
|
||||
/**
|
||||
* @brief Get the robot's position in the costmap using the master costmap
|
||||
*/
|
||||
bool getPosition(double & x, double & y) const;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__CLEAR_COSTMAP_SERVICE_HPP_
|
||||
@@ -0,0 +1,48 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__COST_VALUES_HPP_
|
||||
#define NAV2_COSTMAP_2D__COST_VALUES_HPP_
|
||||
/** Provides a mapping for often used cost values */
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
static constexpr unsigned char NO_INFORMATION = 255;
|
||||
static constexpr unsigned char LETHAL_OBSTACLE = 254;
|
||||
static constexpr unsigned char INSCRIBED_INFLATED_OBSTACLE = 253;
|
||||
static constexpr unsigned char MAX_NON_OBSTACLE = 252;
|
||||
static constexpr unsigned char FREE_SPACE = 0;
|
||||
}
|
||||
#endif // NAV2_COSTMAP_2D__COST_VALUES_HPP_
|
||||
@@ -0,0 +1,572 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_2D_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_2D_HPP_
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include "geometry_msgs/msg/point.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
// convenient for storing x/y point pairs
|
||||
struct MapLocation
|
||||
{
|
||||
unsigned int x;
|
||||
unsigned int y;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class Costmap2D
|
||||
* @brief A 2D costmap provides a mapping between points in the world and their associated "costs".
|
||||
*/
|
||||
class Costmap2D
|
||||
{
|
||||
friend class CostmapTester; // Need this for gtest to work correctly
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for a costmap
|
||||
* @param cells_size_x The x size of the map in cells
|
||||
* @param cells_size_y The y size of the map in cells
|
||||
* @param resolution The resolution of the map in meters/cell
|
||||
* @param origin_x The x origin of the map
|
||||
* @param origin_y The y origin of the map
|
||||
* @param default_value Default Value
|
||||
*/
|
||||
Costmap2D(
|
||||
unsigned int cells_size_x, unsigned int cells_size_y, double resolution,
|
||||
double origin_x, double origin_y, unsigned char default_value = 0);
|
||||
|
||||
/**
|
||||
* @brief Copy constructor for a costmap, creates a copy efficiently
|
||||
* @param map The costmap to copy
|
||||
*/
|
||||
Costmap2D(const Costmap2D & map);
|
||||
|
||||
/**
|
||||
* @brief Constructor for a costmap from an OccupancyGrid map
|
||||
* @param map The OccupancyGrid map to create costmap from
|
||||
*/
|
||||
explicit Costmap2D(const nav_msgs::msg::OccupancyGrid & map);
|
||||
|
||||
/**
|
||||
* @brief Overloaded assignment operator
|
||||
* @param map The costmap to copy
|
||||
* @return A reference to the map after the copy has finished
|
||||
*/
|
||||
Costmap2D & operator=(const Costmap2D & map);
|
||||
|
||||
/**
|
||||
* @brief Turn this costmap into a copy of a window of a costmap passed in
|
||||
* @param map The costmap to copy
|
||||
* @param win_origin_x The x origin (lower left corner) for the window to copy, in meters
|
||||
* @param win_origin_y The y origin (lower left corner) for the window to copy, in meters
|
||||
* @param win_size_x The x size of the window, in meters
|
||||
* @param win_size_y The y size of the window, in meters
|
||||
*/
|
||||
bool copyCostmapWindow(
|
||||
const Costmap2D & map, double win_origin_x, double win_origin_y,
|
||||
double win_size_x,
|
||||
double win_size_y);
|
||||
|
||||
/**
|
||||
* @brief Copies the (x0,y0)..(xn,yn) window from source costmap into a current costmap
|
||||
@param source Source costmap where the window will be copied from
|
||||
@param sx0 Lower x-boundary of the source window to copy, in cells
|
||||
@param sy0 Lower y-boundary of the source window to copy, in cells
|
||||
@param sxn Upper x-boundary of the source window to copy, in cells
|
||||
@param syn Upper y-boundary of the source window to copy, in cells
|
||||
@param dx0 Lower x-boundary of the destination window to copy, in cells
|
||||
@param dx0 Lower y-boundary of the destination window to copy, in cells
|
||||
@returns true if copy was succeeded or false in negative case
|
||||
*/
|
||||
bool copyWindow(
|
||||
const Costmap2D & source,
|
||||
unsigned int sx0, unsigned int sy0, unsigned int sxn, unsigned int syn,
|
||||
unsigned int dx0, unsigned int dy0);
|
||||
|
||||
/**
|
||||
* @brief Default constructor
|
||||
*/
|
||||
Costmap2D();
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
virtual ~Costmap2D();
|
||||
|
||||
/**
|
||||
* @brief Get the cost of a cell in the costmap
|
||||
* @param mx The x coordinate of the cell
|
||||
* @param my The y coordinate of the cell
|
||||
* @return The cost of the cell
|
||||
*/
|
||||
unsigned char getCost(unsigned int mx, unsigned int my) const;
|
||||
|
||||
/**
|
||||
* @brief Get the cost of a cell in the costmap
|
||||
* @param index The cell index
|
||||
* @return The cost of the cell
|
||||
*/
|
||||
unsigned char getCost(unsigned int index) const;
|
||||
|
||||
/**
|
||||
* @brief Set the cost of a cell in the costmap
|
||||
* @param mx The x coordinate of the cell
|
||||
* @param my The y coordinate of the cell
|
||||
* @param cost The cost to set the cell to
|
||||
*/
|
||||
void setCost(unsigned int mx, unsigned int my, unsigned char cost);
|
||||
|
||||
/**
|
||||
* @brief Convert from map coordinates to world coordinates
|
||||
* @param mx The x map coordinate
|
||||
* @param my The y map coordinate
|
||||
* @param wx Will be set to the associated world x coordinate
|
||||
* @param wy Will be set to the associated world y coordinate
|
||||
*/
|
||||
void mapToWorld(unsigned int mx, unsigned int my, double & wx, double & wy) const;
|
||||
|
||||
/**
|
||||
* @brief Convert from world coordinates to map coordinates
|
||||
* @param wx The x world coordinate
|
||||
* @param wy The y world coordinate
|
||||
* @param mx Will be set to the associated map x coordinate
|
||||
* @param my Will be set to the associated map y coordinate
|
||||
* @return True if the conversion was successful (legal bounds) false otherwise
|
||||
*/
|
||||
bool worldToMap(double wx, double wy, unsigned int & mx, unsigned int & my) const;
|
||||
|
||||
/**
|
||||
* @brief Convert from world coordinates to map coordinates without checking for legal bounds
|
||||
* @param wx The x world coordinate
|
||||
* @param wy The y world coordinate
|
||||
* @param mx Will be set to the associated map x coordinate
|
||||
* @param my Will be set to the associated map y coordinate
|
||||
* @note The returned map coordinates <b>are not guaranteed to lie within the map.</b>
|
||||
*/
|
||||
void worldToMapNoBounds(double wx, double wy, int & mx, int & my) const;
|
||||
|
||||
/**
|
||||
* @brief Convert from world coordinates to map coordinates, constraining results to legal bounds.
|
||||
* @param wx The x world coordinate
|
||||
* @param wy The y world coordinate
|
||||
* @param mx Will be set to the associated map x coordinate
|
||||
* @param my Will be set to the associated map y coordinate
|
||||
* @note The returned map coordinates are guaranteed to lie within the map.
|
||||
*/
|
||||
void worldToMapEnforceBounds(double wx, double wy, int & mx, int & my) const;
|
||||
|
||||
/**
|
||||
* @brief Given two map coordinates... compute the associated index
|
||||
* @param mx The x coordinate
|
||||
* @param my The y coordinate
|
||||
* @return The associated index
|
||||
*/
|
||||
inline unsigned int getIndex(unsigned int mx, unsigned int my) const
|
||||
{
|
||||
return my * size_x_ + mx;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Given an index... compute the associated map coordinates
|
||||
* @param index The index
|
||||
* @param mx Will be set to the x coordinate
|
||||
* @param my Will be set to the y coordinate
|
||||
*/
|
||||
inline void indexToCells(unsigned int index, unsigned int & mx, unsigned int & my) const
|
||||
{
|
||||
my = index / size_x_;
|
||||
mx = index - (my * size_x_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Will return a pointer to the underlying unsigned char array used as the costmap
|
||||
* @return A pointer to the underlying unsigned char array storing cost values
|
||||
*/
|
||||
unsigned char * getCharMap() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the x size of the costmap in cells
|
||||
* @return The x size of the costmap
|
||||
*/
|
||||
unsigned int getSizeInCellsX() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the y size of the costmap in cells
|
||||
* @return The y size of the costmap
|
||||
*/
|
||||
unsigned int getSizeInCellsY() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the x size of the costmap in meters
|
||||
* @return The x size of the costmap (returns the centerpoint of the last legal cell in the map)
|
||||
*/
|
||||
double getSizeInMetersX() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the y size of the costmap in meters
|
||||
* @return The y size of the costmap (returns the centerpoint of the last legal cell in the map)
|
||||
*/
|
||||
double getSizeInMetersY() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the x origin of the costmap
|
||||
* @return The x origin of the costmap
|
||||
*/
|
||||
double getOriginX() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the y origin of the costmap
|
||||
* @return The y origin of the costmap
|
||||
*/
|
||||
double getOriginY() const;
|
||||
|
||||
/**
|
||||
* @brief Accessor for the resolution of the costmap
|
||||
* @return The resolution of the costmap
|
||||
*/
|
||||
double getResolution() const;
|
||||
|
||||
/**
|
||||
* @brief Set the default background value of the costmap
|
||||
* @param c default value
|
||||
*/
|
||||
void setDefaultValue(unsigned char c)
|
||||
{
|
||||
default_value_ = c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the default background value of the costmap
|
||||
* @return default value
|
||||
*/
|
||||
unsigned char getDefaultValue()
|
||||
{
|
||||
return default_value_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the cost of a convex polygon to a desired value
|
||||
* @param polygon The polygon to perform the operation on
|
||||
* @param cost_value The value to set costs to
|
||||
* @return True if the polygon was filled... false if it could not be filled
|
||||
*/
|
||||
bool setConvexPolygonCost(
|
||||
const std::vector<geometry_msgs::msg::Point> & polygon,
|
||||
unsigned char cost_value);
|
||||
|
||||
/**
|
||||
* @brief Get the map cells that make up the outline of a polygon
|
||||
* @param polygon The polygon in map coordinates to rasterize
|
||||
* @param polygon_cells Will be set to the cells contained in the outline of the polygon
|
||||
*/
|
||||
void polygonOutlineCells(
|
||||
const std::vector<MapLocation> & polygon,
|
||||
std::vector<MapLocation> & polygon_cells);
|
||||
|
||||
/**
|
||||
* @brief Get the map cells that fill a convex polygon
|
||||
* @param polygon The polygon in map coordinates to rasterize
|
||||
* @param polygon_cells Will be set to the cells that fill the polygon
|
||||
*/
|
||||
void convexFillCells(
|
||||
const std::vector<MapLocation> & polygon,
|
||||
std::vector<MapLocation> & polygon_cells);
|
||||
|
||||
/**
|
||||
* @brief Move the origin of the costmap to a new location.... keeping data when it can
|
||||
* @param new_origin_x The x coordinate of the new origin
|
||||
* @param new_origin_y The y coordinate of the new origin
|
||||
*/
|
||||
virtual void updateOrigin(double new_origin_x, double new_origin_y);
|
||||
|
||||
/**
|
||||
* @brief Save the costmap out to a pgm file
|
||||
* @param file_name The name of the file to save
|
||||
*/
|
||||
bool saveMap(std::string file_name);
|
||||
|
||||
/**
|
||||
* @brief Resize the costmap
|
||||
*/
|
||||
void resizeMap(
|
||||
unsigned int size_x, unsigned int size_y, double resolution, double origin_x,
|
||||
double origin_y);
|
||||
|
||||
/**
|
||||
* @brief Reset the costmap in bounds
|
||||
*/
|
||||
void resetMap(unsigned int x0, unsigned int y0, unsigned int xn, unsigned int yn);
|
||||
|
||||
/**
|
||||
* @brief Reset the costmap in bounds to a value
|
||||
*/
|
||||
void resetMapToValue(
|
||||
unsigned int x0, unsigned int y0, unsigned int xn, unsigned int yn, unsigned char value);
|
||||
|
||||
/**
|
||||
* @brief Given distance in the world... convert it to cells
|
||||
* @param world_dist The world distance
|
||||
* @return The equivalent cell distance
|
||||
*/
|
||||
unsigned int cellDistance(double world_dist);
|
||||
|
||||
// Provide a typedef to ease future code maintenance
|
||||
typedef std::recursive_mutex mutex_t;
|
||||
mutex_t * getMutex()
|
||||
{
|
||||
return access_;
|
||||
}
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Copy a region of a source map into a destination map
|
||||
* @param source_map The source map
|
||||
* @param sm_lower_left_x The lower left x point of the source map to start the copy
|
||||
* @param sm_lower_left_y The lower left y point of the source map to start the copy
|
||||
* @param sm_size_x The x size of the source map
|
||||
* @param dest_map The destination map
|
||||
* @param dm_lower_left_x The lower left x point of the destination map to start the copy
|
||||
* @param dm_lower_left_y The lower left y point of the destination map to start the copy
|
||||
* @param dm_size_x The x size of the destination map
|
||||
* @param region_size_x The x size of the region to copy
|
||||
* @param region_size_y The y size of the region to copy
|
||||
*/
|
||||
template<typename data_type>
|
||||
void copyMapRegion(
|
||||
data_type * source_map, unsigned int sm_lower_left_x,
|
||||
unsigned int sm_lower_left_y,
|
||||
unsigned int sm_size_x, data_type * dest_map, unsigned int dm_lower_left_x,
|
||||
unsigned int dm_lower_left_y, unsigned int dm_size_x, unsigned int region_size_x,
|
||||
unsigned int region_size_y)
|
||||
{
|
||||
// we'll first need to compute the starting points for each map
|
||||
data_type * sm_index = source_map + (sm_lower_left_y * sm_size_x + sm_lower_left_x);
|
||||
data_type * dm_index = dest_map + (dm_lower_left_y * dm_size_x + dm_lower_left_x);
|
||||
|
||||
// now, we'll copy the source map into the destination map
|
||||
for (unsigned int i = 0; i < region_size_y; ++i) {
|
||||
memcpy(dm_index, sm_index, region_size_x * sizeof(data_type));
|
||||
sm_index += sm_size_x;
|
||||
dm_index += dm_size_x;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Deletes the costmap, static_map, and markers data structures
|
||||
*/
|
||||
virtual void deleteMaps();
|
||||
|
||||
/**
|
||||
* @brief Resets the costmap and static_map to be unknown space
|
||||
*/
|
||||
virtual void resetMaps();
|
||||
|
||||
/**
|
||||
* @brief Initializes the costmap, static_map, and markers data structures
|
||||
* @param size_x The x size to use for map initialization
|
||||
* @param size_y The y size to use for map initialization
|
||||
*/
|
||||
virtual void initMaps(unsigned int size_x, unsigned int size_y);
|
||||
|
||||
/**
|
||||
* @brief Raytrace a line and apply some action at each step
|
||||
* @param at The action to take... a functor
|
||||
* @param x0 The starting x coordinate
|
||||
* @param y0 The starting y coordinate
|
||||
* @param x1 The ending x coordinate
|
||||
* @param y1 The ending y coordinate
|
||||
* @param max_length The maximum desired length of the segment...
|
||||
* allows you to not go all the way to the endpoint
|
||||
* @param min_length The minimum desired length of the segment
|
||||
*/
|
||||
template<class ActionType>
|
||||
inline void raytraceLine(
|
||||
ActionType at, unsigned int x0, unsigned int y0, unsigned int x1,
|
||||
unsigned int y1,
|
||||
unsigned int max_length = UINT_MAX, unsigned int min_length = 0)
|
||||
{
|
||||
int dx_full = x1 - x0;
|
||||
int dy_full = y1 - y0;
|
||||
|
||||
// we need to chose how much to scale our dominant dimension,
|
||||
// based on the maximum length of the line
|
||||
double dist = std::hypot(dx_full, dy_full);
|
||||
if (dist < min_length) {
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned int min_x0, min_y0;
|
||||
if (dist > 0.0) {
|
||||
// Adjust starting point and offset to start from min_length distance
|
||||
min_x0 = (unsigned int)(x0 + dx_full / dist * min_length);
|
||||
min_y0 = (unsigned int)(y0 + dy_full / dist * min_length);
|
||||
} else {
|
||||
// dist can be 0 if [x0, y0]==[x1, y1].
|
||||
// In this case only this cell should be processed.
|
||||
min_x0 = x0;
|
||||
min_y0 = y0;
|
||||
}
|
||||
unsigned int offset = min_y0 * size_x_ + min_x0;
|
||||
|
||||
int dx = x1 - min_x0;
|
||||
int dy = y1 - min_y0;
|
||||
|
||||
unsigned int abs_dx = abs(dx);
|
||||
unsigned int abs_dy = abs(dy);
|
||||
|
||||
int offset_dx = sign(dx);
|
||||
int offset_dy = sign(dy) * size_x_;
|
||||
|
||||
double scale = (dist == 0.0) ? 1.0 : std::min(1.0, max_length / dist);
|
||||
// if x is dominant
|
||||
if (abs_dx >= abs_dy) {
|
||||
int error_y = abs_dx / 2;
|
||||
|
||||
bresenham2D(
|
||||
at, abs_dx, abs_dy, error_y, offset_dx, offset_dy, offset, (unsigned int)(scale * abs_dx));
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise y is dominant
|
||||
int error_x = abs_dy / 2;
|
||||
|
||||
bresenham2D(
|
||||
at, abs_dy, abs_dx, error_x, offset_dy, offset_dx, offset, (unsigned int)(scale * abs_dy));
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief A 2D implementation of Bresenham's raytracing algorithm...
|
||||
* applies an action at each step
|
||||
*/
|
||||
template<class ActionType>
|
||||
inline void bresenham2D(
|
||||
ActionType at, unsigned int abs_da, unsigned int abs_db, int error_b,
|
||||
int offset_a,
|
||||
int offset_b, unsigned int offset,
|
||||
unsigned int max_length)
|
||||
{
|
||||
unsigned int end = std::min(max_length, abs_da);
|
||||
for (unsigned int i = 0; i < end; ++i) {
|
||||
at(offset);
|
||||
offset += offset_a;
|
||||
error_b += abs_db;
|
||||
if ((unsigned int)error_b >= abs_da) {
|
||||
offset += offset_b;
|
||||
error_b -= abs_da;
|
||||
}
|
||||
}
|
||||
at(offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief get the sign of an int
|
||||
*/
|
||||
inline int sign(int x)
|
||||
{
|
||||
return x > 0 ? 1.0 : -1.0;
|
||||
}
|
||||
|
||||
mutex_t * access_;
|
||||
|
||||
protected:
|
||||
unsigned int size_x_;
|
||||
unsigned int size_y_;
|
||||
double resolution_;
|
||||
double origin_x_;
|
||||
double origin_y_;
|
||||
unsigned char * costmap_;
|
||||
unsigned char default_value_;
|
||||
|
||||
// *INDENT-OFF* Uncrustify doesn't handle indented public/private labels
|
||||
class MarkCell
|
||||
{
|
||||
public:
|
||||
MarkCell(unsigned char * costmap, unsigned char value)
|
||||
: costmap_(costmap), value_(value)
|
||||
{
|
||||
}
|
||||
inline void operator()(unsigned int offset)
|
||||
{
|
||||
costmap_[offset] = value_;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned char * costmap_;
|
||||
unsigned char value_;
|
||||
};
|
||||
|
||||
class PolygonOutlineCells
|
||||
{
|
||||
public:
|
||||
PolygonOutlineCells(
|
||||
const Costmap2D & costmap, const unsigned char * /*char_map*/,
|
||||
std::vector<MapLocation> & cells)
|
||||
: costmap_(costmap), cells_(cells)
|
||||
{
|
||||
}
|
||||
|
||||
// just push the relevant cells back onto the list
|
||||
inline void operator()(unsigned int offset)
|
||||
{
|
||||
MapLocation loc;
|
||||
costmap_.indexToCells(offset, loc.x, loc.y);
|
||||
cells_.push_back(loc);
|
||||
}
|
||||
|
||||
private:
|
||||
const Costmap2D & costmap_;
|
||||
std::vector<MapLocation> & cells_;
|
||||
};
|
||||
// *INDENT-ON*
|
||||
};
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_2D_HPP_
|
||||
@@ -0,0 +1,181 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* Copyright (c) 2019, Samsung Research America, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_2D_PUBLISHER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_2D_PUBLISHER_HPP_
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp_lifecycle/lifecycle_node.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "map_msgs/msg/occupancy_grid_update.hpp"
|
||||
#include "nav2_msgs/msg/costmap.hpp"
|
||||
#include "nav2_msgs/srv/get_costmap.hpp"
|
||||
#include "tf2/transform_datatypes.h"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
#include "tf2/LinearMath/Quaternion.h"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class Costmap2DPublisher
|
||||
* @brief A tool to periodically publish visualization data from a Costmap2D
|
||||
*/
|
||||
class Costmap2DPublisher
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the Costmap2DPublisher
|
||||
*/
|
||||
Costmap2DPublisher(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
Costmap2D * costmap,
|
||||
std::string global_frame,
|
||||
std::string topic_name,
|
||||
bool always_send_full_costmap = false);
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
~Costmap2DPublisher();
|
||||
|
||||
/**
|
||||
* @brief Configure node
|
||||
*/
|
||||
void on_configure() {}
|
||||
|
||||
/**
|
||||
* @brief Activate node
|
||||
*/
|
||||
void on_activate()
|
||||
{
|
||||
costmap_pub_->on_activate();
|
||||
costmap_update_pub_->on_activate();
|
||||
costmap_raw_pub_->on_activate();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief deactivate node
|
||||
*/
|
||||
void on_deactivate()
|
||||
{
|
||||
costmap_pub_->on_deactivate();
|
||||
costmap_update_pub_->on_deactivate();
|
||||
costmap_raw_pub_->on_deactivate();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Cleanup node
|
||||
*/
|
||||
void on_cleanup() {}
|
||||
|
||||
/** @brief Include the given bounds in the changed-rectangle. */
|
||||
void updateBounds(unsigned int x0, unsigned int xn, unsigned int y0, unsigned int yn)
|
||||
{
|
||||
x0_ = std::min(x0, x0_);
|
||||
xn_ = std::max(xn, xn_);
|
||||
y0_ = std::min(y0, y0_);
|
||||
yn_ = std::max(yn, yn_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Publishes the visualization data over ROS
|
||||
*/
|
||||
void publishCostmap();
|
||||
|
||||
/**
|
||||
* @brief Check if the publisher is active
|
||||
* @return True if the frequency for the publisher is non-zero, false otherwise
|
||||
*/
|
||||
bool active()
|
||||
{
|
||||
return active_;
|
||||
}
|
||||
|
||||
private:
|
||||
/** @brief Prepare grid_ message for publication. */
|
||||
void prepareGrid();
|
||||
void prepareCostmap();
|
||||
|
||||
/** @brief Publish the latest full costmap to the new subscriber. */
|
||||
// void onNewSubscription(const ros::SingleSubscriberPublisher& pub);
|
||||
|
||||
/** @brief GetCostmap callback service */
|
||||
void costmap_service_callback(
|
||||
const std::shared_ptr<rmw_request_id_t> request_header,
|
||||
const std::shared_ptr<nav2_msgs::srv::GetCostmap::Request> request,
|
||||
const std::shared_ptr<nav2_msgs::srv::GetCostmap::Response> response);
|
||||
|
||||
rclcpp::Clock::SharedPtr clock_;
|
||||
rclcpp::Logger logger_{rclcpp::get_logger("nav2_costmap_2d")};
|
||||
|
||||
Costmap2D * costmap_;
|
||||
std::string global_frame_;
|
||||
std::string topic_name_;
|
||||
unsigned int x0_, xn_, y0_, yn_;
|
||||
double saved_origin_x_;
|
||||
double saved_origin_y_;
|
||||
bool active_;
|
||||
bool always_send_full_costmap_;
|
||||
|
||||
// Publisher for translated costmap values as msg::OccupancyGrid used in visualization
|
||||
rclcpp_lifecycle::LifecyclePublisher<nav_msgs::msg::OccupancyGrid>::SharedPtr costmap_pub_;
|
||||
rclcpp_lifecycle::LifecyclePublisher<map_msgs::msg::OccupancyGridUpdate>::SharedPtr
|
||||
costmap_update_pub_;
|
||||
|
||||
// Publisher for raw costmap values as msg::Costmap from layered costmap
|
||||
rclcpp_lifecycle::LifecyclePublisher<nav2_msgs::msg::Costmap>::SharedPtr costmap_raw_pub_;
|
||||
|
||||
// Service for getting the costmaps
|
||||
rclcpp::Service<nav2_msgs::srv::GetCostmap>::SharedPtr costmap_service_;
|
||||
|
||||
float grid_resolution;
|
||||
unsigned int grid_width, grid_height;
|
||||
std::unique_ptr<nav_msgs::msg::OccupancyGrid> grid_;
|
||||
std::unique_ptr<nav2_msgs::msg::Costmap> costmap_raw_;
|
||||
// Translate from 0-255 values in costmap to -1 to 100 values in message.
|
||||
static char * cost_translation_table_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_2D_PUBLISHER_HPP_
|
||||
@@ -0,0 +1,419 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_2D_ROS_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_2D_ROS_HPP_
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "geometry_msgs/msg/polygon.h"
|
||||
#include "geometry_msgs/msg/polygon_stamped.h"
|
||||
#include "nav2_costmap_2d/costmap_2d_publisher.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
#include "nav2_costmap_2d/clear_costmap_service.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
#include "pluginlib/class_loader.hpp"
|
||||
#include "tf2/convert.h"
|
||||
#include "tf2/LinearMath/Transform.h"
|
||||
#include "tf2_ros/buffer.h"
|
||||
#include "tf2_ros/transform_listener.h"
|
||||
#include "tf2/time.h"
|
||||
#include "tf2/transform_datatypes.h"
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wpedantic"
|
||||
#include "tf2/utils.h"
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief A ROS wrapper for a 2D Costmap. Handles subscribing to
|
||||
* topics that provide observations about obstacles in either the form
|
||||
* of PointCloud or LaserScan messages. */
|
||||
class Costmap2DROS : public nav2_util::LifecycleNode
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the wrapper
|
||||
* @param options Additional options to control creation of the node.
|
||||
*/
|
||||
Costmap2DROS(const rclcpp::NodeOptions & options = rclcpp::NodeOptions());
|
||||
|
||||
/**
|
||||
* @brief Constructor for the wrapper, the node will
|
||||
* be placed in a namespace equal to the node's name
|
||||
* @param name Name of the costmap ROS node
|
||||
*/
|
||||
explicit Costmap2DROS(const std::string & name);
|
||||
|
||||
/**
|
||||
* @brief Constructor for the wrapper
|
||||
* @param name Name of the costmap ROS node
|
||||
* @param parent_namespace Absolute namespace of the node hosting the costmap node
|
||||
* @param local_namespace Namespace to append to the parent namespace
|
||||
*/
|
||||
explicit Costmap2DROS(
|
||||
const std::string & name,
|
||||
const std::string & parent_namespace,
|
||||
const std::string & local_namespace);
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~Costmap2DROS();
|
||||
|
||||
/**
|
||||
* @brief Configure node
|
||||
*/
|
||||
nav2_util::CallbackReturn on_configure(const rclcpp_lifecycle::State & state) override;
|
||||
|
||||
/**
|
||||
* @brief Activate node
|
||||
*/
|
||||
nav2_util::CallbackReturn on_activate(const rclcpp_lifecycle::State & state) override;
|
||||
|
||||
/**
|
||||
* @brief Deactivate node
|
||||
*/
|
||||
nav2_util::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & state) override;
|
||||
|
||||
/**
|
||||
* @brief Cleanup node
|
||||
*/
|
||||
nav2_util::CallbackReturn on_cleanup(const rclcpp_lifecycle::State & state) override;
|
||||
|
||||
/**
|
||||
* @brief shutdown node
|
||||
*/
|
||||
nav2_util::CallbackReturn on_shutdown(const rclcpp_lifecycle::State & state) override;
|
||||
|
||||
/**
|
||||
* @brief as a child-LifecycleNode :
|
||||
* Costmap2DROS may be launched by another Lifecycle Node as a composed module
|
||||
* If composed, its parents will handle the shutdown, which includes this module
|
||||
*/
|
||||
void on_rcl_preshutdown() override
|
||||
{
|
||||
if (is_lifecycle_follower_) {
|
||||
// Transitioning handled by parent node
|
||||
return;
|
||||
}
|
||||
|
||||
// Else, if this is an independent node, this node needs to handle itself.
|
||||
RCLCPP_INFO(
|
||||
get_logger(), "Running Nav2 LifecycleNode rcl preshutdown (%s)",
|
||||
this->get_name());
|
||||
|
||||
runCleanups();
|
||||
|
||||
destroyBond();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Subscribes to sensor topics if necessary and starts costmap
|
||||
* updates, can be called to restart the costmap after calls to either
|
||||
* stop() or pause()
|
||||
*/
|
||||
void start();
|
||||
|
||||
/**
|
||||
* @brief Stops costmap updates and unsubscribes from sensor topics
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* @brief Stops the costmap from updating, but sensor data still comes in over the wire
|
||||
*/
|
||||
void pause();
|
||||
|
||||
/**
|
||||
* @brief Resumes costmap updates
|
||||
*/
|
||||
void resume();
|
||||
|
||||
/**
|
||||
* @brief Update the map with the layered costmap / plugins
|
||||
*/
|
||||
void updateMap();
|
||||
|
||||
/**
|
||||
* @brief Reset each individual layer
|
||||
*/
|
||||
void resetLayers();
|
||||
|
||||
/** @brief Same as getLayeredCostmap()->isCurrent(). */
|
||||
bool isCurrent()
|
||||
{
|
||||
return layered_costmap_->isCurrent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the pose of the robot in the global frame of the costmap
|
||||
* @param global_pose Will be set to the pose of the robot in the global frame of the costmap
|
||||
* @return True if the pose was set successfully, false otherwise
|
||||
*/
|
||||
bool getRobotPose(geometry_msgs::msg::PoseStamped & global_pose);
|
||||
|
||||
/**
|
||||
* @brief Transform the input_pose in the global frame of the costmap
|
||||
* @param input_pose pose to be transformed
|
||||
* @param transformed_pose pose transformed
|
||||
* @return True if the pose was transformed successfully, false otherwise
|
||||
*/
|
||||
bool transformPoseToGlobalFrame(
|
||||
const geometry_msgs::msg::PoseStamped & input_pose,
|
||||
geometry_msgs::msg::PoseStamped & transformed_pose);
|
||||
|
||||
/** @brief Returns costmap name */
|
||||
std::string getName() const
|
||||
{
|
||||
return name_;
|
||||
}
|
||||
|
||||
/** @brief Returns the delay in transform (tf) data that is tolerable in seconds */
|
||||
double getTransformTolerance() const
|
||||
{
|
||||
return transform_tolerance_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Return a pointer to the "master" costmap which receives updates from all the layers.
|
||||
*
|
||||
* Same as calling getLayeredCostmap()->getCostmap().
|
||||
*/
|
||||
Costmap2D * getCostmap()
|
||||
{
|
||||
return layered_costmap_->getCostmap();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the global frame of the costmap
|
||||
* @return The global frame of the costmap
|
||||
*/
|
||||
std::string getGlobalFrameID()
|
||||
{
|
||||
return global_frame_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the local frame of the costmap
|
||||
* @return The local frame of the costmap
|
||||
*/
|
||||
std::string getBaseFrameID()
|
||||
{
|
||||
return robot_base_frame_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the layered costmap object used in the node
|
||||
*/
|
||||
LayeredCostmap * getLayeredCostmap()
|
||||
{
|
||||
return layered_costmap_.get();
|
||||
}
|
||||
|
||||
/** @brief Returns the current padded footprint as a geometry_msgs::msg::Polygon. */
|
||||
geometry_msgs::msg::Polygon getRobotFootprintPolygon()
|
||||
{
|
||||
return nav2_costmap_2d::toPolygon(padded_footprint_);
|
||||
}
|
||||
|
||||
/** @brief Return the current footprint of the robot as a vector of points.
|
||||
*
|
||||
* This version of the footprint is padded by the footprint_padding_
|
||||
* distance, set in the rosparam "footprint_padding".
|
||||
*
|
||||
* The footprint initially comes from the rosparam "footprint" but
|
||||
* can be overwritten by dynamic reconfigure or by messages received
|
||||
* on the "footprint" topic. */
|
||||
std::vector<geometry_msgs::msg::Point> getRobotFootprint()
|
||||
{
|
||||
return padded_footprint_;
|
||||
}
|
||||
|
||||
/** @brief Return the current unpadded footprint of the robot as a vector of points.
|
||||
*
|
||||
* This is the raw version of the footprint without padding.
|
||||
*
|
||||
* The footprint initially comes from the rosparam "footprint" but
|
||||
* can be overwritten by dynamic reconfigure or by messages received
|
||||
* on the "footprint" topic. */
|
||||
std::vector<geometry_msgs::msg::Point> getUnpaddedRobotFootprint()
|
||||
{
|
||||
return unpadded_footprint_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Build the oriented footprint of the robot at the robot's current pose
|
||||
* @param oriented_footprint Will be filled with the points in the oriented footprint of the robot
|
||||
*/
|
||||
void getOrientedFootprint(std::vector<geometry_msgs::msg::Point> & oriented_footprint);
|
||||
|
||||
/** @brief Set the footprint of the robot to be the given set of
|
||||
* points, padded by footprint_padding.
|
||||
*
|
||||
* Should be a convex polygon, though this is not enforced.
|
||||
*
|
||||
* First expands the given polygon by footprint_padding_ and then
|
||||
* sets padded_footprint_ and calls
|
||||
* layered_costmap_->setFootprint(). Also saves the unpadded
|
||||
* footprint, which is available from
|
||||
* getUnpaddedRobotFootprint(). */
|
||||
void setRobotFootprint(const std::vector<geometry_msgs::msg::Point> & points);
|
||||
|
||||
/** @brief Set the footprint of the robot to be the given polygon,
|
||||
* padded by footprint_padding.
|
||||
*
|
||||
* Should be a convex polygon, though this is not enforced.
|
||||
*
|
||||
* First expands the given polygon by footprint_padding_ and then
|
||||
* sets padded_footprint_ and calls
|
||||
* layered_costmap_->setFootprint(). Also saves the unpadded
|
||||
* footprint, which is available from
|
||||
* getUnpaddedRobotFootprint(). */
|
||||
void setRobotFootprintPolygon(const geometry_msgs::msg::Polygon::SharedPtr footprint);
|
||||
|
||||
std::shared_ptr<tf2_ros::Buffer> getTfBuffer() {return tf_buffer_;}
|
||||
|
||||
/**
|
||||
* @brief Get the costmap's use_radius_ parameter, corresponding to
|
||||
* whether the footprint for the robot is a circle with radius robot_radius_
|
||||
* or an arbitrarily defined footprint in footprint_.
|
||||
* @return use_radius_
|
||||
*/
|
||||
bool getUseRadius() {return use_radius_;}
|
||||
|
||||
/**
|
||||
* @brief Get the costmap's robot_radius_ parameter, corresponding to
|
||||
* raidus of the robot footprint when it is defined as as circle
|
||||
* (i.e. when use_radius_ == true).
|
||||
* @return robot_radius_
|
||||
*/
|
||||
double getRobotRadius() {return robot_radius_;}
|
||||
|
||||
protected:
|
||||
// Publishers and subscribers
|
||||
rclcpp_lifecycle::LifecyclePublisher<geometry_msgs::msg::PolygonStamped>::SharedPtr
|
||||
footprint_pub_;
|
||||
std::unique_ptr<Costmap2DPublisher> costmap_publisher_{nullptr};
|
||||
|
||||
rclcpp::Subscription<geometry_msgs::msg::Polygon>::SharedPtr footprint_sub_;
|
||||
rclcpp::Subscription<rcl_interfaces::msg::ParameterEvent>::SharedPtr parameter_sub_;
|
||||
|
||||
// Dedicated callback group and executor for tf timer_interface and message fillter
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group_;
|
||||
rclcpp::executors::SingleThreadedExecutor::SharedPtr executor_;
|
||||
std::unique_ptr<nav2_util::NodeThread> executor_thread_;
|
||||
|
||||
// Transform listener
|
||||
std::shared_ptr<tf2_ros::Buffer> tf_buffer_;
|
||||
std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
|
||||
|
||||
std::unique_ptr<LayeredCostmap> layered_costmap_{nullptr};
|
||||
std::string name_;
|
||||
std::string parent_namespace_;
|
||||
|
||||
/**
|
||||
* @brief Function on timer for costmap update
|
||||
*/
|
||||
void mapUpdateLoop(double frequency);
|
||||
bool map_update_thread_shutdown_{false};
|
||||
std::atomic<bool> stop_updates_{false};
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> stopped_{true};
|
||||
std::mutex _dynamic_parameter_mutex;
|
||||
std::unique_ptr<std::thread> map_update_thread_; ///< @brief A thread for updating the map
|
||||
rclcpp::Time last_publish_{0, 0, RCL_ROS_TIME};
|
||||
rclcpp::Duration publish_cycle_{1, 0};
|
||||
pluginlib::ClassLoader<Layer> plugin_loader_{"nav2_costmap_2d", "nav2_costmap_2d::Layer"};
|
||||
|
||||
/**
|
||||
* @brief Get parameters for node
|
||||
*/
|
||||
void getParameters();
|
||||
bool always_send_full_costmap_{false};
|
||||
std::string footprint_;
|
||||
float footprint_padding_{0};
|
||||
std::string global_frame_; ///< The global frame for the costmap
|
||||
int map_height_meters_{0};
|
||||
double map_publish_frequency_{0};
|
||||
double map_update_frequency_{0};
|
||||
int map_width_meters_{0};
|
||||
double origin_x_{0};
|
||||
double origin_y_{0};
|
||||
std::vector<std::string> default_plugins_;
|
||||
std::vector<std::string> default_types_;
|
||||
std::vector<std::string> plugin_names_;
|
||||
std::vector<std::string> plugin_types_;
|
||||
std::vector<std::string> filter_names_;
|
||||
std::vector<std::string> filter_types_;
|
||||
double resolution_{0};
|
||||
std::string robot_base_frame_; ///< The frame_id of the robot base
|
||||
double robot_radius_;
|
||||
bool rolling_window_{false}; ///< Whether to use a rolling window version of the costmap
|
||||
bool track_unknown_space_{false};
|
||||
double transform_tolerance_{0}; ///< The timeout before transform errors
|
||||
|
||||
bool is_lifecycle_follower_{true}; ///< whether is a child-LifecycleNode or an independent node
|
||||
|
||||
// Derived parameters
|
||||
bool use_radius_{false};
|
||||
std::vector<geometry_msgs::msg::Point> unpadded_footprint_;
|
||||
std::vector<geometry_msgs::msg::Point> padded_footprint_;
|
||||
|
||||
std::unique_ptr<ClearCostmapService> clear_costmap_service_;
|
||||
|
||||
// Dynamic parameters handler
|
||||
OnSetParametersCallbackHandle::SharedPtr dyn_params_handler;
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a paramter change is detected
|
||||
* @param parameters list of changed parameters
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters);
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_2D_ROS_HPP_
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_FILTERS__BINARY_FILTER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_FILTERS__BINARY_FILTER_HPP_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/costmap_filter.hpp"
|
||||
|
||||
#include "std_msgs/msg/bool.hpp"
|
||||
#include "nav2_msgs/msg/costmap_filter_info.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class BinaryFilter
|
||||
* @brief Reads in a speed restriction mask and enables a robot to
|
||||
* dynamically adjust speed based on pose in map to slow in dangerous
|
||||
* areas. Done via absolute speed setting or percentage of maximum speed
|
||||
*/
|
||||
class BinaryFilter : public CostmapFilter
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
BinaryFilter();
|
||||
|
||||
/**
|
||||
* @brief Initialize the filter and subscribe to the info topic
|
||||
*/
|
||||
void initializeFilter(
|
||||
const std::string & filter_info_topic);
|
||||
|
||||
/**
|
||||
* @brief Process the keepout layer at the current pose / bounds / grid
|
||||
*/
|
||||
void process(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j,
|
||||
const geometry_msgs::msg::Pose2D & pose);
|
||||
|
||||
/**
|
||||
* @brief Reset the costmap filter / topic / info
|
||||
*/
|
||||
void resetFilter();
|
||||
|
||||
/**
|
||||
* @brief If this filter is active
|
||||
*/
|
||||
bool isActive();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Callback for the filter information
|
||||
*/
|
||||
void filterInfoCallback(const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg);
|
||||
/**
|
||||
* @brief Callback for the filter mask
|
||||
*/
|
||||
void maskCallback(const nav_msgs::msg::OccupancyGrid::SharedPtr msg);
|
||||
/**
|
||||
* @brief Changes binary state of filter. Sends a message with new state.
|
||||
* @param state New binary state
|
||||
*/
|
||||
void changeState(const bool state);
|
||||
|
||||
// Working with filter info and mask
|
||||
rclcpp::Subscription<nav2_msgs::msg::CostmapFilterInfo>::SharedPtr filter_info_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::OccupancyGrid>::SharedPtr mask_sub_;
|
||||
|
||||
rclcpp_lifecycle::LifecyclePublisher<std_msgs::msg::Bool>::SharedPtr binary_state_pub_;
|
||||
|
||||
nav_msgs::msg::OccupancyGrid::SharedPtr filter_mask_;
|
||||
|
||||
std::string mask_frame_; // Frame where mask located in
|
||||
std::string global_frame_; // Frame of currnet layer (master_grid)
|
||||
|
||||
double base_, multiplier_;
|
||||
// Filter values higher than this threshold,
|
||||
// will set binary state to non-default
|
||||
double flip_threshold_;
|
||||
|
||||
bool default_state_; // Default Binary Filter state
|
||||
bool binary_state_; // Current Binary Filter state
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_FILTERS__BINARY_FILTER_HPP_
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
* Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_FILTERS__COSTMAP_FILTER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_FILTERS__COSTMAP_FILTER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
|
||||
#include "geometry_msgs/msg/pose2_d.hpp"
|
||||
#include "std_srvs/srv/set_bool.hpp"
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief: CostmapFilter basic class. It is inherited from Layer in order to avoid
|
||||
* hidden problems when the shared handling of costmap_ resource (PR #1936)
|
||||
*/
|
||||
class CostmapFilter : public Layer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
CostmapFilter();
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~CostmapFilter();
|
||||
|
||||
/**
|
||||
* @brief: Provide a typedef to ease future code maintenance
|
||||
*/
|
||||
typedef std::recursive_mutex mutex_t;
|
||||
/**
|
||||
* @brief: returns pointer to a mutex
|
||||
*/
|
||||
mutex_t * getMutex()
|
||||
{
|
||||
return access_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
void onInitialize() final;
|
||||
|
||||
/**
|
||||
* @brief Update the bounds of the master costmap by this layer's update dimensions
|
||||
* @param robot_x X pose of robot
|
||||
* @param robot_y Y pose of robot
|
||||
* @param robot_yaw Robot orientation
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw,
|
||||
double * min_x, double * min_y, double * max_x, double * max_y) final;
|
||||
|
||||
/**
|
||||
* @brief Update the costs in the master costmap in the window
|
||||
* @param master_grid The master costmap grid to update
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j) final;
|
||||
|
||||
/**
|
||||
* @brief Activate the layer
|
||||
*/
|
||||
void activate() final;
|
||||
/**
|
||||
* @brief Deactivate the layer
|
||||
*/
|
||||
void deactivate() final;
|
||||
/**
|
||||
* @brief Reset the layer
|
||||
*/
|
||||
void reset() final;
|
||||
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
bool isClearable() {return false;}
|
||||
|
||||
/** CostmapFilter API **/
|
||||
/**
|
||||
* @brief: Initializes costmap filter. Creates subscriptions to filter-related topics
|
||||
* @param: Name of costmap filter info topic
|
||||
*/
|
||||
virtual void initializeFilter(
|
||||
const std::string & filter_info_topic) = 0;
|
||||
|
||||
/**
|
||||
* @brief: An algorithm for how to use that map's information. Fills the Costmap2D with
|
||||
* calculated data and makes an action based on processed data
|
||||
* @param: Reference to a master costmap2d
|
||||
* @param: Low window map boundary OX
|
||||
* @param: Low window map boundary OY
|
||||
* @param: High window map boundary OX
|
||||
* @param: High window map boundary OY
|
||||
* @param: Robot 2D-pose
|
||||
*/
|
||||
virtual void process(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j,
|
||||
const geometry_msgs::msg::Pose2D & pose) = 0;
|
||||
|
||||
/**
|
||||
* @brief: Resets costmap filter. Stops all subscriptions
|
||||
*/
|
||||
virtual void resetFilter() = 0;
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Costmap filter enabling/disabling callback
|
||||
* @param request_header Service request header
|
||||
* @param request Service request
|
||||
* @param response Service response
|
||||
*/
|
||||
void enableCallback(
|
||||
const std::shared_ptr<rmw_request_id_t> request_header,
|
||||
const std::shared_ptr<std_srvs::srv::SetBool::Request> request,
|
||||
std::shared_ptr<std_srvs::srv::SetBool::Response> response);
|
||||
|
||||
/**
|
||||
* @brief: Transforms robot pose from current layer frame to mask frame
|
||||
* @param: global_frame Costmap frame to transform from
|
||||
* @param: global_pose Robot pose in costmap frame
|
||||
* @param: mask_frame Filter mask frame to transform to
|
||||
* @param: mask_pose Output robot pose in mask frame
|
||||
* @return: True if the transformation was successful, false otherwise
|
||||
*/
|
||||
bool transformPose(
|
||||
const std::string global_frame,
|
||||
const geometry_msgs::msg::Pose2D & global_pose,
|
||||
const std::string mask_frame,
|
||||
geometry_msgs::msg::Pose2D & mask_pose) const;
|
||||
|
||||
/**
|
||||
* @brief: Convert from world coordinates to mask coordinates.
|
||||
Similar to Costmap2D::worldToMap() method but works directly with OccupancyGrid-s.
|
||||
* @param filter_mask Filter mask on which to convert
|
||||
* @param wx The x world coordinate
|
||||
* @param wy The y world coordinate
|
||||
* @param mx Will be set to the associated mask x coordinate
|
||||
* @param my Will be set to the associated mask y coordinate
|
||||
* @return True if the conversion was successful (legal bounds) false otherwise
|
||||
*/
|
||||
bool worldToMask(
|
||||
nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask,
|
||||
double wx, double wy, unsigned int & mx, unsigned int & my) const;
|
||||
|
||||
/**
|
||||
* @brief Get the data of a cell in the filter mask
|
||||
* @param filter_mask Filter mask to get the data from
|
||||
* @param mx The x coordinate of the cell
|
||||
* @param my The y coordinate of the cell
|
||||
* @return The data of the selected cell
|
||||
*/
|
||||
inline int8_t getMaskData(
|
||||
nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask,
|
||||
const unsigned int mx, const unsigned int my) const
|
||||
{
|
||||
return filter_mask->data[my * filter_mask->info.width + mx];
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief: Name of costmap filter info topic
|
||||
*/
|
||||
std::string filter_info_topic_;
|
||||
|
||||
/**
|
||||
* @brief: Name of filter mask topic
|
||||
*/
|
||||
std::string mask_topic_;
|
||||
|
||||
/**
|
||||
* @brief: mask_frame_->global_frame_ transform tolerance
|
||||
*/
|
||||
tf2::Duration transform_tolerance_;
|
||||
|
||||
/**
|
||||
* @brief: A service to enable/disable costmap filter
|
||||
*/
|
||||
rclcpp::Service<std_srvs::srv::SetBool>::SharedPtr enable_service_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief: Latest robot position
|
||||
*/
|
||||
geometry_msgs::msg::Pose2D latest_pose_;
|
||||
|
||||
/**
|
||||
* @brief: Mutex for locking filter's resources
|
||||
*/
|
||||
mutex_t * access_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_FILTERS__COSTMAP_FILTER_HPP_
|
||||
@@ -0,0 +1,63 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_FILTERS__FILTER_VALUES_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_FILTERS__FILTER_VALUES_HPP_
|
||||
|
||||
/** Provides constants used in costmap filters */
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/** Types of costmap filter */
|
||||
static constexpr uint8_t KEEPOUT_FILTER = 0;
|
||||
static constexpr uint8_t SPEED_FILTER_PERCENT = 1;
|
||||
static constexpr uint8_t SPEED_FILTER_ABSOLUTE = 2;
|
||||
static constexpr uint8_t BINARY_FILTER = 3;
|
||||
|
||||
/** Default values for base and multiplier */
|
||||
static constexpr double BASE_DEFAULT = 0.0;
|
||||
static constexpr double MULTIPLIER_DEFAULT = 1.0;
|
||||
|
||||
/** Speed filter constants */
|
||||
static constexpr int8_t SPEED_MASK_UNKNOWN = -1;
|
||||
static constexpr int8_t SPEED_MASK_NO_LIMIT = 0;
|
||||
static constexpr double NO_SPEED_LIMIT = 0.0;
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_FILTERS__FILTER_VALUES_HPP_
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_FILTERS__KEEPOUT_FILTER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_FILTERS__KEEPOUT_FILTER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/costmap_filter.hpp"
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_msgs/msg/costmap_filter_info.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @class KeepoutFilter
|
||||
* @brief Reads in a keepout mask and marks keepout regions in the map
|
||||
* to prevent planning or control in restricted areas
|
||||
*/
|
||||
class KeepoutFilter : public CostmapFilter
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
KeepoutFilter();
|
||||
|
||||
/**
|
||||
* @brief Initialize the filter and subscribe to the info topic
|
||||
*/
|
||||
void initializeFilter(
|
||||
const std::string & filter_info_topic);
|
||||
|
||||
/**
|
||||
* @brief Process the keepout layer at the current pose / bounds / grid
|
||||
*/
|
||||
void process(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j,
|
||||
const geometry_msgs::msg::Pose2D & pose);
|
||||
|
||||
/**
|
||||
* @brief Reset the costmap filter / topic / info
|
||||
*/
|
||||
void resetFilter();
|
||||
|
||||
/**
|
||||
* @brief If this filter is active
|
||||
*/
|
||||
bool isActive();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Callback for the filter information
|
||||
*/
|
||||
void filterInfoCallback(const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg);
|
||||
/**
|
||||
* @brief Callback for the filter mask
|
||||
*/
|
||||
void maskCallback(const nav_msgs::msg::OccupancyGrid::SharedPtr msg);
|
||||
|
||||
rclcpp::Subscription<nav2_msgs::msg::CostmapFilterInfo>::SharedPtr filter_info_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::OccupancyGrid>::SharedPtr mask_sub_;
|
||||
|
||||
std::unique_ptr<Costmap2D> mask_costmap_;
|
||||
|
||||
std::string mask_frame_; // Frame where mask located in
|
||||
std::string global_frame_; // Frame of currnet layer (master_grid)
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_FILTERS__KEEPOUT_FILTER_HPP_
|
||||
@@ -0,0 +1,116 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_FILTERS__SPEED_FILTER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_FILTERS__SPEED_FILTER_HPP_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/costmap_filter.hpp"
|
||||
|
||||
#include "nav2_msgs/msg/costmap_filter_info.hpp"
|
||||
#include "nav2_msgs/msg/speed_limit.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class SpeedFilter
|
||||
* @brief Reads in a speed restriction mask and enables a robot to
|
||||
* dynamically adjust speed based on pose in map to slow in dangerous
|
||||
* areas. Done via absolute speed setting or percentage of maximum speed
|
||||
*/
|
||||
class SpeedFilter : public CostmapFilter
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
SpeedFilter();
|
||||
|
||||
/**
|
||||
* @brief Initialize the filter and subscribe to the info topic
|
||||
*/
|
||||
void initializeFilter(
|
||||
const std::string & filter_info_topic);
|
||||
|
||||
/**
|
||||
* @brief Process the keepout layer at the current pose / bounds / grid
|
||||
*/
|
||||
void process(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j,
|
||||
const geometry_msgs::msg::Pose2D & pose);
|
||||
|
||||
/**
|
||||
* @brief Reset the costmap filter / topic / info
|
||||
*/
|
||||
void resetFilter();
|
||||
|
||||
/**
|
||||
* @brief If this filter is active
|
||||
*/
|
||||
bool isActive();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Callback for the filter information
|
||||
*/
|
||||
void filterInfoCallback(const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg);
|
||||
/**
|
||||
* @brief Callback for the filter mask
|
||||
*/
|
||||
void maskCallback(const nav_msgs::msg::OccupancyGrid::SharedPtr msg);
|
||||
|
||||
rclcpp::Subscription<nav2_msgs::msg::CostmapFilterInfo>::SharedPtr filter_info_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::OccupancyGrid>::SharedPtr mask_sub_;
|
||||
|
||||
rclcpp_lifecycle::LifecyclePublisher<nav2_msgs::msg::SpeedLimit>::SharedPtr speed_limit_pub_;
|
||||
|
||||
nav_msgs::msg::OccupancyGrid::SharedPtr filter_mask_;
|
||||
|
||||
std::string mask_frame_; // Frame where mask located in
|
||||
std::string global_frame_; // Frame of currnet layer (master_grid)
|
||||
|
||||
double base_, multiplier_;
|
||||
bool percentage_;
|
||||
double speed_limit_, speed_limit_prev_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_FILTERS__SPEED_FILTER_HPP_
|
||||
@@ -0,0 +1,180 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_LAYER_HPP_
|
||||
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <nav2_costmap_2d/layer.hpp>
|
||||
#include <nav2_costmap_2d/layered_costmap.hpp>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @class CostmapLayer
|
||||
* @brief A costmap layer base class for costmap plugin layers.
|
||||
* Rather than just a layer, this object also contains an internal
|
||||
* costmap object to populate and maintain state.
|
||||
*/
|
||||
class CostmapLayer : public Layer, public Costmap2D
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief CostmapLayer constructor
|
||||
*/
|
||||
CostmapLayer()
|
||||
: has_extra_bounds_(false),
|
||||
extra_min_x_(1e6), extra_max_x_(-1e6),
|
||||
extra_min_y_(1e6), extra_max_y_(-1e6) {}
|
||||
|
||||
/**
|
||||
* @brief If layer is discrete
|
||||
*/
|
||||
bool isDiscretized()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Match the size of the master costmap
|
||||
*/
|
||||
virtual void matchSize();
|
||||
|
||||
/**
|
||||
* @brief Clear an are in the costmap with the given dimension
|
||||
* if invert, then clear everything except these dimensions
|
||||
*/
|
||||
virtual void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert);
|
||||
|
||||
/**
|
||||
* If an external source changes values in the costmap,
|
||||
* it should call this method with the area that it changed
|
||||
* to ensure that the costmap includes this region as well.
|
||||
* @param mx0 Minimum x value of the bounding box
|
||||
* @param my0 Minimum y value of the bounding box
|
||||
* @param mx1 Maximum x value of the bounding box
|
||||
* @param my1 Maximum y value of the bounding box
|
||||
*/
|
||||
void addExtraBounds(double mx0, double my0, double mx1, double my1);
|
||||
|
||||
protected:
|
||||
/*
|
||||
* Updates the master_grid within the specified
|
||||
* bounding box using this layer's values.
|
||||
*
|
||||
* TrueOverwrite means every value from this layer
|
||||
* is written into the master grid.
|
||||
*/
|
||||
void updateWithTrueOverwrite(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j);
|
||||
|
||||
/*
|
||||
* Updates the master_grid within the specified
|
||||
* bounding box using this layer's values.
|
||||
*
|
||||
* Overwrite means every valid value from this layer
|
||||
* is written into the master grid (does not copy NO_INFORMATION)
|
||||
*/
|
||||
void updateWithOverwrite(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j);
|
||||
|
||||
/*
|
||||
* Updates the master_grid within the specified
|
||||
* bounding box using this layer's values.
|
||||
*
|
||||
* Sets the new value to the maximum of the master_grid's value
|
||||
* and this layer's value. If the master value is NO_INFORMATION,
|
||||
* it is overwritten. If the layer's value is NO_INFORMATION,
|
||||
* the master value does not change.
|
||||
*/
|
||||
void updateWithMax(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i, int min_j, int max_i,
|
||||
int max_j);
|
||||
|
||||
/*
|
||||
* Updates the master_grid within the specified
|
||||
* bounding box using this layer's values.
|
||||
*
|
||||
* Sets the new value to the sum of the master grid's value
|
||||
* and this layer's value. If the master value is NO_INFORMATION,
|
||||
* it is overwritten with the layer's value. If the layer's value
|
||||
* is NO_INFORMATION, then the master value does not change.
|
||||
*
|
||||
* If the sum value is larger than INSCRIBED_INFLATED_OBSTACLE,
|
||||
* the master value is set to (INSCRIBED_INFLATED_OBSTACLE - 1).
|
||||
*/
|
||||
void updateWithAddition(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i, int min_j, int max_i,
|
||||
int max_j);
|
||||
|
||||
/**
|
||||
* Updates the bounding box specified in the parameters to include
|
||||
* the location (x,y)
|
||||
*
|
||||
* @param x x-coordinate to include
|
||||
* @param y y-coordinate to include
|
||||
* @param min_x bounding box
|
||||
* @param min_y bounding box
|
||||
* @param max_x bounding box
|
||||
* @param max_y bounding box
|
||||
*/
|
||||
void touch(double x, double y, double * min_x, double * min_y, double * max_x, double * max_y);
|
||||
|
||||
/*
|
||||
* Updates the bounding box specified in the parameters
|
||||
* to include the bounding box from the addExtraBounds
|
||||
* call. If addExtraBounds was not called, the method will do nothing.
|
||||
*
|
||||
* Should be called at the beginning of the updateBounds method
|
||||
*
|
||||
* @param min_x bounding box (input and output)
|
||||
* @param min_y bounding box (input and output)
|
||||
* @param max_x bounding box (input and output)
|
||||
* @param max_y bounding box (input and output)
|
||||
*/
|
||||
void useExtraBounds(double * min_x, double * min_y, double * max_x, double * max_y);
|
||||
bool has_extra_bounds_;
|
||||
|
||||
private:
|
||||
double extra_min_x_, extra_max_x_, extra_min_y_, extra_max_y_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_LAYER_HPP_
|
||||
@@ -0,0 +1,68 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_MATH_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_MATH_HPP_
|
||||
|
||||
#include <math.h>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
#include "geometry_msgs/msg/point.hpp"
|
||||
|
||||
/** @brief Return -1 if x < 0, +1 otherwise. */
|
||||
inline double sign(double x)
|
||||
{
|
||||
return x < 0.0 ? -1.0 : 1.0;
|
||||
}
|
||||
|
||||
/** @brief Same as sign(x) but returns 0 if x is 0. */
|
||||
inline double sign0(double x)
|
||||
{
|
||||
return x < 0.0 ? -1.0 : (x > 0.0 ? 1.0 : 0.0);
|
||||
}
|
||||
|
||||
/** @brief Gets L2 norm distance */
|
||||
inline double distance(double x0, double y0, double x1, double y1)
|
||||
{
|
||||
return hypot(x1 - x0, y1 - y0);
|
||||
}
|
||||
|
||||
/** @brief Gets point distance to a line */
|
||||
double distanceToLine(double pX, double pY, double x0, double y0, double x1, double y1);
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_MATH_HPP_
|
||||
@@ -0,0 +1,78 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_SUBSCRIBER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_SUBSCRIBER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_msgs/msg/costmap.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class CostmapSubscriber
|
||||
* @brief Subscribes to the costmap via a ros topic
|
||||
*/
|
||||
class CostmapSubscriber
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
CostmapSubscriber(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
const std::string & topic_name);
|
||||
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
CostmapSubscriber(
|
||||
const rclcpp::Node::WeakPtr & parent,
|
||||
const std::string & topic_name);
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~CostmapSubscriber() {}
|
||||
|
||||
/**
|
||||
* @brief A Get the costmap from topic
|
||||
*/
|
||||
std::shared_ptr<Costmap2D> getCostmap();
|
||||
|
||||
/**
|
||||
* @brief Convert an occ grid message into a costmap object
|
||||
*/
|
||||
void toCostmap2D();
|
||||
/**
|
||||
* @brief Callback for the costmap topic
|
||||
*/
|
||||
void costmapCallback(const nav2_msgs::msg::Costmap::SharedPtr msg);
|
||||
|
||||
protected:
|
||||
std::shared_ptr<Costmap2D> costmap_;
|
||||
nav2_msgs::msg::Costmap::SharedPtr costmap_msg_;
|
||||
std::string topic_name_;
|
||||
bool costmap_received_{false};
|
||||
rclcpp::Subscription<nav2_msgs::msg::Costmap>::SharedPtr costmap_sub_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_SUBSCRIBER_HPP_
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Modified by: Shivang Patel (shivaan14@gmail.com)
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__COSTMAP_TOPIC_COLLISION_CHECKER_HPP_
|
||||
#define NAV2_COSTMAP_2D__COSTMAP_TOPIC_COLLISION_CHECKER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <algorithm>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "geometry_msgs/msg/pose_stamped.hpp"
|
||||
#include "geometry_msgs/msg/pose2_d.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/footprint_collision_checker.hpp"
|
||||
#include "nav2_costmap_2d/costmap_subscriber.hpp"
|
||||
#include "nav2_costmap_2d/footprint_subscriber.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class CostmapTopicCollisionChecker
|
||||
* @brief Using a costmap via a ros topic, this object is used to
|
||||
* find if robot poses are in collision with the costmap environment
|
||||
*/
|
||||
class CostmapTopicCollisionChecker
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
CostmapTopicCollisionChecker(
|
||||
CostmapSubscriber & costmap_sub,
|
||||
FootprintSubscriber & footprint_sub,
|
||||
std::string name = "collision_checker");
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~CostmapTopicCollisionChecker() = default;
|
||||
|
||||
/**
|
||||
* @brief Returns the obstacle footprint score for a particular pose
|
||||
*
|
||||
* @param pose Pose to get score at
|
||||
* @param fetch_costmap_and_footprint Defaults to true. When checking with multiple poses at once,
|
||||
* data should be fetched in the first check but fetching can be skipped in consequent checks for speedup
|
||||
*/
|
||||
double scorePose(
|
||||
const geometry_msgs::msg::Pose2D & pose,
|
||||
bool fetch_costmap_and_footprint = true);
|
||||
|
||||
/**
|
||||
* @brief Returns if a pose is collision free
|
||||
*
|
||||
* @param pose Pose to check collision at
|
||||
* @param fetch_costmap_and_footprint Defaults to true. When checking with multiple poses at once,
|
||||
* data should be fetched in the first check but fetching can be skipped in consequent checks for speedup
|
||||
*/
|
||||
bool isCollisionFree(
|
||||
const geometry_msgs::msg::Pose2D & pose,
|
||||
bool fetch_costmap_and_footprint = true);
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Get a footprint at a set pose
|
||||
*
|
||||
* @param pose Pose to get footprint at
|
||||
* @param fetch_latest_footprint Defaults to true. When checking with multiple poses at once,
|
||||
* footprint should be fetched in the first check but fetching can be skipped in consequent checks for speedup
|
||||
*/
|
||||
Footprint getFootprint(
|
||||
const geometry_msgs::msg::Pose2D & pose,
|
||||
bool fetch_latest_footprint = true);
|
||||
|
||||
// Name used for logging
|
||||
std::string name_;
|
||||
CostmapSubscriber & costmap_sub_;
|
||||
FootprintSubscriber & footprint_sub_;
|
||||
FootprintCollisionChecker<std::shared_ptr<Costmap2D>> collision_checker_;
|
||||
rclcpp::Clock::SharedPtr clock_;
|
||||
Footprint footprint_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__COSTMAP_TOPIC_COLLISION_CHECKER_HPP_
|
||||
@@ -0,0 +1,207 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__DENOISE__IMAGE_HPP_
|
||||
#define NAV2_COSTMAP_2D__DENOISE__IMAGE_HPP_
|
||||
|
||||
#include <cstddef>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief Image with pixels of type T
|
||||
* Сan own data, be a wrapper over some memory buffer, or refer to a fragment of another image
|
||||
* Pixels of one row are stored continuity. But rows continuity is not guaranteed.
|
||||
* The distance (number of elements of type T) from row(i) to row(i + 1) is equal to step()
|
||||
* @tparam T type of pixel
|
||||
*/
|
||||
template<class T>
|
||||
class Image
|
||||
{
|
||||
public:
|
||||
/// @brief Create empty image
|
||||
Image() = default;
|
||||
|
||||
/**
|
||||
* @brief Create image referencing to a third-party buffer
|
||||
* @param rows number of image rows
|
||||
* @param columns number of image columns
|
||||
* @param data existing memory buffer with size at least rows * columns
|
||||
* @param step offset from row(i) to row(i + 1) in memory buffer (number of elements of type T).
|
||||
* offset = columns if rows are stored continuity
|
||||
*/
|
||||
Image(size_t rows, size_t columns, T * data, size_t step);
|
||||
|
||||
/**
|
||||
* @brief Create image referencing to the other
|
||||
* Share image data between new and old object.
|
||||
* Changing data in a new object will affect the given one and vice versa
|
||||
*/
|
||||
Image(const Image & other);
|
||||
|
||||
/**
|
||||
* @brief Create image from the other (move constructor)
|
||||
*/
|
||||
Image(Image && other) noexcept;
|
||||
|
||||
/// @return number of image rows
|
||||
size_t rows() const {return rows_;}
|
||||
|
||||
/// @return number of image columns
|
||||
size_t columns() const {return columns_;}
|
||||
|
||||
/// @return true if image empty
|
||||
bool empty() const {return rows_ == 0 || columns_ == 0;}
|
||||
|
||||
/// @return offset (number of elements of type T) from row(i) to row(i + 1)
|
||||
size_t step() const {return step_;}
|
||||
|
||||
/**
|
||||
* @return pointer to first pixel of row
|
||||
* @warning If row >= rows(), the behavior is undefined
|
||||
*/
|
||||
T * row(size_t row);
|
||||
|
||||
/// @overload
|
||||
const T * row(size_t row) const;
|
||||
|
||||
/**
|
||||
* @brief Read (and modify, if need) each pixel sequentially
|
||||
* @tparam Functor function object.
|
||||
* Signature should be equivalent to the following:
|
||||
* void fn(T& pixel) or void fn(const T& pixel)
|
||||
* @param fn a function that will be applied to each pixel in the image. Can modify image data
|
||||
*/
|
||||
template<class Functor>
|
||||
void forEach(Functor && fn);
|
||||
|
||||
/**
|
||||
* @brief Read each pixel sequentially
|
||||
* @tparam Functor function object.
|
||||
* Signature should be equivalent to the following:
|
||||
* void fn(const T& pixel)
|
||||
* @param fn a function that will be applied to each pixel in the image
|
||||
*/
|
||||
template<class Functor>
|
||||
void forEach(Functor && fn) const;
|
||||
/**
|
||||
* @brief Convert each pixel to corresponding pixel of target using a custom function
|
||||
*
|
||||
* The source and target must be the same size.
|
||||
* For calculation of new target value the operation can use source value and
|
||||
* an optionally current target value.
|
||||
* This function call operation(this[i, j], target[i, j]) for each pixel
|
||||
* where target[i, j] is mutable
|
||||
* @tparam TargetElement type of target pixel
|
||||
* @tparam Converter function object.
|
||||
* Signature should be equivalent to the following:
|
||||
* void fn(const T& src, TargetElement& trg)
|
||||
* @param target output image with TargetElement-type pixels
|
||||
* @param operation the binary operation op is applied to pairs of pixels:
|
||||
* first (const) from source and second (mutable) from target
|
||||
* @throw std::logic_error if the source and target of different sizes
|
||||
*/
|
||||
template<class TargetElement, class Converter>
|
||||
void convert(Image<TargetElement> & target, Converter && converter) const;
|
||||
|
||||
private:
|
||||
T * data_start_{};
|
||||
size_t rows_{};
|
||||
size_t columns_{};
|
||||
size_t step_{};
|
||||
};
|
||||
|
||||
template<class T>
|
||||
Image<T>::Image(size_t rows, size_t columns, T * data, size_t step)
|
||||
: rows_{rows}, columns_{columns}, step_{step}
|
||||
{
|
||||
data_start_ = data;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Image<T>::Image(const Image & other)
|
||||
: data_start_{other.data_start_},
|
||||
rows_{other.rows_}, columns_{other.columns_}, step_{other.step_} {}
|
||||
|
||||
template<class T>
|
||||
Image<T>::Image(Image && other) noexcept
|
||||
: data_start_{other.data_start_},
|
||||
rows_{other.rows_}, columns_{other.columns_}, step_{other.step_} {}
|
||||
|
||||
template<class T>
|
||||
T * Image<T>::row(size_t row)
|
||||
{
|
||||
return const_cast<T *>( static_cast<const Image<T> &>(*this).row(row) );
|
||||
}
|
||||
|
||||
template<class T>
|
||||
const T * Image<T>::row(size_t row) const
|
||||
{
|
||||
return data_start_ + row * step_;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
template<class Functor>
|
||||
void Image<T>::forEach(Functor && fn)
|
||||
{
|
||||
static_cast<const Image<T> &>(*this).forEach(
|
||||
[&](const T & pixel) {
|
||||
fn(const_cast<T &>(pixel));
|
||||
});
|
||||
}
|
||||
|
||||
template<class T>
|
||||
template<class Functor>
|
||||
void Image<T>::forEach(Functor && fn) const
|
||||
{
|
||||
const T * rowPtr = row(0);
|
||||
|
||||
for (size_t row = 0; row < rows(); ++row) {
|
||||
const T * rowEnd = rowPtr + columns();
|
||||
|
||||
for (const T * pixel = rowPtr; pixel != rowEnd; ++pixel) {
|
||||
fn(*pixel);
|
||||
}
|
||||
rowPtr += step();
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
template<class TargetElement, class Converter>
|
||||
void Image<T>::convert(Image<TargetElement> & target, Converter && converter) const
|
||||
{
|
||||
if (rows() != target.rows() || columns() != target.columns()) {
|
||||
throw std::logic_error("Image::convert. The source and target images size are different");
|
||||
}
|
||||
const T * source_row = row(0);
|
||||
TargetElement * target_row = target.row(0);
|
||||
|
||||
for (size_t row = 0; row < rows(); ++row) {
|
||||
const T * rowInEnd = source_row + columns();
|
||||
const T * src = source_row;
|
||||
TargetElement * trg = target_row;
|
||||
|
||||
for (; src != rowInEnd; ++src, ++trg) {
|
||||
converter(*src, *trg);
|
||||
}
|
||||
source_row += step();
|
||||
target_row += target.step();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__DENOISE__IMAGE_HPP_
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,131 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__DENOISE_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__DENOISE_LAYER_HPP_
|
||||
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
#include "nav2_costmap_2d/denoise/image_processing.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class DenoiseLayer
|
||||
* @brief Layer filters noise-induced standalone obstacles (white costmap pixels) or
|
||||
* small obstacles groups
|
||||
*/
|
||||
class DenoiseLayer : public Layer
|
||||
{
|
||||
friend class DenoiseLayerTester; // For test some private methods using gtest
|
||||
|
||||
public:
|
||||
DenoiseLayer() = default;
|
||||
~DenoiseLayer() = default;
|
||||
|
||||
/**
|
||||
* @brief Reset this layer
|
||||
*/
|
||||
void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Reports that no clearing operation is required
|
||||
*/
|
||||
bool isClearable() override;
|
||||
|
||||
/**
|
||||
* @brief Reports that no expansion is required
|
||||
* The method is called to ask the plugin: which area of costmap it needs to update.
|
||||
* A layer is essentially a filter, so it never needs to expand bounds.
|
||||
*/
|
||||
void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw,
|
||||
double * min_x, double * min_y,
|
||||
double * max_x, double * max_y) override;
|
||||
|
||||
/**
|
||||
* @brief Filters noise-induced obstacles in the selected region of the costmap
|
||||
* The method is called when costmap recalculation is required.
|
||||
* It updates the costmap within its window bounds.
|
||||
* @param master_grid The master costmap grid to update
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_x, int min_y, int max_x, int max_y) override;
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Initializes the layer on startup
|
||||
* This method is called at the end of plugin initialization.
|
||||
* Reads plugin parameters from a config file
|
||||
*/
|
||||
void onInitialize() override;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Removes from the image single obstacles (white pixels) or small obstacles groups
|
||||
*
|
||||
* Pixels less than 255 will be interpreted as background (free space), 255 - as obstacles.
|
||||
* Replaces groups of obstacles smaller than minimal_group_size_ to free space.
|
||||
* Groups connectivity type is determined by the connectivity parameter.
|
||||
*
|
||||
* If minimal_group_size_ is 1 or 0, it does nothing
|
||||
* (all standalone obstacles will be preserved, since it satisfies this condition).
|
||||
* If minimal_group_size_ equals 2, performs fast filtering based on the dilation operation.
|
||||
* Otherwise, it performs a slower segmentation-based operation.
|
||||
* @throw std::logic_error in case inner logic errors
|
||||
*/
|
||||
void denoise(Image<uint8_t> & image) const;
|
||||
|
||||
/**
|
||||
* @brief Removes from the image groups of white pixels smaller than minimal_group_size_
|
||||
* Segments the image into groups of connected pixels
|
||||
* Replace pixels in groups whose size smaller than minimal_group_size_ to zero value (background)
|
||||
* @throw std::logic_error in case inner logic errors
|
||||
* @warning If image.empty() the behavior is undefined
|
||||
*/
|
||||
void removeGroups(Image<uint8_t> & image) const;
|
||||
|
||||
/**
|
||||
* @brief Removes from the image freestanding single white pixels
|
||||
* Works similarly to removeGroups with minimal_group_size_ = 2, but about 10x faster
|
||||
* @throw std::logic_error in case inner logic errors
|
||||
* @warning If image.empty() the behavior is undefined
|
||||
*/
|
||||
void removeSinglePixels(Image<uint8_t> & image) const;
|
||||
/**
|
||||
* @brief Separates image pixels into objects and background
|
||||
* @return true if the pixel value is not an obstacle code. False in other case
|
||||
*/
|
||||
bool isBackground(uint8_t pixel) const;
|
||||
|
||||
private:
|
||||
// The border value of group size. Groups of this and larger size will be kept
|
||||
size_t minimal_group_size_{};
|
||||
// Pixels connectivity type. Determines how pixels belonging to the same group can be arranged
|
||||
ConnectivityType group_connectivity_type_{ConnectivityType::Way8};
|
||||
// Memory buffer for temporal image
|
||||
mutable MemoryBuffer buffer_;
|
||||
// Implementing the removal of grouped noise
|
||||
imgproc_impl::GroupsRemover groups_remover_;
|
||||
// Interpret NO_INFORMATION code as obstacle
|
||||
bool no_information_is_obstacle_{};
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__DENOISE_LAYER_HPP_
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2017, Locus Robotics
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the copyright holder nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef NAV2_COSTMAP_2D__EXCEPTIONS_HPP_
|
||||
#define NAV2_COSTMAP_2D__EXCEPTIONS_HPP_
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class CollisionCheckerException
|
||||
* @brief Exceptions thrown if collision checker determines a pose is in
|
||||
* collision with the environment costmap
|
||||
*/
|
||||
class CollisionCheckerException : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
explicit CollisionCheckerException(const std::string description)
|
||||
: std::runtime_error(description) {}
|
||||
};
|
||||
|
||||
/**
|
||||
* @class IllegalPoseException
|
||||
* @brief Thrown when CollisionChecker encounters a fatal error
|
||||
*/
|
||||
class IllegalPoseException : public CollisionCheckerException
|
||||
{
|
||||
public:
|
||||
IllegalPoseException(const std::string name, const std::string description)
|
||||
: CollisionCheckerException(description), name_(name) {}
|
||||
std::string getCriticName() const {return name_;}
|
||||
|
||||
protected:
|
||||
std::string name_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__EXCEPTIONS_HPP_
|
||||
@@ -0,0 +1,134 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__FOOTPRINT_HPP_
|
||||
#define NAV2_COSTMAP_2D__FOOTPRINT_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "geometry_msgs/msg/polygon.hpp"
|
||||
#include "geometry_msgs/msg/polygon_stamped.hpp"
|
||||
#include "geometry_msgs/msg/point.hpp"
|
||||
#include "geometry_msgs/msg/point32.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief Calculate the extreme distances for the footprint
|
||||
*
|
||||
* @param footprint The footprint to examine
|
||||
* @param min_dist Output parameter of the minimum distance
|
||||
* @param max_dist Output parameter of the maximum distance
|
||||
*/
|
||||
void calculateMinAndMaxDistances(
|
||||
const std::vector<geometry_msgs::msg::Point> & footprint,
|
||||
double & min_dist, double & max_dist);
|
||||
|
||||
/**
|
||||
* @brief Convert Point32 to Point
|
||||
*/
|
||||
geometry_msgs::msg::Point toPoint(geometry_msgs::msg::Point32 pt);
|
||||
|
||||
/**
|
||||
* @brief Convert Point to Point32
|
||||
*/
|
||||
geometry_msgs::msg::Point32 toPoint32(geometry_msgs::msg::Point pt);
|
||||
|
||||
/**
|
||||
* @brief Convert vector of Points to Polygon msg
|
||||
*/
|
||||
geometry_msgs::msg::Polygon toPolygon(std::vector<geometry_msgs::msg::Point> pts);
|
||||
|
||||
/**
|
||||
* @brief Convert Polygon msg to vector of Points.
|
||||
*/
|
||||
std::vector<geometry_msgs::msg::Point> toPointVector(
|
||||
geometry_msgs::msg::Polygon::SharedPtr polygon);
|
||||
|
||||
/**
|
||||
* @brief Given a pose and base footprint, build the oriented footprint of the robot (list of Points)
|
||||
* @param x The x position of the robot
|
||||
* @param y The y position of the robot
|
||||
* @param theta The orientation of the robot
|
||||
* @param footprint_spec Basic shape of the footprint
|
||||
* @param oriented_footprint Will be filled with the points in the oriented footprint of the robot
|
||||
*/
|
||||
void transformFootprint(
|
||||
double x, double y, double theta,
|
||||
const std::vector<geometry_msgs::msg::Point> & footprint_spec,
|
||||
std::vector<geometry_msgs::msg::Point> & oriented_footprint);
|
||||
|
||||
/**
|
||||
* @brief Given a pose and base footprint, build the oriented footprint of the robot (PolygonStamped)
|
||||
* @param x The x position of the robot
|
||||
* @param y The y position of the robot
|
||||
* @param theta The orientation of the robot
|
||||
* @param footprint_spec Basic shape of the footprint
|
||||
* @param oriented_footprint Will be filled with the points in the oriented footprint of the robot
|
||||
*/
|
||||
void transformFootprint(
|
||||
double x, double y, double theta,
|
||||
const std::vector<geometry_msgs::msg::Point> & footprint_spec,
|
||||
geometry_msgs::msg::PolygonStamped & oriented_footprint);
|
||||
|
||||
/**
|
||||
* @brief Adds the specified amount of padding to the footprint (in place)
|
||||
*/
|
||||
void padFootprint(std::vector<geometry_msgs::msg::Point> & footprint, double padding);
|
||||
|
||||
/**
|
||||
* @brief Create a circular footprint from a given radius
|
||||
*/
|
||||
std::vector<geometry_msgs::msg::Point> makeFootprintFromRadius(double radius);
|
||||
|
||||
/**
|
||||
* @brief Make the footprint from the given string.
|
||||
*
|
||||
* Format should be bracketed array of arrays of floats, like so: [[1.0, 2.2], [3.3, 4.2], ...]
|
||||
*
|
||||
*/
|
||||
bool makeFootprintFromString(
|
||||
const std::string & footprint_string,
|
||||
std::vector<geometry_msgs::msg::Point> & footprint);
|
||||
|
||||
} // end namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__FOOTPRINT_HPP_
|
||||
@@ -0,0 +1,89 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Modified by: Shivang Patel (shivaang14@gmail.com)
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__FOOTPRINT_COLLISION_CHECKER_HPP_
|
||||
#define NAV2_COSTMAP_2D__FOOTPRINT_COLLISION_CHECKER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <algorithm>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "geometry_msgs/msg/pose_stamped.hpp"
|
||||
#include "geometry_msgs/msg/pose2_d.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_util/robot_utils.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
typedef std::vector<geometry_msgs::msg::Point> Footprint;
|
||||
|
||||
/**
|
||||
* @class FootprintCollisionChecker
|
||||
* @brief Checker for collision with a footprint on a costmap
|
||||
*/
|
||||
template<typename CostmapT>
|
||||
class FootprintCollisionChecker
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor.
|
||||
*/
|
||||
FootprintCollisionChecker();
|
||||
/**
|
||||
* @brief A constructor.
|
||||
*/
|
||||
explicit FootprintCollisionChecker(CostmapT costmap);
|
||||
/**
|
||||
* @brief Find the footprint cost in oriented footprint
|
||||
*/
|
||||
double footprintCost(const Footprint footprint);
|
||||
/**
|
||||
* @brief Find the footprint cost a a post with an unoriented footprint
|
||||
*/
|
||||
double footprintCostAtPose(double x, double y, double theta, const Footprint footprint);
|
||||
/**
|
||||
* @brief Get the cost for a line segment
|
||||
*/
|
||||
double lineCost(int x0, int x1, int y0, int y1) const;
|
||||
/**
|
||||
* @brief Get the map coordinates from a world point
|
||||
*/
|
||||
bool worldToMap(double wx, double wy, unsigned int & mx, unsigned int & my);
|
||||
/**
|
||||
* @brief Get the cost of a point
|
||||
*/
|
||||
double pointCost(int x, int y) const;
|
||||
/**
|
||||
* @brief Set the current costmap object to use for collision detection
|
||||
*/
|
||||
void setCostmap(CostmapT costmap);
|
||||
/**
|
||||
* @brief Get the current costmap object
|
||||
*/
|
||||
CostmapT getCostmap()
|
||||
{
|
||||
return costmap_;
|
||||
}
|
||||
|
||||
protected:
|
||||
CostmapT costmap_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__FOOTPRINT_COLLISION_CHECKER_HPP_
|
||||
@@ -0,0 +1,99 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__FOOTPRINT_SUBSCRIBER_HPP_
|
||||
#define NAV2_COSTMAP_2D__FOOTPRINT_SUBSCRIBER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
#include "nav2_util/robot_utils.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class FootprintSubscriber
|
||||
* @brief Subscriber to the footprint topic to get current robot footprint
|
||||
* (if changing) for use in collision avoidance
|
||||
*/
|
||||
class FootprintSubscriber
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
FootprintSubscriber(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
const std::string & topic_name,
|
||||
tf2_ros::Buffer & tf,
|
||||
std::string robot_base_frame = "base_link",
|
||||
double transform_tolerance = 0.1);
|
||||
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
FootprintSubscriber(
|
||||
const rclcpp::Node::WeakPtr & parent,
|
||||
const std::string & topic_name,
|
||||
tf2_ros::Buffer & tf,
|
||||
std::string robot_base_frame = "base_link",
|
||||
double transform_tolerance = 0.1);
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~FootprintSubscriber() {}
|
||||
|
||||
/**
|
||||
* @brief Returns the latest robot footprint, in the form as received from topic (oriented).
|
||||
*
|
||||
* @param footprint Output param. Latest received footprint
|
||||
* @param footprint_header Output param. Header associated with the footprint
|
||||
* @return False if no footprint has been received
|
||||
*/
|
||||
bool getFootprintRaw(
|
||||
std::vector<geometry_msgs::msg::Point> & footprint,
|
||||
std_msgs::msg::Header & footprint_header);
|
||||
|
||||
/**
|
||||
* @brief Returns the latest robot footprint, transformed into robot base frame (unoriented).
|
||||
*
|
||||
* @param footprint Output param. Latest received footprint, unoriented
|
||||
* @param footprint_header Output param. Header associated with the footprint
|
||||
* @return False if no footprint has been received or if transformation failed
|
||||
*/
|
||||
bool getFootprintInRobotFrame(
|
||||
std::vector<geometry_msgs::msg::Point> & footprint,
|
||||
std_msgs::msg::Header & footprint_header);
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Callback to process new footprint updates.
|
||||
*/
|
||||
void footprint_callback(const geometry_msgs::msg::PolygonStamped::SharedPtr msg);
|
||||
|
||||
tf2_ros::Buffer & tf_;
|
||||
std::string robot_base_frame_;
|
||||
double transform_tolerance_;
|
||||
bool footprint_received_{false};
|
||||
geometry_msgs::msg::PolygonStamped::SharedPtr footprint_;
|
||||
rclcpp::Subscription<geometry_msgs::msg::PolygonStamped>::SharedPtr footprint_sub_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__FOOTPRINT_SUBSCRIBER_HPP_
|
||||
@@ -0,0 +1,272 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__INFLATION_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__INFLATION_LAYER_HPP_
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class CellData
|
||||
* @brief Storage for cell information used during obstacle inflation
|
||||
*/
|
||||
class CellData
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for a CellData objects
|
||||
* @param i The index of the cell in the cost map
|
||||
* @param x The x coordinate of the cell in the cost map
|
||||
* @param y The y coordinate of the cell in the cost map
|
||||
* @param sx The x coordinate of the closest obstacle cell in the costmap
|
||||
* @param sy The y coordinate of the closest obstacle cell in the costmap
|
||||
* @return
|
||||
*/
|
||||
CellData(double i, unsigned int x, unsigned int y, unsigned int sx, unsigned int sy)
|
||||
: index_(static_cast<unsigned int>(i)), x_(x), y_(y), src_x_(sx), src_y_(sy)
|
||||
{
|
||||
}
|
||||
unsigned int index_;
|
||||
unsigned int x_, y_;
|
||||
unsigned int src_x_, src_y_;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class InflationLayer
|
||||
* @brief Layer to convolve costmap by robot's radius or footprint to prevent
|
||||
* collisions and largely simply collision checking
|
||||
*/
|
||||
class InflationLayer : public Layer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
InflationLayer();
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
~InflationLayer();
|
||||
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
void onInitialize() override;
|
||||
|
||||
/**
|
||||
* @brief Update the bounds of the master costmap by this layer's update dimensions
|
||||
* @param robot_x X pose of robot
|
||||
* @param robot_y Y pose of robot
|
||||
* @param robot_yaw Robot orientation
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y) override;
|
||||
/**
|
||||
* @brief Update the costs in the master costmap in the window
|
||||
* @param master_grid The master costmap grid to update
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j) override;
|
||||
|
||||
/**
|
||||
* @brief Match the size of the master costmap
|
||||
*/
|
||||
void matchSize() override;
|
||||
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
virtual bool isClearable() override {return false;}
|
||||
|
||||
/**
|
||||
* @brief Reset this costmap
|
||||
*/
|
||||
void reset() override
|
||||
{
|
||||
matchSize();
|
||||
current_ = false;
|
||||
}
|
||||
|
||||
/** @brief Given a distance, compute a cost.
|
||||
* @param distance The distance from an obstacle in cells
|
||||
* @return A cost value for the distance */
|
||||
inline unsigned char computeCost(double distance) const
|
||||
{
|
||||
unsigned char cost = 0;
|
||||
if (distance == 0) {
|
||||
cost = LETHAL_OBSTACLE;
|
||||
} else if (distance * resolution_ <= inscribed_radius_) {
|
||||
cost = INSCRIBED_INFLATED_OBSTACLE;
|
||||
} else {
|
||||
// make sure cost falls off by Euclidean distance
|
||||
double factor =
|
||||
exp(-1.0 * cost_scaling_factor_ * (distance * resolution_ - inscribed_radius_));
|
||||
cost = static_cast<unsigned char>((INSCRIBED_INFLATED_OBSTACLE - 1) * factor);
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
// Provide a typedef to ease future code maintenance
|
||||
typedef std::recursive_mutex mutex_t;
|
||||
|
||||
/**
|
||||
* @brief Get the mutex of the inflation inforamtion
|
||||
*/
|
||||
mutex_t * getMutex()
|
||||
{
|
||||
return access_;
|
||||
}
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Process updates on footprint changes to the inflation layer
|
||||
*/
|
||||
void onFootprintChanged() override;
|
||||
|
||||
/**
|
||||
* @brief Lookup pre-computed distances
|
||||
* @param mx The x coordinate of the current cell
|
||||
* @param my The y coordinate of the current cell
|
||||
* @param src_x The x coordinate of the source cell
|
||||
* @param src_y The y coordinate of the source cell
|
||||
* @return
|
||||
*/
|
||||
inline double distanceLookup(
|
||||
unsigned int mx, unsigned int my, unsigned int src_x,
|
||||
unsigned int src_y)
|
||||
{
|
||||
unsigned int dx = (mx > src_x) ? mx - src_x : src_x - mx;
|
||||
unsigned int dy = (my > src_y) ? my - src_y : src_y - my;
|
||||
return cached_distances_[dx * cache_length_ + dy];
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Lookup pre-computed costs
|
||||
* @param mx The x coordinate of the current cell
|
||||
* @param my The y coordinate of the current cell
|
||||
* @param src_x The x coordinate of the source cell
|
||||
* @param src_y The y coordinate of the source cell
|
||||
* @return
|
||||
*/
|
||||
inline unsigned char costLookup(
|
||||
unsigned int mx, unsigned int my, unsigned int src_x,
|
||||
unsigned int src_y)
|
||||
{
|
||||
unsigned int dx = (mx > src_x) ? mx - src_x : src_x - mx;
|
||||
unsigned int dy = (my > src_y) ? my - src_y : src_y - my;
|
||||
return cached_costs_[dx * cache_length_ + dy];
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compute cached dsitances
|
||||
*/
|
||||
void computeCaches();
|
||||
|
||||
/**
|
||||
* @brief Compute cached dsitances
|
||||
*/
|
||||
int generateIntegerDistances();
|
||||
|
||||
/**
|
||||
* @brief Compute cached dsitances
|
||||
*/
|
||||
unsigned int cellDistance(double world_dist)
|
||||
{
|
||||
return layered_costmap_->getCostmap()->cellDistance(world_dist);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Enqueue new cells in cache distance update search
|
||||
*/
|
||||
inline void enqueue(
|
||||
unsigned int index, unsigned int mx, unsigned int my,
|
||||
unsigned int src_x, unsigned int src_y);
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters);
|
||||
|
||||
double inflation_radius_, inscribed_radius_, cost_scaling_factor_;
|
||||
bool inflate_unknown_, inflate_around_unknown_;
|
||||
unsigned int cell_inflation_radius_;
|
||||
unsigned int cached_cell_inflation_radius_;
|
||||
std::vector<std::vector<CellData>> inflation_cells_;
|
||||
|
||||
double resolution_;
|
||||
|
||||
std::vector<bool> seen_;
|
||||
|
||||
std::vector<unsigned char> cached_costs_;
|
||||
std::vector<double> cached_distances_;
|
||||
std::vector<std::vector<int>> distance_matrix_;
|
||||
unsigned int cache_length_;
|
||||
double last_min_x_, last_min_y_, last_max_x_, last_max_y_;
|
||||
|
||||
// Indicates that the entire costmap should be reinflated next time around.
|
||||
bool need_reinflation_;
|
||||
mutex_t * access_;
|
||||
// Dynamic parameters handler
|
||||
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr dyn_params_handler_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__INFLATION_LAYER_HPP_
|
||||
@@ -0,0 +1,194 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__LAYER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "tf2_ros/buffer.h"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
class LayeredCostmap;
|
||||
|
||||
/**
|
||||
* @class Layer
|
||||
* @brief Abstract class for layered costmap plugin implementations
|
||||
*/
|
||||
class Layer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
Layer();
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
virtual ~Layer() {}
|
||||
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
void initialize(
|
||||
LayeredCostmap * parent,
|
||||
std::string name,
|
||||
tf2_ros::Buffer * tf,
|
||||
const nav2_util::LifecycleNode::WeakPtr & node,
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group);
|
||||
/** @brief Stop publishers. */
|
||||
virtual void deactivate() {}
|
||||
/** @brief Restart publishers if they've been stopped. */
|
||||
virtual void activate() {}
|
||||
/**
|
||||
* @brief Reset this costmap
|
||||
*/
|
||||
virtual void reset() = 0;
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
virtual bool isClearable() = 0;
|
||||
|
||||
/**
|
||||
* @brief This is called by the LayeredCostmap to poll this plugin as to how
|
||||
* much of the costmap it needs to update. Each layer can increase
|
||||
* the size of this bounds.
|
||||
*
|
||||
* For more details, see "Layered Costmaps for Context-Sensitive Navigation",
|
||||
* by Lu et. Al, IROS 2014.
|
||||
*/
|
||||
virtual void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y) = 0;
|
||||
|
||||
/**
|
||||
* @brief Actually update the underlying costmap, only within the bounds
|
||||
* calculated during UpdateBounds().
|
||||
*/
|
||||
virtual void updateCosts(
|
||||
Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j) = 0;
|
||||
|
||||
/** @brief Implement this to make this layer match the size of the parent costmap. */
|
||||
virtual void matchSize() {}
|
||||
|
||||
/** @brief LayeredCostmap calls this whenever the footprint there
|
||||
* changes (via LayeredCostmap::setFootprint()). Override to be
|
||||
* notified of changes to the robot's footprint. */
|
||||
virtual void onFootprintChanged() {}
|
||||
/** @brief Get the name of the costmap layer */
|
||||
std::string getName() const
|
||||
{
|
||||
return name_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check to make sure all the data in the layer is up to date.
|
||||
* If the layer is not up to date, then it may be unsafe to
|
||||
* plan using the data from this layer, and the planner may
|
||||
* need to know.
|
||||
*
|
||||
* A layer's current state should be managed by the protected
|
||||
* variable current_.
|
||||
* @return Whether the data in the layer is up to date.
|
||||
*/
|
||||
bool isCurrent() const
|
||||
{
|
||||
return current_;
|
||||
}
|
||||
|
||||
/**@brief Gets whether the layer is enabled. */
|
||||
bool isEnabled() const
|
||||
{
|
||||
return enabled_;
|
||||
}
|
||||
|
||||
/** @brief Convenience function for layered_costmap_->getFootprint(). */
|
||||
const std::vector<geometry_msgs::msg::Point> & getFootprint() const;
|
||||
|
||||
/** @brief Convenience functions for declaring ROS parameters */
|
||||
void declareParameter(
|
||||
const std::string & param_name,
|
||||
const rclcpp::ParameterValue & value);
|
||||
/** @brief Convenience functions for declaring ROS parameters */
|
||||
void declareParameter(
|
||||
const std::string & param_name,
|
||||
const rclcpp::ParameterType & param_type);
|
||||
/** @brief Convenience functions for declaring ROS parameters */
|
||||
bool hasParameter(const std::string & param_name);
|
||||
/** @brief Convenience functions for declaring ROS parameters */
|
||||
std::string getFullName(const std::string & param_name);
|
||||
|
||||
protected:
|
||||
LayeredCostmap * layered_costmap_;
|
||||
std::string name_;
|
||||
tf2_ros::Buffer * tf_;
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group_;
|
||||
rclcpp_lifecycle::LifecycleNode::WeakPtr node_;
|
||||
rclcpp::Clock::SharedPtr clock_;
|
||||
rclcpp::Logger logger_{rclcpp::get_logger("nav2_costmap_2d")};
|
||||
|
||||
/** @brief This is called at the end of initialize(). Override to
|
||||
* implement subclass-specific initialization.
|
||||
*
|
||||
* tf_, name_, and layered_costmap_ will all be set already when this is called.
|
||||
*/
|
||||
virtual void onInitialize() {}
|
||||
|
||||
bool current_;
|
||||
// Currently this var is managed by subclasses.
|
||||
// TODO(bpwilcox): make this managed by this class and/or container class.
|
||||
bool enabled_;
|
||||
|
||||
// Names of the parameters declared on the ROS node
|
||||
std::unordered_set<std::string> local_params_;
|
||||
|
||||
private:
|
||||
std::vector<geometry_msgs::msg::Point> footprint_spec_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__LAYER_HPP_
|
||||
@@ -0,0 +1,237 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__LAYERED_COSTMAP_HPP_
|
||||
#define NAV2_COSTMAP_2D__LAYERED_COSTMAP_HPP_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
class Layer;
|
||||
|
||||
/**
|
||||
* @class LayeredCostmap
|
||||
* @brief Instantiates different layer plugins and aggregates them into one score
|
||||
*/
|
||||
class LayeredCostmap
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for a costmap
|
||||
*/
|
||||
LayeredCostmap(std::string global_frame, bool rolling_window, bool track_unknown);
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
~LayeredCostmap();
|
||||
|
||||
/**
|
||||
* @brief Update the underlying costmap with new data.
|
||||
* If you want to update the map outside of the update loop that runs, you can call this.
|
||||
*/
|
||||
void updateMap(double robot_x, double robot_y, double robot_yaw);
|
||||
|
||||
std::string getGlobalFrameID() const
|
||||
{
|
||||
return global_frame_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Resize the map to a new size, resolution, or origin
|
||||
*/
|
||||
void resizeMap(
|
||||
unsigned int size_x, unsigned int size_y, double resolution, double origin_x,
|
||||
double origin_y,
|
||||
bool size_locked = false);
|
||||
|
||||
/**
|
||||
* @brief Get the size of the bounds for update
|
||||
*/
|
||||
void getUpdatedBounds(double & minx, double & miny, double & maxx, double & maxy)
|
||||
{
|
||||
minx = minx_;
|
||||
miny = miny_;
|
||||
maxx = maxx_;
|
||||
maxy = maxy_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief If the costmap is current, e.g. are all the layers processing recent data
|
||||
* and not stale information for a good state.
|
||||
*/
|
||||
bool isCurrent();
|
||||
|
||||
/**
|
||||
* @brief Get the costmap pointer to the master costmap
|
||||
*/
|
||||
Costmap2D * getCostmap()
|
||||
{
|
||||
return &combined_costmap_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief If this costmap is rolling or not
|
||||
*/
|
||||
bool isRolling()
|
||||
{
|
||||
return rolling_window_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief If this costmap is tracking unknown space or not
|
||||
*/
|
||||
bool isTrackingUnknown()
|
||||
{
|
||||
return combined_costmap_.getDefaultValue() == nav2_costmap_2d::NO_INFORMATION;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the vector of pointers to the costmap plugins
|
||||
*/
|
||||
std::vector<std::shared_ptr<Layer>> * getPlugins()
|
||||
{
|
||||
return &plugins_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the vector of pointers to the costmap filters
|
||||
*/
|
||||
std::vector<std::shared_ptr<Layer>> * getFilters()
|
||||
{
|
||||
return &filters_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Add a new plugin to the plugins vector to process
|
||||
*/
|
||||
void addPlugin(std::shared_ptr<Layer> plugin);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Add a new costmap filter plugin to the filters vector to process
|
||||
*/
|
||||
void addFilter(std::shared_ptr<Layer> filter);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get if the size of the costmap is locked
|
||||
*/
|
||||
bool isSizeLocked()
|
||||
{
|
||||
return size_locked_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the bounds of the costmap
|
||||
*/
|
||||
void getBounds(unsigned int * x0, unsigned int * xn, unsigned int * y0, unsigned int * yn)
|
||||
{
|
||||
*x0 = bx0_;
|
||||
*xn = bxn_;
|
||||
*y0 = by0_;
|
||||
*yn = byn_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief if the costmap is initialized
|
||||
*/
|
||||
bool isInitialized()
|
||||
{
|
||||
return initialized_;
|
||||
}
|
||||
|
||||
/** @brief Updates the stored footprint, updates the circumscribed
|
||||
* and inscribed radii, and calls onFootprintChanged() in all
|
||||
* layers. */
|
||||
void setFootprint(const std::vector<geometry_msgs::msg::Point> & footprint_spec);
|
||||
|
||||
/** @brief Returns the latest footprint stored with setFootprint(). */
|
||||
const std::vector<geometry_msgs::msg::Point> & getFootprint() {return footprint_;}
|
||||
|
||||
/** @brief The radius of a circle centered at the origin of the
|
||||
* robot which just surrounds all points on the robot's
|
||||
* footprint.
|
||||
*
|
||||
* This is updated by setFootprint(). */
|
||||
double getCircumscribedRadius() {return circumscribed_radius_;}
|
||||
|
||||
/** @brief The radius of a circle centered at the origin of the
|
||||
* robot which is just within all points and edges of the robot's
|
||||
* footprint.
|
||||
*
|
||||
* This is updated by setFootprint(). */
|
||||
double getInscribedRadius() {return inscribed_radius_;}
|
||||
|
||||
/** @brief Checks if the robot is outside the bounds of its costmap in the case
|
||||
* of poorly configured setups. */
|
||||
bool isOutofBounds(double robot_x, double robot_y);
|
||||
|
||||
private:
|
||||
// primary_costmap_ is a bottom costmap used by plugins when costmap filters were enabled.
|
||||
// combined_costmap_ is a final costmap where all results produced by plugins and filters (if any)
|
||||
// to be merged.
|
||||
// The separation is aimed to avoid interferences of work between plugins and filters.
|
||||
// primay_costmap_ and combined_costmap_ have the same sizes, origins and default values.
|
||||
Costmap2D primary_costmap_, combined_costmap_;
|
||||
std::string global_frame_;
|
||||
|
||||
bool rolling_window_; /// < @brief Whether or not the costmap should roll with the robot
|
||||
|
||||
bool current_;
|
||||
double minx_, miny_, maxx_, maxy_;
|
||||
unsigned int bx0_, bxn_, by0_, byn_;
|
||||
|
||||
std::vector<std::shared_ptr<Layer>> plugins_;
|
||||
std::vector<std::shared_ptr<Layer>> filters_;
|
||||
|
||||
bool initialized_;
|
||||
bool size_locked_;
|
||||
double circumscribed_radius_, inscribed_radius_;
|
||||
std::vector<geometry_msgs::msg::Point> footprint_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__LAYERED_COSTMAP_HPP_
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Authors: Conor McGann
|
||||
*/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__OBSERVATION_HPP_
|
||||
#define NAV2_COSTMAP_2D__OBSERVATION_HPP_
|
||||
|
||||
#include <geometry_msgs/msg/point.hpp>
|
||||
#include <sensor_msgs/msg/point_cloud2.hpp>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief Stores an observation in terms of a point cloud and the origin of the source
|
||||
* @note Tried to make members and constructor arguments const but the compiler would not accept the default
|
||||
* assignment operator for vector insertion!
|
||||
*/
|
||||
class Observation
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Creates an empty observation
|
||||
*/
|
||||
Observation()
|
||||
: cloud_(new sensor_msgs::msg::PointCloud2()), obstacle_max_range_(0.0), obstacle_min_range_(0.0),
|
||||
raytrace_max_range_(0.0),
|
||||
raytrace_min_range_(0.0)
|
||||
{
|
||||
}
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
virtual ~Observation()
|
||||
{
|
||||
delete cloud_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy assignment operator
|
||||
* @param obs The observation to copy
|
||||
*/
|
||||
Observation & operator=(const Observation & obs)
|
||||
{
|
||||
origin_ = obs.origin_;
|
||||
cloud_ = new sensor_msgs::msg::PointCloud2(*(obs.cloud_));
|
||||
obstacle_max_range_ = obs.obstacle_max_range_;
|
||||
obstacle_min_range_ = obs.obstacle_min_range_;
|
||||
raytrace_max_range_ = obs.raytrace_max_range_;
|
||||
raytrace_min_range_ = obs.raytrace_min_range_;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Creates an observation from an origin point and a point cloud
|
||||
* @param origin The origin point of the observation
|
||||
* @param cloud The point cloud of the observation
|
||||
* @param obstacle_max_range The range out to which an observation should be able to insert obstacles
|
||||
* @param obstacle_min_range The range from which an observation should be able to insert obstacles
|
||||
* @param raytrace_max_range The range out to which an observation should be able to clear via raytracing
|
||||
* @param raytrace_min_range The range from which an observation should be able to clear via raytracing
|
||||
*/
|
||||
Observation(
|
||||
geometry_msgs::msg::Point & origin, const sensor_msgs::msg::PointCloud2 & cloud,
|
||||
double obstacle_max_range, double obstacle_min_range, double raytrace_max_range,
|
||||
double raytrace_min_range)
|
||||
: origin_(origin), cloud_(new sensor_msgs::msg::PointCloud2(cloud)),
|
||||
obstacle_max_range_(obstacle_max_range), obstacle_min_range_(obstacle_min_range),
|
||||
raytrace_max_range_(raytrace_max_range), raytrace_min_range_(
|
||||
raytrace_min_range)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor
|
||||
* @param obs The observation to copy
|
||||
*/
|
||||
Observation(const Observation & obs)
|
||||
: origin_(obs.origin_), cloud_(new sensor_msgs::msg::PointCloud2(*(obs.cloud_))),
|
||||
obstacle_max_range_(obs.obstacle_max_range_), obstacle_min_range_(obs.obstacle_min_range_),
|
||||
raytrace_max_range_(obs.raytrace_max_range_),
|
||||
raytrace_min_range_(obs.raytrace_min_range_)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Creates an observation from a point cloud
|
||||
* @param cloud The point cloud of the observation
|
||||
* @param obstacle_max_range The range out to which an observation should be able to insert obstacles
|
||||
* @param obstacle_min_range The range from which an observation should be able to insert obstacles
|
||||
*/
|
||||
Observation(
|
||||
const sensor_msgs::msg::PointCloud2 & cloud, double obstacle_max_range,
|
||||
double obstacle_min_range)
|
||||
: cloud_(new sensor_msgs::msg::PointCloud2(cloud)), obstacle_max_range_(obstacle_max_range),
|
||||
obstacle_min_range_(obstacle_min_range),
|
||||
raytrace_max_range_(0.0), raytrace_min_range_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Point origin_;
|
||||
sensor_msgs::msg::PointCloud2 * cloud_;
|
||||
double obstacle_max_range_, obstacle_min_range_, raytrace_max_range_, raytrace_min_range_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
#endif // NAV2_COSTMAP_2D__OBSERVATION_HPP_
|
||||
@@ -0,0 +1,157 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__OBSERVATION_BUFFER_HPP_
|
||||
#define NAV2_COSTMAP_2D__OBSERVATION_BUFFER_HPP_
|
||||
|
||||
#include <vector>
|
||||
#include <list>
|
||||
#include <string>
|
||||
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "rclcpp/time.hpp"
|
||||
#include "tf2_ros/buffer.h"
|
||||
#include "tf2_sensor_msgs/tf2_sensor_msgs.hpp"
|
||||
#include "sensor_msgs/msg/point_cloud2.hpp"
|
||||
#include "nav2_costmap_2d/observation.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @class ObservationBuffer
|
||||
* @brief Takes in point clouds from sensors, transforms them to the desired frame, and stores them
|
||||
*/
|
||||
class ObservationBuffer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs an observation buffer
|
||||
* @param topic_name The topic of the observations, used as an identifier for error and warning messages
|
||||
* @param observation_keep_time Defines the persistence of observations in seconds, 0 means only keep the latest
|
||||
* @param expected_update_rate How often this buffer is expected to be updated, 0 means there is no limit
|
||||
* @param min_obstacle_height The minimum height of a hitpoint to be considered legal
|
||||
* @param max_obstacle_height The minimum height of a hitpoint to be considered legal
|
||||
* @param obstacle_max_range The range to which the sensor should be trusted for inserting obstacles
|
||||
* @param obstacle_min_range The range from which the sensor should be trusted for inserting obstacles
|
||||
* @param raytrace_max_range The range to which the sensor should be trusted for raytracing to clear out space
|
||||
* @param raytrace_min_range The range from which the sensor should be trusted for raytracing to clear out space
|
||||
* @param tf2_buffer A reference to a tf2 Buffer
|
||||
* @param global_frame The frame to transform PointClouds into
|
||||
* @param sensor_frame The frame of the origin of the sensor, can be left blank to be read from the messages
|
||||
* @param tf_tolerance The amount of time to wait for a transform to be available when setting a new global frame
|
||||
*/
|
||||
ObservationBuffer(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
std::string topic_name,
|
||||
double observation_keep_time,
|
||||
double expected_update_rate,
|
||||
double min_obstacle_height, double max_obstacle_height, double obstacle_max_range,
|
||||
double obstacle_min_range,
|
||||
double raytrace_max_range, double raytrace_min_range, tf2_ros::Buffer & tf2_buffer,
|
||||
std::string global_frame,
|
||||
std::string sensor_frame,
|
||||
tf2::Duration tf_tolerance);
|
||||
|
||||
/**
|
||||
* @brief Destructor... cleans up
|
||||
*/
|
||||
~ObservationBuffer();
|
||||
|
||||
/**
|
||||
* @brief Transforms a PointCloud to the global frame and buffers it
|
||||
* <b>Note: The burden is on the user to make sure the transform is available... ie they should use a MessageNotifier</b>
|
||||
* @param cloud The cloud to be buffered
|
||||
*/
|
||||
void bufferCloud(const sensor_msgs::msg::PointCloud2 & cloud);
|
||||
|
||||
/**
|
||||
* @brief Pushes copies of all current observations onto the end of the vector passed in
|
||||
* @param observations The vector to be filled
|
||||
*/
|
||||
void getObservations(std::vector<Observation> & observations);
|
||||
|
||||
/**
|
||||
* @brief Check if the observation buffer is being update at its expected rate
|
||||
* @return True if it is being updated at the expected rate, false otherwise
|
||||
*/
|
||||
bool isCurrent() const;
|
||||
|
||||
/**
|
||||
* @brief Lock the observation buffer
|
||||
*/
|
||||
inline void lock()
|
||||
{
|
||||
lock_.lock();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Lock the observation buffer
|
||||
*/
|
||||
inline void unlock()
|
||||
{
|
||||
lock_.unlock();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Reset last updated timestamp
|
||||
*/
|
||||
void resetLastUpdated();
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Removes any stale observations from the buffer list
|
||||
*/
|
||||
void purgeStaleObservations();
|
||||
|
||||
rclcpp::Clock::SharedPtr clock_;
|
||||
rclcpp::Logger logger_{rclcpp::get_logger("nav2_costmap_2d")};
|
||||
tf2_ros::Buffer & tf2_buffer_;
|
||||
const rclcpp::Duration observation_keep_time_;
|
||||
const rclcpp::Duration expected_update_rate_;
|
||||
rclcpp::Time last_updated_;
|
||||
std::string global_frame_;
|
||||
std::string sensor_frame_;
|
||||
std::list<Observation> observation_list_;
|
||||
std::string topic_name_;
|
||||
double min_obstacle_height_, max_obstacle_height_;
|
||||
std::recursive_mutex lock_; ///< @brief A lock for accessing data in callbacks safely
|
||||
double obstacle_max_range_, obstacle_min_range_, raytrace_max_range_, raytrace_min_range_;
|
||||
tf2::Duration tf_tolerance_;
|
||||
};
|
||||
} // namespace nav2_costmap_2d
|
||||
#endif // NAV2_COSTMAP_2D__OBSERVATION_BUFFER_HPP_
|
||||
@@ -0,0 +1,260 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__OBSTACLE_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__OBSTACLE_LAYER_HPP_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "laser_geometry/laser_geometry.hpp"
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wreorder"
|
||||
#include "tf2_ros/message_filter.h"
|
||||
#pragma GCC diagnostic pop
|
||||
#include "message_filters/subscriber.h"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "sensor_msgs/msg/laser_scan.hpp"
|
||||
#include "sensor_msgs/msg/point_cloud.hpp"
|
||||
#include "sensor_msgs/msg/point_cloud2.hpp"
|
||||
#include "nav2_costmap_2d/costmap_layer.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_costmap_2d/observation_buffer.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @class ObstacleLayer
|
||||
* @brief Takes in laser and pointcloud data to populate into 2D costmap
|
||||
*/
|
||||
class ObstacleLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
ObstacleLayer()
|
||||
{
|
||||
costmap_ = NULL; // this is the unsigned char* member of parent class Costmap2D.
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief A destructor
|
||||
*/
|
||||
virtual ~ObstacleLayer();
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
virtual void onInitialize();
|
||||
/**
|
||||
* @brief Update the bounds of the master costmap by this layer's update dimensions
|
||||
* @param robot_x X pose of robot
|
||||
* @param robot_y Y pose of robot
|
||||
* @param robot_yaw Robot orientation
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
/**
|
||||
* @brief Update the costs in the master costmap in the window
|
||||
* @param master_grid The master costmap grid to update
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j);
|
||||
|
||||
/**
|
||||
* @brief Deactivate the layer
|
||||
*/
|
||||
virtual void deactivate();
|
||||
|
||||
/**
|
||||
* @brief Activate the layer
|
||||
*/
|
||||
virtual void activate();
|
||||
|
||||
/**
|
||||
* @brief Reset this costmap
|
||||
*/
|
||||
virtual void reset();
|
||||
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
virtual bool isClearable() {return true;}
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters);
|
||||
|
||||
/**
|
||||
* @brief triggers the update of observations buffer
|
||||
*/
|
||||
void resetBuffersLastUpdated();
|
||||
|
||||
/**
|
||||
* @brief A callback to handle buffering LaserScan messages
|
||||
* @param message The message returned from a message notifier
|
||||
* @param buffer A pointer to the observation buffer to update
|
||||
*/
|
||||
void laserScanCallback(
|
||||
sensor_msgs::msg::LaserScan::ConstSharedPtr message,
|
||||
const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer);
|
||||
|
||||
/**
|
||||
* @brief A callback to handle buffering LaserScan messages which need filtering to turn Inf values into range_max.
|
||||
* @param message The message returned from a message notifier
|
||||
* @param buffer A pointer to the observation buffer to update
|
||||
*/
|
||||
void laserScanValidInfCallback(
|
||||
sensor_msgs::msg::LaserScan::ConstSharedPtr message,
|
||||
const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer);
|
||||
|
||||
/**
|
||||
* @brief A callback to handle buffering PointCloud2 messages
|
||||
* @param message The message returned from a message notifier
|
||||
* @param buffer A pointer to the observation buffer to update
|
||||
*/
|
||||
void pointCloud2Callback(
|
||||
sensor_msgs::msg::PointCloud2::ConstSharedPtr message,
|
||||
const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer);
|
||||
|
||||
// for testing purposes
|
||||
void addStaticObservation(nav2_costmap_2d::Observation & obs, bool marking, bool clearing);
|
||||
void clearStaticObservations(bool marking, bool clearing);
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Get the observations used to mark space
|
||||
* @param marking_observations A reference to a vector that will be populated with the observations
|
||||
* @return True if all the observation buffers are current, false otherwise
|
||||
*/
|
||||
bool getMarkingObservations(
|
||||
std::vector<nav2_costmap_2d::Observation> & marking_observations) const;
|
||||
|
||||
/**
|
||||
* @brief Get the observations used to clear space
|
||||
* @param clearing_observations A reference to a vector that will be populated with the observations
|
||||
* @return True if all the observation buffers are current, false otherwise
|
||||
*/
|
||||
bool getClearingObservations(
|
||||
std::vector<nav2_costmap_2d::Observation> & clearing_observations) const;
|
||||
|
||||
/**
|
||||
* @brief Clear freespace based on one observation
|
||||
* @param clearing_observation The observation used to raytrace
|
||||
* @param min_x
|
||||
* @param min_y
|
||||
* @param max_x
|
||||
* @param max_y
|
||||
*/
|
||||
virtual void raytraceFreespace(
|
||||
const nav2_costmap_2d::Observation & clearing_observation,
|
||||
double * min_x, double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
|
||||
/**
|
||||
* @brief Process update costmap with raytracing the window bounds
|
||||
*/
|
||||
void updateRaytraceBounds(
|
||||
double ox, double oy, double wx, double wy, double max_range, double min_range,
|
||||
double * min_x, double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> transformed_footprint_;
|
||||
bool footprint_clearing_enabled_;
|
||||
/**
|
||||
* @brief Clear costmap layer info below the robot's footprint
|
||||
*/
|
||||
void updateFootprint(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
|
||||
std::string global_frame_; ///< @brief The global frame for the costmap
|
||||
double min_obstacle_height_; ///< @brief Max Obstacle Height
|
||||
double max_obstacle_height_; ///< @brief Max Obstacle Height
|
||||
|
||||
/// @brief Used to project laser scans into point clouds
|
||||
laser_geometry::LaserProjection projector_;
|
||||
/// @brief Used for the observation message filters
|
||||
std::vector<std::shared_ptr<message_filters::SubscriberBase<rclcpp_lifecycle::LifecycleNode>>>
|
||||
observation_subscribers_;
|
||||
/// @brief Used to make sure that transforms are available for each sensor
|
||||
std::vector<std::shared_ptr<tf2_ros::MessageFilterBase>> observation_notifiers_;
|
||||
/// @brief Used to store observations from various sensors
|
||||
std::vector<std::shared_ptr<nav2_costmap_2d::ObservationBuffer>> observation_buffers_;
|
||||
/// @brief Used to store observation buffers used for marking obstacles
|
||||
std::vector<std::shared_ptr<nav2_costmap_2d::ObservationBuffer>> marking_buffers_;
|
||||
/// @brief Used to store observation buffers used for clearing obstacles
|
||||
std::vector<std::shared_ptr<nav2_costmap_2d::ObservationBuffer>> clearing_buffers_;
|
||||
|
||||
/// @brief Dynamic parameters handler
|
||||
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr dyn_params_handler_;
|
||||
|
||||
// Used only for testing purposes
|
||||
std::vector<nav2_costmap_2d::Observation> static_clearing_observations_;
|
||||
std::vector<nav2_costmap_2d::Observation> static_marking_observations_;
|
||||
|
||||
bool rolling_window_;
|
||||
bool was_reset_;
|
||||
int combination_method_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__OBSTACLE_LAYER_HPP_
|
||||
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2018 David V. Lu!!
|
||||
* Copyright (c) 2020, Bytes Robotics
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the copyright holder nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__RANGE_SENSOR_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__RANGE_SENSOR_LAYER_HPP_
|
||||
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
#include "map_msgs/msg/occupancy_grid_update.hpp"
|
||||
#include "message_filters/subscriber.h"
|
||||
#include "nav2_costmap_2d/costmap_layer.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "sensor_msgs/msg/range.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @class RangeSensorLayer
|
||||
* @brief Takes in IR/Sonar/similar point measurement sensors and populates in costmap
|
||||
*/
|
||||
class RangeSensorLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
enum class InputSensorType
|
||||
{
|
||||
VARIABLE,
|
||||
FIXED,
|
||||
ALL
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief A constructor
|
||||
*/
|
||||
RangeSensorLayer();
|
||||
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
virtual void onInitialize();
|
||||
|
||||
/**
|
||||
* @brief Update the bounds of the master costmap by this layer's update dimensions
|
||||
* @param robot_x X pose of robot
|
||||
* @param robot_y Y pose of robot
|
||||
* @param robot_yaw Robot orientation
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw,
|
||||
double * min_x, double * min_y, double * max_x, double * max_y);
|
||||
|
||||
/**
|
||||
* @brief Update the costs in the master costmap in the window
|
||||
* @param master_grid The master costmap grid to update
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i,
|
||||
int min_j, int max_i, int max_j);
|
||||
|
||||
/**
|
||||
* @brief Reset this costmap
|
||||
*/
|
||||
virtual void reset();
|
||||
|
||||
/**
|
||||
* @brief Deactivate the layer
|
||||
*/
|
||||
virtual void deactivate();
|
||||
|
||||
/**
|
||||
* @brief Activate the layer
|
||||
*/
|
||||
virtual void activate();
|
||||
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
virtual bool isClearable() {return true;}
|
||||
|
||||
/**
|
||||
* @brief Handle an incoming Range message to populate into costmap
|
||||
*/
|
||||
void bufferIncomingRangeMsg(const sensor_msgs::msg::Range::SharedPtr range_message);
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Processes all sensors into the costmap buffered from callbacks
|
||||
*/
|
||||
void updateCostmap();
|
||||
/**
|
||||
* @brief Update the actual costmap with the values processed
|
||||
*/
|
||||
void updateCostmap(sensor_msgs::msg::Range & range_message, bool clear_sensor_cone);
|
||||
|
||||
/**
|
||||
* @brief Process general incoming range sensor data. If min=max ranges,
|
||||
* fixed processor callback is used, else uses variable callback
|
||||
*/
|
||||
void processRangeMsg(sensor_msgs::msg::Range & range_message);
|
||||
/**
|
||||
* @brief Process fixed range incoming range sensor data
|
||||
*/
|
||||
void processFixedRangeMsg(sensor_msgs::msg::Range & range_message);
|
||||
/**
|
||||
* @brief Process variable range incoming range sensor data
|
||||
*/
|
||||
void processVariableRangeMsg(sensor_msgs::msg::Range & range_message);
|
||||
|
||||
/**
|
||||
* @brief Reset the angle min/max x, and min/max y values
|
||||
*/
|
||||
void resetRange();
|
||||
|
||||
/**
|
||||
* @brief Get the gamma value for an angle, theta
|
||||
*/
|
||||
inline double gamma(double theta);
|
||||
/**
|
||||
* @brief Get the delta value for an angle, phi
|
||||
*/
|
||||
inline double delta(double phi);
|
||||
/**
|
||||
* @brief Apply the sensor model of the layer for range sensors
|
||||
*/
|
||||
inline double sensor_model(double r, double phi, double theta);
|
||||
|
||||
/**
|
||||
* @brief Get angles
|
||||
*/
|
||||
inline void get_deltas(double angle, double * dx, double * dy);
|
||||
|
||||
/**
|
||||
* @brief Update the cost in a cell with information
|
||||
*/
|
||||
inline void update_cell(
|
||||
double ox, double oy, double ot,
|
||||
double r, double nx, double ny, bool clear);
|
||||
|
||||
/**
|
||||
* @brief Find probability value of a cost
|
||||
*/
|
||||
inline double to_prob(unsigned char c)
|
||||
{
|
||||
return static_cast<double>(c) / nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Find cost value of a probability
|
||||
*/
|
||||
inline unsigned char to_cost(double p)
|
||||
{
|
||||
return static_cast<unsigned char>(p * nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
std::function<void(sensor_msgs::msg::Range & range_message)> processRangeMessageFunc_;
|
||||
std::mutex range_message_mutex_;
|
||||
std::list<sensor_msgs::msg::Range> range_msgs_buffer_;
|
||||
|
||||
double max_angle_, phi_v_;
|
||||
double inflate_cone_;
|
||||
std::string global_frame_;
|
||||
|
||||
double clear_threshold_, mark_threshold_;
|
||||
bool clear_on_max_reading_;
|
||||
bool was_reset_;
|
||||
|
||||
tf2::Duration transform_tolerance_;
|
||||
double no_readings_timeout_;
|
||||
rclcpp::Time last_reading_time_;
|
||||
unsigned int buffered_readings_;
|
||||
std::vector<rclcpp::Subscription<sensor_msgs::msg::Range>::SharedPtr> range_subs_;
|
||||
double min_x_, min_y_, max_x_, max_y_;
|
||||
|
||||
/**
|
||||
* @brief Find the area of 3 points of a triangle
|
||||
*/
|
||||
float area(int x1, int y1, int x2, int y2, int x3, int y3)
|
||||
{
|
||||
return fabs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Find the cross product of 3 vectors, A,B,C
|
||||
*/
|
||||
int orient2d(int Ax, int Ay, int Bx, int By, int Cx, int Cy)
|
||||
{
|
||||
return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax);
|
||||
}
|
||||
};
|
||||
} // namespace nav2_costmap_2d
|
||||
#endif // NAV2_COSTMAP_2D__RANGE_SENSOR_LAYER_HPP_
|
||||
@@ -0,0 +1,207 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__STATIC_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__STATIC_LAYER_HPP_
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "map_msgs/msg/occupancy_grid_update.hpp"
|
||||
#include "message_filters/subscriber.h"
|
||||
#include "nav2_costmap_2d/costmap_layer.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @class StaticLayer
|
||||
* @brief Takes in a map generated from SLAM to add costs to costmap
|
||||
*/
|
||||
class StaticLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Static Layer constructor
|
||||
*/
|
||||
StaticLayer();
|
||||
/**
|
||||
* @brief Static Layer destructor
|
||||
*/
|
||||
virtual ~StaticLayer();
|
||||
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
virtual void onInitialize();
|
||||
|
||||
/**
|
||||
* @brief Activate this layer
|
||||
*/
|
||||
virtual void activate();
|
||||
/**
|
||||
* @brief Deactivate this layer
|
||||
*/
|
||||
virtual void deactivate();
|
||||
|
||||
/**
|
||||
* @brief Reset this costmap
|
||||
*/
|
||||
virtual void reset();
|
||||
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
virtual bool isClearable() {return false;}
|
||||
|
||||
/**
|
||||
* @brief Update the bounds of the master costmap by this layer's update dimensions
|
||||
* @param robot_x X pose of robot
|
||||
* @param robot_y Y pose of robot
|
||||
* @param robot_yaw Robot orientation
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y, double * max_x, double * max_y);
|
||||
|
||||
/**
|
||||
* @brief Update the costs in the master costmap in the window
|
||||
* @param master_grid The master costmap grid to update
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j);
|
||||
|
||||
/**
|
||||
* @brief Match the size of the master costmap
|
||||
*/
|
||||
virtual void matchSize();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Get parameters of layer
|
||||
*/
|
||||
void getParameters();
|
||||
|
||||
/**
|
||||
* @brief Process a new map coming from a topic
|
||||
*/
|
||||
void processMap(const nav_msgs::msg::OccupancyGrid & new_map);
|
||||
|
||||
/**
|
||||
* @brief Callback to update the costmap's map from the map_server
|
||||
* @param new_map The map to put into the costmap. The origin of the new
|
||||
* map along with its size will determine what parts of the costmap's
|
||||
* static map are overwritten.
|
||||
*/
|
||||
void incomingMap(const nav_msgs::msg::OccupancyGrid::SharedPtr new_map);
|
||||
/**
|
||||
* @brief Callback to update the costmap's map from the map_server (or SLAM)
|
||||
* with an update in a particular area of the map
|
||||
*/
|
||||
void incomingUpdate(map_msgs::msg::OccupancyGridUpdate::ConstSharedPtr update);
|
||||
|
||||
/**
|
||||
* @brief Interpret the value in the static map given on the topic to
|
||||
* convert into costs for the costmap to utilize
|
||||
*/
|
||||
unsigned char interpretValue(unsigned char value);
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters);
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> transformed_footprint_;
|
||||
bool footprint_clearing_enabled_;
|
||||
/**
|
||||
* @brief Clear costmap layer info below the robot's footprint
|
||||
*/
|
||||
void updateFootprint(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
|
||||
std::string global_frame_; ///< @brief The global frame for the costmap
|
||||
std::string map_frame_; /// @brief frame that map is located in
|
||||
|
||||
bool has_updated_data_{false};
|
||||
|
||||
unsigned int x_{0};
|
||||
unsigned int y_{0};
|
||||
unsigned int width_{0};
|
||||
unsigned int height_{0};
|
||||
|
||||
rclcpp::Subscription<nav_msgs::msg::OccupancyGrid>::SharedPtr map_sub_;
|
||||
rclcpp::Subscription<map_msgs::msg::OccupancyGridUpdate>::SharedPtr map_update_sub_;
|
||||
|
||||
// Parameters
|
||||
std::string map_topic_;
|
||||
bool map_subscribe_transient_local_;
|
||||
bool subscribe_to_updates_;
|
||||
bool track_unknown_space_;
|
||||
bool use_maximum_;
|
||||
unsigned char lethal_threshold_;
|
||||
unsigned char unknown_cost_value_;
|
||||
bool trinary_costmap_;
|
||||
bool map_received_{false};
|
||||
bool map_received_in_update_bounds_{false};
|
||||
tf2::Duration transform_tolerance_;
|
||||
nav_msgs::msg::OccupancyGrid::SharedPtr map_buffer_;
|
||||
// Dynamic parameters handler
|
||||
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr dyn_params_handler_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__STATIC_LAYER_HPP_
|
||||
@@ -0,0 +1,238 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#ifndef NAV2_COSTMAP_2D__VOXEL_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__VOXEL_LAYER_HPP_
|
||||
|
||||
#include <vector>
|
||||
#include "message_filters/subscriber.h"
|
||||
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <nav2_costmap_2d/layer.hpp>
|
||||
#include <nav2_costmap_2d/layered_costmap.hpp>
|
||||
#include <nav2_costmap_2d/observation_buffer.hpp>
|
||||
#include <nav_msgs/msg/occupancy_grid.hpp>
|
||||
#include <nav2_msgs/msg/voxel_grid.hpp>
|
||||
#include <sensor_msgs/msg/laser_scan.hpp>
|
||||
#include <laser_geometry/laser_geometry.hpp>
|
||||
#include <sensor_msgs/msg/point_cloud.hpp>
|
||||
#include <sensor_msgs/msg/point_cloud2.hpp>
|
||||
#include <nav2_costmap_2d/obstacle_layer.hpp>
|
||||
#include <nav2_voxel_grid/voxel_grid.hpp>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @class VoxelLayer
|
||||
* @brief Takes laser and pointcloud data to populate a 3D voxel representation of the environment
|
||||
*/
|
||||
class VoxelLayer : public ObstacleLayer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Voxel Layer constructor
|
||||
*/
|
||||
VoxelLayer()
|
||||
: voxel_grid_(0, 0, 0)
|
||||
{
|
||||
costmap_ = NULL; // this is the unsigned char* member of parent class's parent class Costmap2D
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Voxel Layer destructor
|
||||
*/
|
||||
virtual ~VoxelLayer();
|
||||
|
||||
/**
|
||||
* @brief Initialization process of layer on startup
|
||||
*/
|
||||
virtual void onInitialize();
|
||||
|
||||
/**
|
||||
* @brief Update the bounds of the master costmap by this layer's update dimensions
|
||||
* @param robot_x X pose of robot
|
||||
* @param robot_y Y pose of robot
|
||||
* @param robot_yaw Robot orientation
|
||||
* @param min_x X min map coord of the window to update
|
||||
* @param min_y Y min map coord of the window to update
|
||||
* @param max_x X max map coord of the window to update
|
||||
* @param max_y Y max map coord of the window to update
|
||||
*/
|
||||
virtual void updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
|
||||
/**
|
||||
* @brief Update the layer's origin to a new pose, often when in a rolling costmap
|
||||
*/
|
||||
void updateOrigin(double new_origin_x, double new_origin_y);
|
||||
|
||||
/**
|
||||
* @brief If layer is discretely populated
|
||||
*/
|
||||
bool isDiscretized()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Match the size of the master costmap
|
||||
*/
|
||||
virtual void matchSize();
|
||||
|
||||
/**
|
||||
* @brief Reset this costmap
|
||||
*/
|
||||
virtual void reset();
|
||||
|
||||
/**
|
||||
* @brief If clearing operations should be processed on this layer or not
|
||||
*/
|
||||
virtual bool isClearable() {return true;}
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Reset internal maps
|
||||
*/
|
||||
virtual void resetMaps();
|
||||
|
||||
/**
|
||||
* @brief Use raycasting between 2 points to clear freespace
|
||||
*/
|
||||
virtual void raytraceFreespace(
|
||||
const nav2_costmap_2d::Observation & clearing_observation,
|
||||
double * min_x, double * min_y,
|
||||
double * max_x,
|
||||
double * max_y);
|
||||
|
||||
bool publish_voxel_;
|
||||
rclcpp_lifecycle::LifecyclePublisher<nav2_msgs::msg::VoxelGrid>::SharedPtr voxel_pub_;
|
||||
nav2_voxel_grid::VoxelGrid voxel_grid_;
|
||||
double z_resolution_, origin_z_;
|
||||
int unknown_threshold_, mark_threshold_, size_z_;
|
||||
rclcpp_lifecycle::LifecyclePublisher<sensor_msgs::msg::PointCloud2>::SharedPtr
|
||||
clearing_endpoints_pub_;
|
||||
|
||||
/**
|
||||
* @brief Covert world coordinates into map coordinates
|
||||
*/
|
||||
inline bool worldToMap3DFloat(
|
||||
double wx, double wy, double wz, double & mx, double & my,
|
||||
double & mz)
|
||||
{
|
||||
if (wx < origin_x_ || wy < origin_y_ || wz < origin_z_) {
|
||||
return false;
|
||||
}
|
||||
mx = ((wx - origin_x_) / resolution_);
|
||||
my = ((wy - origin_y_) / resolution_);
|
||||
mz = ((wz - origin_z_) / z_resolution_);
|
||||
if (mx < size_x_ && my < size_y_ && mz < size_z_) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Covert world coordinates into map coordinates
|
||||
*/
|
||||
inline bool worldToMap3D(
|
||||
double wx, double wy, double wz, unsigned int & mx, unsigned int & my,
|
||||
unsigned int & mz)
|
||||
{
|
||||
if (wx < origin_x_ || wy < origin_y_ || wz < origin_z_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mx = static_cast<unsigned int>((wx - origin_x_) / resolution_);
|
||||
my = static_cast<unsigned int>((wy - origin_y_) / resolution_);
|
||||
mz = static_cast<unsigned int>((wz - origin_z_) / z_resolution_);
|
||||
|
||||
if (mx < size_x_ && my < size_y_ && mz < (unsigned int)size_z_) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Covert map coordinates into world coordinates
|
||||
*/
|
||||
inline void mapToWorld3D(
|
||||
unsigned int mx, unsigned int my, unsigned int mz, double & wx,
|
||||
double & wy,
|
||||
double & wz)
|
||||
{
|
||||
// returns the center point of the cell
|
||||
wx = origin_x_ + (mx + 0.5) * resolution_;
|
||||
wy = origin_y_ + (my + 0.5) * resolution_;
|
||||
wz = origin_z_ + (mz + 0.5) * z_resolution_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Find L2 norm distance in 3D
|
||||
*/
|
||||
inline double dist(double x0, double y0, double z0, double x1, double y1, double z1)
|
||||
{
|
||||
return sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) + (z1 - z0) * (z1 - z0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the height of the voxel sizes in meters
|
||||
*/
|
||||
double getSizeInMetersZ() const
|
||||
{
|
||||
return (size_z_ - 1 + 0.5) * z_resolution_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters);
|
||||
|
||||
// Dynamic parameters handler
|
||||
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr dyn_params_handler_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__VOXEL_LAYER_HPP_
|
||||
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0"?>
|
||||
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
|
||||
<package format ="3">
|
||||
<name>nav2_costmap_2d</name>
|
||||
<version>1.1.18</version>
|
||||
<description>
|
||||
This package provides an implementation of a 2D costmap that takes in sensor
|
||||
data from the world, builds a 2D or 3D occupancy grid of the data (depending
|
||||
on whether a voxel based implementation is used), and inflates costs in a
|
||||
2D costmap based on the occupancy grid and a user specified inflation radius.
|
||||
This package also provides support for map_server based initialization of a
|
||||
costmap, rolling window based costmaps, and parameter based subscription to
|
||||
and configuration of sensor topics.
|
||||
</description>
|
||||
<maintainer email="stevenmacenski@gmail.com">Steve Macenski</maintainer>
|
||||
<license>BSD-3-Clause</license>
|
||||
<license>Apache-2.0</license>
|
||||
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<build_depend>nav2_common</build_depend>
|
||||
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>laser_geometry</depend>
|
||||
<depend>map_msgs</depend>
|
||||
<depend>message_filters</depend>
|
||||
<depend>nav2_msgs</depend>
|
||||
<depend>nav2_util</depend>
|
||||
<depend>nav2_voxel_grid</depend>
|
||||
<depend>nav_msgs</depend>
|
||||
<depend>pluginlib</depend>
|
||||
<depend>rclcpp</depend>
|
||||
<depend>rclcpp_lifecycle</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>std_msgs</depend>
|
||||
<depend>std_srvs</depend>
|
||||
<depend>tf2</depend>
|
||||
<depend>tf2_geometry_msgs</depend>
|
||||
<depend>tf2_ros</depend>
|
||||
<depend>tf2_sensor_msgs</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
<depend>angles</depend>
|
||||
|
||||
<test_depend>ament_lint_common</test_depend>
|
||||
<test_depend>ament_lint_auto</test_depend>
|
||||
<test_depend>nav2_map_server</test_depend>
|
||||
<test_depend>ament_cmake_gtest</test_depend>
|
||||
<test_depend>launch</test_depend>
|
||||
<test_depend>launch_testing</test_depend>
|
||||
<test_depend>nav2_lifecycle_manager</test_depend>
|
||||
|
||||
<export>
|
||||
<build_type>ament_cmake</build_type>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,268 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/binary_filter.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
|
||||
#include "nav2_util/occ_grid_values.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
BinaryFilter::BinaryFilter()
|
||||
: filter_info_sub_(nullptr), mask_sub_(nullptr),
|
||||
binary_state_pub_(nullptr), filter_mask_(nullptr), mask_frame_(""), global_frame_(""),
|
||||
default_state_(false), binary_state_(default_state_)
|
||||
{
|
||||
}
|
||||
|
||||
void BinaryFilter::initializeFilter(
|
||||
const std::string & filter_info_topic)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
// Declare parameters specific to BinaryFilter only
|
||||
std::string binary_state_topic;
|
||||
declareParameter("default_state", rclcpp::ParameterValue(false));
|
||||
node->get_parameter(name_ + "." + "default_state", default_state_);
|
||||
declareParameter("binary_state_topic", rclcpp::ParameterValue("binary_state"));
|
||||
node->get_parameter(name_ + "." + "binary_state_topic", binary_state_topic);
|
||||
declareParameter("flip_threshold", rclcpp::ParameterValue(50.0));
|
||||
node->get_parameter(name_ + "." + "flip_threshold", flip_threshold_);
|
||||
|
||||
filter_info_topic_ = filter_info_topic;
|
||||
// Setting new costmap filter info subscriber
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"BinaryFilter: Subscribing to \"%s\" topic for filter info...",
|
||||
filter_info_topic_.c_str());
|
||||
filter_info_sub_ = node->create_subscription<nav2_msgs::msg::CostmapFilterInfo>(
|
||||
filter_info_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&BinaryFilter::filterInfoCallback, this, std::placeholders::_1));
|
||||
|
||||
// Get global frame required for binary state publisher
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
|
||||
// Create new binary state publisher
|
||||
binary_state_pub_ = node->create_publisher<std_msgs::msg::Bool>(
|
||||
binary_state_topic, rclcpp::QoS(10));
|
||||
binary_state_pub_->on_activate();
|
||||
|
||||
// Reset parameters
|
||||
base_ = BASE_DEFAULT;
|
||||
multiplier_ = MULTIPLIER_DEFAULT;
|
||||
|
||||
// Initialize state as "false" by-default
|
||||
changeState(default_state_);
|
||||
}
|
||||
|
||||
void BinaryFilter::filterInfoCallback(
|
||||
const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
if (!mask_sub_) {
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"BinaryFilter: Received filter info from %s topic.", filter_info_topic_.c_str());
|
||||
} else {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"BinaryFilter: New costmap filter info arrived from %s topic. Updating old filter info.",
|
||||
filter_info_topic_.c_str());
|
||||
// Resetting previous subscriber each time when new costmap filter information arrives
|
||||
mask_sub_.reset();
|
||||
}
|
||||
|
||||
if (msg->type != BINARY_FILTER) {
|
||||
RCLCPP_ERROR(logger_, "BinaryFilter: Mode %i is not supported", msg->type);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set base_ and multiplier_
|
||||
base_ = msg->base;
|
||||
multiplier_ = msg->multiplier;
|
||||
// Set topic name to receive filter mask from
|
||||
mask_topic_ = msg->filter_mask_topic;
|
||||
|
||||
// Setting new filter mask subscriber
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"BinaryFilter: Subscribing to \"%s\" topic for filter mask...",
|
||||
mask_topic_.c_str());
|
||||
mask_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
|
||||
mask_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&BinaryFilter::maskCallback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void BinaryFilter::maskCallback(
|
||||
const nav_msgs::msg::OccupancyGrid::SharedPtr msg)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (!filter_mask_) {
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"BinaryFilter: Received filter mask from %s topic.", mask_topic_.c_str());
|
||||
} else {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"BinaryFilter: New filter mask arrived from %s topic. Updating old filter mask.",
|
||||
mask_topic_.c_str());
|
||||
filter_mask_.reset();
|
||||
}
|
||||
|
||||
filter_mask_ = msg;
|
||||
mask_frame_ = msg->header.frame_id;
|
||||
}
|
||||
|
||||
void BinaryFilter::process(
|
||||
nav2_costmap_2d::Costmap2D & /*master_grid*/,
|
||||
int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/,
|
||||
const geometry_msgs::msg::Pose2D & pose)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (!filter_mask_) {
|
||||
// Show warning message every 2 seconds to not litter an output
|
||||
RCLCPP_WARN_THROTTLE(
|
||||
logger_, *(clock_), 2000,
|
||||
"BinaryFilter: Filter mask was not received");
|
||||
return;
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Pose2D mask_pose; // robot coordinates in mask frame
|
||||
|
||||
// Transforming robot pose from current layer frame to mask frame
|
||||
if (!transformPose(global_frame_, pose, mask_frame_, mask_pose)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Converting mask_pose robot position to filter_mask_ indexes (mask_robot_i, mask_robot_j)
|
||||
unsigned int mask_robot_i, mask_robot_j;
|
||||
if (!worldToMask(filter_mask_, mask_pose.x, mask_pose.y, mask_robot_i, mask_robot_j)) {
|
||||
// Robot went out of mask range. Set "false" state by-default
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"BinaryFilter: Robot is outside of filter mask. Resetting binary state to default.");
|
||||
changeState(default_state_);
|
||||
return;
|
||||
}
|
||||
|
||||
// Getting filter_mask data from cell where the robot placed
|
||||
int8_t mask_data = getMaskData(filter_mask_, mask_robot_i, mask_robot_j);
|
||||
if (mask_data == nav2_util::OCC_GRID_UNKNOWN) {
|
||||
// Corresponding filter mask cell is unknown.
|
||||
// Warn and do nothing.
|
||||
RCLCPP_WARN_THROTTLE(
|
||||
logger_, *(clock_), 2000,
|
||||
"BinaryFilter: Filter mask [%i, %i] data is unknown. Do nothing.",
|
||||
mask_robot_i, mask_robot_j);
|
||||
return;
|
||||
}
|
||||
// Check and flip binary state, if necessary
|
||||
if (base_ + mask_data * multiplier_ > flip_threshold_) {
|
||||
if (binary_state_ == default_state_) {
|
||||
changeState(!default_state_);
|
||||
}
|
||||
} else {
|
||||
if (binary_state_ != default_state_) {
|
||||
changeState(default_state_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BinaryFilter::resetFilter()
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
RCLCPP_INFO(logger_, "BinaryFilter: Resetting the filter to default state");
|
||||
changeState(default_state_);
|
||||
|
||||
filter_info_sub_.reset();
|
||||
mask_sub_.reset();
|
||||
if (binary_state_pub_) {
|
||||
binary_state_pub_->on_deactivate();
|
||||
binary_state_pub_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
bool BinaryFilter::isActive()
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (filter_mask_) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void BinaryFilter::changeState(const bool state)
|
||||
{
|
||||
binary_state_ = state;
|
||||
if (state) {
|
||||
RCLCPP_INFO(logger_, "BinaryFilter: Switched on");
|
||||
} else {
|
||||
RCLCPP_INFO(logger_, "BinaryFilter: Switched off");
|
||||
}
|
||||
|
||||
// Forming and publishing new BinaryState message
|
||||
std::unique_ptr<std_msgs::msg::Bool> msg =
|
||||
std::make_unique<std_msgs::msg::Bool>();
|
||||
msg->data = state;
|
||||
binary_state_pub_->publish(std::move(msg));
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::BinaryFilter, nav2_costmap_2d::Layer)
|
||||
@@ -0,0 +1,212 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
* Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/costmap_filter.hpp"
|
||||
|
||||
#include <exception>
|
||||
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "geometry_msgs/msg/point_stamped.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
CostmapFilter::CostmapFilter()
|
||||
: filter_info_topic_(""), mask_topic_("")
|
||||
{
|
||||
access_ = new mutex_t();
|
||||
}
|
||||
|
||||
CostmapFilter::~CostmapFilter()
|
||||
{
|
||||
delete access_;
|
||||
}
|
||||
|
||||
void CostmapFilter::onInitialize()
|
||||
{
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
try {
|
||||
// Declare common for all costmap filters parameters
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("filter_info_topic", rclcpp::PARAMETER_STRING);
|
||||
declareParameter("transform_tolerance", rclcpp::ParameterValue(0.1));
|
||||
|
||||
// Get parameters
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
filter_info_topic_ = node->get_parameter(name_ + "." + "filter_info_topic").as_string();
|
||||
double transform_tolerance {};
|
||||
node->get_parameter(name_ + "." + "transform_tolerance", transform_tolerance);
|
||||
transform_tolerance_ = tf2::durationFromSec(transform_tolerance);
|
||||
|
||||
// Costmap Filter enabling service
|
||||
enable_service_ = node->create_service<std_srvs::srv::SetBool>(
|
||||
name_ + "/toggle_filter",
|
||||
std::bind(
|
||||
&CostmapFilter::enableCallback, this,
|
||||
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
|
||||
} catch (const std::exception & ex) {
|
||||
RCLCPP_ERROR(logger_, "Parameter problem: %s", ex.what());
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapFilter::activate()
|
||||
{
|
||||
initializeFilter(filter_info_topic_);
|
||||
}
|
||||
|
||||
void CostmapFilter::deactivate()
|
||||
{
|
||||
resetFilter();
|
||||
}
|
||||
|
||||
void CostmapFilter::reset()
|
||||
{
|
||||
resetFilter();
|
||||
initializeFilter(filter_info_topic_);
|
||||
current_ = false;
|
||||
}
|
||||
|
||||
void CostmapFilter::updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw,
|
||||
double * /*min_x*/, double * /*min_y*/, double * /*max_x*/, double * /*max_y*/)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
latest_pose_.x = robot_x;
|
||||
latest_pose_.y = robot_y;
|
||||
latest_pose_.theta = robot_yaw;
|
||||
}
|
||||
|
||||
void CostmapFilter::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
process(master_grid, min_i, min_j, max_i, max_j, latest_pose_);
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
void CostmapFilter::enableCallback(
|
||||
const std::shared_ptr<rmw_request_id_t>/*request_header*/,
|
||||
const std::shared_ptr<std_srvs::srv::SetBool::Request> request,
|
||||
std::shared_ptr<std_srvs::srv::SetBool::Response> response)
|
||||
{
|
||||
enabled_ = request->data;
|
||||
response->success = true;
|
||||
if (enabled_) {
|
||||
response->message = "Enabled";
|
||||
} else {
|
||||
response->message = "Disabled";
|
||||
}
|
||||
}
|
||||
|
||||
bool CostmapFilter::transformPose(
|
||||
const std::string global_frame,
|
||||
const geometry_msgs::msg::Pose2D & global_pose,
|
||||
const std::string mask_frame,
|
||||
geometry_msgs::msg::Pose2D & mask_pose) const
|
||||
{
|
||||
if (mask_frame != global_frame) {
|
||||
// Filter mask and current layer are in different frames:
|
||||
// Transform (global_pose.x, global_pose.y) point from current layer frame (global_frame)
|
||||
// to mask_pose point in mask_frame
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
geometry_msgs::msg::PointStamped in, out;
|
||||
in.header.stamp = clock_->now();
|
||||
in.header.frame_id = global_frame;
|
||||
in.point.x = global_pose.x;
|
||||
in.point.y = global_pose.y;
|
||||
in.point.z = 0;
|
||||
|
||||
try {
|
||||
tf_->transform(in, out, mask_frame, transform_tolerance_);
|
||||
} catch (tf2::TransformException & ex) {
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"CostmapFilter: failed to get costmap frame (%s) "
|
||||
"transformation to mask frame (%s) with error: %s",
|
||||
global_frame.c_str(), mask_frame.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
mask_pose.x = out.point.x;
|
||||
mask_pose.y = out.point.y;
|
||||
} else {
|
||||
// Filter mask and current layer are in the same frame:
|
||||
// Just use global_pose coordinates
|
||||
mask_pose = global_pose;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CostmapFilter::worldToMask(
|
||||
nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask,
|
||||
double wx, double wy, unsigned int & mx, unsigned int & my) const
|
||||
{
|
||||
const double origin_x = filter_mask->info.origin.position.x;
|
||||
const double origin_y = filter_mask->info.origin.position.y;
|
||||
const double resolution = filter_mask->info.resolution;
|
||||
const unsigned int size_x = filter_mask->info.width;
|
||||
const unsigned int size_y = filter_mask->info.height;
|
||||
|
||||
if (wx < origin_x || wy < origin_y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mx = static_cast<unsigned int>((wx - origin_x) / resolution);
|
||||
my = static_cast<unsigned int>((wy - origin_y) / resolution);
|
||||
if (mx >= size_x || my >= size_y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,315 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <algorithm>
|
||||
#include "tf2/convert.h"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/keepout_filter.hpp"
|
||||
#include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
KeepoutFilter::KeepoutFilter()
|
||||
: filter_info_sub_(nullptr), mask_sub_(nullptr), mask_costmap_(nullptr),
|
||||
mask_frame_(""), global_frame_("")
|
||||
{
|
||||
}
|
||||
|
||||
void KeepoutFilter::initializeFilter(
|
||||
const std::string & filter_info_topic)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
filter_info_topic_ = filter_info_topic;
|
||||
// Setting new costmap filter info subscriber
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"KeepoutFilter: Subscribing to \"%s\" topic for filter info...",
|
||||
filter_info_topic_.c_str());
|
||||
filter_info_sub_ = node->create_subscription<nav2_msgs::msg::CostmapFilterInfo>(
|
||||
filter_info_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&KeepoutFilter::filterInfoCallback, this, std::placeholders::_1));
|
||||
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
}
|
||||
|
||||
void KeepoutFilter::filterInfoCallback(
|
||||
const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
if (!mask_sub_) {
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"KeepoutFilter: Received filter info from %s topic.", filter_info_topic_.c_str());
|
||||
} else {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"KeepoutFilter: New costmap filter info arrived from %s topic. Updating old filter info.",
|
||||
filter_info_topic_.c_str());
|
||||
// Resetting previous subscriber each time when new costmap filter information arrives
|
||||
mask_sub_.reset();
|
||||
}
|
||||
|
||||
// Checking that base and multiplier are set to their default values
|
||||
if (msg->base != BASE_DEFAULT || msg->multiplier != MULTIPLIER_DEFAULT) {
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"KeepoutFilter: For proper use of keepout filter base and multiplier"
|
||||
" in CostmapFilterInfo message should be set to their default values (%f and %f)",
|
||||
BASE_DEFAULT, MULTIPLIER_DEFAULT);
|
||||
}
|
||||
|
||||
mask_topic_ = msg->filter_mask_topic;
|
||||
|
||||
// Setting new filter mask subscriber
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"KeepoutFilter: Subscribing to \"%s\" topic for filter mask...",
|
||||
mask_topic_.c_str());
|
||||
mask_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
|
||||
mask_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&KeepoutFilter::maskCallback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void KeepoutFilter::maskCallback(
|
||||
const nav_msgs::msg::OccupancyGrid::SharedPtr msg)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
if (!mask_costmap_) {
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"KeepoutFilter: Received filter mask from %s topic.", mask_topic_.c_str());
|
||||
} else {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"KeepoutFilter: New filter mask arrived from %s topic. Updating old filter mask.",
|
||||
mask_topic_.c_str());
|
||||
mask_costmap_.reset();
|
||||
}
|
||||
|
||||
// Making a new mask_costmap_
|
||||
mask_costmap_ = std::make_unique<Costmap2D>(*msg);
|
||||
mask_frame_ = msg->header.frame_id;
|
||||
}
|
||||
|
||||
void KeepoutFilter::process(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j,
|
||||
const geometry_msgs::msg::Pose2D & /*pose*/)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (!mask_costmap_) {
|
||||
// Show warning message every 2 seconds to not litter an output
|
||||
RCLCPP_WARN_THROTTLE(
|
||||
logger_, *(clock_), 2000,
|
||||
"KeepoutFilter: Filter mask was not received");
|
||||
return;
|
||||
}
|
||||
|
||||
tf2::Transform tf2_transform;
|
||||
tf2_transform.setIdentity(); // initialize by identical transform
|
||||
int mg_min_x, mg_min_y; // masger_grid indexes of bottom-left window corner
|
||||
int mg_max_x, mg_max_y; // masger_grid indexes of top-right window corner
|
||||
|
||||
if (mask_frame_ != global_frame_) {
|
||||
// Filter mask and current layer are in different frames:
|
||||
// prepare frame transformation if mask_frame_ != global_frame_
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
try {
|
||||
transform = tf_->lookupTransform(
|
||||
mask_frame_, global_frame_, tf2::TimePointZero,
|
||||
transform_tolerance_);
|
||||
} catch (tf2::TransformException & ex) {
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"KeepoutFilter: Failed to get costmap frame (%s) "
|
||||
"transformation to mask frame (%s) with error: %s",
|
||||
global_frame_.c_str(), mask_frame_.c_str(), ex.what());
|
||||
return;
|
||||
}
|
||||
tf2::fromMsg(transform.transform, tf2_transform);
|
||||
|
||||
mg_min_x = min_i;
|
||||
mg_min_y = min_j;
|
||||
mg_max_x = max_i;
|
||||
mg_max_y = max_j;
|
||||
} else {
|
||||
// Filter mask and current layer are in the same frame:
|
||||
// apply the following optimization - iterate only in overlapped
|
||||
// (min_i, min_j)..(max_i, max_j) & mask_costmap_ area.
|
||||
//
|
||||
// mask_costmap_
|
||||
// *----------------------------*
|
||||
// | |
|
||||
// | |
|
||||
// | (2) |
|
||||
// *-----+-------* |
|
||||
// | |///////|<- overlapped area |
|
||||
// | |///////| to iterate in |
|
||||
// | *-------+--------------------*
|
||||
// | (1) |
|
||||
// | |
|
||||
// *-------------*
|
||||
// master_grid (min_i, min_j)..(max_i, max_j) window
|
||||
//
|
||||
// ToDo: after costmap rotation will be added, this should be re-worked.
|
||||
|
||||
double wx, wy; // world coordinates
|
||||
|
||||
// Calculating bounds corresponding to bottom-left overlapping (1) corner
|
||||
// mask_costmap_ -> master_grid intexes conversion
|
||||
const double half_cell_size = 0.5 * mask_costmap_->getResolution();
|
||||
wx = mask_costmap_->getOriginX() + half_cell_size;
|
||||
wy = mask_costmap_->getOriginY() + half_cell_size;
|
||||
master_grid.worldToMapNoBounds(wx, wy, mg_min_x, mg_min_y);
|
||||
// Calculation of (1) corner bounds
|
||||
if (mg_min_x >= max_i || mg_min_y >= max_j) {
|
||||
// There is no overlapping. Do nothing.
|
||||
return;
|
||||
}
|
||||
mg_min_x = std::max(min_i, mg_min_x);
|
||||
mg_min_y = std::max(min_j, mg_min_y);
|
||||
|
||||
// Calculating bounds corresponding to top-right window (2) corner
|
||||
// mask_costmap_ -> master_grid intexes conversion
|
||||
wx = mask_costmap_->getOriginX() +
|
||||
mask_costmap_->getSizeInCellsX() * mask_costmap_->getResolution() + half_cell_size;
|
||||
wy = mask_costmap_->getOriginY() +
|
||||
mask_costmap_->getSizeInCellsY() * mask_costmap_->getResolution() + half_cell_size;
|
||||
master_grid.worldToMapNoBounds(wx, wy, mg_max_x, mg_max_y);
|
||||
// Calculation of (2) corner bounds
|
||||
if (mg_max_x <= min_i || mg_max_y <= min_j) {
|
||||
// There is no overlapping. Do nothing.
|
||||
return;
|
||||
}
|
||||
mg_max_x = std::min(max_i, mg_max_x);
|
||||
mg_max_y = std::min(max_j, mg_max_y);
|
||||
}
|
||||
|
||||
// unsigned<-signed conversions.
|
||||
unsigned const int mg_min_x_u = static_cast<unsigned int>(mg_min_x);
|
||||
unsigned const int mg_min_y_u = static_cast<unsigned int>(mg_min_y);
|
||||
unsigned const int mg_max_x_u = static_cast<unsigned int>(mg_max_x);
|
||||
unsigned const int mg_max_y_u = static_cast<unsigned int>(mg_max_y);
|
||||
|
||||
unsigned int i, j; // master_grid iterators
|
||||
unsigned int index; // corresponding index of master_grid
|
||||
double gl_wx, gl_wy; // world coordinates in a global_frame_
|
||||
double msk_wx, msk_wy; // world coordinates in a mask_frame_
|
||||
unsigned int mx, my; // mask_costmap_ coordinates
|
||||
unsigned char data, old_data; // master_grid element data
|
||||
|
||||
// Main master_grid updating loop
|
||||
// Iterate in costmap window by master_grid indexes
|
||||
unsigned char * master_array = master_grid.getCharMap();
|
||||
for (i = mg_min_x_u; i < mg_max_x_u; i++) {
|
||||
for (j = mg_min_y_u; j < mg_max_y_u; j++) {
|
||||
index = master_grid.getIndex(i, j);
|
||||
old_data = master_array[index];
|
||||
// Calculating corresponding to (i, j) point at mask_costmap_:
|
||||
// Get world coordinates in global_frame_
|
||||
master_grid.mapToWorld(i, j, gl_wx, gl_wy);
|
||||
if (mask_frame_ != global_frame_) {
|
||||
// Transform (i, j) point from global_frame_ to mask_frame_
|
||||
tf2::Vector3 point(gl_wx, gl_wy, 0);
|
||||
point = tf2_transform * point;
|
||||
msk_wx = point.x();
|
||||
msk_wy = point.y();
|
||||
} else {
|
||||
// In this case master_grid and filter-mask are in the same frame
|
||||
msk_wx = gl_wx;
|
||||
msk_wy = gl_wy;
|
||||
}
|
||||
// Get mask coordinates corresponding to (i, j) point at mask_costmap_
|
||||
if (mask_costmap_->worldToMap(msk_wx, msk_wy, mx, my)) {
|
||||
data = mask_costmap_->getCost(mx, my);
|
||||
// Update if mask_ data is valid and greater than existing master_grid's one
|
||||
if (data == NO_INFORMATION) {
|
||||
continue;
|
||||
}
|
||||
if (data > old_data || old_data == NO_INFORMATION) {
|
||||
master_array[index] = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void KeepoutFilter::resetFilter()
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
filter_info_sub_.reset();
|
||||
mask_sub_.reset();
|
||||
}
|
||||
|
||||
bool KeepoutFilter::isActive()
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (mask_costmap_) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::KeepoutFilter, nav2_costmap_2d::Layer)
|
||||
@@ -0,0 +1,288 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2020 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the <ORGANIZATION> nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/speed_filter.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
SpeedFilter::SpeedFilter()
|
||||
: filter_info_sub_(nullptr), mask_sub_(nullptr),
|
||||
speed_limit_pub_(nullptr), filter_mask_(nullptr), mask_frame_(""), global_frame_(""),
|
||||
speed_limit_(NO_SPEED_LIMIT), speed_limit_prev_(NO_SPEED_LIMIT)
|
||||
{
|
||||
}
|
||||
|
||||
void SpeedFilter::initializeFilter(
|
||||
const std::string & filter_info_topic)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
// Declare "speed_limit_topic" parameter specific to SpeedFilter only
|
||||
std::string speed_limit_topic;
|
||||
declareParameter("speed_limit_topic", rclcpp::ParameterValue("speed_limit"));
|
||||
node->get_parameter(name_ + "." + "speed_limit_topic", speed_limit_topic);
|
||||
|
||||
filter_info_topic_ = filter_info_topic;
|
||||
// Setting new costmap filter info subscriber
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"SpeedFilter: Subscribing to \"%s\" topic for filter info...",
|
||||
filter_info_topic_.c_str());
|
||||
filter_info_sub_ = node->create_subscription<nav2_msgs::msg::CostmapFilterInfo>(
|
||||
filter_info_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&SpeedFilter::filterInfoCallback, this, std::placeholders::_1));
|
||||
|
||||
// Get global frame required for speed limit publisher
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
|
||||
// Create new speed limit publisher
|
||||
speed_limit_pub_ = node->create_publisher<nav2_msgs::msg::SpeedLimit>(
|
||||
speed_limit_topic, rclcpp::QoS(10));
|
||||
speed_limit_pub_->on_activate();
|
||||
|
||||
// Reset speed conversion states
|
||||
base_ = BASE_DEFAULT;
|
||||
multiplier_ = MULTIPLIER_DEFAULT;
|
||||
percentage_ = false;
|
||||
}
|
||||
|
||||
void SpeedFilter::filterInfoCallback(
|
||||
const nav2_msgs::msg::CostmapFilterInfo::SharedPtr msg)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
rclcpp_lifecycle::LifecycleNode::SharedPtr node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
if (!mask_sub_) {
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"SpeedFilter: Received filter info from %s topic.", filter_info_topic_.c_str());
|
||||
} else {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"SpeedFilter: New costmap filter info arrived from %s topic. Updating old filter info.",
|
||||
filter_info_topic_.c_str());
|
||||
// Resetting previous subscriber each time when new costmap filter information arrives
|
||||
mask_sub_.reset();
|
||||
}
|
||||
|
||||
// Set base_/multiplier_ or use speed limit in % of maximum speed
|
||||
base_ = msg->base;
|
||||
multiplier_ = msg->multiplier;
|
||||
if (msg->type == SPEED_FILTER_PERCENT) {
|
||||
// Using speed limit in % of maximum speed
|
||||
percentage_ = true;
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"SpeedFilter: Using expressed in a percent from maximum speed"
|
||||
"speed_limit = %f + filter_mask_data * %f",
|
||||
base_, multiplier_);
|
||||
} else if (msg->type == SPEED_FILTER_ABSOLUTE) {
|
||||
// Using speed limit in m/s
|
||||
percentage_ = false;
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"SpeedFilter: Using absolute speed_limit = %f + filter_mask_data * %f",
|
||||
base_, multiplier_);
|
||||
} else {
|
||||
RCLCPP_ERROR(logger_, "SpeedFilter: Mode is not supported");
|
||||
return;
|
||||
}
|
||||
|
||||
mask_topic_ = msg->filter_mask_topic;
|
||||
|
||||
// Setting new filter mask subscriber
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"SpeedFilter: Subscribing to \"%s\" topic for filter mask...",
|
||||
mask_topic_.c_str());
|
||||
mask_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
|
||||
mask_topic_, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&SpeedFilter::maskCallback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SpeedFilter::maskCallback(
|
||||
const nav_msgs::msg::OccupancyGrid::SharedPtr msg)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (!filter_mask_) {
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"SpeedFilter: Received filter mask from %s topic.", mask_topic_.c_str());
|
||||
} else {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"SpeedFilter: New filter mask arrived from %s topic. Updating old filter mask.",
|
||||
mask_topic_.c_str());
|
||||
filter_mask_.reset();
|
||||
}
|
||||
|
||||
filter_mask_ = msg;
|
||||
mask_frame_ = msg->header.frame_id;
|
||||
}
|
||||
|
||||
void SpeedFilter::process(
|
||||
nav2_costmap_2d::Costmap2D & /*master_grid*/,
|
||||
int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/,
|
||||
const geometry_msgs::msg::Pose2D & pose)
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (!filter_mask_) {
|
||||
// Show warning message every 2 seconds to not litter an output
|
||||
RCLCPP_WARN_THROTTLE(
|
||||
logger_, *(clock_), 2000,
|
||||
"SpeedFilter: Filter mask was not received");
|
||||
return;
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Pose2D mask_pose; // robot coordinates in mask frame
|
||||
|
||||
// Transforming robot pose from current layer frame to mask frame
|
||||
if (!transformPose(global_frame_, pose, mask_frame_, mask_pose)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Converting mask_pose robot position to filter_mask_ indexes (mask_robot_i, mask_robot_j)
|
||||
unsigned int mask_robot_i, mask_robot_j;
|
||||
if (!worldToMask(filter_mask_, mask_pose.x, mask_pose.y, mask_robot_i, mask_robot_j)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Getting filter_mask data from cell where the robot placed and
|
||||
// calculating speed limit value
|
||||
int8_t speed_mask_data = getMaskData(filter_mask_, mask_robot_i, mask_robot_j);
|
||||
if (speed_mask_data == SPEED_MASK_NO_LIMIT) {
|
||||
// Corresponding filter mask cell is free.
|
||||
// Setting no speed limit there.
|
||||
speed_limit_ = NO_SPEED_LIMIT;
|
||||
} else if (speed_mask_data == SPEED_MASK_UNKNOWN) {
|
||||
// Corresponding filter mask cell is unknown.
|
||||
// Do nothing.
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"SpeedFilter: Found unknown cell in filter_mask[%i, %i], "
|
||||
"which is invalid for this kind of filter",
|
||||
mask_robot_i, mask_robot_j);
|
||||
return;
|
||||
} else {
|
||||
// Normal case: speed_mask_data in range of [1..100]
|
||||
speed_limit_ = speed_mask_data * multiplier_ + base_;
|
||||
if (percentage_) {
|
||||
if (speed_limit_ < 0.0 || speed_limit_ > 100.0) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"SpeedFilter: Speed limit in filter_mask[%i, %i] is %f%%, "
|
||||
"out of bounds of [0, 100]. Setting it to no-limit value.",
|
||||
mask_robot_i, mask_robot_j, speed_limit_);
|
||||
speed_limit_ = NO_SPEED_LIMIT;
|
||||
}
|
||||
} else {
|
||||
if (speed_limit_ < 0.0) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"SpeedFilter: Speed limit in filter_mask[%i, %i] is less than 0 m/s, "
|
||||
"which can not be true. Setting it to no-limit value.",
|
||||
mask_robot_i, mask_robot_j);
|
||||
speed_limit_ = NO_SPEED_LIMIT;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (speed_limit_ != speed_limit_prev_) {
|
||||
if (speed_limit_ != NO_SPEED_LIMIT) {
|
||||
RCLCPP_DEBUG(logger_, "SpeedFilter: Speed limit is set to %f", speed_limit_);
|
||||
} else {
|
||||
RCLCPP_DEBUG(logger_, "SpeedFilter: Speed limit is set to its default value");
|
||||
}
|
||||
|
||||
// Forming and publishing new SpeedLimit message
|
||||
std::unique_ptr<nav2_msgs::msg::SpeedLimit> msg =
|
||||
std::make_unique<nav2_msgs::msg::SpeedLimit>();
|
||||
msg->header.frame_id = global_frame_;
|
||||
msg->header.stamp = clock_->now();
|
||||
msg->percentage = percentage_;
|
||||
msg->speed_limit = speed_limit_;
|
||||
speed_limit_pub_->publish(std::move(msg));
|
||||
|
||||
speed_limit_prev_ = speed_limit_;
|
||||
}
|
||||
}
|
||||
|
||||
void SpeedFilter::resetFilter()
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
filter_info_sub_.reset();
|
||||
mask_sub_.reset();
|
||||
if (speed_limit_pub_) {
|
||||
speed_limit_pub_->on_deactivate();
|
||||
speed_limit_pub_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
bool SpeedFilter::isActive()
|
||||
{
|
||||
std::lock_guard<CostmapFilter::mutex_t> guard(*getMutex());
|
||||
|
||||
if (filter_mask_) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::SpeedFilter, nav2_costmap_2d::Layer)
|
||||
@@ -0,0 +1,211 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "nav2_costmap_2d/denoise_layer.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
void
|
||||
DenoiseLayer::onInitialize()
|
||||
{
|
||||
// Enable/disable plugin
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
// Smaller groups should be filtered
|
||||
declareParameter("minimal_group_size", rclcpp::ParameterValue(2));
|
||||
// Pixels connectivity type
|
||||
declareParameter("group_connectivity_type", rclcpp::ParameterValue(8));
|
||||
|
||||
const auto node = node_.lock();
|
||||
|
||||
if (!node) {
|
||||
throw std::runtime_error("DenoiseLayer::onInitialize: Failed to lock node");
|
||||
}
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
|
||||
auto getInt = [&](const std::string & parameter_name) {
|
||||
int param{};
|
||||
node->get_parameter(name_ + "." + parameter_name, param);
|
||||
return param;
|
||||
};
|
||||
|
||||
const int minimal_group_size_param = getInt("minimal_group_size");
|
||||
|
||||
if (minimal_group_size_param <= 1) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"DenoiseLayer::onInitialize(): param minimal_group_size: %i."
|
||||
" A value of 1 or less means that all map cells will be left as they are.",
|
||||
minimal_group_size_param);
|
||||
minimal_group_size_ = 1;
|
||||
} else {
|
||||
minimal_group_size_ = static_cast<size_t>(minimal_group_size_param);
|
||||
}
|
||||
|
||||
const int group_connectivity_type_param = getInt("group_connectivity_type");
|
||||
|
||||
if (group_connectivity_type_param == 4) {
|
||||
group_connectivity_type_ = ConnectivityType::Way4;
|
||||
} else {
|
||||
group_connectivity_type_ = ConnectivityType::Way8;
|
||||
|
||||
if (group_connectivity_type_param != 8) {
|
||||
RCLCPP_WARN(
|
||||
logger_, "DenoiseLayer::onInitialize(): param group_connectivity_type: %i."
|
||||
" Possible values are 4 (neighbors pixels are connected horizontally and vertically) "
|
||||
"or 8 (neighbors pixels are connected horizontally, vertically and diagonally)."
|
||||
"The default value 8 will be used",
|
||||
group_connectivity_type_param);
|
||||
}
|
||||
}
|
||||
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
DenoiseLayer::reset()
|
||||
{
|
||||
current_ = false;
|
||||
}
|
||||
|
||||
bool
|
||||
DenoiseLayer::isClearable()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void
|
||||
DenoiseLayer::updateBounds(
|
||||
double /*robot_x*/, double /*robot_y*/, double /*robot_yaw*/,
|
||||
double * /*min_x*/, double * /*min_y*/,
|
||||
double * /*max_x*/, double * /*max_y*/) {}
|
||||
|
||||
void
|
||||
DenoiseLayer::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_x, int min_y, int max_x, int max_y)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (min_x >= max_x || min_y >= max_y) {
|
||||
return;
|
||||
}
|
||||
no_information_is_obstacle_ = master_grid.getDefaultValue() != NO_INFORMATION;
|
||||
|
||||
// wrap roi_image over existing costmap2d buffer
|
||||
unsigned char * master_array = master_grid.getCharMap();
|
||||
const int step = static_cast<int>(master_grid.getSizeInCellsX());
|
||||
|
||||
const size_t width = max_x - min_x;
|
||||
const size_t height = max_y - min_y;
|
||||
Image<uint8_t> roi_image(height, width, master_array + min_y * step + min_x, step);
|
||||
|
||||
try {
|
||||
denoise(roi_image);
|
||||
} catch (std::exception & ex) {
|
||||
RCLCPP_ERROR(logger_, "%s", (std::string("Inner error: ") + ex.what()).c_str());
|
||||
}
|
||||
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
DenoiseLayer::denoise(Image<uint8_t> & image) const
|
||||
{
|
||||
if (image.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (minimal_group_size_ <= 1) {
|
||||
return; // A smaller group cannot exist. No one pixel will be changed
|
||||
}
|
||||
|
||||
if (minimal_group_size_ == 2) {
|
||||
// Performs fast filtration based on erosion function
|
||||
removeSinglePixels(image);
|
||||
} else {
|
||||
// Performs a slower segmentation-based operation
|
||||
removeGroups(image);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
DenoiseLayer::removeGroups(Image<uint8_t> & image) const
|
||||
{
|
||||
groups_remover_.removeGroups(
|
||||
image, buffer_, group_connectivity_type_, minimal_group_size_,
|
||||
[this](uint8_t pixel) {return isBackground(pixel);});
|
||||
}
|
||||
|
||||
void
|
||||
DenoiseLayer::removeSinglePixels(Image<uint8_t> & image) const
|
||||
{
|
||||
// Building a map of 4 or 8-connected neighbors.
|
||||
// The pixel of the map is 255 if there is an obstacle nearby
|
||||
uint8_t * buf = buffer_.get<uint8_t>(image.rows() * image.columns());
|
||||
Image<uint8_t> max_neighbors_image(image.rows(), image.columns(), buf, image.columns());
|
||||
|
||||
// If NO_INFORMATION (=255) isn't obstacle, we can't use a simple max() to check
|
||||
// any obstacle nearby. In this case, we interpret NO_INFORMATION as an empty space.
|
||||
if (!no_information_is_obstacle_) {
|
||||
auto replace_to_free = [](uint8_t v) {
|
||||
return v == NO_INFORMATION ? FREE_SPACE : v;
|
||||
};
|
||||
auto max = [&](const std::initializer_list<uint8_t> lst) {
|
||||
std::array<uint8_t, 3> buf = {
|
||||
replace_to_free(*lst.begin()),
|
||||
replace_to_free(*(lst.begin() + 1)),
|
||||
replace_to_free(*(lst.begin() + 2))
|
||||
};
|
||||
return *std::max_element(buf.begin(), buf.end());
|
||||
};
|
||||
dilate(image, max_neighbors_image, group_connectivity_type_, max);
|
||||
} else {
|
||||
auto max = [](const std::initializer_list<uint8_t> lst) {
|
||||
return std::max(lst);
|
||||
};
|
||||
dilate(image, max_neighbors_image, group_connectivity_type_, max);
|
||||
}
|
||||
|
||||
max_neighbors_image.convert(
|
||||
image, [this](uint8_t maxNeighbor, uint8_t & img) {
|
||||
if (!isBackground(img) && isBackground(maxNeighbor)) {
|
||||
img = FREE_SPACE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bool DenoiseLayer::isBackground(uint8_t pixel) const
|
||||
{
|
||||
bool is_obstacle =
|
||||
pixel == LETHAL_OBSTACLE ||
|
||||
pixel == INSCRIBED_INFLATED_OBSTACLE ||
|
||||
(pixel == NO_INFORMATION && no_information_is_obstacle_);
|
||||
return !is_obstacle;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
// This is the macro allowing a DenoiseLayer class
|
||||
// to be registered in order to be dynamically loadable of base type nav2_costmap_2d::Layer.
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::DenoiseLayer, nav2_costmap_2d::Layer)
|
||||
@@ -0,0 +1,488 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#include "nav2_costmap_2d/inflation_layer.hpp"
|
||||
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_math.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
#include "rclcpp/parameter_events_filter.hpp"
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::InflationLayer, nav2_costmap_2d::Layer)
|
||||
|
||||
using nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
using nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE;
|
||||
using nav2_costmap_2d::NO_INFORMATION;
|
||||
using rcl_interfaces::msg::ParameterType;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
InflationLayer::InflationLayer()
|
||||
: inflation_radius_(0),
|
||||
inscribed_radius_(0),
|
||||
cost_scaling_factor_(0),
|
||||
inflate_unknown_(false),
|
||||
inflate_around_unknown_(false),
|
||||
cell_inflation_radius_(0),
|
||||
cached_cell_inflation_radius_(0),
|
||||
resolution_(0),
|
||||
cache_length_(0),
|
||||
last_min_x_(std::numeric_limits<double>::lowest()),
|
||||
last_min_y_(std::numeric_limits<double>::lowest()),
|
||||
last_max_x_(std::numeric_limits<double>::max()),
|
||||
last_max_y_(std::numeric_limits<double>::max())
|
||||
{
|
||||
access_ = new mutex_t();
|
||||
}
|
||||
|
||||
InflationLayer::~InflationLayer()
|
||||
{
|
||||
dyn_params_handler_.reset();
|
||||
delete access_;
|
||||
}
|
||||
|
||||
void
|
||||
InflationLayer::onInitialize()
|
||||
{
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("inflation_radius", rclcpp::ParameterValue(0.55));
|
||||
declareParameter("cost_scaling_factor", rclcpp::ParameterValue(10.0));
|
||||
declareParameter("inflate_unknown", rclcpp::ParameterValue(false));
|
||||
declareParameter("inflate_around_unknown", rclcpp::ParameterValue(false));
|
||||
|
||||
{
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
node->get_parameter(name_ + "." + "inflation_radius", inflation_radius_);
|
||||
node->get_parameter(name_ + "." + "cost_scaling_factor", cost_scaling_factor_);
|
||||
node->get_parameter(name_ + "." + "inflate_unknown", inflate_unknown_);
|
||||
node->get_parameter(name_ + "." + "inflate_around_unknown", inflate_around_unknown_);
|
||||
|
||||
dyn_params_handler_ = node->add_on_set_parameters_callback(
|
||||
std::bind(
|
||||
&InflationLayer::dynamicParametersCallback,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
current_ = true;
|
||||
seen_.clear();
|
||||
cached_distances_.clear();
|
||||
cached_costs_.clear();
|
||||
need_reinflation_ = false;
|
||||
cell_inflation_radius_ = cellDistance(inflation_radius_);
|
||||
matchSize();
|
||||
}
|
||||
|
||||
void
|
||||
InflationLayer::matchSize()
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
nav2_costmap_2d::Costmap2D * costmap = layered_costmap_->getCostmap();
|
||||
resolution_ = costmap->getResolution();
|
||||
cell_inflation_radius_ = cellDistance(inflation_radius_);
|
||||
computeCaches();
|
||||
seen_ = std::vector<bool>(costmap->getSizeInCellsX() * costmap->getSizeInCellsY(), false);
|
||||
}
|
||||
|
||||
void
|
||||
InflationLayer::updateBounds(
|
||||
double /*robot_x*/, double /*robot_y*/, double /*robot_yaw*/, double * min_x,
|
||||
double * min_y, double * max_x, double * max_y)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (need_reinflation_) {
|
||||
last_min_x_ = *min_x;
|
||||
last_min_y_ = *min_y;
|
||||
last_max_x_ = *max_x;
|
||||
last_max_y_ = *max_y;
|
||||
|
||||
*min_x = std::numeric_limits<double>::lowest();
|
||||
*min_y = std::numeric_limits<double>::lowest();
|
||||
*max_x = std::numeric_limits<double>::max();
|
||||
*max_y = std::numeric_limits<double>::max();
|
||||
need_reinflation_ = false;
|
||||
} else {
|
||||
double tmp_min_x = last_min_x_;
|
||||
double tmp_min_y = last_min_y_;
|
||||
double tmp_max_x = last_max_x_;
|
||||
double tmp_max_y = last_max_y_;
|
||||
last_min_x_ = *min_x;
|
||||
last_min_y_ = *min_y;
|
||||
last_max_x_ = *max_x;
|
||||
last_max_y_ = *max_y;
|
||||
*min_x = std::min(tmp_min_x, *min_x) - inflation_radius_;
|
||||
*min_y = std::min(tmp_min_y, *min_y) - inflation_radius_;
|
||||
*max_x = std::max(tmp_max_x, *max_x) + inflation_radius_;
|
||||
*max_y = std::max(tmp_max_y, *max_y) + inflation_radius_;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
InflationLayer::onFootprintChanged()
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
inscribed_radius_ = layered_costmap_->getInscribedRadius();
|
||||
cell_inflation_radius_ = cellDistance(inflation_radius_);
|
||||
computeCaches();
|
||||
need_reinflation_ = true;
|
||||
|
||||
if (inflation_radius_ < inscribed_radius_) {
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"The configured inflation radius (%.3f) is smaller than "
|
||||
"the computed inscribed radius (%.3f) of your footprint, "
|
||||
"it is highly recommended to set inflation radius to be at "
|
||||
"least as big as the inscribed radius to avoid collisions",
|
||||
inflation_radius_, inscribed_radius_);
|
||||
}
|
||||
|
||||
RCLCPP_DEBUG(
|
||||
logger_, "InflationLayer::onFootprintChanged(): num footprint points: %zu,"
|
||||
" inscribed_radius_ = %.3f, inflation_radius_ = %.3f",
|
||||
layered_costmap_->getFootprint().size(), inscribed_radius_, inflation_radius_);
|
||||
}
|
||||
|
||||
void
|
||||
InflationLayer::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i, int min_j,
|
||||
int max_i,
|
||||
int max_j)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (!enabled_ || (cell_inflation_radius_ == 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// make sure the inflation list is empty at the beginning of the cycle (should always be true)
|
||||
for (auto & dist : inflation_cells_) {
|
||||
RCLCPP_FATAL_EXPRESSION(
|
||||
logger_,
|
||||
!dist.empty(), "The inflation list must be empty at the beginning of inflation");
|
||||
}
|
||||
|
||||
unsigned char * master_array = master_grid.getCharMap();
|
||||
unsigned int size_x = master_grid.getSizeInCellsX(), size_y = master_grid.getSizeInCellsY();
|
||||
|
||||
if (seen_.size() != size_x * size_y) {
|
||||
RCLCPP_WARN(
|
||||
logger_, "InflationLayer::updateCosts(): seen_ vector size is wrong");
|
||||
seen_ = std::vector<bool>(size_x * size_y, false);
|
||||
}
|
||||
|
||||
std::fill(begin(seen_), end(seen_), false);
|
||||
|
||||
// We need to include in the inflation cells outside the bounding
|
||||
// box min_i...max_j, by the amount cell_inflation_radius_. Cells
|
||||
// up to that distance outside the box can still influence the costs
|
||||
// stored in cells inside the box.
|
||||
const int base_min_i = min_i;
|
||||
const int base_min_j = min_j;
|
||||
const int base_max_i = max_i;
|
||||
const int base_max_j = max_j;
|
||||
min_i -= static_cast<int>(cell_inflation_radius_);
|
||||
min_j -= static_cast<int>(cell_inflation_radius_);
|
||||
max_i += static_cast<int>(cell_inflation_radius_);
|
||||
max_j += static_cast<int>(cell_inflation_radius_);
|
||||
|
||||
min_i = std::max(0, min_i);
|
||||
min_j = std::max(0, min_j);
|
||||
max_i = std::min(static_cast<int>(size_x), max_i);
|
||||
max_j = std::min(static_cast<int>(size_y), max_j);
|
||||
|
||||
// Inflation list; we append cells to visit in a list associated with
|
||||
// its distance to the nearest obstacle
|
||||
// We use a map<distance, list> to emulate the priority queue used before,
|
||||
// with a notable performance boost
|
||||
|
||||
// Start with lethal obstacles: by definition distance is 0.0
|
||||
auto & obs_bin = inflation_cells_[0];
|
||||
for (int j = min_j; j < max_j; j++) {
|
||||
for (int i = min_i; i < max_i; i++) {
|
||||
int index = static_cast<int>(master_grid.getIndex(i, j));
|
||||
unsigned char cost = master_array[index];
|
||||
if (cost == LETHAL_OBSTACLE || (inflate_around_unknown_ && cost == NO_INFORMATION)) {
|
||||
obs_bin.emplace_back(index, i, j, i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process cells by increasing distance; new cells are appended to the
|
||||
// corresponding distance bin, so they
|
||||
// can overtake previously inserted but farther away cells
|
||||
for (const auto & dist_bin : inflation_cells_) {
|
||||
for (std::size_t i = 0; i < dist_bin.size(); ++i) {
|
||||
// Do not use iterator or for-range based loops to
|
||||
// iterate though dist_bin, since it's size might
|
||||
// change when a new cell is enqueued, invalidating all iterators
|
||||
unsigned int index = dist_bin[i].index_;
|
||||
|
||||
// ignore if already visited
|
||||
if (seen_[index]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen_[index] = true;
|
||||
|
||||
unsigned int mx = dist_bin[i].x_;
|
||||
unsigned int my = dist_bin[i].y_;
|
||||
unsigned int sx = dist_bin[i].src_x_;
|
||||
unsigned int sy = dist_bin[i].src_y_;
|
||||
|
||||
// assign the cost associated with the distance from an obstacle to the cell
|
||||
unsigned char cost = costLookup(mx, my, sx, sy);
|
||||
unsigned char old_cost = master_array[index];
|
||||
// In order to avoid artifacts appeared out of boundary areas
|
||||
// when some layer is going after inflation_layer,
|
||||
// we need to apply inflation_layer only to inside of given bounds
|
||||
if (static_cast<int>(mx) >= base_min_i &&
|
||||
static_cast<int>(my) >= base_min_j &&
|
||||
static_cast<int>(mx) < base_max_i &&
|
||||
static_cast<int>(my) < base_max_j)
|
||||
{
|
||||
if (old_cost == NO_INFORMATION &&
|
||||
(inflate_unknown_ ? (cost > FREE_SPACE) : (cost >= INSCRIBED_INFLATED_OBSTACLE)))
|
||||
{
|
||||
master_array[index] = cost;
|
||||
} else {
|
||||
master_array[index] = std::max(old_cost, cost);
|
||||
}
|
||||
}
|
||||
|
||||
// attempt to put the neighbors of the current cell onto the inflation list
|
||||
if (mx > 0) {
|
||||
enqueue(index - 1, mx - 1, my, sx, sy);
|
||||
}
|
||||
if (my > 0) {
|
||||
enqueue(index - size_x, mx, my - 1, sx, sy);
|
||||
}
|
||||
if (mx < size_x - 1) {
|
||||
enqueue(index + 1, mx + 1, my, sx, sy);
|
||||
}
|
||||
if (my < size_y - 1) {
|
||||
enqueue(index + size_x, mx, my + 1, sx, sy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (auto & dist : inflation_cells_) {
|
||||
dist.clear();
|
||||
dist.reserve(200);
|
||||
}
|
||||
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Given an index of a cell in the costmap, place it into a list pending for obstacle inflation
|
||||
* @param grid The costmap
|
||||
* @param index The index of the cell
|
||||
* @param mx The x coordinate of the cell (can be computed from the index, but saves time to store it)
|
||||
* @param my The y coordinate of the cell (can be computed from the index, but saves time to store it)
|
||||
* @param src_x The x index of the obstacle point inflation started at
|
||||
* @param src_y The y index of the obstacle point inflation started at
|
||||
*/
|
||||
void
|
||||
InflationLayer::enqueue(
|
||||
unsigned int index, unsigned int mx, unsigned int my,
|
||||
unsigned int src_x, unsigned int src_y)
|
||||
{
|
||||
if (!seen_[index]) {
|
||||
// we compute our distance table one cell further than the
|
||||
// inflation radius dictates so we can make the check below
|
||||
double distance = distanceLookup(mx, my, src_x, src_y);
|
||||
|
||||
// we only want to put the cell in the list if it is within
|
||||
// the inflation radius of the obstacle point
|
||||
if (distance > cell_inflation_radius_) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unsigned int r = cell_inflation_radius_ + 2;
|
||||
|
||||
// push the cell data onto the inflation list and mark
|
||||
inflation_cells_[distance_matrix_[mx - src_x + r][my - src_y + r]].emplace_back(
|
||||
index, mx, my, src_x, src_y);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
InflationLayer::computeCaches()
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (cell_inflation_radius_ == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
cache_length_ = cell_inflation_radius_ + 2;
|
||||
|
||||
// based on the inflation radius... compute distance and cost caches
|
||||
if (cell_inflation_radius_ != cached_cell_inflation_radius_) {
|
||||
cached_costs_.resize(cache_length_ * cache_length_);
|
||||
cached_distances_.resize(cache_length_ * cache_length_);
|
||||
|
||||
for (unsigned int i = 0; i < cache_length_; ++i) {
|
||||
for (unsigned int j = 0; j < cache_length_; ++j) {
|
||||
cached_distances_[i * cache_length_ + j] = hypot(i, j);
|
||||
}
|
||||
}
|
||||
|
||||
cached_cell_inflation_radius_ = cell_inflation_radius_;
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i < cache_length_; ++i) {
|
||||
for (unsigned int j = 0; j < cache_length_; ++j) {
|
||||
cached_costs_[i * cache_length_ + j] = computeCost(cached_distances_[i * cache_length_ + j]);
|
||||
}
|
||||
}
|
||||
|
||||
int max_dist = generateIntegerDistances();
|
||||
inflation_cells_.clear();
|
||||
inflation_cells_.resize(max_dist + 1);
|
||||
for (auto & dist : inflation_cells_) {
|
||||
dist.reserve(200);
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
InflationLayer::generateIntegerDistances()
|
||||
{
|
||||
const int r = cell_inflation_radius_ + 2;
|
||||
const int size = r * 2 + 1;
|
||||
|
||||
std::vector<std::pair<int, int>> points;
|
||||
|
||||
for (int y = -r; y <= r; y++) {
|
||||
for (int x = -r; x <= r; x++) {
|
||||
if (x * x + y * y <= r * r) {
|
||||
points.emplace_back(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::sort(
|
||||
points.begin(), points.end(),
|
||||
[](const std::pair<int, int> & a, const std::pair<int, int> & b) -> bool {
|
||||
return a.first * a.first + a.second * a.second < b.first * b.first + b.second * b.second;
|
||||
}
|
||||
);
|
||||
|
||||
std::vector<std::vector<int>> distance_matrix(size, std::vector<int>(size, 0));
|
||||
std::pair<int, int> last = {0, 0};
|
||||
int level = 0;
|
||||
for (auto const & p : points) {
|
||||
if (p.first * p.first + p.second * p.second !=
|
||||
last.first * last.first + last.second * last.second)
|
||||
{
|
||||
level++;
|
||||
}
|
||||
distance_matrix[p.first + r][p.second + r] = level;
|
||||
last = p;
|
||||
}
|
||||
|
||||
distance_matrix_ = distance_matrix;
|
||||
return level;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
InflationLayer::dynamicParametersCallback(
|
||||
std::vector<rclcpp::Parameter> parameters)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
rcl_interfaces::msg::SetParametersResult result;
|
||||
|
||||
bool need_cache_recompute = false;
|
||||
|
||||
for (auto parameter : parameters) {
|
||||
const auto & param_type = parameter.get_type();
|
||||
const auto & param_name = parameter.get_name();
|
||||
|
||||
if (param_type == ParameterType::PARAMETER_DOUBLE) {
|
||||
if (param_name == name_ + "." + "inflation_radius" &&
|
||||
inflation_radius_ != parameter.as_double())
|
||||
{
|
||||
inflation_radius_ = parameter.as_double();
|
||||
need_reinflation_ = true;
|
||||
need_cache_recompute = true;
|
||||
} else if (param_name == name_ + "." + "cost_scaling_factor" && // NOLINT
|
||||
cost_scaling_factor_ != parameter.as_double())
|
||||
{
|
||||
cost_scaling_factor_ = parameter.as_double();
|
||||
need_reinflation_ = true;
|
||||
need_cache_recompute = true;
|
||||
}
|
||||
} else if (param_type == ParameterType::PARAMETER_BOOL) {
|
||||
if (param_name == name_ + "." + "enabled" && enabled_ != parameter.as_bool()) {
|
||||
enabled_ = parameter.as_bool();
|
||||
need_reinflation_ = true;
|
||||
current_ = false;
|
||||
} else if (param_name == name_ + "." + "inflate_unknown" && // NOLINT
|
||||
inflate_unknown_ != parameter.as_bool())
|
||||
{
|
||||
inflate_unknown_ = parameter.as_bool();
|
||||
need_reinflation_ = true;
|
||||
} else if (param_name == name_ + "." + "inflate_around_unknown" && // NOLINT
|
||||
inflate_around_unknown_ != parameter.as_bool())
|
||||
{
|
||||
inflate_around_unknown_ = parameter.as_bool();
|
||||
need_reinflation_ = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (need_cache_recompute) {
|
||||
matchSize();
|
||||
}
|
||||
|
||||
result.successful = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,766 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
* Steve Macenski
|
||||
*********************************************************************/
|
||||
#include "nav2_costmap_2d/obstacle_layer.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
#include "sensor_msgs/point_cloud2_iterator.hpp"
|
||||
#include "nav2_costmap_2d/costmap_math.hpp"
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::ObstacleLayer, nav2_costmap_2d::Layer)
|
||||
|
||||
using nav2_costmap_2d::NO_INFORMATION;
|
||||
using nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
using nav2_costmap_2d::FREE_SPACE;
|
||||
|
||||
using nav2_costmap_2d::ObservationBuffer;
|
||||
using nav2_costmap_2d::Observation;
|
||||
using rcl_interfaces::msg::ParameterType;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
ObstacleLayer::~ObstacleLayer()
|
||||
{
|
||||
dyn_params_handler_.reset();
|
||||
for (auto & notifier : observation_notifiers_) {
|
||||
notifier.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void ObstacleLayer::onInitialize()
|
||||
{
|
||||
bool track_unknown_space;
|
||||
double transform_tolerance;
|
||||
|
||||
// The topics that we'll subscribe to from the parameter server
|
||||
std::string topics_string;
|
||||
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("footprint_clearing_enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("min_obstacle_height", rclcpp::ParameterValue(0.0));
|
||||
declareParameter("max_obstacle_height", rclcpp::ParameterValue(2.0));
|
||||
declareParameter("combination_method", rclcpp::ParameterValue(1));
|
||||
declareParameter("observation_sources", rclcpp::ParameterValue(std::string("")));
|
||||
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
node->get_parameter(name_ + "." + "footprint_clearing_enabled", footprint_clearing_enabled_);
|
||||
node->get_parameter(name_ + "." + "min_obstacle_height", min_obstacle_height_);
|
||||
node->get_parameter(name_ + "." + "max_obstacle_height", max_obstacle_height_);
|
||||
node->get_parameter(name_ + "." + "combination_method", combination_method_);
|
||||
node->get_parameter("track_unknown_space", track_unknown_space);
|
||||
node->get_parameter("transform_tolerance", transform_tolerance);
|
||||
node->get_parameter(name_ + "." + "observation_sources", topics_string);
|
||||
|
||||
dyn_params_handler_ = node->add_on_set_parameters_callback(
|
||||
std::bind(
|
||||
&ObstacleLayer::dynamicParametersCallback,
|
||||
this,
|
||||
std::placeholders::_1));
|
||||
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"Subscribed to Topics: %s", topics_string.c_str());
|
||||
|
||||
rolling_window_ = layered_costmap_->isRolling();
|
||||
|
||||
if (track_unknown_space) {
|
||||
default_value_ = NO_INFORMATION;
|
||||
} else {
|
||||
default_value_ = FREE_SPACE;
|
||||
}
|
||||
|
||||
ObstacleLayer::matchSize();
|
||||
current_ = true;
|
||||
was_reset_ = false;
|
||||
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
|
||||
auto sub_opt = rclcpp::SubscriptionOptions();
|
||||
sub_opt.callback_group = callback_group_;
|
||||
|
||||
// now we need to split the topics based on whitespace which we can use a stringstream for
|
||||
std::stringstream ss(topics_string);
|
||||
|
||||
std::string source;
|
||||
while (ss >> source) {
|
||||
// get the parameters for the specific topic
|
||||
double observation_keep_time, expected_update_rate, min_obstacle_height, max_obstacle_height;
|
||||
std::string topic, sensor_frame, data_type;
|
||||
bool inf_is_valid, clearing, marking;
|
||||
|
||||
declareParameter(source + "." + "topic", rclcpp::ParameterValue(source));
|
||||
declareParameter(source + "." + "sensor_frame", rclcpp::ParameterValue(std::string("")));
|
||||
declareParameter(source + "." + "observation_persistence", rclcpp::ParameterValue(0.0));
|
||||
declareParameter(source + "." + "expected_update_rate", rclcpp::ParameterValue(0.0));
|
||||
declareParameter(source + "." + "data_type", rclcpp::ParameterValue(std::string("LaserScan")));
|
||||
declareParameter(source + "." + "min_obstacle_height", rclcpp::ParameterValue(0.0));
|
||||
declareParameter(source + "." + "max_obstacle_height", rclcpp::ParameterValue(0.0));
|
||||
declareParameter(source + "." + "inf_is_valid", rclcpp::ParameterValue(false));
|
||||
declareParameter(source + "." + "marking", rclcpp::ParameterValue(true));
|
||||
declareParameter(source + "." + "clearing", rclcpp::ParameterValue(false));
|
||||
declareParameter(source + "." + "obstacle_max_range", rclcpp::ParameterValue(2.5));
|
||||
declareParameter(source + "." + "obstacle_min_range", rclcpp::ParameterValue(0.0));
|
||||
declareParameter(source + "." + "raytrace_max_range", rclcpp::ParameterValue(3.0));
|
||||
declareParameter(source + "." + "raytrace_min_range", rclcpp::ParameterValue(0.0));
|
||||
|
||||
node->get_parameter(name_ + "." + source + "." + "topic", topic);
|
||||
node->get_parameter(name_ + "." + source + "." + "sensor_frame", sensor_frame);
|
||||
node->get_parameter(
|
||||
name_ + "." + source + "." + "observation_persistence",
|
||||
observation_keep_time);
|
||||
node->get_parameter(
|
||||
name_ + "." + source + "." + "expected_update_rate",
|
||||
expected_update_rate);
|
||||
node->get_parameter(name_ + "." + source + "." + "data_type", data_type);
|
||||
node->get_parameter(name_ + "." + source + "." + "min_obstacle_height", min_obstacle_height);
|
||||
node->get_parameter(name_ + "." + source + "." + "max_obstacle_height", max_obstacle_height);
|
||||
node->get_parameter(name_ + "." + source + "." + "inf_is_valid", inf_is_valid);
|
||||
node->get_parameter(name_ + "." + source + "." + "marking", marking);
|
||||
node->get_parameter(name_ + "." + source + "." + "clearing", clearing);
|
||||
|
||||
if (!(data_type == "PointCloud2" || data_type == "LaserScan")) {
|
||||
RCLCPP_FATAL(
|
||||
logger_,
|
||||
"Only topics that use point cloud2s or laser scans are currently supported");
|
||||
throw std::runtime_error(
|
||||
"Only topics that use point cloud2s or laser scans are currently supported");
|
||||
}
|
||||
|
||||
// get the obstacle range for the sensor
|
||||
double obstacle_max_range, obstacle_min_range;
|
||||
node->get_parameter(name_ + "." + source + "." + "obstacle_max_range", obstacle_max_range);
|
||||
node->get_parameter(name_ + "." + source + "." + "obstacle_min_range", obstacle_min_range);
|
||||
|
||||
// get the raytrace ranges for the sensor
|
||||
double raytrace_max_range, raytrace_min_range;
|
||||
node->get_parameter(name_ + "." + source + "." + "raytrace_min_range", raytrace_min_range);
|
||||
node->get_parameter(name_ + "." + source + "." + "raytrace_max_range", raytrace_max_range);
|
||||
|
||||
|
||||
RCLCPP_DEBUG(
|
||||
logger_,
|
||||
"Creating an observation buffer for source %s, topic %s, frame %s",
|
||||
source.c_str(), topic.c_str(),
|
||||
sensor_frame.c_str());
|
||||
|
||||
// create an observation buffer
|
||||
observation_buffers_.push_back(
|
||||
std::shared_ptr<ObservationBuffer
|
||||
>(
|
||||
new ObservationBuffer(
|
||||
node, topic, observation_keep_time, expected_update_rate,
|
||||
min_obstacle_height,
|
||||
max_obstacle_height, obstacle_max_range, obstacle_min_range, raytrace_max_range,
|
||||
raytrace_min_range, *tf_,
|
||||
global_frame_,
|
||||
sensor_frame, tf2::durationFromSec(transform_tolerance))));
|
||||
|
||||
// check if we'll add this buffer to our marking observation buffers
|
||||
if (marking) {
|
||||
marking_buffers_.push_back(observation_buffers_.back());
|
||||
}
|
||||
|
||||
// check if we'll also add this buffer to our clearing observation buffers
|
||||
if (clearing) {
|
||||
clearing_buffers_.push_back(observation_buffers_.back());
|
||||
}
|
||||
|
||||
RCLCPP_DEBUG(
|
||||
logger_,
|
||||
"Created an observation buffer for source %s, topic %s, global frame: %s, "
|
||||
"expected update rate: %.2f, observation persistence: %.2f",
|
||||
source.c_str(), topic.c_str(),
|
||||
global_frame_.c_str(), expected_update_rate, observation_keep_time);
|
||||
|
||||
rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_sensor_data;
|
||||
custom_qos_profile.depth = 50;
|
||||
|
||||
// create a callback for the topic
|
||||
if (data_type == "LaserScan") {
|
||||
auto sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::LaserScan,
|
||||
rclcpp_lifecycle::LifecycleNode>>(node, topic, custom_qos_profile, sub_opt);
|
||||
sub->unsubscribe();
|
||||
|
||||
auto filter = std::make_shared<tf2_ros::MessageFilter<sensor_msgs::msg::LaserScan>>(
|
||||
*sub, *tf_, global_frame_, 50,
|
||||
node->get_node_logging_interface(),
|
||||
node->get_node_clock_interface(),
|
||||
tf2::durationFromSec(transform_tolerance));
|
||||
|
||||
if (inf_is_valid) {
|
||||
filter->registerCallback(
|
||||
std::bind(
|
||||
&ObstacleLayer::laserScanValidInfCallback, this, std::placeholders::_1,
|
||||
observation_buffers_.back()));
|
||||
|
||||
} else {
|
||||
filter->registerCallback(
|
||||
std::bind(
|
||||
&ObstacleLayer::laserScanCallback, this, std::placeholders::_1,
|
||||
observation_buffers_.back()));
|
||||
}
|
||||
|
||||
observation_subscribers_.push_back(sub);
|
||||
|
||||
observation_notifiers_.push_back(filter);
|
||||
observation_notifiers_.back()->setTolerance(rclcpp::Duration::from_seconds(0.05));
|
||||
|
||||
} else {
|
||||
auto sub = std::make_shared<message_filters::Subscriber<sensor_msgs::msg::PointCloud2,
|
||||
rclcpp_lifecycle::LifecycleNode>>(node, topic, custom_qos_profile, sub_opt);
|
||||
sub->unsubscribe();
|
||||
|
||||
if (inf_is_valid) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.");
|
||||
}
|
||||
|
||||
auto filter = std::make_shared<tf2_ros::MessageFilter<sensor_msgs::msg::PointCloud2>>(
|
||||
*sub, *tf_, global_frame_, 50,
|
||||
node->get_node_logging_interface(),
|
||||
node->get_node_clock_interface(),
|
||||
tf2::durationFromSec(transform_tolerance));
|
||||
|
||||
filter->registerCallback(
|
||||
std::bind(
|
||||
&ObstacleLayer::pointCloud2Callback, this, std::placeholders::_1,
|
||||
observation_buffers_.back()));
|
||||
|
||||
observation_subscribers_.push_back(sub);
|
||||
observation_notifiers_.push_back(filter);
|
||||
}
|
||||
|
||||
if (sensor_frame != "") {
|
||||
std::vector<std::string> target_frames;
|
||||
target_frames.push_back(global_frame_);
|
||||
target_frames.push_back(sensor_frame);
|
||||
observation_notifiers_.back()->setTargetFrames(target_frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
ObstacleLayer::dynamicParametersCallback(
|
||||
std::vector<rclcpp::Parameter> parameters)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
rcl_interfaces::msg::SetParametersResult result;
|
||||
|
||||
for (auto parameter : parameters) {
|
||||
const auto & param_type = parameter.get_type();
|
||||
const auto & param_name = parameter.get_name();
|
||||
|
||||
if (param_type == ParameterType::PARAMETER_DOUBLE) {
|
||||
if (param_name == name_ + "." + "min_obstacle_height") {
|
||||
min_obstacle_height_ = parameter.as_double();
|
||||
} else if (param_name == name_ + "." + "max_obstacle_height") {
|
||||
max_obstacle_height_ = parameter.as_double();
|
||||
}
|
||||
} else if (param_type == ParameterType::PARAMETER_BOOL) {
|
||||
if (param_name == name_ + "." + "enabled" && enabled_ != parameter.as_bool()) {
|
||||
enabled_ = parameter.as_bool();
|
||||
if (enabled_) {
|
||||
current_ = false;
|
||||
}
|
||||
} else if (param_name == name_ + "." + "footprint_clearing_enabled") {
|
||||
footprint_clearing_enabled_ = parameter.as_bool();
|
||||
}
|
||||
} else if (param_type == ParameterType::PARAMETER_INTEGER) {
|
||||
if (param_name == name_ + "." + "combination_method") {
|
||||
combination_method_ = parameter.as_int();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.successful = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::laserScanCallback(
|
||||
sensor_msgs::msg::LaserScan::ConstSharedPtr message,
|
||||
const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer)
|
||||
{
|
||||
// project the laser into a point cloud
|
||||
sensor_msgs::msg::PointCloud2 cloud;
|
||||
cloud.header = message->header;
|
||||
|
||||
// project the scan into a point cloud
|
||||
try {
|
||||
projector_.transformLaserScanToPointCloud(message->header.frame_id, *message, cloud, *tf_);
|
||||
} catch (tf2::TransformException & ex) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"High fidelity enabled, but TF returned a transform exception to frame %s: %s",
|
||||
global_frame_.c_str(),
|
||||
ex.what());
|
||||
projector_.projectLaser(*message, cloud);
|
||||
} catch (std::runtime_error & ex) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"transformLaserScanToPointCloud error, it seems the message from laser is malformed."
|
||||
" Ignore this message. what(): %s",
|
||||
ex.what());
|
||||
return;
|
||||
}
|
||||
|
||||
// buffer the point cloud
|
||||
buffer->lock();
|
||||
buffer->bufferCloud(cloud);
|
||||
buffer->unlock();
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::laserScanValidInfCallback(
|
||||
sensor_msgs::msg::LaserScan::ConstSharedPtr raw_message,
|
||||
const std::shared_ptr<nav2_costmap_2d::ObservationBuffer> & buffer)
|
||||
{
|
||||
// Filter positive infinities ("Inf"s) to max_range.
|
||||
float epsilon = 0.0001; // a tenth of a millimeter
|
||||
sensor_msgs::msg::LaserScan message = *raw_message;
|
||||
for (size_t i = 0; i < message.ranges.size(); i++) {
|
||||
float range = message.ranges[i];
|
||||
if (!std::isfinite(range) && range > 0) {
|
||||
message.ranges[i] = message.range_max - epsilon;
|
||||
}
|
||||
}
|
||||
|
||||
// project the laser into a point cloud
|
||||
sensor_msgs::msg::PointCloud2 cloud;
|
||||
cloud.header = message.header;
|
||||
|
||||
// project the scan into a point cloud
|
||||
try {
|
||||
projector_.transformLaserScanToPointCloud(message.header.frame_id, message, cloud, *tf_);
|
||||
} catch (tf2::TransformException & ex) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"High fidelity enabled, but TF returned a transform exception to frame %s: %s",
|
||||
global_frame_.c_str(), ex.what());
|
||||
projector_.projectLaser(message, cloud);
|
||||
} catch (std::runtime_error & ex) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"transformLaserScanToPointCloud error, it seems the message from laser is malformed."
|
||||
" Ignore this message. what(): %s",
|
||||
ex.what());
|
||||
return;
|
||||
}
|
||||
|
||||
// buffer the point cloud
|
||||
buffer->lock();
|
||||
buffer->bufferCloud(cloud);
|
||||
buffer->unlock();
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::pointCloud2Callback(
|
||||
sensor_msgs::msg::PointCloud2::ConstSharedPtr message,
|
||||
const std::shared_ptr<ObservationBuffer> & buffer)
|
||||
{
|
||||
// buffer the point cloud
|
||||
buffer->lock();
|
||||
buffer->bufferCloud(*message);
|
||||
buffer->unlock();
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y, double * max_x, double * max_y)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (rolling_window_) {
|
||||
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
|
||||
}
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
useExtraBounds(min_x, min_y, max_x, max_y);
|
||||
|
||||
bool current = true;
|
||||
std::vector<Observation> observations, clearing_observations;
|
||||
|
||||
// get the marking observations
|
||||
current = current && getMarkingObservations(observations);
|
||||
|
||||
// get the clearing observations
|
||||
current = current && getClearingObservations(clearing_observations);
|
||||
|
||||
// update the global current status
|
||||
current_ = current;
|
||||
|
||||
// raytrace freespace
|
||||
for (unsigned int i = 0; i < clearing_observations.size(); ++i) {
|
||||
raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
// place the new obstacles into a priority queue... each with a priority of zero to begin with
|
||||
for (std::vector<Observation>::const_iterator it = observations.begin();
|
||||
it != observations.end(); ++it)
|
||||
{
|
||||
const Observation & obs = *it;
|
||||
|
||||
const sensor_msgs::msg::PointCloud2 & cloud = *(obs.cloud_);
|
||||
|
||||
double sq_obstacle_max_range = obs.obstacle_max_range_ * obs.obstacle_max_range_;
|
||||
double sq_obstacle_min_range = obs.obstacle_min_range_ * obs.obstacle_min_range_;
|
||||
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
|
||||
|
||||
for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) {
|
||||
double px = *iter_x, py = *iter_y, pz = *iter_z;
|
||||
|
||||
// if the obstacle is too low, we won't add it
|
||||
if (pz < min_obstacle_height_) {
|
||||
RCLCPP_DEBUG(logger_, "The point is too low");
|
||||
continue;
|
||||
}
|
||||
|
||||
// if the obstacle is too high or too far away from the robot we won't add it
|
||||
if (pz > max_obstacle_height_) {
|
||||
RCLCPP_DEBUG(logger_, "The point is too high");
|
||||
continue;
|
||||
}
|
||||
|
||||
// compute the squared distance from the hitpoint to the pointcloud's origin
|
||||
double sq_dist =
|
||||
(px -
|
||||
obs.origin_.x) * (px - obs.origin_.x) + (py - obs.origin_.y) * (py - obs.origin_.y) +
|
||||
(pz - obs.origin_.z) * (pz - obs.origin_.z);
|
||||
|
||||
// if the point is far enough away... we won't consider it
|
||||
if (sq_dist >= sq_obstacle_max_range) {
|
||||
RCLCPP_DEBUG(logger_, "The point is too far away");
|
||||
continue;
|
||||
}
|
||||
|
||||
// if the point is too close, do not conisder it
|
||||
if (sq_dist < sq_obstacle_min_range) {
|
||||
RCLCPP_DEBUG(logger_, "The point is too close");
|
||||
continue;
|
||||
}
|
||||
|
||||
// now we need to compute the map coordinates for the observation
|
||||
unsigned int mx, my;
|
||||
if (!worldToMap(px, py, mx, my)) {
|
||||
RCLCPP_DEBUG(logger_, "Computing map coords failed");
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned int index = getIndex(mx, my);
|
||||
costmap_[index] = LETHAL_OBSTACLE;
|
||||
touch(px, py, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
}
|
||||
|
||||
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::updateFootprint(
|
||||
double robot_x, double robot_y, double robot_yaw,
|
||||
double * min_x, double * min_y,
|
||||
double * max_x,
|
||||
double * max_y)
|
||||
{
|
||||
if (!footprint_clearing_enabled_) {return;}
|
||||
transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
|
||||
|
||||
for (unsigned int i = 0; i < transformed_footprint_.size(); i++) {
|
||||
touch(transformed_footprint_[i].x, transformed_footprint_[i].y, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i, int min_j,
|
||||
int max_i,
|
||||
int max_j)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if not current due to reset, set current now after clearing
|
||||
if (!current_ && was_reset_) {
|
||||
was_reset_ = false;
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
if (footprint_clearing_enabled_) {
|
||||
setConvexPolygonCost(transformed_footprint_, nav2_costmap_2d::FREE_SPACE);
|
||||
}
|
||||
|
||||
switch (combination_method_) {
|
||||
case 0: // Overwrite
|
||||
updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
|
||||
break;
|
||||
case 1: // Maximum
|
||||
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
|
||||
break;
|
||||
default: // Nothing
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::addStaticObservation(
|
||||
nav2_costmap_2d::Observation & obs,
|
||||
bool marking, bool clearing)
|
||||
{
|
||||
if (marking) {
|
||||
static_marking_observations_.push_back(obs);
|
||||
}
|
||||
if (clearing) {
|
||||
static_clearing_observations_.push_back(obs);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::clearStaticObservations(bool marking, bool clearing)
|
||||
{
|
||||
if (marking) {
|
||||
static_marking_observations_.clear();
|
||||
}
|
||||
if (clearing) {
|
||||
static_clearing_observations_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
ObstacleLayer::getMarkingObservations(std::vector<Observation> & marking_observations) const
|
||||
{
|
||||
bool current = true;
|
||||
// get the marking observations
|
||||
for (unsigned int i = 0; i < marking_buffers_.size(); ++i) {
|
||||
marking_buffers_[i]->lock();
|
||||
marking_buffers_[i]->getObservations(marking_observations);
|
||||
current = marking_buffers_[i]->isCurrent() && current;
|
||||
marking_buffers_[i]->unlock();
|
||||
}
|
||||
marking_observations.insert(
|
||||
marking_observations.end(),
|
||||
static_marking_observations_.begin(), static_marking_observations_.end());
|
||||
return current;
|
||||
}
|
||||
|
||||
bool
|
||||
ObstacleLayer::getClearingObservations(std::vector<Observation> & clearing_observations) const
|
||||
{
|
||||
bool current = true;
|
||||
// get the clearing observations
|
||||
for (unsigned int i = 0; i < clearing_buffers_.size(); ++i) {
|
||||
clearing_buffers_[i]->lock();
|
||||
clearing_buffers_[i]->getObservations(clearing_observations);
|
||||
current = clearing_buffers_[i]->isCurrent() && current;
|
||||
clearing_buffers_[i]->unlock();
|
||||
}
|
||||
clearing_observations.insert(
|
||||
clearing_observations.end(),
|
||||
static_clearing_observations_.begin(), static_clearing_observations_.end());
|
||||
return current;
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::raytraceFreespace(
|
||||
const Observation & clearing_observation, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y)
|
||||
{
|
||||
double ox = clearing_observation.origin_.x;
|
||||
double oy = clearing_observation.origin_.y;
|
||||
const sensor_msgs::msg::PointCloud2 & cloud = *(clearing_observation.cloud_);
|
||||
|
||||
// get the map coordinates of the origin of the sensor
|
||||
unsigned int x0, y0;
|
||||
if (!worldToMap(ox, oy, x0, y0)) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"Sensor origin at (%.2f, %.2f) is out of map bounds (%.2f, %.2f) to (%.2f, %.2f). "
|
||||
"The costmap cannot raytrace for it.",
|
||||
ox, oy,
|
||||
origin_x_, origin_y_,
|
||||
origin_x_ + getSizeInMetersX(), origin_y_ + getSizeInMetersY());
|
||||
return;
|
||||
}
|
||||
|
||||
// we can pre-compute the enpoints of the map outside of the inner loop... we'll need these later
|
||||
double origin_x = origin_x_, origin_y = origin_y_;
|
||||
double map_end_x = origin_x + size_x_ * resolution_;
|
||||
double map_end_y = origin_y + size_y_ * resolution_;
|
||||
|
||||
|
||||
touch(ox, oy, min_x, min_y, max_x, max_y);
|
||||
|
||||
// for each point in the cloud, we want to trace a line from the origin
|
||||
// and clear obstacles along it
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
|
||||
|
||||
for (; iter_x != iter_x.end(); ++iter_x, ++iter_y) {
|
||||
double wx = *iter_x;
|
||||
double wy = *iter_y;
|
||||
|
||||
// now we also need to make sure that the enpoint we're raytracing
|
||||
// to isn't off the costmap and scale if necessary
|
||||
double a = wx - ox;
|
||||
double b = wy - oy;
|
||||
|
||||
// the minimum value to raytrace from is the origin
|
||||
if (wx < origin_x) {
|
||||
double t = (origin_x - ox) / a;
|
||||
wx = origin_x;
|
||||
wy = oy + b * t;
|
||||
}
|
||||
if (wy < origin_y) {
|
||||
double t = (origin_y - oy) / b;
|
||||
wx = ox + a * t;
|
||||
wy = origin_y;
|
||||
}
|
||||
|
||||
// the maximum value to raytrace to is the end of the map
|
||||
if (wx > map_end_x) {
|
||||
double t = (map_end_x - ox) / a;
|
||||
wx = map_end_x - .001;
|
||||
wy = oy + b * t;
|
||||
}
|
||||
if (wy > map_end_y) {
|
||||
double t = (map_end_y - oy) / b;
|
||||
wx = ox + a * t;
|
||||
wy = map_end_y - .001;
|
||||
}
|
||||
|
||||
// now that the vector is scaled correctly... we'll get the map coordinates of its endpoint
|
||||
unsigned int x1, y1;
|
||||
|
||||
// check for legality just in case
|
||||
if (!worldToMap(wx, wy, x1, y1)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned int cell_raytrace_max_range = cellDistance(clearing_observation.raytrace_max_range_);
|
||||
unsigned int cell_raytrace_min_range = cellDistance(clearing_observation.raytrace_min_range_);
|
||||
MarkCell marker(costmap_, FREE_SPACE);
|
||||
// and finally... we can execute our trace to clear obstacles along that line
|
||||
raytraceLine(marker, x0, y0, x1, y1, cell_raytrace_max_range, cell_raytrace_min_range);
|
||||
|
||||
updateRaytraceBounds(
|
||||
ox, oy, wx, wy, clearing_observation.raytrace_max_range_,
|
||||
clearing_observation.raytrace_min_range_, min_x, min_y, max_x,
|
||||
max_y);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::activate()
|
||||
{
|
||||
for (auto & notifier : observation_notifiers_) {
|
||||
notifier->clear();
|
||||
}
|
||||
|
||||
// if we're stopped we need to re-subscribe to topics
|
||||
for (unsigned int i = 0; i < observation_subscribers_.size(); ++i) {
|
||||
if (observation_subscribers_[i] != NULL) {
|
||||
observation_subscribers_[i]->subscribe();
|
||||
}
|
||||
}
|
||||
resetBuffersLastUpdated();
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::deactivate()
|
||||
{
|
||||
for (unsigned int i = 0; i < observation_subscribers_.size(); ++i) {
|
||||
if (observation_subscribers_[i] != NULL) {
|
||||
observation_subscribers_[i]->unsubscribe();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::updateRaytraceBounds(
|
||||
double ox, double oy, double wx, double wy, double max_range, double min_range,
|
||||
double * min_x, double * min_y, double * max_x, double * max_y)
|
||||
{
|
||||
double dx = wx - ox, dy = wy - oy;
|
||||
double full_distance = hypot(dx, dy);
|
||||
if (full_distance < min_range) {
|
||||
return;
|
||||
}
|
||||
double scale = std::min(1.0, max_range / full_distance);
|
||||
double ex = ox + dx * scale, ey = oy + dy * scale;
|
||||
touch(ex, ey, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::reset()
|
||||
{
|
||||
resetMaps();
|
||||
resetBuffersLastUpdated();
|
||||
current_ = false;
|
||||
was_reset_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
ObstacleLayer::resetBuffersLastUpdated()
|
||||
{
|
||||
for (unsigned int i = 0; i < observation_buffers_.size(); ++i) {
|
||||
if (observation_buffers_[i]) {
|
||||
observation_buffers_[i]->resetLastUpdated();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,542 @@
|
||||
/*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2018 David V. Lu!!
|
||||
* Copyright (c) 2020, Bytes Robotics
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the copyright holder nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <angles/angles.h>
|
||||
#include <algorithm>
|
||||
#include <list>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
#include "geometry_msgs/msg/point_stamped.hpp"
|
||||
#include "nav2_costmap_2d/range_sensor_layer.hpp"
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::RangeSensorLayer, nav2_costmap_2d::Layer)
|
||||
|
||||
using nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
using nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE;
|
||||
using nav2_costmap_2d::NO_INFORMATION;
|
||||
|
||||
using namespace std::literals::chrono_literals;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
RangeSensorLayer::RangeSensorLayer() {}
|
||||
|
||||
void RangeSensorLayer::onInitialize()
|
||||
{
|
||||
current_ = true;
|
||||
was_reset_ = false;
|
||||
buffered_readings_ = 0;
|
||||
last_reading_time_ = clock_->now();
|
||||
default_value_ = to_cost(0.5);
|
||||
|
||||
matchSize();
|
||||
resetRange();
|
||||
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
declareParameter("phi", rclcpp::ParameterValue(1.2));
|
||||
node->get_parameter(name_ + "." + "phi", phi_v_);
|
||||
declareParameter("inflate_cone", rclcpp::ParameterValue(1.0));
|
||||
node->get_parameter(name_ + "." + "inflate_cone", inflate_cone_);
|
||||
declareParameter("no_readings_timeout", rclcpp::ParameterValue(0.0));
|
||||
node->get_parameter(name_ + "." + "no_readings_timeout", no_readings_timeout_);
|
||||
declareParameter("clear_threshold", rclcpp::ParameterValue(0.2));
|
||||
node->get_parameter(name_ + "." + "clear_threshold", clear_threshold_);
|
||||
declareParameter("mark_threshold", rclcpp::ParameterValue(0.8));
|
||||
node->get_parameter(name_ + "." + "mark_threshold", mark_threshold_);
|
||||
declareParameter("clear_on_max_reading", rclcpp::ParameterValue(false));
|
||||
node->get_parameter(name_ + "." + "clear_on_max_reading", clear_on_max_reading_);
|
||||
|
||||
double temp_tf_tol = 0.0;
|
||||
node->get_parameter("transform_tolerance", temp_tf_tol);
|
||||
transform_tolerance_ = tf2::durationFromSec(temp_tf_tol);
|
||||
|
||||
std::vector<std::string> topic_names{};
|
||||
declareParameter("topics", rclcpp::ParameterValue(topic_names));
|
||||
node->get_parameter(name_ + "." + "topics", topic_names);
|
||||
|
||||
InputSensorType input_sensor_type = InputSensorType::ALL;
|
||||
std::string sensor_type_name;
|
||||
declareParameter("input_sensor_type", rclcpp::ParameterValue("ALL"));
|
||||
node->get_parameter(name_ + "." + "input_sensor_type", sensor_type_name);
|
||||
|
||||
std::transform(
|
||||
sensor_type_name.begin(), sensor_type_name.end(),
|
||||
sensor_type_name.begin(), ::toupper);
|
||||
RCLCPP_INFO(
|
||||
logger_, "%s: %s as input_sensor_type given",
|
||||
name_.c_str(), sensor_type_name.c_str());
|
||||
|
||||
if (sensor_type_name == "VARIABLE") {
|
||||
input_sensor_type = InputSensorType::VARIABLE;
|
||||
} else if (sensor_type_name == "FIXED") {
|
||||
input_sensor_type = InputSensorType::FIXED;
|
||||
} else if (sensor_type_name == "ALL") {
|
||||
input_sensor_type = InputSensorType::ALL;
|
||||
} else {
|
||||
RCLCPP_ERROR(
|
||||
logger_, "%s: Invalid input sensor type: %s. Defaulting to ALL.",
|
||||
name_.c_str(), sensor_type_name.c_str());
|
||||
}
|
||||
|
||||
// Validate topic names list: it must be a (normally non-empty) list of strings
|
||||
if (topic_names.empty()) {
|
||||
RCLCPP_FATAL(
|
||||
logger_, "Invalid topic names list: it must"
|
||||
"be a non-empty list of strings");
|
||||
return;
|
||||
}
|
||||
|
||||
// Traverse the topic names list subscribing to all of them with the same callback method
|
||||
for (auto & topic_name : topic_names) {
|
||||
if (input_sensor_type == InputSensorType::VARIABLE) {
|
||||
processRangeMessageFunc_ = std::bind(
|
||||
&RangeSensorLayer::processVariableRangeMsg, this,
|
||||
std::placeholders::_1);
|
||||
} else if (input_sensor_type == InputSensorType::FIXED) {
|
||||
processRangeMessageFunc_ = std::bind(
|
||||
&RangeSensorLayer::processFixedRangeMsg, this,
|
||||
std::placeholders::_1);
|
||||
} else if (input_sensor_type == InputSensorType::ALL) {
|
||||
processRangeMessageFunc_ = std::bind(
|
||||
&RangeSensorLayer::processRangeMsg, this,
|
||||
std::placeholders::_1);
|
||||
} else {
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"%s: Invalid input sensor type: %s. Did you make a new type"
|
||||
"and forgot to choose the subscriber for it?",
|
||||
name_.c_str(), sensor_type_name.c_str());
|
||||
}
|
||||
range_subs_.push_back(
|
||||
node->create_subscription<sensor_msgs::msg::Range>(
|
||||
topic_name, rclcpp::SensorDataQoS(), std::bind(
|
||||
&RangeSensorLayer::bufferIncomingRangeMsg, this,
|
||||
std::placeholders::_1)));
|
||||
|
||||
RCLCPP_INFO(
|
||||
logger_, "RangeSensorLayer: subscribed to "
|
||||
"topic %s", range_subs_.back()->get_topic_name());
|
||||
}
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
}
|
||||
|
||||
|
||||
double RangeSensorLayer::gamma(double theta)
|
||||
{
|
||||
if (fabs(theta) > max_angle_) {
|
||||
return 0.0;
|
||||
} else {
|
||||
return 1 - pow(theta / max_angle_, 2);
|
||||
}
|
||||
}
|
||||
|
||||
double RangeSensorLayer::delta(double phi)
|
||||
{
|
||||
return 1 - (1 + tanh(2 * (phi - phi_v_))) / 2;
|
||||
}
|
||||
|
||||
void RangeSensorLayer::get_deltas(double angle, double * dx, double * dy)
|
||||
{
|
||||
double ta = tan(angle);
|
||||
if (ta == 0) {
|
||||
*dx = 0;
|
||||
} else {
|
||||
*dx = resolution_ / ta;
|
||||
}
|
||||
|
||||
*dx = copysign(*dx, cos(angle));
|
||||
*dy = copysign(resolution_, sin(angle));
|
||||
}
|
||||
|
||||
double RangeSensorLayer::sensor_model(double r, double phi, double theta)
|
||||
{
|
||||
double lbda = delta(phi) * gamma(theta);
|
||||
|
||||
double delta = resolution_;
|
||||
|
||||
if (phi >= 0.0 && phi < r - 2 * delta * r) {
|
||||
return (1 - lbda) * (0.5);
|
||||
} else if (phi < r - delta * r) {
|
||||
return lbda * 0.5 * pow((phi - (r - 2 * delta * r)) / (delta * r), 2) +
|
||||
(1 - lbda) * .5;
|
||||
} else if (phi < r + delta * r) {
|
||||
double J = (r - phi) / (delta * r);
|
||||
return lbda * ((1 - (0.5) * pow(J, 2)) - 0.5) + 0.5;
|
||||
} else {
|
||||
return 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
void RangeSensorLayer::bufferIncomingRangeMsg(
|
||||
const sensor_msgs::msg::Range::SharedPtr range_message)
|
||||
{
|
||||
range_message_mutex_.lock();
|
||||
range_msgs_buffer_.push_back(*range_message);
|
||||
range_message_mutex_.unlock();
|
||||
}
|
||||
|
||||
void RangeSensorLayer::updateCostmap()
|
||||
{
|
||||
std::list<sensor_msgs::msg::Range> range_msgs_buffer_copy;
|
||||
|
||||
range_message_mutex_.lock();
|
||||
range_msgs_buffer_copy = std::list<sensor_msgs::msg::Range>(range_msgs_buffer_);
|
||||
range_msgs_buffer_.clear();
|
||||
range_message_mutex_.unlock();
|
||||
|
||||
for (auto & range_msgs_it : range_msgs_buffer_copy) {
|
||||
processRangeMessageFunc_(range_msgs_it);
|
||||
}
|
||||
}
|
||||
|
||||
void RangeSensorLayer::processRangeMsg(sensor_msgs::msg::Range & range_message)
|
||||
{
|
||||
if (range_message.min_range == range_message.max_range) {
|
||||
processFixedRangeMsg(range_message);
|
||||
} else {
|
||||
processVariableRangeMsg(range_message);
|
||||
}
|
||||
}
|
||||
|
||||
void RangeSensorLayer::processFixedRangeMsg(sensor_msgs::msg::Range & range_message)
|
||||
{
|
||||
if (!std::isinf(range_message.range)) {
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"Fixed distance ranger (min_range == max_range) in frame %s sent invalid value. "
|
||||
"Only -Inf (== object detected) and Inf (== no object detected) are valid.",
|
||||
range_message.header.frame_id.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
bool clear_sensor_cone = false;
|
||||
|
||||
if (range_message.range > 0) { // +inf
|
||||
if (!clear_on_max_reading_) {
|
||||
return; // no clearing at all
|
||||
}
|
||||
clear_sensor_cone = true;
|
||||
}
|
||||
|
||||
range_message.range = range_message.min_range;
|
||||
|
||||
updateCostmap(range_message, clear_sensor_cone);
|
||||
}
|
||||
|
||||
void RangeSensorLayer::processVariableRangeMsg(sensor_msgs::msg::Range & range_message)
|
||||
{
|
||||
if (range_message.range < range_message.min_range || range_message.range >
|
||||
range_message.max_range)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool clear_sensor_cone = false;
|
||||
|
||||
if (range_message.range >= range_message.max_range && clear_on_max_reading_) {
|
||||
clear_sensor_cone = true;
|
||||
}
|
||||
|
||||
updateCostmap(range_message, clear_sensor_cone);
|
||||
}
|
||||
|
||||
void RangeSensorLayer::updateCostmap(
|
||||
sensor_msgs::msg::Range & range_message,
|
||||
bool clear_sensor_cone)
|
||||
{
|
||||
max_angle_ = range_message.field_of_view / 2;
|
||||
|
||||
geometry_msgs::msg::PointStamped in, out;
|
||||
in.header.stamp = range_message.header.stamp;
|
||||
in.header.frame_id = range_message.header.frame_id;
|
||||
|
||||
if (!tf_->canTransform(
|
||||
in.header.frame_id, global_frame_,
|
||||
tf2_ros::fromMsg(in.header.stamp),
|
||||
tf2_ros::fromRclcpp(transform_tolerance_)))
|
||||
{
|
||||
RCLCPP_INFO(
|
||||
logger_, "Range sensor layer can't transform from %s to %s",
|
||||
global_frame_.c_str(), in.header.frame_id.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
tf_->transform(in, out, global_frame_, transform_tolerance_);
|
||||
|
||||
double ox = out.point.x, oy = out.point.y;
|
||||
|
||||
in.point.x = range_message.range;
|
||||
|
||||
tf_->transform(in, out, global_frame_, transform_tolerance_);
|
||||
|
||||
double tx = out.point.x, ty = out.point.y;
|
||||
|
||||
// calculate target props
|
||||
double dx = tx - ox, dy = ty - oy, theta = atan2(dy, dx), d = sqrt(dx * dx + dy * dy);
|
||||
|
||||
// Integer Bounds of Update
|
||||
int bx0, by0, bx1, by1;
|
||||
|
||||
// Triangle that will be really updated; the other cells within bounds are ignored
|
||||
// This triangle is formed by the origin and left and right sides of sonar cone
|
||||
int Ox, Oy, Ax, Ay, Bx, By;
|
||||
|
||||
// Bounds includes the origin
|
||||
worldToMapNoBounds(ox, oy, Ox, Oy);
|
||||
bx1 = bx0 = Ox;
|
||||
by1 = by0 = Oy;
|
||||
touch(ox, oy, &min_x_, &min_y_, &max_x_, &max_y_);
|
||||
|
||||
// Update Map with Target Point
|
||||
unsigned int aa, ab;
|
||||
if (worldToMap(tx, ty, aa, ab)) {
|
||||
setCost(aa, ab, 233);
|
||||
touch(tx, ty, &min_x_, &min_y_, &max_x_, &max_y_);
|
||||
}
|
||||
|
||||
double mx, my;
|
||||
|
||||
// Update left side of sonar cone
|
||||
mx = ox + cos(theta - max_angle_) * d * 1.2;
|
||||
my = oy + sin(theta - max_angle_) * d * 1.2;
|
||||
worldToMapNoBounds(mx, my, Ax, Ay);
|
||||
bx0 = std::min(bx0, Ax);
|
||||
bx1 = std::max(bx1, Ax);
|
||||
by0 = std::min(by0, Ay);
|
||||
by1 = std::max(by1, Ay);
|
||||
touch(mx, my, &min_x_, &min_y_, &max_x_, &max_y_);
|
||||
|
||||
// Update right side of sonar cone
|
||||
mx = ox + cos(theta + max_angle_) * d * 1.2;
|
||||
my = oy + sin(theta + max_angle_) * d * 1.2;
|
||||
|
||||
worldToMapNoBounds(mx, my, Bx, By);
|
||||
bx0 = std::min(bx0, Bx);
|
||||
bx1 = std::max(bx1, Bx);
|
||||
by0 = std::min(by0, By);
|
||||
by1 = std::max(by1, By);
|
||||
touch(mx, my, &min_x_, &min_y_, &max_x_, &max_y_);
|
||||
|
||||
// Limit Bounds to Grid
|
||||
bx0 = std::max(0, bx0);
|
||||
by0 = std::max(0, by0);
|
||||
bx1 = std::min(static_cast<int>(size_x_), bx1);
|
||||
by1 = std::min(static_cast<int>(size_y_), by1);
|
||||
|
||||
for (unsigned int x = bx0; x <= (unsigned int)bx1; x++) {
|
||||
for (unsigned int y = by0; y <= (unsigned int)by1; y++) {
|
||||
bool update_xy_cell = true;
|
||||
|
||||
// Unless inflate_cone_ is set to 100 %, we update cells only within the
|
||||
// (partially inflated) sensor cone, projected on the costmap as a triangle.
|
||||
// 0 % corresponds to just the triangle, but if your sensor fov is very
|
||||
// narrow, the covered area can become zero due to cell discretization.
|
||||
// See wiki description for more details
|
||||
if (inflate_cone_ < 1.0) {
|
||||
// Determine barycentric coordinates
|
||||
int w0 = orient2d(Ax, Ay, Bx, By, x, y);
|
||||
int w1 = orient2d(Bx, By, Ox, Oy, x, y);
|
||||
int w2 = orient2d(Ox, Oy, Ax, Ay, x, y);
|
||||
|
||||
// Barycentric coordinates inside area threshold; this is not mathematically
|
||||
// sound at all, but it works!
|
||||
float bcciath = -static_cast<float>(inflate_cone_) * area(Ax, Ay, Bx, By, Ox, Oy);
|
||||
update_xy_cell = w0 >= bcciath && w1 >= bcciath && w2 >= bcciath;
|
||||
}
|
||||
|
||||
if (update_xy_cell) {
|
||||
double wx, wy;
|
||||
mapToWorld(x, y, wx, wy);
|
||||
update_cell(ox, oy, theta, range_message.range, wx, wy, clear_sensor_cone);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buffered_readings_++;
|
||||
last_reading_time_ = clock_->now();
|
||||
}
|
||||
|
||||
void RangeSensorLayer::update_cell(
|
||||
double ox, double oy, double ot, double r,
|
||||
double nx, double ny, bool clear)
|
||||
{
|
||||
unsigned int x, y;
|
||||
if (worldToMap(nx, ny, x, y)) {
|
||||
double dx = nx - ox, dy = ny - oy;
|
||||
double theta = atan2(dy, dx) - ot;
|
||||
theta = angles::normalize_angle(theta);
|
||||
double phi = sqrt(dx * dx + dy * dy);
|
||||
double sensor = 0.0;
|
||||
if (!clear) {
|
||||
sensor = sensor_model(r, phi, theta);
|
||||
}
|
||||
double prior = to_prob(getCost(x, y));
|
||||
double prob_occ = sensor * prior;
|
||||
double prob_not = (1 - sensor) * (1 - prior);
|
||||
double new_prob = prob_occ / (prob_occ + prob_not);
|
||||
|
||||
RCLCPP_DEBUG(
|
||||
logger_,
|
||||
"%f %f | %f %f = %f", dx, dy, theta, phi, sensor);
|
||||
RCLCPP_DEBUG(
|
||||
logger_,
|
||||
"%f | %f %f | %f", prior, prob_occ, prob_not, new_prob);
|
||||
unsigned char c = to_cost(new_prob);
|
||||
setCost(x, y, c);
|
||||
}
|
||||
}
|
||||
|
||||
void RangeSensorLayer::resetRange()
|
||||
{
|
||||
min_x_ = min_y_ = std::numeric_limits<double>::max();
|
||||
max_x_ = max_y_ = -std::numeric_limits<double>::max();
|
||||
}
|
||||
|
||||
void RangeSensorLayer::updateBounds(
|
||||
double robot_x, double robot_y,
|
||||
double robot_yaw, double * min_x, double * min_y,
|
||||
double * max_x, double * max_y)
|
||||
{
|
||||
robot_yaw = 0 + robot_yaw; // Avoid error if variable not in use
|
||||
if (layered_costmap_->isRolling()) {
|
||||
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
|
||||
}
|
||||
|
||||
updateCostmap();
|
||||
|
||||
*min_x = std::min(*min_x, min_x_);
|
||||
*min_y = std::min(*min_y, min_y_);
|
||||
*max_x = std::max(*max_x, max_x_);
|
||||
*max_y = std::max(*max_y, max_y_);
|
||||
|
||||
resetRange();
|
||||
|
||||
if (!enabled_) {
|
||||
current_ = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (buffered_readings_ == 0) {
|
||||
if (no_readings_timeout_ > 0.0 &&
|
||||
(clock_->now() - last_reading_time_).seconds() >
|
||||
no_readings_timeout_)
|
||||
{
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"No range readings received for %.2f seconds, while expected at least every %.2f seconds.",
|
||||
(clock_->now() - last_reading_time_).seconds(),
|
||||
no_readings_timeout_);
|
||||
current_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RangeSensorLayer::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned char * master_array = master_grid.getCharMap();
|
||||
unsigned int span = master_grid.getSizeInCellsX();
|
||||
unsigned char clear = to_cost(clear_threshold_), mark = to_cost(mark_threshold_);
|
||||
|
||||
for (int j = min_j; j < max_j; j++) {
|
||||
unsigned int it = j * span + min_i;
|
||||
for (int i = min_i; i < max_i; i++) {
|
||||
unsigned char prob = costmap_[it];
|
||||
unsigned char current;
|
||||
if (prob == nav2_costmap_2d::NO_INFORMATION) {
|
||||
it++;
|
||||
continue;
|
||||
} else if (prob > mark) {
|
||||
current = nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
} else if (prob < clear) {
|
||||
current = nav2_costmap_2d::FREE_SPACE;
|
||||
} else {
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char old_cost = master_array[it];
|
||||
|
||||
if (old_cost == NO_INFORMATION || old_cost < current) {
|
||||
master_array[it] = current;
|
||||
}
|
||||
it++;
|
||||
}
|
||||
}
|
||||
|
||||
buffered_readings_ = 0;
|
||||
|
||||
// if not current due to reset, set current now after clearing
|
||||
if (!current_ && was_reset_) {
|
||||
was_reset_ = false;
|
||||
current_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void RangeSensorLayer::reset()
|
||||
{
|
||||
RCLCPP_DEBUG(logger_, "Reseting range sensor layer...");
|
||||
deactivate();
|
||||
resetMaps();
|
||||
was_reset_ = true;
|
||||
activate();
|
||||
}
|
||||
|
||||
void RangeSensorLayer::deactivate()
|
||||
{
|
||||
range_msgs_buffer_.clear();
|
||||
}
|
||||
|
||||
void RangeSensorLayer::activate()
|
||||
{
|
||||
range_msgs_buffer_.clear();
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,512 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* Copyright (c) 2015, Fetch Robotics, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
|
||||
#include "nav2_costmap_2d/static_layer.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
#include "tf2/convert.h"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "nav2_util/validate_messages.hpp"
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::StaticLayer, nav2_costmap_2d::Layer)
|
||||
|
||||
using nav2_costmap_2d::NO_INFORMATION;
|
||||
using nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
using nav2_costmap_2d::FREE_SPACE;
|
||||
using rcl_interfaces::msg::ParameterType;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
StaticLayer::StaticLayer()
|
||||
: map_buffer_(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
StaticLayer::~StaticLayer()
|
||||
{
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::onInitialize()
|
||||
{
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
|
||||
getParameters();
|
||||
|
||||
rclcpp::QoS map_qos(10); // initialize to default
|
||||
if (map_subscribe_transient_local_) {
|
||||
map_qos.transient_local();
|
||||
map_qos.reliable();
|
||||
map_qos.keep_last(1);
|
||||
}
|
||||
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"Subscribing to the map topic (%s) with %s durability",
|
||||
map_topic_.c_str(),
|
||||
map_subscribe_transient_local_ ? "transient local" : "volatile");
|
||||
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
map_sub_ = node->create_subscription<nav_msgs::msg::OccupancyGrid>(
|
||||
map_topic_, map_qos,
|
||||
std::bind(&StaticLayer::incomingMap, this, std::placeholders::_1));
|
||||
|
||||
if (subscribe_to_updates_) {
|
||||
RCLCPP_INFO(logger_, "Subscribing to updates");
|
||||
map_update_sub_ = node->create_subscription<map_msgs::msg::OccupancyGridUpdate>(
|
||||
map_topic_ + "_updates",
|
||||
rclcpp::SystemDefaultsQoS(),
|
||||
std::bind(&StaticLayer::incomingUpdate, this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::activate()
|
||||
{
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::deactivate()
|
||||
{
|
||||
dyn_params_handler_.reset();
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::reset()
|
||||
{
|
||||
has_updated_data_ = true;
|
||||
current_ = false;
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::getParameters()
|
||||
{
|
||||
int temp_lethal_threshold = 0;
|
||||
double temp_tf_tol = 0.0;
|
||||
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("subscribe_to_updates", rclcpp::ParameterValue(false));
|
||||
declareParameter("map_subscribe_transient_local", rclcpp::ParameterValue(true));
|
||||
declareParameter("transform_tolerance", rclcpp::ParameterValue(0.0));
|
||||
declareParameter("map_topic", rclcpp::ParameterValue(""));
|
||||
declareParameter("footprint_clearing_enabled", rclcpp::ParameterValue(false));
|
||||
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
node->get_parameter(name_ + "." + "subscribe_to_updates", subscribe_to_updates_);
|
||||
node->get_parameter(name_ + "." + "footprint_clearing_enabled", footprint_clearing_enabled_);
|
||||
std::string private_map_topic, global_map_topic;
|
||||
node->get_parameter(name_ + "." + "map_topic", private_map_topic);
|
||||
node->get_parameter("map_topic", global_map_topic);
|
||||
if (!private_map_topic.empty()) {
|
||||
map_topic_ = private_map_topic;
|
||||
} else {
|
||||
map_topic_ = global_map_topic;
|
||||
}
|
||||
node->get_parameter(
|
||||
name_ + "." + "map_subscribe_transient_local",
|
||||
map_subscribe_transient_local_);
|
||||
node->get_parameter("track_unknown_space", track_unknown_space_);
|
||||
node->get_parameter("use_maximum", use_maximum_);
|
||||
node->get_parameter("lethal_cost_threshold", temp_lethal_threshold);
|
||||
node->get_parameter("unknown_cost_value", unknown_cost_value_);
|
||||
node->get_parameter("trinary_costmap", trinary_costmap_);
|
||||
node->get_parameter("transform_tolerance", temp_tf_tol);
|
||||
|
||||
// Enforce bounds
|
||||
lethal_threshold_ = std::max(std::min(temp_lethal_threshold, 100), 0);
|
||||
map_received_ = false;
|
||||
map_received_in_update_bounds_ = false;
|
||||
|
||||
transform_tolerance_ = tf2::durationFromSec(temp_tf_tol);
|
||||
|
||||
// Add callback for dynamic parameters
|
||||
dyn_params_handler_ = node->add_on_set_parameters_callback(
|
||||
std::bind(
|
||||
&StaticLayer::dynamicParametersCallback,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::processMap(const nav_msgs::msg::OccupancyGrid & new_map)
|
||||
{
|
||||
RCLCPP_DEBUG(logger_, "StaticLayer: Process map");
|
||||
|
||||
unsigned int size_x = new_map.info.width;
|
||||
unsigned int size_y = new_map.info.height;
|
||||
|
||||
RCLCPP_DEBUG(
|
||||
logger_,
|
||||
"StaticLayer: Received a %d X %d map at %f m/pix", size_x, size_y,
|
||||
new_map.info.resolution);
|
||||
|
||||
// resize costmap if size, resolution or origin do not match
|
||||
Costmap2D * master = layered_costmap_->getCostmap();
|
||||
if (!layered_costmap_->isRolling() && (master->getSizeInCellsX() != size_x ||
|
||||
master->getSizeInCellsY() != size_y ||
|
||||
master->getResolution() != new_map.info.resolution ||
|
||||
master->getOriginX() != new_map.info.origin.position.x ||
|
||||
master->getOriginY() != new_map.info.origin.position.y ||
|
||||
!layered_costmap_->isSizeLocked()))
|
||||
{
|
||||
// Update the size of the layered costmap (and all layers, including this one)
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"StaticLayer: Resizing costmap to %d X %d at %f m/pix", size_x, size_y,
|
||||
new_map.info.resolution);
|
||||
layered_costmap_->resizeMap(
|
||||
size_x, size_y, new_map.info.resolution,
|
||||
new_map.info.origin.position.x,
|
||||
new_map.info.origin.position.y,
|
||||
true);
|
||||
} else if (size_x_ != size_x || size_y_ != size_y || // NOLINT
|
||||
resolution_ != new_map.info.resolution ||
|
||||
origin_x_ != new_map.info.origin.position.x ||
|
||||
origin_y_ != new_map.info.origin.position.y)
|
||||
{
|
||||
// only update the size of the costmap stored locally in this layer
|
||||
RCLCPP_INFO(
|
||||
logger_,
|
||||
"StaticLayer: Resizing static layer to %d X %d at %f m/pix", size_x, size_y,
|
||||
new_map.info.resolution);
|
||||
resizeMap(
|
||||
size_x, size_y, new_map.info.resolution,
|
||||
new_map.info.origin.position.x, new_map.info.origin.position.y);
|
||||
}
|
||||
|
||||
unsigned int index = 0;
|
||||
|
||||
// we have a new map, update full size of map
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
|
||||
// initialize the costmap with static data
|
||||
for (unsigned int i = 0; i < size_y; ++i) {
|
||||
for (unsigned int j = 0; j < size_x; ++j) {
|
||||
unsigned char value = new_map.data[index];
|
||||
costmap_[index] = interpretValue(value);
|
||||
++index;
|
||||
}
|
||||
}
|
||||
|
||||
map_frame_ = new_map.header.frame_id;
|
||||
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
has_updated_data_ = true;
|
||||
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::matchSize()
|
||||
{
|
||||
// If we are using rolling costmap, the static map size is
|
||||
// unrelated to the size of the layered costmap
|
||||
if (!layered_costmap_->isRolling()) {
|
||||
Costmap2D * master = layered_costmap_->getCostmap();
|
||||
resizeMap(
|
||||
master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
|
||||
master->getOriginX(), master->getOriginY());
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char
|
||||
StaticLayer::interpretValue(unsigned char value)
|
||||
{
|
||||
// check if the static value is above the unknown or lethal thresholds
|
||||
if (track_unknown_space_ && value == unknown_cost_value_) {
|
||||
return NO_INFORMATION;
|
||||
} else if (!track_unknown_space_ && value == unknown_cost_value_) {
|
||||
return FREE_SPACE;
|
||||
} else if (value >= lethal_threshold_) {
|
||||
return LETHAL_OBSTACLE;
|
||||
} else if (trinary_costmap_) {
|
||||
return FREE_SPACE;
|
||||
}
|
||||
|
||||
double scale = static_cast<double>(value) / lethal_threshold_;
|
||||
return scale * LETHAL_OBSTACLE;
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::incomingMap(const nav_msgs::msg::OccupancyGrid::SharedPtr new_map)
|
||||
{
|
||||
if (!nav2_util::validateMsg(*new_map)) {
|
||||
RCLCPP_ERROR(logger_, "Received map message is malformed. Rejecting.");
|
||||
return;
|
||||
}
|
||||
if (!map_received_) {
|
||||
processMap(*new_map);
|
||||
map_received_ = true;
|
||||
return;
|
||||
}
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
map_buffer_ = new_map;
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::incomingUpdate(map_msgs::msg::OccupancyGridUpdate::ConstSharedPtr update)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (update->y < static_cast<int32_t>(y_) ||
|
||||
y_ + height_ < update->y + update->height ||
|
||||
update->x < static_cast<int32_t>(x_) ||
|
||||
x_ + width_ < update->x + update->width)
|
||||
{
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"StaticLayer: Map update ignored. Exceeds bounds of static layer.\n"
|
||||
"Static layer origin: %d, %d bounds: %d X %d\n"
|
||||
"Update origin: %d, %d bounds: %d X %d",
|
||||
x_, y_, width_, height_, update->x, update->y, update->width,
|
||||
update->height);
|
||||
return;
|
||||
}
|
||||
|
||||
if (update->header.frame_id != map_frame_) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"StaticLayer: Map update ignored. Current map is in frame %s "
|
||||
"but update was in frame %s",
|
||||
map_frame_.c_str(), update->header.frame_id.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned int di = 0;
|
||||
for (unsigned int y = 0; y < update->height; y++) {
|
||||
unsigned int index_base = (update->y + y) * size_x_;
|
||||
for (unsigned int x = 0; x < update->width; x++) {
|
||||
unsigned int index = index_base + x + update->x;
|
||||
costmap_[index] = interpretValue(update->data[di++]);
|
||||
}
|
||||
}
|
||||
|
||||
has_updated_data_ = true;
|
||||
}
|
||||
|
||||
|
||||
void
|
||||
StaticLayer::updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y)
|
||||
{
|
||||
if (!map_received_) {
|
||||
map_received_in_update_bounds_ = false;
|
||||
return;
|
||||
}
|
||||
map_received_in_update_bounds_ = true;
|
||||
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
|
||||
// If there is a new available map, load it.
|
||||
if (map_buffer_) {
|
||||
processMap(*map_buffer_);
|
||||
map_buffer_ = nullptr;
|
||||
}
|
||||
|
||||
if (!layered_costmap_->isRolling() ) {
|
||||
if (!(has_updated_data_ || has_extra_bounds_)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
useExtraBounds(min_x, min_y, max_x, max_y);
|
||||
|
||||
double wx, wy;
|
||||
|
||||
mapToWorld(x_, y_, wx, wy);
|
||||
*min_x = std::min(wx, *min_x);
|
||||
*min_y = std::min(wy, *min_y);
|
||||
|
||||
mapToWorld(x_ + width_, y_ + height_, wx, wy);
|
||||
*max_x = std::max(wx, *max_x);
|
||||
*max_y = std::max(wy, *max_y);
|
||||
|
||||
has_updated_data_ = false;
|
||||
|
||||
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::updateFootprint(
|
||||
double robot_x, double robot_y, double robot_yaw,
|
||||
double * min_x, double * min_y,
|
||||
double * max_x,
|
||||
double * max_y)
|
||||
{
|
||||
if (!footprint_clearing_enabled_) {return;}
|
||||
|
||||
transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
|
||||
|
||||
for (unsigned int i = 0; i < transformed_footprint_.size(); i++) {
|
||||
touch(transformed_footprint_[i].x, transformed_footprint_[i].y, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
StaticLayer::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
if (!map_received_in_update_bounds_) {
|
||||
static int count = 0;
|
||||
// throttle warning down to only 1/10 message rate
|
||||
if (++count == 10) {
|
||||
RCLCPP_WARN(logger_, "Can't update static costmap layer, no map received");
|
||||
count = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (footprint_clearing_enabled_) {
|
||||
setConvexPolygonCost(transformed_footprint_, nav2_costmap_2d::FREE_SPACE);
|
||||
}
|
||||
|
||||
if (!layered_costmap_->isRolling()) {
|
||||
// if not rolling, the layered costmap (master_grid) has same coordinates as this layer
|
||||
if (!use_maximum_) {
|
||||
updateWithTrueOverwrite(master_grid, min_i, min_j, max_i, max_j);
|
||||
} else {
|
||||
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
|
||||
}
|
||||
} else {
|
||||
// If rolling window, the master_grid is unlikely to have same coordinates as this layer
|
||||
unsigned int mx, my;
|
||||
double wx, wy;
|
||||
// Might even be in a different frame
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
try {
|
||||
transform = tf_->lookupTransform(
|
||||
map_frame_, global_frame_, tf2::TimePointZero,
|
||||
transform_tolerance_);
|
||||
} catch (tf2::TransformException & ex) {
|
||||
RCLCPP_ERROR(logger_, "StaticLayer: %s", ex.what());
|
||||
return;
|
||||
}
|
||||
// Copy map data given proper transformations
|
||||
tf2::Transform tf2_transform;
|
||||
tf2::fromMsg(transform.transform, tf2_transform);
|
||||
|
||||
for (int i = min_i; i < max_i; ++i) {
|
||||
for (int j = min_j; j < max_j; ++j) {
|
||||
// Convert master_grid coordinates (i,j) into global_frame_(wx,wy) coordinates
|
||||
layered_costmap_->getCostmap()->mapToWorld(i, j, wx, wy);
|
||||
// Transform from global_frame_ to map_frame_
|
||||
tf2::Vector3 p(wx, wy, 0);
|
||||
p = tf2_transform * p;
|
||||
// Set master_grid with cell from map
|
||||
if (worldToMap(p.x(), p.y(), mx, my)) {
|
||||
if (!use_maximum_) {
|
||||
master_grid.setCost(i, j, getCost(mx, my));
|
||||
} else {
|
||||
master_grid.setCost(i, j, std::max(getCost(mx, my), master_grid.getCost(i, j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
StaticLayer::dynamicParametersCallback(
|
||||
std::vector<rclcpp::Parameter> parameters)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
rcl_interfaces::msg::SetParametersResult result;
|
||||
|
||||
for (auto parameter : parameters) {
|
||||
const auto & param_type = parameter.get_type();
|
||||
const auto & param_name = parameter.get_name();
|
||||
|
||||
if (param_name == name_ + "." + "map_subscribe_transient_local" ||
|
||||
param_name == name_ + "." + "map_topic" ||
|
||||
param_name == name_ + "." + "subscribe_to_updates")
|
||||
{
|
||||
RCLCPP_WARN(
|
||||
logger_, "%s is not a dynamic parameter "
|
||||
"cannot be changed while running. Rejecting parameter update.", param_name.c_str());
|
||||
} else if (param_type == ParameterType::PARAMETER_DOUBLE) {
|
||||
if (param_name == name_ + "." + "transform_tolerance") {
|
||||
transform_tolerance_ = tf2::durationFromSec(parameter.as_double());
|
||||
}
|
||||
} else if (param_type == ParameterType::PARAMETER_BOOL) {
|
||||
if (param_name == name_ + "." + "enabled" && enabled_ != parameter.as_bool()) {
|
||||
enabled_ = parameter.as_bool();
|
||||
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
has_updated_data_ = true;
|
||||
current_ = false;
|
||||
}
|
||||
} else if (param_type == ParameterType::PARAMETER_BOOL) {
|
||||
if (param_name == name_ + "." + "footprint_clearing_enabled") {
|
||||
footprint_clearing_enabled_ = parameter.as_bool();
|
||||
}
|
||||
}
|
||||
}
|
||||
result.successful = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,538 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
|
||||
#include "nav2_costmap_2d/voxel_layer.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
#include "sensor_msgs/point_cloud2_iterator.hpp"
|
||||
|
||||
#define VOXEL_BITS 16
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::VoxelLayer, nav2_costmap_2d::Layer)
|
||||
|
||||
using nav2_costmap_2d::NO_INFORMATION;
|
||||
using nav2_costmap_2d::LETHAL_OBSTACLE;
|
||||
using nav2_costmap_2d::FREE_SPACE;
|
||||
using rcl_interfaces::msg::ParameterType;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
void VoxelLayer::onInitialize()
|
||||
{
|
||||
ObstacleLayer::onInitialize();
|
||||
|
||||
declareParameter("enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("footprint_clearing_enabled", rclcpp::ParameterValue(true));
|
||||
declareParameter("max_obstacle_height", rclcpp::ParameterValue(2.0));
|
||||
declareParameter("z_voxels", rclcpp::ParameterValue(10));
|
||||
declareParameter("origin_z", rclcpp::ParameterValue(0.0));
|
||||
declareParameter("z_resolution", rclcpp::ParameterValue(0.2));
|
||||
declareParameter("unknown_threshold", rclcpp::ParameterValue(15));
|
||||
declareParameter("mark_threshold", rclcpp::ParameterValue(0));
|
||||
declareParameter("combination_method", rclcpp::ParameterValue(1));
|
||||
declareParameter("publish_voxel_map", rclcpp::ParameterValue(false));
|
||||
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
|
||||
node->get_parameter(name_ + "." + "enabled", enabled_);
|
||||
node->get_parameter(name_ + "." + "footprint_clearing_enabled", footprint_clearing_enabled_);
|
||||
node->get_parameter(name_ + "." + "max_obstacle_height", max_obstacle_height_);
|
||||
node->get_parameter(name_ + "." + "z_voxels", size_z_);
|
||||
node->get_parameter(name_ + "." + "origin_z", origin_z_);
|
||||
node->get_parameter(name_ + "." + "z_resolution", z_resolution_);
|
||||
node->get_parameter(name_ + "." + "unknown_threshold", unknown_threshold_);
|
||||
node->get_parameter(name_ + "." + "mark_threshold", mark_threshold_);
|
||||
node->get_parameter(name_ + "." + "combination_method", combination_method_);
|
||||
node->get_parameter(name_ + "." + "publish_voxel_map", publish_voxel_);
|
||||
|
||||
auto custom_qos = rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable();
|
||||
|
||||
if (publish_voxel_) {
|
||||
voxel_pub_ = node->create_publisher<nav2_msgs::msg::VoxelGrid>(
|
||||
"voxel_grid", custom_qos);
|
||||
voxel_pub_->on_activate();
|
||||
}
|
||||
|
||||
clearing_endpoints_pub_ = node->create_publisher<sensor_msgs::msg::PointCloud2>(
|
||||
"clearing_endpoints", custom_qos);
|
||||
clearing_endpoints_pub_->on_activate();
|
||||
|
||||
unknown_threshold_ += (VOXEL_BITS - size_z_);
|
||||
matchSize();
|
||||
|
||||
// Add callback for dynamic parameters
|
||||
dyn_params_handler_ = node->add_on_set_parameters_callback(
|
||||
std::bind(
|
||||
&VoxelLayer::dynamicParametersCallback,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
VoxelLayer::~VoxelLayer()
|
||||
{
|
||||
dyn_params_handler_.reset();
|
||||
}
|
||||
|
||||
void VoxelLayer::matchSize()
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
ObstacleLayer::matchSize();
|
||||
voxel_grid_.resize(size_x_, size_y_, size_z_);
|
||||
assert(voxel_grid_.sizeX() == size_x_ && voxel_grid_.sizeY() == size_y_);
|
||||
}
|
||||
|
||||
void VoxelLayer::reset()
|
||||
{
|
||||
// Call the base class method before adding our own functionality
|
||||
ObstacleLayer::reset();
|
||||
resetMaps();
|
||||
}
|
||||
|
||||
void VoxelLayer::resetMaps()
|
||||
{
|
||||
// Call the base class method before adding our own functionality
|
||||
// Note: at the time this was written, ObstacleLayer doesn't implement
|
||||
// resetMaps so this goes to the next layer down Costmap2DLayer which also
|
||||
// doesn't implement this, so it actually goes all the way to Costmap2D
|
||||
ObstacleLayer::resetMaps();
|
||||
voxel_grid_.reset();
|
||||
}
|
||||
|
||||
void VoxelLayer::updateBounds(
|
||||
double robot_x, double robot_y, double robot_yaw, double * min_x,
|
||||
double * min_y, double * max_x, double * max_y)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
|
||||
if (rolling_window_) {
|
||||
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
|
||||
}
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
useExtraBounds(min_x, min_y, max_x, max_y);
|
||||
|
||||
bool current = true;
|
||||
std::vector<Observation> observations, clearing_observations;
|
||||
|
||||
// get the marking observations
|
||||
current = getMarkingObservations(observations) && current;
|
||||
|
||||
// get the clearing observations
|
||||
current = getClearingObservations(clearing_observations) && current;
|
||||
|
||||
// update the global current status
|
||||
current_ = current;
|
||||
|
||||
// raytrace freespace
|
||||
for (unsigned int i = 0; i < clearing_observations.size(); ++i) {
|
||||
raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
// place the new obstacles into a priority queue... each with a priority of zero to begin with
|
||||
for (std::vector<Observation>::const_iterator it = observations.begin(); it != observations.end();
|
||||
++it)
|
||||
{
|
||||
const Observation & obs = *it;
|
||||
|
||||
const sensor_msgs::msg::PointCloud2 & cloud = *(obs.cloud_);
|
||||
|
||||
double sq_obstacle_max_range = obs.obstacle_max_range_ * obs.obstacle_max_range_;
|
||||
double sq_obstacle_min_range = obs.obstacle_min_range_ * obs.obstacle_min_range_;
|
||||
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
|
||||
|
||||
for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) {
|
||||
// if the obstacle is too high or too far away from the robot we won't add it
|
||||
if (*iter_z > max_obstacle_height_) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// compute the squared distance from the hitpoint to the pointcloud's origin
|
||||
double sq_dist = (*iter_x - obs.origin_.x) * (*iter_x - obs.origin_.x) +
|
||||
(*iter_y - obs.origin_.y) * (*iter_y - obs.origin_.y) +
|
||||
(*iter_z - obs.origin_.z) * (*iter_z - obs.origin_.z);
|
||||
|
||||
// if the point is far enough away... we won't consider it
|
||||
if (sq_dist >= sq_obstacle_max_range) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the point is too close, do not consider it
|
||||
if (sq_dist < sq_obstacle_min_range) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// now we need to compute the map coordinates for the observation
|
||||
unsigned int mx, my, mz;
|
||||
if (*iter_z < origin_z_) {
|
||||
if (!worldToMap3D(*iter_x, *iter_y, origin_z_, mx, my, mz)) {
|
||||
continue;
|
||||
}
|
||||
} else if (!worldToMap3D(*iter_x, *iter_y, *iter_z, mx, my, mz)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// mark the cell in the voxel grid and check if we should also mark it in the costmap
|
||||
if (voxel_grid_.markVoxelInMap(mx, my, mz, mark_threshold_)) {
|
||||
unsigned int index = getIndex(mx, my);
|
||||
|
||||
costmap_[index] = LETHAL_OBSTACLE;
|
||||
touch(
|
||||
static_cast<double>(*iter_x), static_cast<double>(*iter_y),
|
||||
min_x, min_y, max_x, max_y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (publish_voxel_) {
|
||||
auto grid_msg = std::make_unique<nav2_msgs::msg::VoxelGrid>();
|
||||
unsigned int size = voxel_grid_.sizeX() * voxel_grid_.sizeY();
|
||||
grid_msg->size_x = voxel_grid_.sizeX();
|
||||
grid_msg->size_y = voxel_grid_.sizeY();
|
||||
grid_msg->size_z = voxel_grid_.sizeZ();
|
||||
grid_msg->data.resize(size);
|
||||
memcpy(&grid_msg->data[0], voxel_grid_.getData(), size * sizeof(unsigned int));
|
||||
|
||||
grid_msg->origin.x = origin_x_;
|
||||
grid_msg->origin.y = origin_y_;
|
||||
grid_msg->origin.z = origin_z_;
|
||||
|
||||
grid_msg->resolutions.x = resolution_;
|
||||
grid_msg->resolutions.y = resolution_;
|
||||
grid_msg->resolutions.z = z_resolution_;
|
||||
grid_msg->header.frame_id = global_frame_;
|
||||
grid_msg->header.stamp = clock_->now();
|
||||
|
||||
voxel_pub_->publish(std::move(grid_msg));
|
||||
}
|
||||
|
||||
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
void VoxelLayer::raytraceFreespace(
|
||||
const Observation & clearing_observation, double * min_x,
|
||||
double * min_y,
|
||||
double * max_x,
|
||||
double * max_y)
|
||||
{
|
||||
auto clearing_endpoints_ = std::make_unique<sensor_msgs::msg::PointCloud2>();
|
||||
|
||||
if (clearing_observation.cloud_->height == 0 || clearing_observation.cloud_->width == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
double sensor_x, sensor_y, sensor_z;
|
||||
double ox = clearing_observation.origin_.x;
|
||||
double oy = clearing_observation.origin_.y;
|
||||
double oz = clearing_observation.origin_.z;
|
||||
|
||||
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z)) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"Sensor origin at (%.2f, %.2f %.2f) is out of map bounds "
|
||||
"(%.2f, %.2f, %.2f) to (%.2f, %.2f, %.2f). "
|
||||
"The costmap cannot raytrace for it.",
|
||||
ox, oy, oz,
|
||||
origin_x_, origin_y_, origin_z_,
|
||||
origin_x_ + getSizeInMetersX(), origin_y_ + getSizeInMetersY(),
|
||||
origin_z_ + getSizeInMetersZ());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
bool publish_clearing_points;
|
||||
|
||||
{
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
publish_clearing_points = (node->count_subscribers("clearing_endpoints") > 0);
|
||||
}
|
||||
|
||||
clearing_endpoints_->data.clear();
|
||||
clearing_endpoints_->width = clearing_observation.cloud_->width;
|
||||
clearing_endpoints_->height = clearing_observation.cloud_->height;
|
||||
clearing_endpoints_->is_dense = true;
|
||||
clearing_endpoints_->is_bigendian = false;
|
||||
|
||||
sensor_msgs::PointCloud2Modifier modifier(*clearing_endpoints_);
|
||||
modifier.setPointCloud2Fields(
|
||||
3, "x", 1, sensor_msgs::msg::PointField::FLOAT32,
|
||||
"y", 1, sensor_msgs::msg::PointField::FLOAT32,
|
||||
"z", 1, sensor_msgs::msg::PointField::FLOAT32);
|
||||
|
||||
sensor_msgs::PointCloud2Iterator<float> clearing_endpoints_iter_x(*clearing_endpoints_, "x");
|
||||
sensor_msgs::PointCloud2Iterator<float> clearing_endpoints_iter_y(*clearing_endpoints_, "y");
|
||||
sensor_msgs::PointCloud2Iterator<float> clearing_endpoints_iter_z(*clearing_endpoints_, "z");
|
||||
|
||||
// we can pre-compute the enpoints of the map outside of the inner loop... we'll need these later
|
||||
double map_end_x = origin_x_ + getSizeInMetersX();
|
||||
double map_end_y = origin_y_ + getSizeInMetersY();
|
||||
double map_end_z = origin_z_ + getSizeInMetersZ();
|
||||
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_x(*(clearing_observation.cloud_), "x");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_y(*(clearing_observation.cloud_), "y");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_z(*(clearing_observation.cloud_), "z");
|
||||
|
||||
for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) {
|
||||
double wpx = *iter_x;
|
||||
double wpy = *iter_y;
|
||||
double wpz = *iter_z;
|
||||
|
||||
double distance = dist(ox, oy, oz, wpx, wpy, wpz);
|
||||
double scaling_fact = 1.0;
|
||||
scaling_fact = std::max(std::min(scaling_fact, (distance - 2 * resolution_) / distance), 0.0);
|
||||
wpx = scaling_fact * (wpx - ox) + ox;
|
||||
wpy = scaling_fact * (wpy - oy) + oy;
|
||||
wpz = scaling_fact * (wpz - oz) + oz;
|
||||
|
||||
double a = wpx - ox;
|
||||
double b = wpy - oy;
|
||||
double c = wpz - oz;
|
||||
double t = 1.0;
|
||||
|
||||
// we can only raytrace to a maximum z height
|
||||
if (wpz > map_end_z) {
|
||||
// we know we want the vector's z value to be max_z
|
||||
t = std::max(0.0, std::min(t, (map_end_z - 0.01 - oz) / c));
|
||||
} else if (wpz < origin_z_) {
|
||||
// and we can only raytrace down to the floor
|
||||
// we know we want the vector's z value to be 0.0
|
||||
t = std::min(t, (origin_z_ - oz) / c);
|
||||
}
|
||||
|
||||
// the minimum value to raytrace from is the origin
|
||||
if (wpx < origin_x_) {
|
||||
t = std::min(t, (origin_x_ - ox) / a);
|
||||
}
|
||||
if (wpy < origin_y_) {
|
||||
t = std::min(t, (origin_y_ - oy) / b);
|
||||
}
|
||||
|
||||
// the maximum value to raytrace to is the end of the map
|
||||
if (wpx > map_end_x) {
|
||||
t = std::min(t, (map_end_x - ox) / a);
|
||||
}
|
||||
if (wpy > map_end_y) {
|
||||
t = std::min(t, (map_end_y - oy) / b);
|
||||
}
|
||||
|
||||
wpx = ox + a * t;
|
||||
wpy = oy + b * t;
|
||||
wpz = oz + c * t;
|
||||
|
||||
double point_x, point_y, point_z;
|
||||
if (worldToMap3DFloat(wpx, wpy, wpz, point_x, point_y, point_z)) {
|
||||
unsigned int cell_raytrace_max_range = cellDistance(clearing_observation.raytrace_max_range_);
|
||||
unsigned int cell_raytrace_min_range = cellDistance(clearing_observation.raytrace_min_range_);
|
||||
|
||||
|
||||
// voxel_grid_.markVoxelLine(sensor_x, sensor_y, sensor_z, point_x, point_y, point_z);
|
||||
voxel_grid_.clearVoxelLineInMap(
|
||||
sensor_x, sensor_y, sensor_z, point_x, point_y, point_z,
|
||||
costmap_,
|
||||
unknown_threshold_, mark_threshold_, FREE_SPACE, NO_INFORMATION,
|
||||
cell_raytrace_max_range, cell_raytrace_min_range);
|
||||
|
||||
updateRaytraceBounds(
|
||||
ox, oy, wpx, wpy, clearing_observation.raytrace_max_range_,
|
||||
clearing_observation.raytrace_min_range_, min_x, min_y,
|
||||
max_x,
|
||||
max_y);
|
||||
|
||||
if (publish_clearing_points) {
|
||||
*clearing_endpoints_iter_x = wpx;
|
||||
*clearing_endpoints_iter_y = wpy;
|
||||
*clearing_endpoints_iter_z = wpz;
|
||||
|
||||
++clearing_endpoints_iter_x;
|
||||
++clearing_endpoints_iter_y;
|
||||
++clearing_endpoints_iter_z;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (publish_clearing_points) {
|
||||
clearing_endpoints_->header.frame_id = global_frame_;
|
||||
clearing_endpoints_->header.stamp = clearing_observation.cloud_->header.stamp;
|
||||
|
||||
clearing_endpoints_pub_->publish(std::move(clearing_endpoints_));
|
||||
}
|
||||
}
|
||||
|
||||
void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
|
||||
{
|
||||
// project the new origin into the grid
|
||||
int cell_ox, cell_oy;
|
||||
cell_ox = static_cast<int>((new_origin_x - origin_x_) / resolution_);
|
||||
cell_oy = static_cast<int>((new_origin_y - origin_y_) / resolution_);
|
||||
|
||||
// compute the associated world coordinates for the origin cell
|
||||
// beacuase we want to keep things grid-aligned
|
||||
double new_grid_ox, new_grid_oy;
|
||||
new_grid_ox = origin_x_ + cell_ox * resolution_;
|
||||
new_grid_oy = origin_y_ + cell_oy * resolution_;
|
||||
|
||||
// To save casting from unsigned int to int a bunch of times
|
||||
int size_x = size_x_;
|
||||
int size_y = size_y_;
|
||||
|
||||
// we need to compute the overlap of the new and existing windows
|
||||
int lower_left_x, lower_left_y, upper_right_x, upper_right_y;
|
||||
lower_left_x = std::min(std::max(cell_ox, 0), size_x);
|
||||
lower_left_y = std::min(std::max(cell_oy, 0), size_y);
|
||||
upper_right_x = std::min(std::max(cell_ox + size_x, 0), size_x);
|
||||
upper_right_y = std::min(std::max(cell_oy + size_y, 0), size_y);
|
||||
|
||||
unsigned int cell_size_x = upper_right_x - lower_left_x;
|
||||
unsigned int cell_size_y = upper_right_y - lower_left_y;
|
||||
|
||||
// we need a map to store the obstacles in the window temporarily
|
||||
unsigned char * local_map = new unsigned char[cell_size_x * cell_size_y];
|
||||
unsigned int * local_voxel_map = new unsigned int[cell_size_x * cell_size_y];
|
||||
unsigned int * voxel_map = voxel_grid_.getData();
|
||||
|
||||
// copy the local window in the costmap to the local map
|
||||
copyMapRegion(
|
||||
costmap_, lower_left_x, lower_left_y, size_x_, local_map, 0, 0, cell_size_x,
|
||||
cell_size_x,
|
||||
cell_size_y);
|
||||
copyMapRegion(
|
||||
voxel_map, lower_left_x, lower_left_y, size_x_, local_voxel_map, 0, 0, cell_size_x,
|
||||
cell_size_x,
|
||||
cell_size_y);
|
||||
|
||||
// we'll reset our maps to unknown space if appropriate
|
||||
resetMaps();
|
||||
|
||||
// update the origin with the appropriate world coordinates
|
||||
origin_x_ = new_grid_ox;
|
||||
origin_y_ = new_grid_oy;
|
||||
|
||||
// compute the starting cell location for copying data back in
|
||||
int start_x = lower_left_x - cell_ox;
|
||||
int start_y = lower_left_y - cell_oy;
|
||||
|
||||
// now we want to copy the overlapping information back into the map, but in its new location
|
||||
copyMapRegion(
|
||||
local_map, 0, 0, cell_size_x, costmap_, start_x, start_y, size_x_, cell_size_x,
|
||||
cell_size_y);
|
||||
copyMapRegion(
|
||||
local_voxel_map, 0, 0, cell_size_x, voxel_map, start_x, start_y, size_x_,
|
||||
cell_size_x,
|
||||
cell_size_y);
|
||||
|
||||
// make sure to clean up
|
||||
delete[] local_map;
|
||||
delete[] local_voxel_map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Callback executed when a parameter change is detected
|
||||
* @param event ParameterEvent message
|
||||
*/
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
VoxelLayer::dynamicParametersCallback(
|
||||
std::vector<rclcpp::Parameter> parameters)
|
||||
{
|
||||
std::lock_guard<Costmap2D::mutex_t> guard(*getMutex());
|
||||
rcl_interfaces::msg::SetParametersResult result;
|
||||
bool resize_map_needed = false;
|
||||
|
||||
for (auto parameter : parameters) {
|
||||
const auto & param_type = parameter.get_type();
|
||||
const auto & param_name = parameter.get_name();
|
||||
|
||||
if (param_type == ParameterType::PARAMETER_DOUBLE) {
|
||||
if (param_name == name_ + "." + "max_obstacle_height") {
|
||||
max_obstacle_height_ = parameter.as_double();
|
||||
} else if (param_name == name_ + "." + "origin_z") {
|
||||
origin_z_ = parameter.as_double();
|
||||
resize_map_needed = true;
|
||||
} else if (param_name == name_ + "." + "z_resolution") {
|
||||
z_resolution_ = parameter.as_double();
|
||||
resize_map_needed = true;
|
||||
}
|
||||
} else if (param_type == ParameterType::PARAMETER_BOOL) {
|
||||
if (param_name == name_ + "." + "enabled") {
|
||||
enabled_ = parameter.as_bool();
|
||||
current_ = false;
|
||||
} else if (param_name == name_ + "." + "footprint_clearing_enabled") {
|
||||
footprint_clearing_enabled_ = parameter.as_bool();
|
||||
} else if (param_name == name_ + "." + "publish_voxel_map") {
|
||||
RCLCPP_WARN(
|
||||
logger_, "publish voxel map is not a dynamic parameter "
|
||||
"cannot be changed while running. Rejecting parameter update.");
|
||||
continue;
|
||||
}
|
||||
|
||||
} else if (param_type == ParameterType::PARAMETER_INTEGER) {
|
||||
if (param_name == name_ + "." + "z_voxels") {
|
||||
size_z_ = parameter.as_int();
|
||||
resize_map_needed = true;
|
||||
} else if (param_name == name_ + "." + "unknown_threshold") {
|
||||
unknown_threshold_ = parameter.as_int() + (VOXEL_BITS - size_z_);
|
||||
} else if (param_name == name_ + "." + "mark_threshold") {
|
||||
mark_threshold_ = parameter.as_int();
|
||||
} else if (param_name == name_ + "." + "combination_method") {
|
||||
combination_method_ = parameter.as_int();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (resize_map_needed) {
|
||||
matchSize();
|
||||
}
|
||||
|
||||
result.successful = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright (c) 2012, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* author: Dave Hershberger
|
||||
*/
|
||||
|
||||
#include <cstdio> // for EOF
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief Parse a vector of vector of floats from a string.
|
||||
* @param input
|
||||
* @param error_return
|
||||
* Syntax is [[1.0, 2.0], [3.3, 4.4, 5.5], ...] */
|
||||
std::vector<std::vector<float>> parseVVF(const std::string & input, std::string & error_return)
|
||||
{
|
||||
std::vector<std::vector<float>> result;
|
||||
|
||||
std::stringstream input_ss(input);
|
||||
int depth = 0;
|
||||
std::vector<float> current_vector;
|
||||
while (!!input_ss && !input_ss.eof()) {
|
||||
switch (input_ss.peek()) {
|
||||
case EOF:
|
||||
break;
|
||||
case '[':
|
||||
depth++;
|
||||
if (depth > 2) {
|
||||
error_return = "Array depth greater than 2";
|
||||
return result;
|
||||
}
|
||||
input_ss.get();
|
||||
current_vector.clear();
|
||||
break;
|
||||
case ']':
|
||||
depth--;
|
||||
if (depth < 0) {
|
||||
error_return = "More close ] than open [";
|
||||
return result;
|
||||
}
|
||||
input_ss.get();
|
||||
if (depth == 1) {
|
||||
result.push_back(current_vector);
|
||||
}
|
||||
break;
|
||||
case ',':
|
||||
case ' ':
|
||||
case '\t':
|
||||
input_ss.get();
|
||||
break;
|
||||
default: // All other characters should be part of the numbers.
|
||||
if (depth != 2) {
|
||||
std::stringstream err_ss;
|
||||
err_ss << "Numbers at depth other than 2. Char was '" << char(input_ss.peek()) << "'.";
|
||||
error_return = err_ss.str();
|
||||
return result;
|
||||
}
|
||||
float value;
|
||||
input_ss >> value;
|
||||
if (!!input_ss) {
|
||||
current_vector.push_back(value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (depth != 0) {
|
||||
error_return = "Unterminated vector string.";
|
||||
} else {
|
||||
error_return = "";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // end namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,167 @@
|
||||
// Copyright (c) 2018 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
|
||||
#include "nav2_costmap_2d/clear_costmap_service.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
using std::vector;
|
||||
using std::string;
|
||||
using std::shared_ptr;
|
||||
using std::any_of;
|
||||
using ClearExceptRegion = nav2_msgs::srv::ClearCostmapExceptRegion;
|
||||
using ClearAroundRobot = nav2_msgs::srv::ClearCostmapAroundRobot;
|
||||
using ClearEntirely = nav2_msgs::srv::ClearEntireCostmap;
|
||||
|
||||
ClearCostmapService::ClearCostmapService(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
Costmap2DROS & costmap)
|
||||
: costmap_(costmap)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
logger_ = node->get_logger();
|
||||
reset_value_ = costmap_.getCostmap()->getDefaultValue();
|
||||
|
||||
clear_except_service_ = node->create_service<ClearExceptRegion>(
|
||||
"clear_except_" + costmap_.getName(),
|
||||
std::bind(
|
||||
&ClearCostmapService::clearExceptRegionCallback, this,
|
||||
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
|
||||
|
||||
clear_around_service_ = node->create_service<ClearAroundRobot>(
|
||||
"clear_around_" + costmap.getName(),
|
||||
std::bind(
|
||||
&ClearCostmapService::clearAroundRobotCallback, this,
|
||||
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
|
||||
|
||||
clear_entire_service_ = node->create_service<ClearEntirely>(
|
||||
"clear_entirely_" + costmap_.getName(),
|
||||
std::bind(
|
||||
&ClearCostmapService::clearEntireCallback, this,
|
||||
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
|
||||
}
|
||||
|
||||
ClearCostmapService::~ClearCostmapService()
|
||||
{
|
||||
// make sure services shutdown.
|
||||
clear_except_service_.reset();
|
||||
clear_around_service_.reset();
|
||||
clear_entire_service_.reset();
|
||||
}
|
||||
|
||||
void ClearCostmapService::clearExceptRegionCallback(
|
||||
const shared_ptr<rmw_request_id_t>/*request_header*/,
|
||||
const shared_ptr<ClearExceptRegion::Request> request,
|
||||
const shared_ptr<ClearExceptRegion::Response>/*response*/)
|
||||
{
|
||||
RCLCPP_INFO(
|
||||
logger_, "%s",
|
||||
("Received request to clear except a region the " + costmap_.getName()).c_str());
|
||||
|
||||
clearRegion(request->reset_distance, true);
|
||||
}
|
||||
|
||||
void ClearCostmapService::clearAroundRobotCallback(
|
||||
const shared_ptr<rmw_request_id_t>/*request_header*/,
|
||||
const shared_ptr<ClearAroundRobot::Request> request,
|
||||
const shared_ptr<ClearAroundRobot::Response>/*response*/)
|
||||
{
|
||||
clearRegion(request->reset_distance, false);
|
||||
}
|
||||
|
||||
void ClearCostmapService::clearEntireCallback(
|
||||
const std::shared_ptr<rmw_request_id_t>/*request_header*/,
|
||||
const std::shared_ptr<ClearEntirely::Request>/*request*/,
|
||||
const std::shared_ptr<ClearEntirely::Response>/*response*/)
|
||||
{
|
||||
RCLCPP_INFO(
|
||||
logger_, "%s",
|
||||
("Received request to clear entirely the " + costmap_.getName()).c_str());
|
||||
|
||||
clearEntirely();
|
||||
}
|
||||
|
||||
void ClearCostmapService::clearRegion(const double reset_distance, bool invert)
|
||||
{
|
||||
double x, y;
|
||||
|
||||
if (!getPosition(x, y)) {
|
||||
RCLCPP_ERROR(
|
||||
logger_, "%s",
|
||||
"Cannot clear map because robot pose cannot be retrieved.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto layers = costmap_.getLayeredCostmap()->getPlugins();
|
||||
|
||||
for (auto & layer : *layers) {
|
||||
if (layer->isClearable()) {
|
||||
auto costmap_layer = std::static_pointer_cast<CostmapLayer>(layer);
|
||||
clearLayerRegion(costmap_layer, x, y, reset_distance, invert);
|
||||
}
|
||||
}
|
||||
|
||||
// AlexeyMerzlyakov: No need to clear layer region for costmap filters
|
||||
// as they are always supposed to be not clearable.
|
||||
}
|
||||
|
||||
void ClearCostmapService::clearLayerRegion(
|
||||
shared_ptr<CostmapLayer> & costmap, double pose_x, double pose_y, double reset_distance,
|
||||
bool invert)
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(costmap->getMutex()));
|
||||
|
||||
double start_point_x = pose_x - reset_distance / 2;
|
||||
double start_point_y = pose_y - reset_distance / 2;
|
||||
double end_point_x = start_point_x + reset_distance;
|
||||
double end_point_y = start_point_y + reset_distance;
|
||||
|
||||
int start_x, start_y, end_x, end_y;
|
||||
costmap->worldToMapEnforceBounds(start_point_x, start_point_y, start_x, start_y);
|
||||
costmap->worldToMapEnforceBounds(end_point_x, end_point_y, end_x, end_y);
|
||||
|
||||
costmap->clearArea(start_x, start_y, end_x, end_y, invert);
|
||||
|
||||
double ox = costmap->getOriginX(), oy = costmap->getOriginY();
|
||||
double width = costmap->getSizeInMetersX(), height = costmap->getSizeInMetersY();
|
||||
costmap->addExtraBounds(ox, oy, ox + width, oy + height);
|
||||
}
|
||||
|
||||
void ClearCostmapService::clearEntirely()
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(costmap_.getCostmap()->getMutex()));
|
||||
costmap_.resetLayers();
|
||||
}
|
||||
|
||||
bool ClearCostmapService::getPosition(double & x, double & y) const
|
||||
{
|
||||
geometry_msgs::msg::PoseStamped pose;
|
||||
if (!costmap_.getRobotPose(pose)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
x = pose.pose.position.x;
|
||||
y = pose.pose.position.y;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,556 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "nav2_util/occ_grid_values.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
Costmap2D::Costmap2D(
|
||||
unsigned int cells_size_x, unsigned int cells_size_y, double resolution,
|
||||
double origin_x, double origin_y, unsigned char default_value)
|
||||
: size_x_(cells_size_x), size_y_(cells_size_y), resolution_(resolution), origin_x_(origin_x),
|
||||
origin_y_(origin_y), costmap_(NULL), default_value_(default_value)
|
||||
{
|
||||
access_ = new mutex_t();
|
||||
|
||||
// create the costmap
|
||||
initMaps(size_x_, size_y_);
|
||||
resetMaps();
|
||||
}
|
||||
|
||||
Costmap2D::Costmap2D(const nav_msgs::msg::OccupancyGrid & map)
|
||||
: default_value_(FREE_SPACE)
|
||||
{
|
||||
access_ = new mutex_t();
|
||||
|
||||
// fill local variables
|
||||
size_x_ = map.info.width;
|
||||
size_y_ = map.info.height;
|
||||
resolution_ = map.info.resolution;
|
||||
origin_x_ = map.info.origin.position.x;
|
||||
origin_y_ = map.info.origin.position.y;
|
||||
|
||||
// create the costmap
|
||||
costmap_ = new unsigned char[size_x_ * size_y_];
|
||||
|
||||
// fill the costmap with a data
|
||||
int8_t data;
|
||||
for (unsigned int it = 0; it < size_x_ * size_y_; it++) {
|
||||
data = map.data[it];
|
||||
if (data == nav2_util::OCC_GRID_UNKNOWN) {
|
||||
costmap_[it] = NO_INFORMATION;
|
||||
} else {
|
||||
// Linear conversion from OccupancyGrid data range [OCC_GRID_FREE..OCC_GRID_OCCUPIED]
|
||||
// to costmap data range [FREE_SPACE..LETHAL_OBSTACLE]
|
||||
costmap_[it] = std::round(
|
||||
static_cast<double>(data) * (LETHAL_OBSTACLE - FREE_SPACE) /
|
||||
(nav2_util::OCC_GRID_OCCUPIED - nav2_util::OCC_GRID_FREE));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2D::deleteMaps()
|
||||
{
|
||||
// clean up data
|
||||
std::unique_lock<mutex_t> lock(*access_);
|
||||
delete[] costmap_;
|
||||
costmap_ = NULL;
|
||||
}
|
||||
|
||||
void Costmap2D::initMaps(unsigned int size_x, unsigned int size_y)
|
||||
{
|
||||
std::unique_lock<mutex_t> lock(*access_);
|
||||
delete[] costmap_;
|
||||
costmap_ = new unsigned char[size_x * size_y];
|
||||
}
|
||||
|
||||
void Costmap2D::resizeMap(
|
||||
unsigned int size_x, unsigned int size_y, double resolution,
|
||||
double origin_x, double origin_y)
|
||||
{
|
||||
size_x_ = size_x;
|
||||
size_y_ = size_y;
|
||||
resolution_ = resolution;
|
||||
origin_x_ = origin_x;
|
||||
origin_y_ = origin_y;
|
||||
|
||||
initMaps(size_x, size_y);
|
||||
|
||||
// reset our maps to have no information
|
||||
resetMaps();
|
||||
}
|
||||
|
||||
void Costmap2D::resetMaps()
|
||||
{
|
||||
std::unique_lock<mutex_t> lock(*access_);
|
||||
memset(costmap_, default_value_, size_x_ * size_y_ * sizeof(unsigned char));
|
||||
}
|
||||
|
||||
void Costmap2D::resetMap(unsigned int x0, unsigned int y0, unsigned int xn, unsigned int yn)
|
||||
{
|
||||
resetMapToValue(x0, y0, xn, yn, default_value_);
|
||||
}
|
||||
|
||||
void Costmap2D::resetMapToValue(
|
||||
unsigned int x0, unsigned int y0, unsigned int xn, unsigned int yn, unsigned char value)
|
||||
{
|
||||
std::unique_lock<mutex_t> lock(*(access_));
|
||||
unsigned int len = xn - x0;
|
||||
for (unsigned int y = y0 * size_x_ + x0; y < yn * size_x_ + x0; y += size_x_) {
|
||||
memset(costmap_ + y, value, len * sizeof(unsigned char));
|
||||
}
|
||||
}
|
||||
|
||||
bool Costmap2D::copyCostmapWindow(
|
||||
const Costmap2D & map, double win_origin_x, double win_origin_y,
|
||||
double win_size_x,
|
||||
double win_size_y)
|
||||
{
|
||||
// check for self windowing
|
||||
if (this == &map) {
|
||||
// ROS_ERROR("Cannot convert this costmap into a window of itself");
|
||||
return false;
|
||||
}
|
||||
|
||||
// clean up old data
|
||||
deleteMaps();
|
||||
|
||||
// compute the bounds of our new map
|
||||
unsigned int lower_left_x, lower_left_y, upper_right_x, upper_right_y;
|
||||
if (!map.worldToMap(win_origin_x, win_origin_y, lower_left_x, lower_left_y) ||
|
||||
!map.worldToMap(
|
||||
win_origin_x + win_size_x, win_origin_y + win_size_y, upper_right_x,
|
||||
upper_right_y))
|
||||
{
|
||||
// ROS_ERROR("Cannot window a map that the window bounds don't fit inside of");
|
||||
return false;
|
||||
}
|
||||
|
||||
size_x_ = upper_right_x - lower_left_x;
|
||||
size_y_ = upper_right_y - lower_left_y;
|
||||
resolution_ = map.resolution_;
|
||||
origin_x_ = win_origin_x;
|
||||
origin_y_ = win_origin_y;
|
||||
|
||||
// initialize our various maps and reset markers for inflation
|
||||
initMaps(size_x_, size_y_);
|
||||
|
||||
// copy the window of the static map and the costmap that we're taking
|
||||
copyMapRegion(
|
||||
map.costmap_, lower_left_x, lower_left_y, map.size_x_, costmap_, 0, 0, size_x_,
|
||||
size_x_,
|
||||
size_y_);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Costmap2D::copyWindow(
|
||||
const Costmap2D & source,
|
||||
unsigned int sx0, unsigned int sy0, unsigned int sxn, unsigned int syn,
|
||||
unsigned int dx0, unsigned int dy0)
|
||||
{
|
||||
const unsigned int sz_x = sxn - sx0;
|
||||
const unsigned int sz_y = syn - sy0;
|
||||
|
||||
if (sxn > source.getSizeInCellsX() || syn > source.getSizeInCellsY()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (dx0 + sz_x > size_x_ || dy0 + sz_y > size_y_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
copyMapRegion(
|
||||
source.costmap_, sx0, sy0, source.size_x_,
|
||||
costmap_, dx0, dy0, size_x_,
|
||||
sz_x, sz_y);
|
||||
return true;
|
||||
}
|
||||
|
||||
Costmap2D & Costmap2D::operator=(const Costmap2D & map)
|
||||
{
|
||||
// check for self assignement
|
||||
if (this == &map) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
// clean up old data
|
||||
deleteMaps();
|
||||
|
||||
size_x_ = map.size_x_;
|
||||
size_y_ = map.size_y_;
|
||||
resolution_ = map.resolution_;
|
||||
origin_x_ = map.origin_x_;
|
||||
origin_y_ = map.origin_y_;
|
||||
|
||||
// initialize our various maps
|
||||
initMaps(size_x_, size_y_);
|
||||
|
||||
// copy the cost map
|
||||
memcpy(costmap_, map.costmap_, size_x_ * size_y_ * sizeof(unsigned char));
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
Costmap2D::Costmap2D(const Costmap2D & map)
|
||||
: costmap_(NULL)
|
||||
{
|
||||
access_ = new mutex_t();
|
||||
*this = map;
|
||||
}
|
||||
|
||||
// just initialize everything to NULL by default
|
||||
Costmap2D::Costmap2D()
|
||||
: size_x_(0), size_y_(0), resolution_(0.0), origin_x_(0.0), origin_y_(0.0), costmap_(NULL)
|
||||
{
|
||||
access_ = new mutex_t();
|
||||
}
|
||||
|
||||
Costmap2D::~Costmap2D()
|
||||
{
|
||||
deleteMaps();
|
||||
delete access_;
|
||||
}
|
||||
|
||||
unsigned int Costmap2D::cellDistance(double world_dist)
|
||||
{
|
||||
double cells_dist = std::max(0.0, ceil(world_dist / resolution_));
|
||||
return (unsigned int)cells_dist;
|
||||
}
|
||||
|
||||
unsigned char * Costmap2D::getCharMap() const
|
||||
{
|
||||
return costmap_;
|
||||
}
|
||||
|
||||
unsigned char Costmap2D::getCost(unsigned int mx, unsigned int my) const
|
||||
{
|
||||
return costmap_[getIndex(mx, my)];
|
||||
}
|
||||
|
||||
unsigned char Costmap2D::getCost(unsigned int undex) const
|
||||
{
|
||||
return costmap_[undex];
|
||||
}
|
||||
|
||||
void Costmap2D::setCost(unsigned int mx, unsigned int my, unsigned char cost)
|
||||
{
|
||||
costmap_[getIndex(mx, my)] = cost;
|
||||
}
|
||||
|
||||
void Costmap2D::mapToWorld(unsigned int mx, unsigned int my, double & wx, double & wy) const
|
||||
{
|
||||
wx = origin_x_ + (mx + 0.5) * resolution_;
|
||||
wy = origin_y_ + (my + 0.5) * resolution_;
|
||||
}
|
||||
|
||||
bool Costmap2D::worldToMap(double wx, double wy, unsigned int & mx, unsigned int & my) const
|
||||
{
|
||||
if (wx < origin_x_ || wy < origin_y_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mx = static_cast<unsigned int>((wx - origin_x_) / resolution_);
|
||||
my = static_cast<unsigned int>((wy - origin_y_) / resolution_);
|
||||
|
||||
if (mx < size_x_ && my < size_y_) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void Costmap2D::worldToMapNoBounds(double wx, double wy, int & mx, int & my) const
|
||||
{
|
||||
mx = static_cast<int>((wx - origin_x_) / resolution_);
|
||||
my = static_cast<int>((wy - origin_y_) / resolution_);
|
||||
}
|
||||
|
||||
void Costmap2D::worldToMapEnforceBounds(double wx, double wy, int & mx, int & my) const
|
||||
{
|
||||
// Here we avoid doing any math to wx,wy before comparing them to
|
||||
// the bounds, so their values can go out to the max and min values
|
||||
// of double floating point.
|
||||
if (wx < origin_x_) {
|
||||
mx = 0;
|
||||
} else if (wx > resolution_ * size_x_ + origin_x_) {
|
||||
mx = size_x_ - 1;
|
||||
} else {
|
||||
mx = static_cast<int>((wx - origin_x_) / resolution_);
|
||||
}
|
||||
|
||||
if (wy < origin_y_) {
|
||||
my = 0;
|
||||
} else if (wy > resolution_ * size_y_ + origin_y_) {
|
||||
my = size_y_ - 1;
|
||||
} else {
|
||||
my = static_cast<int>((wy - origin_y_) / resolution_);
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2D::updateOrigin(double new_origin_x, double new_origin_y)
|
||||
{
|
||||
// project the new origin into the grid
|
||||
int cell_ox, cell_oy;
|
||||
cell_ox = static_cast<int>((new_origin_x - origin_x_) / resolution_);
|
||||
cell_oy = static_cast<int>((new_origin_y - origin_y_) / resolution_);
|
||||
|
||||
// compute the associated world coordinates for the origin cell
|
||||
// because we want to keep things grid-aligned
|
||||
double new_grid_ox, new_grid_oy;
|
||||
new_grid_ox = origin_x_ + cell_ox * resolution_;
|
||||
new_grid_oy = origin_y_ + cell_oy * resolution_;
|
||||
|
||||
// To save casting from unsigned int to int a bunch of times
|
||||
int size_x = size_x_;
|
||||
int size_y = size_y_;
|
||||
|
||||
// we need to compute the overlap of the new and existing windows
|
||||
int lower_left_x, lower_left_y, upper_right_x, upper_right_y;
|
||||
lower_left_x = std::min(std::max(cell_ox, 0), size_x);
|
||||
lower_left_y = std::min(std::max(cell_oy, 0), size_y);
|
||||
upper_right_x = std::min(std::max(cell_ox + size_x, 0), size_x);
|
||||
upper_right_y = std::min(std::max(cell_oy + size_y, 0), size_y);
|
||||
|
||||
unsigned int cell_size_x = upper_right_x - lower_left_x;
|
||||
unsigned int cell_size_y = upper_right_y - lower_left_y;
|
||||
|
||||
// we need a map to store the obstacles in the window temporarily
|
||||
unsigned char * local_map = new unsigned char[cell_size_x * cell_size_y];
|
||||
|
||||
// copy the local window in the costmap to the local map
|
||||
copyMapRegion(
|
||||
costmap_, lower_left_x, lower_left_y, size_x_, local_map, 0, 0, cell_size_x,
|
||||
cell_size_x,
|
||||
cell_size_y);
|
||||
|
||||
// now we'll set the costmap to be completely unknown if we track unknown space
|
||||
resetMaps();
|
||||
|
||||
// update the origin with the appropriate world coordinates
|
||||
origin_x_ = new_grid_ox;
|
||||
origin_y_ = new_grid_oy;
|
||||
|
||||
// compute the starting cell location for copying data back in
|
||||
int start_x = lower_left_x - cell_ox;
|
||||
int start_y = lower_left_y - cell_oy;
|
||||
|
||||
// now we want to copy the overlapping information back into the map, but in its new location
|
||||
copyMapRegion(
|
||||
local_map, 0, 0, cell_size_x, costmap_, start_x, start_y, size_x_, cell_size_x,
|
||||
cell_size_y);
|
||||
|
||||
// make sure to clean up
|
||||
delete[] local_map;
|
||||
}
|
||||
|
||||
bool Costmap2D::setConvexPolygonCost(
|
||||
const std::vector<geometry_msgs::msg::Point> & polygon,
|
||||
unsigned char cost_value)
|
||||
{
|
||||
// we assume the polygon is given in the global_frame...
|
||||
// we need to transform it to map coordinates
|
||||
std::vector<MapLocation> map_polygon;
|
||||
for (unsigned int i = 0; i < polygon.size(); ++i) {
|
||||
MapLocation loc;
|
||||
if (!worldToMap(polygon[i].x, polygon[i].y, loc.x, loc.y)) {
|
||||
// ("Polygon lies outside map bounds, so we can't fill it");
|
||||
return false;
|
||||
}
|
||||
map_polygon.push_back(loc);
|
||||
}
|
||||
|
||||
std::vector<MapLocation> polygon_cells;
|
||||
|
||||
// get the cells that fill the polygon
|
||||
convexFillCells(map_polygon, polygon_cells);
|
||||
|
||||
// set the cost of those cells
|
||||
for (unsigned int i = 0; i < polygon_cells.size(); ++i) {
|
||||
unsigned int index = getIndex(polygon_cells[i].x, polygon_cells[i].y);
|
||||
costmap_[index] = cost_value;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Costmap2D::polygonOutlineCells(
|
||||
const std::vector<MapLocation> & polygon,
|
||||
std::vector<MapLocation> & polygon_cells)
|
||||
{
|
||||
PolygonOutlineCells cell_gatherer(*this, costmap_, polygon_cells);
|
||||
for (unsigned int i = 0; i < polygon.size() - 1; ++i) {
|
||||
raytraceLine(cell_gatherer, polygon[i].x, polygon[i].y, polygon[i + 1].x, polygon[i + 1].y);
|
||||
}
|
||||
if (!polygon.empty()) {
|
||||
unsigned int last_index = polygon.size() - 1;
|
||||
// we also need to close the polygon by going from the last point to the first
|
||||
raytraceLine(
|
||||
cell_gatherer, polygon[last_index].x, polygon[last_index].y, polygon[0].x,
|
||||
polygon[0].y);
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2D::convexFillCells(
|
||||
const std::vector<MapLocation> & polygon,
|
||||
std::vector<MapLocation> & polygon_cells)
|
||||
{
|
||||
// we need a minimum polygon of a triangle
|
||||
if (polygon.size() < 3) {
|
||||
return;
|
||||
}
|
||||
|
||||
// first get the cells that make up the outline of the polygon
|
||||
polygonOutlineCells(polygon, polygon_cells);
|
||||
|
||||
// quick bubble sort to sort points by x
|
||||
MapLocation swap;
|
||||
unsigned int i = 0;
|
||||
while (i < polygon_cells.size() - 1) {
|
||||
if (polygon_cells[i].x > polygon_cells[i + 1].x) {
|
||||
swap = polygon_cells[i];
|
||||
polygon_cells[i] = polygon_cells[i + 1];
|
||||
polygon_cells[i + 1] = swap;
|
||||
|
||||
if (i > 0) {
|
||||
--i;
|
||||
}
|
||||
} else {
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
i = 0;
|
||||
MapLocation min_pt;
|
||||
MapLocation max_pt;
|
||||
unsigned int min_x = polygon_cells[0].x;
|
||||
unsigned int max_x = polygon_cells[polygon_cells.size() - 1].x;
|
||||
|
||||
// walk through each column and mark cells inside the polygon
|
||||
for (unsigned int x = min_x; x <= max_x; ++x) {
|
||||
if (i >= polygon_cells.size() - 1) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (polygon_cells[i].y < polygon_cells[i + 1].y) {
|
||||
min_pt = polygon_cells[i];
|
||||
max_pt = polygon_cells[i + 1];
|
||||
} else {
|
||||
min_pt = polygon_cells[i + 1];
|
||||
max_pt = polygon_cells[i];
|
||||
}
|
||||
|
||||
i += 2;
|
||||
while (i < polygon_cells.size() && polygon_cells[i].x == x) {
|
||||
if (polygon_cells[i].y < min_pt.y) {
|
||||
min_pt = polygon_cells[i];
|
||||
} else if (polygon_cells[i].y > max_pt.y) {
|
||||
max_pt = polygon_cells[i];
|
||||
}
|
||||
++i;
|
||||
}
|
||||
|
||||
MapLocation pt;
|
||||
// loop though cells in the column
|
||||
for (unsigned int y = min_pt.y; y <= max_pt.y; ++y) {
|
||||
pt.x = x;
|
||||
pt.y = y;
|
||||
polygon_cells.push_back(pt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int Costmap2D::getSizeInCellsX() const
|
||||
{
|
||||
return size_x_;
|
||||
}
|
||||
|
||||
unsigned int Costmap2D::getSizeInCellsY() const
|
||||
{
|
||||
return size_y_;
|
||||
}
|
||||
|
||||
double Costmap2D::getSizeInMetersX() const
|
||||
{
|
||||
return (size_x_ - 1 + 0.5) * resolution_;
|
||||
}
|
||||
|
||||
double Costmap2D::getSizeInMetersY() const
|
||||
{
|
||||
return (size_y_ - 1 + 0.5) * resolution_;
|
||||
}
|
||||
|
||||
double Costmap2D::getOriginX() const
|
||||
{
|
||||
return origin_x_;
|
||||
}
|
||||
|
||||
double Costmap2D::getOriginY() const
|
||||
{
|
||||
return origin_y_;
|
||||
}
|
||||
|
||||
double Costmap2D::getResolution() const
|
||||
{
|
||||
return resolution_;
|
||||
}
|
||||
|
||||
bool Costmap2D::saveMap(std::string file_name)
|
||||
{
|
||||
FILE * fp = fopen(file_name.c_str(), "w");
|
||||
|
||||
if (!fp) {
|
||||
return false;
|
||||
}
|
||||
|
||||
fprintf(fp, "P2\n%u\n%u\n%u\n", size_x_, size_y_, 0xff);
|
||||
for (unsigned int iy = 0; iy < size_y_; iy++) {
|
||||
for (unsigned int ix = 0; ix < size_x_; ix++) {
|
||||
unsigned char cost = getCost(ix, iy);
|
||||
fprintf(fp, "%d ", cost);
|
||||
}
|
||||
fprintf(fp, "\n");
|
||||
}
|
||||
fclose(fp);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,231 @@
|
||||
/*
|
||||
* Copyright (C) 2009, Willow Garage, Inc.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "sensor_msgs/msg/point_cloud2.hpp"
|
||||
#include "sensor_msgs/point_cloud2_iterator.hpp"
|
||||
#include "nav2_voxel_grid/voxel_grid.hpp"
|
||||
#include "nav2_msgs/msg/voxel_grid.hpp"
|
||||
#include "nav2_util/execution_timer.hpp"
|
||||
|
||||
static inline void mapToWorld3D(
|
||||
const unsigned int mx,
|
||||
const unsigned int my, const unsigned int mz,
|
||||
const double origin_x, const double origin_y, const double origin_z,
|
||||
const double x_resolution, const double y_resolution,
|
||||
const double z_resolution,
|
||||
double & wx, double & wy, double & wz)
|
||||
{
|
||||
// returns the center point of the cell
|
||||
wx = origin_x + (mx + 0.5) * x_resolution;
|
||||
wy = origin_y + (my + 0.5) * y_resolution;
|
||||
wz = origin_z + (mz + 0.5) * z_resolution;
|
||||
}
|
||||
|
||||
struct Cell
|
||||
{
|
||||
double x;
|
||||
double y;
|
||||
double z;
|
||||
nav2_voxel_grid::VoxelStatus status;
|
||||
};
|
||||
typedef std::vector<Cell> V_Cell;
|
||||
|
||||
float g_colors_r[] = {0.0f, 0.0f, 1.0f};
|
||||
float g_colors_g[] = {0.0f, 0.0f, 0.0f};
|
||||
float g_colors_b[] = {0.0f, 1.0f, 0.0f};
|
||||
float g_colors_a[] = {0.0f, 0.5f, 1.0f};
|
||||
|
||||
V_Cell g_marked;
|
||||
V_Cell g_unknown;
|
||||
|
||||
rclcpp::Node::SharedPtr g_node;
|
||||
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pub_marked;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pub_unknown;
|
||||
|
||||
/**
|
||||
* @brief An helper function to fill pointcloud2 of both the marked and unknown points from voxel_grid
|
||||
* @param cloud PointCloud2 Ptr which needs to be filled
|
||||
* @param num_channels Represents the total number of points that are going to be filled
|
||||
* @param header Carries the header information that needs to be assigned to PointCloud2 header
|
||||
* @param g_cells contains the x, y, z values that needs to be added to the PointCloud2
|
||||
*/
|
||||
void pointCloud2Helper(
|
||||
std::unique_ptr<sensor_msgs::msg::PointCloud2> & cloud,
|
||||
uint32_t num_channels,
|
||||
std_msgs::msg::Header header,
|
||||
V_Cell & g_cells)
|
||||
{
|
||||
cloud->header = header;
|
||||
cloud->width = num_channels;
|
||||
cloud->height = 1;
|
||||
cloud->is_dense = true;
|
||||
cloud->is_bigendian = false;
|
||||
sensor_msgs::PointCloud2Modifier modifier(*cloud);
|
||||
|
||||
modifier.setPointCloud2Fields(
|
||||
6, "x", 1, sensor_msgs::msg::PointField::FLOAT32,
|
||||
"y", 1, sensor_msgs::msg::PointField::FLOAT32,
|
||||
"z", 1, sensor_msgs::msg::PointField::FLOAT32,
|
||||
"r", 1, sensor_msgs::msg::PointField::UINT8,
|
||||
"g", 1, sensor_msgs::msg::PointField::UINT8,
|
||||
"b", 1, sensor_msgs::msg::PointField::UINT8);
|
||||
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_x(*cloud, "x");
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_y(*cloud, "y");
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_z(*cloud, "z");
|
||||
|
||||
sensor_msgs::PointCloud2Iterator<uint8_t> iter_r(*cloud, "r");
|
||||
sensor_msgs::PointCloud2Iterator<uint8_t> iter_g(*cloud, "g");
|
||||
sensor_msgs::PointCloud2Iterator<uint8_t> iter_b(*cloud, "b");
|
||||
|
||||
for (uint32_t i = 0; i < num_channels; ++i) {
|
||||
Cell & c = g_cells[i];
|
||||
// assigning value to the point cloud2's iterator
|
||||
*iter_x = c.x;
|
||||
*iter_y = c.y;
|
||||
*iter_z = c.z;
|
||||
*iter_r = g_colors_r[c.status] * 255.0;
|
||||
*iter_g = g_colors_g[c.status] * 255.0;
|
||||
*iter_b = g_colors_b[c.status] * 255.0;
|
||||
|
||||
++iter_x;
|
||||
++iter_y;
|
||||
++iter_z;
|
||||
++iter_r;
|
||||
++iter_g;
|
||||
++iter_b;
|
||||
}
|
||||
}
|
||||
|
||||
void voxelCallback(const nav2_msgs::msg::VoxelGrid::ConstSharedPtr grid)
|
||||
{
|
||||
if (grid->data.empty()) {
|
||||
RCLCPP_ERROR(g_node->get_logger(), "Received empty voxel grid");
|
||||
return;
|
||||
}
|
||||
|
||||
nav2_util::ExecutionTimer timer;
|
||||
timer.start();
|
||||
|
||||
RCLCPP_DEBUG(g_node->get_logger(), "Received voxel grid");
|
||||
const std::string frame_id = grid->header.frame_id;
|
||||
const rclcpp::Time stamp = grid->header.stamp;
|
||||
const uint32_t * data = &grid->data.front();
|
||||
const double x_origin = grid->origin.x;
|
||||
const double y_origin = grid->origin.y;
|
||||
const double z_origin = grid->origin.z;
|
||||
const double x_res = grid->resolutions.x;
|
||||
const double y_res = grid->resolutions.y;
|
||||
const double z_res = grid->resolutions.z;
|
||||
const uint32_t x_size = grid->size_x;
|
||||
const uint32_t y_size = grid->size_y;
|
||||
const uint32_t z_size = grid->size_z;
|
||||
|
||||
g_marked.clear();
|
||||
g_unknown.clear();
|
||||
uint32_t num_marked = 0;
|
||||
uint32_t num_unknown = 0;
|
||||
for (uint32_t y_grid = 0; y_grid < y_size; ++y_grid) {
|
||||
for (uint32_t x_grid = 0; x_grid < x_size; ++x_grid) {
|
||||
for (uint32_t z_grid = 0; z_grid < z_size; ++z_grid) {
|
||||
nav2_voxel_grid::VoxelStatus status =
|
||||
nav2_voxel_grid::VoxelGrid::getVoxel(
|
||||
x_grid, y_grid,
|
||||
z_grid, x_size, y_size, z_size, data);
|
||||
if (status == nav2_voxel_grid::UNKNOWN) {
|
||||
Cell c;
|
||||
c.status = status;
|
||||
mapToWorld3D(
|
||||
x_grid, y_grid, z_grid, x_origin, y_origin,
|
||||
z_origin, x_res, y_res, z_res, c.x, c.y, c.z);
|
||||
|
||||
g_unknown.push_back(c);
|
||||
|
||||
++num_unknown;
|
||||
} else if (status == nav2_voxel_grid::MARKED) {
|
||||
Cell c;
|
||||
c.status = status;
|
||||
mapToWorld3D(
|
||||
x_grid, y_grid, z_grid, x_origin, y_origin,
|
||||
z_origin, x_res, y_res, z_res, c.x, c.y, c.z);
|
||||
|
||||
g_marked.push_back(c);
|
||||
|
||||
++num_marked;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std_msgs::msg::Header pcl_header;
|
||||
pcl_header.frame_id = frame_id;
|
||||
pcl_header.stamp = stamp;
|
||||
|
||||
{
|
||||
auto cloud = std::make_unique<sensor_msgs::msg::PointCloud2>();
|
||||
pointCloud2Helper(cloud, num_marked, pcl_header, g_marked);
|
||||
pub_marked->publish(std::move(cloud));
|
||||
}
|
||||
|
||||
{
|
||||
auto cloud = std::make_unique<sensor_msgs::msg::PointCloud2>();
|
||||
pointCloud2Helper(cloud, num_unknown, pcl_header, g_unknown);
|
||||
pub_unknown->publish(std::move(cloud));
|
||||
}
|
||||
|
||||
timer.end();
|
||||
RCLCPP_DEBUG(
|
||||
g_node->get_logger(), "Published %d points in %f seconds",
|
||||
num_marked + num_unknown, timer.elapsed_time_in_seconds());
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
g_node = rclcpp::Node::make_shared("costmap_2d_cloud");
|
||||
|
||||
RCLCPP_DEBUG(g_node->get_logger(), "Starting up costmap_2d_cloud");
|
||||
|
||||
pub_marked = g_node->create_publisher<sensor_msgs::msg::PointCloud2>(
|
||||
"voxel_marked_cloud", 1);
|
||||
pub_unknown = g_node->create_publisher<sensor_msgs::msg::PointCloud2>(
|
||||
"voxel_unknown_cloud", 1);
|
||||
auto sub = g_node->create_subscription<nav2_msgs::msg::VoxelGrid>(
|
||||
"voxel_grid", rclcpp::SystemDefaultsQoS(), voxelCallback);
|
||||
|
||||
rclcpp::spin(g_node->get_node_base_interface());
|
||||
rclcpp::shutdown();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
* Steve Macenski
|
||||
*********************************************************************/
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "visualization_msgs/msg/marker.hpp"
|
||||
#include "nav2_msgs/msg/voxel_grid.hpp"
|
||||
#include "nav2_voxel_grid/voxel_grid.hpp"
|
||||
#include "nav2_util/execution_timer.hpp"
|
||||
|
||||
struct Cell
|
||||
{
|
||||
double x;
|
||||
double y;
|
||||
double z;
|
||||
nav2_voxel_grid::VoxelStatus status;
|
||||
};
|
||||
typedef std::vector<Cell> V_Cell;
|
||||
|
||||
float g_colors_r[] = {0.0f, 0.0f, 1.0f};
|
||||
float g_colors_g[] = {0.0f, 0.0f, 0.0f};
|
||||
float g_colors_b[] = {0.0f, 1.0f, 0.0f};
|
||||
float g_colors_a[] = {0.0f, 0.5f, 1.0f};
|
||||
|
||||
V_Cell g_cells;
|
||||
rclcpp::Node::SharedPtr g_node;
|
||||
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr pub;
|
||||
|
||||
void voxelCallback(const nav2_msgs::msg::VoxelGrid::ConstSharedPtr grid)
|
||||
{
|
||||
if (grid->data.empty()) {
|
||||
RCLCPP_ERROR(g_node->get_logger(), "Received voxel grid");
|
||||
return;
|
||||
}
|
||||
|
||||
nav2_util::ExecutionTimer timer;
|
||||
timer.start();
|
||||
|
||||
RCLCPP_DEBUG(g_node->get_logger(), "Received voxel grid");
|
||||
|
||||
const std::string frame_id = grid->header.frame_id;
|
||||
const rclcpp::Time stamp = grid->header.stamp;
|
||||
const uint32_t * data = &grid->data.front();
|
||||
const double x_origin = grid->origin.x;
|
||||
const double y_origin = grid->origin.y;
|
||||
const double z_origin = grid->origin.z;
|
||||
const double x_res = grid->resolutions.x;
|
||||
const double y_res = grid->resolutions.y;
|
||||
const double z_res = grid->resolutions.z;
|
||||
const uint32_t x_size = grid->size_x;
|
||||
const uint32_t y_size = grid->size_y;
|
||||
const uint32_t z_size = grid->size_z;
|
||||
|
||||
g_cells.clear();
|
||||
uint32_t num_markers = 0;
|
||||
for (uint32_t y_grid = 0; y_grid < y_size; ++y_grid) {
|
||||
for (uint32_t x_grid = 0; x_grid < x_size; ++x_grid) {
|
||||
for (uint32_t z_grid = 0; z_grid < z_size; ++z_grid) {
|
||||
nav2_voxel_grid::VoxelStatus status =
|
||||
nav2_voxel_grid::VoxelGrid::getVoxel(
|
||||
x_grid, y_grid,
|
||||
z_grid, x_size, y_size, z_size, data);
|
||||
if (status == nav2_voxel_grid::MARKED) {
|
||||
Cell c;
|
||||
c.status = status;
|
||||
c.x = x_origin + (x_grid + 0.5) * x_res;
|
||||
c.y = y_origin + (y_grid + 0.5) * y_res;
|
||||
c.z = z_origin + (z_grid + 0.5) * z_res;
|
||||
g_cells.push_back(c);
|
||||
|
||||
++num_markers;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto m = std::make_unique<visualization_msgs::msg::Marker>();
|
||||
m->header.frame_id = frame_id;
|
||||
m->header.stamp = stamp;
|
||||
m->ns = g_node->get_namespace();
|
||||
m->id = 0;
|
||||
m->type = visualization_msgs::msg::Marker::CUBE_LIST;
|
||||
m->action = visualization_msgs::msg::Marker::ADD;
|
||||
m->pose.orientation.w = 1.0;
|
||||
m->scale.x = x_res;
|
||||
m->scale.y = y_res;
|
||||
m->scale.z = z_res;
|
||||
m->color.r = g_colors_r[nav2_voxel_grid::MARKED];
|
||||
m->color.g = g_colors_g[nav2_voxel_grid::MARKED];
|
||||
m->color.b = g_colors_b[nav2_voxel_grid::MARKED];
|
||||
m->color.a = g_colors_a[nav2_voxel_grid::MARKED];
|
||||
m->points.resize(num_markers);
|
||||
for (uint32_t i = 0; i < num_markers; ++i) {
|
||||
Cell & c = g_cells[i];
|
||||
geometry_msgs::msg::Point & p = m->points[i];
|
||||
p.x = c.x;
|
||||
p.y = c.y;
|
||||
p.z = c.z;
|
||||
}
|
||||
|
||||
pub->publish(std::move(m));
|
||||
|
||||
timer.end();
|
||||
RCLCPP_INFO(
|
||||
g_node->get_logger(), "Published %d markers in %f seconds",
|
||||
num_markers, timer.elapsed_time_in_seconds());
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
g_node = rclcpp::Node::make_shared("costmap_2d_marker");
|
||||
|
||||
RCLCPP_DEBUG(g_node->get_logger(), "Starting costmap_2d_marker");
|
||||
|
||||
pub = g_node->create_publisher<visualization_msgs::msg::Marker>(
|
||||
"visualization_marker", 1);
|
||||
|
||||
auto sub = g_node->create_subscription<nav2_msgs::msg::VoxelGrid>(
|
||||
"voxel_grid", rclcpp::SystemDefaultsQoS(), voxelCallback);
|
||||
|
||||
rclcpp::spin(g_node->get_node_base_interface());
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#include <memory>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
auto node = std::make_shared<nav2_costmap_2d::Costmap2DROS>("costmap");
|
||||
rclcpp::spin(node->get_node_base_interface());
|
||||
rclcpp::shutdown();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* Copyright (c) 2019, Samsung Research America, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#include "nav2_costmap_2d/costmap_2d_publisher.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
char * Costmap2DPublisher::cost_translation_table_ = NULL;
|
||||
|
||||
Costmap2DPublisher::Costmap2DPublisher(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
Costmap2D * costmap,
|
||||
std::string global_frame,
|
||||
std::string topic_name,
|
||||
bool always_send_full_costmap)
|
||||
: costmap_(costmap),
|
||||
global_frame_(global_frame),
|
||||
topic_name_(topic_name),
|
||||
active_(false),
|
||||
always_send_full_costmap_(always_send_full_costmap)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
clock_ = node->get_clock();
|
||||
logger_ = node->get_logger();
|
||||
|
||||
auto custom_qos = rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable();
|
||||
|
||||
// TODO(bpwilcox): port onNewSubscription functionality for publisher
|
||||
costmap_pub_ = node->create_publisher<nav_msgs::msg::OccupancyGrid>(
|
||||
topic_name,
|
||||
custom_qos);
|
||||
costmap_raw_pub_ = node->create_publisher<nav2_msgs::msg::Costmap>(
|
||||
topic_name + "_raw",
|
||||
custom_qos);
|
||||
costmap_update_pub_ = node->create_publisher<map_msgs::msg::OccupancyGridUpdate>(
|
||||
topic_name + "_updates", custom_qos);
|
||||
|
||||
// Create a service that will use the callback function to handle requests.
|
||||
costmap_service_ = node->create_service<nav2_msgs::srv::GetCostmap>(
|
||||
"get_costmap", std::bind(
|
||||
&Costmap2DPublisher::costmap_service_callback,
|
||||
this, std::placeholders::_1, std::placeholders::_2,
|
||||
std::placeholders::_3));
|
||||
|
||||
if (cost_translation_table_ == NULL) {
|
||||
cost_translation_table_ = new char[256];
|
||||
|
||||
// special values:
|
||||
cost_translation_table_[0] = 0; // NO obstacle
|
||||
cost_translation_table_[253] = 99; // INSCRIBED obstacle
|
||||
cost_translation_table_[254] = 100; // LETHAL obstacle
|
||||
cost_translation_table_[255] = -1; // UNKNOWN
|
||||
|
||||
// regular cost values scale the range 1 to 252 (inclusive) to fit
|
||||
// into 1 to 98 (inclusive).
|
||||
for (int i = 1; i < 253; i++) {
|
||||
cost_translation_table_[i] = static_cast<char>(1 + (97 * (i - 1)) / 251);
|
||||
}
|
||||
}
|
||||
|
||||
xn_ = yn_ = 0;
|
||||
x0_ = costmap_->getSizeInCellsX();
|
||||
y0_ = costmap_->getSizeInCellsY();
|
||||
}
|
||||
|
||||
Costmap2DPublisher::~Costmap2DPublisher() {}
|
||||
|
||||
// TODO(bpwilcox): find equivalent/workaround to ros::SingleSubscriberPublishr
|
||||
/*
|
||||
void Costmap2DPublisher::onNewSubscription(const ros::SingleSubscriberPublisher& pub)
|
||||
{
|
||||
prepareGrid();
|
||||
pub.publish(grid_);
|
||||
} */
|
||||
|
||||
// prepare grid_ message for publication.
|
||||
void Costmap2DPublisher::prepareGrid()
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
|
||||
grid_resolution = costmap_->getResolution();
|
||||
grid_width = costmap_->getSizeInCellsX();
|
||||
grid_height = costmap_->getSizeInCellsY();
|
||||
|
||||
grid_ = std::make_unique<nav_msgs::msg::OccupancyGrid>();
|
||||
|
||||
grid_->header.frame_id = global_frame_;
|
||||
grid_->header.stamp = clock_->now();
|
||||
|
||||
grid_->info.resolution = grid_resolution;
|
||||
|
||||
grid_->info.width = grid_width;
|
||||
grid_->info.height = grid_height;
|
||||
|
||||
double wx, wy;
|
||||
costmap_->mapToWorld(0, 0, wx, wy);
|
||||
grid_->info.origin.position.x = wx - grid_resolution / 2;
|
||||
grid_->info.origin.position.y = wy - grid_resolution / 2;
|
||||
grid_->info.origin.position.z = 0.0;
|
||||
grid_->info.origin.orientation.w = 1.0;
|
||||
saved_origin_x_ = costmap_->getOriginX();
|
||||
saved_origin_y_ = costmap_->getOriginY();
|
||||
|
||||
grid_->data.resize(grid_->info.width * grid_->info.height);
|
||||
|
||||
unsigned char * data = costmap_->getCharMap();
|
||||
for (unsigned int i = 0; i < grid_->data.size(); i++) {
|
||||
grid_->data[i] = cost_translation_table_[data[i]];
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2DPublisher::prepareCostmap()
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
|
||||
double resolution = costmap_->getResolution();
|
||||
|
||||
costmap_raw_ = std::make_unique<nav2_msgs::msg::Costmap>();
|
||||
|
||||
costmap_raw_->header.frame_id = global_frame_;
|
||||
costmap_raw_->header.stamp = clock_->now();
|
||||
|
||||
costmap_raw_->metadata.layer = "master";
|
||||
costmap_raw_->metadata.resolution = resolution;
|
||||
|
||||
costmap_raw_->metadata.size_x = costmap_->getSizeInCellsX();
|
||||
costmap_raw_->metadata.size_y = costmap_->getSizeInCellsY();
|
||||
|
||||
double wx, wy;
|
||||
costmap_->mapToWorld(0, 0, wx, wy);
|
||||
costmap_raw_->metadata.origin.position.x = wx - resolution / 2;
|
||||
costmap_raw_->metadata.origin.position.y = wy - resolution / 2;
|
||||
costmap_raw_->metadata.origin.position.z = 0.0;
|
||||
costmap_raw_->metadata.origin.orientation.w = 1.0;
|
||||
|
||||
costmap_raw_->data.resize(costmap_raw_->metadata.size_x * costmap_raw_->metadata.size_y);
|
||||
|
||||
unsigned char * data = costmap_->getCharMap();
|
||||
for (unsigned int i = 0; i < costmap_raw_->data.size(); i++) {
|
||||
costmap_raw_->data[i] = data[i];
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2DPublisher::publishCostmap()
|
||||
{
|
||||
if (costmap_raw_pub_->get_subscription_count() > 0) {
|
||||
prepareCostmap();
|
||||
costmap_raw_pub_->publish(std::move(costmap_raw_));
|
||||
}
|
||||
float resolution = costmap_->getResolution();
|
||||
|
||||
if (always_send_full_costmap_ || grid_resolution != resolution ||
|
||||
grid_width != costmap_->getSizeInCellsX() ||
|
||||
grid_height != costmap_->getSizeInCellsY() ||
|
||||
saved_origin_x_ != costmap_->getOriginX() ||
|
||||
saved_origin_y_ != costmap_->getOriginY())
|
||||
{
|
||||
if (costmap_pub_->get_subscription_count() > 0) {
|
||||
prepareGrid();
|
||||
costmap_pub_->publish(std::move(grid_));
|
||||
}
|
||||
} else if (x0_ < xn_) {
|
||||
if (costmap_update_pub_->get_subscription_count() > 0) {
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
|
||||
// Publish Just an Update
|
||||
auto update = std::make_unique<map_msgs::msg::OccupancyGridUpdate>();
|
||||
update->header.stamp = rclcpp::Time();
|
||||
update->header.frame_id = global_frame_;
|
||||
update->x = x0_;
|
||||
update->y = y0_;
|
||||
update->width = xn_ - x0_;
|
||||
update->height = yn_ - y0_;
|
||||
update->data.resize(update->width * update->height);
|
||||
unsigned int i = 0;
|
||||
for (unsigned int y = y0_; y < yn_; y++) {
|
||||
for (unsigned int x = x0_; x < xn_; x++) {
|
||||
unsigned char cost = costmap_->getCost(x, y);
|
||||
update->data[i++] = cost_translation_table_[cost];
|
||||
}
|
||||
}
|
||||
costmap_update_pub_->publish(std::move(update));
|
||||
}
|
||||
}
|
||||
|
||||
xn_ = yn_ = 0;
|
||||
x0_ = costmap_->getSizeInCellsX();
|
||||
y0_ = costmap_->getSizeInCellsY();
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DPublisher::costmap_service_callback(
|
||||
const std::shared_ptr<rmw_request_id_t>/*request_header*/,
|
||||
const std::shared_ptr<nav2_msgs::srv::GetCostmap::Request>/*request*/,
|
||||
const std::shared_ptr<nav2_msgs::srv::GetCostmap::Response> response)
|
||||
{
|
||||
RCLCPP_DEBUG(logger_, "Received costmap service request");
|
||||
|
||||
// TODO(bpwilcox): Grab correct orientation information
|
||||
tf2::Quaternion quaternion;
|
||||
quaternion.setRPY(0.0, 0.0, 0.0);
|
||||
|
||||
auto size_x = costmap_->getSizeInCellsX();
|
||||
auto size_y = costmap_->getSizeInCellsY();
|
||||
auto data_length = size_x * size_y;
|
||||
unsigned char * data = costmap_->getCharMap();
|
||||
auto current_time = clock_->now();
|
||||
|
||||
response->map.header.stamp = current_time;
|
||||
response->map.header.frame_id = global_frame_;
|
||||
response->map.metadata.size_x = size_x;
|
||||
response->map.metadata.size_y = size_y;
|
||||
response->map.metadata.resolution = costmap_->getResolution();
|
||||
response->map.metadata.layer = "master";
|
||||
response->map.metadata.map_load_time = current_time;
|
||||
response->map.metadata.update_time = current_time;
|
||||
response->map.metadata.origin.position.x = costmap_->getOriginX();
|
||||
response->map.metadata.origin.position.y = costmap_->getOriginY();
|
||||
response->map.metadata.origin.position.z = 0.0;
|
||||
response->map.metadata.origin.orientation = tf2::toMsg(quaternion);
|
||||
response->map.data.resize(data_length);
|
||||
response->map.data.assign(data, data + data_length);
|
||||
}
|
||||
|
||||
} // end namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,769 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_util/execution_timer.hpp"
|
||||
#include "nav2_util/node_utils.hpp"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "tf2_ros/create_timer_ros.h"
|
||||
#include "nav2_util/robot_utils.hpp"
|
||||
#include "rcl_interfaces/msg/set_parameters_result.hpp"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using std::placeholders::_1;
|
||||
using rcl_interfaces::msg::ParameterType;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
Costmap2DROS::Costmap2DROS(const std::string & name)
|
||||
: Costmap2DROS(name, "/", name) {}
|
||||
|
||||
Costmap2DROS::Costmap2DROS(const rclcpp::NodeOptions & options)
|
||||
: nav2_util::LifecycleNode("costmap", "", options),
|
||||
name_("costmap"),
|
||||
default_plugins_{"static_layer", "obstacle_layer", "inflation_layer"},
|
||||
default_types_{
|
||||
"nav2_costmap_2d::StaticLayer",
|
||||
"nav2_costmap_2d::ObstacleLayer",
|
||||
"nav2_costmap_2d::InflationLayer"}
|
||||
{
|
||||
is_lifecycle_follower_ = false;
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Creating Costmap");
|
||||
|
||||
declare_parameter("always_send_full_costmap", rclcpp::ParameterValue(false));
|
||||
declare_parameter("footprint_padding", rclcpp::ParameterValue(0.01f));
|
||||
declare_parameter("footprint", rclcpp::ParameterValue(std::string("[]")));
|
||||
declare_parameter("global_frame", rclcpp::ParameterValue(std::string("map")));
|
||||
declare_parameter("height", rclcpp::ParameterValue(5));
|
||||
declare_parameter("width", rclcpp::ParameterValue(5));
|
||||
declare_parameter("lethal_cost_threshold", rclcpp::ParameterValue(100));
|
||||
declare_parameter(
|
||||
"map_topic", rclcpp::ParameterValue(
|
||||
(parent_namespace_ == "/" ? "/" : parent_namespace_ + "/") + std::string("map")));
|
||||
declare_parameter("observation_sources", rclcpp::ParameterValue(std::string("")));
|
||||
declare_parameter("origin_x", rclcpp::ParameterValue(0.0));
|
||||
declare_parameter("origin_y", rclcpp::ParameterValue(0.0));
|
||||
declare_parameter("plugins", rclcpp::ParameterValue(default_plugins_));
|
||||
declare_parameter("filters", rclcpp::ParameterValue(std::vector<std::string>()));
|
||||
declare_parameter("publish_frequency", rclcpp::ParameterValue(1.0));
|
||||
declare_parameter("resolution", rclcpp::ParameterValue(0.1));
|
||||
declare_parameter("robot_base_frame", rclcpp::ParameterValue(std::string("base_link")));
|
||||
declare_parameter("robot_radius", rclcpp::ParameterValue(0.1));
|
||||
declare_parameter("rolling_window", rclcpp::ParameterValue(false));
|
||||
declare_parameter("track_unknown_space", rclcpp::ParameterValue(false));
|
||||
declare_parameter("transform_tolerance", rclcpp::ParameterValue(0.3));
|
||||
declare_parameter("trinary_costmap", rclcpp::ParameterValue(true));
|
||||
declare_parameter("unknown_cost_value", rclcpp::ParameterValue(static_cast<unsigned char>(0xff)));
|
||||
declare_parameter("update_frequency", rclcpp::ParameterValue(5.0));
|
||||
declare_parameter("use_maximum", rclcpp::ParameterValue(false));
|
||||
}
|
||||
|
||||
Costmap2DROS::Costmap2DROS(
|
||||
const std::string & name,
|
||||
const std::string & parent_namespace,
|
||||
const std::string & local_namespace)
|
||||
: nav2_util::LifecycleNode(name, "",
|
||||
// NodeOption arguments take precedence over the ones provided on the command line
|
||||
// use this to make sure the node is placed on the provided namespace
|
||||
// TODO(orduno) Pass a sub-node instead of creating a new node for better handling
|
||||
// of the namespaces
|
||||
rclcpp::NodeOptions().arguments({
|
||||
"--ros-args", "-r", std::string("__ns:=") +
|
||||
nav2_util::add_namespaces(parent_namespace, local_namespace),
|
||||
"--ros-args", "-r", name + ":" + std::string("__node:=") + name
|
||||
})),
|
||||
name_(name),
|
||||
parent_namespace_(parent_namespace),
|
||||
default_plugins_{"static_layer", "obstacle_layer", "inflation_layer"},
|
||||
default_types_{
|
||||
"nav2_costmap_2d::StaticLayer",
|
||||
"nav2_costmap_2d::ObstacleLayer",
|
||||
"nav2_costmap_2d::InflationLayer"}
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Creating Costmap");
|
||||
|
||||
declare_parameter("always_send_full_costmap", rclcpp::ParameterValue(false));
|
||||
declare_parameter("footprint_padding", rclcpp::ParameterValue(0.01f));
|
||||
declare_parameter("footprint", rclcpp::ParameterValue(std::string("[]")));
|
||||
declare_parameter("global_frame", rclcpp::ParameterValue(std::string("map")));
|
||||
declare_parameter("height", rclcpp::ParameterValue(5));
|
||||
declare_parameter("width", rclcpp::ParameterValue(5));
|
||||
declare_parameter("lethal_cost_threshold", rclcpp::ParameterValue(100));
|
||||
declare_parameter(
|
||||
"map_topic", rclcpp::ParameterValue(
|
||||
(parent_namespace_ == "/" ? "/" : parent_namespace_ + "/") + std::string("map")));
|
||||
declare_parameter("observation_sources", rclcpp::ParameterValue(std::string("")));
|
||||
declare_parameter("origin_x", rclcpp::ParameterValue(0.0));
|
||||
declare_parameter("origin_y", rclcpp::ParameterValue(0.0));
|
||||
declare_parameter("plugins", rclcpp::ParameterValue(default_plugins_));
|
||||
declare_parameter("filters", rclcpp::ParameterValue(std::vector<std::string>()));
|
||||
declare_parameter("publish_frequency", rclcpp::ParameterValue(1.0));
|
||||
declare_parameter("resolution", rclcpp::ParameterValue(0.1));
|
||||
declare_parameter("robot_base_frame", rclcpp::ParameterValue(std::string("base_link")));
|
||||
declare_parameter("robot_radius", rclcpp::ParameterValue(0.1));
|
||||
declare_parameter("rolling_window", rclcpp::ParameterValue(false));
|
||||
declare_parameter("track_unknown_space", rclcpp::ParameterValue(false));
|
||||
declare_parameter("transform_tolerance", rclcpp::ParameterValue(0.3));
|
||||
declare_parameter("trinary_costmap", rclcpp::ParameterValue(true));
|
||||
declare_parameter("unknown_cost_value", rclcpp::ParameterValue(static_cast<unsigned char>(0xff)));
|
||||
declare_parameter("update_frequency", rclcpp::ParameterValue(5.0));
|
||||
declare_parameter("use_maximum", rclcpp::ParameterValue(false));
|
||||
}
|
||||
|
||||
Costmap2DROS::~Costmap2DROS()
|
||||
{
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
Costmap2DROS::on_configure(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Configuring");
|
||||
getParameters();
|
||||
|
||||
callback_group_ = create_callback_group(
|
||||
rclcpp::CallbackGroupType::MutuallyExclusive, false);
|
||||
|
||||
// Create the costmap itself
|
||||
layered_costmap_ = std::make_unique<LayeredCostmap>(
|
||||
global_frame_, rolling_window_, track_unknown_space_);
|
||||
|
||||
if (!layered_costmap_->isSizeLocked()) {
|
||||
layered_costmap_->resizeMap(
|
||||
(unsigned int)(map_width_meters_ / resolution_),
|
||||
(unsigned int)(map_height_meters_ / resolution_), resolution_, origin_x_, origin_y_);
|
||||
}
|
||||
|
||||
// Create the transform-related objects
|
||||
tf_buffer_ = std::make_shared<tf2_ros::Buffer>(get_clock());
|
||||
auto timer_interface = std::make_shared<tf2_ros::CreateTimerROS>(
|
||||
get_node_base_interface(),
|
||||
get_node_timers_interface(),
|
||||
callback_group_);
|
||||
tf_buffer_->setCreateTimerInterface(timer_interface);
|
||||
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
|
||||
|
||||
// Then load and add the plug-ins to the costmap
|
||||
for (unsigned int i = 0; i < plugin_names_.size(); ++i) {
|
||||
RCLCPP_INFO(get_logger(), "Using plugin \"%s\"", plugin_names_[i].c_str());
|
||||
|
||||
std::shared_ptr<Layer> plugin = plugin_loader_.createSharedInstance(plugin_types_[i]);
|
||||
|
||||
// lock the costmap because no update is allowed until the plugin is initialized
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(layered_costmap_->getCostmap()->getMutex()));
|
||||
|
||||
layered_costmap_->addPlugin(plugin);
|
||||
|
||||
// TODO(mjeronimo): instead of get(), use a shared ptr
|
||||
plugin->initialize(
|
||||
layered_costmap_.get(), plugin_names_[i], tf_buffer_.get(),
|
||||
shared_from_this(), callback_group_);
|
||||
|
||||
lock.unlock();
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Initialized plugin \"%s\"", plugin_names_[i].c_str());
|
||||
}
|
||||
// and costmap filters as well
|
||||
for (unsigned int i = 0; i < filter_names_.size(); ++i) {
|
||||
RCLCPP_INFO(get_logger(), "Using costmap filter \"%s\"", filter_names_[i].c_str());
|
||||
|
||||
std::shared_ptr<Layer> filter = plugin_loader_.createSharedInstance(filter_types_[i]);
|
||||
|
||||
// lock the costmap because no update is allowed until the filter is initialized
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(layered_costmap_->getCostmap()->getMutex()));
|
||||
|
||||
layered_costmap_->addFilter(filter);
|
||||
|
||||
filter->initialize(
|
||||
layered_costmap_.get(), filter_names_[i], tf_buffer_.get(),
|
||||
shared_from_this(), callback_group_);
|
||||
|
||||
lock.unlock();
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Initialized costmap filter \"%s\"", filter_names_[i].c_str());
|
||||
}
|
||||
|
||||
// Create the publishers and subscribers
|
||||
footprint_sub_ = create_subscription<geometry_msgs::msg::Polygon>(
|
||||
"footprint",
|
||||
rclcpp::SystemDefaultsQoS(),
|
||||
std::bind(&Costmap2DROS::setRobotFootprintPolygon, this, std::placeholders::_1));
|
||||
|
||||
footprint_pub_ = create_publisher<geometry_msgs::msg::PolygonStamped>(
|
||||
"published_footprint", rclcpp::SystemDefaultsQoS());
|
||||
|
||||
costmap_publisher_ = std::make_unique<Costmap2DPublisher>(
|
||||
shared_from_this(),
|
||||
layered_costmap_->getCostmap(), global_frame_,
|
||||
"costmap", always_send_full_costmap_);
|
||||
|
||||
// Set the footprint
|
||||
if (use_radius_) {
|
||||
setRobotFootprint(makeFootprintFromRadius(robot_radius_));
|
||||
} else {
|
||||
std::vector<geometry_msgs::msg::Point> new_footprint;
|
||||
makeFootprintFromString(footprint_, new_footprint);
|
||||
setRobotFootprint(new_footprint);
|
||||
}
|
||||
|
||||
// Add cleaning service
|
||||
clear_costmap_service_ = std::make_unique<ClearCostmapService>(shared_from_this(), *this);
|
||||
|
||||
executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
|
||||
executor_->add_callback_group(callback_group_, get_node_base_interface());
|
||||
executor_thread_ = std::make_unique<nav2_util::NodeThread>(executor_);
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
Costmap2DROS::on_activate(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Activating");
|
||||
|
||||
costmap_publisher_->on_activate();
|
||||
footprint_pub_->on_activate();
|
||||
|
||||
// First, make sure that the transform between the robot base frame
|
||||
// and the global frame is available
|
||||
|
||||
std::string tf_error;
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Checking transform");
|
||||
rclcpp::Rate r(2);
|
||||
while (rclcpp::ok() &&
|
||||
!tf_buffer_->canTransform(
|
||||
global_frame_, robot_base_frame_, tf2::TimePointZero, &tf_error))
|
||||
{
|
||||
RCLCPP_INFO(
|
||||
get_logger(), "Timed out waiting for transform from %s to %s"
|
||||
" to become available, tf error: %s",
|
||||
robot_base_frame_.c_str(), global_frame_.c_str(), tf_error.c_str());
|
||||
|
||||
// The error string will accumulate and errors will typically be the same, so the last
|
||||
// will do for the warning above. Reset the string here to avoid accumulation
|
||||
tf_error.clear();
|
||||
r.sleep();
|
||||
}
|
||||
|
||||
// Create a thread to handle updating the map
|
||||
stopped_ = true; // to active plugins
|
||||
stop_updates_ = false;
|
||||
map_update_thread_shutdown_ = false;
|
||||
map_update_thread_ = std::make_unique<std::thread>(
|
||||
std::bind(&Costmap2DROS::mapUpdateLoop, this, map_update_frequency_));
|
||||
|
||||
start();
|
||||
|
||||
// Add callback for dynamic parameters
|
||||
dyn_params_handler = this->add_on_set_parameters_callback(
|
||||
std::bind(&Costmap2DROS::dynamicParametersCallback, this, _1));
|
||||
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
Costmap2DROS::on_deactivate(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Deactivating");
|
||||
|
||||
dyn_params_handler.reset();
|
||||
|
||||
stop();
|
||||
|
||||
// Map thread stuff
|
||||
map_update_thread_shutdown_ = true;
|
||||
|
||||
if (map_update_thread_->joinable()) {
|
||||
map_update_thread_->join();
|
||||
}
|
||||
|
||||
costmap_publisher_->on_deactivate();
|
||||
footprint_pub_->on_deactivate();
|
||||
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
Costmap2DROS::on_cleanup(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Cleaning up");
|
||||
|
||||
layered_costmap_.reset();
|
||||
|
||||
tf_listener_.reset();
|
||||
tf_buffer_.reset();
|
||||
|
||||
footprint_sub_.reset();
|
||||
footprint_pub_.reset();
|
||||
|
||||
costmap_publisher_.reset();
|
||||
clear_costmap_service_.reset();
|
||||
|
||||
executor_thread_.reset();
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
Costmap2DROS::on_shutdown(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Shutting down");
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::getParameters()
|
||||
{
|
||||
RCLCPP_DEBUG(get_logger(), " getParameters");
|
||||
|
||||
// Get all of the required parameters
|
||||
get_parameter("always_send_full_costmap", always_send_full_costmap_);
|
||||
get_parameter("footprint", footprint_);
|
||||
get_parameter("footprint_padding", footprint_padding_);
|
||||
get_parameter("global_frame", global_frame_);
|
||||
get_parameter("height", map_height_meters_);
|
||||
get_parameter("origin_x", origin_x_);
|
||||
get_parameter("origin_y", origin_y_);
|
||||
get_parameter("publish_frequency", map_publish_frequency_);
|
||||
get_parameter("resolution", resolution_);
|
||||
get_parameter("robot_base_frame", robot_base_frame_);
|
||||
get_parameter("robot_radius", robot_radius_);
|
||||
get_parameter("rolling_window", rolling_window_);
|
||||
get_parameter("track_unknown_space", track_unknown_space_);
|
||||
get_parameter("transform_tolerance", transform_tolerance_);
|
||||
get_parameter("update_frequency", map_update_frequency_);
|
||||
get_parameter("width", map_width_meters_);
|
||||
get_parameter("plugins", plugin_names_);
|
||||
get_parameter("filters", filter_names_);
|
||||
|
||||
auto node = shared_from_this();
|
||||
|
||||
if (plugin_names_ == default_plugins_) {
|
||||
for (size_t i = 0; i < default_plugins_.size(); ++i) {
|
||||
nav2_util::declare_parameter_if_not_declared(
|
||||
node, default_plugins_[i] + ".plugin", rclcpp::ParameterValue(default_types_[i]));
|
||||
}
|
||||
}
|
||||
plugin_types_.resize(plugin_names_.size());
|
||||
filter_types_.resize(filter_names_.size());
|
||||
|
||||
// 1. All plugins must have 'plugin' param defined in their namespace to define the plugin type
|
||||
for (size_t i = 0; i < plugin_names_.size(); ++i) {
|
||||
plugin_types_[i] = nav2_util::get_plugin_type_param(node, plugin_names_[i]);
|
||||
}
|
||||
for (size_t i = 0; i < filter_names_.size(); ++i) {
|
||||
filter_types_[i] = nav2_util::get_plugin_type_param(node, filter_names_[i]);
|
||||
}
|
||||
|
||||
// 2. The map publish frequency cannot be 0 (to avoid a divde-by-zero)
|
||||
if (map_publish_frequency_ > 0) {
|
||||
publish_cycle_ = rclcpp::Duration::from_seconds(1 / map_publish_frequency_);
|
||||
} else {
|
||||
publish_cycle_ = rclcpp::Duration(-1s);
|
||||
}
|
||||
|
||||
// 3. If the footprint has been specified, it must be in the correct format
|
||||
use_radius_ = true;
|
||||
|
||||
if (footprint_ != "" && footprint_ != "[]") {
|
||||
// Footprint parameter has been specified, try to convert it
|
||||
std::vector<geometry_msgs::msg::Point> new_footprint;
|
||||
if (makeFootprintFromString(footprint_, new_footprint)) {
|
||||
// The specified footprint is valid, so we'll use that instead of the radius
|
||||
use_radius_ = false;
|
||||
} else {
|
||||
// Footprint provided but invalid, so stay with the radius
|
||||
RCLCPP_ERROR(
|
||||
get_logger(), "The footprint parameter is invalid: \"%s\", using radius (%lf) instead",
|
||||
footprint_.c_str(), robot_radius_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::setRobotFootprint(const std::vector<geometry_msgs::msg::Point> & points)
|
||||
{
|
||||
unpadded_footprint_ = points;
|
||||
padded_footprint_ = points;
|
||||
padFootprint(padded_footprint_, footprint_padding_);
|
||||
layered_costmap_->setFootprint(padded_footprint_);
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::setRobotFootprintPolygon(
|
||||
const geometry_msgs::msg::Polygon::SharedPtr footprint)
|
||||
{
|
||||
setRobotFootprint(toPointVector(footprint));
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::getOrientedFootprint(std::vector<geometry_msgs::msg::Point> & oriented_footprint)
|
||||
{
|
||||
geometry_msgs::msg::PoseStamped global_pose;
|
||||
if (!getRobotPose(global_pose)) {
|
||||
return;
|
||||
}
|
||||
|
||||
double yaw = tf2::getYaw(global_pose.pose.orientation);
|
||||
transformFootprint(
|
||||
global_pose.pose.position.x, global_pose.pose.position.y, yaw,
|
||||
padded_footprint_, oriented_footprint);
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::mapUpdateLoop(double frequency)
|
||||
{
|
||||
RCLCPP_DEBUG(get_logger(), "mapUpdateLoop frequency: %lf", frequency);
|
||||
|
||||
// the user might not want to run the loop every cycle
|
||||
if (frequency == 0.0) {
|
||||
return;
|
||||
}
|
||||
|
||||
RCLCPP_DEBUG(get_logger(), "Entering loop");
|
||||
|
||||
rclcpp::WallRate r(frequency); // 200ms by default
|
||||
|
||||
while (rclcpp::ok() && !map_update_thread_shutdown_) {
|
||||
nav2_util::ExecutionTimer timer;
|
||||
|
||||
// Execute after start() will complete plugins activation
|
||||
if (!stopped_) {
|
||||
// Lock while modifying layered costmap and publishing values
|
||||
std::scoped_lock<std::mutex> lock(_dynamic_parameter_mutex);
|
||||
|
||||
// Measure the execution time of the updateMap method
|
||||
timer.start();
|
||||
updateMap();
|
||||
timer.end();
|
||||
|
||||
RCLCPP_DEBUG(get_logger(), "Map update time: %.9f", timer.elapsed_time_in_seconds());
|
||||
if (publish_cycle_ > rclcpp::Duration(0s) && layered_costmap_->isInitialized()) {
|
||||
unsigned int x0, y0, xn, yn;
|
||||
layered_costmap_->getBounds(&x0, &xn, &y0, &yn);
|
||||
costmap_publisher_->updateBounds(x0, xn, y0, yn);
|
||||
|
||||
auto current_time = now();
|
||||
if ((last_publish_ + publish_cycle_ < current_time) || // publish_cycle_ is due
|
||||
(current_time < last_publish_)) // time has moved backwards, probably due to a switch to sim_time // NOLINT
|
||||
{
|
||||
RCLCPP_DEBUG(get_logger(), "Publish costmap at %s", name_.c_str());
|
||||
costmap_publisher_->publishCostmap();
|
||||
last_publish_ = current_time;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure to sleep for the remainder of our cycle time
|
||||
r.sleep();
|
||||
|
||||
#if 0
|
||||
// TODO(bpwilcox): find ROS2 equivalent or port for r.cycletime()
|
||||
if (r.period() > tf2::durationFromSec(1 / frequency)) {
|
||||
RCLCPP_WARN(
|
||||
get_logger(),
|
||||
"Costmap2DROS: Map update loop missed its desired rate of %.4fHz... "
|
||||
"the loop actually took %.4f seconds", frequency, r.period());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::updateMap()
|
||||
{
|
||||
RCLCPP_DEBUG(get_logger(), "Updating map...");
|
||||
|
||||
if (!stop_updates_) {
|
||||
// get global pose
|
||||
geometry_msgs::msg::PoseStamped pose;
|
||||
if (getRobotPose(pose)) {
|
||||
const double & x = pose.pose.position.x;
|
||||
const double & y = pose.pose.position.y;
|
||||
const double yaw = tf2::getYaw(pose.pose.orientation);
|
||||
layered_costmap_->updateMap(x, y, yaw);
|
||||
|
||||
auto footprint = std::make_unique<geometry_msgs::msg::PolygonStamped>();
|
||||
footprint->header = pose.header;
|
||||
transformFootprint(x, y, yaw, padded_footprint_, *footprint);
|
||||
|
||||
RCLCPP_DEBUG(get_logger(), "Publishing footprint");
|
||||
footprint_pub_->publish(std::move(footprint));
|
||||
initialized_ = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::start()
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "start");
|
||||
std::vector<std::shared_ptr<Layer>> * plugins = layered_costmap_->getPlugins();
|
||||
std::vector<std::shared_ptr<Layer>> * filters = layered_costmap_->getFilters();
|
||||
|
||||
// check if we're stopped or just paused
|
||||
if (stopped_) {
|
||||
// if we're stopped we need to re-subscribe to topics
|
||||
for (std::vector<std::shared_ptr<Layer>>::iterator plugin = plugins->begin();
|
||||
plugin != plugins->end();
|
||||
++plugin)
|
||||
{
|
||||
(*plugin)->activate();
|
||||
}
|
||||
for (std::vector<std::shared_ptr<Layer>>::iterator filter = filters->begin();
|
||||
filter != filters->end();
|
||||
++filter)
|
||||
{
|
||||
(*filter)->activate();
|
||||
}
|
||||
stopped_ = false;
|
||||
}
|
||||
stop_updates_ = false;
|
||||
|
||||
// block until the costmap is re-initialized.. meaning one update cycle has run
|
||||
rclcpp::Rate r(20.0);
|
||||
while (rclcpp::ok() && !initialized_) {
|
||||
RCLCPP_DEBUG(get_logger(), "Sleeping, waiting for initialized_");
|
||||
r.sleep();
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::stop()
|
||||
{
|
||||
stop_updates_ = true;
|
||||
// layered_costmap_ is set only if on_configure has been called
|
||||
if (layered_costmap_) {
|
||||
std::vector<std::shared_ptr<Layer>> * plugins = layered_costmap_->getPlugins();
|
||||
std::vector<std::shared_ptr<Layer>> * filters = layered_costmap_->getFilters();
|
||||
|
||||
// unsubscribe from topics
|
||||
for (std::vector<std::shared_ptr<Layer>>::iterator plugin = plugins->begin();
|
||||
plugin != plugins->end(); ++plugin)
|
||||
{
|
||||
(*plugin)->deactivate();
|
||||
}
|
||||
for (std::vector<std::shared_ptr<Layer>>::iterator filter = filters->begin();
|
||||
filter != filters->end(); ++filter)
|
||||
{
|
||||
(*filter)->deactivate();
|
||||
}
|
||||
}
|
||||
initialized_ = false;
|
||||
stopped_ = true;
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::pause()
|
||||
{
|
||||
stop_updates_ = true;
|
||||
initialized_ = false;
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::resume()
|
||||
{
|
||||
stop_updates_ = false;
|
||||
|
||||
// block until the costmap is re-initialized.. meaning one update cycle has run
|
||||
rclcpp::Rate r(100.0);
|
||||
while (!initialized_) {
|
||||
r.sleep();
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Costmap2DROS::resetLayers()
|
||||
{
|
||||
Costmap2D * top = layered_costmap_->getCostmap();
|
||||
top->resetMap(0, 0, top->getSizeInCellsX(), top->getSizeInCellsY());
|
||||
|
||||
// Reset each of the plugins
|
||||
std::vector<std::shared_ptr<Layer>> * plugins = layered_costmap_->getPlugins();
|
||||
std::vector<std::shared_ptr<Layer>> * filters = layered_costmap_->getFilters();
|
||||
for (std::vector<std::shared_ptr<Layer>>::iterator plugin = plugins->begin();
|
||||
plugin != plugins->end(); ++plugin)
|
||||
{
|
||||
(*plugin)->reset();
|
||||
}
|
||||
for (std::vector<std::shared_ptr<Layer>>::iterator filter = filters->begin();
|
||||
filter != filters->end(); ++filter)
|
||||
{
|
||||
(*filter)->reset();
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
Costmap2DROS::getRobotPose(geometry_msgs::msg::PoseStamped & global_pose)
|
||||
{
|
||||
return nav2_util::getCurrentPose(
|
||||
global_pose, *tf_buffer_,
|
||||
global_frame_, robot_base_frame_, transform_tolerance_);
|
||||
}
|
||||
|
||||
bool
|
||||
Costmap2DROS::transformPoseToGlobalFrame(
|
||||
const geometry_msgs::msg::PoseStamped & input_pose,
|
||||
geometry_msgs::msg::PoseStamped & transformed_pose)
|
||||
{
|
||||
if (input_pose.header.frame_id == global_frame_) {
|
||||
transformed_pose = input_pose;
|
||||
return true;
|
||||
} else {
|
||||
return nav2_util::transformPoseInTargetFrame(
|
||||
input_pose, transformed_pose, *tf_buffer_,
|
||||
global_frame_, transform_tolerance_);
|
||||
}
|
||||
}
|
||||
|
||||
rcl_interfaces::msg::SetParametersResult
|
||||
Costmap2DROS::dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters)
|
||||
{
|
||||
auto result = rcl_interfaces::msg::SetParametersResult();
|
||||
bool resize_map = false;
|
||||
std::lock_guard<std::mutex> lock_reinit(_dynamic_parameter_mutex);
|
||||
|
||||
for (auto parameter : parameters) {
|
||||
const auto & type = parameter.get_type();
|
||||
const auto & name = parameter.get_name();
|
||||
|
||||
if (type == ParameterType::PARAMETER_DOUBLE) {
|
||||
if (name == "robot_radius") {
|
||||
robot_radius_ = parameter.as_double();
|
||||
// Set the footprint
|
||||
if (use_radius_) {
|
||||
setRobotFootprint(makeFootprintFromRadius(robot_radius_));
|
||||
}
|
||||
} else if (name == "footprint_padding") {
|
||||
footprint_padding_ = parameter.as_double();
|
||||
padded_footprint_ = unpadded_footprint_;
|
||||
padFootprint(padded_footprint_, footprint_padding_);
|
||||
layered_costmap_->setFootprint(padded_footprint_);
|
||||
} else if (name == "transform_tolerance") {
|
||||
transform_tolerance_ = parameter.as_double();
|
||||
} else if (name == "publish_frequency") {
|
||||
map_publish_frequency_ = parameter.as_double();
|
||||
if (map_publish_frequency_ > 0) {
|
||||
publish_cycle_ = rclcpp::Duration::from_seconds(1 / map_publish_frequency_);
|
||||
} else {
|
||||
publish_cycle_ = rclcpp::Duration(-1s);
|
||||
}
|
||||
} else if (name == "resolution") {
|
||||
resize_map = true;
|
||||
resolution_ = parameter.as_double();
|
||||
} else if (name == "origin_x") {
|
||||
resize_map = true;
|
||||
origin_x_ = parameter.as_double();
|
||||
} else if (name == "origin_y") {
|
||||
resize_map = true;
|
||||
origin_y_ = parameter.as_double();
|
||||
}
|
||||
} else if (type == ParameterType::PARAMETER_INTEGER) {
|
||||
if (name == "width") {
|
||||
if (parameter.as_int() > 0) {
|
||||
resize_map = true;
|
||||
map_width_meters_ = parameter.as_int();
|
||||
} else {
|
||||
RCLCPP_ERROR(
|
||||
get_logger(), "You try to set width of map to be negative or zero,"
|
||||
" this isn't allowed, please give a positive value.");
|
||||
result.successful = false;
|
||||
return result;
|
||||
}
|
||||
} else if (name == "height") {
|
||||
if (parameter.as_int() > 0) {
|
||||
resize_map = true;
|
||||
map_height_meters_ = parameter.as_int();
|
||||
} else {
|
||||
RCLCPP_ERROR(
|
||||
get_logger(), "You try to set height of map to be negative or zero,"
|
||||
" this isn't allowed, please give a positive value.");
|
||||
result.successful = false;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (type == ParameterType::PARAMETER_STRING) {
|
||||
if (name == "footprint") {
|
||||
footprint_ = parameter.as_string();
|
||||
std::vector<geometry_msgs::msg::Point> new_footprint;
|
||||
if (makeFootprintFromString(footprint_, new_footprint)) {
|
||||
setRobotFootprint(new_footprint);
|
||||
}
|
||||
} else if (name == "robot_base_frame") {
|
||||
// First, make sure that the transform between the robot base frame
|
||||
// and the global frame is available
|
||||
std::string tf_error;
|
||||
RCLCPP_INFO(get_logger(), "Checking transform");
|
||||
if (!tf_buffer_->canTransform(
|
||||
global_frame_, parameter.as_string(), tf2::TimePointZero,
|
||||
tf2::durationFromSec(1.0), &tf_error))
|
||||
{
|
||||
RCLCPP_WARN(
|
||||
get_logger(), "Timed out waiting for transform from %s to %s"
|
||||
" to become available, tf error: %s",
|
||||
parameter.as_string().c_str(), global_frame_.c_str(), tf_error.c_str());
|
||||
RCLCPP_WARN(
|
||||
get_logger(), "Rejecting robot_base_frame change to %s , leaving it to its original"
|
||||
" value of %s", parameter.as_string().c_str(), robot_base_frame_.c_str());
|
||||
result.successful = false;
|
||||
return result;
|
||||
}
|
||||
robot_base_frame_ = parameter.as_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (resize_map && !layered_costmap_->isSizeLocked()) {
|
||||
layered_costmap_->resizeMap(
|
||||
(unsigned int)(map_width_meters_ / resolution_),
|
||||
(unsigned int)(map_height_meters_ / resolution_), resolution_, origin_x_, origin_y_);
|
||||
updateMap();
|
||||
}
|
||||
|
||||
result.successful = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,218 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
|
||||
#include <nav2_costmap_2d/costmap_layer.hpp>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
void CostmapLayer::touch(
|
||||
double x, double y, double * min_x, double * min_y, double * max_x,
|
||||
double * max_y)
|
||||
{
|
||||
*min_x = std::min(x, *min_x);
|
||||
*min_y = std::min(y, *min_y);
|
||||
*max_x = std::max(x, *max_x);
|
||||
*max_y = std::max(y, *max_y);
|
||||
}
|
||||
|
||||
void CostmapLayer::matchSize()
|
||||
{
|
||||
Costmap2D * master = layered_costmap_->getCostmap();
|
||||
resizeMap(
|
||||
master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
|
||||
master->getOriginX(), master->getOriginY());
|
||||
}
|
||||
|
||||
void CostmapLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert)
|
||||
{
|
||||
current_ = false;
|
||||
unsigned char * grid = getCharMap();
|
||||
for (int x = 0; x < static_cast<int>(getSizeInCellsX()); x++) {
|
||||
bool xrange = x > start_x && x < end_x;
|
||||
|
||||
for (int y = 0; y < static_cast<int>(getSizeInCellsY()); y++) {
|
||||
if ((xrange && y > start_y && y < end_y) == invert) {
|
||||
continue;
|
||||
}
|
||||
int index = getIndex(x, y);
|
||||
if (grid[index] != NO_INFORMATION) {
|
||||
grid[index] = NO_INFORMATION;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapLayer::addExtraBounds(double mx0, double my0, double mx1, double my1)
|
||||
{
|
||||
extra_min_x_ = std::min(mx0, extra_min_x_);
|
||||
extra_max_x_ = std::max(mx1, extra_max_x_);
|
||||
extra_min_y_ = std::min(my0, extra_min_y_);
|
||||
extra_max_y_ = std::max(my1, extra_max_y_);
|
||||
has_extra_bounds_ = true;
|
||||
}
|
||||
|
||||
void CostmapLayer::useExtraBounds(double * min_x, double * min_y, double * max_x, double * max_y)
|
||||
{
|
||||
if (!has_extra_bounds_) {
|
||||
return;
|
||||
}
|
||||
|
||||
*min_x = std::min(extra_min_x_, *min_x);
|
||||
*min_y = std::min(extra_min_y_, *min_y);
|
||||
*max_x = std::max(extra_max_x_, *max_x);
|
||||
*max_y = std::max(extra_max_y_, *max_y);
|
||||
extra_min_x_ = 1e6;
|
||||
extra_min_y_ = 1e6;
|
||||
extra_max_x_ = -1e6;
|
||||
extra_max_y_ = -1e6;
|
||||
has_extra_bounds_ = false;
|
||||
}
|
||||
|
||||
void CostmapLayer::updateWithMax(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i, int min_j,
|
||||
int max_i,
|
||||
int max_j)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned char * master_array = master_grid.getCharMap();
|
||||
unsigned int span = master_grid.getSizeInCellsX();
|
||||
|
||||
for (int j = min_j; j < max_j; j++) {
|
||||
unsigned int it = j * span + min_i;
|
||||
for (int i = min_i; i < max_i; i++) {
|
||||
if (costmap_[it] == NO_INFORMATION) {
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char old_cost = master_array[it];
|
||||
if (old_cost == NO_INFORMATION || old_cost < costmap_[it]) {
|
||||
master_array[it] = costmap_[it];
|
||||
}
|
||||
it++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapLayer::updateWithTrueOverwrite(
|
||||
nav2_costmap_2d::Costmap2D & master_grid, int min_i,
|
||||
int min_j,
|
||||
int max_i,
|
||||
int max_j)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (costmap_ == nullptr) {
|
||||
throw std::runtime_error("Can't update costmap layer: It has't been initialized yet!");
|
||||
}
|
||||
|
||||
unsigned char * master = master_grid.getCharMap();
|
||||
unsigned int span = master_grid.getSizeInCellsX();
|
||||
|
||||
for (int j = min_j; j < max_j; j++) {
|
||||
unsigned int it = span * j + min_i;
|
||||
for (int i = min_i; i < max_i; i++) {
|
||||
master[it] = costmap_[it];
|
||||
it++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapLayer::updateWithOverwrite(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
unsigned char * master = master_grid.getCharMap();
|
||||
unsigned int span = master_grid.getSizeInCellsX();
|
||||
|
||||
for (int j = min_j; j < max_j; j++) {
|
||||
unsigned int it = span * j + min_i;
|
||||
for (int i = min_i; i < max_i; i++) {
|
||||
if (costmap_[it] != NO_INFORMATION) {
|
||||
master[it] = costmap_[it];
|
||||
}
|
||||
it++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapLayer::updateWithAddition(
|
||||
nav2_costmap_2d::Costmap2D & master_grid,
|
||||
int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
unsigned char * master_array = master_grid.getCharMap();
|
||||
unsigned int span = master_grid.getSizeInCellsX();
|
||||
|
||||
for (int j = min_j; j < max_j; j++) {
|
||||
unsigned int it = j * span + min_i;
|
||||
for (int i = min_i; i < max_i; i++) {
|
||||
if (costmap_[it] == NO_INFORMATION) {
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char old_cost = master_array[it];
|
||||
if (old_cost == NO_INFORMATION) {
|
||||
master_array[it] = costmap_[it];
|
||||
} else {
|
||||
int sum = old_cost + costmap_[it];
|
||||
if (sum >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) {
|
||||
master_array[it] = nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE - 1;
|
||||
} else {
|
||||
master_array[it] = sum;
|
||||
}
|
||||
}
|
||||
it++;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright (c) 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <nav2_costmap_2d/costmap_math.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
double distanceToLine(double pX, double pY, double x0, double y0, double x1, double y1)
|
||||
{
|
||||
double A = pX - x0;
|
||||
double B = pY - y0;
|
||||
double C = x1 - x0;
|
||||
double D = y1 - y0;
|
||||
|
||||
double dot = A * C + B * D;
|
||||
double len_sq = C * C + D * D;
|
||||
double param = dot / len_sq;
|
||||
|
||||
double xx, yy;
|
||||
|
||||
if (param < 0) {
|
||||
xx = x0;
|
||||
yy = y0;
|
||||
} else if (param > 1) {
|
||||
xx = x1;
|
||||
yy = y1;
|
||||
} else {
|
||||
xx = x0 + param * C;
|
||||
yy = y0 + param * D;
|
||||
}
|
||||
|
||||
return distance(pX, pY, xx, yy);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_subscriber.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
CostmapSubscriber::CostmapSubscriber(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
const std::string & topic_name)
|
||||
: topic_name_(topic_name)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
costmap_sub_ = node->create_subscription<nav2_msgs::msg::Costmap>(
|
||||
topic_name_,
|
||||
rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&CostmapSubscriber::costmapCallback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
CostmapSubscriber::CostmapSubscriber(
|
||||
const rclcpp::Node::WeakPtr & parent,
|
||||
const std::string & topic_name)
|
||||
: topic_name_(topic_name)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
costmap_sub_ = node->create_subscription<nav2_msgs::msg::Costmap>(
|
||||
topic_name_,
|
||||
rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable(),
|
||||
std::bind(&CostmapSubscriber::costmapCallback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
std::shared_ptr<Costmap2D> CostmapSubscriber::getCostmap()
|
||||
{
|
||||
if (!costmap_received_) {
|
||||
throw std::runtime_error("Costmap is not available");
|
||||
}
|
||||
toCostmap2D();
|
||||
return costmap_;
|
||||
}
|
||||
|
||||
void CostmapSubscriber::toCostmap2D()
|
||||
{
|
||||
auto current_costmap_msg = std::atomic_load(&costmap_msg_);
|
||||
|
||||
if (costmap_ == nullptr) {
|
||||
costmap_ = std::make_shared<Costmap2D>(
|
||||
current_costmap_msg->metadata.size_x, current_costmap_msg->metadata.size_y,
|
||||
current_costmap_msg->metadata.resolution, current_costmap_msg->metadata.origin.position.x,
|
||||
current_costmap_msg->metadata.origin.position.y);
|
||||
} else if (costmap_->getSizeInCellsX() != current_costmap_msg->metadata.size_x || // NOLINT
|
||||
costmap_->getSizeInCellsY() != current_costmap_msg->metadata.size_y ||
|
||||
costmap_->getResolution() != current_costmap_msg->metadata.resolution ||
|
||||
costmap_->getOriginX() != current_costmap_msg->metadata.origin.position.x ||
|
||||
costmap_->getOriginY() != current_costmap_msg->metadata.origin.position.y)
|
||||
{
|
||||
// Update the size of the costmap
|
||||
costmap_->resizeMap(
|
||||
current_costmap_msg->metadata.size_x, current_costmap_msg->metadata.size_y,
|
||||
current_costmap_msg->metadata.resolution,
|
||||
current_costmap_msg->metadata.origin.position.x,
|
||||
current_costmap_msg->metadata.origin.position.y);
|
||||
}
|
||||
|
||||
unsigned char * master_array = costmap_->getCharMap();
|
||||
unsigned int index = 0;
|
||||
for (unsigned int i = 0; i < current_costmap_msg->metadata.size_x; ++i) {
|
||||
for (unsigned int j = 0; j < current_costmap_msg->metadata.size_y; ++j) {
|
||||
master_array[index] = current_costmap_msg->data[index];
|
||||
++index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapSubscriber::costmapCallback(const nav2_msgs::msg::Costmap::SharedPtr msg)
|
||||
{
|
||||
std::atomic_store(&costmap_msg_, msg);
|
||||
if (!costmap_received_) {
|
||||
costmap_received_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,103 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Modified by: Shivang Patel (shivaan14@gmail.com)
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_topic_collision_checker.hpp"
|
||||
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "nav2_costmap_2d/exceptions.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
#include "nav2_util/line_iterator.hpp"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
CostmapTopicCollisionChecker::CostmapTopicCollisionChecker(
|
||||
CostmapSubscriber & costmap_sub,
|
||||
FootprintSubscriber & footprint_sub,
|
||||
std::string name)
|
||||
: name_(name),
|
||||
costmap_sub_(costmap_sub),
|
||||
footprint_sub_(footprint_sub),
|
||||
collision_checker_(nullptr)
|
||||
{}
|
||||
|
||||
bool CostmapTopicCollisionChecker::isCollisionFree(
|
||||
const geometry_msgs::msg::Pose2D & pose,
|
||||
bool fetch_costmap_and_footprint)
|
||||
{
|
||||
try {
|
||||
if (scorePose(pose, fetch_costmap_and_footprint) >= LETHAL_OBSTACLE) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (const IllegalPoseException & e) {
|
||||
RCLCPP_ERROR(rclcpp::get_logger(name_), "%s", e.what());
|
||||
return false;
|
||||
} catch (const CollisionCheckerException & e) {
|
||||
RCLCPP_ERROR(rclcpp::get_logger(name_), "%s", e.what());
|
||||
return false;
|
||||
} catch (...) {
|
||||
RCLCPP_ERROR(rclcpp::get_logger(name_), "Failed to check pose score!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
double CostmapTopicCollisionChecker::scorePose(
|
||||
const geometry_msgs::msg::Pose2D & pose,
|
||||
bool fetch_costmap_and_footprint)
|
||||
{
|
||||
if (fetch_costmap_and_footprint) {
|
||||
try {
|
||||
collision_checker_.setCostmap(costmap_sub_.getCostmap());
|
||||
} catch (const std::runtime_error & e) {
|
||||
throw CollisionCheckerException(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int cell_x, cell_y;
|
||||
if (!collision_checker_.worldToMap(pose.x, pose.y, cell_x, cell_y)) {
|
||||
RCLCPP_DEBUG(rclcpp::get_logger(name_), "Map Cell: [%d, %d]", cell_x, cell_y);
|
||||
throw IllegalPoseException(name_, "Pose Goes Off Grid.");
|
||||
}
|
||||
|
||||
return collision_checker_.footprintCost(getFootprint(pose, fetch_costmap_and_footprint));
|
||||
}
|
||||
|
||||
Footprint CostmapTopicCollisionChecker::getFootprint(
|
||||
const geometry_msgs::msg::Pose2D & pose,
|
||||
bool fetch_latest_footprint)
|
||||
{
|
||||
if (fetch_latest_footprint) {
|
||||
std_msgs::msg::Header header;
|
||||
if (!footprint_sub_.getFootprintInRobotFrame(footprint_, header)) {
|
||||
throw CollisionCheckerException("Current footprint not available.");
|
||||
}
|
||||
}
|
||||
Footprint footprint;
|
||||
transformFootprint(pose.x, pose.y, pose.theta, footprint_, footprint);
|
||||
|
||||
return footprint;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Copyright (c) 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "geometry_msgs/msg/point32.hpp"
|
||||
#include "nav2_costmap_2d/array_parser.hpp"
|
||||
#include "nav2_costmap_2d/costmap_math.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
void calculateMinAndMaxDistances(
|
||||
const std::vector<geometry_msgs::msg::Point> & footprint,
|
||||
double & min_dist, double & max_dist)
|
||||
{
|
||||
min_dist = std::numeric_limits<double>::max();
|
||||
max_dist = 0.0;
|
||||
|
||||
if (footprint.size() <= 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i < footprint.size() - 1; ++i) {
|
||||
// check the distance from the robot center point to the first vertex
|
||||
double vertex_dist = distance(0.0, 0.0, footprint[i].x, footprint[i].y);
|
||||
double edge_dist = distanceToLine(
|
||||
0.0, 0.0, footprint[i].x, footprint[i].y,
|
||||
footprint[i + 1].x, footprint[i + 1].y);
|
||||
min_dist = std::min(min_dist, std::min(vertex_dist, edge_dist));
|
||||
max_dist = std::max(max_dist, std::max(vertex_dist, edge_dist));
|
||||
}
|
||||
|
||||
// we also need to do the last vertex and the first vertex
|
||||
double vertex_dist = distance(0.0, 0.0, footprint.back().x, footprint.back().y);
|
||||
double edge_dist = distanceToLine(
|
||||
0.0, 0.0, footprint.back().x, footprint.back().y,
|
||||
footprint.front().x, footprint.front().y);
|
||||
min_dist = std::min(min_dist, std::min(vertex_dist, edge_dist));
|
||||
max_dist = std::max(max_dist, std::max(vertex_dist, edge_dist));
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Point32 toPoint32(geometry_msgs::msg::Point pt)
|
||||
{
|
||||
geometry_msgs::msg::Point32 point32;
|
||||
point32.x = pt.x;
|
||||
point32.y = pt.y;
|
||||
point32.z = pt.z;
|
||||
return point32;
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Point toPoint(geometry_msgs::msg::Point32 pt)
|
||||
{
|
||||
geometry_msgs::msg::Point point;
|
||||
point.x = pt.x;
|
||||
point.y = pt.y;
|
||||
point.z = pt.z;
|
||||
return point;
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Polygon toPolygon(std::vector<geometry_msgs::msg::Point> pts)
|
||||
{
|
||||
geometry_msgs::msg::Polygon polygon;
|
||||
for (unsigned int i = 0; i < pts.size(); i++) {
|
||||
polygon.points.push_back(toPoint32(pts[i]));
|
||||
}
|
||||
return polygon;
|
||||
}
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> toPointVector(geometry_msgs::msg::Polygon::SharedPtr polygon)
|
||||
{
|
||||
std::vector<geometry_msgs::msg::Point> pts;
|
||||
for (unsigned int i = 0; i < polygon->points.size(); i++) {
|
||||
pts.push_back(toPoint(polygon->points[i]));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
void transformFootprint(
|
||||
double x, double y, double theta,
|
||||
const std::vector<geometry_msgs::msg::Point> & footprint_spec,
|
||||
std::vector<geometry_msgs::msg::Point> & oriented_footprint)
|
||||
{
|
||||
// build the oriented footprint at a given location
|
||||
oriented_footprint.resize(footprint_spec.size());
|
||||
double cos_th = cos(theta);
|
||||
double sin_th = sin(theta);
|
||||
for (unsigned int i = 0; i < footprint_spec.size(); ++i) {
|
||||
double new_x = x + (footprint_spec[i].x * cos_th - footprint_spec[i].y * sin_th);
|
||||
double new_y = y + (footprint_spec[i].x * sin_th + footprint_spec[i].y * cos_th);
|
||||
geometry_msgs::msg::Point & new_pt = oriented_footprint[i];
|
||||
new_pt.x = new_x;
|
||||
new_pt.y = new_y;
|
||||
}
|
||||
}
|
||||
|
||||
void transformFootprint(
|
||||
double x, double y, double theta,
|
||||
const std::vector<geometry_msgs::msg::Point> & footprint_spec,
|
||||
geometry_msgs::msg::PolygonStamped & oriented_footprint)
|
||||
{
|
||||
// build the oriented footprint at a given location
|
||||
oriented_footprint.polygon.points.clear();
|
||||
double cos_th = cos(theta);
|
||||
double sin_th = sin(theta);
|
||||
for (unsigned int i = 0; i < footprint_spec.size(); ++i) {
|
||||
geometry_msgs::msg::Point32 new_pt;
|
||||
new_pt.x = x + (footprint_spec[i].x * cos_th - footprint_spec[i].y * sin_th);
|
||||
new_pt.y = y + (footprint_spec[i].x * sin_th + footprint_spec[i].y * cos_th);
|
||||
oriented_footprint.polygon.points.push_back(new_pt);
|
||||
}
|
||||
}
|
||||
|
||||
void padFootprint(std::vector<geometry_msgs::msg::Point> & footprint, double padding)
|
||||
{
|
||||
// pad footprint in place
|
||||
for (unsigned int i = 0; i < footprint.size(); i++) {
|
||||
geometry_msgs::msg::Point & pt = footprint[i];
|
||||
pt.x += sign0(pt.x) * padding;
|
||||
pt.y += sign0(pt.y) * padding;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> makeFootprintFromRadius(double radius)
|
||||
{
|
||||
std::vector<geometry_msgs::msg::Point> points;
|
||||
|
||||
// Loop over 16 angles around a circle making a point each time
|
||||
int N = 16;
|
||||
geometry_msgs::msg::Point pt;
|
||||
for (int i = 0; i < N; ++i) {
|
||||
double angle = i * 2 * M_PI / N;
|
||||
pt.x = cos(angle) * radius;
|
||||
pt.y = sin(angle) * radius;
|
||||
|
||||
points.push_back(pt);
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
|
||||
bool makeFootprintFromString(
|
||||
const std::string & footprint_string,
|
||||
std::vector<geometry_msgs::msg::Point> & footprint)
|
||||
{
|
||||
std::string error;
|
||||
std::vector<std::vector<float>> vvf = parseVVF(footprint_string, error);
|
||||
|
||||
if (error != "") {
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"), "Error parsing footprint parameter: '%s'", error.c_str());
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"), " Footprint string was '%s'.", footprint_string.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
// convert vvf into points.
|
||||
if (vvf.size() < 3) {
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"),
|
||||
"You must specify at least three points for the robot footprint, reverting to previous footprint."); //NOLINT
|
||||
return false;
|
||||
}
|
||||
footprint.reserve(vvf.size());
|
||||
for (unsigned int i = 0; i < vvf.size(); i++) {
|
||||
if (vvf[i].size() == 2) {
|
||||
geometry_msgs::msg::Point point;
|
||||
point.x = vvf[i][0];
|
||||
point.y = vvf[i][1];
|
||||
point.z = 0;
|
||||
footprint.push_back(point);
|
||||
} else {
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"),
|
||||
"Points in the footprint specification must be pairs of numbers. Found a point with %d numbers.", //NOLINT
|
||||
static_cast<int>(vvf[i].size()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // end namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,149 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Modified by: Shivang Patel (shivaang14@gmail.com)
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
#include "nav2_costmap_2d/footprint_collision_checker.hpp"
|
||||
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "nav2_costmap_2d/exceptions.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
#include "nav2_util/line_iterator.hpp"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
template<typename CostmapT>
|
||||
FootprintCollisionChecker<CostmapT>::FootprintCollisionChecker()
|
||||
: costmap_(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
FootprintCollisionChecker<CostmapT>::FootprintCollisionChecker(
|
||||
CostmapT costmap)
|
||||
: costmap_(costmap)
|
||||
{
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
double FootprintCollisionChecker<CostmapT>::footprintCost(const Footprint footprint)
|
||||
{
|
||||
// now we really have to lay down the footprint in the costmap_ grid
|
||||
unsigned int x0, x1, y0, y1;
|
||||
double footprint_cost = 0.0;
|
||||
|
||||
// get the cell coord of the first point
|
||||
if (!worldToMap(footprint[0].x, footprint[0].y, x0, y0)) {
|
||||
return static_cast<double>(LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
// cache the start to eliminate a worldToMap call
|
||||
unsigned int xstart = x0;
|
||||
unsigned int ystart = y0;
|
||||
|
||||
// we need to rasterize each line in the footprint
|
||||
for (unsigned int i = 0; i < footprint.size() - 1; ++i) {
|
||||
// get the cell coord of the second point
|
||||
if (!worldToMap(footprint[i + 1].x, footprint[i + 1].y, x1, y1)) {
|
||||
return static_cast<double>(LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
footprint_cost = std::max(lineCost(x0, x1, y0, y1), footprint_cost);
|
||||
|
||||
// the second point is next iteration's first point
|
||||
x0 = x1;
|
||||
y0 = y1;
|
||||
|
||||
// if in collision, no need to continue
|
||||
if (footprint_cost == static_cast<double>(LETHAL_OBSTACLE)) {
|
||||
return footprint_cost;
|
||||
}
|
||||
}
|
||||
|
||||
// we also need to connect the first point in the footprint to the last point
|
||||
// the last iteration's x1, y1 are the last footprint point's coordinates
|
||||
return std::max(lineCost(xstart, x1, ystart, y1), footprint_cost);
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
double FootprintCollisionChecker<CostmapT>::lineCost(int x0, int x1, int y0, int y1) const
|
||||
{
|
||||
double line_cost = 0.0;
|
||||
double point_cost = -1.0;
|
||||
|
||||
for (nav2_util::LineIterator line(x0, y0, x1, y1); line.isValid(); line.advance()) {
|
||||
point_cost = pointCost(line.getX(), line.getY()); // Score the current point
|
||||
|
||||
// if in collision, no need to continue
|
||||
if (point_cost == static_cast<double>(LETHAL_OBSTACLE)) {
|
||||
return point_cost;
|
||||
}
|
||||
|
||||
if (line_cost < point_cost) {
|
||||
line_cost = point_cost;
|
||||
}
|
||||
}
|
||||
|
||||
return line_cost;
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
bool FootprintCollisionChecker<CostmapT>::worldToMap(
|
||||
double wx, double wy, unsigned int & mx, unsigned int & my)
|
||||
{
|
||||
return costmap_->worldToMap(wx, wy, mx, my);
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
double FootprintCollisionChecker<CostmapT>::pointCost(int x, int y) const
|
||||
{
|
||||
return costmap_->getCost(x, y);
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
void FootprintCollisionChecker<CostmapT>::setCostmap(CostmapT costmap)
|
||||
{
|
||||
costmap_ = costmap;
|
||||
}
|
||||
|
||||
template<typename CostmapT>
|
||||
double FootprintCollisionChecker<CostmapT>::footprintCostAtPose(
|
||||
double x, double y, double theta, const Footprint footprint)
|
||||
{
|
||||
double cos_th = cos(theta);
|
||||
double sin_th = sin(theta);
|
||||
Footprint oriented_footprint;
|
||||
for (unsigned int i = 0; i < footprint.size(); ++i) {
|
||||
geometry_msgs::msg::Point new_pt;
|
||||
new_pt.x = x + (footprint[i].x * cos_th - footprint[i].y * sin_th);
|
||||
new_pt.y = y + (footprint[i].x * sin_th + footprint[i].y * cos_th);
|
||||
oriented_footprint.push_back(new_pt);
|
||||
}
|
||||
|
||||
return footprintCost(oriented_footprint);
|
||||
}
|
||||
|
||||
// declare our valid template parameters
|
||||
template class FootprintCollisionChecker<std::shared_ptr<nav2_costmap_2d::Costmap2D>>;
|
||||
template class FootprintCollisionChecker<nav2_costmap_2d::Costmap2D *>;
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,117 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
#include "nav2_costmap_2d/footprint_subscriber.hpp"
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wpedantic"
|
||||
#include "tf2/utils.h"
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
FootprintSubscriber::FootprintSubscriber(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
const std::string & topic_name,
|
||||
tf2_ros::Buffer & tf,
|
||||
std::string robot_base_frame,
|
||||
double transform_tolerance)
|
||||
: tf_(tf),
|
||||
robot_base_frame_(robot_base_frame),
|
||||
transform_tolerance_(transform_tolerance)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
footprint_sub_ = node->create_subscription<geometry_msgs::msg::PolygonStamped>(
|
||||
topic_name, rclcpp::SystemDefaultsQoS(),
|
||||
std::bind(&FootprintSubscriber::footprint_callback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
FootprintSubscriber::FootprintSubscriber(
|
||||
const rclcpp::Node::WeakPtr & parent,
|
||||
const std::string & topic_name,
|
||||
tf2_ros::Buffer & tf,
|
||||
std::string robot_base_frame,
|
||||
double transform_tolerance)
|
||||
: tf_(tf),
|
||||
robot_base_frame_(robot_base_frame),
|
||||
transform_tolerance_(transform_tolerance)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
footprint_sub_ = node->create_subscription<geometry_msgs::msg::PolygonStamped>(
|
||||
topic_name, rclcpp::SystemDefaultsQoS(),
|
||||
std::bind(&FootprintSubscriber::footprint_callback, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
bool
|
||||
FootprintSubscriber::getFootprintRaw(
|
||||
std::vector<geometry_msgs::msg::Point> & footprint,
|
||||
std_msgs::msg::Header & footprint_header)
|
||||
{
|
||||
if (!footprint_received_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto current_footprint = std::atomic_load(&footprint_);
|
||||
footprint = toPointVector(
|
||||
std::make_shared<geometry_msgs::msg::Polygon>(current_footprint->polygon));
|
||||
footprint_header = current_footprint->header;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
FootprintSubscriber::getFootprintInRobotFrame(
|
||||
std::vector<geometry_msgs::msg::Point> & footprint,
|
||||
std_msgs::msg::Header & footprint_header)
|
||||
{
|
||||
if (!getFootprintRaw(footprint, footprint_header)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
geometry_msgs::msg::PoseStamped current_pose;
|
||||
if (!nav2_util::getCurrentPose(
|
||||
current_pose, tf_, footprint_header.frame_id, robot_base_frame_,
|
||||
transform_tolerance_, footprint_header.stamp))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
double x = current_pose.pose.position.x;
|
||||
double y = current_pose.pose.position.y;
|
||||
double theta = tf2::getYaw(current_pose.pose.orientation);
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> temp;
|
||||
transformFootprint(-x, -y, 0, footprint, temp);
|
||||
transformFootprint(0, 0, -theta, temp, footprint);
|
||||
|
||||
footprint_header.frame_id = robot_base_frame_;
|
||||
footprint_header.stamp = current_pose.header.stamp;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
FootprintSubscriber::footprint_callback(const geometry_msgs::msg::PolygonStamped::SharedPtr msg)
|
||||
{
|
||||
std::atomic_store(&footprint_, msg);
|
||||
if (!footprint_received_) {
|
||||
footprint_received_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* Copyright (c) 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "nav2_util/node_utils.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
Layer::Layer()
|
||||
: layered_costmap_(nullptr),
|
||||
name_(),
|
||||
tf_(nullptr),
|
||||
current_(false),
|
||||
enabled_(false)
|
||||
{}
|
||||
|
||||
void
|
||||
Layer::initialize(
|
||||
LayeredCostmap * parent,
|
||||
std::string name,
|
||||
tf2_ros::Buffer * tf,
|
||||
const nav2_util::LifecycleNode::WeakPtr & node,
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group)
|
||||
{
|
||||
layered_costmap_ = parent;
|
||||
name_ = name;
|
||||
tf_ = tf;
|
||||
node_ = node;
|
||||
callback_group_ = callback_group;
|
||||
{
|
||||
auto node_shared_ptr = node_.lock();
|
||||
logger_ = node_shared_ptr->get_logger();
|
||||
clock_ = node_shared_ptr->get_clock();
|
||||
}
|
||||
|
||||
onInitialize();
|
||||
}
|
||||
|
||||
const std::vector<geometry_msgs::msg::Point> &
|
||||
Layer::getFootprint() const
|
||||
{
|
||||
return layered_costmap_->getFootprint();
|
||||
}
|
||||
|
||||
void
|
||||
Layer::declareParameter(
|
||||
const std::string & param_name,
|
||||
const rclcpp::ParameterValue & value)
|
||||
{
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
local_params_.insert(param_name);
|
||||
nav2_util::declare_parameter_if_not_declared(
|
||||
node, getFullName(param_name), value);
|
||||
}
|
||||
|
||||
void
|
||||
Layer::declareParameter(
|
||||
const std::string & param_name,
|
||||
const rclcpp::ParameterType & param_type)
|
||||
{
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
local_params_.insert(param_name);
|
||||
nav2_util::declare_parameter_if_not_declared(
|
||||
node, getFullName(param_name), param_type);
|
||||
}
|
||||
|
||||
bool
|
||||
Layer::hasParameter(const std::string & param_name)
|
||||
{
|
||||
auto node = node_.lock();
|
||||
if (!node) {
|
||||
throw std::runtime_error{"Failed to lock node"};
|
||||
}
|
||||
return node->has_parameter(getFullName(param_name));
|
||||
}
|
||||
|
||||
std::string
|
||||
Layer::getFullName(const std::string & param_name)
|
||||
{
|
||||
return std::string(name_ + "." + param_name);
|
||||
}
|
||||
|
||||
} // end namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,296 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
* David V. Lu!!
|
||||
*********************************************************************/
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <limits>
|
||||
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
|
||||
|
||||
using std::vector;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
LayeredCostmap::LayeredCostmap(std::string global_frame, bool rolling_window, bool track_unknown)
|
||||
: primary_costmap_(), combined_costmap_(),
|
||||
global_frame_(global_frame),
|
||||
rolling_window_(rolling_window),
|
||||
current_(false),
|
||||
minx_(0.0),
|
||||
miny_(0.0),
|
||||
maxx_(0.0),
|
||||
maxy_(0.0),
|
||||
bx0_(0),
|
||||
bxn_(0),
|
||||
by0_(0),
|
||||
byn_(0),
|
||||
initialized_(false),
|
||||
size_locked_(false),
|
||||
circumscribed_radius_(1.0),
|
||||
inscribed_radius_(0.1)
|
||||
{
|
||||
if (track_unknown) {
|
||||
primary_costmap_.setDefaultValue(255);
|
||||
combined_costmap_.setDefaultValue(255);
|
||||
} else {
|
||||
primary_costmap_.setDefaultValue(0);
|
||||
combined_costmap_.setDefaultValue(0);
|
||||
}
|
||||
}
|
||||
|
||||
LayeredCostmap::~LayeredCostmap()
|
||||
{
|
||||
while (plugins_.size() > 0) {
|
||||
plugins_.pop_back();
|
||||
}
|
||||
while (filters_.size() > 0) {
|
||||
filters_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
void LayeredCostmap::addPlugin(std::shared_ptr<Layer> plugin)
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(combined_costmap_.getMutex()));
|
||||
plugins_.push_back(plugin);
|
||||
}
|
||||
|
||||
void LayeredCostmap::addFilter(std::shared_ptr<Layer> filter)
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(combined_costmap_.getMutex()));
|
||||
filters_.push_back(filter);
|
||||
}
|
||||
|
||||
void LayeredCostmap::resizeMap(
|
||||
unsigned int size_x, unsigned int size_y, double resolution,
|
||||
double origin_x,
|
||||
double origin_y,
|
||||
bool size_locked)
|
||||
{
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(combined_costmap_.getMutex()));
|
||||
size_locked_ = size_locked;
|
||||
primary_costmap_.resizeMap(size_x, size_y, resolution, origin_x, origin_y);
|
||||
combined_costmap_.resizeMap(size_x, size_y, resolution, origin_x, origin_y);
|
||||
for (vector<std::shared_ptr<Layer>>::iterator plugin = plugins_.begin();
|
||||
plugin != plugins_.end(); ++plugin)
|
||||
{
|
||||
(*plugin)->matchSize();
|
||||
}
|
||||
for (vector<std::shared_ptr<Layer>>::iterator filter = filters_.begin();
|
||||
filter != filters_.end(); ++filter)
|
||||
{
|
||||
(*filter)->matchSize();
|
||||
}
|
||||
}
|
||||
|
||||
bool LayeredCostmap::isOutofBounds(double robot_x, double robot_y)
|
||||
{
|
||||
unsigned int mx, my;
|
||||
return !combined_costmap_.worldToMap(robot_x, robot_y, mx, my);
|
||||
}
|
||||
|
||||
void LayeredCostmap::updateMap(double robot_x, double robot_y, double robot_yaw)
|
||||
{
|
||||
// Lock for the remainder of this function, some plugins (e.g. VoxelLayer)
|
||||
// implement thread unsafe updateBounds() functions.
|
||||
std::unique_lock<Costmap2D::mutex_t> lock(*(combined_costmap_.getMutex()));
|
||||
|
||||
// if we're using a rolling buffer costmap...
|
||||
// we need to update the origin using the robot's position
|
||||
if (rolling_window_) {
|
||||
double new_origin_x = robot_x - combined_costmap_.getSizeInMetersX() / 2;
|
||||
double new_origin_y = robot_y - combined_costmap_.getSizeInMetersY() / 2;
|
||||
primary_costmap_.updateOrigin(new_origin_x, new_origin_y);
|
||||
combined_costmap_.updateOrigin(new_origin_x, new_origin_y);
|
||||
}
|
||||
|
||||
if (isOutofBounds(robot_x, robot_y)) {
|
||||
RCLCPP_WARN(
|
||||
rclcpp::get_logger("nav2_costmap_2d"),
|
||||
"Robot is out of bounds of the costmap!");
|
||||
}
|
||||
|
||||
if (plugins_.size() == 0 && filters_.size() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
minx_ = miny_ = std::numeric_limits<double>::max();
|
||||
maxx_ = maxy_ = std::numeric_limits<double>::lowest();
|
||||
|
||||
for (vector<std::shared_ptr<Layer>>::iterator plugin = plugins_.begin();
|
||||
plugin != plugins_.end(); ++plugin)
|
||||
{
|
||||
double prev_minx = minx_;
|
||||
double prev_miny = miny_;
|
||||
double prev_maxx = maxx_;
|
||||
double prev_maxy = maxy_;
|
||||
(*plugin)->updateBounds(robot_x, robot_y, robot_yaw, &minx_, &miny_, &maxx_, &maxy_);
|
||||
if (minx_ > prev_minx || miny_ > prev_miny || maxx_ < prev_maxx || maxy_ < prev_maxy) {
|
||||
RCLCPP_WARN(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"), "Illegal bounds change, was [tl: (%f, %f), br: (%f, %f)], but "
|
||||
"is now [tl: (%f, %f), br: (%f, %f)]. The offending layer is %s",
|
||||
prev_minx, prev_miny, prev_maxx, prev_maxy,
|
||||
minx_, miny_, maxx_, maxy_,
|
||||
(*plugin)->getName().c_str());
|
||||
}
|
||||
}
|
||||
for (vector<std::shared_ptr<Layer>>::iterator filter = filters_.begin();
|
||||
filter != filters_.end(); ++filter)
|
||||
{
|
||||
double prev_minx = minx_;
|
||||
double prev_miny = miny_;
|
||||
double prev_maxx = maxx_;
|
||||
double prev_maxy = maxy_;
|
||||
(*filter)->updateBounds(robot_x, robot_y, robot_yaw, &minx_, &miny_, &maxx_, &maxy_);
|
||||
if (minx_ > prev_minx || miny_ > prev_miny || maxx_ < prev_maxx || maxy_ < prev_maxy) {
|
||||
RCLCPP_WARN(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"), "Illegal bounds change, was [tl: (%f, %f), br: (%f, %f)], but "
|
||||
"is now [tl: (%f, %f), br: (%f, %f)]. The offending filter is %s",
|
||||
prev_minx, prev_miny, prev_maxx, prev_maxy,
|
||||
minx_, miny_, maxx_, maxy_,
|
||||
(*filter)->getName().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
int x0, xn, y0, yn;
|
||||
combined_costmap_.worldToMapEnforceBounds(minx_, miny_, x0, y0);
|
||||
combined_costmap_.worldToMapEnforceBounds(maxx_, maxy_, xn, yn);
|
||||
|
||||
x0 = std::max(0, x0);
|
||||
xn = std::min(static_cast<int>(combined_costmap_.getSizeInCellsX()), xn + 1);
|
||||
y0 = std::max(0, y0);
|
||||
yn = std::min(static_cast<int>(combined_costmap_.getSizeInCellsY()), yn + 1);
|
||||
|
||||
RCLCPP_DEBUG(
|
||||
rclcpp::get_logger(
|
||||
"nav2_costmap_2d"), "Updating area x: [%d, %d] y: [%d, %d]", x0, xn, y0, yn);
|
||||
|
||||
if (xn < x0 || yn < y0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (filters_.size() == 0) {
|
||||
// If there are no filters enabled just update costmap sequentially by each plugin
|
||||
combined_costmap_.resetMap(x0, y0, xn, yn);
|
||||
for (vector<std::shared_ptr<Layer>>::iterator plugin = plugins_.begin();
|
||||
plugin != plugins_.end(); ++plugin)
|
||||
{
|
||||
(*plugin)->updateCosts(combined_costmap_, x0, y0, xn, yn);
|
||||
}
|
||||
} else {
|
||||
// Costmap Filters enabled
|
||||
// 1. Update costmap by plugins
|
||||
primary_costmap_.resetMap(x0, y0, xn, yn);
|
||||
for (vector<std::shared_ptr<Layer>>::iterator plugin = plugins_.begin();
|
||||
plugin != plugins_.end(); ++plugin)
|
||||
{
|
||||
(*plugin)->updateCosts(primary_costmap_, x0, y0, xn, yn);
|
||||
}
|
||||
|
||||
// 2. Copy processed costmap window to a final costmap.
|
||||
// primary_costmap_ remain to be untouched for further usage by plugins.
|
||||
if (!combined_costmap_.copyWindow(primary_costmap_, x0, y0, xn, yn, x0, y0)) {
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger("nav2_costmap_2d"),
|
||||
"Can not copy costmap (%i,%i)..(%i,%i) window",
|
||||
x0, y0, xn, yn);
|
||||
throw std::runtime_error{"Can not copy costmap"};
|
||||
}
|
||||
|
||||
// 3. Apply filters over the plugins in order to make filters' work
|
||||
// not being considered by plugins on next updateMap() calls
|
||||
for (vector<std::shared_ptr<Layer>>::iterator filter = filters_.begin();
|
||||
filter != filters_.end(); ++filter)
|
||||
{
|
||||
(*filter)->updateCosts(combined_costmap_, x0, y0, xn, yn);
|
||||
}
|
||||
}
|
||||
|
||||
bx0_ = x0;
|
||||
bxn_ = xn;
|
||||
by0_ = y0;
|
||||
byn_ = yn;
|
||||
|
||||
initialized_ = true;
|
||||
}
|
||||
|
||||
bool LayeredCostmap::isCurrent()
|
||||
{
|
||||
current_ = true;
|
||||
for (vector<std::shared_ptr<Layer>>::iterator plugin = plugins_.begin();
|
||||
plugin != plugins_.end(); ++plugin)
|
||||
{
|
||||
current_ = current_ && ((*plugin)->isCurrent() || !(*plugin)->isEnabled());
|
||||
}
|
||||
for (vector<std::shared_ptr<Layer>>::iterator filter = filters_.begin();
|
||||
filter != filters_.end(); ++filter)
|
||||
{
|
||||
current_ = current_ && ((*filter)->isCurrent() || !(*filter)->isEnabled());
|
||||
}
|
||||
return current_;
|
||||
}
|
||||
|
||||
void LayeredCostmap::setFootprint(const std::vector<geometry_msgs::msg::Point> & footprint_spec)
|
||||
{
|
||||
footprint_ = footprint_spec;
|
||||
nav2_costmap_2d::calculateMinAndMaxDistances(
|
||||
footprint_spec,
|
||||
inscribed_radius_, circumscribed_radius_);
|
||||
|
||||
for (vector<std::shared_ptr<Layer>>::iterator plugin = plugins_.begin();
|
||||
plugin != plugins_.end();
|
||||
++plugin)
|
||||
{
|
||||
(*plugin)->onFootprintChanged();
|
||||
}
|
||||
for (vector<std::shared_ptr<Layer>>::iterator filter = filters_.begin();
|
||||
filter != filters_.end();
|
||||
++filter)
|
||||
{
|
||||
(*filter)->onFootprintChanged();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,236 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
*********************************************************************/
|
||||
#include "nav2_costmap_2d/observation_buffer.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
|
||||
#include "tf2/convert.h"
|
||||
#include "sensor_msgs/point_cloud2_iterator.hpp"
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
ObservationBuffer::ObservationBuffer(
|
||||
const nav2_util::LifecycleNode::WeakPtr & parent,
|
||||
std::string topic_name,
|
||||
double observation_keep_time,
|
||||
double expected_update_rate,
|
||||
double min_obstacle_height, double max_obstacle_height, double obstacle_max_range,
|
||||
double obstacle_min_range,
|
||||
double raytrace_max_range, double raytrace_min_range, tf2_ros::Buffer & tf2_buffer,
|
||||
std::string global_frame,
|
||||
std::string sensor_frame,
|
||||
tf2::Duration tf_tolerance)
|
||||
: tf2_buffer_(tf2_buffer),
|
||||
observation_keep_time_(rclcpp::Duration::from_seconds(observation_keep_time)),
|
||||
expected_update_rate_(rclcpp::Duration::from_seconds(expected_update_rate)),
|
||||
global_frame_(global_frame),
|
||||
sensor_frame_(sensor_frame),
|
||||
topic_name_(topic_name),
|
||||
min_obstacle_height_(min_obstacle_height), max_obstacle_height_(max_obstacle_height),
|
||||
obstacle_max_range_(obstacle_max_range), obstacle_min_range_(obstacle_min_range),
|
||||
raytrace_max_range_(raytrace_max_range), raytrace_min_range_(
|
||||
raytrace_min_range), tf_tolerance_(tf_tolerance)
|
||||
{
|
||||
auto node = parent.lock();
|
||||
clock_ = node->get_clock();
|
||||
logger_ = node->get_logger();
|
||||
last_updated_ = node->now();
|
||||
}
|
||||
|
||||
ObservationBuffer::~ObservationBuffer()
|
||||
{
|
||||
}
|
||||
|
||||
void ObservationBuffer::bufferCloud(const sensor_msgs::msg::PointCloud2 & cloud)
|
||||
{
|
||||
geometry_msgs::msg::PointStamped global_origin;
|
||||
|
||||
// create a new observation on the list to be populated
|
||||
observation_list_.push_front(Observation());
|
||||
|
||||
// check whether the origin frame has been set explicitly
|
||||
// or whether we should get it from the cloud
|
||||
std::string origin_frame = sensor_frame_ == "" ? cloud.header.frame_id : sensor_frame_;
|
||||
|
||||
try {
|
||||
// given these observations come from sensors...
|
||||
// we'll need to store the origin pt of the sensor
|
||||
geometry_msgs::msg::PointStamped local_origin;
|
||||
local_origin.header.stamp = cloud.header.stamp;
|
||||
local_origin.header.frame_id = origin_frame;
|
||||
local_origin.point.x = 0;
|
||||
local_origin.point.y = 0;
|
||||
local_origin.point.z = 0;
|
||||
tf2_buffer_.transform(local_origin, global_origin, global_frame_, tf_tolerance_);
|
||||
tf2::convert(global_origin.point, observation_list_.front().origin_);
|
||||
|
||||
// make sure to pass on the raytrace/obstacle range
|
||||
// of the observation buffer to the observations
|
||||
observation_list_.front().raytrace_max_range_ = raytrace_max_range_;
|
||||
observation_list_.front().raytrace_min_range_ = raytrace_min_range_;
|
||||
observation_list_.front().obstacle_max_range_ = obstacle_max_range_;
|
||||
observation_list_.front().obstacle_min_range_ = obstacle_min_range_;
|
||||
|
||||
sensor_msgs::msg::PointCloud2 global_frame_cloud;
|
||||
|
||||
// transform the point cloud
|
||||
tf2_buffer_.transform(cloud, global_frame_cloud, global_frame_, tf_tolerance_);
|
||||
global_frame_cloud.header.stamp = cloud.header.stamp;
|
||||
|
||||
// now we need to remove observations from the cloud that are below
|
||||
// or above our height thresholds
|
||||
sensor_msgs::msg::PointCloud2 & observation_cloud = *(observation_list_.front().cloud_);
|
||||
observation_cloud.height = global_frame_cloud.height;
|
||||
observation_cloud.width = global_frame_cloud.width;
|
||||
observation_cloud.fields = global_frame_cloud.fields;
|
||||
observation_cloud.is_bigendian = global_frame_cloud.is_bigendian;
|
||||
observation_cloud.point_step = global_frame_cloud.point_step;
|
||||
observation_cloud.row_step = global_frame_cloud.row_step;
|
||||
observation_cloud.is_dense = global_frame_cloud.is_dense;
|
||||
|
||||
unsigned int cloud_size = global_frame_cloud.height * global_frame_cloud.width;
|
||||
sensor_msgs::PointCloud2Modifier modifier(observation_cloud);
|
||||
modifier.resize(cloud_size);
|
||||
unsigned int point_count = 0;
|
||||
|
||||
// copy over the points that are within our height bounds
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_z(global_frame_cloud, "z");
|
||||
std::vector<unsigned char>::const_iterator iter_global = global_frame_cloud.data.begin(),
|
||||
iter_global_end = global_frame_cloud.data.end();
|
||||
std::vector<unsigned char>::iterator iter_obs = observation_cloud.data.begin();
|
||||
for (; iter_global != iter_global_end; ++iter_z, iter_global +=
|
||||
global_frame_cloud.point_step)
|
||||
{
|
||||
if ((*iter_z) <= max_obstacle_height_ &&
|
||||
(*iter_z) >= min_obstacle_height_)
|
||||
{
|
||||
std::copy(iter_global, iter_global + global_frame_cloud.point_step, iter_obs);
|
||||
iter_obs += global_frame_cloud.point_step;
|
||||
++point_count;
|
||||
}
|
||||
}
|
||||
|
||||
// resize the cloud for the number of legal points
|
||||
modifier.resize(point_count);
|
||||
observation_cloud.header.stamp = cloud.header.stamp;
|
||||
observation_cloud.header.frame_id = global_frame_cloud.header.frame_id;
|
||||
} catch (tf2::TransformException & ex) {
|
||||
// if an exception occurs, we need to remove the empty observation from the list
|
||||
observation_list_.pop_front();
|
||||
RCLCPP_ERROR(
|
||||
logger_,
|
||||
"TF Exception that should never happen for sensor frame: %s, cloud frame: %s, %s",
|
||||
sensor_frame_.c_str(),
|
||||
cloud.header.frame_id.c_str(), ex.what());
|
||||
return;
|
||||
}
|
||||
|
||||
// if the update was successful, we want to update the last updated time
|
||||
last_updated_ = clock_->now();
|
||||
|
||||
// we'll also remove any stale observations from the list
|
||||
purgeStaleObservations();
|
||||
}
|
||||
|
||||
// returns a copy of the observations
|
||||
void ObservationBuffer::getObservations(std::vector<Observation> & observations)
|
||||
{
|
||||
// first... let's make sure that we don't have any stale observations
|
||||
purgeStaleObservations();
|
||||
|
||||
// now we'll just copy the observations for the caller
|
||||
std::list<Observation>::iterator obs_it;
|
||||
for (obs_it = observation_list_.begin(); obs_it != observation_list_.end(); ++obs_it) {
|
||||
observations.push_back(*obs_it);
|
||||
}
|
||||
}
|
||||
|
||||
void ObservationBuffer::purgeStaleObservations()
|
||||
{
|
||||
if (!observation_list_.empty()) {
|
||||
std::list<Observation>::iterator obs_it = observation_list_.begin();
|
||||
// if we're keeping observations for no time... then we'll only keep one observation
|
||||
if (observation_keep_time_ == rclcpp::Duration(0.0s)) {
|
||||
observation_list_.erase(++obs_it, observation_list_.end());
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise... we'll have to loop through the observations to see which ones are stale
|
||||
for (obs_it = observation_list_.begin(); obs_it != observation_list_.end(); ++obs_it) {
|
||||
Observation & obs = *obs_it;
|
||||
// check if the observation is out of date... and if it is,
|
||||
// remove it and those that follow from the list
|
||||
if ((clock_->now() - obs.cloud_->header.stamp) >
|
||||
observation_keep_time_)
|
||||
{
|
||||
observation_list_.erase(obs_it, observation_list_.end());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ObservationBuffer::isCurrent() const
|
||||
{
|
||||
if (expected_update_rate_ == rclcpp::Duration(0.0s)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool current = (clock_->now() - last_updated_) <=
|
||||
expected_update_rate_;
|
||||
if (!current) {
|
||||
RCLCPP_WARN(
|
||||
logger_,
|
||||
"The %s observation buffer has not been updated for %.2f seconds, "
|
||||
"and it should be updated every %.2f seconds.",
|
||||
topic_name_.c_str(),
|
||||
(clock_->now() - last_updated_).seconds(),
|
||||
expected_update_rate_.seconds());
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
void ObservationBuffer::resetLastUpdated()
|
||||
{
|
||||
last_updated_ = clock_->now();
|
||||
}
|
||||
} // namespace nav2_costmap_2d
|
||||
@@ -0,0 +1,6 @@
|
||||
set(TEST_MAP_DIR ${CMAKE_CURRENT_SOURCE_DIR}/map)
|
||||
set(TEST_LAUNCH_DIR ${CMAKE_CURRENT_SOURCE_DIR}/test_launch_files)
|
||||
|
||||
add_subdirectory(unit)
|
||||
add_subdirectory(integration)
|
||||
add_subdirectory(regression)
|
||||
@@ -0,0 +1,31 @@
|
||||
global_frame: map
|
||||
robot_base_frame: base_link
|
||||
update_frequency: 5.0
|
||||
publish_frequency: 0.0
|
||||
static_map: true
|
||||
rolling_window: false
|
||||
|
||||
#START VOXEL STUFF
|
||||
map_type: voxel
|
||||
origin_z: 0.0
|
||||
z_resolution: 0.2
|
||||
z_voxels: 10
|
||||
unknown_threshold: 10
|
||||
mark_threshold: 0
|
||||
#END VOXEL STUFF
|
||||
|
||||
transform_tolerance: 0.3
|
||||
obstacle_max_range: 2.5
|
||||
obstacle_min_range: 0.0
|
||||
max_obstacle_height: 2.0
|
||||
raytrace_max_range: 3.0
|
||||
raytrace_min_range: 0.0
|
||||
footprint: [[-0.325, -0.325], [-0.325, 0.325], [0.325, 0.325], [0.46, 0.0], [0.325, -0.325]]
|
||||
#robot_radius: 0.46
|
||||
footprint_padding: 0.01
|
||||
inflation_radius: 0.55
|
||||
cost_scaling_factor: 10.0
|
||||
lethal_cost_threshold: 100
|
||||
observation_sources: base_scan
|
||||
base_scan: {data_type: LaserScan, expected_update_rate: 0.4,
|
||||
observation_persistence: 0.0, marking: true, clearing: true, max_obstacle_height: 0.4, min_obstacle_height: 0.08}
|
||||
@@ -0,0 +1,110 @@
|
||||
ament_add_gtest_executable(footprint_tests_exec
|
||||
footprint_tests.cpp
|
||||
)
|
||||
target_link_libraries(footprint_tests_exec
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::layers
|
||||
)
|
||||
|
||||
ament_add_gtest_executable(test_collision_checker_exec
|
||||
test_costmap_topic_collision_checker.cpp
|
||||
)
|
||||
target_link_libraries(test_collision_checker_exec
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::nav2_costmap_2d_client
|
||||
${PROJECT_NAME}::layers
|
||||
)
|
||||
|
||||
ament_add_gtest_executable(inflation_tests_exec
|
||||
inflation_tests.cpp
|
||||
)
|
||||
target_link_libraries(inflation_tests_exec
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::layers
|
||||
)
|
||||
|
||||
ament_add_gtest_executable(obstacle_tests_exec
|
||||
obstacle_tests.cpp
|
||||
)
|
||||
target_link_libraries(obstacle_tests_exec
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::layers
|
||||
)
|
||||
|
||||
ament_add_gtest_executable(range_tests_exec
|
||||
range_tests.cpp
|
||||
)
|
||||
target_link_libraries(range_tests_exec
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::layers
|
||||
)
|
||||
|
||||
ament_add_gtest(dyn_params_tests
|
||||
dyn_params_tests.cpp
|
||||
)
|
||||
target_link_libraries(dyn_params_tests
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_test(test_collision_checker
|
||||
GENERATE_RESULT_FOR_RETURN_CODE_ZERO
|
||||
COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/costmap_tests_launch.py"
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
ENV
|
||||
TEST_MAP=${TEST_MAP_DIR}/TenByTen.yaml
|
||||
TEST_LAUNCH_DIR=${TEST_LAUNCH_DIR}
|
||||
TEST_EXECUTABLE=$<TARGET_FILE:test_collision_checker_exec>
|
||||
)
|
||||
|
||||
ament_add_test(footprint_tests
|
||||
GENERATE_RESULT_FOR_RETURN_CODE_ZERO
|
||||
COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/costmap_tests_launch.py"
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
ENV
|
||||
TEST_MAP=${TEST_MAP_DIR}/TenByTen.yaml
|
||||
TEST_LAUNCH_DIR=${TEST_LAUNCH_DIR}
|
||||
TEST_EXECUTABLE=$<TARGET_FILE:footprint_tests_exec>
|
||||
)
|
||||
|
||||
ament_add_test(inflation_tests
|
||||
GENERATE_RESULT_FOR_RETURN_CODE_ZERO
|
||||
COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/costmap_tests_launch.py"
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
ENV
|
||||
TEST_MAP=${TEST_MAP_DIR}/TenByTen.yaml
|
||||
TEST_LAUNCH_DIR=${TEST_LAUNCH_DIR}
|
||||
TEST_EXECUTABLE=$<TARGET_FILE:inflation_tests_exec>
|
||||
)
|
||||
|
||||
ament_add_test(obstacle_tests
|
||||
GENERATE_RESULT_FOR_RETURN_CODE_ZERO
|
||||
COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/costmap_tests_launch.py"
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
ENV
|
||||
TEST_MAP=${TEST_MAP_DIR}/TenByTen.yaml
|
||||
TEST_LAUNCH_DIR=${TEST_LAUNCH_DIR}
|
||||
TEST_EXECUTABLE=$<TARGET_FILE:obstacle_tests_exec>
|
||||
)
|
||||
|
||||
ament_add_test(range_tests
|
||||
GENERATE_RESULT_FOR_RETURN_CODE_ZERO
|
||||
COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/costmap_tests_launch.py"
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
|
||||
ENV
|
||||
TEST_MAP=${TEST_MAP_DIR}/TenByTen.yaml
|
||||
TEST_LAUNCH_DIR=${TEST_LAUNCH_DIR}
|
||||
TEST_EXECUTABLE=$<TARGET_FILE:range_tests_exec>
|
||||
)
|
||||
|
||||
## TODO(bpwilcox): this test (I believe) is intended to be launched with the simple_driving_test.xml,
|
||||
## which has a dependency on rosbag playback
|
||||
# ament_add_gtest_executable(costmap_tester
|
||||
# costmap_tester.cpp
|
||||
# )
|
||||
# ament_target_dependencies(costmap_tester
|
||||
# ${dependencies}
|
||||
# )
|
||||
# target_link_libraries(costmap_tester
|
||||
# ${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
# layers
|
||||
# )
|
||||
@@ -0,0 +1,175 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2009, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Eitan Marder-Eppstein
|
||||
*********************************************************************/
|
||||
#include <memory>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "tf2_ros/transform_listener.h"
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros_;
|
||||
|
||||
class CostmapTester : public testing::Test
|
||||
{
|
||||
public:
|
||||
explicit CostmapTester(tf2_ros::Buffer & tf);
|
||||
void checkConsistentCosts();
|
||||
void compareCellToNeighbors(
|
||||
nav2_costmap_2d::Costmap2D & costmap,
|
||||
unsigned int x, unsigned int y);
|
||||
void compareCells(
|
||||
nav2_costmap_2d::Costmap2D & costmap,
|
||||
unsigned int x, unsigned int y, unsigned int nx, unsigned int ny);
|
||||
virtual void TestBody() {}
|
||||
};
|
||||
|
||||
CostmapTester::CostmapTester(tf2_ros::Buffer & tf)
|
||||
{
|
||||
costmap_ros_ = std::make_shared<nav2_costmap_2d::Costmap2DROS>("test_costmap", tf);
|
||||
}
|
||||
|
||||
void CostmapTester::checkConsistentCosts()
|
||||
{
|
||||
nav2_costmap_2d::Costmap2D * costmap = costmap_ros_->getCostmap();
|
||||
|
||||
// get a copy of the costmap contained by our ros wrapper
|
||||
costmap->saveMap("costmap_test.pgm");
|
||||
|
||||
// loop through the costmap and check for any unexpected drop-offs in costs
|
||||
for (unsigned int i = 0; i < costmap->getSizeInCellsX(); ++i) {
|
||||
for (unsigned int j = 0; j < costmap->getSizeInCellsY(); ++j) {
|
||||
compareCellToNeighbors(*costmap, i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CostmapTester::compareCellToNeighbors(
|
||||
nav2_costmap_2d::Costmap2D & costmap,
|
||||
unsigned int x, unsigned int y)
|
||||
{
|
||||
// we'll compare the cost of this cell with that of
|
||||
// its eight neighbors to see if they're reasonable
|
||||
for (int offset_x = -1; offset_x <= 1; ++offset_x) {
|
||||
for (int offset_y = -1; offset_y <= 1; ++offset_y) {
|
||||
int nx = x + offset_x;
|
||||
int ny = y + offset_y;
|
||||
|
||||
// check to make sure that the neighbor cell is a legal one
|
||||
if (nx >= 0 && nx < static_cast<int>(costmap.getSizeInCellsX()) && ny >= 0 &&
|
||||
ny < static_cast<int>(costmap.getSizeInCellsY()))
|
||||
{
|
||||
compareCells(costmap, x, y, nx, ny);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// for all lethal and inscribed costs,
|
||||
// we'll make sure that their neighbors have the cost values we'd expect
|
||||
void CostmapTester::compareCells(
|
||||
nav2_costmap_2d::Costmap2D & costmap,
|
||||
unsigned int x, unsigned int y, unsigned int nx, unsigned int ny)
|
||||
{
|
||||
double cell_distance = hypot(static_cast<int>(x - nx), static_cast<int>(y - ny));
|
||||
|
||||
unsigned char cell_cost = costmap.getCost(x, y);
|
||||
unsigned char neighbor_cost = costmap.getCost(nx, ny);
|
||||
|
||||
if (cell_cost == nav2_costmap_2d::LETHAL_OBSTACLE) {
|
||||
// if the cell is a lethal obstacle,
|
||||
// then we know that all its neighbors should have equal or slighlty less cost
|
||||
unsigned char expected_lowest_cost = 0;
|
||||
EXPECT_TRUE(
|
||||
neighbor_cost >= expected_lowest_cost ||
|
||||
(cell_distance > 0 && neighbor_cost == nav2_costmap_2d::FREE_SPACE));
|
||||
} else if (cell_cost == nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) {
|
||||
// the furthest valid distance from an obstacle
|
||||
// is the inscribed radius plus the cell distance away
|
||||
double furthest_valid_distance = 0;
|
||||
unsigned char expected_lowest_cost = 0;
|
||||
if (neighbor_cost < expected_lowest_cost) {
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger(
|
||||
"costmap_tester"),
|
||||
"Cell cost (%d, %d): %d, neighbor cost (%d, %d): %d, expected lowest cost: %d, cell distance: %.2f, furthest valid distance: %.2f", // NOLINT
|
||||
x, y, cell_cost, nx, ny, neighbor_cost, expected_lowest_cost,
|
||||
cell_distance, furthest_valid_distance);
|
||||
RCLCPP_ERROR(
|
||||
rclcpp::get_logger("costmap_tester"), "Cell: (%d, %d), Neighbor: (%d, %d)",
|
||||
x, y, nx, ny);
|
||||
costmap.saveMap("failing_costmap.pgm");
|
||||
}
|
||||
EXPECT_TRUE(
|
||||
neighbor_cost >= expected_lowest_cost ||
|
||||
(furthest_valid_distance > 0 && neighbor_cost == nav2_costmap_2d::FREE_SPACE));
|
||||
}
|
||||
}
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
nav2_costmap_2d::CostmapTester * map_tester = NULL;
|
||||
tf2_ros::TransformListener * tfl_;
|
||||
tf2_ros::Buffer * tf_;
|
||||
|
||||
TEST(CostmapTester, checkConsistentCosts) {
|
||||
map_tester->checkConsistentCosts();
|
||||
}
|
||||
|
||||
void testCallback()
|
||||
{
|
||||
int test_result = RUN_ALL_TESTS();
|
||||
RCLCPP_INFO(rclcpp::get_logger("costmap_tester"), "gtest return value: %d", test_result);
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
auto node = nav2_util::LifecycleNode::make_shared("costmap_tester");
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
tf_ = new tf2_ros::Buffer(node->get_clock());
|
||||
tfl_ = new tf2_ros::TransformListener(*tf_);
|
||||
map_tester = new nav2_costmap_2d::CostmapTester(*tf_);
|
||||
rclcpp::TimerBase::SharedPtr timer = node->create_wall_timer(30000ms, testCallback);
|
||||
rclcpp::spin(costmap_ros_);
|
||||
rclcpp::shutdown();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2018 Intel Corporation
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from launch import LaunchDescription
|
||||
from launch import LaunchService
|
||||
from launch.actions import ExecuteProcess
|
||||
from launch.actions import IncludeLaunchDescription
|
||||
from launch.launch_description_sources import PythonLaunchDescriptionSource
|
||||
import launch_ros.actions
|
||||
from launch_testing.legacy import LaunchTestService
|
||||
|
||||
|
||||
def main(argv=sys.argv[1:]):
|
||||
launchFile = os.path.join(os.getenv('TEST_LAUNCH_DIR'), 'costmap_map_server.launch.py')
|
||||
testExecutable = os.getenv('TEST_EXECUTABLE')
|
||||
|
||||
lifecycle_manager = launch_ros.actions.Node(
|
||||
package='nav2_lifecycle_manager',
|
||||
executable='lifecycle_manager',
|
||||
name='lifecycle_manager',
|
||||
output='screen',
|
||||
parameters=[{'node_names': ['map_server']}, {'autostart': True}])
|
||||
|
||||
ld = LaunchDescription([
|
||||
IncludeLaunchDescription(PythonLaunchDescriptionSource([launchFile])),
|
||||
lifecycle_manager
|
||||
])
|
||||
|
||||
test1_action = ExecuteProcess(
|
||||
cmd=[testExecutable],
|
||||
name='costmap_tests',
|
||||
output='screen'
|
||||
)
|
||||
|
||||
lts = LaunchTestService()
|
||||
lts.add_test_action(ld, test1_action)
|
||||
ls = LaunchService(argv=argv)
|
||||
ls.include_launch_description(ld)
|
||||
return lts.run(ls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) 2021 Wyca Robotics
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
#include "tf2_ros/transform_broadcaster.h"
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class DynParamTestNode
|
||||
{
|
||||
public:
|
||||
DynParamTestNode() {}
|
||||
~DynParamTestNode() {}
|
||||
};
|
||||
|
||||
TEST(DynParamTestNode, testDynParamsSet)
|
||||
{
|
||||
auto node = std::make_shared<rclcpp_lifecycle::LifecycleNode>("dyn_param_tester");
|
||||
auto costmap = std::make_shared<nav2_costmap_2d::Costmap2DROS>("test_costmap");
|
||||
costmap->on_configure(rclcpp_lifecycle::State());
|
||||
|
||||
// Set tf between default global_frame and robot_base_frame in order not to block in on_activate
|
||||
std::unique_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster_ =
|
||||
std::make_unique<tf2_ros::TransformBroadcaster>(node);
|
||||
geometry_msgs::msg::TransformStamped t;
|
||||
t.header.stamp = node->get_clock()->now();
|
||||
t.header.frame_id = "map";
|
||||
t.child_frame_id = "base_link";
|
||||
tf_broadcaster_->sendTransform(t);
|
||||
t.header.frame_id = "map";
|
||||
t.child_frame_id = "test_frame";
|
||||
tf_broadcaster_->sendTransform(t);
|
||||
|
||||
costmap->on_activate(rclcpp_lifecycle::State());
|
||||
|
||||
auto parameter_client = std::make_shared<rclcpp::AsyncParametersClient>(
|
||||
node->shared_from_this(),
|
||||
"/test_costmap/test_costmap",
|
||||
rmw_qos_profile_parameters);
|
||||
auto results1 = parameter_client->set_parameters_atomically(
|
||||
{
|
||||
rclcpp::Parameter("robot_radius", 1.234),
|
||||
rclcpp::Parameter("footprint_padding", 2.345),
|
||||
rclcpp::Parameter("transform_tolerance", 3.456),
|
||||
rclcpp::Parameter("publish_frequency", 4.567),
|
||||
rclcpp::Parameter("resolution", 5.678),
|
||||
rclcpp::Parameter("origin_x", 6.789),
|
||||
rclcpp::Parameter("origin_y", 7.891),
|
||||
rclcpp::Parameter("width", 2),
|
||||
rclcpp::Parameter("height", 3),
|
||||
rclcpp::Parameter(
|
||||
"footprint",
|
||||
"[[-0.325, -0.325], [-0.325, 0.325], [0.325, 0.325], [0.46, 0.0], [0.325, -0.325]]"),
|
||||
rclcpp::Parameter("robot_base_frame", "test_frame"),
|
||||
});
|
||||
|
||||
// Try setting robot_base_frame to an invalid frame, should be rejected
|
||||
auto results2 = parameter_client->set_parameters_atomically(
|
||||
{
|
||||
rclcpp::Parameter("robot_base_frame", "wrong_test_frame"),
|
||||
});
|
||||
|
||||
rclcpp::spin_some(costmap->get_node_base_interface());
|
||||
|
||||
EXPECT_EQ(costmap->get_parameter("robot_radius").as_double(), 1.234);
|
||||
EXPECT_EQ(costmap->get_parameter("footprint_padding").as_double(), 2.345);
|
||||
EXPECT_EQ(costmap->get_parameter("transform_tolerance").as_double(), 3.456);
|
||||
EXPECT_EQ(costmap->get_parameter("publish_frequency").as_double(), 4.567);
|
||||
EXPECT_EQ(costmap->get_parameter("resolution").as_double(), 5.678);
|
||||
EXPECT_EQ(costmap->get_parameter("origin_x").as_double(), 6.789);
|
||||
EXPECT_EQ(costmap->get_parameter("origin_y").as_double(), 7.891);
|
||||
EXPECT_EQ(costmap->get_parameter("width").as_int(), 2);
|
||||
EXPECT_EQ(costmap->get_parameter("height").as_int(), 3);
|
||||
EXPECT_EQ(
|
||||
costmap->get_parameter("footprint").as_string(),
|
||||
"[[-0.325, -0.325], [-0.325, 0.325], [0.325, 0.325], [0.46, 0.0], [0.325, -0.325]]");
|
||||
EXPECT_EQ(costmap->get_parameter("robot_base_frame").as_string(), "test_frame");
|
||||
|
||||
costmap->on_deactivate(rclcpp_lifecycle::State());
|
||||
costmap->on_cleanup(rclcpp_lifecycle::State());
|
||||
costmap->on_shutdown(rclcpp_lifecycle::State());
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2009, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Dave Hershberger
|
||||
*********************************************************************/
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "tf2_geometry_msgs/tf2_geometry_msgs.hpp"
|
||||
#include "tf2_ros/transform_listener.h"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class FootprintTestNode
|
||||
{
|
||||
public:
|
||||
FootprintTestNode()
|
||||
{
|
||||
// Default footprint padding and footprint radius from Costmap2DROS
|
||||
testFootprint(0.01f, 0.1);
|
||||
}
|
||||
|
||||
~FootprintTestNode() {}
|
||||
|
||||
void testFootprint(double footprint_padding, std::string footprint)
|
||||
{
|
||||
footprint_padding_ = footprint_padding;
|
||||
if (footprint != "" && footprint != "[]") {
|
||||
std::vector<geometry_msgs::msg::Point> new_footprint;
|
||||
if (nav2_costmap_2d::makeFootprintFromString(footprint, new_footprint)) {
|
||||
setRobotFootprint(new_footprint);
|
||||
} else {
|
||||
RCLCPP_ERROR(rclcpp::get_logger("footprint_tester"), "Invalid footprint string");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void testFootprint(double footprint_padding, double robot_radius)
|
||||
{
|
||||
footprint_padding_ = footprint_padding;
|
||||
setRobotFootprint(nav2_costmap_2d::makeFootprintFromRadius(robot_radius));
|
||||
}
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> getRobotFootprint()
|
||||
{
|
||||
return footprint_;
|
||||
}
|
||||
|
||||
protected:
|
||||
void setRobotFootprint(const std::vector<geometry_msgs::msg::Point> & points)
|
||||
{
|
||||
footprint_ = points;
|
||||
nav2_costmap_2d::padFootprint(footprint_, footprint_padding_);
|
||||
}
|
||||
|
||||
double footprint_padding_;
|
||||
std::vector<geometry_msgs::msg::Point> footprint_;
|
||||
};
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode()
|
||||
{
|
||||
footprint_tester_ = std::make_shared<FootprintTestNode>();
|
||||
}
|
||||
|
||||
~TestNode() {}
|
||||
|
||||
protected:
|
||||
std::shared_ptr<FootprintTestNode> footprint_tester_;
|
||||
};
|
||||
|
||||
// Start with empty test before updating test footprints
|
||||
TEST_F(TestNode, footprint_empty)
|
||||
{
|
||||
// FootprintTestNode cm("costmap_footprint_empty", *tf_);
|
||||
std::vector<geometry_msgs::msg::Point> footprint = footprint_tester_->getRobotFootprint();
|
||||
// With no specification of footprint or radius,
|
||||
// defaults to 0.1 meter radius plus 0.01 meter padding.
|
||||
EXPECT_EQ(16u, footprint.size());
|
||||
|
||||
EXPECT_NEAR(0.11f, footprint[0].x, 0.0001);
|
||||
EXPECT_NEAR(0.0f, footprint[0].y, 0.0001);
|
||||
EXPECT_EQ(0.0f, footprint[0].z);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, unpadded_footprint_from_string_param)
|
||||
{
|
||||
footprint_tester_->testFootprint(0.0, "[[1, 1], [-1, 1], [-1, -1]]");
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> footprint = footprint_tester_->getRobotFootprint();
|
||||
EXPECT_EQ(3u, footprint.size());
|
||||
|
||||
EXPECT_EQ(1.0f, footprint[0].x);
|
||||
EXPECT_EQ(1.0f, footprint[0].y);
|
||||
EXPECT_EQ(0.0f, footprint[0].z);
|
||||
|
||||
EXPECT_EQ(-1.0f, footprint[1].x);
|
||||
EXPECT_EQ(1.0f, footprint[1].y);
|
||||
EXPECT_EQ(0.0f, footprint[1].z);
|
||||
|
||||
EXPECT_EQ(-1.0f, footprint[2].x);
|
||||
EXPECT_EQ(-1.0f, footprint[2].y);
|
||||
EXPECT_EQ(0.0f, footprint[2].z);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, padded_footprint_from_string_param)
|
||||
{
|
||||
footprint_tester_->testFootprint(0.5, "[[1, 1], [-1, 1], [-1, -1]]");
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> footprint = footprint_tester_->getRobotFootprint();
|
||||
EXPECT_EQ(3u, footprint.size());
|
||||
|
||||
EXPECT_EQ(1.5f, footprint[0].x);
|
||||
EXPECT_EQ(1.5f, footprint[0].y);
|
||||
EXPECT_EQ(0.0f, footprint[0].z);
|
||||
|
||||
EXPECT_EQ(-1.5f, footprint[1].x);
|
||||
EXPECT_EQ(1.5f, footprint[1].y);
|
||||
EXPECT_EQ(0.0f, footprint[1].z);
|
||||
|
||||
EXPECT_EQ(-1.5f, footprint[2].x);
|
||||
EXPECT_EQ(-1.5f, footprint[2].y);
|
||||
EXPECT_EQ(0.0f, footprint[2].z);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, radius_param)
|
||||
{
|
||||
footprint_tester_->testFootprint(0, 10.0);
|
||||
std::vector<geometry_msgs::msg::Point> footprint = footprint_tester_->getRobotFootprint();
|
||||
// Circular robot has 16-point footprint auto-generated.
|
||||
EXPECT_EQ(16u, footprint.size());
|
||||
|
||||
// Check the first point
|
||||
EXPECT_EQ(10.0f, footprint[0].x);
|
||||
EXPECT_EQ(0.0f, footprint[0].y);
|
||||
EXPECT_EQ(0.0f, footprint[0].z);
|
||||
|
||||
// Check the 4th point, which should be 90 degrees around the circle from the first.
|
||||
EXPECT_NEAR(0.0f, footprint[4].x, 0.0001);
|
||||
EXPECT_NEAR(10.0f, footprint[4].y, 0.0001);
|
||||
EXPECT_EQ(0.0f, footprint[4].z);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, footprint_from_same_level_param)
|
||||
{
|
||||
footprint_tester_->testFootprint(0.0, "[[1, 2], [3, 4], [5, 6]]");
|
||||
std::vector<geometry_msgs::msg::Point> footprint = footprint_tester_->getRobotFootprint();
|
||||
EXPECT_EQ(3u, footprint.size());
|
||||
|
||||
EXPECT_EQ(1.0f, footprint[0].x);
|
||||
EXPECT_EQ(2.0f, footprint[0].y);
|
||||
EXPECT_EQ(0.0f, footprint[0].z);
|
||||
|
||||
EXPECT_EQ(3.0f, footprint[1].x);
|
||||
EXPECT_EQ(4.0f, footprint[1].y);
|
||||
EXPECT_EQ(0.0f, footprint[1].z);
|
||||
|
||||
EXPECT_EQ(5.0f, footprint[2].x);
|
||||
EXPECT_EQ(6.0f, footprint[2].y);
|
||||
EXPECT_EQ(0.0f, footprint[2].z);
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
/*
|
||||
* Copyright (c) 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @author David Lu!!
|
||||
* Test harness for InflationLayer for Costmap2D
|
||||
*/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_costmap_2d/obstacle_layer.hpp"
|
||||
#include "nav2_costmap_2d/inflation_layer.hpp"
|
||||
#include "nav2_costmap_2d/observation_buffer.hpp"
|
||||
#include "../testing_helper.hpp"
|
||||
#include "nav2_util/node_utils.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
|
||||
using geometry_msgs::msg::Point;
|
||||
using nav2_costmap_2d::CellData;
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode() {}
|
||||
|
||||
~TestNode() {}
|
||||
|
||||
std::vector<Point> setRadii(
|
||||
nav2_costmap_2d::LayeredCostmap & layers,
|
||||
double length, double width);
|
||||
|
||||
void validatePointInflation(
|
||||
unsigned int mx, unsigned int my,
|
||||
nav2_costmap_2d::Costmap2D * costmap,
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> & ilayer,
|
||||
double inflation_radius);
|
||||
|
||||
void initNode(std::vector<rclcpp::Parameter> parameters);
|
||||
void initNode(double inflation_radius);
|
||||
|
||||
void waitForMap(std::shared_ptr<nav2_costmap_2d::StaticLayer> & slayer);
|
||||
|
||||
protected:
|
||||
nav2_util::LifecycleNode::SharedPtr node_;
|
||||
};
|
||||
|
||||
std::vector<Point> TestNode::setRadii(
|
||||
nav2_costmap_2d::LayeredCostmap & layers,
|
||||
double length, double width)
|
||||
{
|
||||
std::vector<Point> polygon;
|
||||
Point p;
|
||||
p.x = width;
|
||||
p.y = length;
|
||||
polygon.push_back(p);
|
||||
p.x = width;
|
||||
p.y = -length;
|
||||
polygon.push_back(p);
|
||||
p.x = -width;
|
||||
p.y = -length;
|
||||
polygon.push_back(p);
|
||||
p.x = -width;
|
||||
p.y = length;
|
||||
polygon.push_back(p);
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
return polygon;
|
||||
}
|
||||
|
||||
void TestNode::waitForMap(std::shared_ptr<nav2_costmap_2d::StaticLayer> & slayer)
|
||||
{
|
||||
while (!slayer->isCurrent()) {
|
||||
rclcpp::spin_some(node_->get_node_base_interface());
|
||||
}
|
||||
}
|
||||
|
||||
// Test that a single point gets inflated properly
|
||||
void TestNode::validatePointInflation(
|
||||
unsigned int mx, unsigned int my,
|
||||
nav2_costmap_2d::Costmap2D * costmap,
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> & ilayer,
|
||||
double inflation_radius)
|
||||
{
|
||||
bool * seen = new bool[costmap->getSizeInCellsX() * costmap->getSizeInCellsY()];
|
||||
memset(seen, false, costmap->getSizeInCellsX() * costmap->getSizeInCellsY() * sizeof(bool));
|
||||
std::map<double, std::vector<CellData>> m;
|
||||
CellData initial(costmap->getIndex(mx, my), mx, my, mx, my);
|
||||
m[0].push_back(initial);
|
||||
for (std::map<double, std::vector<CellData>>::iterator bin = m.begin();
|
||||
bin != m.end(); ++bin)
|
||||
{
|
||||
for (unsigned int i = 0; i < bin->second.size(); ++i) {
|
||||
const CellData cell = bin->second[i];
|
||||
if (!seen[cell.index_]) {
|
||||
seen[cell.index_] = true;
|
||||
unsigned int dx = (cell.x_ > cell.src_x_) ? cell.x_ - cell.src_x_ : cell.src_x_ - cell.x_;
|
||||
unsigned int dy = (cell.y_ > cell.src_y_) ? cell.y_ - cell.src_y_ : cell.src_y_ - cell.y_;
|
||||
double dist = std::hypot(dx, dy);
|
||||
|
||||
unsigned char expected_cost = ilayer->computeCost(dist);
|
||||
ASSERT_TRUE(costmap->getCost(cell.x_, cell.y_) >= expected_cost);
|
||||
|
||||
if (dist > inflation_radius) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dist == bin->first) {
|
||||
// Adding to our current bin could cause a reallocation
|
||||
// Which appears to cause the iterator to get messed up
|
||||
dist += 0.001;
|
||||
}
|
||||
|
||||
if (cell.x_ > 0) {
|
||||
CellData data(costmap->getIndex(cell.x_ - 1, cell.y_),
|
||||
cell.x_ - 1, cell.y_, cell.src_x_, cell.src_y_);
|
||||
m[dist].push_back(data);
|
||||
}
|
||||
if (cell.y_ > 0) {
|
||||
CellData data(costmap->getIndex(cell.x_, cell.y_ - 1),
|
||||
cell.x_, cell.y_ - 1, cell.src_x_, cell.src_y_);
|
||||
m[dist].push_back(data);
|
||||
}
|
||||
if (cell.x_ < costmap->getSizeInCellsX() - 1) {
|
||||
CellData data(costmap->getIndex(cell.x_ + 1, cell.y_),
|
||||
cell.x_ + 1, cell.y_, cell.src_x_, cell.src_y_);
|
||||
m[dist].push_back(data);
|
||||
}
|
||||
if (cell.y_ < costmap->getSizeInCellsY() - 1) {
|
||||
CellData data(costmap->getIndex(cell.x_, cell.y_ + 1),
|
||||
cell.x_, cell.y_ + 1, cell.src_x_, cell.src_y_);
|
||||
m[dist].push_back(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
delete[] seen;
|
||||
}
|
||||
|
||||
void TestNode::initNode(std::vector<rclcpp::Parameter> parameters)
|
||||
{
|
||||
auto options = rclcpp::NodeOptions();
|
||||
options.parameter_overrides(parameters);
|
||||
|
||||
node_ = std::make_shared<nav2_util::LifecycleNode>(
|
||||
"inflation_test_node", "", options);
|
||||
|
||||
// Declare non-plugin specific costmap parameters
|
||||
node_->declare_parameter("map_topic", rclcpp::ParameterValue(std::string("map")));
|
||||
node_->declare_parameter("track_unknown_space", rclcpp::ParameterValue(false));
|
||||
node_->declare_parameter("use_maximum", rclcpp::ParameterValue(false));
|
||||
node_->declare_parameter("lethal_cost_threshold", rclcpp::ParameterValue(100));
|
||||
node_->declare_parameter(
|
||||
"unknown_cost_value",
|
||||
rclcpp::ParameterValue(static_cast<unsigned char>(0xff)));
|
||||
node_->declare_parameter("trinary_costmap", rclcpp::ParameterValue(true));
|
||||
node_->declare_parameter("transform_tolerance", rclcpp::ParameterValue(0.3));
|
||||
node_->declare_parameter("observation_sources", rclcpp::ParameterValue(std::string("")));
|
||||
}
|
||||
|
||||
void TestNode::initNode(double inflation_radius)
|
||||
{
|
||||
std::vector<rclcpp::Parameter> parameters;
|
||||
// Set cost_scaling_factor parameter to 1.0 for inflation layer
|
||||
parameters.push_back(rclcpp::Parameter("inflation.cost_scaling_factor", 1.0));
|
||||
parameters.push_back(rclcpp::Parameter("inflation.inflation_radius", inflation_radius));
|
||||
|
||||
initNode(parameters);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testAdjacentToObstacleCanStillMove)
|
||||
{
|
||||
initNode(4.1);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 2.1, 2.3);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
addObservation(olayer, 0, 0, MAX_Z);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
// printMap(*costmap);
|
||||
EXPECT_EQ(nav2_costmap_2d::LETHAL_OBSTACLE, costmap->getCost(0, 0));
|
||||
EXPECT_EQ(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, costmap->getCost(1, 0));
|
||||
EXPECT_EQ(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, costmap->getCost(2, 0));
|
||||
EXPECT_TRUE(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE > costmap->getCost(3, 0));
|
||||
EXPECT_TRUE(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE > costmap->getCost(2, 1));
|
||||
EXPECT_EQ(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, costmap->getCost(1, 1));
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testInflationShouldNotCreateUnknowns)
|
||||
{
|
||||
initNode(4.1);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 2.1, 2.3);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
addObservation(olayer, 0, 0, MAX_Z);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
|
||||
EXPECT_EQ(countValues(*costmap, nav2_costmap_2d::NO_INFORMATION), 0u);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testInflationInUnkown)
|
||||
{
|
||||
std::vector<rclcpp::Parameter> parameters;
|
||||
// Set cost_scaling_factor parameter to 1.0 for inflation layer
|
||||
parameters.push_back(rclcpp::Parameter("inflation.cost_scaling_factor", 1.0));
|
||||
parameters.push_back(rclcpp::Parameter("inflation.inflation_radius", 4.1));
|
||||
parameters.push_back(rclcpp::Parameter("inflation.inflate_unknown", true));
|
||||
|
||||
initNode(parameters);
|
||||
|
||||
node_->set_parameter(rclcpp::Parameter("track_unknown_space", true));
|
||||
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, true);
|
||||
layers.resizeMap(9, 9, 1, 0, 0);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 2.1, 2.3);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
addObservation(olayer, 4, 4, MAX_Z, 0.0, 0.0, MAX_Z, true, false);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
|
||||
// Only the 4 corners of the map should remain unknown
|
||||
EXPECT_EQ(countValues(*costmap, nav2_costmap_2d::NO_INFORMATION), 4u);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testInflationAroundUnkown)
|
||||
{
|
||||
auto inflation_radius = 4.1;
|
||||
std::vector<rclcpp::Parameter> parameters;
|
||||
// Set cost_scaling_factor parameter to 1.0 for inflation layer
|
||||
parameters.push_back(rclcpp::Parameter("inflation.cost_scaling_factor", 1.0));
|
||||
parameters.push_back(rclcpp::Parameter("inflation.inflation_radius", inflation_radius));
|
||||
parameters.push_back(rclcpp::Parameter("inflation.inflate_around_unknown", true));
|
||||
|
||||
initNode(parameters);
|
||||
|
||||
node_->set_parameter(rclcpp::Parameter("track_unknown_space", true));
|
||||
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 2.1, 2.3);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
layers.setFootprint(polygon);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
layers.getCostmap()->setCost(4, 4, nav2_costmap_2d::NO_INFORMATION);
|
||||
ilayer->updateCosts(*layers.getCostmap(), 0, 0, 10, 10);
|
||||
|
||||
validatePointInflation(4, 4, layers.getCostmap(), ilayer, inflation_radius);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for the cost function correctness with a larger range and different values
|
||||
*/
|
||||
TEST_F(TestNode, testCostFunctionCorrectness)
|
||||
{
|
||||
initNode(10.5);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
|
||||
layers.resizeMap(100, 100, 1, 0, 0);
|
||||
// Footprint with inscribed radius = 5.0
|
||||
// circumscribed radius = 8.0
|
||||
std::vector<Point> polygon = setRadii(layers, 5.0, 6.25);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
addObservation(olayer, 50, 50, MAX_Z);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
nav2_costmap_2d::Costmap2D * map = layers.getCostmap();
|
||||
|
||||
// Verify that the circumscribed cost lower bound is as expected: based on the cost function.
|
||||
// unsigned char c = ilayer->computeCost(8.0);
|
||||
// ASSERT_EQ(ilayer->getCircumscribedCost(), c);
|
||||
|
||||
for (unsigned int i = 0; i <= (unsigned int)ceil(5.0); i++) {
|
||||
// To the right
|
||||
ASSERT_EQ(map->getCost(50 + i, 50) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
ASSERT_EQ(map->getCost(50 + i, 50) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
// To the left
|
||||
ASSERT_EQ(map->getCost(50 - i, 50) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
ASSERT_EQ(map->getCost(50 - i, 50) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
// Down
|
||||
ASSERT_EQ(map->getCost(50, 50 + i) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
ASSERT_EQ(map->getCost(50, 50 + i) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
// Up
|
||||
ASSERT_EQ(map->getCost(50, 50 - i) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
ASSERT_EQ(map->getCost(50, 50 - i) >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
}
|
||||
|
||||
// Verify the normalized cost attenuates as expected
|
||||
for (unsigned int i = (unsigned int)(ceil(5.0) + 1); i <= (unsigned int)ceil(10.5); i++) {
|
||||
unsigned char expectedValue = ilayer->computeCost(i / 1.0);
|
||||
ASSERT_EQ(map->getCost(50 + i, 50), expectedValue);
|
||||
}
|
||||
|
||||
// Update with no hits. Should clear (revert to the static map
|
||||
/*map->resetMapOutsideWindow(0, 0, 0.0, 0.0);
|
||||
cloud.points.resize(0);
|
||||
|
||||
p.x = 0.0;
|
||||
p.y = 0.0;
|
||||
p.z = MAX_Z;
|
||||
|
||||
Observation obs2(p, cloud, 100.0, 100.0);
|
||||
std::vector<Observation> obsBuf2;
|
||||
obsBuf2.push_back(obs2);
|
||||
|
||||
map->updateWorld(0, 0, obsBuf2, obsBuf2);
|
||||
|
||||
for(unsigned int i = 0; i < 100; i++)
|
||||
for(unsigned int j = 0; j < 100; j++)
|
||||
ASSERT_EQ(map->getCost(i, j), nav2_costmap_2d::FREE_SPACE);*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that there is no regression and that costs do not get
|
||||
* underestimated with the distance-as-key map used to replace
|
||||
* the previously used priority queue. This is a more thorough
|
||||
* test of the cost function being correctly applied.
|
||||
*/
|
||||
TEST_F(TestNode, testInflationOrderCorrectness)
|
||||
{
|
||||
const double inflation_radius = 4.1;
|
||||
initNode(inflation_radius);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 2.1, 2.3);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
// Add two diagonal cells, they would induce problems under the
|
||||
// previous implementations
|
||||
addObservation(olayer, 4, 4, MAX_Z);
|
||||
addObservation(olayer, 5, 5, MAX_Z);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
validatePointInflation(4, 4, layers.getCostmap(), ilayer, inflation_radius);
|
||||
validatePointInflation(5, 5, layers.getCostmap(), ilayer, inflation_radius);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test inflation for both static and dynamic obstacles
|
||||
*/
|
||||
TEST_F(TestNode, testInflation)
|
||||
{
|
||||
initNode(1);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 1, 1);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::StaticLayer> slayer = nullptr;
|
||||
addStaticLayer(layers, tf, node_, slayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
waitForMap(slayer);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
// printMap(*costmap);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 20u);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE), 28u);
|
||||
|
||||
/*/ Iterate over all id's and verify they are obstacles
|
||||
for(std::vector<unsigned int>::const_iterator it = occupiedCells.begin(); it != occupiedCells.end(); ++it){
|
||||
unsigned int ind = *it;
|
||||
unsigned int x, y;
|
||||
map.indexToCells(ind, x, y);
|
||||
ASSERT_EQ(find(occupiedCells, map.getIndex(x, y)), true);
|
||||
ASSERT_EQ(map.getCost(x, y) == nav2_costmap_2d::LETHAL_OBSTACLE ||
|
||||
map.getCost(x, y) == nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE, true);
|
||||
}*/
|
||||
|
||||
addObservation(olayer, 0, 0, 0.4);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
// It and its 2 neighbors makes 3 obstacles
|
||||
ASSERT_EQ(
|
||||
countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE) +
|
||||
countValues(*costmap, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE), 51u);
|
||||
|
||||
// @todo Rewrite
|
||||
// Add an obstacle at <2,0> which will inflate and refresh to of the other inflated cells
|
||||
addObservation(olayer, 2, 0);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
// Now we expect insertions for it, and 2 more neighbors, but not all 5.
|
||||
// Free space will propagate from
|
||||
// the origin to the target, clearing the point at <0, 0>,
|
||||
// but not over-writing the inflation of the obstacle
|
||||
// at <0, 1>
|
||||
ASSERT_EQ(
|
||||
countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE) +
|
||||
countValues(*costmap, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE), 54u);
|
||||
|
||||
// Add an obstacle at <1, 9>. This will inflate obstacles around it
|
||||
addObservation(olayer, 1, 9);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
ASSERT_EQ(costmap->getCost(1, 9), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
ASSERT_EQ(costmap->getCost(0, 9), nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
|
||||
ASSERT_EQ(costmap->getCost(2, 9), nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
|
||||
|
||||
// Add an obstacle and verify that it over-writes its inflated status
|
||||
addObservation(olayer, 0, 9);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
ASSERT_EQ(costmap->getCost(0, 9), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test specific inflation scenario to ensure we do not set inflated obstacles to be raw obstacles.
|
||||
*/
|
||||
TEST_F(TestNode, testInflation2)
|
||||
{
|
||||
initNode(1);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
|
||||
// Footprint with inscribed radius = 2.1
|
||||
// circumscribed radius = 3.1
|
||||
std::vector<Point> polygon = setRadii(layers, 1, 1);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::StaticLayer> slayer = nullptr;
|
||||
addStaticLayer(layers, tf, node_, slayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
waitForMap(slayer);
|
||||
|
||||
// Creat a small L-Shape all at once
|
||||
addObservation(olayer, 1, 1, MAX_Z);
|
||||
addObservation(olayer, 2, 1, MAX_Z);
|
||||
addObservation(olayer, 2, 2, MAX_Z);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
// printMap(*costmap);
|
||||
ASSERT_EQ(costmap->getCost(2, 3), nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
|
||||
ASSERT_EQ(costmap->getCost(3, 3), nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test inflation behavior, starting with an empty map
|
||||
*/
|
||||
TEST_F(TestNode, testInflation3)
|
||||
{
|
||||
initNode(3);
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
// 1 2 3
|
||||
std::vector<Point> polygon = setRadii(layers, 1, 1.75);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(layers, tf, node_, ilayer);
|
||||
|
||||
layers.setFootprint(polygon);
|
||||
|
||||
// There should be no occupied cells
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 0u);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE), 0u);
|
||||
printMap(*costmap);
|
||||
// Add an obstacle at 5,5
|
||||
addObservation(olayer, 5, 5, MAX_Z);
|
||||
layers.updateMap(0, 0, 0);
|
||||
printMap(*costmap);
|
||||
|
||||
// Test fails because updated cell value is 0
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::FREE_SPACE, false), 29u);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 1u);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE), 4u);
|
||||
|
||||
// Update again - should see no change
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::FREE_SPACE, false), 29u);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 1u);
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE), 4u);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test dynamic parameter setting of inflation layer
|
||||
*/
|
||||
TEST_F(TestNode, testDynParamsSet)
|
||||
{
|
||||
auto costmap = std::make_shared<nav2_costmap_2d::Costmap2DROS>("test_costmap");
|
||||
|
||||
costmap->set_parameter(rclcpp::Parameter("global_frame", std::string("base_link")));
|
||||
costmap->on_configure(rclcpp_lifecycle::State());
|
||||
|
||||
costmap->on_activate(rclcpp_lifecycle::State());
|
||||
|
||||
auto parameter_client = std::make_shared<rclcpp::AsyncParametersClient>(
|
||||
costmap->get_node_base_interface(), costmap->get_node_topics_interface(),
|
||||
costmap->get_node_graph_interface(),
|
||||
costmap->get_node_services_interface());
|
||||
|
||||
auto results = parameter_client->set_parameters_atomically(
|
||||
{
|
||||
rclcpp::Parameter("inflation_layer.inflation_radius", 0.0),
|
||||
rclcpp::Parameter("inflation_layer.cost_scaling_factor", 0.0),
|
||||
rclcpp::Parameter("inflation_layer.inflate_unknown", true),
|
||||
rclcpp::Parameter("inflation_layer.inflate_around_unknown", true),
|
||||
rclcpp::Parameter("inflation_layer.enabled", false)
|
||||
});
|
||||
|
||||
rclcpp::spin_until_future_complete(
|
||||
costmap->get_node_base_interface(),
|
||||
results);
|
||||
|
||||
EXPECT_EQ(costmap->get_parameter("inflation_layer.inflation_radius").as_double(), 0.0);
|
||||
EXPECT_EQ(costmap->get_parameter("inflation_layer.cost_scaling_factor").as_double(), 0.0);
|
||||
EXPECT_EQ(costmap->get_parameter("inflation_layer.inflate_unknown").as_bool(), true);
|
||||
EXPECT_EQ(costmap->get_parameter("inflation_layer.inflate_around_unknown").as_bool(), true);
|
||||
EXPECT_EQ(costmap->get_parameter("inflation_layer.enabled").as_bool(), false);
|
||||
|
||||
costmap->on_deactivate(rclcpp_lifecycle::State());
|
||||
costmap->on_cleanup(rclcpp_lifecycle::State());
|
||||
costmap->on_shutdown(rclcpp_lifecycle::State());
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
/*
|
||||
* Copyright (c) 2013, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @author David Lu!!
|
||||
* Test harness for ObstacleLayer for Costmap2D
|
||||
*/
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_costmap_2d/observation_buffer.hpp"
|
||||
#include "../testing_helper.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d_ros.hpp"
|
||||
|
||||
using std::begin;
|
||||
using std::end;
|
||||
using std::for_each;
|
||||
using std::all_of;
|
||||
using std::none_of;
|
||||
using std::pair;
|
||||
using std::string;
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class TestLifecycleNode : public nav2_util::LifecycleNode
|
||||
{
|
||||
public:
|
||||
explicit TestLifecycleNode(const string & name)
|
||||
: nav2_util::LifecycleNode(name)
|
||||
{
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_configure(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_activate(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_deactivate(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_cleanup(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn onShutdown(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn onError(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
};
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode()
|
||||
{
|
||||
node_ = std::make_shared<TestLifecycleNode>("obstacle_test_node");
|
||||
node_->declare_parameter("map_topic", rclcpp::ParameterValue(std::string("map")));
|
||||
node_->declare_parameter("track_unknown_space", rclcpp::ParameterValue(false));
|
||||
node_->declare_parameter("use_maximum", rclcpp::ParameterValue(false));
|
||||
node_->declare_parameter("lethal_cost_threshold", rclcpp::ParameterValue(100));
|
||||
node_->declare_parameter(
|
||||
"unknown_cost_value",
|
||||
rclcpp::ParameterValue(static_cast<unsigned char>(0xff)));
|
||||
node_->declare_parameter("trinary_costmap", rclcpp::ParameterValue(true));
|
||||
node_->declare_parameter("transform_tolerance", rclcpp::ParameterValue(0.3));
|
||||
node_->declare_parameter("observation_sources", rclcpp::ParameterValue(std::string("")));
|
||||
}
|
||||
|
||||
~TestNode() {}
|
||||
|
||||
protected:
|
||||
std::shared_ptr<TestLifecycleNode> node_;
|
||||
};
|
||||
|
||||
/*
|
||||
* For reference, the static map looks like this:
|
||||
*
|
||||
* 0 0 0 0 0 0 0 254 254 254
|
||||
*
|
||||
* 0 0 0 0 0 0 0 254 254 254
|
||||
*
|
||||
* 0 0 0 254 254 254 0 0 0 0
|
||||
*
|
||||
* 0 0 0 0 0 0 0 0 0 0
|
||||
*
|
||||
* 0 0 0 0 0 0 0 0 0 0
|
||||
*
|
||||
* 0 0 0 0 254 0 0 254 254 254
|
||||
*
|
||||
* 0 0 0 0 254 0 0 254 254 254
|
||||
*
|
||||
* 0 0 0 0 0 0 0 254 254 254
|
||||
*
|
||||
* 0 0 0 0 0 0 0 0 0 0
|
||||
*
|
||||
* 0 0 0 0 0 0 0 0 0 0
|
||||
*
|
||||
* upper left is 0,0, lower right is 9,9
|
||||
*/
|
||||
|
||||
#if (0)
|
||||
/**
|
||||
* Test for ray tracing free space
|
||||
*/
|
||||
TEST_F(TestNode, testRaytracing) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
addStaticLayer(layers, tf, node_);
|
||||
auto olayer = addObstacleLayer(layers, tf, node_);
|
||||
|
||||
// Add a point at 0, 0, 0
|
||||
addObservation(olayer, 0.0, 0.0, MAX_Z / 2, 0, 0, MAX_Z / 2);
|
||||
|
||||
// This actually puts the LETHAL (254) point in the costmap at (0,0)
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
int lethal_count = countValues(*(layers.getCostmap()), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
|
||||
// We expect just one obstacle to be added (20 in static map)
|
||||
ASSERT_EQ(lethal_count, 21);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for ray tracing free space
|
||||
*/
|
||||
TEST_F(TestNode, testRaytracing2) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
addStaticLayer(layers, tf, node_);
|
||||
auto olayer = addObstacleLayer(layers, tf, node_);
|
||||
|
||||
// If we print map now, it is 10x10 all value 0
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
// Update will fill in the costmap with the static map
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
// If we print the map now, we get the static map
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
// Static map has 20 LETHAL cells (see diagram above)
|
||||
int obs_before = countValues(*(layers.getCostmap()), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
ASSERT_EQ(obs_before, 20);
|
||||
|
||||
// The sensor origin will be <0,0>. So if we add an obstacle at 9,9,
|
||||
// we would expect cells <0, 0> thru <8, 8> to be traced through
|
||||
// however the static map is not cleared by obstacle layer
|
||||
addObservation(olayer, 9.5, 9.5, MAX_Z / 2, 0.5, 0.5, MAX_Z / 2);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
// If we print map now, we have static map + <9,9> is LETHAL
|
||||
// printMap(*(layers.getCostmap()));
|
||||
int obs_after = countValues(*(layers.getCostmap()), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
|
||||
// Change from previous test:
|
||||
// No obstacles from the static map will be cleared, so the
|
||||
// net change is +1.
|
||||
ASSERT_EQ(obs_after, obs_before + 1);
|
||||
|
||||
// Fill in the diagonal, <7,7> and <9,9> already filled in, <0,0> is robot
|
||||
for (int i = 0; i < olayer->getSizeInCellsY(); ++i) {
|
||||
olayer->setCost(i, i, nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
}
|
||||
// This will updateBounds, which will raytrace the static observation added
|
||||
// above, thus clearing out the diagonal again!
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
// Map now has diagonal except <0,0> filled with LETHAL (254)
|
||||
// printMap(*(layers.getCostmap()));
|
||||
int with_static = countValues(*(layers.getCostmap()), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
|
||||
// Should thus be the same
|
||||
ASSERT_EQ(with_static, obs_after);
|
||||
// If 21 are filled, 79 should be free
|
||||
ASSERT_EQ(79, countValues(*(layers.getCostmap()), nav2_costmap_2d::FREE_SPACE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for wave interference
|
||||
*/
|
||||
TEST_F(TestNode, testWaveInterference) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
node_->set_parameter(rclcpp::Parameter("track_unknown_space", true));
|
||||
// Start with an empty map, no rolling window, tracking unknown
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, true);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
auto olayer = addObstacleLayer(layers, tf, node_);
|
||||
|
||||
// If we print map now, it is 10x10, all cells are 255 (NO_INFORMATION)
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
// Lay out 3 obstacles in a line - along the diagonal, separated by a cell.
|
||||
addObservation(olayer, 3.0, 3.0, MAX_Z);
|
||||
addObservation(olayer, 5.0, 5.0, MAX_Z);
|
||||
addObservation(olayer, 7.0, 7.0, MAX_Z);
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
// 3 obstacle cells are filled, <1,1>,<2,2>,<4,4> and <6,6> are now free
|
||||
// <0,0> is footprint and is free
|
||||
// printMap(*costmap);
|
||||
ASSERT_EQ(3, countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE));
|
||||
ASSERT_EQ(92, countValues(*costmap, nav2_costmap_2d::NO_INFORMATION));
|
||||
ASSERT_EQ(5, countValues(*costmap, nav2_costmap_2d::FREE_SPACE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure we ignore points outside of our z threshold
|
||||
*/
|
||||
TEST_F(TestNode, testZThreshold) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
// Start with an empty map
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, true);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
auto olayer = addObstacleLayer(layers, tf, node_);
|
||||
|
||||
// A point cloud with 2 points falling in a cell with a non-lethal cost
|
||||
addObservation(olayer, 0.0, 5.0, 0.4);
|
||||
addObservation(olayer, 1.0, 5.0, 2.2);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that dynamic obstacles are added
|
||||
*/
|
||||
TEST_F(TestNode, testDynamicObstacles) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
addStaticLayer(layers, tf, node_);
|
||||
|
||||
auto olayer = addObstacleLayer(layers, tf, node_);
|
||||
|
||||
// Add a point cloud and verify its insertion. There should be only one new one
|
||||
addObservation(olayer, 0.0, 0.0);
|
||||
addObservation(olayer, 0.0, 0.0);
|
||||
addObservation(olayer, 0.0, 0.0);
|
||||
|
||||
layers.updateMap(0, 0, 0);
|
||||
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
// Should now have 1 insertion and no deletions
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 21);
|
||||
|
||||
// Repeating the call - we should see no insertions or deletions
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 21);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that if we add a point that is already a static obstacle we do not end up with a new ostacle
|
||||
*/
|
||||
TEST_F(TestNode, testMultipleAdditions) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
addStaticLayer(layers, tf, node_);
|
||||
|
||||
auto olayer = addObstacleLayer(layers, tf, node_);
|
||||
|
||||
// A point cloud with one point that falls within an existing obstacle
|
||||
addObservation(olayer, 9.5, 0.0);
|
||||
layers.updateMap(0, 0, 0);
|
||||
nav2_costmap_2d::Costmap2D * costmap = layers.getCostmap();
|
||||
// printMap(*costmap);
|
||||
|
||||
ASSERT_EQ(countValues(*costmap, nav2_costmap_2d::LETHAL_OBSTACLE), 20);
|
||||
}
|
||||
#endif
|
||||
/**
|
||||
* Verify correct init/reset cycling of layer
|
||||
*/
|
||||
TEST_F(TestNode, testRepeatedResets) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::StaticLayer> slayer = nullptr;
|
||||
addStaticLayer(layers, tf, node_, slayer);
|
||||
|
||||
// TODO(orduno) Add obstacle layer
|
||||
|
||||
// Define a node-level parameter
|
||||
pair<string, string> node_dummy = {"node_dummy_param", "node_dummy_val"};
|
||||
node_->declare_parameter(node_dummy.first, rclcpp::ParameterValue(node_dummy.second));
|
||||
|
||||
// Define a layer-level parameter
|
||||
pair<string, string> layer_dummy = {"dummy_param", "dummy_val"};
|
||||
|
||||
// Set parameters
|
||||
auto plugins = layers.getPlugins();
|
||||
for_each(
|
||||
begin(*plugins), end(*plugins), [&layer_dummy](const auto & plugin) {
|
||||
string layer_param = layer_dummy.first + "_" + plugin->getName();
|
||||
|
||||
// Notice we are using Layer::declareParameter
|
||||
plugin->declareParameter(layer_param, rclcpp::ParameterValue(layer_dummy.second));
|
||||
});
|
||||
|
||||
// Check that all parameters have been set
|
||||
// node-level param
|
||||
ASSERT_TRUE(node_->has_parameter(node_dummy.first));
|
||||
|
||||
// layer-level param
|
||||
ASSERT_TRUE(
|
||||
all_of(
|
||||
begin(*plugins), end(*plugins), [&layer_dummy](const auto & plugin) {
|
||||
string layer_param = layer_dummy.first + "_" + plugin->getName();
|
||||
return plugin->hasParameter(layer_param);
|
||||
}));
|
||||
|
||||
// Reset all layers. Parameters should be declared if not declared, otherwise skipped.
|
||||
ASSERT_NO_THROW(
|
||||
for_each(
|
||||
begin(*plugins), end(*plugins), [](const auto & plugin) {
|
||||
plugin->reset();
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Test for ray tracing free space
|
||||
*/
|
||||
TEST_F(TestNode, testRaytracing) {
|
||||
tf2_ros::Buffer tf(node_->get_clock());
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::StaticLayer> slayer = nullptr;
|
||||
addStaticLayer(layers, tf, node_, slayer);
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer = nullptr;
|
||||
addObstacleLayer(layers, tf, node_, olayer);
|
||||
|
||||
addObservation(olayer, 0.0, 0.0, MAX_Z / 2, 0, 0, MAX_Z / 2);
|
||||
|
||||
// This actually puts the LETHAL (254) point in the costmap at (0,0)
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
int lethal_count = countValues(*(layers.getCostmap()), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
|
||||
ASSERT_EQ(lethal_count, 1);
|
||||
|
||||
addObservation(olayer, 1.0, 1.0, MAX_Z / 2, 0, 0, MAX_Z / 2, true, true, 100.0, 5.0, 100.0, 5.0);
|
||||
|
||||
// This actually puts the LETHAL (254) point in the costmap at (0,0)
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
// New observation should not be recorded as min_range is higher than obstacle range
|
||||
lethal_count = countValues(*(layers.getCostmap()), nav2_costmap_2d::LETHAL_OBSTACLE);
|
||||
|
||||
ASSERT_EQ(lethal_count, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test dynamic parameter setting of obstacle layer
|
||||
*/
|
||||
TEST_F(TestNode, testDynParamsSetObstacle)
|
||||
{
|
||||
auto costmap = std::make_shared<nav2_costmap_2d::Costmap2DROS>("test_costmap");
|
||||
|
||||
// Add obstacle layer
|
||||
std::vector<std::string> plugins_str;
|
||||
plugins_str.push_back("obstacle_layer");
|
||||
costmap->set_parameter(rclcpp::Parameter("plugins", plugins_str));
|
||||
costmap->declare_parameter(
|
||||
"obstacle_layer.plugin",
|
||||
rclcpp::ParameterValue(std::string("nav2_costmap_2d::ObstacleLayer")));
|
||||
|
||||
costmap->set_parameter(rclcpp::Parameter("global_frame", std::string("base_link")));
|
||||
costmap->on_configure(rclcpp_lifecycle::State());
|
||||
|
||||
costmap->on_activate(rclcpp_lifecycle::State());
|
||||
|
||||
auto parameter_client = std::make_shared<rclcpp::AsyncParametersClient>(
|
||||
costmap->get_node_base_interface(), costmap->get_node_topics_interface(),
|
||||
costmap->get_node_graph_interface(),
|
||||
costmap->get_node_services_interface());
|
||||
|
||||
auto results = parameter_client->set_parameters_atomically(
|
||||
{
|
||||
rclcpp::Parameter("obstacle_layer.combination_method", 5),
|
||||
rclcpp::Parameter("obstacle_layer.max_obstacle_height", 4.0),
|
||||
rclcpp::Parameter("obstacle_layer.enabled", false),
|
||||
rclcpp::Parameter("obstacle_layer.footprint_clearing_enabled", false)
|
||||
});
|
||||
|
||||
rclcpp::spin_until_future_complete(
|
||||
costmap->get_node_base_interface(),
|
||||
results);
|
||||
|
||||
EXPECT_EQ(costmap->get_parameter("obstacle_layer.combination_method").as_int(), 5);
|
||||
EXPECT_EQ(costmap->get_parameter("obstacle_layer.max_obstacle_height").as_double(), 4.0);
|
||||
EXPECT_EQ(costmap->get_parameter("obstacle_layer.enabled").as_bool(), false);
|
||||
EXPECT_EQ(costmap->get_parameter("obstacle_layer.footprint_clearing_enabled").as_bool(), false);
|
||||
|
||||
costmap->on_deactivate(rclcpp_lifecycle::State());
|
||||
costmap->on_cleanup(rclcpp_lifecycle::State());
|
||||
costmap->on_shutdown(rclcpp_lifecycle::State());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test dynamic parameter setting of voxel layer
|
||||
*/
|
||||
TEST_F(TestNode, testDynParamsSetVoxel)
|
||||
{
|
||||
auto costmap = std::make_shared<nav2_costmap_2d::Costmap2DROS>("test_costmap");
|
||||
|
||||
// Add voxel layer
|
||||
std::vector<std::string> plugins_str;
|
||||
plugins_str.push_back("voxel_layer");
|
||||
costmap->set_parameter(rclcpp::Parameter("plugins", plugins_str));
|
||||
costmap->declare_parameter(
|
||||
"voxel_layer.plugin",
|
||||
rclcpp::ParameterValue(std::string("nav2_costmap_2d::VoxelLayer")));
|
||||
|
||||
costmap->set_parameter(rclcpp::Parameter("global_frame", std::string("base_link")));
|
||||
costmap->on_configure(rclcpp_lifecycle::State());
|
||||
|
||||
costmap->on_activate(rclcpp_lifecycle::State());
|
||||
|
||||
auto parameter_client = std::make_shared<rclcpp::AsyncParametersClient>(
|
||||
costmap->get_node_base_interface(), costmap->get_node_topics_interface(),
|
||||
costmap->get_node_graph_interface(),
|
||||
costmap->get_node_services_interface());
|
||||
|
||||
auto results = parameter_client->set_parameters_atomically(
|
||||
{
|
||||
rclcpp::Parameter("voxel_layer.combination_method", 0),
|
||||
rclcpp::Parameter("voxel_layer.mark_threshold", 1),
|
||||
rclcpp::Parameter("voxel_layer.unknown_threshold", 10),
|
||||
rclcpp::Parameter("voxel_layer.z_resolution", 0.4),
|
||||
rclcpp::Parameter("voxel_layer.origin_z", 1.0),
|
||||
rclcpp::Parameter("voxel_layer.z_voxels", 14),
|
||||
rclcpp::Parameter("voxel_layer.max_obstacle_height", 4.0),
|
||||
rclcpp::Parameter("voxel_layer.footprint_clearing_enabled", false),
|
||||
rclcpp::Parameter("voxel_layer.enabled", false),
|
||||
rclcpp::Parameter("voxel_layer.publish_voxel_map", true)
|
||||
});
|
||||
|
||||
rclcpp::spin_until_future_complete(
|
||||
costmap->get_node_base_interface(),
|
||||
results);
|
||||
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.combination_method").as_int(), 0);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.mark_threshold").as_int(), 1);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.unknown_threshold").as_int(), 10);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.z_resolution").as_double(), 0.4);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.origin_z").as_double(), 1.0);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.z_voxels").as_int(), 14);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.max_obstacle_height").as_double(), 4.0);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.footprint_clearing_enabled").as_bool(), false);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.enabled").as_bool(), false);
|
||||
EXPECT_EQ(costmap->get_parameter("voxel_layer.publish_voxel_map").as_bool(), true);
|
||||
|
||||
costmap->on_deactivate(rclcpp_lifecycle::State());
|
||||
costmap->on_cleanup(rclcpp_lifecycle::State());
|
||||
costmap->on_shutdown(rclcpp_lifecycle::State());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test dynamic parameter setting of static layer
|
||||
*/
|
||||
TEST_F(TestNode, testDynParamsSetStatic)
|
||||
{
|
||||
auto costmap = std::make_shared<nav2_costmap_2d::Costmap2DROS>("test_costmap");
|
||||
|
||||
costmap->set_parameter(rclcpp::Parameter("global_frame", std::string("base_link")));
|
||||
costmap->on_configure(rclcpp_lifecycle::State());
|
||||
|
||||
costmap->on_activate(rclcpp_lifecycle::State());
|
||||
|
||||
auto parameter_client = std::make_shared<rclcpp::AsyncParametersClient>(
|
||||
costmap->get_node_base_interface(), costmap->get_node_topics_interface(),
|
||||
costmap->get_node_graph_interface(),
|
||||
costmap->get_node_services_interface());
|
||||
|
||||
auto results = parameter_client->set_parameters_atomically(
|
||||
{
|
||||
rclcpp::Parameter("static_layer.transform_tolerance", 1.0),
|
||||
rclcpp::Parameter("static_layer.enabled", false),
|
||||
rclcpp::Parameter("static_layer.map_subscribe_transient_local", false),
|
||||
rclcpp::Parameter("static_layer.map_topic", "dynamic_topic"),
|
||||
rclcpp::Parameter("static_layer.subscribe_to_updates", true)
|
||||
});
|
||||
|
||||
rclcpp::spin_until_future_complete(
|
||||
costmap->get_node_base_interface(),
|
||||
results);
|
||||
|
||||
EXPECT_EQ(costmap->get_parameter("static_layer.transform_tolerance").as_double(), 1.0);
|
||||
EXPECT_EQ(costmap->get_parameter("static_layer.enabled").as_bool(), false);
|
||||
EXPECT_EQ(costmap->get_parameter("static_layer.map_subscribe_transient_local").as_bool(), false);
|
||||
EXPECT_EQ(costmap->get_parameter("static_layer.map_topic").as_string(), "dynamic_topic");
|
||||
EXPECT_EQ(costmap->get_parameter("static_layer.subscribe_to_updates").as_bool(), true);
|
||||
|
||||
costmap->on_deactivate(rclcpp_lifecycle::State());
|
||||
costmap->on_cleanup(rclcpp_lifecycle::State());
|
||||
costmap->on_shutdown(rclcpp_lifecycle::State());
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2020, Bytes Robotics
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of the copyright holder nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_costmap_2d/observation_buffer.hpp"
|
||||
#include "../testing_helper.hpp"
|
||||
#include "sensor_msgs/msg/range.hpp"
|
||||
|
||||
using std::begin;
|
||||
using std::end;
|
||||
using std::for_each;
|
||||
using std::all_of;
|
||||
using std::none_of;
|
||||
using std::pair;
|
||||
using std::string;
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture()
|
||||
{
|
||||
rclcpp::init(0, nullptr);
|
||||
}
|
||||
|
||||
~RclCppFixture()
|
||||
{
|
||||
rclcpp::shutdown();
|
||||
}
|
||||
};
|
||||
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class TestLifecycleNode : public nav2_util::LifecycleNode
|
||||
{
|
||||
public:
|
||||
explicit TestLifecycleNode(const string & name)
|
||||
: nav2_util::LifecycleNode(name)
|
||||
{
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_configure(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_activate(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_deactivate(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn on_cleanup(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn onShutdown(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn onError(const rclcpp_lifecycle::State &)
|
||||
{
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
};
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode()
|
||||
: node_(std::make_shared<TestLifecycleNode>("range_test_node")),
|
||||
tf_(node_->get_clock())
|
||||
{
|
||||
tf_.setUsingDedicatedThread(true);
|
||||
// Standard non-plugin specific parameters
|
||||
node_->declare_parameter("map_topic", rclcpp::ParameterValue(std::string("map")));
|
||||
node_->declare_parameter("track_unknown_space", rclcpp::ParameterValue(false));
|
||||
node_->declare_parameter("use_maximum", rclcpp::ParameterValue(false));
|
||||
node_->declare_parameter("lethal_cost_threshold", rclcpp::ParameterValue(100));
|
||||
node_->declare_parameter(
|
||||
"unknown_cost_value",
|
||||
rclcpp::ParameterValue(static_cast<unsigned char>(0xff)));
|
||||
node_->declare_parameter("trinary_costmap", rclcpp::ParameterValue(true));
|
||||
node_->declare_parameter("transform_tolerance", rclcpp::ParameterValue(0.3));
|
||||
node_->declare_parameter("observation_sources", rclcpp::ParameterValue(std::string("range")));
|
||||
node_->declare_parameter("global_frame", rclcpp::ParameterValue(std::string("map")));
|
||||
|
||||
|
||||
// Range sensor specific parameters
|
||||
node_->declare_parameter(
|
||||
"range.topics",
|
||||
rclcpp::ParameterValue(
|
||||
std::vector<std::string>{"/range/topic"}));
|
||||
node_->declare_parameter("range.phi", rclcpp::ParameterValue(1.2));
|
||||
node_->declare_parameter("range.clear_on_max_reading", rclcpp::ParameterValue(true));
|
||||
}
|
||||
|
||||
~TestNode() {}
|
||||
|
||||
protected:
|
||||
std::shared_ptr<TestLifecycleNode> node_;
|
||||
tf2_ros::Buffer tf_;
|
||||
};
|
||||
|
||||
// Test clearing at max range
|
||||
TEST_F(TestNode, testClearingAtMaxRange) {
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
transform.header.stamp = node_->now();
|
||||
transform.header.frame_id = "frame";
|
||||
transform.child_frame_id = "base_link";
|
||||
transform.transform.translation.y = 5;
|
||||
transform.transform.translation.x = 2;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::RangeSensorLayer> rlayer{nullptr};
|
||||
addRangeLayer(layers, tf_, node_, rlayer);
|
||||
|
||||
sensor_msgs::msg::Range msg;
|
||||
msg.min_range = 1.0;
|
||||
msg.max_range = 7.0;
|
||||
msg.range = 2.0;
|
||||
msg.header.stamp = node_->now();
|
||||
msg.header.frame_id = "base_link";
|
||||
msg.radiation_type = msg.ULTRASOUND;
|
||||
msg.field_of_view = 0.174533; // 10 deg
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(4, 5), 254);
|
||||
|
||||
msg.range = 7.0;
|
||||
msg.header.stamp = node_->now();
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(4, 5), 0);
|
||||
}
|
||||
|
||||
// Testing fixed scan with robot forward motion
|
||||
TEST_F(TestNode, testProbabalisticModelForward) {
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
transform.header.stamp = node_->now();
|
||||
transform.header.frame_id = "frame";
|
||||
transform.child_frame_id = "base_link";
|
||||
transform.transform.translation.y = 5;
|
||||
transform.transform.translation.x = 2;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::RangeSensorLayer> rlayer{nullptr};
|
||||
addRangeLayer(layers, tf_, node_, rlayer);
|
||||
|
||||
sensor_msgs::msg::Range msg;
|
||||
msg.min_range = 1.0;
|
||||
msg.max_range = 10.0;
|
||||
msg.range = 3.0;
|
||||
msg.header.stamp = node_->now();
|
||||
msg.header.frame_id = "base_link";
|
||||
msg.radiation_type = msg.ULTRASOUND;
|
||||
msg.field_of_view = 0.174533; // 10 deg
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
transform.transform.translation.y = 5;
|
||||
transform.transform.translation.x = 4;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
|
||||
transform.transform.translation.y = 5;
|
||||
transform.transform.translation.x = 6;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(5, 5), 254);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(6, 5), 0);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(7, 5), 254);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(8, 5), 0);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(9, 5), 254);
|
||||
}
|
||||
|
||||
// Testing fixed motion with downward movement
|
||||
TEST_F(TestNode, testProbabalisticModelDownward) {
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
transform.header.stamp = node_->now();
|
||||
transform.header.frame_id = "frame";
|
||||
transform.child_frame_id = "base_link";
|
||||
transform.transform.translation.y = 3;
|
||||
transform.transform.translation.x = 2;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
layers.resizeMap(10, 10, 1, 0, 0);
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::RangeSensorLayer> rlayer{nullptr};
|
||||
addRangeLayer(layers, tf_, node_, rlayer);
|
||||
|
||||
sensor_msgs::msg::Range msg;
|
||||
msg.min_range = 1.0;
|
||||
msg.max_range = 10.0;
|
||||
msg.range = 1.0;
|
||||
msg.header.stamp = node_->now();
|
||||
msg.header.frame_id = "base_link";
|
||||
msg.radiation_type = msg.ULTRASOUND;
|
||||
msg.field_of_view = 0.174533; // 10 deg
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
|
||||
transform.transform.translation.y = 5;
|
||||
transform.transform.translation.x = 2;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
rlayer->bufferIncomingRangeMsg(std::make_shared<sensor_msgs::msg::Range>(msg));
|
||||
|
||||
transform.transform.translation.y = 7;
|
||||
transform.transform.translation.x = 2;
|
||||
tf_.setTransform(transform, "default_authority", true);
|
||||
|
||||
layers.updateMap(0, 0, 0); // 0, 0, 0 is robot pose
|
||||
// printMap(*(layers.getCostmap()));
|
||||
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(3, 3), 254);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(3, 4), 0);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(3, 5), 254);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(3, 6), 0);
|
||||
ASSERT_EQ(layers.getCostmap()->getCost(3, 7), 254);
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <chrono>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/costmap_topic_collision_checker.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/layered_costmap.hpp"
|
||||
#include "nav2_costmap_2d/static_layer.hpp"
|
||||
#include "nav2_costmap_2d/inflation_layer.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d_publisher.hpp"
|
||||
#include "../testing_helper.hpp"
|
||||
#include "nav2_util/robot_utils.hpp"
|
||||
#include "nav2_util/node_utils.hpp"
|
||||
#include "geometry_msgs/msg/pose_stamped.hpp"
|
||||
#include "tf2_ros/buffer.h"
|
||||
#include "tf2_ros/transform_listener.h"
|
||||
#include "tf2_ros/create_timer_ros.h"
|
||||
#include "tf2_ros/transform_broadcaster.h"
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wpedantic"
|
||||
#include "tf2/utils.h"
|
||||
#pragma GCC diagnostic pop
|
||||
#include "nav2_util/geometry_utils.hpp"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using namespace std::placeholders;
|
||||
using nav2_util::geometry_utils::orientationAroundZAxis;
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class DummyCostmapSubscriber : public nav2_costmap_2d::CostmapSubscriber
|
||||
{
|
||||
public:
|
||||
DummyCostmapSubscriber(
|
||||
nav2_util::LifecycleNode::SharedPtr node,
|
||||
std::string & topic_name)
|
||||
: CostmapSubscriber(node, topic_name)
|
||||
{}
|
||||
|
||||
void setCostmap(nav2_msgs::msg::Costmap::SharedPtr msg)
|
||||
{
|
||||
costmap_msg_ = msg;
|
||||
costmap_received_ = true;
|
||||
}
|
||||
};
|
||||
|
||||
class DummyFootprintSubscriber : public nav2_costmap_2d::FootprintSubscriber
|
||||
{
|
||||
public:
|
||||
DummyFootprintSubscriber(
|
||||
nav2_util::LifecycleNode::SharedPtr node,
|
||||
std::string & topic_name,
|
||||
tf2_ros::Buffer & tf_)
|
||||
: FootprintSubscriber(node, topic_name, tf_)
|
||||
{}
|
||||
|
||||
void setFootprint(geometry_msgs::msg::PolygonStamped::SharedPtr msg)
|
||||
{
|
||||
footprint_ = msg;
|
||||
footprint_received_ = true;
|
||||
}
|
||||
};
|
||||
|
||||
class TestCollisionChecker : public nav2_util::LifecycleNode
|
||||
{
|
||||
public:
|
||||
explicit TestCollisionChecker(std::string name)
|
||||
: LifecycleNode(name),
|
||||
global_frame_("map")
|
||||
{
|
||||
// Declare non-plugin specific costmap parameters
|
||||
declare_parameter("map_topic", rclcpp::ParameterValue(std::string("map")));
|
||||
declare_parameter("track_unknown_space", rclcpp::ParameterValue(true));
|
||||
declare_parameter("use_maximum", rclcpp::ParameterValue(false));
|
||||
declare_parameter("lethal_cost_threshold", rclcpp::ParameterValue(100));
|
||||
declare_parameter(
|
||||
"unknown_cost_value",
|
||||
rclcpp::ParameterValue(static_cast<unsigned char>(0xff)));
|
||||
declare_parameter("trinary_costmap", rclcpp::ParameterValue(true));
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
on_configure(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Configuring");
|
||||
callback_group_ = create_callback_group(
|
||||
rclcpp::CallbackGroupType::MutuallyExclusive, false);
|
||||
tf_buffer_ = std::make_shared<tf2_ros::Buffer>(get_clock());
|
||||
auto timer_interface = std::make_shared<tf2_ros::CreateTimerROS>(
|
||||
get_node_base_interface(),
|
||||
get_node_timers_interface(),
|
||||
callback_group_);
|
||||
tf_buffer_->setCreateTimerInterface(timer_interface);
|
||||
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
|
||||
tf_broadcaster_ = std::make_shared<tf2_ros::TransformBroadcaster>(shared_from_this());
|
||||
|
||||
std::string costmap_topic = "costmap_raw";
|
||||
std::string footprint_topic = "published_footprint";
|
||||
|
||||
costmap_sub_ = std::make_shared<DummyCostmapSubscriber>(
|
||||
shared_from_this(),
|
||||
costmap_topic);
|
||||
|
||||
footprint_sub_ = std::make_shared<DummyFootprintSubscriber>(
|
||||
shared_from_this(),
|
||||
footprint_topic,
|
||||
*tf_buffer_);
|
||||
|
||||
collision_checker_ = std::make_unique<nav2_costmap_2d::CostmapTopicCollisionChecker>(
|
||||
*costmap_sub_, *footprint_sub_, get_name());
|
||||
|
||||
layers_ = new nav2_costmap_2d::LayeredCostmap("map", false, false);
|
||||
// Add Static Layer
|
||||
std::shared_ptr<nav2_costmap_2d::StaticLayer> slayer = nullptr;
|
||||
addStaticLayer(*layers_, *tf_buffer_, shared_from_this(), slayer, callback_group_);
|
||||
|
||||
while (!slayer->isCurrent()) {
|
||||
rclcpp::spin_some(this->get_node_base_interface());
|
||||
}
|
||||
// Add Inflation Layer
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> ilayer = nullptr;
|
||||
addInflationLayer(*layers_, *tf_buffer_, shared_from_this(), ilayer, callback_group_);
|
||||
|
||||
executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
|
||||
executor_->add_callback_group(callback_group_, get_node_base_interface());
|
||||
executor_thread_ = std::make_unique<nav2_util::NodeThread>(executor_);
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
on_activate(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Activating");
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
on_deactivate(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Deactivating");
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
nav2_util::CallbackReturn
|
||||
on_cleanup(const rclcpp_lifecycle::State & /*state*/)
|
||||
{
|
||||
RCLCPP_INFO(get_logger(), "Cleaning Up");
|
||||
delete layers_;
|
||||
layers_ = nullptr;
|
||||
|
||||
executor_thread_.reset();
|
||||
tf_buffer_.reset();
|
||||
|
||||
footprint_sub_.reset();
|
||||
costmap_sub_.reset();
|
||||
|
||||
return nav2_util::CallbackReturn::SUCCESS;
|
||||
}
|
||||
|
||||
~TestCollisionChecker() {}
|
||||
|
||||
bool testPose(double x, double y, double theta)
|
||||
{
|
||||
rclcpp::Time stamp = now();
|
||||
publishPose(x, y, theta, stamp);
|
||||
geometry_msgs::msg::Pose2D pose;
|
||||
pose.x = x;
|
||||
pose.y = y;
|
||||
pose.theta = theta;
|
||||
|
||||
setPose(x, y, theta, stamp);
|
||||
publishFootprint();
|
||||
publishCostmap();
|
||||
rclcpp::sleep_for(std::chrono::milliseconds(1000));
|
||||
return collision_checker_->isCollisionFree(pose);
|
||||
}
|
||||
|
||||
void setFootprint(double footprint_padding, double robot_radius)
|
||||
{
|
||||
std::vector<geometry_msgs::msg::Point> new_footprint;
|
||||
new_footprint = nav2_costmap_2d::makeFootprintFromRadius(robot_radius);
|
||||
nav2_costmap_2d::padFootprint(new_footprint, footprint_padding);
|
||||
footprint_ = new_footprint;
|
||||
layers_->setFootprint(footprint_);
|
||||
}
|
||||
|
||||
protected:
|
||||
void setPose(double x, double y, double theta, const rclcpp::Time & stamp)
|
||||
{
|
||||
x_ = x;
|
||||
y_ = y;
|
||||
yaw_ = theta;
|
||||
stamp_ = stamp;
|
||||
|
||||
current_pose_.pose.position.x = x_;
|
||||
current_pose_.pose.position.y = y_;
|
||||
current_pose_.pose.position.z = 0;
|
||||
current_pose_.pose.orientation = orientationAroundZAxis(yaw_);
|
||||
current_pose_.header.stamp = stamp;
|
||||
}
|
||||
|
||||
void publishFootprint()
|
||||
{
|
||||
geometry_msgs::msg::PolygonStamped oriented_footprint;
|
||||
oriented_footprint.header.frame_id = global_frame_;
|
||||
oriented_footprint.header.stamp = stamp_;
|
||||
nav2_costmap_2d::transformFootprint(x_, y_, yaw_, footprint_, oriented_footprint);
|
||||
footprint_sub_->setFootprint(
|
||||
std::make_shared<geometry_msgs::msg::PolygonStamped>(oriented_footprint));
|
||||
}
|
||||
|
||||
void publishCostmap()
|
||||
{
|
||||
layers_->updateMap(x_, y_, yaw_);
|
||||
costmap_sub_->setCostmap(
|
||||
std::make_shared<nav2_msgs::msg::Costmap>(toCostmapMsg(layers_->getCostmap())));
|
||||
}
|
||||
|
||||
void publishPose(double x, double y, double /*theta*/, const rclcpp::Time & stamp)
|
||||
{
|
||||
geometry_msgs::msg::TransformStamped tf_stamped;
|
||||
tf_stamped.header.frame_id = "map";
|
||||
tf_stamped.header.stamp = stamp;
|
||||
tf_stamped.child_frame_id = "base_link";
|
||||
tf_stamped.transform.translation.x = x;
|
||||
tf_stamped.transform.translation.y = y;
|
||||
tf_stamped.transform.rotation.w = 1.0;
|
||||
tf_broadcaster_->sendTransform(tf_stamped);
|
||||
}
|
||||
|
||||
nav2_msgs::msg::Costmap
|
||||
toCostmapMsg(nav2_costmap_2d::Costmap2D * costmap)
|
||||
{
|
||||
double resolution = costmap->getResolution();
|
||||
|
||||
double wx, wy;
|
||||
costmap->mapToWorld(0, 0, wx, wy);
|
||||
|
||||
unsigned char * data = costmap->getCharMap();
|
||||
|
||||
nav2_msgs::msg::Costmap costmap_msg;
|
||||
costmap_msg.header.frame_id = global_frame_;
|
||||
costmap_msg.header.stamp = stamp_;
|
||||
costmap_msg.metadata.layer = "master";
|
||||
costmap_msg.metadata.resolution = resolution;
|
||||
costmap_msg.metadata.size_x = costmap->getSizeInCellsX();
|
||||
costmap_msg.metadata.size_y = costmap->getSizeInCellsY();
|
||||
costmap_msg.metadata.origin.position.x = wx - resolution / 2;
|
||||
costmap_msg.metadata.origin.position.y = wy - resolution / 2;
|
||||
costmap_msg.metadata.origin.position.z = 0.0;
|
||||
costmap_msg.metadata.origin.orientation.w = 1.0;
|
||||
costmap_msg.data.resize(costmap_msg.metadata.size_x * costmap_msg.metadata.size_y);
|
||||
|
||||
for (unsigned int i = 0; i < costmap_msg.data.size(); i++) {
|
||||
costmap_msg.data[i] = data[i];
|
||||
}
|
||||
|
||||
return costmap_msg;
|
||||
}
|
||||
|
||||
std::shared_ptr<tf2_ros::Buffer> tf_buffer_;
|
||||
std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
|
||||
std::shared_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster_;
|
||||
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group_;
|
||||
rclcpp::executors::SingleThreadedExecutor::SharedPtr executor_;
|
||||
std::unique_ptr<nav2_util::NodeThread> executor_thread_;
|
||||
|
||||
std::shared_ptr<DummyCostmapSubscriber> costmap_sub_;
|
||||
std::shared_ptr<DummyFootprintSubscriber> footprint_sub_;
|
||||
std::unique_ptr<nav2_costmap_2d::CostmapTopicCollisionChecker> collision_checker_;
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap * layers_{nullptr};
|
||||
std::string global_frame_;
|
||||
double x_, y_, yaw_;
|
||||
rclcpp::Time stamp_;
|
||||
geometry_msgs::msg::PoseStamped current_pose_;
|
||||
std::vector<geometry_msgs::msg::Point> footprint_;
|
||||
};
|
||||
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode()
|
||||
{
|
||||
collision_checker_ = std::make_shared<TestCollisionChecker>("test_collision_checker");
|
||||
collision_checker_->on_configure(collision_checker_->get_current_state());
|
||||
collision_checker_->on_activate(collision_checker_->get_current_state());
|
||||
}
|
||||
|
||||
~TestNode()
|
||||
{
|
||||
collision_checker_->on_deactivate(collision_checker_->get_current_state());
|
||||
collision_checker_->on_cleanup(collision_checker_->get_current_state());
|
||||
}
|
||||
|
||||
protected:
|
||||
std::shared_ptr<TestCollisionChecker> collision_checker_;
|
||||
};
|
||||
|
||||
TEST_F(TestNode, unknownSpace)
|
||||
{
|
||||
collision_checker_->setFootprint(0, 1);
|
||||
|
||||
// Completely off map
|
||||
ASSERT_EQ(collision_checker_->testPose(5, 13, 0), false);
|
||||
|
||||
// Partially off map
|
||||
ASSERT_EQ(collision_checker_->testPose(5, 9.5, 0), false);
|
||||
|
||||
// In unknown region inside map
|
||||
ASSERT_EQ(collision_checker_->testPose(2, 4, 0), false);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, FreeSpace)
|
||||
{
|
||||
collision_checker_->setFootprint(0, 1);
|
||||
|
||||
// In complete free space
|
||||
ASSERT_EQ(collision_checker_->testPose(2, 8.5, 0), true);
|
||||
|
||||
// Partially in inscribed space
|
||||
ASSERT_EQ(collision_checker_->testPose(2.5, 7, 0), true);
|
||||
}
|
||||
|
||||
TEST_F(TestNode, CollisionSpace)
|
||||
{
|
||||
collision_checker_->setFootprint(0, 1);
|
||||
|
||||
// Completely in obstacle
|
||||
ASSERT_EQ(collision_checker_->testPose(8.5, 6.5, 0), false);
|
||||
|
||||
// Partially in obstacle
|
||||
ASSERT_EQ(collision_checker_->testPose(4.5, 4.5, 0), false);
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
image: TenByTen.pgm
|
||||
resolution: 1.0
|
||||
origin: [0,0,0]
|
||||
negate: 0
|
||||
occupied_thresh: 0.65
|
||||
free_thresh: 0.196
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
# Bresenham2D corner cases test
|
||||
ament_add_gtest(costmap_bresenham_2d costmap_bresenham_2d.cpp)
|
||||
target_link_libraries(costmap_bresenham_2d
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
# OrderLayer for checking Costmap2D plugins API calling order
|
||||
add_library(order_layer SHARED
|
||||
order_layer.cpp)
|
||||
ament_target_dependencies(order_layer
|
||||
${dependencies}
|
||||
)
|
||||
target_link_libraries(order_layer
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
install(TARGETS
|
||||
order_layer
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Costmap2D plugins API calling order test
|
||||
ament_add_gtest(plugin_api_order plugin_api_order.cpp)
|
||||
target_link_libraries(plugin_api_order
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
@@ -0,0 +1,159 @@
|
||||
/*********************************************************************
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Copyright (c) 2022 Samsung Research Russia
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* Author: Alexey Merzlyakov
|
||||
*********************************************************************/
|
||||
#include <nav2_costmap_2d/costmap_2d.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
class CostmapAction
|
||||
{
|
||||
public:
|
||||
explicit CostmapAction(
|
||||
unsigned char * costmap, unsigned int size, unsigned char mark_val = 128)
|
||||
: costmap_(costmap), size_(size), mark_val_(mark_val)
|
||||
{
|
||||
}
|
||||
|
||||
inline void operator()(unsigned int off)
|
||||
{
|
||||
ASSERT_TRUE(off < size_);
|
||||
costmap_[off] = mark_val_;
|
||||
}
|
||||
|
||||
inline unsigned int get(unsigned int off)
|
||||
{
|
||||
return costmap_[off];
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned char * costmap_;
|
||||
unsigned int size_;
|
||||
unsigned char mark_val_;
|
||||
};
|
||||
|
||||
class CostmapTest : public nav2_costmap_2d::Costmap2D
|
||||
{
|
||||
public:
|
||||
CostmapTest(
|
||||
unsigned int size_x, unsigned int size_y, double resolution,
|
||||
double origin_x, double origin_y, unsigned char default_val = 0)
|
||||
: nav2_costmap_2d::Costmap2D(size_x, size_y, resolution, origin_x, origin_y, default_val)
|
||||
{
|
||||
}
|
||||
|
||||
unsigned char * getCostmap()
|
||||
{
|
||||
return costmap_;
|
||||
}
|
||||
|
||||
unsigned int getSize()
|
||||
{
|
||||
return size_x_ * size_y_;
|
||||
}
|
||||
|
||||
void raytraceLine(
|
||||
CostmapAction ca, unsigned int x0, unsigned int y0, unsigned int x1,
|
||||
unsigned int y1,
|
||||
unsigned int max_length = UINT_MAX, unsigned int min_length = 0)
|
||||
{
|
||||
nav2_costmap_2d::Costmap2D::raytraceLine(ca, x0, y0, x1, y1, max_length, min_length);
|
||||
}
|
||||
};
|
||||
|
||||
TEST(costmap_2d, bresenham2DBoundariesCheck)
|
||||
{
|
||||
const unsigned int sz_x = 60;
|
||||
const unsigned int sz_y = 60;
|
||||
const unsigned int max_length = 60;
|
||||
const unsigned int min_length = 6;
|
||||
CostmapTest ct(sz_x, sz_y, 0.1, 0.0, 0.0);
|
||||
CostmapAction ca(ct.getCostmap(), ct.getSize());
|
||||
|
||||
// Initial point - some assymetrically standing point in order to cover most corner cases
|
||||
const unsigned int x0 = 2;
|
||||
const unsigned int y0 = 4;
|
||||
// (x1, y1) point will move
|
||||
unsigned int x1, y1;
|
||||
|
||||
// Running on (x, 0) edge
|
||||
y1 = 0;
|
||||
for (x1 = 0; x1 < sz_x; x1++) {
|
||||
ct.raytraceLine(ca, x0, y0, x1, y1, max_length, min_length);
|
||||
}
|
||||
|
||||
// Running on (x, sz_y) edge
|
||||
y1 = sz_y - 1;
|
||||
for (x1 = 0; x1 < sz_x; x1++) {
|
||||
ct.raytraceLine(ca, x0, y0, x1, y1, max_length, min_length);
|
||||
}
|
||||
|
||||
// Running on (0, y) edge
|
||||
x1 = 0;
|
||||
for (y1 = 0; y1 < sz_y; y1++) {
|
||||
ct.raytraceLine(ca, x0, y0, x1, y1, max_length, min_length);
|
||||
}
|
||||
|
||||
// Running on (sz_x, y) edge
|
||||
x1 = sz_x - 1;
|
||||
for (y1 = 0; y1 < sz_y; y1++) {
|
||||
ct.raytraceLine(ca, x0, y0, x1, y1, max_length, min_length);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(costmap_2d, bresenham2DSamePoint)
|
||||
{
|
||||
const unsigned int sz_x = 60;
|
||||
const unsigned int sz_y = 60;
|
||||
const unsigned int max_length = 60;
|
||||
const unsigned int min_length = 0;
|
||||
CostmapTest ct(sz_x, sz_y, 0.1, 0.0, 0.0);
|
||||
CostmapAction ca(ct.getCostmap(), ct.getSize());
|
||||
|
||||
// Initial point
|
||||
const double x0 = 2;
|
||||
const double y0 = 4;
|
||||
|
||||
unsigned int offset = y0 * sz_x + x0;
|
||||
unsigned char val_before = ca.get(offset);
|
||||
// Same point to check
|
||||
ct.raytraceLine(ca, x0, y0, x0, y0, max_length, min_length);
|
||||
unsigned char val_after = ca.get(offset);
|
||||
ASSERT_FALSE(val_before == val_after);
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include "order_layer.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
OrderLayer::OrderLayer()
|
||||
: activated_(false)
|
||||
{
|
||||
}
|
||||
|
||||
void OrderLayer::activate()
|
||||
{
|
||||
std::this_thread::sleep_for(100ms);
|
||||
activated_ = true;
|
||||
}
|
||||
|
||||
void OrderLayer::deactivate()
|
||||
{
|
||||
activated_ = false;
|
||||
}
|
||||
|
||||
void OrderLayer::updateBounds(
|
||||
double, double, double, double *, double *, double *, double *)
|
||||
{
|
||||
if (!activated_) {
|
||||
throw std::runtime_error("update before activated");
|
||||
}
|
||||
}
|
||||
|
||||
void OrderLayer::updateCosts(
|
||||
nav2_costmap_2d::Costmap2D &, int, int, int, int)
|
||||
{
|
||||
if (!activated_) {
|
||||
throw std::runtime_error("update before activated");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::OrderLayer, nav2_costmap_2d::Layer)
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__ORDER_LAYER_HPP_
|
||||
#define NAV2_COSTMAP_2D__ORDER_LAYER_HPP_
|
||||
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
|
||||
class OrderLayer : public nav2_costmap_2d::Layer
|
||||
{
|
||||
public:
|
||||
OrderLayer();
|
||||
|
||||
virtual void activate();
|
||||
virtual void deactivate();
|
||||
|
||||
virtual void reset() {}
|
||||
virtual bool isClearable() {return false;}
|
||||
|
||||
virtual void updateBounds(
|
||||
double, double, double, double *, double *, double *, double *);
|
||||
|
||||
virtual void updateCosts(
|
||||
nav2_costmap_2d::Costmap2D &, int, int, int, int);
|
||||
|
||||
private:
|
||||
bool activated_;
|
||||
};
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__ORDER_LAYER_HPP_
|
||||
@@ -0,0 +1,7 @@
|
||||
<class_libraries>
|
||||
<library path="order_layer">
|
||||
<class type="nav2_costmap_2d::OrderLayer" base_class_type="nav2_costmap_2d::Layer">
|
||||
<description>Plugin checking order of activate() and updateBounds()/updateCosts() calls</description>
|
||||
</class>
|
||||
</library>
|
||||
</class_libraries>
|
||||
@@ -0,0 +1,53 @@
|
||||
// Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
#include <nav2_costmap_2d/costmap_2d_ros.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(CostmapPluginsTester, checkPluginAPIOrder)
|
||||
{
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros =
|
||||
std::make_shared<nav2_costmap_2d::Costmap2DROS>("costmap_ros");
|
||||
|
||||
// Workaround to avoid setting base_link->map transform
|
||||
costmap_ros->set_parameter(rclcpp::Parameter("robot_base_frame", "map"));
|
||||
// Specifying order verification plugin in the parameters
|
||||
std::vector<std::string> plugins_str;
|
||||
plugins_str.push_back("order_layer");
|
||||
costmap_ros->set_parameter(rclcpp::Parameter("plugins", plugins_str));
|
||||
costmap_ros->declare_parameter(
|
||||
"order_layer.plugin",
|
||||
rclcpp::ParameterValue(std::string("nav2_costmap_2d::OrderLayer")));
|
||||
|
||||
// Do actual test: ensure that plugin->updateBounds()/updateCosts()
|
||||
// will be called after plugin->activate()
|
||||
costmap_ros->on_configure(costmap_ros->get_current_state());
|
||||
costmap_ros->on_activate(costmap_ros->get_current_state());
|
||||
|
||||
// Do cleanup
|
||||
costmap_ros->on_deactivate(costmap_ros->get_current_state());
|
||||
costmap_ros->on_cleanup(costmap_ros->get_current_state());
|
||||
costmap_ros->on_shutdown(costmap_ros->get_current_state());
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<launch>
|
||||
<param name="/use_sim_time" value="true"/>
|
||||
|
||||
<node name="rosplay" pkg="rosbag" type="play"
|
||||
args="-s 5 -r 1 --clock --hz=10 $(find nav2_costmap_2d)/test/simple_driving_test_indexed.bag" />
|
||||
|
||||
<node name="map_server" pkg="map_server" type="map_server" args="$(find nav2_costmap_2d)/test/willow-full-0.025.pgm 0.025" />
|
||||
|
||||
<rosparam file="$(find nav2_costmap_2d)/test/costmap_params.yaml" command="load" ns="simple_driving_test/test_costmap" />
|
||||
<test time-limit="600" test-name="simple_driving_test" pkg="nav2_costmap_2d" type="costmap_tester">
|
||||
<param name="wait_time" value="40.0" />
|
||||
</test>
|
||||
|
||||
</launch>
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2018 Intel Corporation
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
|
||||
from launch import LaunchDescription
|
||||
import launch_ros.actions
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
mapFile = os.getenv('TEST_MAP')
|
||||
return LaunchDescription([
|
||||
launch_ros.actions.Node(
|
||||
package='nav2_map_server',
|
||||
executable='map_server',
|
||||
name='map_server',
|
||||
output='screen',
|
||||
parameters=[{'yaml_filename': mapFile}])
|
||||
])
|
||||
@@ -0,0 +1,146 @@
|
||||
// Copyright (c) Willow Garage
|
||||
// Copyright (c) 2019 Intel Corporation
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef TESTING_HELPER_HPP_
|
||||
#define TESTING_HELPER_HPP_
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "sensor_msgs/point_cloud2_iterator.hpp"
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/static_layer.hpp"
|
||||
#include "nav2_costmap_2d/range_sensor_layer.hpp"
|
||||
#include "nav2_costmap_2d/obstacle_layer.hpp"
|
||||
#include "nav2_costmap_2d/inflation_layer.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
const double MAX_Z(1.0);
|
||||
|
||||
char printableCost(unsigned char cost)
|
||||
{
|
||||
switch (cost) {
|
||||
case nav2_costmap_2d::NO_INFORMATION: return '?';
|
||||
case nav2_costmap_2d::LETHAL_OBSTACLE: return 'L';
|
||||
case nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE: return 'I';
|
||||
case nav2_costmap_2d::FREE_SPACE: return '.';
|
||||
default: return '0' + (unsigned char) (10 * cost / 255);
|
||||
}
|
||||
}
|
||||
|
||||
void printMap(nav2_costmap_2d::Costmap2D & costmap)
|
||||
{
|
||||
printf("map:\n");
|
||||
for (unsigned int i = 0; i < costmap.getSizeInCellsY(); i++) {
|
||||
for (unsigned int j = 0; j < costmap.getSizeInCellsX(); j++) {
|
||||
printf("%4d", static_cast<int>(costmap.getCost(j, i)));
|
||||
}
|
||||
printf("\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int countValues(
|
||||
nav2_costmap_2d::Costmap2D & costmap,
|
||||
unsigned char value, bool equal = true)
|
||||
{
|
||||
unsigned int count = 0;
|
||||
for (unsigned int i = 0; i < costmap.getSizeInCellsY(); i++) {
|
||||
for (unsigned int j = 0; j < costmap.getSizeInCellsX(); j++) {
|
||||
unsigned char c = costmap.getCost(j, i);
|
||||
if ((equal && c == value) || (!equal && c != value)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
void addStaticLayer(
|
||||
nav2_costmap_2d::LayeredCostmap & layers,
|
||||
tf2_ros::Buffer & tf, nav2_util::LifecycleNode::SharedPtr node,
|
||||
std::shared_ptr<nav2_costmap_2d::StaticLayer> & slayer,
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group = nullptr)
|
||||
{
|
||||
slayer = std::make_shared<nav2_costmap_2d::StaticLayer>();
|
||||
layers.addPlugin(std::shared_ptr<nav2_costmap_2d::Layer>(slayer));
|
||||
slayer->initialize(&layers, "static", &tf, node, callback_group);
|
||||
}
|
||||
|
||||
void addObstacleLayer(
|
||||
nav2_costmap_2d::LayeredCostmap & layers,
|
||||
tf2_ros::Buffer & tf, nav2_util::LifecycleNode::SharedPtr node,
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> & olayer,
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group = nullptr)
|
||||
{
|
||||
olayer = std::make_shared<nav2_costmap_2d::ObstacleLayer>();
|
||||
olayer->initialize(&layers, "obstacles", &tf, node, callback_group);
|
||||
layers.addPlugin(std::shared_ptr<nav2_costmap_2d::Layer>(olayer));
|
||||
}
|
||||
|
||||
void addRangeLayer(
|
||||
nav2_costmap_2d::LayeredCostmap & layers,
|
||||
tf2_ros::Buffer & tf, nav2_util::LifecycleNode::SharedPtr node,
|
||||
std::shared_ptr<nav2_costmap_2d::RangeSensorLayer> & rlayer,
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group = nullptr)
|
||||
{
|
||||
rlayer = std::make_shared<nav2_costmap_2d::RangeSensorLayer>();
|
||||
rlayer->initialize(&layers, "range", &tf, node, callback_group);
|
||||
layers.addPlugin(std::shared_ptr<nav2_costmap_2d::Layer>(rlayer));
|
||||
}
|
||||
|
||||
void addObservation(
|
||||
std::shared_ptr<nav2_costmap_2d::ObstacleLayer> olayer, double x, double y, double z = 0.0,
|
||||
double ox = 0.0, double oy = 0.0, double oz = MAX_Z, bool marking = true, bool clearing = true,
|
||||
double raytrace_max_range = 100.0,
|
||||
double raytrace_min_range = 0.0,
|
||||
double obstacle_max_range = 100.0,
|
||||
double obstacle_min_range = 0.0)
|
||||
{
|
||||
sensor_msgs::msg::PointCloud2 cloud;
|
||||
sensor_msgs::PointCloud2Modifier modifier(cloud);
|
||||
modifier.setPointCloud2FieldsByString(1, "xyz");
|
||||
modifier.resize(1);
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_x(cloud, "x");
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_y(cloud, "y");
|
||||
sensor_msgs::PointCloud2Iterator<float> iter_z(cloud, "z");
|
||||
*iter_x = x;
|
||||
*iter_y = y;
|
||||
*iter_z = z;
|
||||
|
||||
geometry_msgs::msg::Point p;
|
||||
p.x = ox;
|
||||
p.y = oy;
|
||||
p.z = oz;
|
||||
|
||||
nav2_costmap_2d::Observation obs(p, cloud, obstacle_max_range, obstacle_min_range,
|
||||
raytrace_max_range, raytrace_min_range);
|
||||
olayer->addStaticObservation(obs, marking, clearing);
|
||||
}
|
||||
|
||||
void addInflationLayer(
|
||||
nav2_costmap_2d::LayeredCostmap & layers,
|
||||
tf2_ros::Buffer & tf, nav2_util::LifecycleNode::SharedPtr node,
|
||||
std::shared_ptr<nav2_costmap_2d::InflationLayer> & ilayer,
|
||||
rclcpp::CallbackGroup::SharedPtr callback_group = nullptr)
|
||||
{
|
||||
ilayer = std::make_shared<nav2_costmap_2d::InflationLayer>();
|
||||
ilayer->initialize(&layers, "inflation", &tf, node, callback_group);
|
||||
std::shared_ptr<nav2_costmap_2d::Layer> ipointer(ilayer);
|
||||
layers.addPlugin(ipointer);
|
||||
}
|
||||
|
||||
|
||||
#endif // TESTING_HELPER_HPP_
|
||||
@@ -0,0 +1,58 @@
|
||||
ament_add_gtest(array_parser_test array_parser_test.cpp)
|
||||
target_link_libraries(array_parser_test
|
||||
nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(collision_footprint_test footprint_collision_checker_test.cpp)
|
||||
target_link_libraries(collision_footprint_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(costmap_convesion_test costmap_conversion_test.cpp)
|
||||
target_link_libraries(costmap_convesion_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(declare_parameter_test declare_parameter_test.cpp)
|
||||
target_link_libraries(declare_parameter_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(costmap_filter_test costmap_filter_test.cpp)
|
||||
target_link_libraries(costmap_filter_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(keepout_filter_test keepout_filter_test.cpp)
|
||||
target_link_libraries(keepout_filter_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::filters
|
||||
)
|
||||
|
||||
ament_add_gtest(speed_filter_test speed_filter_test.cpp)
|
||||
target_link_libraries(speed_filter_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::filters
|
||||
)
|
||||
|
||||
ament_add_gtest(binary_filter_test binary_filter_test.cpp)
|
||||
target_link_libraries(binary_filter_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::filters
|
||||
)
|
||||
|
||||
ament_add_gtest(copy_window_test copy_window_test.cpp)
|
||||
target_link_libraries(copy_window_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(costmap_filter_service_test costmap_filter_service_test.cpp)
|
||||
target_link_libraries(costmap_filter_service_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
)
|
||||
|
||||
ament_add_gtest(denoise_layer_test denoise_layer_test.cpp image_test.cpp image_processing_test.cpp)
|
||||
target_link_libraries(denoise_layer_test
|
||||
${PROJECT_NAME}::nav2_costmap_2d_core
|
||||
${PROJECT_NAME}::layers
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright (c) 2012, Willow Garage, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of the Willow Garage, Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "nav2_costmap_2d/array_parser.hpp"
|
||||
|
||||
TEST(array_parser, basic_operation)
|
||||
{
|
||||
std::string error;
|
||||
std::vector<std::vector<float>> vvf;
|
||||
vvf = nav2_costmap_2d::parseVVF("[[1, 2.2], [.3, -4e4]]", error);
|
||||
EXPECT_EQ(2u, vvf.size() );
|
||||
EXPECT_EQ(2u, vvf[0].size() );
|
||||
EXPECT_EQ(2u, vvf[1].size() );
|
||||
EXPECT_EQ(1.0f, vvf[0][0]);
|
||||
EXPECT_EQ(2.2f, vvf[0][1]);
|
||||
EXPECT_EQ(0.3f, vvf[1][0]);
|
||||
EXPECT_EQ(-40000.0f, vvf[1][1]);
|
||||
EXPECT_EQ("", error);
|
||||
}
|
||||
|
||||
TEST(array_parser, missing_open)
|
||||
{
|
||||
std::string error;
|
||||
std::vector<std::vector<float>> vvf;
|
||||
vvf = nav2_costmap_2d::parseVVF("[1, 2.2], [.3, -4e4]]", error);
|
||||
EXPECT_NE(error, "");
|
||||
}
|
||||
|
||||
TEST(array_parser, missing_close)
|
||||
{
|
||||
std::string error;
|
||||
std::vector<std::vector<float>> vvf;
|
||||
vvf = nav2_costmap_2d::parseVVF("[[1, 2.2], [.3, -4e4]", error);
|
||||
EXPECT_NE(error, "");
|
||||
}
|
||||
|
||||
TEST(array_parser, wrong_depth)
|
||||
{
|
||||
std::string error;
|
||||
std::vector<std::vector<float>> vvf;
|
||||
vvf = nav2_costmap_2d::parseVVF("[1, 2.2], [.3, -4e4]", error);
|
||||
EXPECT_NE(error, "");
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -0,0 +1,877 @@
|
||||
// Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <tuple>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
#include "tf2_ros/buffer.h"
|
||||
#include "tf2_ros/transform_listener.h"
|
||||
#include "tf2_ros/transform_broadcaster.h"
|
||||
#include "nav2_util/occ_grid_values.hpp"
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "std_msgs/msg/bool.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "nav2_msgs/msg/costmap_filter_info.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/costmap_filters/filter_values.hpp"
|
||||
#include "nav2_costmap_2d/costmap_filters/binary_filter.hpp"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
static const char FILTER_NAME[]{"binary_filter"};
|
||||
static const char INFO_TOPIC[]{"costmap_filter_info"};
|
||||
static const char MASK_TOPIC[]{"mask"};
|
||||
static const char BINARY_STATE_TOPIC[]{"binary_state"};
|
||||
|
||||
static const double NO_TRANSLATION = 0.0;
|
||||
static const double TRANSLATION_X = 1.0;
|
||||
static const double TRANSLATION_Y = 1.0;
|
||||
|
||||
static const uint8_t INCORRECT_TYPE = 200;
|
||||
|
||||
class InfoPublisher : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
InfoPublisher(uint8_t type, const char * mask_topic, double base, double multiplier)
|
||||
: Node("costmap_filter_info_pub")
|
||||
{
|
||||
publisher_ = this->create_publisher<nav2_msgs::msg::CostmapFilterInfo>(
|
||||
INFO_TOPIC, rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable());
|
||||
|
||||
std::unique_ptr<nav2_msgs::msg::CostmapFilterInfo> msg =
|
||||
std::make_unique<nav2_msgs::msg::CostmapFilterInfo>();
|
||||
msg->type = type;
|
||||
msg->filter_mask_topic = mask_topic;
|
||||
msg->base = static_cast<float>(base);
|
||||
msg->multiplier = static_cast<float>(multiplier);
|
||||
|
||||
publisher_->publish(std::move(msg));
|
||||
}
|
||||
|
||||
~InfoPublisher()
|
||||
{
|
||||
publisher_.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
rclcpp::Publisher<nav2_msgs::msg::CostmapFilterInfo>::SharedPtr publisher_;
|
||||
}; // InfoPublisher
|
||||
|
||||
class MaskPublisher : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
explicit MaskPublisher(const nav_msgs::msg::OccupancyGrid & mask)
|
||||
: Node("mask_pub")
|
||||
{
|
||||
publisher_ = this->create_publisher<nav_msgs::msg::OccupancyGrid>(
|
||||
MASK_TOPIC,
|
||||
rclcpp::QoS(rclcpp::KeepLast(1)).transient_local().reliable());
|
||||
|
||||
publisher_->publish(mask);
|
||||
}
|
||||
|
||||
~MaskPublisher()
|
||||
{
|
||||
publisher_.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
rclcpp::Publisher<nav_msgs::msg::OccupancyGrid>::SharedPtr publisher_;
|
||||
}; // MaskPublisher
|
||||
|
||||
class BinaryStateSubscriber : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
explicit BinaryStateSubscriber(const std::string & binary_state_topic, bool default_state)
|
||||
: Node("binary_state_sub"), binary_state_updated_(false)
|
||||
{
|
||||
subscriber_ = this->create_subscription<std_msgs::msg::Bool>(
|
||||
binary_state_topic, rclcpp::QoS(10),
|
||||
std::bind(&BinaryStateSubscriber::binaryStateCallback, this, std::placeholders::_1));
|
||||
|
||||
// Initialize with default state
|
||||
msg_ = std::make_shared<std_msgs::msg::Bool>();
|
||||
msg_->data = default_state;
|
||||
}
|
||||
|
||||
void binaryStateCallback(
|
||||
const std_msgs::msg::Bool::SharedPtr msg)
|
||||
{
|
||||
msg_ = msg;
|
||||
binary_state_updated_ = true;
|
||||
}
|
||||
|
||||
std_msgs::msg::Bool::SharedPtr getBinaryState()
|
||||
{
|
||||
return msg_;
|
||||
}
|
||||
|
||||
inline bool binaryStateUpdated()
|
||||
{
|
||||
return binary_state_updated_;
|
||||
}
|
||||
|
||||
inline void resetBinaryStateIndicator()
|
||||
{
|
||||
binary_state_updated_ = false;
|
||||
}
|
||||
|
||||
private:
|
||||
rclcpp::Subscription<std_msgs::msg::Bool>::SharedPtr subscriber_;
|
||||
std_msgs::msg::Bool::SharedPtr msg_;
|
||||
bool binary_state_updated_;
|
||||
}; // BinaryStateSubscriber
|
||||
|
||||
class TestMask : public nav_msgs::msg::OccupancyGrid
|
||||
{
|
||||
public:
|
||||
TestMask(
|
||||
unsigned int width, unsigned int height, double resolution,
|
||||
const std::string & mask_frame)
|
||||
: width_(width), height_(height)
|
||||
{
|
||||
// Fill filter mask info
|
||||
header.frame_id = mask_frame;
|
||||
info.resolution = resolution;
|
||||
info.width = width_;
|
||||
info.height = height_;
|
||||
info.origin.position.x = 0.0;
|
||||
info.origin.position.y = 0.0;
|
||||
info.origin.position.z = 0.0;
|
||||
info.origin.orientation.x = 0.0;
|
||||
info.origin.orientation.y = 0.0;
|
||||
info.origin.orientation.z = 0.0;
|
||||
info.origin.orientation.w = 1.0;
|
||||
|
||||
// Fill test mask as follows:
|
||||
//
|
||||
// mask (10,11)
|
||||
// *----------------*
|
||||
// |91|92|...|99|100|
|
||||
// |... |
|
||||
// |... |
|
||||
// |11|12|13|...| 20|
|
||||
// | 1| 2| 3|...| 10|
|
||||
// |-1| 0| 0|...| 0|
|
||||
// *----------------*
|
||||
// (0,0)
|
||||
data.resize(width_ * height_, nav2_util::OCC_GRID_UNKNOWN);
|
||||
|
||||
unsigned int mx, my;
|
||||
data[0] = nav2_util::OCC_GRID_UNKNOWN;
|
||||
for (mx = 1; mx < width_; mx++) {
|
||||
data[mx] = nav2_util::OCC_GRID_FREE;
|
||||
}
|
||||
unsigned int it;
|
||||
for (my = 1; my < height_; my++) {
|
||||
for (mx = 0; mx < width_; mx++) {
|
||||
it = mx + my * width_;
|
||||
data[it] = makeData(mx, my);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline int8_t makeData(unsigned int mx, unsigned int my)
|
||||
{
|
||||
return mx + (my - 1) * width_ + 1;
|
||||
}
|
||||
|
||||
private:
|
||||
const unsigned int width_;
|
||||
const unsigned int height_;
|
||||
}; // TestMask
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode()
|
||||
: default_state_(false) {}
|
||||
|
||||
~TestNode() {}
|
||||
|
||||
protected:
|
||||
void createMaps(const std::string & mask_frame);
|
||||
void publishMaps(uint8_t type, const char * mask_topic, double base, double multiplier);
|
||||
void rePublishInfo(uint8_t type, const char * mask_topic, double base, double multiplier);
|
||||
void rePublishMask();
|
||||
void setDefaultState(bool default_state); // NOTE: must be called before createBinaryFilter()
|
||||
bool createBinaryFilter(const std::string & global_frame, double flip_threshold);
|
||||
void createTFBroadcaster(const std::string & mask_frame, const std::string & global_frame);
|
||||
void publishTransform();
|
||||
|
||||
// Test methods
|
||||
void testFullMask(
|
||||
double base, double multiplier, double flip_threshold, double tr_x, double tr_y);
|
||||
void testSimpleMask(
|
||||
double base, double multiplier, double flip_threshold, double tr_x, double tr_y);
|
||||
void testOutOfMask();
|
||||
void testIncorrectTF();
|
||||
void testResetFilter();
|
||||
|
||||
void resetMaps();
|
||||
void reset();
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::BinaryFilter> binary_filter_;
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> master_grid_;
|
||||
|
||||
bool default_state_;
|
||||
|
||||
private:
|
||||
void waitSome(const std::chrono::nanoseconds & duration);
|
||||
std_msgs::msg::Bool::SharedPtr getBinaryState();
|
||||
std_msgs::msg::Bool::SharedPtr waitBinaryState();
|
||||
bool getSign(
|
||||
unsigned int x, unsigned int y, double base, double multiplier, double flip_threshold);
|
||||
void verifyBinaryState(bool sign, std_msgs::msg::Bool::SharedPtr state);
|
||||
|
||||
const unsigned int width_ = 10;
|
||||
const unsigned int height_ = 11;
|
||||
const double resolution_ = 1.0;
|
||||
|
||||
nav2_util::LifecycleNode::SharedPtr node_;
|
||||
|
||||
std::shared_ptr<tf2_ros::Buffer> tf_buffer_;
|
||||
std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
|
||||
std::shared_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster_;
|
||||
std::unique_ptr<geometry_msgs::msg::TransformStamped> transform_;
|
||||
|
||||
std::shared_ptr<TestMask> mask_;
|
||||
|
||||
std::shared_ptr<InfoPublisher> info_publisher_;
|
||||
std::shared_ptr<MaskPublisher> mask_publisher_;
|
||||
std::shared_ptr<BinaryStateSubscriber> binary_state_subscriber_;
|
||||
};
|
||||
|
||||
void TestNode::createMaps(const std::string & mask_frame)
|
||||
{
|
||||
// Make map and mask put as follows:
|
||||
// master_grid (12,13)
|
||||
// *----------------*
|
||||
// | |
|
||||
// | mask (10,11) |
|
||||
// | *-------* |
|
||||
// | |///////| |
|
||||
// | |///////| |
|
||||
// | |///////| |
|
||||
// | *-------* |
|
||||
// | (0,0) |
|
||||
// | |
|
||||
// *----------------*
|
||||
// (-2,-2)
|
||||
|
||||
// Create master_grid_
|
||||
master_grid_ = std::make_shared<nav2_costmap_2d::Costmap2D>(
|
||||
width_ + 4, height_ + 4, resolution_, -2.0, -2.0, nav2_costmap_2d::FREE_SPACE);
|
||||
|
||||
// Create mask_
|
||||
mask_ = std::make_shared<TestMask>(width_, height_, resolution_, mask_frame);
|
||||
}
|
||||
|
||||
void TestNode::publishMaps(
|
||||
uint8_t type, const char * mask_topic, double base, double multiplier)
|
||||
{
|
||||
info_publisher_ = std::make_shared<InfoPublisher>(type, mask_topic, base, multiplier);
|
||||
mask_publisher_ = std::make_shared<MaskPublisher>(*mask_);
|
||||
}
|
||||
|
||||
void TestNode::rePublishInfo(
|
||||
uint8_t type, const char * mask_topic, double base, double multiplier)
|
||||
{
|
||||
info_publisher_.reset();
|
||||
info_publisher_ = std::make_shared<InfoPublisher>(type, mask_topic, base, multiplier);
|
||||
// Allow both CostmapFilterInfo and filter mask subscribers
|
||||
// to receive a new message
|
||||
waitSome(100ms);
|
||||
}
|
||||
|
||||
void TestNode::rePublishMask()
|
||||
{
|
||||
mask_publisher_.reset();
|
||||
mask_publisher_ = std::make_shared<MaskPublisher>(*mask_);
|
||||
// Allow filter mask subscriber to receive a new message
|
||||
waitSome(100ms);
|
||||
}
|
||||
|
||||
void TestNode::waitSome(const std::chrono::nanoseconds & duration)
|
||||
{
|
||||
rclcpp::Time start_time = node_->now();
|
||||
while (rclcpp::ok() && node_->now() - start_time <= rclcpp::Duration(duration)) {
|
||||
rclcpp::spin_some(node_->get_node_base_interface());
|
||||
rclcpp::spin_some(binary_state_subscriber_);
|
||||
std::this_thread::sleep_for(10ms);
|
||||
}
|
||||
}
|
||||
|
||||
std_msgs::msg::Bool::SharedPtr TestNode::getBinaryState()
|
||||
{
|
||||
std::this_thread::sleep_for(100ms);
|
||||
rclcpp::spin_some(binary_state_subscriber_);
|
||||
return binary_state_subscriber_->getBinaryState();
|
||||
}
|
||||
|
||||
std_msgs::msg::Bool::SharedPtr TestNode::waitBinaryState()
|
||||
{
|
||||
const std::chrono::nanoseconds timeout = 500ms;
|
||||
|
||||
rclcpp::Time start_time = node_->now();
|
||||
binary_state_subscriber_->resetBinaryStateIndicator();
|
||||
while (rclcpp::ok() && node_->now() - start_time <= rclcpp::Duration(timeout)) {
|
||||
if (binary_state_subscriber_->binaryStateUpdated()) {
|
||||
binary_state_subscriber_->resetBinaryStateIndicator();
|
||||
return binary_state_subscriber_->getBinaryState();
|
||||
}
|
||||
rclcpp::spin_some(binary_state_subscriber_);
|
||||
std::this_thread::sleep_for(10ms);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void TestNode::setDefaultState(bool default_state)
|
||||
{
|
||||
default_state_ = default_state;
|
||||
}
|
||||
|
||||
bool TestNode::createBinaryFilter(const std::string & global_frame, double flip_threshold)
|
||||
{
|
||||
node_ = std::make_shared<nav2_util::LifecycleNode>("test_node");
|
||||
tf_buffer_ = std::make_shared<tf2_ros::Buffer>(node_->get_clock());
|
||||
tf_buffer_->setUsingDedicatedThread(true); // One-thread broadcasting-listening model
|
||||
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
|
||||
|
||||
nav2_costmap_2d::LayeredCostmap layers(global_frame, false, false);
|
||||
|
||||
node_->declare_parameter(
|
||||
std::string(FILTER_NAME) + ".transform_tolerance", rclcpp::ParameterValue(0.5));
|
||||
node_->set_parameter(
|
||||
rclcpp::Parameter(std::string(FILTER_NAME) + ".transform_tolerance", 0.5));
|
||||
node_->declare_parameter(
|
||||
std::string(FILTER_NAME) + ".filter_info_topic", rclcpp::ParameterValue(INFO_TOPIC));
|
||||
node_->set_parameter(
|
||||
rclcpp::Parameter(std::string(FILTER_NAME) + ".filter_info_topic", INFO_TOPIC));
|
||||
node_->declare_parameter(
|
||||
std::string(FILTER_NAME) + ".default_state", rclcpp::ParameterValue(default_state_));
|
||||
node_->set_parameter(
|
||||
rclcpp::Parameter(std::string(FILTER_NAME) + ".default_state", default_state_));
|
||||
node_->declare_parameter(
|
||||
std::string(FILTER_NAME) + ".binary_state_topic", rclcpp::ParameterValue(BINARY_STATE_TOPIC));
|
||||
node_->set_parameter(
|
||||
rclcpp::Parameter(std::string(FILTER_NAME) + ".binary_state_topic", BINARY_STATE_TOPIC));
|
||||
node_->declare_parameter(
|
||||
std::string(FILTER_NAME) + ".flip_threshold", rclcpp::ParameterValue(flip_threshold));
|
||||
node_->set_parameter(
|
||||
rclcpp::Parameter(std::string(FILTER_NAME) + ".flip_threshold", flip_threshold));
|
||||
|
||||
binary_filter_ = std::make_shared<nav2_costmap_2d::BinaryFilter>();
|
||||
binary_filter_->initialize(&layers, FILTER_NAME, tf_buffer_.get(), node_, nullptr);
|
||||
binary_filter_->initializeFilter(INFO_TOPIC);
|
||||
|
||||
binary_state_subscriber_ =
|
||||
std::make_shared<BinaryStateSubscriber>(BINARY_STATE_TOPIC, default_state_);
|
||||
|
||||
// Wait until mask will be received by BinaryFilter
|
||||
const std::chrono::nanoseconds timeout = 500ms;
|
||||
rclcpp::Time start_time = node_->now();
|
||||
while (!binary_filter_->isActive()) {
|
||||
if (node_->now() - start_time > rclcpp::Duration(timeout)) {
|
||||
return false;
|
||||
}
|
||||
rclcpp::spin_some(node_->get_node_base_interface());
|
||||
std::this_thread::sleep_for(10ms);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void TestNode::createTFBroadcaster(const std::string & mask_frame, const std::string & global_frame)
|
||||
{
|
||||
tf_broadcaster_ = std::make_shared<tf2_ros::TransformBroadcaster>(node_);
|
||||
|
||||
transform_ = std::make_unique<geometry_msgs::msg::TransformStamped>();
|
||||
transform_->header.frame_id = mask_frame;
|
||||
transform_->child_frame_id = global_frame;
|
||||
|
||||
transform_->header.stamp = node_->now() + rclcpp::Duration(100ms);
|
||||
transform_->transform.translation.x = TRANSLATION_X;
|
||||
transform_->transform.translation.y = TRANSLATION_Y;
|
||||
transform_->transform.translation.z = 0.0;
|
||||
transform_->transform.rotation.x = 0.0;
|
||||
transform_->transform.rotation.y = 0.0;
|
||||
transform_->transform.rotation.z = 0.0;
|
||||
transform_->transform.rotation.w = 1.0;
|
||||
|
||||
tf_broadcaster_->sendTransform(*transform_);
|
||||
|
||||
// Allow tf_buffer_ to be filled by listener
|
||||
waitSome(100ms);
|
||||
}
|
||||
|
||||
void TestNode::publishTransform()
|
||||
{
|
||||
if (tf_broadcaster_) {
|
||||
transform_->header.stamp = node_->now() + rclcpp::Duration(100ms);
|
||||
tf_broadcaster_->sendTransform(*transform_);
|
||||
}
|
||||
}
|
||||
|
||||
bool TestNode::getSign(
|
||||
unsigned int x, unsigned int y, double base, double multiplier, double flip_threshold)
|
||||
{
|
||||
const int8_t cost = mask_->makeData(x, y);
|
||||
return base + cost * multiplier > flip_threshold;
|
||||
}
|
||||
|
||||
void TestNode::verifyBinaryState(bool sign, std_msgs::msg::Bool::SharedPtr state)
|
||||
{
|
||||
ASSERT_TRUE(state != nullptr);
|
||||
if (sign) {
|
||||
EXPECT_FALSE(state->data == default_state_);
|
||||
} else {
|
||||
EXPECT_TRUE(state->data == default_state_);
|
||||
}
|
||||
}
|
||||
|
||||
void TestNode::testFullMask(
|
||||
double base, double multiplier, double flip_threshold, double tr_x, double tr_y)
|
||||
{
|
||||
const int min_i = 0;
|
||||
const int min_j = 0;
|
||||
const int max_i = width_ + 4;
|
||||
const int max_j = height_ + 4;
|
||||
|
||||
geometry_msgs::msg::Pose2D pose;
|
||||
std_msgs::msg::Bool::SharedPtr binary_state;
|
||||
|
||||
unsigned int x, y;
|
||||
bool prev_sign = false;
|
||||
bool sign;
|
||||
|
||||
// data = 0
|
||||
x = 1;
|
||||
y = 0;
|
||||
pose.x = x - tr_x;
|
||||
pose.y = y - tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
sign = getSign(x, y, base, multiplier, flip_threshold);
|
||||
if (sign != prev_sign) {
|
||||
// Binary filter just flipped
|
||||
binary_state = waitBinaryState();
|
||||
prev_sign = sign;
|
||||
} else {
|
||||
// Binary filter state should not be changed
|
||||
binary_state = getBinaryState();
|
||||
}
|
||||
verifyBinaryState(sign, binary_state);
|
||||
|
||||
// data in range [1..100] (sparsed for testing speed)
|
||||
for (y = 1; y < height_; y += 2) {
|
||||
for (x = 0; x < width_; x += 2) {
|
||||
pose.x = x - tr_x;
|
||||
pose.y = y - tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
|
||||
sign = getSign(x, y, base, multiplier, flip_threshold);
|
||||
if (prev_sign != sign) {
|
||||
// Binary filter just flipped
|
||||
binary_state = waitBinaryState();
|
||||
prev_sign = sign;
|
||||
} else {
|
||||
// Binary filter state should not be changed
|
||||
binary_state = getBinaryState();
|
||||
}
|
||||
verifyBinaryState(sign, binary_state);
|
||||
}
|
||||
}
|
||||
|
||||
// data = -1 (unknown)
|
||||
bool prev_state = binary_state->data;
|
||||
pose.x = -tr_x;
|
||||
pose.y = -tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = getBinaryState();
|
||||
ASSERT_TRUE(binary_state != nullptr);
|
||||
ASSERT_EQ(binary_state->data, prev_state); // Binary state won't be updated
|
||||
}
|
||||
|
||||
void TestNode::testSimpleMask(
|
||||
double base, double multiplier, double flip_threshold, double tr_x, double tr_y)
|
||||
{
|
||||
const int min_i = 0;
|
||||
const int min_j = 0;
|
||||
const int max_i = width_ + 4;
|
||||
const int max_j = height_ + 4;
|
||||
|
||||
geometry_msgs::msg::Pose2D pose;
|
||||
std_msgs::msg::Bool::SharedPtr binary_state;
|
||||
|
||||
unsigned int x, y;
|
||||
bool prev_sign = false;
|
||||
bool sign;
|
||||
|
||||
// data = 0
|
||||
x = 1;
|
||||
y = 0;
|
||||
pose.x = x - tr_x;
|
||||
pose.y = y - tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
sign = getSign(x, y, base, multiplier, flip_threshold);
|
||||
if (sign != prev_sign) {
|
||||
// Binary filter just flipped
|
||||
binary_state = waitBinaryState();
|
||||
prev_sign = sign;
|
||||
} else {
|
||||
// Binary filter state should not be changed
|
||||
binary_state = getBinaryState();
|
||||
}
|
||||
verifyBinaryState(sign, binary_state);
|
||||
|
||||
// data = <some_middle_value>
|
||||
x = width_ / 2 - 1;
|
||||
y = height_ / 2 - 1;
|
||||
pose.x = x - tr_x;
|
||||
pose.y = y - tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
|
||||
sign = getSign(x, y, base, multiplier, flip_threshold);
|
||||
if (prev_sign != sign) {
|
||||
// Binary filter just flipped
|
||||
binary_state = waitBinaryState();
|
||||
prev_sign = sign;
|
||||
} else {
|
||||
// Binary filter state should not be changed
|
||||
binary_state = getBinaryState();
|
||||
}
|
||||
verifyBinaryState(sign, binary_state);
|
||||
|
||||
// data = 100
|
||||
x = width_ - 1;
|
||||
y = height_ - 1;
|
||||
pose.x = x - tr_x;
|
||||
pose.y = y - tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
|
||||
sign = getSign(x, y, base, multiplier, flip_threshold);
|
||||
if (prev_sign != sign) {
|
||||
// Binary filter just flipped
|
||||
binary_state = waitBinaryState();
|
||||
prev_sign = sign;
|
||||
} else {
|
||||
// Binary filter state should not be changed
|
||||
binary_state = getBinaryState();
|
||||
}
|
||||
verifyBinaryState(sign, binary_state);
|
||||
|
||||
// data = -1 (unknown)
|
||||
bool prev_state = binary_state->data;
|
||||
pose.x = -tr_x;
|
||||
pose.y = -tr_y;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = getBinaryState();
|
||||
ASSERT_TRUE(binary_state != nullptr);
|
||||
ASSERT_EQ(binary_state->data, prev_state); // Binary state won't be updated
|
||||
}
|
||||
|
||||
void TestNode::testOutOfMask()
|
||||
{
|
||||
// base, multiplier and flip_threshold should have values as below for this test
|
||||
const double base = 0.0;
|
||||
const double multiplier = 1.0;
|
||||
const double flip_threshold = 10.0;
|
||||
|
||||
const int min_i = 0;
|
||||
const int min_j = 0;
|
||||
const int max_i = width_ + 4;
|
||||
const int max_j = height_ + 4;
|
||||
|
||||
geometry_msgs::msg::Pose2D pose;
|
||||
std_msgs::msg::Bool::SharedPtr binary_state;
|
||||
|
||||
// data = <some_middle_value>
|
||||
pose.x = width_ / 2 - 1;
|
||||
pose.y = height_ / 2 - 1;
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = waitBinaryState();
|
||||
verifyBinaryState(getSign(pose.x, pose.y, base, multiplier, flip_threshold), binary_state);
|
||||
|
||||
// Then go to out of mask bounds and ensure that binary state is set back to default
|
||||
pose.x = -2.0;
|
||||
pose.y = -2.0;
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = getBinaryState();
|
||||
ASSERT_TRUE(binary_state != nullptr);
|
||||
ASSERT_EQ(binary_state->data, default_state_);
|
||||
|
||||
pose.x = width_ + 1.0;
|
||||
pose.y = height_ + 1.0;
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = getBinaryState();
|
||||
ASSERT_TRUE(binary_state != nullptr);
|
||||
ASSERT_EQ(binary_state->data, default_state_);
|
||||
}
|
||||
|
||||
void TestNode::testIncorrectTF()
|
||||
{
|
||||
const int min_i = 0;
|
||||
const int min_j = 0;
|
||||
const int max_i = width_ + 4;
|
||||
const int max_j = height_ + 4;
|
||||
|
||||
geometry_msgs::msg::Pose2D pose;
|
||||
std_msgs::msg::Bool::SharedPtr binary_state;
|
||||
|
||||
// data = <some_middle_value>
|
||||
pose.x = width_ / 2 - 1;
|
||||
pose.y = height_ / 2 - 1;
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = waitBinaryState();
|
||||
ASSERT_TRUE(binary_state == nullptr);
|
||||
}
|
||||
|
||||
void TestNode::testResetFilter()
|
||||
{
|
||||
// base, multiplier and flip_threshold should have values as below for this test
|
||||
const double base = 0.0;
|
||||
const double multiplier = 1.0;
|
||||
const double flip_threshold = 10.0;
|
||||
|
||||
const int min_i = 0;
|
||||
const int min_j = 0;
|
||||
const int max_i = width_ + 4;
|
||||
const int max_j = height_ + 4;
|
||||
|
||||
geometry_msgs::msg::Pose2D pose;
|
||||
std_msgs::msg::Bool::SharedPtr binary_state;
|
||||
|
||||
// Switch-on binary filter
|
||||
pose.x = width_ / 2 - 1;
|
||||
pose.y = height_ / 2 - 1;
|
||||
publishTransform();
|
||||
binary_filter_->process(*master_grid_, min_i, min_j, max_i, max_j, pose);
|
||||
binary_state = waitBinaryState();
|
||||
verifyBinaryState(getSign(pose.x, pose.y, base, multiplier, flip_threshold), binary_state);
|
||||
|
||||
// Reset binary filter and check its state was resetted to default
|
||||
binary_filter_->resetFilter();
|
||||
binary_state = waitBinaryState();
|
||||
ASSERT_TRUE(binary_state != nullptr);
|
||||
ASSERT_EQ(binary_state->data, default_state_);
|
||||
}
|
||||
|
||||
void TestNode::resetMaps()
|
||||
{
|
||||
mask_.reset();
|
||||
master_grid_.reset();
|
||||
}
|
||||
|
||||
void TestNode::reset()
|
||||
{
|
||||
resetMaps();
|
||||
info_publisher_.reset();
|
||||
mask_publisher_.reset();
|
||||
binary_state_subscriber_.reset();
|
||||
binary_filter_.reset();
|
||||
node_.reset();
|
||||
tf_listener_.reset();
|
||||
tf_broadcaster_.reset();
|
||||
tf_buffer_.reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testBinaryState)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
ASSERT_TRUE(createBinaryFilter("map", 10.0));
|
||||
|
||||
// Test BinaryFilter
|
||||
testSimpleMask(0.0, 1.0, 10.0, NO_TRANSLATION, NO_TRANSLATION);
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testBinaryStateScaled)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 100.0, -1.0);
|
||||
ASSERT_TRUE(createBinaryFilter("map", 35.0));
|
||||
|
||||
// Test BinaryFilter
|
||||
testFullMask(100.0, -1.0, 35.0, NO_TRANSLATION, NO_TRANSLATION);
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testInvertedBinaryState)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
setDefaultState(true);
|
||||
ASSERT_TRUE(createBinaryFilter("map", 10.0));
|
||||
|
||||
// Test BinaryFilter
|
||||
testSimpleMask(0.0, 1.0, 10.0, NO_TRANSLATION, NO_TRANSLATION);
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testOutOfBounds)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
ASSERT_TRUE(createBinaryFilter("map", 10.0));
|
||||
|
||||
// Test BinaryFilter
|
||||
testOutOfMask();
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testInfoRePublish)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
// Publish Info with incorrect dummy mask topic
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, "dummy_topic", 0.0, 1.0);
|
||||
ASSERT_FALSE(createBinaryFilter("map", 10.0));
|
||||
|
||||
// Re-publish filter info with correct mask topic
|
||||
// and ensure that everything works fine
|
||||
rePublishInfo(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
|
||||
// Test BinaryFilter
|
||||
testSimpleMask(0.0, 1.0, 10.0, NO_TRANSLATION, NO_TRANSLATION);
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testMaskRePublish)
|
||||
{
|
||||
// Create mask in incorrect frame
|
||||
createMaps("dummy");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
EXPECT_TRUE(createBinaryFilter("map", 10.0));
|
||||
|
||||
// Create mask in correct frame
|
||||
resetMaps();
|
||||
createMaps("map");
|
||||
// Re-publish correct filter mask and ensure that everything works fine
|
||||
rePublishMask();
|
||||
|
||||
// Test BinaryFilter
|
||||
testSimpleMask(0.0, 1.0, 10.0, NO_TRANSLATION, NO_TRANSLATION);
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testIncorrectFilterType)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(INCORRECT_TYPE, MASK_TOPIC, 0.0, 1.0);
|
||||
ASSERT_FALSE(createBinaryFilter("map", 10.0));
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testDifferentFrame)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
ASSERT_TRUE(createBinaryFilter("odom", 10.0));
|
||||
createTFBroadcaster("map", "odom");
|
||||
|
||||
// Test BinaryFilter
|
||||
testSimpleMask(0.0, 1.0, 10.0, TRANSLATION_X, TRANSLATION_Y);
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testIncorrectFrame)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
ASSERT_TRUE(createBinaryFilter("odom", 10.0));
|
||||
// map->odom TF does not exit
|
||||
|
||||
// Test BinaryFilter with incorrect TF chain
|
||||
testIncorrectTF();
|
||||
|
||||
// Clean-up
|
||||
binary_filter_->resetFilter();
|
||||
reset();
|
||||
}
|
||||
|
||||
TEST_F(TestNode, testResetState)
|
||||
{
|
||||
// Initialize test system
|
||||
createMaps("map");
|
||||
publishMaps(nav2_costmap_2d::BINARY_FILTER, MASK_TOPIC, 0.0, 1.0);
|
||||
ASSERT_TRUE(createBinaryFilter("map", 10.0));
|
||||
|
||||
testResetFilter();
|
||||
|
||||
// Clean-up
|
||||
// do not need to resetFilter(): this was already done in testResetFilter()
|
||||
reset();
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
// Initialize the system
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
rclcpp::init(argc, argv);
|
||||
|
||||
// Actual testing
|
||||
bool test_result = RUN_ALL_TESTS();
|
||||
|
||||
// Shutdown
|
||||
rclcpp::shutdown();
|
||||
|
||||
return test_result;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright (c) 2021 Samsung Research Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
TEST(CopyWindow, copyValidWindow)
|
||||
{
|
||||
nav2_costmap_2d::Costmap2D src(10, 10, 0.1, 0.0, 0.0);
|
||||
nav2_costmap_2d::Costmap2D dst(5, 5, 0.2, 100.0, 100.0);
|
||||
// Adding 2 marked cells to source costmap
|
||||
src.setCost(2, 2, 100);
|
||||
src.setCost(5, 5, 200);
|
||||
|
||||
ASSERT_TRUE(dst.copyWindow(src, 2, 2, 6, 6, 0, 0));
|
||||
// Check that both marked cells were copied to destination costmap
|
||||
ASSERT_EQ(dst.getCost(0, 0), 100);
|
||||
ASSERT_EQ(dst.getCost(3, 3), 200);
|
||||
}
|
||||
|
||||
TEST(CopyWindow, copyInvalidWindow)
|
||||
{
|
||||
nav2_costmap_2d::Costmap2D src(10, 10, 0.1, 0.0, 0.0);
|
||||
nav2_costmap_2d::Costmap2D dst(5, 5, 0.2, 100.0, 100.0);
|
||||
|
||||
// Case1: incorrect source bounds
|
||||
ASSERT_FALSE(dst.copyWindow(src, 9, 9, 11, 11, 0, 0));
|
||||
// Case2: incorrect destination bounds
|
||||
ASSERT_FALSE(dst.copyWindow(src, 0, 0, 1, 1, 5, 5));
|
||||
ASSERT_FALSE(dst.copyWindow(src, 0, 0, 6, 6, 0, 0));
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// Copyright (c) 2020 Samsung Research Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_util/occ_grid_values.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "nav2_costmap_2d/cost_values.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
static constexpr double EPSILON = std::numeric_limits<float>::epsilon();
|
||||
static constexpr double RESOLUTION = 0.05;
|
||||
static constexpr double ORIGIN_X = 0.1;
|
||||
static constexpr double ORIGIN_Y = 0.2;
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode() {}
|
||||
|
||||
~TestNode()
|
||||
{
|
||||
occ_grid_.reset();
|
||||
costmap_.reset();
|
||||
}
|
||||
|
||||
protected:
|
||||
void createMaps();
|
||||
void verifyCostmap();
|
||||
|
||||
private:
|
||||
std::shared_ptr<nav_msgs::msg::OccupancyGrid> occ_grid_;
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> costmap_;
|
||||
};
|
||||
|
||||
void TestNode::createMaps()
|
||||
{
|
||||
// Create occ_grid_ map
|
||||
occ_grid_ = std::make_shared<nav_msgs::msg::OccupancyGrid>();
|
||||
|
||||
const unsigned int width = 4;
|
||||
const unsigned int height = 3;
|
||||
|
||||
occ_grid_->info.resolution = RESOLUTION;
|
||||
occ_grid_->info.width = width;
|
||||
occ_grid_->info.height = height;
|
||||
occ_grid_->info.origin.position.x = ORIGIN_X;
|
||||
occ_grid_->info.origin.position.y = ORIGIN_Y;
|
||||
occ_grid_->info.origin.position.z = 0.0;
|
||||
occ_grid_->info.origin.orientation.x = 0.0;
|
||||
occ_grid_->info.origin.orientation.y = 0.0;
|
||||
occ_grid_->info.origin.orientation.z = 0.0;
|
||||
occ_grid_->info.origin.orientation.w = 1.0;
|
||||
occ_grid_->data.resize(width * height);
|
||||
|
||||
int8_t data;
|
||||
for (unsigned int i = 0; i < width * height; i++) {
|
||||
data = i * 10;
|
||||
if (data <= nav2_util::OCC_GRID_OCCUPIED) {
|
||||
occ_grid_->data[i] = data;
|
||||
} else {
|
||||
occ_grid_->data[i] = nav2_util::OCC_GRID_UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
// Create costmap_ (convert OccupancyGrid -> to Costmap2D)
|
||||
costmap_ = std::make_shared<nav2_costmap_2d::Costmap2D>(*occ_grid_);
|
||||
}
|
||||
|
||||
void TestNode::verifyCostmap()
|
||||
{
|
||||
// Verify Costmap2D info
|
||||
EXPECT_NEAR(costmap_->getResolution(), RESOLUTION, EPSILON);
|
||||
EXPECT_NEAR(costmap_->getOriginX(), ORIGIN_X, EPSILON);
|
||||
EXPECT_NEAR(costmap_->getOriginY(), ORIGIN_Y, EPSILON);
|
||||
|
||||
// Verify Costmap2D data
|
||||
unsigned int it;
|
||||
unsigned char data, data_ref;
|
||||
for (it = 0; it < (costmap_->getSizeInCellsX() * costmap_->getSizeInCellsY() - 1); it++) {
|
||||
data = costmap_->getCharMap()[it];
|
||||
if (it != costmap_->getSizeInCellsX() * costmap_->getSizeInCellsY() - 1) {
|
||||
data_ref = std::round(
|
||||
static_cast<double>(nav2_costmap_2d::LETHAL_OBSTACLE - nav2_costmap_2d::FREE_SPACE) * it /
|
||||
10);
|
||||
} else {
|
||||
data_ref = nav2_costmap_2d::NO_INFORMATION;
|
||||
}
|
||||
EXPECT_EQ(data, data_ref);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(TestNode, convertOccGridToCostmap)
|
||||
{
|
||||
createMaps();
|
||||
verifyCostmap();
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// Copyright (c) 2022 Samsung R&D Institute Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_util/lifecycle_node.hpp"
|
||||
|
||||
#include "nav2_costmap_2d/costmap_filters/costmap_filter.hpp"
|
||||
#include "std_srvs/srv/set_bool.hpp"
|
||||
|
||||
static const char FILTER_NAME[]{"costmap_filter"};
|
||||
|
||||
class CostmapFilterWrapper : public nav2_costmap_2d::CostmapFilter
|
||||
{
|
||||
public:
|
||||
// Dummy implementations of virtual methods
|
||||
void initializeFilter(
|
||||
const std::string &) {}
|
||||
|
||||
void process(
|
||||
nav2_costmap_2d::Costmap2D &,
|
||||
int, int, int, int,
|
||||
const geometry_msgs::msg::Pose2D &) {}
|
||||
|
||||
void resetFilter() {}
|
||||
|
||||
// Actual testing methods
|
||||
void setName(const std::string & name)
|
||||
{
|
||||
name_ = name;
|
||||
}
|
||||
|
||||
void setNode(const nav2_util::LifecycleNode::WeakPtr & node)
|
||||
{
|
||||
node_ = node;
|
||||
}
|
||||
|
||||
bool getEnabled()
|
||||
{
|
||||
return enabled_;
|
||||
}
|
||||
};
|
||||
|
||||
class TestNode : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
TestNode()
|
||||
{
|
||||
// Create new LifecycleNode
|
||||
node_ = std::make_shared<nav2_util::LifecycleNode>("test_node");
|
||||
|
||||
// Create new CostmapFilter
|
||||
costmap_filter_ = std::make_shared<CostmapFilterWrapper>();
|
||||
costmap_filter_->setNode(node_);
|
||||
costmap_filter_->setName(FILTER_NAME);
|
||||
|
||||
// Set CostmapFilter ROS-parameters
|
||||
node_->declare_parameter(
|
||||
std::string(FILTER_NAME) + ".filter_info_topic", rclcpp::ParameterValue("filter_info"));
|
||||
node_->set_parameter(
|
||||
rclcpp::Parameter(std::string(FILTER_NAME) + ".filter_info_topic", "filter_info"));
|
||||
}
|
||||
|
||||
~TestNode()
|
||||
{
|
||||
costmap_filter_.reset();
|
||||
node_.reset();
|
||||
}
|
||||
|
||||
template<class T>
|
||||
typename T::Response::SharedPtr send_request(
|
||||
nav2_util::LifecycleNode::SharedPtr node,
|
||||
typename rclcpp::Client<T>::SharedPtr client,
|
||||
typename T::Request::SharedPtr request)
|
||||
{
|
||||
auto result = client->async_send_request(request);
|
||||
|
||||
// Wait for the result
|
||||
if (rclcpp::spin_until_future_complete(node, result) == rclcpp::FutureReturnCode::SUCCESS) {
|
||||
return result.get();
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
nav2_util::LifecycleNode::SharedPtr node_;
|
||||
std::shared_ptr<CostmapFilterWrapper> costmap_filter_;
|
||||
};
|
||||
|
||||
TEST_F(TestNode, testEnableService)
|
||||
{
|
||||
costmap_filter_->onInitialize();
|
||||
|
||||
RCLCPP_INFO(node_->get_logger(), "Testing enabling service");
|
||||
auto req = std::make_shared<std_srvs::srv::SetBool::Request>();
|
||||
auto client = node_->create_client<std_srvs::srv::SetBool>(
|
||||
std::string(FILTER_NAME) + "/toggle_filter");
|
||||
|
||||
RCLCPP_INFO(node_->get_logger(), "Waiting for enabling service");
|
||||
ASSERT_TRUE(client->wait_for_service());
|
||||
|
||||
// Set costmap filter enabled
|
||||
req->data = true;
|
||||
auto resp = send_request<std_srvs::srv::SetBool>(node_, client, req);
|
||||
|
||||
ASSERT_NE(resp, nullptr);
|
||||
ASSERT_TRUE(resp->success);
|
||||
ASSERT_EQ(resp->message, "Enabled");
|
||||
ASSERT_TRUE(costmap_filter_->getEnabled());
|
||||
|
||||
// Set costmap filter disabled
|
||||
req->data = false;
|
||||
resp = send_request<std_srvs::srv::SetBool>(node_, client, req);
|
||||
|
||||
ASSERT_NE(resp, nullptr);
|
||||
ASSERT_TRUE(resp->success);
|
||||
ASSERT_EQ(resp->message, "Disabled");
|
||||
ASSERT_FALSE(costmap_filter_->getEnabled());
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
// Initialize the system
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
rclcpp::init(argc, argv);
|
||||
|
||||
// Actual testing
|
||||
bool test_result = RUN_ALL_TESTS();
|
||||
|
||||
// Shutdown
|
||||
rclcpp::shutdown();
|
||||
|
||||
return test_result;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) 2023 Samsung R&D Institute Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_util/occ_grid_values.hpp"
|
||||
#include "nav_msgs/msg/occupancy_grid.hpp"
|
||||
#include "geometry_msgs/msg/pose2_d.hpp"
|
||||
#include "nav2_costmap_2d/costmap_2d.hpp"
|
||||
#include "nav2_costmap_2d/costmap_filters/costmap_filter.hpp"
|
||||
|
||||
class CostmapFilterWrapper : public nav2_costmap_2d::CostmapFilter
|
||||
{
|
||||
public:
|
||||
CostmapFilterWrapper() {}
|
||||
|
||||
bool worldToMask(
|
||||
nav_msgs::msg::OccupancyGrid::ConstSharedPtr filter_mask,
|
||||
double wx, double wy, unsigned int & mx, unsigned int & my) const
|
||||
{
|
||||
return nav2_costmap_2d::CostmapFilter::worldToMask(filter_mask, wx, wy, mx, my);
|
||||
}
|
||||
|
||||
// API coverage
|
||||
void initializeFilter(const std::string &) {}
|
||||
void process(
|
||||
nav2_costmap_2d::Costmap2D &, int, int, int, int, const geometry_msgs::msg::Pose2D &)
|
||||
{}
|
||||
void resetFilter() {}
|
||||
};
|
||||
|
||||
TEST(CostmapFilter, testWorldToMask)
|
||||
{
|
||||
// Create occupancy grid for test as follows:
|
||||
//
|
||||
// ^
|
||||
// | (6,6)
|
||||
// | *-----*
|
||||
// | |/////| <- mask
|
||||
// | |/////|
|
||||
// | *-----*
|
||||
// | (3,3)
|
||||
// *---------------->
|
||||
// (0,0)
|
||||
|
||||
const unsigned int width = 3;
|
||||
const unsigned int height = 3;
|
||||
|
||||
auto mask = std::make_shared<nav_msgs::msg::OccupancyGrid>();
|
||||
mask->header.frame_id = "map";
|
||||
mask->info.resolution = 1.0;
|
||||
mask->info.width = width;
|
||||
mask->info.height = height;
|
||||
mask->info.origin.position.x = 3.0;
|
||||
mask->info.origin.position.y = 3.0;
|
||||
|
||||
mask->data.resize(width * height, nav2_util::OCC_GRID_OCCUPIED);
|
||||
|
||||
CostmapFilterWrapper cf;
|
||||
unsigned int mx, my;
|
||||
// Point inside mask
|
||||
ASSERT_TRUE(cf.worldToMask(mask, 4.0, 5.0, mx, my));
|
||||
ASSERT_EQ(mx, 1u);
|
||||
ASSERT_EQ(my, 2u);
|
||||
// Corner cases
|
||||
ASSERT_TRUE(cf.worldToMask(mask, 3.0, 3.0, mx, my));
|
||||
ASSERT_EQ(mx, 0u);
|
||||
ASSERT_EQ(my, 0u);
|
||||
ASSERT_TRUE(cf.worldToMask(mask, 5.9, 5.9, mx, my));
|
||||
ASSERT_EQ(mx, 2u);
|
||||
ASSERT_EQ(my, 2u);
|
||||
// Point outside mask
|
||||
ASSERT_FALSE(cf.worldToMask(mask, 2.9, 2.9, mx, my));
|
||||
ASSERT_FALSE(cf.worldToMask(mask, 6.0, 6.0, mx, my));
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
// Initialize the system
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
rclcpp::init(argc, argv);
|
||||
|
||||
// Actual testing
|
||||
bool test_result = RUN_ALL_TESTS();
|
||||
|
||||
// Shutdown
|
||||
rclcpp::shutdown();
|
||||
|
||||
return test_result;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright (c) 2020 Samsung Research Russia
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License. Reserved.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include "rclcpp/rclcpp.hpp"
|
||||
#include "nav2_costmap_2d/layer.hpp"
|
||||
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture g_rclcppfixture;
|
||||
|
||||
class LayerWrapper : public nav2_costmap_2d::Layer
|
||||
{
|
||||
void reset() {}
|
||||
void updateBounds(double, double, double, double *, double *, double *, double *) {}
|
||||
void updateCosts(nav2_costmap_2d::Costmap2D &, int, int, int, int) {}
|
||||
bool isClearable() {return false;}
|
||||
};
|
||||
|
||||
TEST(DeclareParameter, useValidParameter)
|
||||
{
|
||||
LayerWrapper layer;
|
||||
nav2_util::LifecycleNode::SharedPtr node =
|
||||
std::make_shared<nav2_util::LifecycleNode>("test_node");
|
||||
tf2_ros::Buffer tf(node->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
|
||||
layer.initialize(&layers, "test_layer", &tf, node, nullptr);
|
||||
|
||||
layer.declareParameter("test1", rclcpp::ParameterValue("test_val1"));
|
||||
try {
|
||||
std::string val = node->get_parameter("test_layer.test1").as_string();
|
||||
EXPECT_EQ(val, "test_val1");
|
||||
} catch (rclcpp::exceptions::ParameterNotDeclaredException & ex) {
|
||||
FAIL() << "test_layer.test1 parameter is not set";
|
||||
}
|
||||
}
|
||||
|
||||
TEST(DeclareParameter, useInvalidParameter)
|
||||
{
|
||||
LayerWrapper layer;
|
||||
nav2_util::LifecycleNode::SharedPtr node =
|
||||
std::make_shared<nav2_util::LifecycleNode>("test_node");
|
||||
tf2_ros::Buffer tf(node->get_clock());
|
||||
nav2_costmap_2d::LayeredCostmap layers("frame", false, false);
|
||||
|
||||
layer.initialize(&layers, "test_layer", &tf, node, nullptr);
|
||||
|
||||
layer.declareParameter("test2", rclcpp::PARAMETER_STRING);
|
||||
try {
|
||||
std::string val = node->get_parameter("test_layer.test2").as_string();
|
||||
FAIL() << "Incorrectly handling test_layer.test2 parameter which was not set";
|
||||
} catch (rclcpp::exceptions::ParameterUninitializedException & ex) {
|
||||
SUCCEED();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <tuple>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
||||
#include "nav2_costmap_2d/denoise_layer.hpp"
|
||||
#include "image_tests_helper.hpp"
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
/**
|
||||
* @brief nav2_costmap_2d::DenoiseLayer class wrapper
|
||||
*
|
||||
* Provides access to DenoiseLayer private methods for testing them in isolation
|
||||
*/
|
||||
class DenoiseLayerTester : public ::testing::Test
|
||||
{
|
||||
public:
|
||||
void removeSinglePixels(
|
||||
Image<uint8_t> & image, ConnectivityType connectivity,
|
||||
bool no_information_is_obstacle = true)
|
||||
{
|
||||
denoise_.group_connectivity_type_ = connectivity;
|
||||
denoise_.no_information_is_obstacle_ = no_information_is_obstacle;
|
||||
denoise_.removeSinglePixels(image);
|
||||
}
|
||||
|
||||
void removeGroups(
|
||||
Image<uint8_t> & image, ConnectivityType connectivity,
|
||||
size_t minimal_group_size, bool no_information_is_obstacle = true)
|
||||
{
|
||||
denoise_.group_connectivity_type_ = connectivity;
|
||||
denoise_.minimal_group_size_ = minimal_group_size;
|
||||
denoise_.no_information_is_obstacle_ = no_information_is_obstacle;
|
||||
denoise_.removeGroups(image);
|
||||
}
|
||||
|
||||
void denoise(
|
||||
Image<uint8_t> & image, ConnectivityType connectivity,
|
||||
size_t minimal_group_size, bool no_information_is_obstacle = true)
|
||||
{
|
||||
denoise_.group_connectivity_type_ = connectivity;
|
||||
denoise_.minimal_group_size_ = minimal_group_size;
|
||||
denoise_.no_information_is_obstacle_ = no_information_is_obstacle;
|
||||
denoise_.denoise(image);
|
||||
}
|
||||
|
||||
bool reset()
|
||||
{
|
||||
denoise_.current_ = true;
|
||||
denoise_.reset();
|
||||
return denoise_.current_;
|
||||
}
|
||||
|
||||
static void initialize(nav2_costmap_2d::DenoiseLayer & d)
|
||||
{
|
||||
d.onInitialize();
|
||||
}
|
||||
|
||||
static bool & touchCurrent(nav2_costmap_2d::DenoiseLayer & d)
|
||||
{
|
||||
return d.current_;
|
||||
}
|
||||
|
||||
static void configure(
|
||||
nav2_costmap_2d::DenoiseLayer & d, ConnectivityType connectivity, size_t minimal_group_size)
|
||||
{
|
||||
d.enabled_ = true;
|
||||
d.group_connectivity_type_ = connectivity;
|
||||
d.minimal_group_size_ = minimal_group_size;
|
||||
}
|
||||
|
||||
static std::tuple<bool, ConnectivityType, size_t> getParameters(
|
||||
const nav2_costmap_2d::DenoiseLayer & d)
|
||||
{
|
||||
return std::make_tuple(d.enabled_, d.group_connectivity_type_, d.minimal_group_size_);
|
||||
}
|
||||
|
||||
protected:
|
||||
std::vector<uint8_t> image_buffer_bytes;
|
||||
std::vector<uint8_t> image_buffer_bytes2;
|
||||
std::vector<uint8_t> image_buffer_bytes3;
|
||||
|
||||
private:
|
||||
nav2_costmap_2d::DenoiseLayer denoise_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
using namespace nav2_costmap_2d;
|
||||
|
||||
TEST_F(DenoiseLayerTester, removeSinglePixels4way) {
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x.x."
|
||||
"x..x"
|
||||
".x.."
|
||||
"xx.x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
"x..."
|
||||
"x..."
|
||||
".x.."
|
||||
"xx..", image_buffer_bytes2);
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way4);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removeSinglePixels4wayNoInformationIsEmpty) {
|
||||
const std::map<char, uint8_t> legend = {{'.', 0}, {'n', NO_INFORMATION}, {'x', LETHAL_OBSTACLE}};
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x.x."
|
||||
"xnnx"
|
||||
"nxnn"
|
||||
"xx.x", image_buffer_bytes, legend);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
"x..."
|
||||
"xnn."
|
||||
"nxnn"
|
||||
"xx..", image_buffer_bytes2, legend);
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way4, false);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removeSinglePixels8way) {
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x.x."
|
||||
"x..x"
|
||||
".x.."
|
||||
"xx.x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
"x.x."
|
||||
"x..x"
|
||||
".x.."
|
||||
"xx..", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way8);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removeSinglePixelsFromExtremelySmallImage) {
|
||||
{
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way8);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp));
|
||||
}
|
||||
|
||||
{
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x."
|
||||
".x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
"x."
|
||||
".x", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way8);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp));
|
||||
}
|
||||
|
||||
{
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x."
|
||||
".x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".."
|
||||
"..", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way4);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removeSinglePixelsFromNonBinary) {
|
||||
// buffer for 9 pixels with neutral (between FREE_SPACE and INSCRIBED_INFLATED_OBSTACLE) value
|
||||
image_buffer_bytes.assign(9, 250);
|
||||
Image<uint8_t> in = makeImage<uint8_t>(3, 3, image_buffer_bytes);
|
||||
in.row(1)[1] = NO_INFORMATION;
|
||||
Image<uint8_t> exp = clone(in, image_buffer_bytes2);
|
||||
exp.row(1)[1] = FREE_SPACE;
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeSinglePixels(out, ConnectivityType::Way4);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removePixelsGroup4way) {
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
".xx..xx"
|
||||
"..x.x.."
|
||||
"x..x..x"
|
||||
"x......"
|
||||
"...x.xx"
|
||||
"xxx..xx"
|
||||
"....xx.", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".xx...."
|
||||
"..x...."
|
||||
"......."
|
||||
"......."
|
||||
".....xx"
|
||||
"xxx..xx"
|
||||
"....xx.", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeGroups(out, ConnectivityType::Way4, 3);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removePixelsGroup4wayNoInformationIsEmpty) {
|
||||
const std::map<char, uint8_t> legend = {{'.', 0}, {'n', NO_INFORMATION}, {'x', LETHAL_OBSTACLE}};
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
".xxnnxx"
|
||||
"..xnx.."
|
||||
"x..x..x"
|
||||
"x......"
|
||||
"nnnxnxx"
|
||||
"xxx..xx"
|
||||
"....xx.", image_buffer_bytes, legend);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".xxnn.."
|
||||
"..xn..."
|
||||
"......."
|
||||
"......."
|
||||
"nnn.nxx"
|
||||
"xxx..xx"
|
||||
"....xx.", image_buffer_bytes2, legend);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeGroups(out, ConnectivityType::Way4, 3, false);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removePixelsGroup8way) {
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
".xx..xx"
|
||||
"..x.x.."
|
||||
"x..x..x"
|
||||
"x......"
|
||||
"...x.xx"
|
||||
"xxx..xx"
|
||||
"....xx.", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".xx..xx"
|
||||
"..x.x.."
|
||||
"...x..."
|
||||
"......."
|
||||
"...x.xx"
|
||||
"xxx..xx"
|
||||
"....xx.", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeGroups(out, ConnectivityType::Way8, 3);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removePixelsGroupFromExtremelySmallImage) {
|
||||
{
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeGroups(out, ConnectivityType::Way8, 3);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp));
|
||||
}
|
||||
|
||||
{
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"x."
|
||||
".x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
".."
|
||||
"..", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeGroups(out, ConnectivityType::Way8, 3);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, removePixelsGroupFromNonBinary) {
|
||||
// buffer for 9 pixels with neutral (between FREE_SPACE and INSCRIBED_INFLATED_OBSTACLE) value
|
||||
image_buffer_bytes.assign(9, 250);
|
||||
Image<uint8_t> in = makeImage<uint8_t>(3, 3, image_buffer_bytes);
|
||||
in.row(1)[1] = 255;
|
||||
|
||||
Image<uint8_t> exp = clone(in, image_buffer_bytes2);
|
||||
exp.row(1)[1] = 0;
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
removeGroups(out, ConnectivityType::Way4, 2);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, denoiseSingles) {
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"xx."
|
||||
"..."
|
||||
"..x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
"xx."
|
||||
"..."
|
||||
"...", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
denoise(out, ConnectivityType::Way4, 2);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, denoiseGroups) {
|
||||
const auto in = imageFromString<uint8_t>(
|
||||
"xx."
|
||||
"x.x"
|
||||
"..x", image_buffer_bytes);
|
||||
const auto exp = imageFromString<uint8_t>(
|
||||
"xx."
|
||||
"x.."
|
||||
"...", image_buffer_bytes2);
|
||||
|
||||
auto out = clone(in, image_buffer_bytes3);
|
||||
denoise(out, ConnectivityType::Way4, 3);
|
||||
|
||||
ASSERT_TRUE(isEqual(out, exp)) <<
|
||||
"input:" << std::endl << in << std::endl <<
|
||||
"output:" << std::endl << out << std::endl <<
|
||||
"expected:" << std::endl << exp;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, denoiseEmpty) {
|
||||
Image<uint8_t> in;
|
||||
|
||||
ASSERT_NO_THROW(denoise(in, ConnectivityType::Way4, 2));
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, denoiseNothing) {
|
||||
Image<uint8_t> in = makeImage<uint8_t>(1, 1, image_buffer_bytes);
|
||||
|
||||
ASSERT_NO_THROW(denoise(in, ConnectivityType::Way4, 1));
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, constructorAndDestructor) {
|
||||
ASSERT_NO_THROW(
|
||||
// []()
|
||||
{
|
||||
nav2_costmap_2d::DenoiseLayer layer;
|
||||
});
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, reset) {
|
||||
ASSERT_FALSE(reset());
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, isClearable) {
|
||||
nav2_costmap_2d::DenoiseLayer layer;
|
||||
|
||||
ASSERT_FALSE(layer.isClearable());
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, updateBounds) {
|
||||
nav2_costmap_2d::DenoiseLayer layer;
|
||||
|
||||
const std::array<double, 4> region = {1., 2., 3., 4.};
|
||||
auto r = region;
|
||||
|
||||
ASSERT_NO_THROW(layer.updateBounds(0., 0., 0., &r[0], &r[1], &r[2], &r[3]));
|
||||
ASSERT_EQ(r, region);
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, updateCostsIfDisabled) {
|
||||
nav2_costmap_2d::DenoiseLayer layer;
|
||||
nav2_costmap_2d::Costmap2D costmap(1, 1, 1., 0., 0., 255);
|
||||
|
||||
layer.updateCosts(costmap, 0, 0, 1, 1);
|
||||
|
||||
ASSERT_EQ(costmap.getCost(0), 255);
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, updateCosts) {
|
||||
nav2_costmap_2d::DenoiseLayer layer;
|
||||
nav2_costmap_2d::Costmap2D costmap(1, 1, 1., 0., 0.);
|
||||
costmap.setCost(0, 0, NO_INFORMATION);
|
||||
DenoiseLayerTester::configure(layer, ConnectivityType::Way4, 2);
|
||||
|
||||
layer.updateCosts(costmap, 0, 0, 1, 1);
|
||||
|
||||
ASSERT_EQ(costmap.getCost(0), FREE_SPACE);
|
||||
}
|
||||
|
||||
// Copy paste from declare_parameter_test.cpp
|
||||
class RclCppFixture
|
||||
{
|
||||
public:
|
||||
RclCppFixture() {rclcpp::init(0, nullptr);}
|
||||
~RclCppFixture() {rclcpp::shutdown();}
|
||||
};
|
||||
RclCppFixture rcl_cpp_fixture;
|
||||
|
||||
std::shared_ptr<nav2_costmap_2d::DenoiseLayer> constructLayer(
|
||||
std::shared_ptr<nav2_util::LifecycleNode> node =
|
||||
std::make_shared<nav2_util::LifecycleNode>("test_node"))
|
||||
{
|
||||
auto tf = std::make_shared<tf2_ros::Buffer>(node->get_clock());
|
||||
auto layers = std::make_shared<nav2_costmap_2d::LayeredCostmap>("frame", false, false);
|
||||
|
||||
auto deleter = [node, tf, layers](nav2_costmap_2d::DenoiseLayer * ptr)
|
||||
{
|
||||
delete ptr;
|
||||
};
|
||||
auto layer = std::shared_ptr<nav2_costmap_2d::DenoiseLayer>(
|
||||
new nav2_costmap_2d::DenoiseLayer, deleter);
|
||||
layer->initialize(layers.get(), "test_layer", tf.get(), node, nullptr);
|
||||
return layer;
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, initializeDefault) {
|
||||
auto layer = constructLayer();
|
||||
|
||||
DenoiseLayerTester::initialize(*layer);
|
||||
|
||||
ASSERT_EQ(
|
||||
DenoiseLayerTester::getParameters(*layer),
|
||||
std::make_tuple(true, ConnectivityType::Way8, 2));
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, initializeCustom) {
|
||||
auto node = std::make_shared<nav2_util::LifecycleNode>("test_node");
|
||||
auto layer = constructLayer(node);
|
||||
node->set_parameter(
|
||||
rclcpp::Parameter(layer->getFullName("minimal_group_size"), rclcpp::ParameterValue(5)));
|
||||
node->set_parameter(
|
||||
rclcpp::Parameter(layer->getFullName("group_connectivity_type"), rclcpp::ParameterValue(4)));
|
||||
|
||||
DenoiseLayerTester::initialize(*layer);
|
||||
|
||||
ASSERT_EQ(
|
||||
DenoiseLayerTester::getParameters(*layer),
|
||||
std::make_tuple(true, ConnectivityType::Way4, 5));
|
||||
}
|
||||
|
||||
TEST_F(DenoiseLayerTester, initializeInvalid) {
|
||||
auto node = std::make_shared<nav2_util::LifecycleNode>("test_node");
|
||||
auto layer = constructLayer(node);
|
||||
node->set_parameter(
|
||||
rclcpp::Parameter(layer->getFullName("minimal_group_size"), rclcpp::ParameterValue(-1)));
|
||||
node->set_parameter(
|
||||
rclcpp::Parameter(layer->getFullName("group_connectivity_type"), rclcpp::ParameterValue(3)));
|
||||
|
||||
DenoiseLayerTester::initialize(*layer);
|
||||
|
||||
ASSERT_EQ(
|
||||
DenoiseLayerTester::getParameters(*layer),
|
||||
std::make_tuple(true, ConnectivityType::Way8, 1));
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// Copyright (c) 2020 Shivang Patel
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "nav2_costmap_2d/footprint_collision_checker.hpp"
|
||||
#include "nav2_costmap_2d/footprint.hpp"
|
||||
|
||||
TEST(collision_footprint, test_basic)
|
||||
{
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> costmap_ =
|
||||
std::make_shared<nav2_costmap_2d::Costmap2D>(100, 100, 0.1, 0, 0, 0);
|
||||
|
||||
geometry_msgs::msg::Point p1;
|
||||
p1.x = -0.5;
|
||||
p1.y = 0.0;
|
||||
geometry_msgs::msg::Point p2;
|
||||
p2.x = 0.0;
|
||||
p2.y = 0.5;
|
||||
geometry_msgs::msg::Point p3;
|
||||
p3.x = 0.5;
|
||||
p3.y = 0.0;
|
||||
geometry_msgs::msg::Point p4;
|
||||
p4.x = 0.0;
|
||||
p4.y = -0.5;
|
||||
|
||||
nav2_costmap_2d::Footprint footprint = {p1, p2, p3, p4};
|
||||
|
||||
nav2_costmap_2d::FootprintCollisionChecker<std::shared_ptr<nav2_costmap_2d::Costmap2D>>
|
||||
collision_checker(costmap_);
|
||||
|
||||
auto value = collision_checker.footprintCostAtPose(5.0, 5.0, 0.0, footprint);
|
||||
|
||||
EXPECT_NEAR(value, 0.0, 0.001);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, test_point_cost)
|
||||
{
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> costmap_ =
|
||||
std::make_shared<nav2_costmap_2d::Costmap2D>(100, 100, 0.1, 0, 0, 0);
|
||||
|
||||
nav2_costmap_2d::FootprintCollisionChecker<std::shared_ptr<nav2_costmap_2d::Costmap2D>>
|
||||
collision_checker(costmap_);
|
||||
|
||||
auto value = collision_checker.pointCost(50, 50);
|
||||
|
||||
EXPECT_NEAR(value, 0.0, 0.001);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, test_world_to_map)
|
||||
{
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> costmap_ =
|
||||
std::make_shared<nav2_costmap_2d::Costmap2D>(100, 100, 0.1, 0, 0, 0);
|
||||
|
||||
nav2_costmap_2d::FootprintCollisionChecker<std::shared_ptr<nav2_costmap_2d::Costmap2D>>
|
||||
collision_checker(costmap_);
|
||||
|
||||
unsigned int x, y;
|
||||
|
||||
collision_checker.worldToMap(1.0, 1.0, x, y);
|
||||
|
||||
auto value = collision_checker.pointCost(x, y);
|
||||
|
||||
EXPECT_NEAR(value, 0.0, 0.001);
|
||||
|
||||
costmap_->setCost(50, 50, 200);
|
||||
collision_checker.worldToMap(5.0, 5.0, x, y);
|
||||
|
||||
EXPECT_NEAR(collision_checker.pointCost(x, y), 200.0, 0.001);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, test_footprint_at_pose_with_movement)
|
||||
{
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> costmap_ =
|
||||
std::make_shared<nav2_costmap_2d::Costmap2D>(100, 100, 0.1, 0, 0, 254);
|
||||
|
||||
for (unsigned int i = 40; i <= 60; ++i) {
|
||||
for (unsigned int j = 40; j <= 60; ++j) {
|
||||
costmap_->setCost(i, j, 0);
|
||||
}
|
||||
}
|
||||
|
||||
geometry_msgs::msg::Point p1;
|
||||
p1.x = -1.0;
|
||||
p1.y = 1.0;
|
||||
geometry_msgs::msg::Point p2;
|
||||
p2.x = 1.0;
|
||||
p2.y = 1.0;
|
||||
geometry_msgs::msg::Point p3;
|
||||
p3.x = 1.0;
|
||||
p3.y = -1.0;
|
||||
geometry_msgs::msg::Point p4;
|
||||
p4.x = -1.0;
|
||||
p4.y = -1.0;
|
||||
|
||||
nav2_costmap_2d::Footprint footprint = {p1, p2, p3, p4};
|
||||
|
||||
nav2_costmap_2d::FootprintCollisionChecker<std::shared_ptr<nav2_costmap_2d::Costmap2D>>
|
||||
collision_checker(costmap_);
|
||||
|
||||
auto value = collision_checker.footprintCostAtPose(5.0, 5.0, 0.0, footprint);
|
||||
EXPECT_NEAR(value, 0.0, 0.001);
|
||||
|
||||
auto up_value = collision_checker.footprintCostAtPose(5.0, 4.9, 0.0, footprint);
|
||||
EXPECT_NEAR(up_value, 254.0, 0.001);
|
||||
|
||||
auto down_value = collision_checker.footprintCostAtPose(5.0, 5.2, 0.0, footprint);
|
||||
EXPECT_NEAR(down_value, 254.0, 0.001);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, test_point_and_line_cost)
|
||||
{
|
||||
std::shared_ptr<nav2_costmap_2d::Costmap2D> costmap_ =
|
||||
std::make_shared<nav2_costmap_2d::Costmap2D>(100, 100, 0.10000, 0, 0.0, 0.0);
|
||||
|
||||
costmap_->setCost(62, 50, 254);
|
||||
costmap_->setCost(39, 60, 254);
|
||||
|
||||
geometry_msgs::msg::Point p1;
|
||||
p1.x = -1.0;
|
||||
p1.y = 1.0;
|
||||
geometry_msgs::msg::Point p2;
|
||||
p2.x = 1.0;
|
||||
p2.y = 1.0;
|
||||
geometry_msgs::msg::Point p3;
|
||||
p3.x = 1.0;
|
||||
p3.y = -1.0;
|
||||
geometry_msgs::msg::Point p4;
|
||||
p4.x = -1.0;
|
||||
p4.y = -1.0;
|
||||
|
||||
nav2_costmap_2d::Footprint footprint = {p1, p2, p3, p4};
|
||||
|
||||
nav2_costmap_2d::FootprintCollisionChecker<std::shared_ptr<nav2_costmap_2d::Costmap2D>>
|
||||
collision_checker(costmap_);
|
||||
|
||||
auto value = collision_checker.footprintCostAtPose(5.0, 5.0, 0.0, footprint);
|
||||
EXPECT_NEAR(value, 0.0, 0.001);
|
||||
|
||||
auto left_value = collision_checker.footprintCostAtPose(4.9, 5.0, 0.0, footprint);
|
||||
EXPECT_NEAR(left_value, 254.0, 0.001);
|
||||
|
||||
auto right_value = collision_checker.footprintCostAtPose(5.2, 5.0, 0.0, footprint);
|
||||
EXPECT_NEAR(right_value, 254.0, 0.001);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, not_enough_points)
|
||||
{
|
||||
geometry_msgs::msg::Point p1;
|
||||
p1.x = 2.0;
|
||||
p1.y = 2.0;
|
||||
|
||||
geometry_msgs::msg::Point p2;
|
||||
p2.x = -2.0;
|
||||
p2.y = -2.0;
|
||||
|
||||
std::vector<geometry_msgs::msg::Point> footprint = {p1, p2};
|
||||
double min_dist = 0.0;
|
||||
double max_dist = 0.0;
|
||||
|
||||
nav2_costmap_2d::calculateMinAndMaxDistances(footprint, min_dist, max_dist);
|
||||
EXPECT_EQ(min_dist, std::numeric_limits<double>::max());
|
||||
EXPECT_EQ(max_dist, 0.0f);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, to_point_32) {
|
||||
geometry_msgs::msg::Point p;
|
||||
p.x = 123.0;
|
||||
p.y = 456.0;
|
||||
p.z = 789.0;
|
||||
|
||||
geometry_msgs::msg::Point32 p32;
|
||||
p32 = nav2_costmap_2d::toPoint32(p);
|
||||
EXPECT_NEAR(p.x, p32.x, 1e-5);
|
||||
EXPECT_NEAR(p.y, p32.y, 1e-5);
|
||||
EXPECT_NEAR(p.z, p32.z, 1e-5);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, to_polygon) {
|
||||
geometry_msgs::msg::Point p1;
|
||||
p1.x = 1.2;
|
||||
p1.y = 3.4;
|
||||
p1.z = 5.1;
|
||||
|
||||
geometry_msgs::msg::Point p2;
|
||||
p2.x = -5.6;
|
||||
p2.y = -7.8;
|
||||
p2.z = -9.1;
|
||||
std::vector<geometry_msgs::msg::Point> pts = {p1, p2};
|
||||
|
||||
geometry_msgs::msg::Polygon poly;
|
||||
poly = nav2_costmap_2d::toPolygon(pts);
|
||||
|
||||
EXPECT_EQ(2u, sizeof(poly.points) / sizeof(poly.points[0]));
|
||||
EXPECT_NEAR(poly.points[0].x, p1.x, 1e-5);
|
||||
EXPECT_NEAR(poly.points[0].y, p1.y, 1e-5);
|
||||
EXPECT_NEAR(poly.points[0].z, p1.z, 1e-5);
|
||||
EXPECT_NEAR(poly.points[1].x, p2.x, 1e-5);
|
||||
EXPECT_NEAR(poly.points[1].y, p2.y, 1e-5);
|
||||
EXPECT_NEAR(poly.points[1].z, p2.z, 1e-5);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, make_footprint_from_string) {
|
||||
std::vector<geometry_msgs::msg::Point> footprint;
|
||||
bool result = nav2_costmap_2d::makeFootprintFromString(
|
||||
"[[1, 2.2], [.3, -4e4], [-.3, -4e4], [-1, 2.2]]", footprint);
|
||||
EXPECT_EQ(result, true);
|
||||
EXPECT_EQ(4u, footprint.size());
|
||||
EXPECT_NEAR(footprint[0].x, 1.0, 1e-5);
|
||||
EXPECT_NEAR(footprint[0].y, 2.2, 1e-5);
|
||||
EXPECT_NEAR(footprint[1].x, 0.3, 1e-5);
|
||||
EXPECT_NEAR(footprint[1].y, -4e4, 1e-5);
|
||||
EXPECT_NEAR(footprint[2].x, -0.3, 1e-5);
|
||||
EXPECT_NEAR(footprint[2].y, -4e4, 1e-5);
|
||||
EXPECT_NEAR(footprint[3].x, -1.0, 1e-5);
|
||||
EXPECT_NEAR(footprint[3].y, 2.2, 1e-5);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, make_footprint_from_string_parse_error) {
|
||||
std::vector<geometry_msgs::msg::Point> footprint;
|
||||
bool result = nav2_costmap_2d::makeFootprintFromString(
|
||||
"[[bad_string", footprint);
|
||||
EXPECT_EQ(result, false);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, make_footprint_from_string_two_points_error) {
|
||||
std::vector<geometry_msgs::msg::Point> footprint;
|
||||
bool result = nav2_costmap_2d::makeFootprintFromString(
|
||||
"[[1, 2.2], [.3, -4e4]", footprint);
|
||||
EXPECT_EQ(result, false);
|
||||
}
|
||||
|
||||
TEST(collision_footprint, make_footprint_from_string_not_pairs) {
|
||||
std::vector<geometry_msgs::msg::Point> footprint;
|
||||
bool result = nav2_costmap_2d::makeFootprintFromString(
|
||||
"[[1, 2.2], [.3, -4e4], [-.3, -4e4], [-1, 2.2, 5.6]]", footprint);
|
||||
EXPECT_EQ(result, false);
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <cmath>
|
||||
|
||||
#include "nav2_costmap_2d/denoise/image_processing.hpp"
|
||||
#include "image_tests_helper.hpp"
|
||||
|
||||
using namespace nav2_costmap_2d;
|
||||
using namespace imgproc_impl;
|
||||
|
||||
struct ImageProcTester : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
std::vector<uint8_t> image_buffer_bytes_;
|
||||
std::vector<uint8_t> image_buffer_bytes2_;
|
||||
std::vector<uint8_t> image_buffer_bytes3_;
|
||||
std::vector<uint16_t> image_buffer_words_;
|
||||
};
|
||||
|
||||
TEST(OutOfBounds, outOfBoundsAccess) {
|
||||
// check access to nullptr row (up)
|
||||
{
|
||||
out_of_bounds_policy::ReplaceToZero<uint8_t> c(nullptr, nullptr, 2);
|
||||
uint8_t * any_non_null = reinterpret_cast<uint8_t *>(&c);
|
||||
ASSERT_EQ(c.up(any_non_null), uint8_t(0));
|
||||
}
|
||||
// check out of bounds access
|
||||
{
|
||||
std::array<uint8_t, 3> data = {1, 2, 3};
|
||||
out_of_bounds_policy::ReplaceToZero<uint8_t> c(data.data(), data.data(), 2);
|
||||
auto left_out_of_bounds = std::prev(data.data());
|
||||
auto right_out_of_bounds = data.data() + data.size();
|
||||
|
||||
ASSERT_EQ(c.up(left_out_of_bounds), uint8_t(0));
|
||||
ASSERT_EQ(c.up(right_out_of_bounds), uint8_t(0));
|
||||
|
||||
ASSERT_EQ(c.down(left_out_of_bounds), uint8_t(0));
|
||||
ASSERT_EQ(c.down(right_out_of_bounds), uint8_t(0));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, calculateHistogramWithoutTruncation) {
|
||||
image_buffer_words_ = {0, 2, 1, 0, 3, 4, 1, 2, 0};
|
||||
Image<uint16_t> image = makeImage(3, 3, image_buffer_words_);
|
||||
const uint16_t max_bin_size = 3; // three zeros
|
||||
const uint16_t max_value = 4;
|
||||
const auto hist = histogram(image, max_value, max_bin_size);
|
||||
|
||||
const std::array<uint8_t, 5> expected = {3, 2, 2, 1, 1};
|
||||
ASSERT_EQ(hist.size(), expected.size());
|
||||
ASSERT_TRUE(std::equal(expected.begin(), expected.end(), hist.begin()));
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, calculateHistogramWithTruncation) {
|
||||
image_buffer_words_ = {0, 2, 1, 0, 3, 4, 1, 2, 0};
|
||||
Image<uint16_t> image = makeImage(3, 3, image_buffer_words_);
|
||||
const uint16_t max_bin_size = 2;
|
||||
const uint16_t max_value = 4;
|
||||
const auto hist = histogram(image, max_value, max_bin_size);
|
||||
|
||||
const std::array<uint8_t, 5> expected = {2, 2, 2, 1, 1};
|
||||
ASSERT_EQ(hist.size(), expected.size());
|
||||
ASSERT_TRUE(std::equal(expected.begin(), expected.end(), hist.begin()));
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, calculateHistogramOfEmpty) {
|
||||
const uint16_t max_bin_size = 1;
|
||||
const uint16_t max_value = 0;
|
||||
Image<uint16_t> empty;
|
||||
|
||||
const auto hist = histogram(empty, max_value, max_bin_size);
|
||||
ASSERT_TRUE(hist.empty());
|
||||
}
|
||||
|
||||
|
||||
TEST(EquivalenceLabelTrees, newLabelsTest) {
|
||||
EquivalenceLabelTrees<uint8_t> eq;
|
||||
eq.reset(10, 10, ConnectivityType::Way4);
|
||||
ASSERT_EQ(eq.makeLabel(), 1);
|
||||
ASSERT_EQ(eq.makeLabel(), 2);
|
||||
ASSERT_EQ(eq.makeLabel(), 3);
|
||||
}
|
||||
|
||||
TEST(EquivalenceLabelTrees, unionTest) {
|
||||
EquivalenceLabelTrees<uint8_t> eq;
|
||||
eq.reset(10, 10, ConnectivityType::Way4);
|
||||
|
||||
// create 5 single nodes
|
||||
for (size_t i = 1; i < 6; ++i) {
|
||||
eq.makeLabel();
|
||||
}
|
||||
ASSERT_EQ(eq.unionTrees(4, 3), 3);
|
||||
ASSERT_EQ(eq.unionTrees(5, 3), 3);
|
||||
ASSERT_EQ(eq.unionTrees(4, 1), 1);
|
||||
ASSERT_EQ(eq.unionTrees(2, 5), 1);
|
||||
}
|
||||
|
||||
struct ConnectedComponentsTester : public ImageProcTester
|
||||
{
|
||||
protected:
|
||||
template<ConnectivityType connectivity>
|
||||
bool fingerTest();
|
||||
|
||||
template<ConnectivityType connectivity>
|
||||
bool spiralTest();
|
||||
|
||||
inline static bool isBackground(uint8_t pixel)
|
||||
{
|
||||
return pixel == BACKGROUND_CODE;
|
||||
}
|
||||
|
||||
inline Image<uint8_t> makeChessboardLikeImage(
|
||||
size_t rows, size_t cols,
|
||||
std::vector<uint8_t> & buffer) const;
|
||||
|
||||
protected:
|
||||
MemoryBuffer buffer_;
|
||||
imgproc_impl::EquivalenceLabelTrees<uint8_t> label_trees_;
|
||||
static const uint8_t BACKGROUND_CODE = 0;
|
||||
static const uint8_t FOREGROUND_CODE = 255;
|
||||
};
|
||||
|
||||
Image<uint8_t> ConnectedComponentsTester::makeChessboardLikeImage(
|
||||
size_t rows, size_t cols,
|
||||
std::vector<uint8_t> & buffer) const
|
||||
{
|
||||
Image<uint8_t> image = makeImage<uint8_t>(rows, cols, buffer, cols * 3);
|
||||
|
||||
auto inverse = [](uint8_t v) {
|
||||
return (v == BACKGROUND_CODE) ? FOREGROUND_CODE : BACKGROUND_CODE;
|
||||
};
|
||||
|
||||
uint8_t current_value = FOREGROUND_CODE;
|
||||
for (size_t j = 0; j < cols; ++j) {
|
||||
*(image.row(0) + j) = current_value;
|
||||
current_value = inverse(current_value);
|
||||
}
|
||||
|
||||
for (size_t i = 1; i < rows; ++i) {
|
||||
auto up = image.row(i - 1);
|
||||
auto current = image.row(i);
|
||||
for (size_t j = 0; j < cols; ++j, ++up, ++current) {
|
||||
*current = inverse(*up);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4EmptyTest) {
|
||||
Image<uint8_t> empty;
|
||||
uint8_t total_labels;
|
||||
connectedComponents<ConnectivityType::Way4>(
|
||||
empty, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
ASSERT_EQ(total_labels, uint8_t(0));
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4SinglePixelTest) {
|
||||
Image<uint8_t> input = makeImage(1, 1, image_buffer_bytes_);
|
||||
uint8_t total_labels;
|
||||
{
|
||||
input.row(0)[0] = BACKGROUND_CODE;
|
||||
|
||||
const auto result = connectedComponents<ConnectivityType::Way4>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(result.row(0)[0], 0);
|
||||
ASSERT_EQ(total_labels, 1);
|
||||
}
|
||||
{
|
||||
input.row(0)[0] = FOREGROUND_CODE;
|
||||
|
||||
const auto result = connectedComponents<ConnectivityType::Way4>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(result.row(0)[0], 1);
|
||||
ASSERT_EQ(total_labels, 2);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4ImageSmallTest) {
|
||||
{
|
||||
Image<uint8_t> input = makeImage(1, 2, image_buffer_bytes_);
|
||||
uint8_t total_labels;
|
||||
input.row(0)[0] = BACKGROUND_CODE;
|
||||
input.row(0)[1] = FOREGROUND_CODE;
|
||||
|
||||
const auto result = connectedComponents<ConnectivityType::Way4>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(total_labels, uint8_t(2));
|
||||
ASSERT_EQ(result.row(0)[0], 0);
|
||||
ASSERT_EQ(result.row(0)[1], 1);
|
||||
}
|
||||
{
|
||||
Image<uint8_t> input = makeImage(2, 1, image_buffer_bytes_);
|
||||
uint8_t total_labels;
|
||||
input.row(0)[0] = BACKGROUND_CODE;
|
||||
input.row(1)[0] = FOREGROUND_CODE;
|
||||
|
||||
const auto result = connectedComponents<ConnectivityType::Way4>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(total_labels, uint8_t(2));
|
||||
ASSERT_EQ(result.row(0)[0], 0);
|
||||
ASSERT_EQ(result.row(1)[0], 1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4LabelsOverflowTest) {
|
||||
// big chessboard image
|
||||
Image<uint8_t> input = makeChessboardLikeImage(32, 17, image_buffer_bytes_);
|
||||
uint8_t total_labels;
|
||||
|
||||
ASSERT_THROW(
|
||||
(connectedComponents<ConnectivityType::Way4>(input, buffer_, label_trees_,
|
||||
isBackground, total_labels)),
|
||||
LabelOverflow);
|
||||
}
|
||||
|
||||
template<class T>
|
||||
struct UniformLabel
|
||||
{
|
||||
const Image<T> & labels;
|
||||
std::map<T, T> labels_map = {{0, 0}};
|
||||
size_t next_label = 1;
|
||||
T at(size_t i, size_t j)
|
||||
{
|
||||
const T label = labels.row(i)[j];
|
||||
|
||||
if (labels_map.find(label) == labels_map.end()) {
|
||||
labels_map[label] = next_label++;
|
||||
}
|
||||
return labels_map[label];
|
||||
}
|
||||
};
|
||||
|
||||
template<class T>
|
||||
bool isEqualLabels(const Image<T> & lhs, const Image<T> & rhs)
|
||||
{
|
||||
UniformLabel<T> l = {lhs};
|
||||
UniformLabel<T> r = {rhs};
|
||||
|
||||
for (size_t i = 0; i < lhs.rows(); ++i) {
|
||||
for (size_t j = 0; j < lhs.rows(); ++j) {
|
||||
if (l.at(i, j) != r.at(i, j)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4ImageStepsTest) {
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"..xx"
|
||||
".xx."
|
||||
"xx.."
|
||||
"....", image_buffer_bytes_);
|
||||
const Image<uint8_t> expected_labels = imageFromString<uint8_t>(
|
||||
"..xx"
|
||||
".xx."
|
||||
"xx.."
|
||||
"....", image_buffer_bytes2_);
|
||||
uint8_t total_labels;
|
||||
const auto result = connectedComponents<ConnectivityType::Way4>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(total_labels, uint8_t(2));
|
||||
ASSERT_TRUE(isEqualLabels(result, expected_labels));
|
||||
}
|
||||
|
||||
/// @brief create mapping '.'->0, 'a'->1, 'b'->2, ... max_symbol->n
|
||||
std::map<char, uint8_t> makeLabelsMap(char max_symbol)
|
||||
{
|
||||
std::map<char, uint8_t> labels_map = {{'.', 0}};
|
||||
|
||||
for (char s = 'a'; s <= max_symbol; ++s) {
|
||||
labels_map.emplace(s, uint8_t(s - 'a' + 1));
|
||||
}
|
||||
return labels_map;
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way8ImageStepsTest) {
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"....xx"
|
||||
"..xx.."
|
||||
"xx...."
|
||||
"...xx."
|
||||
".....x"
|
||||
"....x.", image_buffer_bytes_);
|
||||
const Image<uint8_t> expected_labels = imageFromString<uint8_t>(
|
||||
"....aa"
|
||||
"..aa.."
|
||||
"aa...."
|
||||
"...bb."
|
||||
".....b"
|
||||
"....b.", image_buffer_bytes2_, makeLabelsMap('b'));
|
||||
uint8_t total_labels;
|
||||
|
||||
const auto result = connectedComponents<ConnectivityType::Way8>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(total_labels, uint8_t(3));
|
||||
ASSERT_TRUE(isEqualLabels(result, expected_labels));
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4ImageSieveTest) {
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"x.x.x"
|
||||
".x.x."
|
||||
"x.x.x"
|
||||
".x.x."
|
||||
"x.x.x", image_buffer_bytes_);
|
||||
const Image<uint8_t> expected_labels = imageFromString<uint8_t>(
|
||||
"a.b.c"
|
||||
".d.e."
|
||||
"f.g.h"
|
||||
".i.j."
|
||||
"k.l.m", image_buffer_bytes2_, makeLabelsMap('m'));
|
||||
uint8_t total_labels;
|
||||
|
||||
const auto result = connectedComponents<ConnectivityType::Way4>(
|
||||
input, buffer_, label_trees_,
|
||||
isBackground, total_labels);
|
||||
|
||||
ASSERT_EQ(total_labels, uint8_t(14));
|
||||
ASSERT_TRUE(isEqualLabels(result, expected_labels));
|
||||
}
|
||||
|
||||
template<ConnectivityType connectivity>
|
||||
bool ConnectedComponentsTester::fingerTest()
|
||||
{
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"....."
|
||||
"....x"
|
||||
"..x.x"
|
||||
"x.x.x"
|
||||
"x.x.x", image_buffer_bytes_);
|
||||
const Image<uint8_t> expected_labels = imageFromString<uint8_t>(
|
||||
"....."
|
||||
"....c"
|
||||
"..b.c"
|
||||
"a.b.c"
|
||||
"a.b.c", image_buffer_bytes2_, makeLabelsMap('c'));
|
||||
uint8_t total_labels;
|
||||
|
||||
const auto result = connectedComponents<connectivity>(input, buffer_,
|
||||
label_trees_, isBackground, total_labels);
|
||||
|
||||
return total_labels == 4 && isEqualLabels(result, expected_labels);
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4ImageFingerTest) {
|
||||
ASSERT_TRUE(fingerTest<ConnectivityType::Way4>());
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way8ImageFingerTest) {
|
||||
ASSERT_TRUE(fingerTest<ConnectivityType::Way8>());
|
||||
}
|
||||
|
||||
template<ConnectivityType connectivity>
|
||||
bool ConnectedComponentsTester::spiralTest()
|
||||
{
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
".xxxxxx"
|
||||
"......x"
|
||||
".xxxx.x"
|
||||
".x..x.x"
|
||||
".x.xx.x"
|
||||
".x....x"
|
||||
".xxxxxx", image_buffer_bytes_);
|
||||
const Image<uint8_t> expected_labels = imageFromString<uint8_t>(
|
||||
".xxxxxx"
|
||||
"......x"
|
||||
".xxxx.x"
|
||||
".x..x.x"
|
||||
".x.xx.x"
|
||||
".x....x"
|
||||
".xxxxxx", image_buffer_bytes2_);
|
||||
uint8_t total_labels;
|
||||
|
||||
const auto result = connectedComponents<connectivity>(input, buffer_,
|
||||
label_trees_, isBackground, total_labels);
|
||||
return total_labels == 2 && isEqualLabels(result, expected_labels);
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way4ImageSpiralTest) {
|
||||
ASSERT_TRUE(spiralTest<ConnectivityType::Way4>());
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, way8ImageSpiralTest) {
|
||||
ASSERT_TRUE(spiralTest<ConnectivityType::Way8>());
|
||||
}
|
||||
|
||||
TEST_F(ConnectedComponentsTester, groupsRemoverUint16LabelOverflow) {
|
||||
Image<uint8_t> image = makeChessboardLikeImage(512, 512, image_buffer_bytes_);
|
||||
GroupsRemover remover;
|
||||
MemoryBuffer buffer;
|
||||
remover.removeGroups(image, buffer, ConnectivityType::Way4, 2, isBackground);
|
||||
const auto bg = BACKGROUND_CODE;
|
||||
image.forEach([bg](uint8_t v) {ASSERT_EQ(v, bg);});
|
||||
}
|
||||
|
||||
ShapeBuffer3x3 shape_buffer{};
|
||||
const Image<uint8_t> cross_shape = createShape(shape_buffer, ConnectivityType::Way4);
|
||||
|
||||
uint8_t max_list(std::initializer_list<uint8_t> lst)
|
||||
{
|
||||
return std::max(lst);
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, emptyImage) {
|
||||
Image<uint8_t> input;
|
||||
Image<uint8_t> output;
|
||||
|
||||
ASSERT_NO_THROW(morphologyOperation(input, output, cross_shape, max_list));
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, wrongShapeSize) {
|
||||
Image<uint8_t> input = makeImage(1, 1, image_buffer_bytes_);
|
||||
Image<uint8_t> output = makeImage(1, 1, image_buffer_bytes2_);
|
||||
ASSERT_THROW(
|
||||
morphologyOperation(input, output, makeImage(2, 2, image_buffer_bytes3_), max_list),
|
||||
std::logic_error);
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, wrongSize) {
|
||||
Image<uint8_t> input = makeImage(3, 2, image_buffer_bytes_);
|
||||
|
||||
{
|
||||
Image<uint8_t> output = makeImage(2, 2, image_buffer_bytes2_);
|
||||
ASSERT_THROW(
|
||||
morphologyOperation(input, output, cross_shape, max_list),
|
||||
std::logic_error);
|
||||
}
|
||||
|
||||
{
|
||||
Image<uint8_t> output = makeImage(3, 3, image_buffer_bytes2_);
|
||||
ASSERT_THROW(
|
||||
morphologyOperation(input, output, cross_shape, max_list),
|
||||
std::logic_error);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, singlePixelImage) {
|
||||
image_buffer_bytes_ = {255};
|
||||
Image<uint8_t> input = makeImage(1, 1, image_buffer_bytes_);
|
||||
Image<uint8_t> output = makeImage(1, 1, image_buffer_bytes2_);
|
||||
|
||||
morphologyOperation(input, output, cross_shape, max_list);
|
||||
|
||||
ASSERT_EQ(output.row(0)[0], 0);
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, cornersImage) {
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"x..x"
|
||||
"...."
|
||||
"...."
|
||||
"x..x", image_buffer_bytes_);
|
||||
Image<uint8_t> expected = imageFromString<uint8_t>(
|
||||
".xx."
|
||||
"x..x"
|
||||
"x..x"
|
||||
".xx.", image_buffer_bytes2_);
|
||||
Image<uint8_t> output = makeImage(input.rows(), input.columns(), image_buffer_bytes3_);
|
||||
|
||||
morphologyOperation(input, output, cross_shape, max_list);
|
||||
|
||||
ASSERT_TRUE(isEqual(output, expected));
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, horizontalBordersImage) {
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"x..x"
|
||||
"x..x"
|
||||
"x..x"
|
||||
"x..x", image_buffer_bytes_);
|
||||
Image<uint8_t> expected = imageFromString<uint8_t>(
|
||||
"xxxx"
|
||||
"xxxx"
|
||||
"xxxx"
|
||||
"xxxx", image_buffer_bytes2_);
|
||||
Image<uint8_t> output = makeImage(input.rows(), input.columns(), image_buffer_bytes3_);
|
||||
|
||||
morphologyOperation(input, output, cross_shape, max_list);
|
||||
|
||||
ASSERT_TRUE(isEqual(output, expected));
|
||||
}
|
||||
|
||||
TEST_F(ImageProcTester, verticalBordersImage) {
|
||||
const Image<uint8_t> input = imageFromString<uint8_t>(
|
||||
"xxxx"
|
||||
"...."
|
||||
"...."
|
||||
"xxxx", image_buffer_bytes_);
|
||||
Image<uint8_t> expected = imageFromString<uint8_t>(
|
||||
"xxxx"
|
||||
"xxxx"
|
||||
"xxxx"
|
||||
"xxxx", image_buffer_bytes2_);
|
||||
Image<uint8_t> output = makeImage(input.rows(), input.columns(), image_buffer_bytes3_);
|
||||
|
||||
morphologyOperation(input, output, cross_shape, max_list);
|
||||
|
||||
ASSERT_TRUE(isEqual(output, expected));
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "nav2_costmap_2d/denoise/image.hpp"
|
||||
#include "image_tests_helper.hpp"
|
||||
|
||||
using namespace nav2_costmap_2d;
|
||||
|
||||
struct ImageTester : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
std::vector<uint8_t> image_buffer_bytes;
|
||||
std::vector<uint16_t> image_buffer_words;
|
||||
};
|
||||
|
||||
TEST_F(ImageTester, emptyProps) {
|
||||
Image<uint8_t> empty;
|
||||
ASSERT_EQ(empty.rows(), 0ul);
|
||||
ASSERT_EQ(empty.columns(), 0ul);
|
||||
ASSERT_EQ(empty.step(), 0ul);
|
||||
}
|
||||
|
||||
TEST_F(ImageTester, memoryAccess) {
|
||||
std::array<uint8_t, 7> buffer{};
|
||||
for (uint8_t i = 0; i < buffer.size(); ++i) {
|
||||
buffer[i] = i;
|
||||
}
|
||||
// buffer[3] is unused
|
||||
Image<uint8_t> wrapper(2, 3, buffer.data(), 4);
|
||||
|
||||
ASSERT_EQ(wrapper.row(0), buffer.data());
|
||||
ASSERT_EQ(wrapper.row(1), buffer.data() + 4);
|
||||
}
|
||||
|
||||
TEST_F(ImageTester, forEach) {
|
||||
Image<uint8_t> image = makeImage(3, 2, image_buffer_bytes);
|
||||
const uint8_t non_zero_initial_value = 42;
|
||||
uint8_t current(non_zero_initial_value);
|
||||
|
||||
image.forEach(
|
||||
[&](uint8_t & pixel) {
|
||||
pixel = current++;
|
||||
});
|
||||
|
||||
for (size_t i = 0; i < image.rows(); ++i) {
|
||||
for (size_t j = 0; j < image.columns(); ++j) {
|
||||
ASSERT_EQ(image.row(i)[j], non_zero_initial_value + i * image.columns() + j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ImageTester, convert) {
|
||||
image_buffer_words = {1, 2, 3, 4, 5, 6};
|
||||
Image<uint16_t> source = makeImage(2, 3, image_buffer_words);
|
||||
Image<uint8_t> target = makeImage(2, 3, image_buffer_bytes);
|
||||
|
||||
source.convert(
|
||||
target, [](uint16_t s, uint8_t & t) {
|
||||
t = s * 2;
|
||||
});
|
||||
|
||||
const std::array<uint8_t, 6> expected = {2, 4, 6, 8, 10, 12};
|
||||
ASSERT_TRUE(std::equal(expected.begin(), expected.end(), image_buffer_bytes.begin()));
|
||||
}
|
||||
|
||||
TEST_F(ImageTester, convertDifferentSizes) {
|
||||
Image<uint16_t> source = makeImage(2, 3, image_buffer_words);
|
||||
Image<uint8_t> target = makeImage(3, 2, image_buffer_bytes);
|
||||
auto do_nothing = [](uint16_t /*src*/, uint8_t & /*trg*/) {};
|
||||
|
||||
// Extra parentheses need to protect commas in template arguments
|
||||
ASSERT_THROW((source.convert(target, do_nothing)), std::logic_error);
|
||||
}
|
||||
|
||||
TEST_F(ImageTester, convertEmptyImages) {
|
||||
const Image<uint16_t> source;
|
||||
Image<uint8_t> target;
|
||||
auto shouldn_t_be_called = [](uint16_t /*src*/, uint8_t & /*trg*/) {
|
||||
throw std::logic_error("");
|
||||
};
|
||||
|
||||
ASSERT_NO_THROW((source.convert(target, shouldn_t_be_called)));
|
||||
}
|
||||
|
||||
TEST_F(ImageTester, convertWrongSize) {
|
||||
Image<uint16_t> source = makeImage(2, 3, image_buffer_words);
|
||||
|
||||
auto do_nothing = [](uint16_t /*src*/, uint8_t & /*trg*/) {};
|
||||
{
|
||||
Image<uint8_t> target = makeImage(3, 3, image_buffer_bytes);
|
||||
ASSERT_THROW((source.convert(target, do_nothing)), std::logic_error);
|
||||
}
|
||||
{
|
||||
Image<uint8_t> target = makeImage(2, 2, image_buffer_bytes);
|
||||
ASSERT_THROW((source.convert(target, do_nothing)), std::logic_error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Copyright (c) 2023 Andrey Ryzhikov
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef NAV2_COSTMAP_2D__IMAGE_TESTS_HELPER_HPP_
|
||||
#define NAV2_COSTMAP_2D__IMAGE_TESTS_HELPER_HPP_
|
||||
|
||||
#include "nav2_costmap_2d/denoise/image.hpp"
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
||||
namespace nav2_costmap_2d
|
||||
{
|
||||
template<class T>
|
||||
Image<T> makeImage(size_t rows, size_t columns, std::vector<T> & buffer, size_t step = 0)
|
||||
{
|
||||
step = std::max(step, columns);
|
||||
buffer.resize(rows * step);
|
||||
return Image<T>(rows, columns, buffer.data(), step);
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Image<T> clone(const Image<T> & source, std::vector<T> & buffer)
|
||||
{
|
||||
buffer.resize(source.rows() * source.columns());
|
||||
Image<T> result(source.rows(), source.columns(), buffer.data(), source.columns());
|
||||
|
||||
for (size_t row = 0; row < source.rows(); ++row) {
|
||||
for (size_t column = 0; column < source.columns(); ++column) {
|
||||
result.row(row)[column] = source.row(row)[column];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Decodes image from a string
|
||||
*
|
||||
* Used only for tests.
|
||||
* Each character of the string will be replaced with a code from the codes
|
||||
* and written to the corresponding pixel of the image
|
||||
* The image is always square, i.e. the number of rows is equal to the number of columns
|
||||
* For example, string
|
||||
* "x.x"
|
||||
* ".x."
|
||||
* "..."
|
||||
* describes a 3x3 image in which a v-shape is drawn with code 255 (with default codes map)
|
||||
* @throw std::logic_error if the format of the string is incorrect
|
||||
*/
|
||||
template<class T>
|
||||
Image<T> imageFromString(
|
||||
const std::string & s, std::vector<T> & buffer,
|
||||
const std::map<char, T> & codes = {{'.', 0}, {'x', 255}})
|
||||
{
|
||||
const size_t side_size = static_cast<size_t>(std::sqrt(s.size()));
|
||||
|
||||
if (size_t(side_size) * side_size != s.size()) {
|
||||
throw std::logic_error("Test data error: parseBinaryMatrix: Unexpected input string size");
|
||||
}
|
||||
|
||||
const size_t step = static_cast<size_t>(side_size * 3);
|
||||
|
||||
Image<T> image = makeImage(side_size, side_size, buffer, step);
|
||||
auto iter = s.begin();
|
||||
image.forEach(
|
||||
[&](T & pixel) {
|
||||
try {
|
||||
pixel = codes.at(*iter);
|
||||
++iter;
|
||||
} catch (...) {
|
||||
throw std::logic_error(
|
||||
"Test data error: parseBinaryMatrix: Unexpected symbol: " +
|
||||
std::string(1, *iter));
|
||||
}
|
||||
});
|
||||
return image;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Checks exact match of images
|
||||
*
|
||||
* @return true if images a and b have the same type, size, and data. Otherwise false
|
||||
*/
|
||||
inline bool isEqual(const Image<uint8_t> & a, const Image<uint8_t> & b)
|
||||
{
|
||||
bool equal = a.rows() == b.rows() && a.columns() == b.columns();
|
||||
|
||||
for (size_t row = 0; row < a.rows() && equal; ++row) {
|
||||
for (size_t column = 0; column < a.columns() && equal; ++column) {
|
||||
equal = a.row(row)[column] == b.row(row)[column];
|
||||
}
|
||||
}
|
||||
return equal;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
std::ostream & operator<<(std::ostream & out, const Image<T> & image)
|
||||
{
|
||||
for (size_t i = 0; i < image.rows(); ++i) {
|
||||
for (size_t j = 0; j < image.columns(); ++j) {
|
||||
out << int64_t(image.row(i)[j]) << " ";
|
||||
}
|
||||
out << std::endl;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace nav2_costmap_2d
|
||||
|
||||
#endif // NAV2_COSTMAP_2D__IMAGE_TESTS_HELPER_HPP_
|
||||
Loaded 100 of 1280 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user