Compare commits
24 Commits
a8fc8cb9a4
...
refactor/d
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b93a45b45 | |||
| e40e9c0104 | |||
| 3b89add5ee | |||
| 64974d48b7 | |||
| a63c084002 | |||
| 45c8227f5c | |||
| faa57d9c93 | |||
| a2a021c114 | |||
| 2fcd211ccf | |||
| 3d621de809 | |||
| 1f9e9f1398 | |||
| 9208c8bcdc | |||
| 6c6e5b44f8 | |||
| eb52edc6e8 | |||
| ed43912c33 | |||
| 9026c03e1e | |||
| 81e7874274 | |||
| 9d3d31a4f9 | |||
| b18aeb39ab | |||
| b66bd7c751 | |||
| 384897b750 | |||
| f052dac142 | |||
| 80bde38f4d | |||
| 03c151afd2 |
448
CMakeLists.txt
448
CMakeLists.txt
@@ -1,61 +1,43 @@
|
||||
# --- CMake version và project name ---
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(robot_costmap_2d)
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(robot_costmap_2d VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
# --- C++ standard và position independent code ---
|
||||
set(CMAKE_CXX_STANDARD 17) # Sử dụng C++17
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON) # Thư viện có thể build thành shared lib
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building robot_costmap_2d with Catkin")
|
||||
|
||||
# --- RPATH settings: ưu tiên thư viện build tại chỗ ---
|
||||
# Dùng để runtime linker tìm thư viện đã build trước khi install
|
||||
set(CMAKE_SKIP_BUILD_RPATH FALSE)
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}/robot_costmap_2d")
|
||||
set(CMAKE_INSTALL_RPATH "${CMAKE_BINARY_DIR}/robot_costmap_2d")
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building robot_costmap_2d with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# --- Dependencies ---
|
||||
# Tìm các thư viện cần thiết
|
||||
# find_package(tf3 REQUIRED) # Nếu dùng tf3
|
||||
find_package(Eigen3 REQUIRED) # Thư viện Eigen cho toán học
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem) # Boost: system, thread, filesystem
|
||||
find_package(GTest REQUIRED) # Google Test cho unit test
|
||||
find_package(PCL REQUIRED COMPONENTS common io) # Point Cloud Library
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# --- Define macro để dùng trong code ---
|
||||
add_definitions(-DROBOT_COSTMAP_2D_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
# Find dependencies
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem)
|
||||
# GTest is only needed by the test executables, which the robot deployment build
|
||||
# does not produce. QUIET, not REQUIRED: a robot without GTest installed must
|
||||
# still configure. The test block below requires it where it is actually used.
|
||||
find_package(GTest QUIET)
|
||||
find_package(yaml-cpp REQUIRED)
|
||||
# DepthCameraObstacleLayer only (voxel grid, kd-tree clearing, Euclidean clustering); the core
|
||||
# library and the other layers do not use PCL.
|
||||
find_package(PCL REQUIRED COMPONENTS common filters kdtree search segmentation)
|
||||
|
||||
# --- Include directories ---
|
||||
# Thêm các folder chứa header files
|
||||
include_directories(
|
||||
include
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${GTEST_INCLUDE_DIRS}
|
||||
${PCL_INCLUDE_DIRS}
|
||||
)
|
||||
link_directories(${PCL_LIBRARY_DIRS}) # Thêm thư viện PCL vào linker path
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# --- Eigen và PCL definitions ---
|
||||
add_definitions(${EIGEN3_DEFINITIONS} ${PCL_DEFINITIONS})
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# --- Core library: robot_costmap_2d ---
|
||||
# Tạo thư viện chính
|
||||
add_library(robot_costmap_2d
|
||||
src/costmap_2d_robot.cpp
|
||||
src/array_parser.cpp
|
||||
src/costmap_2d.cpp
|
||||
src/observation_buffer.cpp
|
||||
src/layer.cpp
|
||||
src/layered_costmap.cpp
|
||||
src/costmap_math.cpp
|
||||
src/footprint.cpp
|
||||
src/costmap_layer.cpp
|
||||
)
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
# --- Link các thư viện phụ thuộc ---
|
||||
target_link_libraries(robot_costmap_2d
|
||||
${Boost_LIBRARIES} # Boost
|
||||
set(PACKAGES_DIR
|
||||
robot_std_msgs
|
||||
robot_sensor_msgs
|
||||
geometry_msgs
|
||||
@@ -68,127 +50,295 @@ target_link_libraries(robot_costmap_2d
|
||||
robot_tf3_geometry_msgs
|
||||
robot_tf3_sensor_msgs
|
||||
data_convert
|
||||
robot_xmlrpcpp # XMLRPC
|
||||
yaml-cpp
|
||||
dl
|
||||
robot_xmlrpcpp
|
||||
robot_cpp
|
||||
robot_time
|
||||
)
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
robot_std_msgs
|
||||
robot_sensor_msgs
|
||||
geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_map_msgs
|
||||
robot_laser_geometry
|
||||
robot_visualization_msgs
|
||||
robot_voxel_grid
|
||||
robot_tf3_geometry_msgs
|
||||
robot_tf3_sensor_msgs
|
||||
data_convert
|
||||
robot_xmlrpcpp
|
||||
robot_cpp
|
||||
robot_time
|
||||
)
|
||||
|
||||
find_library(TF3_LIBRARY NAMES tf3)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES robot_costmap_2d plugins
|
||||
CATKIN_DEPENDS robot_std_msgs robot_sensor_msgs geometry_msgs robot_nav_msgs robot_map_msgs robot_laser_geometry robot_visualization_msgs robot_voxel_grid robot_tf3_geometry_msgs robot_tf3_sensor_msgs data_convert robot_xmlrpcpp robot_cpp robot_time
|
||||
DEPENDS Boost
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${GTEST_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
endif()
|
||||
|
||||
# Define macro để dùng trong code
|
||||
add_definitions(-DROBOT_COSTMAP_2D_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
|
||||
# Eigen definitions
|
||||
add_definitions(${EIGEN3_DEFINITIONS})
|
||||
|
||||
# ========================================================
|
||||
# Core library: robot_costmap_2d
|
||||
# ========================================================
|
||||
add_library(robot_costmap_2d SHARED
|
||||
src/costmap_2d_robot.cpp
|
||||
src/array_parser.cpp
|
||||
src/costmap_2d.cpp
|
||||
src/observation_buffer.cpp
|
||||
src/layer.cpp
|
||||
src/layered_costmap.cpp
|
||||
src/costmap_math.cpp
|
||||
src/footprint.cpp
|
||||
src/costmap_layer.cpp
|
||||
)
|
||||
|
||||
# --- Include directories cho target ---
|
||||
target_include_directories(robot_costmap_2d
|
||||
PUBLIC
|
||||
${Boost_INCLUDE_DIRS} # Boost headers
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> # Khi build từ source
|
||||
$<INSTALL_INTERFACE:include/${PROJECT_NAME}> # Khi install
|
||||
)
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(robot_costmap_2d ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
# --- Cài đặt thư viện vào hệ thống khi chạy make install ---
|
||||
install(TARGETS robot_costmap_2d
|
||||
EXPORT robot_costmap_2d-targets
|
||||
ARCHIVE DESTINATION lib # Thư viện tĩnh .a
|
||||
LIBRARY DESTINATION lib # Thư viện động .so
|
||||
RUNTIME DESTINATION bin # File thực thi (nếu có)
|
||||
INCLUDES DESTINATION include # Cài đặt include
|
||||
)
|
||||
target_include_directories(robot_costmap_2d
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
# --- Xuất export set robot_costmap_2dTargets thành file CMake module ---
|
||||
# --- Tạo file lib/cmake/robot_costmap_2d/robot_costmap_2dTargets.cmake ---
|
||||
# --- File này chứa cấu hình giúp project khác có thể dùng ---
|
||||
# --- Find_package(robot_costmap_2d REQUIRED) ---
|
||||
# --- Target_link_libraries(my_app PRIVATE robot_costmap_2d::robot_costmap_2d) ---
|
||||
install(EXPORT robot_costmap_2d-targets
|
||||
FILE robot_costmap_2d-targets.cmake
|
||||
NAMESPACE robot_costmap_2d::
|
||||
DESTINATION lib/cmake/robot_costmap_2d
|
||||
)
|
||||
target_link_libraries(robot_costmap_2d
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::boost Boost::system Boost::thread Boost::filesystem
|
||||
PRIVATE yaml-cpp
|
||||
PRIVATE dl
|
||||
PRIVATE ${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
# --- Cài đặt headers ---
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include/${PROJECT_NAME}
|
||||
)
|
||||
else()
|
||||
|
||||
# --- Plugin libraries ---
|
||||
# Tạo các plugin shared library
|
||||
add_library(plugins
|
||||
SHARED
|
||||
plugins/static_layer.cpp
|
||||
plugins/obstacle_layer.cpp
|
||||
plugins/inflation_layer.cpp
|
||||
plugins/voxel_layer.cpp
|
||||
plugins/critical_layer.cpp
|
||||
plugins/directional_layer.cpp
|
||||
plugins/preferred_layer.cpp
|
||||
plugins/unpreferred_layer.cpp
|
||||
)
|
||||
target_include_directories(robot_costmap_2d
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
target_link_libraries(plugins
|
||||
target_link_libraries(robot_costmap_2d
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
robot_costmap_2d
|
||||
${Boost_LIBRARIES}
|
||||
yaml-cpp
|
||||
robot_time
|
||||
robot_cpp
|
||||
)
|
||||
Boost::boost Boost::system Boost::thread Boost::filesystem
|
||||
yaml-cpp
|
||||
dl
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
set_target_properties(plugins PROPERTIES
|
||||
set_target_properties(robot_costmap_2d PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Plugin library: plugins
|
||||
# ========================================================
|
||||
add_library(plugins SHARED
|
||||
plugins/static_layer.cpp
|
||||
plugins/obstacle_layer.cpp
|
||||
plugins/inflation_layer.cpp
|
||||
plugins/voxel_layer.cpp
|
||||
plugins/critical_layer.cpp
|
||||
plugins/directional_layer.cpp
|
||||
plugins/preferred_layer.cpp
|
||||
plugins/unpreferred_layer.cpp
|
||||
plugins/depth_camera_obstacle_layer.cpp
|
||||
)
|
||||
# PCL stays private to the plugin library: no PCL type in public headers.
|
||||
target_include_directories(plugins SYSTEM PRIVATE ${PCL_INCLUDE_DIRS})
|
||||
target_compile_options(plugins PRIVATE ${PCL_DEFINITIONS})
|
||||
target_link_libraries(plugins PRIVATE ${PCL_LIBRARIES})
|
||||
|
||||
install(TARGETS plugins
|
||||
EXPORT plugins-targets
|
||||
ARCHIVE DESTINATION lib # Thư viện tĩnh .a
|
||||
LIBRARY DESTINATION lib # Thư viện động .so
|
||||
RUNTIME DESTINATION bin # File thực thi (nếu có)
|
||||
INCLUDES DESTINATION include # Cài đặt include
|
||||
)
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
install(EXPORT plugins-targets
|
||||
FILE plugins-targets.cmake
|
||||
NAMESPACE robot_costmap_2d::
|
||||
DESTINATION lib/cmake/plugins
|
||||
)
|
||||
target_include_directories(plugins
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(plugins
|
||||
PUBLIC robot_costmap_2d
|
||||
PRIVATE ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::boost Boost::system Boost::thread Boost::filesystem
|
||||
PRIVATE yaml-cpp
|
||||
PRIVATE ${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
# --- Option để bật/tắt test ---
|
||||
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables" ON)
|
||||
else()
|
||||
|
||||
target_include_directories(plugins
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(plugins
|
||||
PUBLIC robot_costmap_2d
|
||||
PRIVATE Boost::boost Boost::system Boost::thread Boost::filesystem
|
||||
PRIVATE yaml-cpp
|
||||
PRIVATE robot_time
|
||||
PRIVATE robot_cpp
|
||||
PRIVATE ${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
set_target_properties(plugins PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS robot_costmap_2d plugins
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS robot_costmap_2d plugins
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Libraries: robot_costmap_2d, plugins")
|
||||
message(STATUS "Dependencies: robot_std_msgs, robot_sensor_msgs, geometry_msgs, robot_nav_msgs, robot_map_msgs, robot_laser_geometry, robot_visualization_msgs, robot_voxel_grid, tf3, robot_tf3_geometry_msgs, robot_tf3_sensor_msgs, data_convert, robot_xmlrpcpp, robot_cpp, robot_time, Eigen3, Boost, yaml-cpp")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Test executables
|
||||
# ========================================================
|
||||
# Default follows the build mode, not a fixed value: a catkin workspace is a
|
||||
# development machine and gets the tests, while the standalone CMake build is how
|
||||
# the robot is deployed and must not need GTest installed at all. Force it on with
|
||||
# -DBUILD_COSTMAP_TESTS=ON to run the tests from a standalone build.
|
||||
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables"
|
||||
${BUILDING_WITH_CATKIN})
|
||||
|
||||
if(BUILD_COSTMAP_TESTS)
|
||||
# --- Test executables ---
|
||||
find_package(GTest REQUIRED)
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem)
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/array_parser_test.cpp)
|
||||
add_executable(test_array_parser test/array_parser_test.cpp)
|
||||
target_link_libraries(test_array_parser PRIVATE
|
||||
robot_costmap_2d
|
||||
GTest::GTest
|
||||
GTest::Main
|
||||
Boost::system Boost::thread
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
endif()
|
||||
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/coordinates_test.cpp)
|
||||
add_executable(test_costmap test/coordinates_test.cpp)
|
||||
target_link_libraries(test_costmap PRIVATE
|
||||
plugins
|
||||
robot_costmap_2d
|
||||
GTest::GTest
|
||||
GTest::Main
|
||||
Boost::system Boost::thread
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
endif()
|
||||
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/static_layer_test.cpp)
|
||||
add_executable(test_plugin test/static_layer_test.cpp)
|
||||
|
||||
# --- Link thư viện cho test ---
|
||||
target_link_libraries(test_array_parser PRIVATE robot_costmap_2d GTest::GTest GTest::Main pthread)
|
||||
target_link_libraries(test_costmap PRIVATE robot_costmap_2d GTest::GTest GTest::Main pthread)
|
||||
target_link_libraries(test_plugin PRIVATE
|
||||
robot_costmap_2d
|
||||
Boost::boost Boost::filesystem Boost::system
|
||||
yaml-cpp
|
||||
dl
|
||||
Boost::system Boost::thread
|
||||
robot_time
|
||||
GTest::GTest
|
||||
GTest::Main
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
endif()
|
||||
|
||||
${Boost_LIBRARIES}
|
||||
Boost::filesystem
|
||||
Boost::system
|
||||
dl
|
||||
pthread
|
||||
yaml-cpp
|
||||
tf3
|
||||
robot_time
|
||||
robot_costmap_2d
|
||||
GTest::GTest GTest::Main
|
||||
)
|
||||
|
||||
# --- Set RPATH để tìm thư viện của project này thay vì system ROS libraries ---
|
||||
set_target_properties(test_array_parser PROPERTIES
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}/src/Libraries/robot_costmap_2d:${CMAKE_BINARY_DIR}/src/Libraries/robot_time:${CMAKE_BINARY_DIR}/src/Libraries/tf3"
|
||||
INSTALL_RPATH "${CMAKE_BINARY_DIR}/src/Libraries/robot_costmap_2d"
|
||||
LINK_FLAGS "-Wl,--disable-new-dtags"
|
||||
)
|
||||
set_target_properties(test_costmap PROPERTIES
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}/src/Libraries/robot_costmap_2d:${CMAKE_BINARY_DIR}/src/Libraries/robot_time:${CMAKE_BINARY_DIR}/src/Libraries/tf3"
|
||||
INSTALL_RPATH "${CMAKE_BINARY_DIR}/src/Libraries/robot_costmap_2d"
|
||||
LINK_FLAGS "-Wl,--disable-new-dtags"
|
||||
)
|
||||
set_target_properties(test_plugin PROPERTIES
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}/src/Libraries/robot_costmap_2d:${CMAKE_BINARY_DIR}/src/Libraries/robot_time:${CMAKE_BINARY_DIR}/src/Libraries/tf3"
|
||||
INSTALL_RPATH "${CMAKE_BINARY_DIR}/src/Libraries/robot_costmap_2d"
|
||||
LINK_FLAGS "-Wl,--disable-new-dtags"
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/depth_camera_obstacle_layer_test.cpp)
|
||||
add_executable(depth_camera_obstacle_layer_test test/depth_camera_obstacle_layer_test.cpp)
|
||||
target_link_libraries(depth_camera_obstacle_layer_test PRIVATE
|
||||
plugins
|
||||
robot_costmap_2d
|
||||
GTest::GTest
|
||||
GTest::Main
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
653
README.md
Normal file
653
README.md
Normal file
@@ -0,0 +1,653 @@
|
||||
# robot_costmap_2d
|
||||
|
||||
`robot_costmap_2d` là thư viện costmap dạng nhiều lớp của T800. Package duy trì
|
||||
lưới chi phí 2D dùng cho global/local planner, nhận bản đồ tĩnh và dữ liệu cảm
|
||||
biến, xóa vùng trống, đánh dấu vật cản, sau đó tạo vùng chi phí an toàn quanh
|
||||
vật cản.
|
||||
|
||||
Package hỗ trợ C++17, catkin và standalone CMake. Các plugin được nạp bằng
|
||||
`boost::dll` từ thư viện `libplugins`.
|
||||
|
||||
## 1. Luồng dữ liệu và kiến trúc
|
||||
|
||||
Luồng cập nhật chính:
|
||||
|
||||
```text
|
||||
OccupancyGrid -------------------------> StaticLayer ---------+
|
||||
LaserScan / PointCloud / PointCloud2 --> ObstacleLayer -------+--> master costmap
|
||||
LaserScan / PointCloud2 ---------------> VoxelLayer ----------+
|
||||
PointCloud2 từ depth camera -----------> DepthCameraObstacleLayer
|
||||
master costmap ------------------------> InflationLayer -------+
|
||||
```
|
||||
|
||||
Mỗi chu kỳ, `LayeredCostmap` gọi lần lượt:
|
||||
|
||||
1. `updateBounds()` để từng layer mở rộng vùng cần cập nhật.
|
||||
2. Reset vùng tương ứng trên master costmap.
|
||||
3. `updateCosts()` theo đúng thứ tự trong danh sách `plugins`.
|
||||
|
||||
Vì vậy thứ tự plugin có ảnh hưởng trực tiếp tới kết quả. Trong cấu hình chạy
|
||||
thực tế, nên đặt layer bản đồ trước, layer vật cản sau và `InflationLayer` cuối
|
||||
cùng để cả vật cản tĩnh lẫn vật cản động đều được inflation.
|
||||
|
||||
Các plugin được build trong package:
|
||||
|
||||
| Plugin | Vai trò |
|
||||
| --- | --- |
|
||||
| `StaticLayer` | Đưa `OccupancyGrid` tĩnh vào costmap. |
|
||||
| `ObstacleLayer` | Marking/clearing 2D từ `LaserScan`, `PointCloud`, `PointCloud2`. |
|
||||
| `VoxelLayer` | Lưu vật cản theo voxel 3D, chiếu kết quả xuống costmap 2D, xóa bằng raytrace (laser/point cloud). |
|
||||
| `DepthCameraObstacleLayer` | Vật cản từ depth camera: lưu điểm 3D, xóa trong khối nhìn của camera bằng kd-tree, đánh dấu theo cụm Euclidean. Xem mục 5.6. |
|
||||
| `InflationLayer` | Tạo vùng chi phí giảm dần quanh ô vật cản. |
|
||||
| `CriticalLayer` | Gộp vùng critical do hệ thống T800 cung cấp. |
|
||||
| `DirectionalLayer` | Gộp thông tin vùng có hướng di chuyển. |
|
||||
| `PreferredLayer` | Gộp vùng ưu tiên. |
|
||||
| `UnPreferredLayer` | Gộp vùng không ưu tiên. |
|
||||
|
||||
## 2. Cách package nạp cấu hình
|
||||
|
||||
Tham số có ba tầng ưu tiên, tầng sau ghi đè tầng trước:
|
||||
|
||||
1. Giá trị fallback trong code khi một key không tồn tại trong YAML.
|
||||
2. Các file YAML tên cố định nằm dưới thư mục `config/`.
|
||||
3. Tham số trong `robot::NodeHandle`, thường được launch nạp cho
|
||||
`global_costmap` hoặc `local_costmap`.
|
||||
|
||||
Biến môi trường `PNKX_NAV_CORE_CONFIG_DIR` phải trỏ tới thư mục cha có thư mục
|
||||
con `config/`. Hàm nạp sẽ tìm đệ quy các file sau:
|
||||
|
||||
- `costmap_params.yaml`
|
||||
- `static_layer_params.yaml`
|
||||
- `obstacle_layer_params.yaml`
|
||||
- `voxel_layer_params.yaml`
|
||||
- `inflation_layer_params.yaml`
|
||||
|
||||
Ví dụ dùng các file mặc định nằm ngay trong package:
|
||||
|
||||
```bash
|
||||
export PNKX_NAV_CORE_CONFIG_DIR=/home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Libraries/costmap_2d
|
||||
```
|
||||
|
||||
Ở hệ thống chạy thật, cấu hình launch-facing nằm trong
|
||||
`Controllers/Packages/amr_startup/config/`; launch nạp
|
||||
`costmap_common_params.yaml` riêng vào namespace `global_costmap` và
|
||||
`local_costmap`, sau đó nạp file global/local tương ứng.
|
||||
|
||||
> Không đặt nhiều file trùng tên trong các nhánh con của cùng một thư mục
|
||||
> `config/`. Hàm tìm kiếm dừng ở file đầu tiên tìm thấy, nên nguồn cấu hình sẽ
|
||||
> khó xác định.
|
||||
|
||||
## 3. Cấu hình mặc định của package
|
||||
|
||||
Các file trong `config/` là fallback và cũng được test của package sử dụng.
|
||||
Chúng mô tả giá trị mặc định, không phải cấu hình hoàn chỉnh để chạy robot.
|
||||
|
||||
### 3.1. Costmap chính
|
||||
|
||||
File `config/costmap_params.yaml`:
|
||||
|
||||
```yaml
|
||||
robot_costmap_2d:
|
||||
global_frame: map
|
||||
robot_base_frame: base_link
|
||||
rolling_window: false
|
||||
track_unknown_space: false
|
||||
|
||||
plugins:
|
||||
- name: static_layer
|
||||
type: StaticLayer
|
||||
- name: inflation_layer
|
||||
type: InflationLayer
|
||||
- name: obstacle_layer
|
||||
type: ObstacleLayer
|
||||
- name: voxel_layer
|
||||
type: VoxelLayer
|
||||
|
||||
library_path: ./libplugins.so
|
||||
|
||||
footprint:
|
||||
- [0.3, 0.3]
|
||||
- [0.3, -0.3]
|
||||
- [-0.3, -0.3]
|
||||
- [-0.3, 0.3]
|
||||
|
||||
transform_tolerance: 0.0
|
||||
performance_metrics_enabled: false
|
||||
performance_metrics_period: 5.0
|
||||
update_frequency: 1.0
|
||||
width: 0.0
|
||||
height: 0.0
|
||||
resolution: 0.0
|
||||
origin_x: 0.0
|
||||
origin_y: 0.0
|
||||
footprint_padding: 0.0
|
||||
robot_radius: 0.0
|
||||
```
|
||||
|
||||
Các giá trị `width`, `height` và `resolution` bằng `0.0` chỉ là placeholder.
|
||||
Khi không có `StaticLayer` resize costmap từ bản đồ, bắt buộc ghi đè cả ba giá
|
||||
trị bằng số dương trước khi chạy.
|
||||
|
||||
Danh sách plugin fallback ở trên phản ánh file hiện tại. Cấu hình deployment
|
||||
nên khai báo lại plugin và đặt `InflationLayer` cuối danh sách.
|
||||
|
||||
### 3.2. Static layer
|
||||
|
||||
File `config/static_layer_params.yaml`:
|
||||
|
||||
```yaml
|
||||
static_layer:
|
||||
enabled: true
|
||||
map_topic: map
|
||||
first_map_only: false
|
||||
subscribe_to_updates: false
|
||||
track_unknown_space: true
|
||||
use_maximum: false
|
||||
lethal_cost_threshold: 100
|
||||
unknown_cost_value: -1
|
||||
trinary_costmap: true
|
||||
base_frame_id: map
|
||||
```
|
||||
|
||||
### 3.3. Obstacle layer
|
||||
|
||||
File `config/obstacle_layer_params.yaml` hiện chứa các giá trị cơ sở:
|
||||
|
||||
```yaml
|
||||
obstacle_layer:
|
||||
track_unknown_space: true
|
||||
transform_tolerance: 0.2
|
||||
topic: map
|
||||
sensor_frame: laser_frame
|
||||
observation_persistence: 0.0
|
||||
expected_update_rate: 0.0
|
||||
data_type: PointCloud
|
||||
min_obstacle_height: 0.0
|
||||
max_obstacle_height: 2.0
|
||||
inf_is_valid: false
|
||||
clearing: false
|
||||
marking: true
|
||||
obstacle_range: 2.5
|
||||
raytrace_range: 3.0
|
||||
footprint_clearing_enabled: true
|
||||
combination_method: 1
|
||||
```
|
||||
|
||||
`ObstacleLayer` chỉ tạo buffer khi có `observation_sources`. Các tham số
|
||||
`topic`, `data_type`, `marking`, `clearing`, range và height phải được đặt dưới
|
||||
từng source. Do file fallback trên chưa khai báo `observation_sources`, nó không
|
||||
tự đăng ký nguồn cảm biến nào.
|
||||
|
||||
### 3.4. Voxel layer
|
||||
|
||||
File `config/voxel_layer_params.yaml`:
|
||||
|
||||
```yaml
|
||||
voxel_layer:
|
||||
enabled: true
|
||||
footprint_clearing_enabled: true
|
||||
max_obstacle_height: 3.0
|
||||
origin_z: 0.0
|
||||
z_resolution: 0.2
|
||||
z_voxels: 16
|
||||
unknown_threshold: 15.0
|
||||
mark_threshold: 0
|
||||
combination_method: 1
|
||||
```
|
||||
|
||||
Depth camera dùng plugin `DepthCameraObstacleLayer` (mục 5.6), không đi qua `VoxelLayer`.
|
||||
|
||||
### 3.5. Inflation layer
|
||||
|
||||
File `config/inflation_layer_params.yaml`:
|
||||
|
||||
```yaml
|
||||
inflation_layer:
|
||||
enabled: true
|
||||
inflate_unknown: false
|
||||
cost_scaling_factor: 15.0
|
||||
inflation_radius: 0.55
|
||||
```
|
||||
|
||||
## 4. Cấu hình tham khảo cho T800
|
||||
|
||||
Ví dụ sau dùng laser cho `VoxelLayer` (marking + raytrace clearing) và point cloud đã
|
||||
xử lý của depth camera cho `DepthCameraObstacleLayer`.
|
||||
|
||||
### 4.1. Tham số dùng chung cho global và local costmap
|
||||
|
||||
```yaml
|
||||
robot_base_frame: base_link
|
||||
transform_tolerance: 1.0
|
||||
footprint_padding: 0.0
|
||||
|
||||
# Polygon phải đo theo robot thật, đơn vị mét, trong robot_base_frame.
|
||||
footprint:
|
||||
- [0.583, -0.48]
|
||||
- [0.583, 0.48]
|
||||
- [-0.583, 0.48]
|
||||
- [-0.583, -0.48]
|
||||
|
||||
lidar_obstacles:
|
||||
observation_sources: f_scan
|
||||
|
||||
f_scan:
|
||||
topic: /f_scan
|
||||
data_type: LaserScan
|
||||
sensor_frame: ""
|
||||
marking: true
|
||||
clearing: true
|
||||
inf_is_valid: true
|
||||
observation_persistence: 0.0
|
||||
expected_update_rate: 0.0
|
||||
obstacle_range: 2.5
|
||||
raytrace_range: 3.0
|
||||
min_obstacle_height: 0.0
|
||||
max_obstacle_height: 0.25
|
||||
|
||||
depth_obstacles:
|
||||
observation_sources: depth_cam
|
||||
# tham số chung cho mọi camera của layer: xem mục 5.6
|
||||
check_radius: 0.1
|
||||
number_clearing_threshold: 2
|
||||
ec_seg_distance: 0.2
|
||||
ec_cluster_min_size: 1
|
||||
size_of_cluster_rejection: 0
|
||||
|
||||
depth_cam:
|
||||
topic: /camera/depth/points_proc
|
||||
sensor_frame: ""
|
||||
sensor_frame_is_optical: true
|
||||
observation_persistence: 0.0
|
||||
expected_update_rate: 0.8
|
||||
FOV_W: 1.23
|
||||
FOV_V: 0.76
|
||||
min_detect_distance: 0.15
|
||||
max_detect_distance: 2.5
|
||||
min_obstacle_height: 0.04
|
||||
max_obstacle_height: 1.0
|
||||
```
|
||||
|
||||
### 4.2. Global costmap
|
||||
|
||||
```yaml
|
||||
global_costmap:
|
||||
library_path: libplugins
|
||||
global_frame: map
|
||||
robot_base_frame: base_link
|
||||
update_frequency: 1.0
|
||||
rolling_window: false
|
||||
track_unknown_space: true
|
||||
resolution: 0.05
|
||||
|
||||
plugins:
|
||||
- {name: navigation_map, type: StaticLayer}
|
||||
- {name: obstacles, type: VoxelLayer}
|
||||
- {name: inflation, type: InflationLayer}
|
||||
|
||||
navigation_map:
|
||||
enabled: true
|
||||
map_topic: /map
|
||||
track_unknown_space: true
|
||||
trinary_costmap: true
|
||||
lethal_cost_threshold: 100
|
||||
|
||||
obstacles:
|
||||
enabled: true
|
||||
footprint_clearing_enabled: true
|
||||
origin_z: 0.0
|
||||
z_resolution: 0.2
|
||||
z_voxels: 16
|
||||
unknown_threshold: 15
|
||||
mark_threshold: 0
|
||||
combination_method: 1
|
||||
|
||||
inflation:
|
||||
enabled: true
|
||||
inflate_unknown: false
|
||||
inflation_radius: 0.60
|
||||
cost_scaling_factor: 10.0
|
||||
```
|
||||
|
||||
Khi dùng static map, kích thước, resolution và origin có thể được lấy từ
|
||||
`OccupancyGrid`. Nếu tắt static map, phải khai báo `width`, `height`,
|
||||
`resolution`, `origin_x` và `origin_y` hợp lệ.
|
||||
|
||||
### 4.3. Local costmap
|
||||
|
||||
```yaml
|
||||
local_costmap:
|
||||
library_path: libplugins
|
||||
global_frame: odom
|
||||
robot_base_frame: base_link
|
||||
update_frequency: 6.0
|
||||
rolling_window: true
|
||||
track_unknown_space: false
|
||||
width: 8.0
|
||||
height: 8.0
|
||||
resolution: 0.05
|
||||
origin_x: 0.0
|
||||
origin_y: 0.0
|
||||
|
||||
plugins:
|
||||
- {name: lidar_obstacles, type: VoxelLayer}
|
||||
- {name: depth_obstacles, type: DepthCameraObstacleLayer}
|
||||
- {name: inflation, type: InflationLayer}
|
||||
|
||||
lidar_obstacles:
|
||||
enabled: true
|
||||
footprint_clearing_enabled: true
|
||||
origin_z: 0.0
|
||||
z_resolution: 0.15
|
||||
z_voxels: 8
|
||||
unknown_threshold: 7
|
||||
mark_threshold: 0
|
||||
combination_method: 1
|
||||
|
||||
inflation:
|
||||
enabled: true
|
||||
inflate_unknown: false
|
||||
inflation_radius: 0.55
|
||||
cost_scaling_factor: 10.0
|
||||
```
|
||||
|
||||
Với rolling window, code tự cập nhật origin theo pose robot; `origin_x` và
|
||||
`origin_y` ban đầu không phải tâm cửa sổ cố định quanh robot.
|
||||
|
||||
## 5. Ý nghĩa và cách chỉnh từng nhóm tham số
|
||||
|
||||
### 5.1. Hình học và kích thước costmap
|
||||
|
||||
| Tham số | Đơn vị | Mặc định package | Ý nghĩa và cách chỉnh |
|
||||
| --- | ---: | ---: | --- |
|
||||
| `global_frame` | frame | `map` | Global costmap thường dùng `map`; local costmap thường dùng `odom`. |
|
||||
| `robot_base_frame` | frame | `base_link` | Phải có TF ổn định từ frame này tới `global_frame`. |
|
||||
| `rolling_window` | bool | `false` | Bật cho local costmap để cửa sổ đi theo robot. |
|
||||
| `track_unknown_space` | bool | `false` | Bật khi planner cần phân biệt vùng chưa biết với vùng trống. |
|
||||
| `width`, `height` | m | `0.0` | Kích thước cửa sổ. Tăng để nhìn xa hơn nhưng tăng CPU/RAM theo diện tích. |
|
||||
| `resolution` | m/cell | `0.0` | Giảm để chi tiết hơn nhưng số cell tăng theo nghịch đảo bình phương. Giá trị chạy T800 thường là `0.05`. |
|
||||
| `origin_x`, `origin_y` | m | `0.0` | Góc dưới trái của costmap không rolling. Với static map thường lấy từ map. |
|
||||
| `update_frequency` | Hz | `1.0` | Tốc độ tính costmap. Local cần nhanh hơn global nhưng không nên cao hơn khả năng cấp dữ liệu/CPU. |
|
||||
| `transform_tolerance` | s | `0.0` | Dung sai TF. Chỉ tăng vừa đủ cho jitter; không dùng để che lỗi timestamp hoặc TF bị mất. |
|
||||
| `footprint_padding` | m | `0.0` | Biên an toàn cộng đều quanh footprint. |
|
||||
| `robot_radius` | m | `0.0` | Dùng cho robot tròn. Với T800 dạng chữ nhật nên khai báo polygon `footprint`. |
|
||||
|
||||
Số cell 2D xấp xỉ:
|
||||
|
||||
```text
|
||||
(width / resolution) * (height / resolution)
|
||||
```
|
||||
|
||||
Ví dụ cửa sổ `8 m x 8 m`, resolution `0.05 m` có `160 x 160 = 25,600`
|
||||
cell. Nếu dùng `16` lớp voxel thì phần voxel có khoảng `409,600` ô.
|
||||
|
||||
### 5.2. Footprint
|
||||
|
||||
`footprint` là polygon theo mét trong `robot_base_frame`. Đây là tham số an toàn,
|
||||
phải đo theo kích thước ngoài cùng thực tế của robot và tải hàng, không đo theo
|
||||
khung chassis bên trong.
|
||||
|
||||
Quy trình chỉnh:
|
||||
|
||||
1. Đo khoảng cách từ tâm `robot_base_frame` tới mép trước, sau, trái, phải.
|
||||
2. Khai báo các đỉnh theo thứ tự quanh polygon, không tự cắt nhau.
|
||||
3. Kiểm tra pose quay tại chỗ gần tường và góc kệ.
|
||||
4. Chỉ dùng `footprint_padding` cho sai số nhỏ; không dùng padding để bù một
|
||||
footprint sai lớn.
|
||||
|
||||
### 5.3. StaticLayer
|
||||
|
||||
| Tham số | Mặc định | Ý nghĩa và cách chỉnh |
|
||||
| --- | ---: | --- |
|
||||
| `enabled` | `true` | Bật/tắt layer. |
|
||||
| `map_topic` | `map` | Topic `OccupancyGrid`. |
|
||||
| `first_map_only` | `false` | `true` nếu map không thay đổi và muốn bỏ các map gửi lại. |
|
||||
| `subscribe_to_updates` | `false` | Bật nếu map server gửi `OccupancyGridUpdate`. |
|
||||
| `track_unknown_space` | `true` | Giữ ô `unknown_cost_value` là `NO_INFORMATION`; tắt để coi unknown là free. |
|
||||
| `use_maximum` | `false` | `false`: overwrite master; `true`: lấy max để không làm mất cost đã có. |
|
||||
| `lethal_cost_threshold` | `100` | Occupancy value từ ngưỡng này trở lên được coi là lethal; code clamp trong `[0, 100]`. |
|
||||
| `unknown_cost_value` | `-1` | Giá trị unknown trong map đầu vào. |
|
||||
| `trinary_costmap` | `true` | Chỉ phân loại free/lethal/unknown; tắt để scale dải occupancy thành cost. |
|
||||
| `base_frame_id` | `map` | Frame dùng bởi layer map trong implementation T800. |
|
||||
|
||||
### 5.4. Observation source của ObstacleLayer/VoxelLayer
|
||||
|
||||
`observation_sources` là chuỗi các tên source cách nhau bằng khoảng trắng, ví
|
||||
dụ `f_scan b_scan`. Mỗi tên phải có một map tham số cùng tên.
|
||||
|
||||
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
|
||||
| --- | ---: | --- |
|
||||
| `topic` | `map` | Topic input. Đây cũng là key dispatch callback, phải khớp tuyệt đối. |
|
||||
| `data_type` | `PointCloud` | Một trong `LaserScan`, `PointCloud`, `PointCloud2`; giá trị khác báo lỗi lúc khởi động. |
|
||||
| `sensor_frame` | rỗng | Để rỗng để dùng `header.frame_id`; chỉ đặt khi cần ép origin của sensor. |
|
||||
| `marking` | `true` | Đánh dấu điểm quan sát thành vật cản. |
|
||||
| `clearing` | `false` | Raytrace PointCloud/LaserScan để xóa vùng trống. |
|
||||
| `inf_is_valid` | `false` | Với `LaserScan`, coi `+Inf` là tia không gặp vật cản để clearing. Không áp dụng cho point cloud. |
|
||||
| `observation_persistence` | `0.0 s` | `0`: chỉ giữ mẫu mới nhất; tăng khi sensor thưa nhưng có thể tạo ghost obstacle. |
|
||||
| `expected_update_rate` | `0.0 s` | Khoảng thời gian cập nhật mong đợi; `0`: không kiểm tra stale. Trong code đây là duration, không phải Hz. |
|
||||
| `min_obstacle_height` | `0.0 m` | Bỏ điểm thấp hơn ngưỡng, hữu ích để lọc sàn. |
|
||||
| `max_obstacle_height` | `2.0 m` | Bỏ điểm cao hơn ngưỡng. Phải phù hợp chiều cao robot/kệ và dải z của voxel. |
|
||||
| `obstacle_range` | `2.5 m` | Khoảng cách tối đa dùng để marking. |
|
||||
| `raytrace_range` | `3.0 m` | Khoảng cách tối đa dùng để clearing. Thường đặt lớn hơn `obstacle_range`. |
|
||||
|
||||
Lưu ý `expected_update_rate` được truyền vào `robot::Duration`. Ví dụ `0.5`
|
||||
nghĩa là kỳ vọng có dữ liệu ít nhất mỗi `0.5 s`, tương đương tối thiểu `2 Hz`.
|
||||
|
||||
### 5.5. VoxelLayer
|
||||
|
||||
| Tham số | Mặc định YAML | Ý nghĩa và cách chỉnh |
|
||||
| --- | ---: | --- |
|
||||
| `enabled` | `true` | Bật/tắt layer. |
|
||||
| `origin_z` | `0.0 m` | Đáy của voxel grid trong hệ tọa độ costmap. |
|
||||
| `z_resolution` | `0.2 m` | Chiều cao mỗi voxel. Giảm để phân giải z tốt hơn nhưng dễ nhiễu và tốn xử lý hơn. |
|
||||
| `z_voxels` | `16` | Số lớp z; implementation dùng tối đa 16 bit cho mỗi cột, nên giữ trong `1..16`. |
|
||||
| `max_obstacle_height` | `3.0 m` | Trần điểm hợp lệ của layer. |
|
||||
| `unknown_threshold` | `15` | Số voxel unknown cần để cột 2D còn unknown; cần chỉnh cùng `z_voxels`. |
|
||||
| `mark_threshold` | `0` | Số voxel marked cần để cột 2D thành vật cản. Tăng nếu một điểm nhiễu đơn lẻ thường tạo vật cản giả. |
|
||||
| `combination_method` | `1` | `0`: overwrite master, `1`: lấy maximum. Thường dùng `1` để không xóa cost layer trước. |
|
||||
| `footprint_clearing_enabled` | `true` | Xóa vật cản nằm trong footprint hiện tại của robot. |
|
||||
|
||||
Dải z của voxel xấp xỉ:
|
||||
|
||||
```text
|
||||
[origin_z, origin_z + z_resolution * z_voxels)
|
||||
```
|
||||
|
||||
Dải này phải bao phủ vùng `min_obstacle_height..max_obstacle_height` mà robot
|
||||
cần quan sát. Không tăng `max_obstacle_height` vượt khỏi voxel grid mà không
|
||||
đồng thời kiểm tra `origin_z`, `z_resolution` và `z_voxels`.
|
||||
|
||||
### 5.6. DepthCameraObstacleLayer
|
||||
|
||||
Port thuật toán của `costmap_depth_camera` (noetic). Layer có loại riêng `LayerType::DEPTH_CAMERA_LAYER`:
|
||||
`SensorGateway` của `move_base2` chỉ đẩy `PointCloud2` vào nó (không đẩy `LaserScan`, `PointCloud`, `DepthCameraData`).
|
||||
Layer nhận `PointCloud2` đã lọc của từng depth camera và giữ các điểm vật cản 3D trong frame global của costmap. Lưới riêng của layer
|
||||
phản chiếu các điểm đó theo từng ô (cột có điểm là `LETHAL`, cột mất điểm cuối cùng thành
|
||||
`FREE_SPACE`), rồi được gộp lên master như `ObstacleLayer` (`combination_method`). Mỗi chu kỳ:
|
||||
|
||||
1. Cloud mới nhất của từng source được biến đổi sang frame global bằng TF **tại đúng
|
||||
stamp của cloud** (chờ tối đa `transform_tolerance`, quá hạn thì bỏ cloud và log lỗi),
|
||||
lọc theo `min/max_obstacle_height`, rồi gộp voxel 5 cm.
|
||||
2. **Xóa:** điểm đã lưu nằm trong khối nhìn (frustum) của bất kỳ camera nào bị xóa nếu cloud
|
||||
hiện tại có ít hơn `number_clearing_threshold` điểm trong bán kính `check_radius`,
|
||||
hoặc nếu điểm cách tâm robot dưới `forced_clearing_distance`. Cloud có
|
||||
`<= number_points_considered_as_blocked` điểm thì xóa hết trong khối nhìn, trừ khi
|
||||
bật `enable_near_blocked_protection`.
|
||||
3. **Đánh dấu:** gom cụm Euclidean (`ec_seg_distance`); cụm có `<= size_of_cluster_rejection`
|
||||
điểm bị bỏ; điểm của cụm còn lại nằm trong khối nhìn và cách mọi mặt khối nhìn hơn
|
||||
12 cm thì được lưu.
|
||||
4. Điểm ra ngoài cửa sổ costmap (rolling window) bị bỏ; điểm dưới footprint robot bị xóa khi
|
||||
bật `footprint_clearing_enabled`.
|
||||
|
||||
Mọi ô đổi trạng thái (đánh dấu hoặc xóa) đều được đưa vào vùng cập nhật, nên ô vừa xóa biến
|
||||
khỏi master ngay trong chu kỳ đó. `reset()` (dùng bởi `Costmap2DROBOT::resetLayers()`) xóa toàn
|
||||
bộ điểm đã lưu; `clearArea()` (dùng bởi `ClearCostmapRecovery`) xóa điểm theo đúng ngữ nghĩa
|
||||
của `CostmapLayer::clearArea()`: `invert_area: false` xóa các ô **ngoài** hình chữ nhật và giữ
|
||||
các ô bên trong, `true` xóa các ô **bên trong**.
|
||||
|
||||
Tham số chung của layer:
|
||||
|
||||
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
|
||||
| --- | ---: | --- |
|
||||
| `enabled` | `true` | Bật/tắt layer. |
|
||||
| `observation_sources` | rỗng | Danh sách tên source, mỗi camera một source. |
|
||||
| `check_radius` | `0.1 m` | Bán kính tìm điểm cloud quanh điểm đã lưu khi xét xóa. |
|
||||
| `number_clearing_threshold` | `2` | Ít hơn số điểm này trong `check_radius` thì xóa. Giảm xuống `1`: giữ vật nhỏ tốt hơn, ma xóa chậm hơn một chút. |
|
||||
| `ec_seg_distance` | `0.2 m` | Khoảng cách gom cụm. |
|
||||
| `ec_cluster_min_size` | `5` | Cụm nhỏ nhất PCL trả về. Vật nhỏ (vài voxel) cần `1`. |
|
||||
| `size_of_cluster_rejection` | `5` | Bỏ cụm có số điểm không vượt quá giá trị này. Vật nhỏ cần `0`. |
|
||||
| `forced_clearing_distance` | `0.1 m` | Điểm trong khối nhìn gần tâm robot hơn mức này luôn bị xóa. |
|
||||
| `enable_near_blocked_protection` | `true` | `false`: cloud gần như trống thì xóa hết trong khối nhìn. |
|
||||
| `number_points_considered_as_blocked` | `5` | Ngưỡng "cloud gần như trống". |
|
||||
| `voxel_resolution` | `0.01 m` | Bước lượng tử độ cao của điểm lưu. |
|
||||
| `use_voxelized_observation` | `true` | Gộp voxel 5 cm trước khi xử lý. |
|
||||
| `transform_tolerance` | `0.2 s` | Thời gian chờ TF tại stamp của cloud. |
|
||||
| `footprint_clearing_enabled` | `true` | Xóa ô và điểm đã lưu nằm dưới footprint robot. |
|
||||
| `combination_method` | `1` | Như các layer khác. |
|
||||
| `use_global_frame_to_mark` | `true` | Chỉ hỗ trợ `true`; `false` báo lỗi. |
|
||||
| `debug/stats` | `true` | Log `[debug/stats]` định kỳ: số điểm, số điểm đánh dấu/xóa, TF chờ/bỏ, thời gian. |
|
||||
| `debug/stats_period` | `5.0 s` | Chu kỳ log trên. |
|
||||
|
||||
Tham số của từng source (camera):
|
||||
|
||||
| Tham số | Mặc định code | Ý nghĩa |
|
||||
| --- | ---: | --- |
|
||||
| `topic` | tên source | Topic `PointCloud2`, phải khớp tên topic mà gateway đẩy vào. |
|
||||
| `sensor_frame` | rỗng | Rỗng: dùng frame của cloud để dựng khối nhìn. |
|
||||
| `sensor_frame_is_optical` | `false` | `true` khi frame là frame quang học (Z hướng nhìn). |
|
||||
| `FOV_W`, `FOV_V` | `1.5`, `1.0 rad` | Góc nhìn ngang/dọc của khối nhìn. Tính từ `camera_info`. |
|
||||
| `min_detect_distance`, `max_detect_distance` | `0.15`, `2.5 m` | Mặt gần/xa của khối nhìn. Ngoài khoảng này không đánh dấu, không xóa. |
|
||||
| `min_obstacle_height`, `max_obstacle_height` | `0.0`, `2.0 m` | Lọc độ cao trong frame global. |
|
||||
| `marking` | `true` | `false`: bỏ qua source. |
|
||||
| `observation_persistence` | `0.0 s` | `0`: chỉ dùng cloud mới nhất. |
|
||||
| `expected_update_rate` | `0.0 s` | Quá lâu không có cloud thì costmap báo không current. `0`: tắt. |
|
||||
|
||||
Giới hạn đã biết:
|
||||
|
||||
- Điểm chỉ được xét xóa khi nằm **trong khối nhìn**. Điểm ra ngoài khối nhìn (robot quay đi,
|
||||
vật đi ra ngoài FOV, hoặc điểm cao vượt mép trên ảnh khi robot tới gần) được giữ cho tới
|
||||
khi ra khỏi cửa sổ costmap. Đặt `max_obstacle_height` sát chiều cao robot để giảm loại thứ
|
||||
hai.
|
||||
- Khối nhìn đối xứng và trùng mép ảnh; dải mép ảnh không có depth (lọc mép, dải stereo
|
||||
bên trái) vẫn được coi là "nhìn thấy trống".
|
||||
- Layer không dùng ảnh depth (`DepthCameraData`): host phải đổi ảnh sang `PointCloud2` trước khi đẩy vào.
|
||||
|
||||
### 5.7. InflationLayer
|
||||
|
||||
| Tham số | Mặc định | Ý nghĩa và cách chỉnh |
|
||||
| --- | ---: | --- |
|
||||
| `enabled` | `true` | Bật/tắt inflation. |
|
||||
| `inflation_radius` | `0.55 m` | Bán kính tối đa có cost quanh vật cản. Tăng để robot tránh xa hơn. |
|
||||
| `cost_scaling_factor` | `15.0` | Hệ số suy giảm mũ. **Tăng** giá trị làm cost giảm nhanh hơn và vùng cost mạnh hẹp hơn; **giảm** giá trị làm robot giữ khoảng cách mềm xa hơn. |
|
||||
| `inflate_unknown` | `false` | Có inflation vùng unknown hay không. Bật có thể làm planner thận trọng hơn nhưng dễ chặn đường trong map chưa hoàn chỉnh. |
|
||||
|
||||
`inflation_radius` phải được chọn sau khi footprint đúng. Bán kính này nên lớn
|
||||
hơn inscribed radius cộng biên an toàn mong muốn; tăng radius không thể sửa một
|
||||
footprint sai.
|
||||
|
||||
### 5.8. Performance metrics
|
||||
|
||||
| Tham số | Mặc định | Ý nghĩa |
|
||||
| --- | ---: | --- |
|
||||
| `performance_metrics_enabled` | `false` | Log thời gian `updateBounds` và `updateCosts` theo từng layer. |
|
||||
| `performance_metrics_period` | `5.0 s` | Chu kỳ tổng hợp và in metrics. |
|
||||
|
||||
Bật metrics trong lúc tuning CPU, sau đó có thể tắt để giảm log runtime.
|
||||
|
||||
## 6. Quy trình tuning khuyến nghị
|
||||
|
||||
Chỉ thay một nhóm tham số mỗi lần và lưu lại bag/log trước khi chỉnh.
|
||||
|
||||
1. **Kiểm tra TF và timestamp**: phải có transform liên tục từ từng sensor frame
|
||||
tới `map`/`odom`. Không tuning costmap khi TF còn lỗi.
|
||||
2. **Chốt footprint**: đo robot và tải hàng thật, kiểm tra quay tại chỗ.
|
||||
3. **Chọn resolution và kích thước cửa sổ**: bắt đầu `0.05 m`; local thường
|
||||
`6..10 m` tùy vận tốc và khoảng phanh.
|
||||
4. **Chỉ bật marking**: xác nhận vật cản xuất hiện đúng vị trí, đúng height và
|
||||
range.
|
||||
5. **Bật clearing**: laser/point cloud dùng raytrace; depth camera dùng
|
||||
`DepthCameraObstacleLayer`.
|
||||
6. **Chỉnh voxel**: đặt dải z, sau đó tăng `mark_threshold` nếu nhiễu đơn điểm.
|
||||
7. **Chỉnh inflation**: chỉnh `inflation_radius` trước, sau đó mới chỉnh
|
||||
`cost_scaling_factor` theo khoảng cách đường đi mong muốn.
|
||||
8. **Đo tải CPU**: bật performance metrics; chỉ tăng frequency hoặc giảm
|
||||
resolution khi chu kỳ cập nhật vẫn hoàn thành ổn định.
|
||||
|
||||
Các ràng buộc nên giữ:
|
||||
|
||||
```text
|
||||
resolution > 0
|
||||
width > 0 và height > 0 nếu không lấy size từ static map
|
||||
raytrace_range >= obstacle_range
|
||||
max_detect_distance > min_detect_distance >= 0 (DepthCameraObstacleLayer)
|
||||
1 <= z_voxels <= 16
|
||||
origin_z + z_resolution * z_voxels đủ bao phủ dải vật cản cần quan sát
|
||||
InflationLayer nằm sau các layer tạo vật cản
|
||||
```
|
||||
|
||||
## 7. Tuning theo triệu chứng
|
||||
|
||||
| Triệu chứng | Kiểm tra trước | Hướng chỉnh |
|
||||
| --- | --- | --- |
|
||||
| Vật cản đã đi nhưng vẫn còn trên costmap | TF, topic clearing, dữ liệu có còn cập nhật; với depth: điểm có nằm trong khối nhìn không | Bật đúng `clearing`; giảm `observation_persistence`; với depth xem giới hạn ở mục 5.6. |
|
||||
| Vật cản thật không được đánh dấu | Topic/type/frame, range và height | Kiểm tra `marking`, `min/max_obstacle_height`, `obstacle_range`; với voxel thử `mark_threshold: 0` trước. |
|
||||
| Vật cản chớp tắt | Tần số sensor, packet drop, TF | Đặt `expected_update_rate` đúng chu kỳ; tăng nhẹ `observation_persistence` nhưng phải kiểm tra ghost obstacle. |
|
||||
| Robot đi quá sát vật cản | Footprint trước, inflation sau | Tăng `inflation_radius` hoặc giảm `cost_scaling_factor`. |
|
||||
| Robot tránh quá xa/không tìm được đường | Footprint, unknown space, inflation | Giảm `inflation_radius` hoặc tăng `cost_scaling_factor`; kiểm tra `inflate_unknown`. |
|
||||
| Costmap local trễ hoặc CPU cao | Metrics theo layer | Tăng `resolution`, giảm `width/height`, giảm `update_frequency`, giảm `max_detect_distance` hoặc giảm mật độ `/camera/depth/points_proc`. |
|
||||
| Costmap báo stale/not current | Sensor thực tế có đúng chu kỳ không | Tăng giá trị `expected_update_rate` theo đơn vị giây hoặc đặt `0` để tắt kiểm tra trong lúc chẩn đoán. |
|
||||
| Vật nhỏ/thấp từ depth bị mất | Số điểm trên vật sau lọc độ cao | `ec_cluster_min_size: 1`, `size_of_cluster_rejection: 0`, cân nhắc `number_clearing_threshold: 1` và `min_obstacle_height` (đổi lại: dễ có sàn ma nếu TF camera lệch). |
|
||||
| Sensor origin nằm ngoài voxel map | `global_frame`, rolling window, TF z | Sửa TF/origin, tăng cửa sổ phù hợp; không chỉ tăng tolerance. |
|
||||
| Vật cản sàn/nhiễu thấp xuất hiện | Height filter và calibration | Tăng `min_obstacle_height` từng bước nhỏ; không tăng quá đáy vật cản robot cần tránh. |
|
||||
|
||||
## 8. Lưu ý cho depth camera
|
||||
|
||||
- Layer chỉ dùng `PointCloud2` đã lọc (ví dụ `/camera/depth/points_proc`); bridge đổi ảnh
|
||||
depth sang cloud trước khi đẩy vào nav core.
|
||||
- Mỗi camera là một source trong `observation_sources` của cùng một
|
||||
`DepthCameraObstacleLayer`, với topic, frame, FOV và dải độ cao riêng.
|
||||
- Ngưỡng độ cao làm việc trong frame global: sai số lắp camera (roll, pitch, chiều cao)
|
||||
quyết định ngưỡng thấp nhất dùng được trước khi sàn bị đánh dấu.
|
||||
- Khi mất marking, kiểm tra lần lượt cloud sau bridge, TF tại stamp của cloud (dòng
|
||||
`[debug/stats]`: `tf_wait`, `tf_drop`) và ngưỡng cụm trước khi đổi ngưỡng độ cao.
|
||||
|
||||
## 9. Build và kiểm tra
|
||||
|
||||
Build package trong workspace:
|
||||
|
||||
```bash
|
||||
cd /home/duongtd/T800_ws
|
||||
catkin_make --pkg robot_costmap_2d
|
||||
```
|
||||
|
||||
Các executable test được tạo khi `BUILD_COSTMAP_TESTS=ON`:
|
||||
|
||||
```bash
|
||||
./devel/lib/robot_costmap_2d/test_array_parser
|
||||
./devel/lib/robot_costmap_2d/test_costmap
|
||||
./devel/lib/robot_costmap_2d/test_plugin
|
||||
./devel/lib/robot_costmap_2d/depth_camera_obstacle_layer_test
|
||||
```
|
||||
|
||||
Kiểm tra tối thiểu trước khi chạy robot:
|
||||
|
||||
- YAML parse được và đúng namespace global/local.
|
||||
- `library_path` tìm thấy `libplugins`.
|
||||
- Plugin được tạo đúng tên và đúng thứ tự.
|
||||
- TF giữa sensor, `robot_base_frame` và `global_frame` sẵn sàng.
|
||||
- Sensor topic, `data_type` và `header.frame_id` khớp cấu hình.
|
||||
- Costmap update ổn định, không stale và không vượt ngân sách chu kỳ.
|
||||
- Footprint và inflation đã được kiểm tra ở tốc độ thấp trước.
|
||||
|
||||
## 10. Cấu trúc package
|
||||
|
||||
```text
|
||||
costmap_2d/
|
||||
├── config/ # Fallback YAML của package
|
||||
├── include/robot_costmap_2d/ # Public headers
|
||||
├── plugins/ # Layer implementations
|
||||
├── src/ # Costmap core và observation buffer
|
||||
├── test/ # Unit/integration tests
|
||||
├── CMakeLists.txt
|
||||
└── package.xml
|
||||
```
|
||||
@@ -25,6 +25,8 @@ robot_costmap_2d:
|
||||
- [-0.3, 0.3]
|
||||
|
||||
transform_tolerance: 0.0
|
||||
performance_metrics_enabled: false
|
||||
performance_metrics_period: 5.0
|
||||
update_frequency: 1.0
|
||||
width: 0.0
|
||||
height: 0.0
|
||||
|
||||
46
config/depth_camera_obstacle_layer_params.yaml
Normal file
46
config/depth_camera_obstacle_layer_params.yaml
Normal file
@@ -0,0 +1,46 @@
|
||||
# Giá trị mặc định của DepthCameraObstacleLayer, bằng mặc định trong code.
|
||||
# Plugin đọc file này TRƯỚC, rồi khoá cùng tên trong khối <costmap>/<plugin> của config costmap đè lên
|
||||
# (Costmap2DROBOT chép khối chung <plugin>: vào đó trước khi tạo layer).
|
||||
# Đây là bản đóng gói kèm gói robot_costmap_2d; robot chạy bản trong
|
||||
# pnkx_nav_core/config/runtime/config/depth_camera_obstacle_layer_params.yaml.
|
||||
depth_camera_obstacle_layer:
|
||||
enabled: true # [bool] false = layer không đánh dấu, không xoá gì.
|
||||
# [m] Độ phân giải chiều cao của điểm lưu. > 0. Tăng (vd 0.05): ít điểm, nhẹ CPU hơn nhiều;
|
||||
# giảm: nhiều điểm hơn, kd-tree mỗi chu kỳ nặng hơn.
|
||||
voxel_resolution: 0.01
|
||||
# [m] Bán kính tìm điểm cloud quanh điểm đã lưu. > 0. Tăng: khó xoá (vết ma bám lâu hơn);
|
||||
# giảm: vật mỏng/thưa dễ bị xoá nhầm.
|
||||
check_radius: 0.1
|
||||
# [điểm] Ít hơn số điểm cloud này trong check_radius thì điểm đã lưu bị xoá. >= 1. Tăng: xoá mạnh hơn.
|
||||
number_clearing_threshold: 2
|
||||
# [m] Khoảng cách gom cụm Euclidean khi đánh dấu. > 0.
|
||||
ec_seg_distance: 0.2
|
||||
# [điểm] Cỡ cụm nhỏ nhất khi gom cụm. >= 1.
|
||||
ec_cluster_min_size: 5
|
||||
# [điểm] Cụm có <= số điểm này không được đánh dấu (lọc nhiễu). >= 0. Tăng: bỏ vật nhỏ.
|
||||
size_of_cluster_rejection: 5
|
||||
# [m] Điểm trong FOV cách tâm robot dưới mức này luôn bị xoá. >= 0.
|
||||
forced_clearing_distance: 0.1
|
||||
# [bool] true: cloud dưới number_points_considered_as_blocked điểm thì bỏ qua xoá (coi camera bị che).
|
||||
# false: cloud ít điểm như vậy thì xoá hết điểm trong FOV ("không thấy gì").
|
||||
enable_near_blocked_protection: true
|
||||
number_points_considered_as_blocked: 5 # [điểm] >= 0.
|
||||
# [bool] VoxelGrid 5 cm trên cloud gộp trước khi xoá/đánh dấu (nhẹ CPU).
|
||||
use_voxelized_observation: true
|
||||
# [bool] Chỉ hỗ trợ true (lưu điểm theo toạ độ global). false thì nav từ chối khởi động.
|
||||
use_global_frame_to_mark: true
|
||||
# [s] Cloud chờ TF đúng stamp tối đa bao lâu rồi bỏ. >= 0. Không bao giờ dùng TF mới nhất.
|
||||
transform_tolerance: 0.2
|
||||
# [bool] true: xoá ô và điểm đã lưu nằm dưới footprint robot mỗi chu kỳ. false: chỉ dùng khi chẩn đoán.
|
||||
footprint_clearing_enabled: true
|
||||
# [-] Cách gộp lên costmap chung: 1 = lấy max (không hạ cost của layer khác), 0 = ghi đè trong vùng
|
||||
# cập nhật. Giá trị khác: layer không tác động gì lên costmap.
|
||||
combination_method: 1
|
||||
# Danh sách nguồn, cách nhau bằng dấu cách. Rỗng = layer không đánh dấu gì. Khoá của từng nguồn
|
||||
# (topic, FOV_W, FOV_V, min/max_detect_distance, min/max_obstacle_height...) KHÔNG đặt ở đây mà
|
||||
# trong khối <plugin>/<tên nguồn>/ của config costmap.
|
||||
observation_sources: ""
|
||||
# track_unknown_space cố ý KHÔNG có ở đây: không đặt thì layer theo track_unknown_space của costmap.
|
||||
debug:
|
||||
stats: true # [bool] log đếm định kỳ (điểm cloud, điểm lưu, đánh dấu/xoá, thời gian).
|
||||
stats_period: 5.0 # [s] chu kỳ in log đếm. > 0.
|
||||
@@ -1,18 +1,13 @@
|
||||
# Giá trị mặc định của ObstacleLayer (cũng là phần ObstacleLayer bên trong VoxelLayer).
|
||||
# Plugin đọc file này TRƯỚC, rồi khoá cùng tên trong khối <costmap>/<plugin> của config costmap đè lên.
|
||||
# Đây là bản đóng gói kèm gói robot_costmap_2d; robot chạy bản trong
|
||||
# pnkx_nav_core/config/runtime/config/obstacle_layer_params.yaml.
|
||||
# Khoá theo từng nguồn (topic, sensor_frame, data_type, clearing, marking, obstacle_range,
|
||||
# raytrace_range...) KHÔNG đặt ở đây: plugin chỉ đọc chúng trong khối <plugin>/<tên source>/.
|
||||
obstacle_layer:
|
||||
track_unknown_space: true
|
||||
transform_tolerance: 0.2
|
||||
topic: "map"
|
||||
sensor_frame: laser_frame
|
||||
observation_persistence: 0.0
|
||||
expected_update_rate: 0.0
|
||||
data_type: PointCloud
|
||||
min_obstacle_height: 0.0
|
||||
max_obstacle_height: 2.0
|
||||
inf_is_valid: false
|
||||
clearing: false
|
||||
marking: true
|
||||
obstacle_range: 2.5
|
||||
raytrace_range: 3.0
|
||||
footprint_clearing_enabled: true
|
||||
combination_method: 1
|
||||
|
||||
track_unknown_space: true # [bool] true = ô chưa quan sát giữ NO_INFORMATION; false = coi là free.
|
||||
transform_tolerance: 0.2 # [s] độ trễ TF tối đa khi đổi điểm sensor sang frame costmap. Nhỏ quá
|
||||
# thì điểm bị bỏ khi TF trễ; lớn quá thì điểm được đặt sai chỗ khi robot quay.
|
||||
max_obstacle_height: 2.0 # [m] điểm cao hơn mức này không được đánh dấu.
|
||||
footprint_clearing_enabled: true # [bool] xoá vật cản nằm trong footprint robot (chính thân robot).
|
||||
combination_method: 1 # [-] 0 = ghi đè lên master costmap; 1 = lấy max với master.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
static_layer:
|
||||
enabled: true
|
||||
map_topic: "map"
|
||||
first_map_only: false
|
||||
subscribe_to_updates: false
|
||||
track_unknown_space: true
|
||||
|
||||
@@ -7,5 +7,4 @@ voxel_layer:
|
||||
z_voxels: 16
|
||||
unknown_threshold: 15.0
|
||||
mark_threshold: 0
|
||||
combination_method: 3
|
||||
|
||||
combination_method: 1
|
||||
@@ -86,6 +86,18 @@ public:
|
||||
*/
|
||||
Costmap2D& operator=(const Costmap2D& map);
|
||||
|
||||
/**
|
||||
* @brief Copy metadata and grid from another costmap, reusing the existing
|
||||
* buffer when the size is unchanged (no delete/new per call).
|
||||
*
|
||||
* Built for periodic snapshotting (readers copy the master grid every
|
||||
* control cycle): operator= reallocates on every call, this only when the
|
||||
* grid size actually changed. The caller must hold the source map's mutex —
|
||||
* this method does not lock the source.
|
||||
* @param map The costmap to copy from
|
||||
*/
|
||||
void copyFrom(const Costmap2D& map);
|
||||
|
||||
/**
|
||||
* @brief Turn this costmap into a copy of a window of a costmap passed in
|
||||
* @param map The costmap to copy
|
||||
@@ -425,6 +437,7 @@ protected:
|
||||
double origin_y_;
|
||||
unsigned char* costmap_;
|
||||
unsigned char default_value_;
|
||||
std::vector<unsigned char> rolling_window_scratch_;
|
||||
|
||||
class MarkCell
|
||||
{
|
||||
|
||||
@@ -47,14 +47,13 @@
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
|
||||
#include <tf3/LinearMath/Transform.h>
|
||||
#include <robot/rate.h>
|
||||
#include <robot/robot.h>
|
||||
#include <data_convert/data_convert.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <robot_xmlrpcpp/XmlRpcValue.h>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/plugin_loader_helper.h>
|
||||
|
||||
|
||||
class RobotSuperValue : public robot_xmlrpcpp::XmlRpcValue
|
||||
{
|
||||
@@ -74,12 +73,6 @@ public:
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
void signalHandler(int)
|
||||
{
|
||||
std::signal(SIGINT, SIG_DFL);
|
||||
std::raise(SIGINT);
|
||||
}
|
||||
|
||||
/** @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. */
|
||||
@@ -164,6 +157,35 @@ public:
|
||||
return layered_costmap_->getCostmap();
|
||||
}
|
||||
|
||||
/** @brief Whether readers should work on a snapshot copy instead of the
|
||||
* live master grid (config key "snapshot_for_readers", default false).
|
||||
*
|
||||
* With snapshots on, a reader calls refreshSnapshot() once per cycle and
|
||||
* then reads getCostmapForRead() without holding the master mutex during
|
||||
* its whole computation — the mutex is only held for the memcpy inside
|
||||
* refreshSnapshot(). With snapshots off, getCostmapForRead() returns the
|
||||
* live master grid and the reader must keep the legacy long lock. */
|
||||
inline bool isSnapshotEnabled() const noexcept
|
||||
{
|
||||
return snapshot_enabled_;
|
||||
}
|
||||
|
||||
/** @brief Re-copy the master grid into the internal snapshot.
|
||||
*
|
||||
* Locks the master mutex only for the duration of the copy. Single-consumer
|
||||
* contract: refreshSnapshot() and reads of getCostmapForRead() must happen
|
||||
* on the same thread (the control loop) — the snapshot itself is not
|
||||
* additionally locked. No-op while snapshots are disabled. */
|
||||
void refreshSnapshot();
|
||||
|
||||
/** @brief Grid a reader should compute on: the snapshot when enabled,
|
||||
* otherwise the live master costmap.
|
||||
*
|
||||
* The returned pointer stays stable for the lifetime of this object —
|
||||
* the snapshot buffer is reused between refreshes, never reallocated as an
|
||||
* object. Never returns null. */
|
||||
Costmap2D* getCostmapForRead();
|
||||
|
||||
/**
|
||||
* @brief Returns the global frame of the costmap
|
||||
* @return The global frame of the costmap
|
||||
@@ -181,6 +203,17 @@ public:
|
||||
{
|
||||
return robot_base_frame_;
|
||||
}
|
||||
|
||||
/** @brief Return the TF buffer shared by the costmap and navigation plugins.
|
||||
*
|
||||
* The returned reference is non-owning and remains valid only for the
|
||||
* lifetime of this Costmap2DROBOT instance.
|
||||
*/
|
||||
inline tf3::BufferCore& getTfBuffer() noexcept
|
||||
{
|
||||
return tf_;
|
||||
}
|
||||
|
||||
LayeredCostmap* getLayeredCostmap() const
|
||||
{
|
||||
return layered_costmap_;
|
||||
@@ -205,13 +238,19 @@ public:
|
||||
return padded_footprint_;
|
||||
}
|
||||
|
||||
inline const robot_geometry_msgs::PolygonStamped& getRobotFootprintPolygonStamped() const noexcept
|
||||
{
|
||||
return 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. */
|
||||
* on the "footprint" topic.
|
||||
*/
|
||||
inline const std::vector<robot_geometry_msgs::Point>& getUnpaddedRobotFootprint() const noexcept
|
||||
{
|
||||
return unpadded_footprint_;
|
||||
@@ -256,6 +295,7 @@ protected:
|
||||
double transform_tolerance_; ///< timeout before transform errors
|
||||
|
||||
private:
|
||||
void copyParentParameters(const std::string& costmap_name, const std::string& plugin_name, const std::string& plugin_type, robot::NodeHandle& nh);
|
||||
/** @brief Set the footprint from the new_config object.
|
||||
*
|
||||
* If the values of footprint and robot_radius are the same in
|
||||
@@ -276,10 +316,16 @@ private:
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> unpadded_footprint_;
|
||||
std::vector<robot_geometry_msgs::Point> padded_footprint_;
|
||||
robot_geometry_msgs::PolygonStamped footprint_;
|
||||
float footprint_padding_;
|
||||
|
||||
// Reader-side snapshot of the master grid (see getCostmapForRead()).
|
||||
// Stable object: refreshed in place, so readers may hold the pointer.
|
||||
Costmap2D costmap_snapshot_;
|
||||
bool snapshot_enabled_ = false;
|
||||
|
||||
private:
|
||||
void getParams(const std::string& config_file_name, robot::NodeHandle& nh);
|
||||
void getParams(const std::string& config_file_name,const std::string& name, robot::NodeHandle& nh);
|
||||
};
|
||||
// class Costmap2DROBOT
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
@@ -10,6 +10,12 @@ class CriticalLayer : public StaticLayer
|
||||
public:
|
||||
CriticalLayer();
|
||||
virtual ~CriticalLayer();
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::CRITICAL_LAYER;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned char interpretValue(unsigned char value) override;
|
||||
void updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override;
|
||||
|
||||
248
include/robot_costmap_2d/depth_camera_obstacle_layer.h
Normal file
248
include/robot_costmap_2d/depth_camera_obstacle_layer.h
Normal file
@@ -0,0 +1,248 @@
|
||||
/*********************************************************************
|
||||
* Port of costmap_depth_camera::DepthCameraObstacleLayer (BSD, Apola),
|
||||
* https://github.com/tsengapola/costmap_depth_camera, noetic branch 59b7737,
|
||||
* onto robot_costmap_2d (boost::dll, robot::NodeHandle, tf3).
|
||||
*
|
||||
* The clearing and marking algorithm is the source's (kd-tree "seen again" test inside the
|
||||
* frustums, Euclidean clusters away from the frustum faces). How the result reaches the costmap
|
||||
* follows the CostmapLayer contract of ObstacleLayer/VoxelLayer instead of the source, which
|
||||
* wrote LETHAL straight into the master and left its own grid empty:
|
||||
* - the stored 3D points (pc_3d_map_global_) stay the source of truth, and this layer's own
|
||||
* grid mirrors them cell by cell: a column with points is LETHAL, a column that loses its
|
||||
* last point becomes FREE_SPACE, and every such change touches the update bounds, so a
|
||||
* cleared cell leaves the master in the same cycle (the source's B7);
|
||||
* - updateCosts() only merges the own grid (combination_method), like ObstacleLayer;
|
||||
* - reset(), clearArea() and footprint clearing also erase the stored points, so
|
||||
* Costmap2DROBOT::resetLayers() and ClearCostmapRecovery work on this layer (the source's
|
||||
* reset() kept its global-mode points, B9).
|
||||
* Host adaptations: data arrives through handleImpl() and a cloud is processed in
|
||||
* updateBounds() once TF at its stamp exists (the role of the tf2_ros::MessageFilter);
|
||||
* getType() is its own DEPTH_CAMERA_LAYER, which SensorGateway feeds PointCloud2 and
|
||||
* DepthCameraData; no ROS publishers or dynamic_reconfigure; `sensor_frame_is_optical` builds the frustum in a Z-forward
|
||||
* optical frame; markings that leave the rolling window are dropped (B6).
|
||||
*********************************************************************/
|
||||
#ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
|
||||
#define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_costmap_2d/costmap_layer.h>
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
#include <robot_costmap_2d/footprint.h>
|
||||
#include <robot_geometry_msgs/Point.h>
|
||||
#include <robot_sensor_msgs/PointCloud2.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
#include <Eigen/Core>
|
||||
#include <Eigen/Geometry>
|
||||
|
||||
#include <array>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief Truncated pyramid of one depth camera observation, in the global frame.
|
||||
*
|
||||
* Same construction as costmap_depth_camera::Observation: 8 vertices from the configured
|
||||
* FOV and detect range in the sensor frame, transformed to the global frame, then 6 inward
|
||||
* normals (inside test) and 6 plane equations (12 cm "attach" band test).
|
||||
*/
|
||||
struct DepthCameraFrustum
|
||||
{
|
||||
Eigen::Vector3f origin = Eigen::Vector3f::Zero(); ///< sensor origin, global frame [m]
|
||||
std::array<Eigen::Vector3f, 8> vertices; ///< TLNear TRNear BLNear BRNear TLFar TRFar BLFar BRFar
|
||||
std::array<Eigen::Vector3f, 6> normals; ///< near right bottom left far top
|
||||
std::array<Eigen::Vector4f, 6> planes; ///< a, b, c, d of each face
|
||||
double max_detect_distance = 2.5; ///< [m]
|
||||
|
||||
/**
|
||||
* @brief Build the frustum.
|
||||
* @param T_global_sensor pose of the sensor frame in the global frame
|
||||
* @param fov_w, fov_v full horizontal / vertical field of view [rad]
|
||||
* @param min_d, max_d near / far plane distance along the viewing axis [m]
|
||||
* @param optical true: sensor frame is Z forward, X right, Y down (REP 103 optical);
|
||||
* false: X forward, Y left, Z up (camera_link), as the source assumes
|
||||
*/
|
||||
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
|
||||
double max_d, bool optical);
|
||||
|
||||
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
|
||||
bool inside(const Eigen::Vector3f& p) const;
|
||||
|
||||
/// Within 0.12 m of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
|
||||
bool nearFace(const Eigen::Vector3f& p) const;
|
||||
};
|
||||
|
||||
/// FrustumUtils::isInsideFRUSTUMs: inside at least one frustum.
|
||||
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
|
||||
|
||||
/// FrustumUtils::isAttachFRUSTUMs: near a face of one frustum and not well inside another.
|
||||
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
|
||||
|
||||
class DepthCameraObstacleLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
DepthCameraObstacleLayer();
|
||||
~DepthCameraObstacleLayer() override;
|
||||
|
||||
void onInitialize() override;
|
||||
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y) override;
|
||||
void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override;
|
||||
void activate() override;
|
||||
void deactivate() override;
|
||||
/// Drops the stored points and the buffered observations as well as the own grid.
|
||||
void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Same contract as CostmapLayer::clearArea(), applied to the stored points too.
|
||||
*
|
||||
* Cells strictly inside (start, end) are kept and the rest is cleared when invert_area is
|
||||
* false; invert_area true clears the inside instead. Called by ClearCostmapRecovery with the
|
||||
* layer mutex held (recursive).
|
||||
*/
|
||||
void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override;
|
||||
|
||||
/// Own type: SensorGateway delivers PointCloud2 and DepthCameraData to it, not LaserScan.
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::DEPTH_CAMERA_LAYER;
|
||||
}
|
||||
|
||||
/// Resizes the own grid to the master and re-marks the stored columns right away.
|
||||
void matchSize() override;
|
||||
|
||||
/// Number of stored (column, height) points, for tests and the stats log.
|
||||
std::size_t storedPoints() const;
|
||||
|
||||
protected:
|
||||
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
|
||||
|
||||
private:
|
||||
/// One observation: cloud after TF and the height gate, plus its frustum (both global frame).
|
||||
struct Observation
|
||||
{
|
||||
robot::Time stamp;
|
||||
std::vector<Eigen::Vector3f> points;
|
||||
DepthCameraFrustum frustum;
|
||||
};
|
||||
|
||||
/// ObservationBuffer of the source, one per entry of observation_sources.
|
||||
struct Source
|
||||
{
|
||||
std::string name;
|
||||
std::string topic;
|
||||
std::string sensor_frame;
|
||||
bool sensor_frame_is_optical = false;
|
||||
double observation_keep_time = 0.0; ///< [s] 0 keeps only the newest observation
|
||||
double expected_update_rate = 0.0; ///< [s] 0 disables the staleness check
|
||||
double min_obstacle_height = 0.0; ///< [m] global-frame z gate
|
||||
double max_obstacle_height = 2.0; ///< [m]
|
||||
double fov_w = 1.5; ///< [rad]
|
||||
double fov_v = 1.0; ///< [rad]
|
||||
double min_detect_distance = 0.15; ///< [m]
|
||||
double max_detect_distance = 2.5; ///< [m]
|
||||
bool marking = true;
|
||||
|
||||
std::list<Observation> observations; ///< newest first
|
||||
robot::Time last_updated;
|
||||
|
||||
std::mutex pending_mutex; ///< guards pending: handleImpl runs on the producer thread
|
||||
std::shared_ptr<const robot_sensor_msgs::PointCloud2> pending;
|
||||
};
|
||||
|
||||
void loadParameters();
|
||||
bool processPending(Source& source);
|
||||
bool bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud);
|
||||
void purgeStale(Source& source) const;
|
||||
bool sourceIsCurrent(const Source& source) const;
|
||||
|
||||
void clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
|
||||
const std::vector<DepthCameraFrustum>& frustums, double robot_x,
|
||||
double robot_y, double* min_x, double* min_y, double* max_x,
|
||||
double* max_y);
|
||||
void processCluster(const std::vector<DepthCameraFrustum>& frustums,
|
||||
const std::vector<Eigen::Vector3f>& cluster, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y);
|
||||
void updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
|
||||
double* min_y, double* max_x, double* max_y);
|
||||
bool isValid(int mx, int my) const;
|
||||
/// Own-grid cell of a stored column; false when it is outside the window or on its edge.
|
||||
bool columnCell(const std::pair<int, int>& column, unsigned int& mx, unsigned int& my) const;
|
||||
/// Drops columns that left the window (B6), frees edge cells, re-marks cells a column lost.
|
||||
void dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, double* max_y);
|
||||
/// The column became empty: erase it, free its own-grid cell and touch the bounds.
|
||||
std::map<std::pair<int, int>, std::map<int, float>>::iterator eraseColumn(
|
||||
std::map<std::pair<int, int>, std::map<int, float>>::iterator it, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y);
|
||||
void logStats();
|
||||
|
||||
// (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points.
|
||||
void worldToIntIndex(double wx, double wy, int& mx, int& my, double resolution) const
|
||||
{
|
||||
mx = static_cast<int>(wx / resolution);
|
||||
my = static_cast<int>(wy / resolution);
|
||||
}
|
||||
void intIndexToWorld(double& wx, double& wy, int mx, int my, double resolution) const
|
||||
{
|
||||
wx = mx * resolution;
|
||||
wy = my * resolution;
|
||||
}
|
||||
|
||||
std::string global_frame_;
|
||||
bool rolling_window_ = false;
|
||||
std::vector<std::unique_ptr<Source>> sources_;
|
||||
|
||||
// Parameters, names and defaults as in the source.
|
||||
bool footprint_clearing_enabled_ = true;
|
||||
int combination_method_ = 1; ///< 0 overwrite, 1 maximum, other: nothing
|
||||
bool enable_near_blocked_protection_ = true;
|
||||
int number_points_considered_as_blocked_ = 5;
|
||||
double forced_clearing_distance_ = 0.1; ///< [m] from robot_base_frame
|
||||
double ec_seg_distance_ = 0.2; ///< [m] Euclidean cluster tolerance
|
||||
int ec_cluster_min_size_ = 5;
|
||||
int size_of_cluster_rejection_ = 5; ///< clusters with <= this many points are not marked
|
||||
double voxel_resolution_ = 0.01; ///< [m] height quantization of stored points
|
||||
double check_radius_ = 0.1; ///< [m] kd-tree radius of the "seen again" test
|
||||
int number_clearing_threshold_ = 2; ///< fewer neighbours than this clears the point
|
||||
bool use_voxelized_observation_ = true; ///< VoxelGrid 5 cm on the combined cloud
|
||||
double transform_tolerance_ = 0.2; ///< [s] how long a cloud may wait for its TF
|
||||
double marking_height_under_ground_ = 100.0;
|
||||
double marking_height_above_ground_ = -100.0;
|
||||
|
||||
// Additions of this port.
|
||||
bool debug_stats_ = true; ///< debug/stats: periodic counters log
|
||||
double debug_stats_period_ = 5.0; ///< [s]
|
||||
|
||||
/// (ix, iy) of the cell corner -> {height index -> label}, global frame (use_global_frame_to_mark).
|
||||
std::map<std::pair<int, int>, std::map<int, float>> pc_3d_map_global_;
|
||||
std::vector<robot_geometry_msgs::Point> transformed_footprint_;
|
||||
|
||||
struct Stats
|
||||
{
|
||||
std::size_t cycles = 0;
|
||||
std::size_t cloud_points = 0;
|
||||
std::size_t marked = 0;
|
||||
std::size_t cleared = 0;
|
||||
std::size_t footprint_cleared = 0; ///< columns erased under the robot footprint
|
||||
std::size_t cleared_all_frames = 0;
|
||||
std::size_t bypassed_frames = 0;
|
||||
std::size_t tf_waits = 0;
|
||||
std::size_t tf_drops = 0;
|
||||
std::size_t dropped_out_of_window = 0;
|
||||
double bounds_ms_sum = 0.0;
|
||||
double bounds_ms_max = 0.0;
|
||||
} stats_;
|
||||
robot::Time last_stats_log_;
|
||||
};
|
||||
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
#endif // ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
|
||||
@@ -14,6 +14,11 @@ namespace robot_costmap_2d
|
||||
bool laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan);
|
||||
void resetMap();
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::DIRECTIONAL_LAYER;
|
||||
}
|
||||
|
||||
private:
|
||||
void incomingMap(const robot_nav_msgs::OccupancyGrid &new_map);
|
||||
bool laneFilter(std::vector<std::array<uint16_t, 2>> new_map, const robot_nav_msgs::Path path);
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
#include <robot_geometry_msgs/Point.h>
|
||||
#include <robot_geometry_msgs/Point32.h>
|
||||
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_xmlrpcpp/XmlRpcValue.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
|
||||
@@ -42,6 +42,9 @@
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
#include <boost/thread.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
/**
|
||||
@@ -77,8 +80,7 @@ public:
|
||||
virtual ~InflationLayer()
|
||||
{
|
||||
deleteKernels();
|
||||
if (seen_)
|
||||
delete[] seen_;
|
||||
delete inflation_access_;
|
||||
}
|
||||
|
||||
virtual void onInitialize();
|
||||
@@ -96,8 +98,9 @@ public:
|
||||
/** @brief Given a distance, compute a cost.
|
||||
* @param distance The distance from an obstacle in cells
|
||||
* @return A cost value for the distance */
|
||||
virtual inline unsigned char computeCost(double distance) const
|
||||
virtual unsigned char computeCost(double distance) const override
|
||||
{
|
||||
// robot::log_warning("InflationLayer::computeCost() is deprecated. Please use costLookup() instead.");
|
||||
unsigned char cost = 0;
|
||||
if (distance == 0)
|
||||
cost = LETHAL_OBSTACLE;
|
||||
@@ -120,6 +123,11 @@ public:
|
||||
*/
|
||||
void setInflationParameters(double inflation_radius, double cost_scaling_factor);
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::INFLATION_LAYER;
|
||||
}
|
||||
|
||||
protected:
|
||||
virtual void onFootprintChanged();
|
||||
boost::recursive_mutex* inflation_access_;
|
||||
@@ -178,10 +186,13 @@ private:
|
||||
|
||||
unsigned int cell_inflation_radius_;
|
||||
unsigned int cached_cell_inflation_radius_;
|
||||
std::map<double, std::vector<CellData> > inflation_cells_;
|
||||
std::vector<std::vector<CellData>> inflation_cells_;
|
||||
std::vector<double> distance_levels_;
|
||||
std::vector<unsigned int> distance_bin_lookup_;
|
||||
unsigned int distance_lookup_size_ = 0;
|
||||
|
||||
bool* seen_;
|
||||
int seen_size_;
|
||||
std::vector<std::uint32_t> seen_;
|
||||
std::uint32_t seen_generation_ = 0;
|
||||
|
||||
unsigned char** cached_costs_;
|
||||
double** cached_distances_;
|
||||
|
||||
@@ -42,9 +42,26 @@
|
||||
#include <robot_costmap_2d/utils.h>
|
||||
#include <string>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot/robot.h>
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
enum class LayerType
|
||||
{
|
||||
UNKNOWN,
|
||||
STATIC_LAYER,
|
||||
OBSTACLE_LAYER,
|
||||
INFLATION_LAYER,
|
||||
CRITICAL_LAYER,
|
||||
DIRECTIONAL_LAYER,
|
||||
PREFERRED_LAYER,
|
||||
UNPREFERRED_LAYER,
|
||||
VOXEL_LAYER,
|
||||
/// DepthCameraObstacleLayer. Appended last so the values above keep their numbers; the host's
|
||||
/// SensorGateway feeds it PointCloud2.
|
||||
DEPTH_CAMERA_LAYER
|
||||
};
|
||||
|
||||
class LayeredCostmap;
|
||||
|
||||
class Layer
|
||||
@@ -71,6 +88,8 @@ public:
|
||||
*/
|
||||
virtual void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) {}
|
||||
|
||||
virtual unsigned char computeCost(double distance) const { throw std::runtime_error("Function computeCost is not Support."); };
|
||||
|
||||
/** @brief Stop publishers. */
|
||||
virtual void deactivate() {}
|
||||
|
||||
@@ -134,6 +153,9 @@ public:
|
||||
void dataCallBack(const T& value, const std::string& topic) {
|
||||
handle(value, topic);
|
||||
}
|
||||
|
||||
virtual LayerType getType() const { return LayerType::UNKNOWN; }
|
||||
|
||||
protected:
|
||||
|
||||
// Hàm template public, dùng để gửi dữ liệu
|
||||
|
||||
@@ -43,6 +43,8 @@
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
@@ -71,6 +73,14 @@ public:
|
||||
*/
|
||||
void updateMap(double robot_x, double robot_y, double robot_yaw);
|
||||
|
||||
void setPerformanceMetrics(bool enabled, double reporting_period_seconds);
|
||||
|
||||
/** @brief Debug verbosity for the periodic performance report.
|
||||
* 0 keeps the legacy output untouched; 1 adds lock-wait/hold, update-window
|
||||
* size and empty-cycle counters; 2 adds per-layer bounds-growth lines.
|
||||
* Only effective while performance metrics are enabled. */
|
||||
void setDebugLevel(int level);
|
||||
|
||||
inline const std::string& getGlobalFrameID() const noexcept
|
||||
{
|
||||
return global_frame_;
|
||||
@@ -155,6 +165,21 @@ public:
|
||||
double getInscribedRadius() { return inscribed_radius_; }
|
||||
|
||||
private:
|
||||
struct LayerPerformance
|
||||
{
|
||||
std::uint64_t bounds_nanoseconds = 0;
|
||||
std::uint64_t costs_nanoseconds = 0;
|
||||
std::uint64_t bounds_calls = 0;
|
||||
std::uint64_t costs_calls = 0;
|
||||
// debug_level >= 2: how much this layer grew the update rect [m^2],
|
||||
// clamped to the map extent so the inflation full-map request stays finite
|
||||
double bounds_grow_m2_sum = 0.0;
|
||||
double bounds_grow_m2_max = 0.0;
|
||||
};
|
||||
|
||||
void resetPerformanceMetrics();
|
||||
void maybeReportPerformance();
|
||||
|
||||
Costmap2D costmap_;
|
||||
std::string global_frame_;
|
||||
|
||||
@@ -170,6 +195,25 @@ private:
|
||||
bool size_locked_;
|
||||
double circumscribed_radius_, inscribed_radius_;
|
||||
std::vector<robot_geometry_msgs::Point> footprint_;
|
||||
|
||||
bool performance_metrics_enabled_ = false;
|
||||
double performance_metrics_period_seconds_ = 5.0;
|
||||
int debug_level_ = 0;
|
||||
std::chrono::steady_clock::time_point performance_window_start_;
|
||||
std::uint64_t performance_cycle_nanoseconds_ = 0;
|
||||
std::uint64_t performance_reset_nanoseconds_ = 0;
|
||||
std::uint64_t performance_cycles_ = 0;
|
||||
std::vector<std::uint64_t> performance_cycle_samples_;
|
||||
std::vector<LayerPerformance> layer_performance_;
|
||||
// debug_level >= 1: master-mutex acquisition time is the contention signal
|
||||
// (planners hold the same mutex while reading costs), hold time is our own
|
||||
// cost; empty cycles are updates that found no dirty bounds and did no work.
|
||||
std::uint64_t lock_wait_nanoseconds_ = 0;
|
||||
std::uint64_t lock_wait_max_nanoseconds_ = 0;
|
||||
std::uint64_t lock_hold_nanoseconds_ = 0;
|
||||
std::uint64_t window_cells_sum_ = 0;
|
||||
std::uint64_t window_cells_max_ = 0;
|
||||
std::uint64_t performance_empty_cycles_ = 0;
|
||||
};
|
||||
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
@@ -34,6 +34,9 @@
|
||||
|
||||
#include <robot_geometry_msgs/Point.h>
|
||||
#include <robot_sensor_msgs/PointCloud2.h>
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
@@ -50,14 +53,12 @@ public:
|
||||
* @brief Creates an empty observation
|
||||
*/
|
||||
Observation() :
|
||||
cloud_(new robot_sensor_msgs::PointCloud2()), obstacle_range_(0.0), raytrace_range_(0.0)
|
||||
cloud_handle_(boost::make_shared<robot_sensor_msgs::PointCloud2>()),
|
||||
cloud_(cloud_handle_.get()), obstacle_range_(0.0), raytrace_range_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~Observation()
|
||||
{
|
||||
delete cloud_;
|
||||
}
|
||||
virtual ~Observation() = default;
|
||||
|
||||
/**
|
||||
* @brief Creates an observation from an origin point and a point cloud
|
||||
@@ -68,7 +69,17 @@ public:
|
||||
*/
|
||||
Observation(robot_geometry_msgs::Point& origin, const robot_sensor_msgs::PointCloud2 &cloud,
|
||||
double obstacle_range, double raytrace_range) :
|
||||
origin_(origin), cloud_(new robot_sensor_msgs::PointCloud2(cloud)),
|
||||
origin_(origin), cloud_handle_(boost::make_shared<robot_sensor_msgs::PointCloud2>(cloud)),
|
||||
cloud_(cloud_handle_.get()),
|
||||
obstacle_range_(obstacle_range), raytrace_range_(raytrace_range)
|
||||
{
|
||||
}
|
||||
|
||||
Observation(robot_geometry_msgs::Point origin,
|
||||
boost::shared_ptr<robot_sensor_msgs::PointCloud2> cloud,
|
||||
double obstacle_range, double raytrace_range) :
|
||||
origin_(std::move(origin)), cloud_handle_(std::move(cloud)),
|
||||
cloud_(cloud_handle_.get()),
|
||||
obstacle_range_(obstacle_range), raytrace_range_(raytrace_range)
|
||||
{
|
||||
}
|
||||
@@ -78,22 +89,59 @@ public:
|
||||
* @param obs The observation to copy
|
||||
*/
|
||||
Observation(const Observation& obs) :
|
||||
origin_(obs.origin_), cloud_(new robot_sensor_msgs::PointCloud2(*(obs.cloud_))),
|
||||
origin_(obs.origin_), cloud_handle_(obs.cloud_handle_), cloud_(cloud_handle_.get()),
|
||||
obstacle_range_(obs.obstacle_range_), raytrace_range_(obs.raytrace_range_)
|
||||
{
|
||||
}
|
||||
|
||||
Observation(Observation&& obs) noexcept :
|
||||
origin_(std::move(obs.origin_)), cloud_handle_(std::move(obs.cloud_handle_)),
|
||||
cloud_(cloud_handle_.get()), obstacle_range_(obs.obstacle_range_),
|
||||
raytrace_range_(obs.raytrace_range_)
|
||||
{
|
||||
obs.cloud_ = nullptr;
|
||||
}
|
||||
|
||||
Observation& operator=(const Observation& obs)
|
||||
{
|
||||
if (this == &obs)
|
||||
return *this;
|
||||
|
||||
origin_ = obs.origin_;
|
||||
cloud_handle_ = obs.cloud_handle_;
|
||||
cloud_ = cloud_handle_.get();
|
||||
obstacle_range_ = obs.obstacle_range_;
|
||||
raytrace_range_ = obs.raytrace_range_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Observation& operator=(Observation&& obs) noexcept
|
||||
{
|
||||
if (this == &obs)
|
||||
return *this;
|
||||
|
||||
origin_ = std::move(obs.origin_);
|
||||
cloud_handle_ = std::move(obs.cloud_handle_);
|
||||
cloud_ = cloud_handle_.get();
|
||||
obstacle_range_ = obs.obstacle_range_;
|
||||
raytrace_range_ = obs.raytrace_range_;
|
||||
obs.cloud_ = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Creates an observation from a point cloud
|
||||
* @param cloud The point cloud of the observation
|
||||
* @param obstacle_range The range out to which an observation should be able to insert obstacles
|
||||
*/
|
||||
Observation(const robot_sensor_msgs::PointCloud2 &cloud, double obstacle_range) :
|
||||
cloud_(new robot_sensor_msgs::PointCloud2(cloud)), obstacle_range_(obstacle_range), raytrace_range_(0.0)
|
||||
cloud_handle_(boost::make_shared<robot_sensor_msgs::PointCloud2>(cloud)),
|
||||
cloud_(cloud_handle_.get()), obstacle_range_(obstacle_range), raytrace_range_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Point origin_;
|
||||
boost::shared_ptr<robot_sensor_msgs::PointCloud2> cloud_handle_;
|
||||
robot_sensor_msgs::PointCloud2* cloud_;
|
||||
double obstacle_range_, raytrace_range_;
|
||||
};
|
||||
|
||||
@@ -40,10 +40,9 @@
|
||||
#include <vector>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <robot/time.h>
|
||||
#include <robot/robot.h>
|
||||
#include <robot_costmap_2d/observation.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
#include <robot_sensor_msgs/PointCloud2.h>
|
||||
|
||||
// Thread support
|
||||
@@ -77,6 +76,7 @@ public:
|
||||
double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
|
||||
std::string sensor_frame, double tf_tolerance);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Destructor... cleans up
|
||||
*/
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_OBSTACLE_LAYER_H_
|
||||
#define ROBOT_COSTMAP_2D_OBSTACLE_LAYER_H_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_costmap_2d/costmap_layer.h>
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
#include <robot_costmap_2d/observation_buffer.h>
|
||||
@@ -45,18 +46,21 @@
|
||||
|
||||
#include <robot_nav_msgs/OccupancyGrid.h>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_laser_geometry/laser_geometry.hpp>
|
||||
#include <robot_sensor_msgs/PointCloud.h>
|
||||
#include <robot_sensor_msgs/PointCloud2.h>
|
||||
#include <robot_sensor_msgs/point_cloud_conversion.h>
|
||||
|
||||
#include <robot/console.h>
|
||||
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
struct CallBackInfo
|
||||
{
|
||||
std::string observation_source;
|
||||
std::string data_type;
|
||||
std::string topic;
|
||||
bool inf_is_valid;
|
||||
@@ -84,6 +88,11 @@ public:
|
||||
void addStaticObservation(robot_costmap_2d::Observation& obs, bool marking, bool clearing);
|
||||
void clearStaticObservations(bool marking, bool clearing);
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::OBSTACLE_LAYER;
|
||||
}
|
||||
|
||||
protected:
|
||||
void handleImpl(const void* data,
|
||||
const std::type_info&,
|
||||
|
||||
@@ -10,6 +10,12 @@ class PreferredLayer : public StaticLayer
|
||||
public:
|
||||
PreferredLayer();
|
||||
virtual ~PreferredLayer();
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::PREFERRED_LAYER;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned char interpretValue(unsigned char value);
|
||||
};
|
||||
|
||||
@@ -63,6 +63,12 @@ public:
|
||||
virtual void updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j);
|
||||
|
||||
virtual void matchSize();
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::STATIC_LAYER;
|
||||
}
|
||||
|
||||
protected:
|
||||
void handleImpl(const void* data,
|
||||
const std::type_info& type,
|
||||
|
||||
@@ -25,12 +25,12 @@ char printableCost(unsigned char cost)
|
||||
|
||||
void printMap(robot_costmap_2d::Costmap2D& costmap)
|
||||
{
|
||||
printf("map:\n");
|
||||
robot::log_info("map:\n");
|
||||
for (int i = 0; i < costmap.getSizeInCellsY(); i++){
|
||||
for (int j = 0; j < costmap.getSizeInCellsX(); j++){
|
||||
printf("%4d", int(costmap.getCost(j, i)));
|
||||
robot::log_info("%4d", int(costmap.getCost(j, i)));
|
||||
}
|
||||
printf("\n\n");
|
||||
robot::log_info("\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,11 @@ public:
|
||||
UnPreferredLayer();
|
||||
virtual ~UnPreferredLayer();
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::UNPREFERRED_LAYER;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned char interpretValue(unsigned char value);
|
||||
|
||||
|
||||
@@ -51,6 +51,9 @@
|
||||
#include <robot_costmap_2d/obstacle_layer.h>
|
||||
#include <robot_voxel_grid/voxel_grid.h>
|
||||
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
@@ -77,6 +80,10 @@ public:
|
||||
virtual void matchSize();
|
||||
virtual void reset();
|
||||
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::VOXEL_LAYER;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
@@ -88,12 +95,13 @@ private:
|
||||
virtual void raytraceFreespace(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y);
|
||||
|
||||
|
||||
bool publish_voxel_;
|
||||
robot_voxel_grid::VoxelGrid robot_voxel_grid_;
|
||||
double z_resolution_, origin_z_;
|
||||
unsigned int unknown_threshold_, mark_threshold_, size_z_;
|
||||
robot_sensor_msgs::PointCloud clearing_endpoints_;
|
||||
std::vector<unsigned char> rolling_costmap_scratch_;
|
||||
std::vector<unsigned int> rolling_voxel_scratch_;
|
||||
|
||||
inline bool worldToMap3DFloat(double wx, double wy, double wz, double& mx, double& my, double& mz)
|
||||
{
|
||||
|
||||
45
package.xml
45
package.xml
@@ -20,7 +20,50 @@
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>libconsole-bridge-dev</build_depend>
|
||||
|
||||
<build_depend>libpcl-all-dev</build_depend>
|
||||
<run_depend>libpcl-all</run_depend>
|
||||
<run_depend>libconsole-bridge-dev</run_depend>
|
||||
|
||||
<build_depend>robot_std_msgs</build_depend>
|
||||
<run_depend>robot_std_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_sensor_msgs</build_depend>
|
||||
<run_depend>robot_sensor_msgs</run_depend>
|
||||
|
||||
<build_depend>geometry_msgs</build_depend>
|
||||
<run_depend>geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_msgs</build_depend>
|
||||
<run_depend>robot_nav_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_map_msgs</build_depend>
|
||||
<run_depend>robot_map_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_laser_geometry</build_depend>
|
||||
<run_depend>robot_laser_geometry</run_depend>
|
||||
|
||||
<build_depend>robot_visualization_msgs</build_depend>
|
||||
<run_depend>robot_visualization_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_voxel_grid</build_depend>
|
||||
<run_depend>robot_voxel_grid</run_depend>
|
||||
|
||||
<build_depend>robot_tf3_geometry_msgs</build_depend>
|
||||
<run_depend>robot_tf3_geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_tf3_sensor_msgs</build_depend>
|
||||
<run_depend>robot_tf3_sensor_msgs</run_depend>
|
||||
|
||||
<build_depend>data_convert</build_depend>
|
||||
<run_depend>data_convert</run_depend>
|
||||
|
||||
<build_depend>robot_xmlrpcpp</build_depend>
|
||||
<run_depend>robot_xmlrpcpp</run_depend>
|
||||
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
|
||||
<build_depend>robot_time</build_depend>
|
||||
<run_depend>robot_time</run_depend>
|
||||
|
||||
</package>
|
||||
@@ -13,7 +13,6 @@ CriticalLayer::~CriticalLayer(){}
|
||||
|
||||
unsigned char CriticalLayer::interpretValue(unsigned char value)
|
||||
{
|
||||
// printf("TEST PLUGIN CRITICAL\n");
|
||||
// check if the static value is above the unknown or lethal thresholds
|
||||
if(value >= *this->threshold_)
|
||||
return CRITICAL_SPACE;
|
||||
@@ -23,7 +22,6 @@ unsigned char CriticalLayer::interpretValue(unsigned char value)
|
||||
|
||||
void CriticalLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
// printf("TEST PLUGIN CRITICAL\n");
|
||||
if (!map_received_)
|
||||
return;
|
||||
|
||||
|
||||
1026
plugins/depth_camera_obstacle_layer.cpp
Normal file
1026
plugins/depth_camera_obstacle_layer.cpp
Normal file
File diff suppressed because it is too large
Load Diff
@@ -36,7 +36,7 @@ namespace robot_costmap_2d
|
||||
{
|
||||
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
|
||||
|
||||
printf("Received a %d X %d map at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
robot::log_info("Received a %d X %d map at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
|
||||
// resize costmap if size, resolution or origin do not match
|
||||
Costmap2D *master = layered_costmap_->getCostmap();
|
||||
@@ -48,7 +48,7 @@ namespace robot_costmap_2d
|
||||
master->getOriginY() != new_map.info.origin.position.y))
|
||||
{
|
||||
// Update the size of the layered costmap (and all layers, including this one)
|
||||
printf("Resizing costmap to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
robot::log_info("Resizing costmap to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
layered_costmap_->resizeMap(size_x / 2, size_y / 2, new_map.info.resolution, new_map.info.origin.position.x,
|
||||
new_map.info.origin.position.y,
|
||||
true /* set size_locked to true, prevents reconfigureCb from overriding map size*/);
|
||||
@@ -59,7 +59,7 @@ namespace robot_costmap_2d
|
||||
origin_y_ != new_map.info.origin.position.y)
|
||||
{
|
||||
// only update the size of the costmap stored locally in this layer
|
||||
printf("Resizing static layer to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
robot::log_info("Resizing static layer to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
resizeMap(size_x / 2, size_y / 2, new_map.info.resolution,
|
||||
new_map.info.origin.position.x, new_map.info.origin.position.y);
|
||||
}
|
||||
@@ -99,12 +99,12 @@ namespace robot_costmap_2d
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Stop receive new map!\n");
|
||||
robot::log_info("Stop receive new map!\n");
|
||||
}
|
||||
// shutdown the map subscrber if firt_map_only_ flag is on
|
||||
if (first_map_only_)
|
||||
{
|
||||
printf("Shutting down the map subscriber. first_map_only flag is on\n");
|
||||
robot::log_info("Shutting down the map subscriber. first_map_only flag is on\n");
|
||||
map_shutdown_ = true;
|
||||
// map_sub_.shutdown();
|
||||
}
|
||||
@@ -129,7 +129,7 @@ namespace robot_costmap_2d
|
||||
unsigned int mx, my;
|
||||
if (!worldToMap(p.pose.position.x, p.pose.position.y, mx, my))
|
||||
{
|
||||
printf("ERROR: trying to set a start cell %f %f that is outside of map\n", p.pose.position.x, p.pose.position.y);
|
||||
robot::log_error("ERROR: trying to set a start cell %f %f that is outside of map\n", p.pose.position.x, p.pose.position.y);
|
||||
return false;
|
||||
}
|
||||
// Convert to yaw
|
||||
@@ -162,14 +162,6 @@ namespace robot_costmap_2d
|
||||
robot_nav_msgs::OccupancyGrid lanes;
|
||||
convertToMap(costmap_, lanes, 0.65, 0.196);
|
||||
|
||||
//////////////////////////////////
|
||||
//////////////////////////////////
|
||||
/////////THAY THẾ PUBLISH////////
|
||||
// lane_mask_pub_.publish(lanes);
|
||||
//////////////////////////////////
|
||||
//////////////////////////////////
|
||||
//////////////////////////////////
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -263,8 +255,7 @@ namespace robot_costmap_2d
|
||||
y_max_w = std::max(y_max_w, y[i].second);
|
||||
|
||||
}
|
||||
// printf("%d %d %d %d", x_min, y_min, x_max, y_max);
|
||||
// printf("%f %f %f %f", x_min_w, y_min_w, x_max_w, y_max_w);
|
||||
|
||||
for (int i = 0; i < yaw_robot.size(); i++)
|
||||
{
|
||||
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
|
||||
@@ -407,7 +398,7 @@ namespace robot_costmap_2d
|
||||
}
|
||||
catch (tf3::TransformException &ex)
|
||||
{
|
||||
printf("%s\n", ex.what());
|
||||
robot::log_error("%s\n", ex.what());
|
||||
return false;
|
||||
}
|
||||
// Copy map data given proper transformations
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
#include <robot_costmap_2d/footprint.h>
|
||||
#include <boost/thread.hpp>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
using robot_costmap_2d::LETHAL_OBSTACLE;
|
||||
@@ -58,7 +59,6 @@ InflationLayer::InflationLayer()
|
||||
, inflate_unknown_(false)
|
||||
, cell_inflation_radius_(0)
|
||||
, cached_cell_inflation_radius_(0)
|
||||
, seen_(NULL)
|
||||
, cached_costs_(NULL)
|
||||
, cached_distances_(NULL)
|
||||
, last_min_x_(-std::numeric_limits<float>::max())
|
||||
@@ -76,14 +76,13 @@ void InflationLayer::onInitialize()
|
||||
|
||||
boost::unique_lock < boost::recursive_mutex > lock(*inflation_access_);
|
||||
current_ = true;
|
||||
if (seen_)
|
||||
delete[] seen_;
|
||||
seen_ = NULL;
|
||||
seen_size_ = 0;
|
||||
seen_.clear();
|
||||
seen_generation_ = 0;
|
||||
need_reinflation_ = false;
|
||||
std::string config_file_name = "inflation_layer_params.yaml";
|
||||
// std::cout << "InflationLayer: " << config_file_name << std::endl;
|
||||
getParams(config_file_name, priv_nh);
|
||||
if (!getParams(config_file_name, priv_nh))
|
||||
throw std::runtime_error("InflationLayer " + name_ + ": cannot open the default file " + config_file_name);
|
||||
|
||||
matchSize();
|
||||
}
|
||||
@@ -91,7 +90,13 @@ void InflationLayer::onInitialize()
|
||||
bool InflationLayer::getParams(const std::string& config_file_name, robot::NodeHandle &nh)
|
||||
{
|
||||
try {
|
||||
std::string folder = ROBOT_COSTMAP_2D_DIR;
|
||||
const char *env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::string folder;
|
||||
if (env_config && std::filesystem::exists(env_config))
|
||||
{
|
||||
folder = std::string(env_config);
|
||||
// robot::log_error("config_directory: %s", folder.c_str());
|
||||
}
|
||||
std::string path_source = getSourceFile(folder,config_file_name);
|
||||
|
||||
YAML::Node config = YAML::LoadFile(path_source);
|
||||
@@ -138,10 +143,8 @@ void InflationLayer::matchSize()
|
||||
computeCaches();
|
||||
|
||||
unsigned int size_x = costmap->getSizeInCellsX(), size_y = costmap->getSizeInCellsY();
|
||||
if (seen_)
|
||||
delete[] seen_;
|
||||
seen_size_ = size_x * size_y;
|
||||
seen_ = new bool[seen_size_];
|
||||
seen_.assign(static_cast<std::size_t>(size_x) * size_y, 0);
|
||||
seen_generation_ = 0;
|
||||
}
|
||||
|
||||
void InflationLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
|
||||
@@ -186,7 +189,7 @@ void InflationLayer::onFootprintChanged()
|
||||
computeCaches();
|
||||
need_reinflation_ = true;
|
||||
|
||||
printf("InflationLayer::onFootprintChanged(): num footprint points: %lu,"
|
||||
robot::log_info("InflationLayer::onFootprintChanged(): num footprint points: %lu,"
|
||||
" inscribed_radius_ = %.3f, inflation_radius_ = %.3f\n",
|
||||
layered_costmap_->getFootprint().size(), inscribed_radius_, inflation_radius_);
|
||||
}
|
||||
@@ -197,25 +200,28 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
if (cell_inflation_radius_ == 0)
|
||||
return;
|
||||
|
||||
// make sure the inflation list is empty at the beginning of the cycle (should always be true)
|
||||
printf("The inflation list must be empty at the beginning of inflation\n");
|
||||
for (std::vector<CellData>& cells : inflation_cells_)
|
||||
cells.clear();
|
||||
|
||||
unsigned char* master_array = master_grid.getCharMap();
|
||||
unsigned int size_x = master_grid.getSizeInCellsX(), size_y = master_grid.getSizeInCellsY();
|
||||
|
||||
if (seen_ == NULL) {
|
||||
printf("InflationLayer::updateCosts(): seen_ array is NULL\n");
|
||||
seen_size_ = size_x * size_y;
|
||||
seen_ = new bool[seen_size_];
|
||||
}
|
||||
else if (seen_size_ != size_x * size_y)
|
||||
const std::size_t map_size = static_cast<std::size_t>(size_x) * size_y;
|
||||
if (seen_.size() != map_size)
|
||||
{
|
||||
printf("InflationLayer::updateCosts(): seen_ array size is wrong\n");
|
||||
delete[] seen_;
|
||||
seen_size_ = size_x * size_y;
|
||||
seen_ = new bool[seen_size_];
|
||||
seen_.assign(map_size, 0);
|
||||
seen_generation_ = 0;
|
||||
}
|
||||
|
||||
if (seen_generation_ == std::numeric_limits<std::uint32_t>::max())
|
||||
{
|
||||
std::fill(seen_.begin(), seen_.end(), 0);
|
||||
seen_generation_ = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
++seen_generation_;
|
||||
}
|
||||
memset(seen_, false, size_x * size_y * sizeof(bool));
|
||||
|
||||
// We need to include in the inflation cells outside the bounding
|
||||
// box min_i...max_j, by the amount cell_inflation_radius_. Cells
|
||||
@@ -231,11 +237,13 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
max_i = std::min(int(size_x), max_i);
|
||||
max_j = std::min(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
|
||||
// Precomputed distance buckets preserve priority ordering without a tree lookup
|
||||
// for every enqueued cell.
|
||||
|
||||
// Start with lethal obstacles: by definition distance is 0.0
|
||||
std::vector<CellData>& obs_bin = inflation_cells_[0.0];
|
||||
if (inflation_cells_.empty())
|
||||
return;
|
||||
std::vector<CellData>& obs_bin = inflation_cells_.front();
|
||||
for (int j = min_j; j < max_j; j++)
|
||||
{
|
||||
for (int i = min_i; i < max_i; i++)
|
||||
@@ -251,23 +259,22 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
|
||||
// Process cells by increasing distance; new cells are appended to the corresponding distance bin, so they
|
||||
// can overtake previously inserted but farther away cells
|
||||
std::map<double, std::vector<CellData> >::iterator bin;
|
||||
for (bin = inflation_cells_.begin(); bin != inflation_cells_.end(); ++bin)
|
||||
for (std::vector<CellData>& bin : inflation_cells_)
|
||||
{
|
||||
for (int i = 0; i < bin->second.size(); ++i)
|
||||
for (std::size_t i = 0; i < bin.size(); ++i)
|
||||
{
|
||||
// process all cells at distance dist_bin.first
|
||||
const CellData& cell = bin->second[i];
|
||||
const CellData& cell = bin[i];
|
||||
|
||||
unsigned int index = cell.index_;
|
||||
|
||||
// ignore if already visited
|
||||
if (seen_[index])
|
||||
if (seen_[index] == seen_generation_)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
seen_[index] = true;
|
||||
seen_[index] = seen_generation_;
|
||||
|
||||
unsigned int mx = cell.x_;
|
||||
unsigned int my = cell.y_;
|
||||
@@ -294,7 +301,6 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
}
|
||||
}
|
||||
|
||||
inflation_cells_.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -309,7 +315,7 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
inline void InflationLayer::enqueue(unsigned int index, unsigned int mx, unsigned int my,
|
||||
unsigned int src_x, unsigned int src_y)
|
||||
{
|
||||
if (!seen_[index])
|
||||
if (seen_[index] != seen_generation_)
|
||||
{
|
||||
// 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);
|
||||
@@ -318,8 +324,10 @@ inline void InflationLayer::enqueue(unsigned int index, unsigned int mx, unsigne
|
||||
if (distance > cell_inflation_radius_)
|
||||
return;
|
||||
|
||||
// push the cell data onto the inflation list and mark
|
||||
inflation_cells_[distance].push_back(CellData(index, mx, my, src_x, src_y));
|
||||
const unsigned int dx = std::abs(static_cast<int>(mx) - static_cast<int>(src_x));
|
||||
const unsigned int dy = std::abs(static_cast<int>(my) - static_cast<int>(src_y));
|
||||
const unsigned int bin_index = distance_bin_lookup_[dx * distance_lookup_size_ + dy];
|
||||
inflation_cells_[bin_index].push_back(CellData(index, mx, my, src_x, src_y));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,6 +355,38 @@ void InflationLayer::computeCaches()
|
||||
}
|
||||
|
||||
cached_cell_inflation_radius_ = cell_inflation_radius_;
|
||||
|
||||
distance_lookup_size_ = cell_inflation_radius_ + 2;
|
||||
distance_levels_.clear();
|
||||
for (unsigned int i = 0; i < distance_lookup_size_; ++i)
|
||||
{
|
||||
for (unsigned int j = 0; j < distance_lookup_size_; ++j)
|
||||
{
|
||||
if (cached_distances_[i][j] <= cell_inflation_radius_)
|
||||
distance_levels_.push_back(cached_distances_[i][j]);
|
||||
}
|
||||
}
|
||||
std::sort(distance_levels_.begin(), distance_levels_.end());
|
||||
distance_levels_.erase(
|
||||
std::unique(distance_levels_.begin(), distance_levels_.end()), distance_levels_.end());
|
||||
|
||||
inflation_cells_.clear();
|
||||
inflation_cells_.resize(distance_levels_.size());
|
||||
distance_bin_lookup_.assign(
|
||||
static_cast<std::size_t>(distance_lookup_size_) * distance_lookup_size_, 0);
|
||||
for (unsigned int i = 0; i < distance_lookup_size_; ++i)
|
||||
{
|
||||
for (unsigned int j = 0; j < distance_lookup_size_; ++j)
|
||||
{
|
||||
const double distance = cached_distances_[i][j];
|
||||
if (distance > cell_inflation_radius_)
|
||||
continue;
|
||||
distance_bin_lookup_[i * distance_lookup_size_ + j] =
|
||||
static_cast<unsigned int>(
|
||||
std::lower_bound(distance_levels_.begin(), distance_levels_.end(), distance) -
|
||||
distance_levels_.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i <= cell_inflation_radius_ + 1; ++i)
|
||||
@@ -360,6 +400,10 @@ void InflationLayer::computeCaches()
|
||||
|
||||
void InflationLayer::deleteKernels()
|
||||
{
|
||||
inflation_cells_.clear();
|
||||
distance_levels_.clear();
|
||||
distance_bin_lookup_.clear();
|
||||
distance_lookup_size_ = 0;
|
||||
if (cached_distances_ != NULL)
|
||||
{
|
||||
for (unsigned int i = 0; i <= cached_cell_inflation_radius_ + 1; ++i)
|
||||
@@ -404,7 +448,7 @@ void InflationLayer::handleImpl(const void* data,
|
||||
const std::type_info& info,
|
||||
const std::string& source)
|
||||
{
|
||||
printf("This function is not available!\n");
|
||||
robot::log_error("This function is not available!\n");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
|
||||
#include <tf3/exceptions.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
using robot_costmap_2d::NO_INFORMATION;
|
||||
@@ -66,7 +67,8 @@ void ObstacleLayer::onInitialize()
|
||||
stop_receiving_data_ = false;
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
std::string config_file_name = "obstacle_layer_params.yaml";
|
||||
getParams(config_file_name, priv_nh);
|
||||
if (!getParams(config_file_name, priv_nh))
|
||||
throw std::runtime_error("ObstacleLayer " + name_ + ": cannot open the default file " + config_file_name);
|
||||
}
|
||||
|
||||
ObstacleLayer::~ObstacleLayer()
|
||||
@@ -75,7 +77,14 @@ ObstacleLayer::~ObstacleLayer()
|
||||
bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHandle &nh)
|
||||
{
|
||||
try {
|
||||
std::string folder = ROBOT_COSTMAP_2D_DIR;
|
||||
const char *env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::string folder;
|
||||
if (env_config && std::filesystem::exists(env_config))
|
||||
{
|
||||
folder = std::string(env_config);
|
||||
// robot::log_error("config_directory: %s", folder.c_str());
|
||||
}
|
||||
// robot::log_error("folder: %s", folder.c_str());
|
||||
std::string path_source = getSourceFile(folder,config_file_name);
|
||||
|
||||
YAML::Node config = YAML::LoadFile(path_source);
|
||||
@@ -111,7 +120,7 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
std::string topics_string = loadParam(layer,"observation_sources", std::string(""));
|
||||
if (nh.hasParam("observation_sources"))
|
||||
nh.getParam("observation_sources", topics_string);
|
||||
robot::log_error("Subscribed to Topics: %s\n", topics_string.c_str());
|
||||
robot::log_info("Subscribed to Topics: %s\n", topics_string.c_str());
|
||||
|
||||
// now we need to split the topics based on whitespace which we can use a stringstream for
|
||||
std::stringstream ss(topics_string);
|
||||
@@ -158,6 +167,16 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
if (priv_nh.hasParam("marking"))
|
||||
priv_nh.getParam("marking", marking);
|
||||
|
||||
double obstacle_range = 2.5;
|
||||
obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range);
|
||||
double raytrace_range = 3.0;
|
||||
raytrace_range = loadParam(layer[source],"raytrace_range", raytrace_range);
|
||||
|
||||
if (priv_nh.hasParam("obstacle_range"))
|
||||
priv_nh.getParam("obstacle_range", obstacle_range);
|
||||
if (priv_nh.hasParam("raytrace_range"))
|
||||
priv_nh.getParam("raytrace_range", raytrace_range);
|
||||
|
||||
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan"))
|
||||
{
|
||||
robot::log_error("Only topics that use point clouds or laser scans are currently supported\n");
|
||||
@@ -165,29 +184,14 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
}
|
||||
|
||||
CallBackInfo info_tmp;
|
||||
info_tmp.observation_source = source;
|
||||
info_tmp.data_type = data_type;
|
||||
info_tmp.topic = topic;
|
||||
info_tmp.inf_is_valid = inf_is_valid;
|
||||
callback_infos_.push_back(info_tmp);
|
||||
|
||||
std::string raytrace_range_param_name, obstacle_range_param_name;
|
||||
|
||||
double obstacle_range = 2.5;
|
||||
obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range);
|
||||
double raytrace_range = 3.0;
|
||||
raytrace_range = loadParam(layer[source],"raytrace_range", raytrace_range);
|
||||
|
||||
|
||||
|
||||
if (priv_nh.hasParam("obstacle_range"))
|
||||
priv_nh.getParam("obstacle_range", obstacle_range);
|
||||
if (priv_nh.hasParam("raytrace_range"))
|
||||
priv_nh.getParam("raytrace_range", raytrace_range);
|
||||
|
||||
// enabled_ = enabled;
|
||||
|
||||
printf("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
|
||||
sensor_frame.c_str());
|
||||
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
|
||||
priv_nh.getNamespace().c_str());
|
||||
|
||||
// create an observation buffer
|
||||
observation_buffers_.push_back(
|
||||
@@ -201,8 +205,7 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
// check if we'll also add this buffer to our clearing observation buffers
|
||||
if (clearing)
|
||||
clearing_buffers_.push_back(observation_buffers_.back());
|
||||
|
||||
printf(
|
||||
robot::log_info(
|
||||
"Created an observation buffer for topic %s, global frame: %s, "
|
||||
"expected update rate: %.2f, observation persistence: %.2f\n",
|
||||
topic.c_str(), global_frame_.c_str(), expected_update_rate, observation_keep_time);
|
||||
@@ -210,7 +213,7 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
}
|
||||
}
|
||||
catch (const YAML::BadFile& e) {
|
||||
std::cerr << "Cannot open YAML file: " << e.what() << std::endl;
|
||||
robot::log_error("Cannot open YAML file: %s\n", e.what());
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -222,60 +225,63 @@ void ObstacleLayer::handleImpl(const void* data,
|
||||
const std::type_info& type,
|
||||
const std::string& topic)
|
||||
{
|
||||
if(!stop_receiving_data_)
|
||||
{
|
||||
|
||||
if(observation_buffers_.empty() || callback_infos_.empty()) return;
|
||||
|
||||
int size_callback = static_cast<int>(callback_infos_.size());
|
||||
for(int i = 0; i < size_callback; i++)
|
||||
{
|
||||
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
|
||||
|
||||
if (type == typeid(robot_sensor_msgs::LaserScan) &&
|
||||
callback_infos_[i].data_type == "LaserScan" &&
|
||||
topic == callback_infos_[i].topic &&
|
||||
!callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
|
||||
}
|
||||
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
|
||||
callback_infos_[i].data_type == "LaserScan" &&
|
||||
topic == callback_infos_[i].topic &&
|
||||
callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
|
||||
}
|
||||
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
|
||||
callback_infos_[i].data_type == "PointCloud" &&
|
||||
topic == callback_infos_[i].topic)
|
||||
{
|
||||
if (callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
printf("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.");
|
||||
}
|
||||
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
|
||||
}
|
||||
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
|
||||
callback_infos_[i].data_type == "PointCloud2" &&
|
||||
topic == callback_infos_[i].topic)
|
||||
{
|
||||
if (callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
printf("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.");
|
||||
}
|
||||
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "obstacle_layer: Unknown type: " << type.name() << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Stop receiving data!" << std::endl;
|
||||
if (!enabled_ || stop_receiving_data_)
|
||||
return;
|
||||
|
||||
// Samples that match no configured source (type and topic) are ignored.
|
||||
if (observation_buffers_.empty() || callback_infos_.empty())
|
||||
return;
|
||||
|
||||
int size_callback = static_cast<int>(callback_infos_.size());
|
||||
for (int i = 0; i < size_callback; i++)
|
||||
{
|
||||
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
|
||||
|
||||
if (type == typeid(robot_sensor_msgs::LaserScan) &&
|
||||
callback_infos_[i].data_type == "LaserScan" &&
|
||||
topic == callback_infos_[i].topic &&
|
||||
!callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
|
||||
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
|
||||
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
|
||||
}
|
||||
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
|
||||
callback_infos_[i].data_type == "LaserScan" &&
|
||||
topic == callback_infos_[i].topic &&
|
||||
callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
|
||||
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
|
||||
}
|
||||
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
|
||||
callback_infos_[i].data_type == "PointCloud" &&
|
||||
topic == callback_infos_[i].topic)
|
||||
{
|
||||
if (callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
|
||||
}
|
||||
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
|
||||
}
|
||||
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
|
||||
callback_infos_[i].data_type == "PointCloud2" &&
|
||||
topic == callback_infos_[i].topic)
|
||||
{
|
||||
if (callback_infos_[i].inf_is_valid)
|
||||
{
|
||||
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
|
||||
}
|
||||
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
|
||||
}
|
||||
// else
|
||||
// {
|
||||
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
|
||||
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
|
||||
// << "data type: " << callback_infos_[i].data_type << std::endl
|
||||
// << "topic: " << topic << std::endl
|
||||
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,13 +299,13 @@ void ObstacleLayer::laserScanCallback(const robot_sensor_msgs::LaserScan& messag
|
||||
}
|
||||
catch (tf3::TransformException &ex)
|
||||
{
|
||||
printf("High fidelity enabled, but TF returned a transform exception to frame %s: %s\n", global_frame_.c_str(),
|
||||
robot::log_error("High fidelity enabled, but TF returned a transform exception to frame %s: %s\n", global_frame_.c_str(),
|
||||
ex.what());
|
||||
projector_.projectLaser(message, cloud);
|
||||
}
|
||||
catch (std::runtime_error &ex)
|
||||
{
|
||||
printf("transformLaserScanToPointCloud error, it seems the message from laser sensor is malformed. Ignore this laser scan. what(): %s\n", ex.what());
|
||||
robot::log_error("transformLaserScanToPointCloud error, it seems the message from laser sensor is malformed. Ignore this laser scan. what(): %s\n", ex.what());
|
||||
return; //ignore this message
|
||||
}
|
||||
|
||||
@@ -335,13 +341,13 @@ void ObstacleLayer::laserScanValidInfCallback(const robot_sensor_msgs::LaserScan
|
||||
}
|
||||
catch (tf3::TransformException &ex)
|
||||
{
|
||||
printf("High fidelity enabled, but TF returned a transform exception to frame %s: %s\n",
|
||||
robot::log_error("High fidelity enabled, but TF returned a transform exception to frame %s: %s\n",
|
||||
global_frame_.c_str(), ex.what());
|
||||
projector_.projectLaser(message, cloud);
|
||||
}
|
||||
catch (std::runtime_error &ex)
|
||||
{
|
||||
printf("transformLaserScanToPointCloud error, it seems the message from laser sensor is malformed. Ignore this laser scan. what(): %s\n", ex.what());
|
||||
robot::log_error("transformLaserScanToPointCloud error, it seems the message from laser sensor is malformed. Ignore this laser scan. what(): %s\n", ex.what());
|
||||
return; //ignore this message
|
||||
}
|
||||
|
||||
@@ -358,7 +364,7 @@ void ObstacleLayer::pointCloudCallback(const robot_sensor_msgs::PointCloud& mess
|
||||
|
||||
if (!robot_sensor_msgs::convertPointCloudToPointCloud2(message, cloud2))
|
||||
{
|
||||
printf("Failed to convert a PointCloud to a PointCloud2, dropping message\n");
|
||||
robot::log_error("Failed to convert a PointCloud to a PointCloud2, dropping message\n");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -415,6 +421,9 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
|
||||
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
|
||||
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
|
||||
|
||||
std::size_t rejected_height = 0;
|
||||
std::size_t rejected_range = 0;
|
||||
std::size_t rejected_bounds = 0;
|
||||
for (; iter_x !=iter_x.end(); ++iter_x, ++iter_y, ++iter_z)
|
||||
{
|
||||
double px = *iter_x, py = *iter_y, pz = *iter_z;
|
||||
@@ -422,7 +431,7 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
|
||||
// if the obstacle is too high or too far away from the robot we won't add it
|
||||
if (pz > max_obstacle_height_)
|
||||
{
|
||||
printf("The point is too high\n");
|
||||
++rejected_height;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -433,7 +442,7 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
|
||||
// if the point is far enough away... we won't consider it
|
||||
if (sq_dist >= sq_obstacle_range)
|
||||
{
|
||||
printf("The point is too far away\n");
|
||||
++rejected_range;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -441,7 +450,7 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
|
||||
unsigned int mx, my;
|
||||
if (!worldToMap(px, py, mx, my))
|
||||
{
|
||||
printf("Computing map coords failed\n");
|
||||
++rejected_bounds;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -449,6 +458,14 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
|
||||
costmap_[index] = LETHAL_OBSTACLE;
|
||||
touch(px, py, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
if (rejected_height + rejected_range + rejected_bounds > 0)
|
||||
{
|
||||
robot::log_info_throttle(
|
||||
5.0,
|
||||
"ObstacleLayer filtered points: height=%zu range=%zu outside_map=%zu\n",
|
||||
rejected_height, rejected_range, rejected_bounds);
|
||||
}
|
||||
}
|
||||
|
||||
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
|
||||
@@ -546,7 +563,7 @@ void ObstacleLayer::raytraceFreespace(const Observation& clearing_observation, d
|
||||
unsigned int x0, y0;
|
||||
if (!worldToMap(ox, oy, x0, y0))
|
||||
{
|
||||
printf(
|
||||
robot::log_error(
|
||||
"The origin for the sensor at (%.2f, %.2f) is out of map bounds. So, the costmap cannot raytrace for it.\n",
|
||||
ox, oy);
|
||||
return;
|
||||
|
||||
@@ -14,7 +14,6 @@ PreferredLayer::~PreferredLayer(){}
|
||||
|
||||
unsigned char PreferredLayer::interpretValue(unsigned char value)
|
||||
{
|
||||
printf("TEST PLUGIN !!!\n");
|
||||
// check if the static value is above the unknown or lethal thresholds
|
||||
if(value == 0) return NO_INFORMATION;
|
||||
else if (value >= *this->threshold_)
|
||||
|
||||
@@ -43,7 +43,9 @@
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <stdexcept>
|
||||
#include <fstream>
|
||||
#include <cxxabi.h>
|
||||
|
||||
|
||||
using robot_costmap_2d::NO_INFORMATION;
|
||||
@@ -70,13 +72,21 @@ void StaticLayer::onInitialize()
|
||||
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
std::string config_file_name = "static_layer_params.yaml";
|
||||
getParams(config_file_name, priv_nh);
|
||||
if (!getParams(config_file_name, priv_nh))
|
||||
throw std::runtime_error("StaticLayer " + name_ + ": cannot open the default file " + config_file_name);
|
||||
robot::log_warning("Initializing static layer with map topic \"%s\" in frame \"%s\"", map_topic_.c_str(), global_frame_.c_str());
|
||||
}
|
||||
|
||||
bool StaticLayer::getParams(const std::string& config_file_name, robot::NodeHandle &nh)
|
||||
{
|
||||
try {
|
||||
std::string folder = ROBOT_COSTMAP_2D_DIR;
|
||||
const char *env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::string folder;
|
||||
if (env_config && std::filesystem::exists(env_config))
|
||||
{
|
||||
folder = std::string(env_config);
|
||||
// robot::log_error("config_directory: %s", folder.c_str());
|
||||
}
|
||||
std::string path_source = getSourceFile(folder,config_file_name);
|
||||
|
||||
YAML::Node config = YAML::LoadFile(path_source);
|
||||
@@ -185,12 +195,23 @@ void StaticLayer::handleImpl(const void* data,
|
||||
const std::type_info& type,
|
||||
const std::string& topic)
|
||||
{
|
||||
if (type == typeid(robot_nav_msgs::OccupancyGrid) && topic == map_topic_) {
|
||||
if (type == typeid(robot_nav_msgs::OccupancyGrid) &&
|
||||
(topic == map_topic_ || topic == "/" + map_topic_)) {
|
||||
incomingMap(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data));
|
||||
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) && topic == map_topic_ + "_updates") {
|
||||
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) &&
|
||||
(topic == map_topic_ + "_updates" || topic == "/" + map_topic_ + "_updates")) {
|
||||
incomingUpdate(*static_cast<const robot_map_msgs::OccupancyGridUpdate*>(data));
|
||||
} else {
|
||||
std::cout << "[Plugin] Unknown type: " << type.name() << std::endl;
|
||||
std::string readable = boost::core::demangle(type.name());
|
||||
|
||||
size_t pos = readable.find("<");
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
readable = readable.substr(0, pos);
|
||||
}
|
||||
robot::log_error("[] con1: %x, con2: %x ", type == typeid(robot_nav_msgs::OccupancyGrid), (topic == map_topic_ || topic == "/" + map_topic_));
|
||||
robot::log_error("[StaticLayer] Received data of unknown type: %s on topic: %s, map_topic_: %s\n", readable.c_str(), topic.c_str(), map_topic_.c_str());
|
||||
// std::cout << "[StaticLayer] Unknown type: " << type.name() << " on topic: " << topic << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,10 +219,10 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
{
|
||||
if(!map_shutdown_)
|
||||
{
|
||||
std::cout << "Received new map!" << std::endl;
|
||||
std::cout << "[StaticLayer] Received new map!" << std::endl;
|
||||
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
|
||||
|
||||
printf("Received a %d X %d map at %f m/pix\n", size_x, size_y, new_map.info.resolution);
|
||||
robot::log_info("Received a %d X %d map at %f m/pix\n", size_x, size_y, new_map.info.resolution);
|
||||
|
||||
// resize costmap if size, resolution or origin do not match
|
||||
Costmap2D* master = layered_costmap_->getCostmap();
|
||||
@@ -213,7 +234,7 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
master->getOriginY() != new_map.info.origin.position.y))
|
||||
{
|
||||
// Update the size of the layered costmap (and all layers, including this one)
|
||||
printf("Resizing costmap to %d X %d at %f m/pix\n", size_x, size_y, new_map.info.resolution);
|
||||
robot::log_info("Resizing costmap to %d X %d at %f m/pix\n", 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 /* set size_locked to true, prevents reconfigureCb from overriding map size*/);
|
||||
@@ -224,7 +245,7 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
origin_y_ != new_map.info.origin.position.y)
|
||||
{
|
||||
// only update the size of the costmap stored locally in this layer
|
||||
printf("Resizing static layer to %d X %d at %f m/pix\n", size_x, size_y, new_map.info.resolution);
|
||||
robot::log_info("Resizing static layer to %d X %d at %f m/pix\n", 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);
|
||||
}
|
||||
@@ -247,11 +268,9 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
{
|
||||
unsigned char value = new_map.data[index];
|
||||
costmap_[index] = interpretValue(value);
|
||||
// printf("%d , ",costmap_[index]);
|
||||
// 3. Ghi giá trị biến
|
||||
// file << static_cast<int>(costmap_[index]) << " , ";
|
||||
++index;
|
||||
// printf("%d , ",costmap_[index]);
|
||||
}
|
||||
// file << std::endl;
|
||||
}
|
||||
@@ -268,13 +287,13 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Stop receive new map!");
|
||||
robot::log_info("Stop receive new map!\n");
|
||||
}
|
||||
|
||||
// shutdown the map subscrber if firt_map_only_ flag is on
|
||||
if (first_map_only_)
|
||||
{
|
||||
printf("Shutting down the map subscriber. first_map_only flag is on\n");
|
||||
robot::log_info("Shutting down the map subscriber. first_map_only flag is on\n");
|
||||
map_shutdown_ = true;
|
||||
}
|
||||
}
|
||||
@@ -283,7 +302,7 @@ void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& upda
|
||||
{
|
||||
if(!map_update_shutdown_)
|
||||
{
|
||||
std::cout << "Update new map!" << std::endl;
|
||||
robot::log_info("Update new map!\n");
|
||||
unsigned int di = 0;
|
||||
for (unsigned int y = 0; y < update.height ; y++)
|
||||
{
|
||||
@@ -328,7 +347,6 @@ void StaticLayer::reset()
|
||||
{
|
||||
onInitialize();
|
||||
}
|
||||
printf("RESET MAP");
|
||||
}
|
||||
|
||||
void StaticLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
|
||||
@@ -378,11 +396,11 @@ void StaticLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_
|
||||
tf3::TransformStampedMsg transformMsg;
|
||||
try
|
||||
{
|
||||
transformMsg = tf_->lookupTransform(map_frame_, global_frame_, tf3::Time::now());
|
||||
transformMsg = tf_->lookupTransform(map_frame_, global_frame_, tf3::Time());
|
||||
}
|
||||
catch (tf3::TransformException ex)
|
||||
{
|
||||
printf("%s", ex.what());
|
||||
robot::log_error("StaticLayer::updateCosts(): %s \n", ex.what());
|
||||
return;
|
||||
}
|
||||
// Copy map data given proper transformations
|
||||
|
||||
@@ -37,7 +37,16 @@
|
||||
*********************************************************************/
|
||||
#include <robot_costmap_2d/voxel_layer.h>
|
||||
#include <robot_sensor_msgs/point_cloud2_iterator.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
#include <robot_geometry_msgs/Vector3.h>
|
||||
#include <tf3/exceptions.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#define VOXEL_BITS 16
|
||||
|
||||
@@ -58,7 +67,8 @@ void VoxelLayer::onInitialize()
|
||||
|
||||
ObstacleLayer::onInitialize();
|
||||
std::string config_file_name = "voxel_layer_params.yaml";
|
||||
getParams(config_file_name, priv_nh);
|
||||
if (!getParams(config_file_name, priv_nh))
|
||||
throw std::runtime_error("VoxelLayer " + name_ + ": cannot open the default file " + config_file_name);
|
||||
}
|
||||
|
||||
VoxelLayer::~VoxelLayer()
|
||||
@@ -68,7 +78,14 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
|
||||
{
|
||||
try
|
||||
{
|
||||
std::string folder = ROBOT_COSTMAP_2D_DIR;
|
||||
const char *env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::string folder;
|
||||
if (env_config && std::filesystem::exists(env_config))
|
||||
{
|
||||
folder = std::string(env_config);
|
||||
// robot::log_error("config_directory: %s", folder.c_str());
|
||||
}
|
||||
|
||||
std::string path_source = getSourceFile(folder,config_file_name);
|
||||
|
||||
YAML::Node config = YAML::LoadFile(path_source);
|
||||
@@ -78,14 +95,14 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
|
||||
enabled_ = loadParam(layer, "enabled", true);
|
||||
footprint_clearing_enabled_ = loadParam(layer, "footprint_clearing_enabled", true);
|
||||
max_obstacle_height_ = loadParam(layer, "max_obstacle_height", 2.0);
|
||||
size_z_ = loadParam(layer, "z_voxels", 10);
|
||||
int size_z = loadParam(layer, "z_voxels", 10);
|
||||
origin_z_ = loadParam(layer, "origin_z", 0.0);
|
||||
z_resolution_ = loadParam(layer, "z_resolution", 0.2);
|
||||
unknown_threshold_ = loadParam(layer, "unknown_threshold", 15.0) + (VOXEL_BITS - size_z_);
|
||||
mark_threshold_ = loadParam(layer, "mark_threshold", 0);
|
||||
// Read as double: the default file writes 15.0, which yaml-cpp refuses to convert to int.
|
||||
double unknown_threshold = loadParam(layer, "unknown_threshold", 15.0);
|
||||
int mark_threshold = loadParam(layer, "mark_threshold", 0);
|
||||
combination_method_ = loadParam(layer, "combination_method", 0.0);
|
||||
|
||||
int size_z, unknown_threshold, mark_threshold;
|
||||
if (nh.hasParam("enabled"))
|
||||
nh.getParam("enabled", enabled_);
|
||||
if (nh.hasParam("footprint_clearing_enabled"))
|
||||
@@ -93,25 +110,39 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
|
||||
if (nh.hasParam("max_obstacle_height"))
|
||||
nh.getParam("max_obstacle_height", max_obstacle_height_);
|
||||
if (nh.hasParam("z_voxels"))
|
||||
{
|
||||
nh.getParam("z_voxels", size_z);
|
||||
size_z_ = size_z;
|
||||
}
|
||||
if (nh.hasParam("origin_z"))
|
||||
nh.getParam("origin_z", origin_z_);
|
||||
if (nh.hasParam("z_resolution"))
|
||||
nh.getParam("z_resolution", z_resolution_);
|
||||
if (nh.hasParam("unknown_threshold"))
|
||||
{
|
||||
nh.getParam("unknown_threshold", unknown_threshold);
|
||||
unknown_threshold_ = unknown_threshold + (VOXEL_BITS - size_z_);
|
||||
}
|
||||
if (nh.hasParam("mark_threshold"))
|
||||
{
|
||||
nh.getParam("mark_threshold", mark_threshold);
|
||||
mark_threshold_ = mark_threshold;
|
||||
}
|
||||
if (nh.hasParam("combination_method"))
|
||||
nh.getParam("combination_method", combination_method_);
|
||||
|
||||
// A column stores VOXEL_BITS levels at most, and worldToMap3D divides by z_resolution.
|
||||
if (size_z < 1 || size_z > VOXEL_BITS)
|
||||
throw std::invalid_argument("VoxelLayer " + name_ + ": z_voxels must be in [1, 16]");
|
||||
if (!(z_resolution_ > 0.0) || !std::isfinite(z_resolution_))
|
||||
throw std::invalid_argument("VoxelLayer " + name_ + ": z_resolution must be > 0 [m]");
|
||||
if (!std::isfinite(origin_z_))
|
||||
throw std::invalid_argument("VoxelLayer " + name_ + ": origin_z must be finite [m]");
|
||||
if (!(unknown_threshold >= 0.0) || mark_threshold < 0)
|
||||
throw std::invalid_argument("VoxelLayer " + name_ + ": unknown_threshold and mark_threshold must be >= 0");
|
||||
|
||||
size_z_ = size_z;
|
||||
// Levels above z_voxels are never observed and stay unknown; adding them keeps the threshold
|
||||
// counting only the levels in use. Computed after size_z_ is final, so overriding z_voxels
|
||||
// alone no longer leaves the threshold sized for the default file's column.
|
||||
unknown_threshold_ = static_cast<unsigned int>(unknown_threshold) + (VOXEL_BITS - size_z_);
|
||||
mark_threshold_ = static_cast<unsigned int>(mark_threshold);
|
||||
|
||||
robot::log_info("VoxelLayer %s: column origin_z=%.2f m z_resolution=%.3f m z_voxels=%u (top %.2f m) "
|
||||
"unknown_threshold=%u mark_threshold=%u max_obstacle_height=%.2f m\n",
|
||||
name_.c_str(), origin_z_, z_resolution_, size_z_, origin_z_ + size_z_ * z_resolution_,
|
||||
unknown_threshold_, mark_threshold_, max_obstacle_height_);
|
||||
|
||||
this->matchSize();
|
||||
}
|
||||
@@ -225,29 +256,6 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if (publish_voxel_)
|
||||
// {
|
||||
// robot_costmap_2d::VoxelGrid grid_msg;
|
||||
// unsigned int size = robot_voxel_grid_.sizeX() * robot_voxel_grid_.sizeY();
|
||||
// grid_msg.size_x = robot_voxel_grid_.sizeX();
|
||||
// grid_msg.size_y = robot_voxel_grid_.sizeY();
|
||||
// grid_msg.size_z = robot_voxel_grid_.sizeZ();
|
||||
// grid_msg.data.resize(size);
|
||||
// memcpy(&grid_msg.data[0], robot_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 = robot::Time::now();
|
||||
// voxel_pub_.publish(grid_msg);
|
||||
// }
|
||||
|
||||
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
@@ -316,19 +324,11 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
|
||||
|
||||
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z))
|
||||
{
|
||||
printf(
|
||||
robot::log_error(
|
||||
"The origin for the sensor at (%.2f, %.2f, %.2f) is out of map bounds. So, the costmap cannot raytrace for it.\n",
|
||||
ox, oy, oz);
|
||||
return;
|
||||
}
|
||||
|
||||
// bool publish_clearing_points = (clearing_endpoints_pub_.getNumSubscribers() > 0);
|
||||
// if (publish_clearing_points)
|
||||
// {
|
||||
clearing_endpoints_.points.clear();
|
||||
clearing_endpoints_.points.reserve(clearing_observation_cloud_size);
|
||||
// }
|
||||
|
||||
// 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();
|
||||
@@ -403,26 +403,8 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
|
||||
cell_raytrace_range);
|
||||
|
||||
updateRaytraceBounds(ox, oy, wpx, wpy, clearing_observation.raytrace_range_, min_x, min_y, max_x, max_y);
|
||||
|
||||
// if (publish_clearing_points)
|
||||
// {
|
||||
robot_geometry_msgs::Point32 point;
|
||||
point.x = wpx;
|
||||
point.y = wpy;
|
||||
point.z = wpz;
|
||||
clearing_endpoints_.points.push_back(point);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
// if (publish_clearing_points)
|
||||
// {
|
||||
clearing_endpoints_.header.frame_id = global_frame_;
|
||||
clearing_endpoints_.header.stamp = clearing_observation.cloud_->header.stamp;
|
||||
clearing_endpoints_.header.seq = clearing_observation.cloud_->header.seq;
|
||||
|
||||
// clearing_endpoints_pub_.publish(clearing_endpoints_);
|
||||
// }
|
||||
}
|
||||
|
||||
void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
|
||||
@@ -432,6 +414,11 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
|
||||
cell_ox = int((new_origin_x - origin_x_) / resolution_);
|
||||
cell_oy = int((new_origin_y - origin_y_) / resolution_);
|
||||
|
||||
// Most update cycles do not cross a costmap cell boundary. Avoid copying and
|
||||
// resetting the complete 2D/3D grids when the cell-aligned origin is unchanged.
|
||||
if (cell_ox == 0 && cell_oy == 0)
|
||||
return;
|
||||
|
||||
// compute the associated world coordinates for the origin cell
|
||||
// beacuase we want to keep things grid-aligned
|
||||
double new_grid_ox, new_grid_oy;
|
||||
@@ -452,15 +439,20 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_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];
|
||||
const std::size_t overlap_size = static_cast<std::size_t>(cell_size_x) * cell_size_y;
|
||||
rolling_costmap_scratch_.resize(overlap_size);
|
||||
rolling_voxel_scratch_.resize(overlap_size);
|
||||
unsigned char* local_map = rolling_costmap_scratch_.data();
|
||||
unsigned int* local_voxel_map = rolling_voxel_scratch_.data();
|
||||
unsigned int* voxel_map = robot_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);
|
||||
if (overlap_size > 0)
|
||||
{
|
||||
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();
|
||||
@@ -474,12 +466,14 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
|
||||
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);
|
||||
if (overlap_size > 0)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
// Export factory function
|
||||
|
||||
@@ -165,6 +165,28 @@ Costmap2D::Costmap2D(const Costmap2D& map) :
|
||||
*this = map;
|
||||
}
|
||||
|
||||
void Costmap2D::copyFrom(const Costmap2D& map)
|
||||
{
|
||||
if (this == &map)
|
||||
return;
|
||||
|
||||
boost::unique_lock<mutex_t> lock(*access_);
|
||||
if (costmap_ == NULL || size_x_ != map.size_x_ || size_y_ != map.size_y_)
|
||||
{
|
||||
delete[] costmap_;
|
||||
costmap_ = new unsigned char[static_cast<std::size_t>(map.size_x_) * map.size_y_];
|
||||
size_x_ = map.size_x_;
|
||||
size_y_ = map.size_y_;
|
||||
}
|
||||
|
||||
resolution_ = map.resolution_;
|
||||
origin_x_ = map.origin_x_;
|
||||
origin_y_ = map.origin_y_;
|
||||
default_value_ = map.default_value_;
|
||||
memcpy(costmap_, map.costmap_,
|
||||
static_cast<std::size_t>(size_x_) * size_y_ * sizeof(unsigned char));
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -288,11 +310,17 @@ void Costmap2D::updateOrigin(double new_origin_x, double new_origin_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];
|
||||
const std::size_t overlap_size = static_cast<std::size_t>(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);
|
||||
// Reuse the temporary window to avoid allocating on every rolling-window shift.
|
||||
rolling_window_scratch_.resize(overlap_size);
|
||||
unsigned char* local_map = rolling_window_scratch_.data();
|
||||
|
||||
if (overlap_size > 0)
|
||||
{
|
||||
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();
|
||||
@@ -306,10 +334,12 @@ void Costmap2D::updateOrigin(double new_origin_x, double new_origin_y)
|
||||
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);
|
||||
if (overlap_size > 0)
|
||||
{
|
||||
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<robot_geometry_msgs::Point>& polygon, unsigned char cost_value)
|
||||
@@ -471,15 +501,12 @@ bool Costmap2D::saveMap(std::string file_name)
|
||||
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;
|
||||
|
||||
@@ -48,13 +48,44 @@
|
||||
#include <tf3/convert.h>
|
||||
#include <tf3/utils.h>
|
||||
#include <exception>
|
||||
#include <initializer_list>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <boost/dll/import.hpp>
|
||||
|
||||
#include <pthread.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
template <class T>
|
||||
void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::string name,T& value)
|
||||
{
|
||||
if (!old_h.hasParam(name))
|
||||
return;
|
||||
|
||||
// A failed getParam() writes its default (0, false, "") into value; copying that would replace
|
||||
// the layer's own default with a silent zero. A key of the wrong type is a configuration error.
|
||||
if (!old_h.getParam(name, value, value))
|
||||
throw std::invalid_argument("'" + old_h.getNamespace() + "/" + name +
|
||||
"' does not convert to the type the layer reads");
|
||||
new_h.setParam(name, value);
|
||||
}
|
||||
|
||||
// Moves each key of names that exists under old_h, read as T.
|
||||
template <class T>
|
||||
void move_parameters(robot::NodeHandle& old_h, robot::NodeHandle& new_h,
|
||||
std::initializer_list<const char*> names)
|
||||
{
|
||||
for (const char* name : names)
|
||||
{
|
||||
T value{};
|
||||
move_parameter(old_h, new_h, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) :
|
||||
layered_costmap_(NULL),
|
||||
name_(name),
|
||||
@@ -67,12 +98,11 @@ Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) :
|
||||
map_update_thread_(NULL),
|
||||
footprint_padding_(0.0)
|
||||
{
|
||||
std::signal(SIGINT, signalHandler);
|
||||
robot::NodeHandle nh("~");
|
||||
robot::NodeHandle priv_nh(nh, name);
|
||||
name_ = name;
|
||||
std::string config_file_name = "costmap_params.yaml";
|
||||
getParams(config_file_name, priv_nh);
|
||||
getParams(config_file_name, name_, nh);
|
||||
|
||||
// create a thread to handle updating the map
|
||||
stop_updates_ = false;
|
||||
@@ -80,23 +110,42 @@ Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) :
|
||||
stopped_ = false;
|
||||
}
|
||||
|
||||
void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeHandle& nh)
|
||||
void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::string& name, robot::NodeHandle& nh)
|
||||
{
|
||||
try
|
||||
{
|
||||
std::string folder = ROBOT_COSTMAP_2D_DIR;
|
||||
const char *env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::string folder;
|
||||
if (env_config && std::filesystem::exists(env_config))
|
||||
{
|
||||
folder = std::string(env_config);
|
||||
// robot::log_error("config_directory: %s", folder.c_str());
|
||||
}
|
||||
std::string path_source = getSourceFile(folder,config_file_name);
|
||||
|
||||
YAML::Node config = YAML::LoadFile(path_source);
|
||||
YAML::Node layer = config["robot_costmap_2d"];
|
||||
|
||||
robot::NodeHandle priv_nh(nh, name);
|
||||
|
||||
// A costmap missing a layer, the layers after it or its update thread still looks alive to the
|
||||
// planner, which then drives on a map that never marks obstacles. Refuse to build it instead:
|
||||
// NavigationRuntime::buildCostmaps() turns the exception into an initialization error and the
|
||||
// host never reports READY. The destructor does not run when the constructor throws, so the
|
||||
// layered costmap (and the layers already added to it) is released here.
|
||||
const auto fail = [this](const std::string& what) {
|
||||
delete layered_costmap_;
|
||||
layered_costmap_ = NULL;
|
||||
throw std::runtime_error("costmap '" + name_ + "': " + what);
|
||||
};
|
||||
|
||||
std::string global_frame =
|
||||
loadParam(layer, "global_frame", std::string("map"));
|
||||
std::string robot_base_frame =
|
||||
loadParam(layer, "robot_base_frame", std::string("base_link"));
|
||||
|
||||
if (nh.hasParam("global_frame"))
|
||||
nh.getParam("global_frame", global_frame);
|
||||
if (priv_nh.hasParam("global_frame"))
|
||||
priv_nh.getParam("global_frame", global_frame);
|
||||
|
||||
if (nh.hasParam("robot_base_frame"))
|
||||
nh.getParam("robot_base_frame", robot_base_frame);
|
||||
@@ -112,6 +161,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
{
|
||||
if (last_error + robot::Duration(5.0) < robot::Time::now())
|
||||
{
|
||||
std::string all_frames_string = tf_.allFramesAsString();
|
||||
robot::log_info("[%s:%d]\n INFO: tf allFramesAsString: %s", __FILE__, __LINE__, all_frames_string.c_str());
|
||||
// std::cout << std::fixed << std::setprecision(6) << robot::Time::now().toSec() << std::endl;
|
||||
robot::log_warning("[%s:%d] %0.6f: Timed out waiting for transform from %s to %s to become available before running costmap, tf error: %s\n",
|
||||
__FILE__, __LINE__, robot::Time::now().toSec(), robot_base_frame_.c_str(), global_frame_.c_str(), tf_error.c_str());
|
||||
@@ -130,16 +181,67 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
robot::PluginLoaderHelper loader;
|
||||
|
||||
|
||||
if (nh.hasParam("rolling_window"))
|
||||
nh.getParam("rolling_window", rolling_window);
|
||||
if (priv_nh.hasParam("rolling_window"))
|
||||
priv_nh.getParam("rolling_window", rolling_window);
|
||||
|
||||
if (nh.hasParam("track_unknown_space"))
|
||||
nh.getParam("track_unknown_space", track_unknown_space);
|
||||
if (priv_nh.hasParam("track_unknown_space"))
|
||||
priv_nh.getParam("track_unknown_space", track_unknown_space);
|
||||
|
||||
if (nh.hasParam("library_path"))
|
||||
bool performance_metrics_enabled =
|
||||
loadParam(layer, "performance_metrics_enabled", false);
|
||||
double performance_metrics_period =
|
||||
loadParam(layer, "performance_metrics_period", 5.0);
|
||||
if (priv_nh.hasParam("performance_metrics_enabled"))
|
||||
priv_nh.getParam("performance_metrics_enabled", performance_metrics_enabled);
|
||||
if (priv_nh.hasParam("performance_metrics_period"))
|
||||
priv_nh.getParam("performance_metrics_period", performance_metrics_period);
|
||||
|
||||
int debug_level = loadParam(layer, "debug_level", 0);
|
||||
if (priv_nh.hasParam("debug_level"))
|
||||
priv_nh.getParam("debug_level", debug_level);
|
||||
|
||||
bool snapshot_for_readers = loadParam(layer, "snapshot_for_readers", false);
|
||||
if (priv_nh.hasParam("snapshot_for_readers"))
|
||||
priv_nh.getParam("snapshot_for_readers", snapshot_for_readers);
|
||||
snapshot_enabled_ = snapshot_for_readers;
|
||||
if (debug_level < 0 || debug_level > 2)
|
||||
{
|
||||
robot::log_warning("costmap '%s': debug_level %d out of [0, 2], clamped\n",
|
||||
name_.c_str(), debug_level);
|
||||
debug_level = std::max(0, std::min(debug_level, 2));
|
||||
}
|
||||
|
||||
if (priv_nh.hasParam("library_path"))
|
||||
path_plugins = loader.findLibraryPath(name_);
|
||||
|
||||
layered_costmap_ = new LayeredCostmap(global_frame_, rolling_window, track_unknown_space);
|
||||
layered_costmap_->setPerformanceMetrics(
|
||||
performance_metrics_enabled, performance_metrics_period);
|
||||
layered_costmap_->setDebugLevel(debug_level);
|
||||
|
||||
// find size parameters
|
||||
double map_width_meters = loadParam(layer, "width", 0.0);
|
||||
double map_height_meters = loadParam(layer, "height", 0.0);
|
||||
double resolution = loadParam(layer, "resolution", 0.0);
|
||||
double origin_x = loadParam(layer, "origin_x", 0.0);
|
||||
double origin_y = loadParam(layer, "origin_y", 0.0);
|
||||
|
||||
if (priv_nh.hasParam("width"))
|
||||
priv_nh.getParam("width", map_width_meters);
|
||||
if (priv_nh.hasParam("height"))
|
||||
priv_nh.getParam("height", map_height_meters);
|
||||
if (priv_nh.hasParam("resolution"))
|
||||
priv_nh.getParam("resolution", resolution);
|
||||
if (priv_nh.hasParam("origin_x"))
|
||||
priv_nh.getParam("origin_x", origin_x);
|
||||
if (priv_nh.hasParam("origin_y"))
|
||||
priv_nh.getParam("origin_y", origin_y);
|
||||
|
||||
if (!layered_costmap_->isSizeLocked())
|
||||
{
|
||||
// robot::log_warning("ROBOT origin_x: %f | origin_y: %f", origin_x, origin_y);
|
||||
layered_costmap_->resizeMap((unsigned int)(map_width_meters / resolution),
|
||||
(unsigned int)(map_height_meters / resolution), resolution, origin_x, origin_y);
|
||||
}
|
||||
|
||||
struct PluginConfig
|
||||
{
|
||||
@@ -148,48 +250,26 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
};
|
||||
std::vector<PluginConfig> my_list;
|
||||
|
||||
if(nh.hasParam("plugins"))
|
||||
if(priv_nh.hasParam("plugins"))
|
||||
{
|
||||
my_list.clear();
|
||||
YAML::Node my_plugins = nh.getParamValue("plugins");
|
||||
if (my_plugins && my_plugins.IsSequence())
|
||||
YAML::Node my_plugins = priv_nh.getParamValue("plugins");
|
||||
if (!my_plugins || !my_plugins.IsSequence())
|
||||
fail("plugins: must be a list of {name, type} maps");
|
||||
for (size_t i = 0; i < my_plugins.size(); ++i)
|
||||
{
|
||||
for (size_t i = 0; i < my_plugins.size(); ++i)
|
||||
{
|
||||
YAML::Node plugin_i = my_plugins[i].as<YAML::Node>();
|
||||
YAML::Node plugin_i = my_plugins[i].as<YAML::Node>();
|
||||
// Checked before reading the fields: indexing a scalar entry throws a bare YAML error.
|
||||
if (!plugin_i.IsMap() || !plugin_i["name"] || !plugin_i["type"])
|
||||
fail("plugins: entry " + std::to_string(i) + " must be a map with a name and a type");
|
||||
|
||||
PluginConfig p;
|
||||
p.type = plugin_i["type"].as<std::string>();
|
||||
p.name = plugin_i["name"].as<std::string>();
|
||||
my_list.push_back(p);
|
||||
if (!plugin_i.IsMap())
|
||||
{
|
||||
std::cerr << "Plugins must be specified as maps. We'll use the default recovery behaviors instead." << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!plugin_i["name"] || !plugin_i["type"])
|
||||
{
|
||||
std::cerr << "Plugins must have a name and a type. Using the default recovery behaviors instead." << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
// check for recovery behaviors with the same name
|
||||
std::string name_i = plugin_i["name"].as<std::string>();
|
||||
for (size_t j = i + 1; j < my_plugins.size(); ++j)
|
||||
{
|
||||
YAML::Node plugin_j = my_plugins[j].as<YAML::Node>();
|
||||
if (plugin_j.IsMap() && plugin_j["name"])
|
||||
{
|
||||
std::string name_j = plugin_j["name"].as<std::string>();
|
||||
if (name_i == name_j)
|
||||
{
|
||||
std::cerr << "A plugin with the name " << name_i << " already exists, this is not allowed. Using the default recovery behaviors instead." << std::endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PluginConfig p;
|
||||
p.type = plugin_i["type"].as<std::string>();
|
||||
p.name = plugin_i["name"].as<std::string>();
|
||||
for (const auto& known : my_list)
|
||||
if (known.name == p.name)
|
||||
fail("plugins: the name '" + p.name + "' is used twice; each layer needs its own name");
|
||||
my_list.push_back(p);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -205,12 +285,12 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
robot::NodeHandle private_nh("~");
|
||||
for (auto& info : my_list)
|
||||
{
|
||||
try
|
||||
{
|
||||
// copyParentParameters(pname, type, private_nh);
|
||||
copyParentParameters(name_, info.name, info.type, private_nh);
|
||||
creators_.push_back(
|
||||
boost::dll::import_alias<PluginLayerPtr()>(
|
||||
path_plugins, info.type, boost::dll::load_mode::append_decorations)
|
||||
@@ -221,10 +301,10 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
plugin->initialize(layered_costmap_,name_ + "/" + info.name, &tf_);
|
||||
layered_costmap_->addPlugin(plugin);
|
||||
}
|
||||
catch (std::exception &ex)
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error("Failed to create the %s, are you sure it is properly registered and that the containing library is built? Exception: %s\n", info.name.c_str(), ex.what());
|
||||
return;
|
||||
// Covers a missing library or symbol as well as a layer rejecting its parameters.
|
||||
fail("layer '" + info.name + "' (" + info.type + "): " + ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,13 +312,15 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
new_footprint = loadFootprint(layer["footprint"], new_footprint);
|
||||
transform_tolerance_ = loadParam(layer, "transform_tolerance", 0.0);
|
||||
|
||||
if (nh.hasParam("footprint"))
|
||||
if (priv_nh.hasParam("footprint"))
|
||||
{
|
||||
std::cout <<"FOOTPRINT ROBOT:"<<std::endl;
|
||||
new_footprint = makeFootprintFromParams(nh);
|
||||
new_footprint = makeFootprintFromParams(priv_nh);
|
||||
}
|
||||
|
||||
if (nh.hasParam("transform_tolerance"))
|
||||
nh.getParam("transform_tolerance", transform_tolerance_);
|
||||
// robot::log_info("transform_tolerance: %d", transform_tolerance_);
|
||||
|
||||
setUnpaddedRobotFootprint(new_footprint);
|
||||
|
||||
@@ -254,31 +336,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
map_update_thread_shutdown_ = false;
|
||||
double map_update_frequency = loadParam(layer, "update_frequency", 0.0);
|
||||
|
||||
// find size parameters
|
||||
double map_width_meters = loadParam(layer, "width", 0.0);
|
||||
double map_height_meters = loadParam(layer, "height", 0.0);
|
||||
double resolution = loadParam(layer, "resolution", 0.0);
|
||||
double origin_x = loadParam(layer, "origin_x", 0.0);
|
||||
double origin_y = loadParam(layer, "origin_y", 0.0);
|
||||
|
||||
if (nh.hasParam("update_frequency"))
|
||||
nh.getParam("update_frequency", map_update_frequency);
|
||||
if (nh.hasParam("width"))
|
||||
nh.getParam("width", map_width_meters);
|
||||
if (nh.hasParam("height"))
|
||||
nh.getParam("height", map_height_meters);
|
||||
if (nh.hasParam("resolution"))
|
||||
nh.getParam("resolution", resolution);
|
||||
if (nh.hasParam("origin_x"))
|
||||
nh.getParam("origin_x", origin_x);
|
||||
if (nh.hasParam("origin_y"))
|
||||
nh.getParam("origin_y", origin_y);
|
||||
|
||||
if (!layered_costmap_->isSizeLocked())
|
||||
{
|
||||
layered_costmap_->resizeMap((unsigned int)(map_width_meters / resolution),
|
||||
(unsigned int)(map_height_meters / resolution), resolution, origin_x, origin_y);
|
||||
}
|
||||
if (priv_nh.hasParam("update_frequency"))
|
||||
priv_nh.getParam("update_frequency", map_update_frequency);
|
||||
|
||||
// If the padding has changed, call setUnpaddedRobotFootprint() to
|
||||
// re-apply the padding.
|
||||
@@ -292,8 +351,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
}
|
||||
|
||||
double robot_radius = loadParam(layer, "robot_radius", 0.0);
|
||||
if (nh.hasParam("robot_radius"))
|
||||
nh.getParam("robot_radius", robot_radius);
|
||||
if (priv_nh.hasParam("robot_radius"))
|
||||
priv_nh.getParam("robot_radius", robot_radius);
|
||||
readFootprintFromConfig(new_footprint, unpadded_footprint_, robot_radius);
|
||||
|
||||
// only construct the thread if the frequency is positive
|
||||
@@ -302,8 +361,93 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name, robot::NodeH
|
||||
}
|
||||
catch (const YAML::BadFile& e)
|
||||
{
|
||||
std::cerr << "Cannot open YAML file: " << e.what() << std::endl;
|
||||
return;
|
||||
// costmap_params.yaml is read before layered_costmap_ exists; delete is a no-op on NULL.
|
||||
delete layered_costmap_;
|
||||
layered_costmap_ = NULL;
|
||||
throw std::runtime_error("costmap '" + name_ + "': cannot open the default file " + config_file_name +
|
||||
" under $PNKX_NAV_CORE_CONFIG_DIR/config: " + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
|
||||
const std::string& plugin_name,
|
||||
const std::string& plugin_type,
|
||||
robot::NodeHandle& nh)
|
||||
{
|
||||
// Step 2 of the layer config flow. A layer reads its default file, then overrides each key found
|
||||
// in "<costmap>/<plugin>". This copies the keys of the shared "<plugin>:" block there first, so the
|
||||
// lists below must hold every key the layer reads with hasParam(): a key missing here is ignored
|
||||
// without a word when it is set in the shared block. A copied key overwrites the same key in
|
||||
// "<costmap>/<plugin>". Types follow what the layer reads.
|
||||
robot::NodeHandle costmap_nh(nh, costmap_name);
|
||||
robot::NodeHandle costmap_plugin_nh(costmap_nh, plugin_name);
|
||||
robot::NodeHandle plugin_nh(nh, plugin_name);
|
||||
|
||||
// observation_sources, then the keys of each source under "<plugin>/<source>/".
|
||||
const auto move_sources = [&](const auto& move_source_keys) {
|
||||
std::string topics_string;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
|
||||
std::stringstream ss(topics_string);
|
||||
std::string source;
|
||||
while (ss >> source)
|
||||
{
|
||||
robot::NodeHandle plugin_nh_element(plugin_nh, source);
|
||||
robot::NodeHandle costmap_plugin_nh_element(costmap_plugin_nh, source);
|
||||
move_source_keys(plugin_nh_element, costmap_plugin_nh_element);
|
||||
}
|
||||
};
|
||||
|
||||
if (plugin_type == "StaticLayer")
|
||||
{
|
||||
move_parameters<std::string>(plugin_nh, costmap_plugin_nh, {"map_topic", "base_frame_id"});
|
||||
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"unknown_cost_value", "lethal_cost_threshold"});
|
||||
move_parameters<bool>(plugin_nh, costmap_plugin_nh,
|
||||
{"enabled", "track_unknown_space", "first_map_only", "subscribe_to_updates",
|
||||
"use_maximum", "trinary_costmap"});
|
||||
}
|
||||
else if (plugin_type == "ObstacleLayer" || plugin_type == "VoxelLayer")
|
||||
{
|
||||
// VoxelLayer runs ObstacleLayer::getParams() first, so it reads these keys too.
|
||||
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"max_obstacle_height", "transform_tolerance"});
|
||||
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"combination_method"});
|
||||
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"track_unknown_space", "footprint_clearing_enabled"});
|
||||
if (plugin_type == "VoxelLayer")
|
||||
{
|
||||
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"origin_z", "z_resolution", "unknown_threshold"});
|
||||
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"z_voxels", "mark_threshold"});
|
||||
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"enabled"});
|
||||
}
|
||||
move_sources([](robot::NodeHandle& from, robot::NodeHandle& to) {
|
||||
move_parameters<std::string>(from, to, {"topic", "sensor_frame", "data_type"});
|
||||
move_parameters<double>(from, to, {"observation_persistence", "expected_update_rate", "min_obstacle_height",
|
||||
"max_obstacle_height", "obstacle_range", "raytrace_range"});
|
||||
move_parameters<bool>(from, to, {"clearing", "marking", "inf_is_valid"});
|
||||
});
|
||||
}
|
||||
else if (plugin_type == "InflationLayer")
|
||||
{
|
||||
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"cost_scaling_factor", "inflation_radius"});
|
||||
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"enabled", "inflate_unknown"});
|
||||
}
|
||||
else if (plugin_type == "DepthCameraObstacleLayer")
|
||||
{
|
||||
move_parameters<bool>(plugin_nh, costmap_plugin_nh,
|
||||
{"track_unknown_space", "enabled", "footprint_clearing_enabled",
|
||||
"enable_near_blocked_protection", "use_voxelized_observation", "use_global_frame_to_mark",
|
||||
"clear_touches_bounds", "debug/stats"});
|
||||
move_parameters<int>(plugin_nh, costmap_plugin_nh,
|
||||
{"combination_method", "number_points_considered_as_blocked", "ec_cluster_min_size",
|
||||
"size_of_cluster_rejection", "number_clearing_threshold"});
|
||||
move_parameters<double>(plugin_nh, costmap_plugin_nh,
|
||||
{"forced_clearing_distance", "ec_seg_distance", "voxel_resolution", "check_radius",
|
||||
"transform_tolerance", "debug/stats_period"});
|
||||
move_sources([](robot::NodeHandle& from, robot::NodeHandle& to) {
|
||||
move_parameters<std::string>(from, to, {"topic", "sensor_frame"});
|
||||
move_parameters<bool>(from, to, {"sensor_frame_is_optical", "marking", "inf_is_valid"});
|
||||
move_parameters<double>(from, to, {"observation_persistence", "expected_update_rate", "min_obstacle_height",
|
||||
"max_obstacle_height", "FOV_V", "FOV_W", "min_detect_distance",
|
||||
"max_detect_distance"});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,6 +456,30 @@ void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs:
|
||||
setUnpaddedRobotFootprint(toPointVector(footprint));
|
||||
}
|
||||
|
||||
void Costmap2DROBOT::refreshSnapshot()
|
||||
{
|
||||
if (!snapshot_enabled_ || layered_costmap_ == NULL)
|
||||
return;
|
||||
|
||||
Costmap2D* master = layered_costmap_->getCostmap();
|
||||
// Master mutex held only for the copy (~us for a local-costmap grid), not
|
||||
// for the reader's whole computation — that is the entire point.
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*(master->getMutex()));
|
||||
costmap_snapshot_.copyFrom(*master);
|
||||
}
|
||||
|
||||
Costmap2D* Costmap2DROBOT::getCostmapForRead()
|
||||
{
|
||||
if (!snapshot_enabled_)
|
||||
return getCostmap();
|
||||
|
||||
// First read before any refresh (e.g. planner initialize probing the grid):
|
||||
// fill the snapshot once so the reader never sees an empty map.
|
||||
if (costmap_snapshot_.getCharMap() == NULL)
|
||||
refreshSnapshot();
|
||||
return &costmap_snapshot_;
|
||||
}
|
||||
|
||||
Costmap2DROBOT::~Costmap2DROBOT()
|
||||
{
|
||||
map_update_thread_shutdown_ = true;
|
||||
@@ -357,6 +525,7 @@ void Costmap2DROBOT::readFootprintFromConfig(const std::vector<robot_geometry_ms
|
||||
|
||||
void Costmap2DROBOT::setUnpaddedRobotFootprint(const std::vector<robot_geometry_msgs::Point>& points)
|
||||
{
|
||||
boost::recursive_mutex::scoped_lock lock(configuration_mutex_);
|
||||
unpadded_footprint_ = points;
|
||||
padded_footprint_ = points;
|
||||
padFootprint(padded_footprint_, footprint_padding_);
|
||||
@@ -373,6 +542,11 @@ void Costmap2DROBOT::checkMovement()
|
||||
|
||||
void Costmap2DROBOT::mapUpdateLoop(double frequency)
|
||||
{
|
||||
// Name the thread so `top -H` / `pidstat -t` can attribute CPU to this
|
||||
// costmap directly (kernel limit: 15 chars + NUL).
|
||||
std::string thread_name = "cm_" + name_;
|
||||
pthread_setname_np(pthread_self(), thread_name.substr(0, 15).c_str());
|
||||
|
||||
std::cout << robot::Time::now().toNSec()<< " :Costmap2DROBOT::mapUpdateLoop updateMap\n";
|
||||
robot::Rate r(frequency);
|
||||
while (!map_update_thread_shutdown_)
|
||||
@@ -381,13 +555,14 @@ void Costmap2DROBOT::mapUpdateLoop(double frequency)
|
||||
r.sleep();
|
||||
// make sure to sleep for the remainder of our cycle time
|
||||
if (r.cycleTime() > robot::Duration(1 / frequency))
|
||||
printf("Map update loop missed its desired rate of %.4fHz... the loop actually took %.4f seconds\n", frequency,
|
||||
robot::log_warning("Map update %s loop missed its desired rate of %.4fHz... the loop actually took %.4f seconds\n", name_.c_str(), frequency,
|
||||
r.cycleTime().toSec());
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2DROBOT::updateMap()
|
||||
{
|
||||
boost::recursive_mutex::scoped_lock lock(configuration_mutex_);
|
||||
if (!stop_updates_)
|
||||
{
|
||||
// get global pose
|
||||
@@ -397,17 +572,19 @@ void Costmap2DROBOT::updateMap()
|
||||
double x = pose.pose.position.x,
|
||||
y = pose.pose.position.y,
|
||||
yaw = data_convert::getYaw(pose.pose.orientation);
|
||||
// robot::log_error("ROBOT POSE: %f | %f | %f",x,y,yaw);
|
||||
layered_costmap_->updateMap(x, y, yaw);
|
||||
robot_geometry_msgs::PolygonStamped footprint;
|
||||
footprint.header.frame_id = global_frame_;
|
||||
footprint.header.stamp = robot::Time::now();
|
||||
transformFootprint(x, y, yaw, padded_footprint_, footprint);
|
||||
|
||||
footprint_.header.frame_id = global_frame_;
|
||||
footprint_.header.stamp = robot::Time::now();
|
||||
transformFootprint(x, y, yaw, padded_footprint_, footprint_);
|
||||
|
||||
initialized_ = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Costmap2DROBOT::start()
|
||||
{
|
||||
// if(name_.find("global_costmap")) ROS_WARN("Costmap2DROBOT::start");
|
||||
@@ -431,11 +608,11 @@ void Costmap2DROBOT::start()
|
||||
robot::Rate r(100.0);
|
||||
while (!initialized_ && map_update_thread_)
|
||||
{
|
||||
// if (robot::Time::now() - start_time > robot::Duration(5.0))
|
||||
// {
|
||||
// printf("Costmap2DROBOT::start() timed out waiting for costmap to initialize or map_update_thread\n");
|
||||
// break;
|
||||
// }
|
||||
if (robot::Time::now() - start_time > robot::Duration(5.0))
|
||||
{
|
||||
robot::log_warning_throttle(3.0, "Costmap2DROBOT::start() timed out waiting for costmap to initialize or map_update_thread\n");
|
||||
break;
|
||||
}
|
||||
r.sleep();
|
||||
}
|
||||
}
|
||||
@@ -474,7 +651,7 @@ void Costmap2DROBOT::resume()
|
||||
{
|
||||
if (robot::Time::now() - start_time > robot::Duration(5.0))
|
||||
{
|
||||
printf("Costmap2DROBOT::resume() timed out waiting for costmap to initialize\n");
|
||||
robot::log_warning("Costmap2DROBOT::resume() timed out waiting for costmap to initialize\n");
|
||||
break;
|
||||
}
|
||||
r.sleep();
|
||||
@@ -500,6 +677,13 @@ bool Costmap2DROBOT::getRobotPose(robot_geometry_msgs::PoseStamped& global_pose)
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped robot_pose;
|
||||
robot_geometry_msgs::Pose pose_default;
|
||||
pose_default.orientation.x = 0;
|
||||
pose_default.orientation.y = 0;
|
||||
pose_default.orientation.z = 0;
|
||||
pose_default.orientation.w = 1;
|
||||
pose_default.position.x = 0;
|
||||
pose_default.position.y = 0;
|
||||
pose_default.position.z = 0;
|
||||
global_pose.pose = pose_default;
|
||||
robot_pose.pose = pose_default;
|
||||
|
||||
@@ -510,44 +694,30 @@ bool Costmap2DROBOT::getRobotPose(robot_geometry_msgs::PoseStamped& global_pose)
|
||||
// get the global pose of the robot
|
||||
try
|
||||
{
|
||||
// use current time if possible (makes sure it's not in the future)
|
||||
if (tf_.canTransform(global_frame_, robot_base_frame_, data_convert::convertTime(current_time)))
|
||||
{
|
||||
tf3::TransformStampedMsg transform = tf_.lookupTransform(global_frame_, robot_base_frame_, data_convert::convertTime(current_time));
|
||||
tf3::doTransform(robot_pose, global_pose, transform);
|
||||
}
|
||||
// use the latest otherwise
|
||||
else
|
||||
{
|
||||
// tf_.transform(robot_pose, global_pose, global_frame_);
|
||||
tf3::TransformStampedMsg transform = tf_.lookupTransform(
|
||||
global_frame_, // frame đích
|
||||
robot_base_frame_, // frame nguồn
|
||||
data_convert::convertTime(robot_pose.header.stamp)
|
||||
);
|
||||
tf3::doTransform(robot_pose, global_pose, transform);
|
||||
}
|
||||
const tf3::TransformStampedMsg transform =
|
||||
tf_.lookupTransform(global_frame_, robot_base_frame_, tf3::Time());
|
||||
tf3::doTransform(robot_pose, global_pose, transform);
|
||||
}
|
||||
catch (tf3::LookupException& ex)
|
||||
{
|
||||
printf("Cost Map No Transform available Error looking up robot pose: %s\n", ex.what());
|
||||
robot::log_error("Costmap2DROBOT %s No Transform available Error looking up robot pose: %s\n", name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
catch (tf3::ConnectivityException& ex)
|
||||
{
|
||||
printf("Connectivity Error looking up robot pose: %s\n", ex.what());
|
||||
robot::log_error("Costmap2DROBOT %s Connectivity Error looking up robot pose: %s\n", name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
catch (tf3::ExtrapolationException& ex)
|
||||
{
|
||||
printf("Extrapolation Error looking up robot pose: %s\n", ex.what());
|
||||
// robot::log_error("Costmap2DROBOT %s Extrapolation Error looking up robot pose: %s\n", name_.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
// ROS_INFO_THROTTLE(1.0, "Time Delay %f , p %f %f", current_time.toSec() - global_pose.header.stamp.toSec(), global_pose.pose.position.x, global_pose.pose.position.y);
|
||||
// check global_pose timeout
|
||||
if (!global_pose.header.stamp.isZero() && current_time.toSec() - global_pose.header.stamp.toSec() > transform_tolerance_)
|
||||
{
|
||||
printf("Costmap2DROBOT transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n",
|
||||
robot::log_warning("Costmap2DROBOT %s transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n", name_.c_str(),
|
||||
current_time.toSec(), global_pose.header.stamp.toSec(), transform_tolerance_);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -174,15 +174,15 @@ bool makeFootprintFromString(const std::string& footprint_string, std::vector<ro
|
||||
|
||||
if (error != "")
|
||||
{
|
||||
printf("Error parsing footprint parameter: '%s'\n", error.c_str());
|
||||
printf(" Footprint string was '%s'.\n", footprint_string.c_str());
|
||||
robot::log_error("Error parsing footprint parameter: '%s'\n", error.c_str());
|
||||
robot::log_error(" Footprint string was '%s'.\n", footprint_string.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
// convert vvf into points.
|
||||
if (vvf.size() < 3)
|
||||
{
|
||||
printf("You must specify at least three points for the robot footprint, reverting to previous footprint.\n");
|
||||
robot::log_error("You must specify at least three points for the robot footprint, reverting to previous footprint.\n");
|
||||
return false;
|
||||
}
|
||||
footprint.reserve(vvf.size());
|
||||
@@ -198,7 +198,7 @@ bool makeFootprintFromString(const std::string& footprint_string, std::vector<ro
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Points in the footprint specification must be pairs of numbers. Found a point with %d numbers.\n",
|
||||
robot::log_error("Points in the footprint specification must be pairs of numbers. Found a point with %d numbers.\n",
|
||||
int(vvf[ i ].size()));
|
||||
return false;
|
||||
}
|
||||
@@ -256,7 +256,7 @@ double getNumberFromXMLRPC(robot_xmlrpcpp::XmlRpcValue& value, const std::string
|
||||
value.getType() != robot_xmlrpcpp::XmlRpcValue::TypeDouble)
|
||||
{
|
||||
std::string& value_string = value;
|
||||
printf("Values in the footprint specification (param %s) must be numbers. Found value %s.\n",
|
||||
robot::log_error("Values in the footprint specification (param %s) must be numbers. Found value %s.\n",
|
||||
full_param_name.c_str(), value_string.c_str());
|
||||
throw std::runtime_error("Values in the footprint specification must be numbers");
|
||||
}
|
||||
@@ -270,7 +270,7 @@ std::vector<robot_geometry_msgs::Point> makeFootprintFromXMLRPC(robot_xmlrpcpp::
|
||||
if (footprint_xmlrpc.getType() != robot_xmlrpcpp::XmlRpcValue::TypeArray ||
|
||||
footprint_xmlrpc.size() < 3)
|
||||
{
|
||||
printf("The footprint must be specified as list of lists on the parameter server, %s was specified as %s\n",
|
||||
robot::log_error("The footprint must be specified as list of lists on the parameter server, %s was specified as %s\n",
|
||||
full_param_name.c_str(), std::string(footprint_xmlrpc).c_str());
|
||||
throw std::runtime_error("The footprint must be specified as list of lists on the parameter server with at least "
|
||||
"3 points eg: [[x1, y1], [x2, y2], ..., [xn, yn]]");
|
||||
@@ -286,7 +286,7 @@ std::vector<robot_geometry_msgs::Point> makeFootprintFromXMLRPC(robot_xmlrpcpp::
|
||||
if (point.getType() != robot_xmlrpcpp::XmlRpcValue::TypeArray ||
|
||||
point.size() != 2)
|
||||
{
|
||||
printf("The footprint (parameter %s) must be specified as list of lists on the parameter server eg: "
|
||||
robot::log_error("The footprint (parameter %s) must be specified as list of lists on the parameter server eg: "
|
||||
"[[x1, y1], [x2, y2], ..., [xn, yn]], but this spec is not of that form.\n",
|
||||
full_param_name.c_str());
|
||||
throw std::runtime_error("The footprint must be specified as list of lists on the parameter server eg: "
|
||||
|
||||
@@ -69,6 +69,119 @@ namespace robot_costmap_2d
|
||||
costmap_.setDefaultValue(NO_INFORMATION);
|
||||
else
|
||||
costmap_.setDefaultValue(FREE_SPACE);
|
||||
performance_window_start_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
void LayeredCostmap::setPerformanceMetrics(bool enabled, double reporting_period_seconds)
|
||||
{
|
||||
performance_metrics_enabled_ = enabled;
|
||||
performance_metrics_period_seconds_ = reporting_period_seconds > 0.0 ? reporting_period_seconds : 5.0;
|
||||
resetPerformanceMetrics();
|
||||
}
|
||||
|
||||
void LayeredCostmap::setDebugLevel(int level)
|
||||
{
|
||||
debug_level_ = std::max(0, std::min(level, 2));
|
||||
}
|
||||
|
||||
void LayeredCostmap::resetPerformanceMetrics()
|
||||
{
|
||||
performance_window_start_ = std::chrono::steady_clock::now();
|
||||
performance_cycle_nanoseconds_ = 0;
|
||||
performance_reset_nanoseconds_ = 0;
|
||||
performance_cycles_ = 0;
|
||||
performance_cycle_samples_.clear();
|
||||
performance_cycle_samples_.reserve(128);
|
||||
layer_performance_.assign(plugins_.size(), LayerPerformance());
|
||||
lock_wait_nanoseconds_ = 0;
|
||||
lock_wait_max_nanoseconds_ = 0;
|
||||
lock_hold_nanoseconds_ = 0;
|
||||
window_cells_sum_ = 0;
|
||||
window_cells_max_ = 0;
|
||||
performance_empty_cycles_ = 0;
|
||||
}
|
||||
|
||||
void LayeredCostmap::maybeReportPerformance()
|
||||
{
|
||||
// debug_level >= 1 also reports windows with only empty cycles, so an idle
|
||||
// costmap (e.g. the global one with obstacle updates disabled) stays visible.
|
||||
const bool has_activity = performance_cycles_ > 0 ||
|
||||
(debug_level_ >= 1 && performance_empty_cycles_ > 0);
|
||||
if (!performance_metrics_enabled_ || !has_activity)
|
||||
return;
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const double elapsed = std::chrono::duration<double>(now - performance_window_start_).count();
|
||||
if (elapsed < performance_metrics_period_seconds_)
|
||||
return;
|
||||
|
||||
if (performance_cycles_ > 0)
|
||||
{
|
||||
const double average_cycle_ms =
|
||||
static_cast<double>(performance_cycle_nanoseconds_) / performance_cycles_ / 1.0e6;
|
||||
const double average_reset_ms =
|
||||
static_cast<double>(performance_reset_nanoseconds_) / performance_cycles_ / 1.0e6;
|
||||
std::sort(performance_cycle_samples_.begin(), performance_cycle_samples_.end());
|
||||
const auto percentile_ms = [this](double percentile) {
|
||||
if (performance_cycle_samples_.empty())
|
||||
return 0.0;
|
||||
const std::size_t index = static_cast<std::size_t>(
|
||||
percentile * static_cast<double>(performance_cycle_samples_.size() - 1));
|
||||
return static_cast<double>(performance_cycle_samples_[index]) / 1.0e6;
|
||||
};
|
||||
robot::log_info(
|
||||
"Costmap performance: cycles=%llu avg_cycle_ms=%.3f p95_cycle_ms=%.3f "
|
||||
"p99_cycle_ms=%.3f avg_reset_ms=%.3f\n",
|
||||
static_cast<unsigned long long>(performance_cycles_), average_cycle_ms,
|
||||
percentile_ms(0.95), percentile_ms(0.99), average_reset_ms);
|
||||
|
||||
for (std::size_t i = 0; i < plugins_.size() && i < layer_performance_.size(); ++i)
|
||||
{
|
||||
const LayerPerformance& stats = layer_performance_[i];
|
||||
const double average_bounds_ms = stats.bounds_calls == 0 ? 0.0 :
|
||||
static_cast<double>(stats.bounds_nanoseconds) / stats.bounds_calls / 1.0e6;
|
||||
const double average_costs_ms = stats.costs_calls == 0 ? 0.0 :
|
||||
static_cast<double>(stats.costs_nanoseconds) / stats.costs_calls / 1.0e6;
|
||||
robot::log_info(
|
||||
"Costmap layer [%s]: avg_bounds_ms=%.3f avg_costs_ms=%.3f\n",
|
||||
plugins_[i]->getName().c_str(), average_bounds_ms, average_costs_ms);
|
||||
}
|
||||
}
|
||||
|
||||
if (debug_level_ >= 1)
|
||||
{
|
||||
const std::uint64_t lock_samples = performance_cycles_ + performance_empty_cycles_;
|
||||
const double average_lock_wait_ms = lock_samples == 0 ? 0.0 :
|
||||
static_cast<double>(lock_wait_nanoseconds_) / lock_samples / 1.0e6;
|
||||
const double max_lock_wait_ms = static_cast<double>(lock_wait_max_nanoseconds_) / 1.0e6;
|
||||
const double average_lock_hold_ms = performance_cycles_ == 0 ? 0.0 :
|
||||
static_cast<double>(lock_hold_nanoseconds_) / performance_cycles_ / 1.0e6;
|
||||
const std::uint64_t average_window_cells = performance_cycles_ == 0 ? 0 :
|
||||
window_cells_sum_ / performance_cycles_;
|
||||
robot::log_info(
|
||||
"Costmap debug: lock_wait avg=%.3f max=%.3f [ms], lock_hold avg=%.3f [ms], "
|
||||
"window avg=%llu max=%llu [cells], empty_cycles=%llu\n",
|
||||
average_lock_wait_ms, max_lock_wait_ms, average_lock_hold_ms,
|
||||
static_cast<unsigned long long>(average_window_cells),
|
||||
static_cast<unsigned long long>(window_cells_max_),
|
||||
static_cast<unsigned long long>(performance_empty_cycles_));
|
||||
}
|
||||
|
||||
if (debug_level_ >= 2 && performance_cycles_ > 0)
|
||||
{
|
||||
for (std::size_t i = 0; i < plugins_.size() && i < layer_performance_.size(); ++i)
|
||||
{
|
||||
const LayerPerformance& stats = layer_performance_[i];
|
||||
if (stats.bounds_calls == 0)
|
||||
continue;
|
||||
const double average_grow = stats.bounds_grow_m2_sum / stats.bounds_calls;
|
||||
robot::log_info(
|
||||
"Costmap debug layer [%s]: bounds_grow avg=%.2f max=%.2f [m^2]\n",
|
||||
plugins_[i]->getName().c_str(), average_grow, stats.bounds_grow_m2_max);
|
||||
}
|
||||
}
|
||||
|
||||
resetPerformanceMetrics();
|
||||
}
|
||||
|
||||
LayeredCostmap::~LayeredCostmap()
|
||||
@@ -94,9 +207,23 @@ namespace robot_costmap_2d
|
||||
|
||||
void LayeredCostmap::updateMap(double robot_x, double robot_y, double robot_yaw)
|
||||
{
|
||||
const auto cycle_start = performance_metrics_enabled_ ? std::chrono::steady_clock::now() :
|
||||
std::chrono::steady_clock::time_point();
|
||||
// Lock for the remainder of this function, some plugins (e.g. VoxelLayer)
|
||||
// implement thread unsafe updateBounds() functions.
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_.getMutex()));
|
||||
// Time spent acquiring the master mutex is the contention with planner
|
||||
// reads — measured separately from our own work (hold time) so the two
|
||||
// show up as distinct numbers in the debug report.
|
||||
const auto lock_acquired = performance_metrics_enabled_ ? std::chrono::steady_clock::now() :
|
||||
std::chrono::steady_clock::time_point();
|
||||
if (performance_metrics_enabled_)
|
||||
{
|
||||
const std::uint64_t wait_ns = static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(lock_acquired - cycle_start).count());
|
||||
lock_wait_nanoseconds_ += wait_ns;
|
||||
lock_wait_max_nanoseconds_ = std::max(lock_wait_max_nanoseconds_, wait_ns);
|
||||
}
|
||||
|
||||
// if we're using a rolling buffer costmap... we need to update the origin using the robot's position
|
||||
if (rolling_window_)
|
||||
@@ -111,24 +238,57 @@ namespace robot_costmap_2d
|
||||
|
||||
minx_ = miny_ = 1e30;
|
||||
maxx_ = maxy_ = -1e30;
|
||||
if (performance_metrics_enabled_ && layer_performance_.size() != plugins_.size())
|
||||
layer_performance_.assign(plugins_.size(), LayerPerformance());
|
||||
|
||||
for (vector<boost::shared_ptr<Layer>>::iterator plugin = plugins_.begin(); plugin != plugins_.end();
|
||||
++plugin)
|
||||
for (std::size_t plugin_index = 0; plugin_index < plugins_.size(); ++plugin_index)
|
||||
{
|
||||
if (!(*plugin)->isEnabled())
|
||||
const boost::shared_ptr<Layer>& plugin = plugins_[plugin_index];
|
||||
if (!plugin->isEnabled())
|
||||
continue;
|
||||
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_);
|
||||
const auto bounds_start = performance_metrics_enabled_ ? std::chrono::steady_clock::now() :
|
||||
std::chrono::steady_clock::time_point();
|
||||
plugin->updateBounds(robot_x, robot_y, robot_yaw, &minx_, &miny_, &maxx_, &maxy_);
|
||||
if (performance_metrics_enabled_)
|
||||
{
|
||||
layer_performance_[plugin_index].bounds_nanoseconds +=
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now() - bounds_start).count();
|
||||
++layer_performance_[plugin_index].bounds_calls;
|
||||
if (debug_level_ >= 2 && plugin_index < layer_performance_.size())
|
||||
{
|
||||
// Rect area clamped to the map extent, so the inflation layer's
|
||||
// "reinflate everything" request (+/-FLT_MAX) stays finite.
|
||||
const auto clamped_area = [this](double mnx, double mny, double mxx, double mxy) {
|
||||
const double ox = costmap_.getOriginX();
|
||||
const double oy = costmap_.getOriginY();
|
||||
const double ex = ox + costmap_.getSizeInMetersX();
|
||||
const double ey = oy + costmap_.getSizeInMetersY();
|
||||
const double cx0 = std::max(mnx, ox), cy0 = std::max(mny, oy);
|
||||
const double cx1 = std::min(mxx, ex), cy1 = std::min(mxy, ey);
|
||||
return (cx1 > cx0 && cy1 > cy0) ? (cx1 - cx0) * (cy1 - cy0) : 0.0;
|
||||
};
|
||||
const double grow = clamped_area(minx_, miny_, maxx_, maxy_) -
|
||||
clamped_area(prev_minx, prev_miny, prev_maxx, prev_maxy);
|
||||
if (grow > 0.0)
|
||||
{
|
||||
layer_performance_[plugin_index].bounds_grow_m2_sum += grow;
|
||||
layer_performance_[plugin_index].bounds_grow_m2_max =
|
||||
std::max(layer_performance_[plugin_index].bounds_grow_m2_max, grow);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (minx_ > prev_minx || miny_ > prev_miny || maxx_ < prev_maxx || maxy_ < prev_maxy)
|
||||
{
|
||||
printf("Illegal bounds change, was [tl: (%f, %f), br: (%f, %f)], but "
|
||||
robot::log_error("Illegal bounds change, was [tl: (%f, %f), br: (%f, %f)], but "
|
||||
"is now [tl: (%f, %f), br: (%f, %f)]. The offending layer is %s\n",
|
||||
prev_minx, prev_miny, prev_maxx, prev_maxy,
|
||||
minx_, miny_, maxx_, maxy_,
|
||||
(*plugin)->getName().c_str());
|
||||
plugin->getName().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,18 +301,44 @@ namespace robot_costmap_2d
|
||||
y0 = std::max(0, y0);
|
||||
yn = std::min(int(costmap_.getSizeInCellsY()), yn + 1);
|
||||
|
||||
printf("Updating area x: [%d, %d] y: [%d, %d]\n", x0, xn, y0, yn);
|
||||
|
||||
if (xn < x0 || yn < y0)
|
||||
return;
|
||||
|
||||
costmap_.resetMap(x0, y0, xn, yn);
|
||||
|
||||
for (vector<boost::shared_ptr<Layer>>::iterator plugin = plugins_.begin(); plugin != plugins_.end();
|
||||
++plugin)
|
||||
{
|
||||
if ((*plugin)->isEnabled())
|
||||
(*plugin)->updateCosts(costmap_, x0, y0, xn, yn);
|
||||
// No dirty region this cycle (idle costmap): count it so the debug
|
||||
// report still fires and the idle costmap stays visible in the log.
|
||||
if (performance_metrics_enabled_)
|
||||
{
|
||||
++performance_empty_cycles_;
|
||||
maybeReportPerformance();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const auto reset_start = performance_metrics_enabled_ ? std::chrono::steady_clock::now() :
|
||||
std::chrono::steady_clock::time_point();
|
||||
costmap_.resetMap(x0, y0, xn, yn);
|
||||
if (performance_metrics_enabled_)
|
||||
{
|
||||
performance_reset_nanoseconds_ +=
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now() - reset_start).count();
|
||||
}
|
||||
|
||||
for (std::size_t plugin_index = 0; plugin_index < plugins_.size(); ++plugin_index)
|
||||
{
|
||||
const boost::shared_ptr<Layer>& plugin = plugins_[plugin_index];
|
||||
if (!plugin->isEnabled())
|
||||
continue;
|
||||
|
||||
const auto costs_start = performance_metrics_enabled_ ? std::chrono::steady_clock::now() :
|
||||
std::chrono::steady_clock::time_point();
|
||||
plugin->updateCosts(costmap_, x0, y0, xn, yn);
|
||||
if (performance_metrics_enabled_)
|
||||
{
|
||||
layer_performance_[plugin_index].costs_nanoseconds +=
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now() - costs_start).count();
|
||||
++layer_performance_[plugin_index].costs_calls;
|
||||
}
|
||||
}
|
||||
|
||||
bx0_ = x0;
|
||||
@@ -161,6 +347,23 @@ namespace robot_costmap_2d
|
||||
byn_ = yn;
|
||||
|
||||
initialized_ = true;
|
||||
|
||||
if (performance_metrics_enabled_)
|
||||
{
|
||||
const auto cycle_end = std::chrono::steady_clock::now();
|
||||
const std::uint64_t cycle_nanoseconds = static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(cycle_end - cycle_start).count());
|
||||
performance_cycle_nanoseconds_ += cycle_nanoseconds;
|
||||
performance_cycle_samples_.push_back(cycle_nanoseconds);
|
||||
++performance_cycles_;
|
||||
lock_hold_nanoseconds_ += static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(cycle_end - lock_acquired).count());
|
||||
const std::uint64_t window_cells =
|
||||
static_cast<std::uint64_t>(xn - x0) * static_cast<std::uint64_t>(yn - y0);
|
||||
window_cells_sum_ += window_cells;
|
||||
window_cells_max_ = std::max(window_cells_max_, window_cells);
|
||||
maybeReportPerformance();
|
||||
}
|
||||
}
|
||||
|
||||
bool LayeredCostmap::isCurrent()
|
||||
|
||||
@@ -40,6 +40,8 @@
|
||||
#include <robot_tf3_sensor_msgs/tf3_sensor_msgs.h>
|
||||
#include <robot_sensor_msgs/point_cloud2_iterator.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
using namespace std;
|
||||
using namespace tf3;
|
||||
|
||||
@@ -68,7 +70,7 @@ bool ObservationBuffer::setGlobalFrame(const std::string new_global_frame)
|
||||
robot_geometry_msgs::TransformStamped transformStamped;
|
||||
if (!tf3_buffer_.canTransform(new_global_frame, global_frame_, transform_time, &tf_error))
|
||||
{
|
||||
printf("Transform between %s and %s with tolerance %.2f failed: %s.\n", new_global_frame.c_str(),
|
||||
robot::log_error("Transform between %s and %s with tolerance %.2f failed: %s.\n", new_global_frame.c_str(),
|
||||
global_frame_.c_str(), tf_tolerance_, tf_error.c_str());
|
||||
return false;
|
||||
}
|
||||
@@ -80,6 +82,12 @@ bool ObservationBuffer::setGlobalFrame(const std::string new_global_frame)
|
||||
{
|
||||
Observation& obs = *obs_it;
|
||||
|
||||
if (!obs.cloud_handle_.unique())
|
||||
{
|
||||
obs.cloud_handle_ = boost::make_shared<robot_sensor_msgs::PointCloud2>(*obs.cloud_);
|
||||
obs.cloud_ = obs.cloud_handle_.get();
|
||||
}
|
||||
|
||||
robot_geometry_msgs::PointStamped origin;
|
||||
origin.header.frame_id = global_frame_;
|
||||
origin.header.stamp = data_convert::convertTime(transform_time);
|
||||
@@ -106,7 +114,7 @@ bool ObservationBuffer::setGlobalFrame(const std::string new_global_frame)
|
||||
}
|
||||
catch (TransformException& ex)
|
||||
{
|
||||
printf("TF Error attempting to transform an observation from %s to %s: %s\n", global_frame_.c_str(),
|
||||
robot::log_error("TF Error attempting to transform an observation from %s to %s: %s\n", global_frame_.c_str(),
|
||||
new_global_frame.c_str(), ex.what());
|
||||
return false;
|
||||
}
|
||||
@@ -120,9 +128,7 @@ bool ObservationBuffer::setGlobalFrame(const std::string new_global_frame)
|
||||
void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
|
||||
{
|
||||
robot_geometry_msgs::PointStamped global_origin;
|
||||
|
||||
// create a new observation on the list to be populated
|
||||
observation_list_.push_front(Observation());
|
||||
Observation observation;
|
||||
|
||||
// check whether the origin frame has been set explicitly or whether we should get it from the cloud
|
||||
string origin_frame = sensor_frame_ == "" ? cloud.header.frame_id : sensor_frame_;
|
||||
@@ -137,79 +143,68 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
|
||||
local_origin.point.y = 0;
|
||||
local_origin.point.z = 0;
|
||||
// tf3_buffer_.transform(local_origin, global_origin, global_frame_);
|
||||
tf3::TransformStampedMsg tfm_1 = tf3_buffer_.lookupTransform(
|
||||
global_frame_, // frame đích
|
||||
local_origin.header.frame_id, // frame nguồn
|
||||
data_convert::convertTime(local_origin.header.stamp)
|
||||
);
|
||||
tf3::doTransform(local_origin, global_origin, tfm_1);
|
||||
const tf3::TransformStampedMsg cloud_transform = tf3_buffer_.lookupTransform(
|
||||
global_frame_, cloud.header.frame_id, tf3::Time());
|
||||
if (origin_frame == cloud.header.frame_id)
|
||||
tf3::doTransform(local_origin, global_origin, cloud_transform);
|
||||
else
|
||||
tf3::doTransform(
|
||||
local_origin, global_origin,
|
||||
tf3_buffer_.lookupTransform(global_frame_, origin_frame, tf3::Time()));
|
||||
|
||||
/////////////////////////////////////////////////
|
||||
///////////chú ý hàm này/////////////////////////
|
||||
tf3::convert(global_origin.point, observation_list_.front().origin_);
|
||||
/////////////////////////////////////////////////
|
||||
/////////////////////////////////////////////////
|
||||
tf3::convert(global_origin.point, observation.origin_);
|
||||
observation.raytrace_range_ = raytrace_range_;
|
||||
observation.obstacle_range_ = obstacle_range_;
|
||||
|
||||
// make sure to pass on the raytrace/obstacle range of the observation buffer to the observations
|
||||
observation_list_.front().raytrace_range_ = raytrace_range_;
|
||||
observation_list_.front().obstacle_range_ = obstacle_range_;
|
||||
robot_sensor_msgs::PointCloud2& observation_cloud = *observation.cloud_;
|
||||
tf3::doTransform(cloud, observation_cloud, cloud_transform);
|
||||
observation_cloud.header.stamp = cloud.header.stamp;
|
||||
|
||||
robot_sensor_msgs::PointCloud2 global_frame_cloud;
|
||||
const std::size_t cloud_size =
|
||||
static_cast<std::size_t>(observation_cloud.height) * observation_cloud.width;
|
||||
const std::size_t point_step = observation_cloud.point_step;
|
||||
std::size_t point_count = 0;
|
||||
robot_sensor_msgs::PointCloud2Iterator<float> iter_z(observation_cloud, "z");
|
||||
|
||||
// transform the point cloud
|
||||
// tf3_buffer_.transform(cloud, global_frame_cloud, global_frame_);
|
||||
tf3::TransformStampedMsg tfm_2 = tf3_buffer_.lookupTransform(
|
||||
global_frame_, // frame đích
|
||||
cloud.header.frame_id, // frame nguồn
|
||||
data_convert::convertTime(cloud.header.stamp)
|
||||
);
|
||||
tf3::doTransform(cloud, global_frame_cloud, tfm_2);
|
||||
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
|
||||
robot_sensor_msgs::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;
|
||||
robot_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
|
||||
robot_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)
|
||||
// Compact accepted points in-place. This avoids allocating and copying a
|
||||
// second full-size filtered cloud after the TF transform.
|
||||
for (std::size_t read_index = 0; read_index < cloud_size; ++read_index, ++iter_z)
|
||||
{
|
||||
if ((*iter_z) <= max_obstacle_height_
|
||||
&& (*iter_z) >= min_obstacle_height_)
|
||||
if ((*iter_z) > max_obstacle_height_ || (*iter_z) < min_obstacle_height_)
|
||||
continue;
|
||||
|
||||
if (point_count != read_index)
|
||||
{
|
||||
std::copy(iter_global, iter_global + global_frame_cloud.point_step, iter_obs);
|
||||
iter_obs += global_frame_cloud.point_step;
|
||||
++point_count;
|
||||
std::memmove(observation_cloud.data.data() + point_count * point_step,
|
||||
observation_cloud.data.data() + read_index * point_step,
|
||||
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;
|
||||
if (point_count != cloud_size)
|
||||
{
|
||||
robot_sensor_msgs::PointCloud2Modifier modifier(observation_cloud);
|
||||
modifier.resize(point_count);
|
||||
}
|
||||
}
|
||||
catch (TransformException& ex)
|
||||
{
|
||||
// if an exception occurs, we need to remove the empty observation from the list
|
||||
observation_list_.pop_front();
|
||||
printf("TF Exception that should never happen for sensor frame: %s, cloud frame: %s, %s\n", sensor_frame_.c_str(),
|
||||
robot::log_error("TF Exception that should never happen for sensor frame: %s, cloud frame: %s, %s\n", sensor_frame_.c_str(),
|
||||
cloud.header.frame_id.c_str(), ex.what());
|
||||
return;
|
||||
}
|
||||
|
||||
if (observation_keep_time_ == robot::Duration(0.0) && !observation_list_.empty())
|
||||
{
|
||||
observation_list_.front() = std::move(observation);
|
||||
observation_list_.erase(++observation_list_.begin(), observation_list_.end());
|
||||
}
|
||||
else
|
||||
{
|
||||
observation_list_.push_front(std::move(observation));
|
||||
}
|
||||
|
||||
// if the update was successful, we want to update the last updated time
|
||||
last_updated_ = robot::Time::now();
|
||||
|
||||
@@ -265,8 +260,7 @@ bool ObservationBuffer::isCurrent() const
|
||||
bool current = (robot::Time::now() - last_updated_).toSec() <= expected_update_rate_.toSec();
|
||||
if (!current)
|
||||
{
|
||||
printf(
|
||||
"The %s observation buffer has not been updated for %.2f seconds, and it should be updated every %.2f seconds.\n",
|
||||
robot::log_error("The %s observation buffer has not been updated for %.2f seconds, and it should be updated every %.2f seconds.\n",
|
||||
topic_name_.c_str(), (robot::Time::now() - last_updated_).toSec(), expected_update_rate_.toSec());
|
||||
}
|
||||
return current;
|
||||
@@ -277,4 +271,3 @@ void ObservationBuffer::resetLastUpdated()
|
||||
last_updated_ = robot::Time::now();
|
||||
}
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
|
||||
@@ -36,6 +36,14 @@
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <robot_costmap_2d/inflation_layer.h>
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
#include <robot_costmap_2d/observation_buffer.h>
|
||||
#include <robot_costmap_2d/voxel_layer.h>
|
||||
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <cstdlib>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
|
||||
@@ -124,9 +132,129 @@ TEST(CostmapCoordinates, hard_coordinates_test)
|
||||
EXPECT_EQ(my, 2);
|
||||
}
|
||||
|
||||
TEST(CostmapPerformanceRegression, rolling_origin_preserves_overlap)
|
||||
{
|
||||
Costmap2D costmap(4, 3, 1.0, 0.0, 0.0, FREE_SPACE);
|
||||
costmap.setCost(1, 1, LETHAL_OBSTACLE);
|
||||
costmap.setCost(3, 2, INSCRIBED_INFLATED_OBSTACLE);
|
||||
|
||||
costmap.updateOrigin(0.25, 0.25);
|
||||
EXPECT_DOUBLE_EQ(costmap.getOriginX(), 0.0);
|
||||
EXPECT_DOUBLE_EQ(costmap.getOriginY(), 0.0);
|
||||
EXPECT_EQ(costmap.getCost(1, 1), LETHAL_OBSTACLE);
|
||||
|
||||
costmap.updateOrigin(1.0, 0.0);
|
||||
EXPECT_DOUBLE_EQ(costmap.getOriginX(), 1.0);
|
||||
EXPECT_EQ(costmap.getCost(0, 1), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(costmap.getCost(3, 2), FREE_SPACE);
|
||||
}
|
||||
|
||||
TEST(CostmapPerformanceRegression, voxel_origin_subcell_shift_is_noop)
|
||||
{
|
||||
VoxelLayer layer;
|
||||
layer.resizeMap(4, 3, 1.0, 0.0, 0.0);
|
||||
layer.setCost(1, 1, LETHAL_OBSTACLE);
|
||||
|
||||
layer.updateOrigin(0.25, 0.25);
|
||||
|
||||
EXPECT_DOUBLE_EQ(layer.getOriginX(), 0.0);
|
||||
EXPECT_DOUBLE_EQ(layer.getOriginY(), 0.0);
|
||||
EXPECT_EQ(layer.getCost(1, 1), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST(CostmapPerformanceRegression, observation_copy_shares_cloud_payload)
|
||||
{
|
||||
robot_geometry_msgs::Point origin;
|
||||
robot_sensor_msgs::PointCloud2 cloud;
|
||||
cloud.height = 1;
|
||||
cloud.width = 1;
|
||||
cloud.point_step = 4;
|
||||
cloud.row_step = 4;
|
||||
cloud.data = {1, 2, 3, 4};
|
||||
|
||||
Observation observation(origin, cloud, 2.5, 3.0);
|
||||
Observation copied = observation;
|
||||
|
||||
EXPECT_EQ(copied.cloud_, observation.cloud_);
|
||||
EXPECT_EQ(copied.cloud_handle_.use_count(), 2);
|
||||
EXPECT_EQ(copied.cloud_->data, cloud.data);
|
||||
}
|
||||
|
||||
TEST(CostmapPerformanceRegression, inflation_buckets_preserve_radial_costs)
|
||||
{
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);
|
||||
|
||||
LayeredCostmap layered_costmap("map", false, false);
|
||||
layered_costmap.resizeMap(7, 7, 1.0, 0.0, 0.0, true);
|
||||
tf3::BufferCore tf_buffer(tf3::Duration(10.0));
|
||||
InflationLayer inflation;
|
||||
inflation.initialize(&layered_costmap, "inflation", &tf_buffer);
|
||||
inflation.setInflationParameters(2.0, 1.0);
|
||||
|
||||
Costmap2D& master = *layered_costmap.getCostmap();
|
||||
master.setCost(3, 3, LETHAL_OBSTACLE);
|
||||
inflation.updateCosts(master, 0, 0, 7, 7);
|
||||
|
||||
EXPECT_EQ(master.getCost(3, 3), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master.getCost(2, 3), master.getCost(4, 3));
|
||||
EXPECT_EQ(master.getCost(3, 2), master.getCost(3, 4));
|
||||
EXPECT_GT(master.getCost(4, 3), master.getCost(5, 3));
|
||||
EXPECT_EQ(master.getCost(6, 3), FREE_SPACE);
|
||||
}
|
||||
|
||||
TEST(CostmapSnapshot, copy_from_copies_grid_and_metadata)
|
||||
{
|
||||
Costmap2D src(10, 8, 0.05, 1.0, 2.0, FREE_SPACE);
|
||||
src.setCost(3, 4, LETHAL_OBSTACLE);
|
||||
src.setCost(9, 7, 42);
|
||||
|
||||
Costmap2D dst;
|
||||
dst.copyFrom(src);
|
||||
|
||||
EXPECT_EQ(dst.getSizeInCellsX(), 10u);
|
||||
EXPECT_EQ(dst.getSizeInCellsY(), 8u);
|
||||
EXPECT_DOUBLE_EQ(dst.getResolution(), 0.05);
|
||||
EXPECT_DOUBLE_EQ(dst.getOriginX(), 1.0);
|
||||
EXPECT_DOUBLE_EQ(dst.getOriginY(), 2.0);
|
||||
EXPECT_EQ(dst.getCost(3, 4), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(dst.getCost(9, 7), 42);
|
||||
EXPECT_EQ(dst.getCost(0, 0), FREE_SPACE);
|
||||
}
|
||||
|
||||
TEST(CostmapSnapshot, copy_from_reuses_buffer_when_size_unchanged)
|
||||
{
|
||||
Costmap2D src(6, 6, 0.05, 0.0, 0.0, FREE_SPACE);
|
||||
Costmap2D dst;
|
||||
dst.copyFrom(src);
|
||||
unsigned char* first_buffer = dst.getCharMap();
|
||||
|
||||
src.setCost(2, 2, LETHAL_OBSTACLE);
|
||||
dst.copyFrom(src);
|
||||
|
||||
// Same size: the buffer must be reused (this is the whole point of
|
||||
// copyFrom vs operator=), and the fresh cell must arrive.
|
||||
EXPECT_EQ(dst.getCharMap(), first_buffer);
|
||||
EXPECT_EQ(dst.getCost(2, 2), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST(CostmapSnapshot, copy_from_reallocates_on_resize)
|
||||
{
|
||||
Costmap2D src(4, 4, 0.05, 0.0, 0.0, FREE_SPACE);
|
||||
Costmap2D dst;
|
||||
dst.copyFrom(src);
|
||||
|
||||
Costmap2D bigger(12, 9, 0.1, -1.0, -2.0, NO_INFORMATION);
|
||||
bigger.setCost(11, 8, LETHAL_OBSTACLE);
|
||||
dst.copyFrom(bigger);
|
||||
|
||||
EXPECT_EQ(dst.getSizeInCellsX(), 12u);
|
||||
EXPECT_EQ(dst.getSizeInCellsY(), 9u);
|
||||
EXPECT_EQ(dst.getCost(11, 8), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(dst.getCost(0, 0), NO_INFORMATION);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest( &argc, argv );
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
|
||||
|
||||
479
test/depth_camera_obstacle_layer_test.cpp
Normal file
479
test/depth_camera_obstacle_layer_test.cpp
Normal file
@@ -0,0 +1,479 @@
|
||||
#include <robot_costmap_2d/depth_camera_obstacle_layer.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <robot_sensor_msgs/point_cloud2_iterator.h>
|
||||
#include <robot_sensor_msgs/DepthCameraData.h>
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr double kFovW = 1.23; // D410 at 424x240, fx = 300 [rad]
|
||||
constexpr double kFovV = 0.76;
|
||||
constexpr char kTopic[] = "/camera/depth/points_proc";
|
||||
|
||||
// The layer reads config/depth_camera_obstacle_layer_params.yaml under PNKX_NAV_CORE_CONFIG_DIR
|
||||
// before its own namespace; point it at this package for every test.
|
||||
class ConfigDirEnvironment : public ::testing::Environment
|
||||
{
|
||||
public:
|
||||
void SetUp() override
|
||||
{
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);
|
||||
}
|
||||
};
|
||||
::testing::Environment* const kConfigDirEnvironment = ::testing::AddGlobalTestEnvironment(new ConfigDirEnvironment);
|
||||
|
||||
// Optical frame "camera" 0.19 m above odom, looking along +x of odom (rotated by yaw).
|
||||
tf3::TransformStampedMsg pose(robot::Time stamp, double yaw = 0)
|
||||
{
|
||||
tf3::TransformStampedMsg p;
|
||||
p.header.frame_id = "odom";
|
||||
p.child_frame_id = "camera";
|
||||
p.header.stamp = tf3::Time(stamp.sec, stamp.nsec);
|
||||
Eigen::Matrix3d optical;
|
||||
optical << 0, 0, 1, -1, 0, 0, 0, -1, 0;
|
||||
Eigen::Quaterniond q(Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ()) * optical);
|
||||
p.transform.rotation.x = q.x();
|
||||
p.transform.rotation.y = q.y();
|
||||
p.transform.rotation.z = q.z();
|
||||
p.transform.rotation.w = q.w();
|
||||
p.transform.translation.z = .19;
|
||||
return p;
|
||||
}
|
||||
|
||||
// Points given in odom for a camera at yaw 0; stored in the optical frame of the cloud.
|
||||
robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, const std::vector<Eigen::Vector3d>& odom_points)
|
||||
{
|
||||
robot_sensor_msgs::PointCloud2 c;
|
||||
c.header.stamp = stamp;
|
||||
c.header.frame_id = "camera";
|
||||
c.height = 1;
|
||||
robot_sensor_msgs::PointCloud2Modifier m(c);
|
||||
m.setPointCloud2FieldsByString(1, "xyz");
|
||||
m.resize(odom_points.size());
|
||||
robot_sensor_msgs::PointCloud2Iterator<float> x(c, "x"), y(c, "y"), z(c, "z");
|
||||
for (const auto& p : odom_points)
|
||||
{
|
||||
*x = -p.y();
|
||||
*y = .19 - p.z();
|
||||
*z = p.x();
|
||||
++x;
|
||||
++y;
|
||||
++z;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// 3 x 3 points, 6 cm apart (one per 5 cm voxel), one Euclidean cluster. Kept away from cell
|
||||
// boundaries: the source stores (int)(x / 0.05), so y = .07 .13 .19 are columns 1 2 3.
|
||||
std::vector<Eigen::Vector3d> object(double x = 1.02, double y = .13, double z = .30)
|
||||
{
|
||||
std::vector<Eigen::Vector3d> pts;
|
||||
for (double dy : {-.06, 0., .06})
|
||||
for (double dz : {-.06, 0., .06})
|
||||
pts.emplace_back(x, y + dy, z + dz);
|
||||
return pts;
|
||||
}
|
||||
|
||||
// 11 points in a row 0.6 m behind the object: keeps the cloud above 5 points, own cluster.
|
||||
std::vector<Eigen::Vector3d> wall()
|
||||
{
|
||||
std::vector<Eigen::Vector3d> pts;
|
||||
for (int i = -5; i <= 5; ++i)
|
||||
pts.emplace_back(1.62, i * .06 + .13, .30);
|
||||
return pts;
|
||||
}
|
||||
|
||||
std::vector<Eigen::Vector3d> join(std::vector<Eigen::Vector3d> a, const std::vector<Eigen::Vector3d>& b)
|
||||
{
|
||||
a.insert(a.end(), b.begin(), b.end());
|
||||
return a;
|
||||
}
|
||||
|
||||
YAML::Node baseConfig()
|
||||
{
|
||||
YAML::Node cfg;
|
||||
cfg["enabled"] = true;
|
||||
cfg["footprint_clearing_enabled"] = false;
|
||||
cfg["use_global_frame_to_mark"] = true;
|
||||
cfg["enable_near_blocked_protection"] = false;
|
||||
cfg["observation_sources"] = "depth_cam";
|
||||
cfg["debug"]["stats"] = false;
|
||||
cfg["depth_cam"]["topic"] = kTopic;
|
||||
cfg["depth_cam"]["sensor_frame_is_optical"] = true;
|
||||
cfg["depth_cam"]["FOV_W"] = kFovW;
|
||||
cfg["depth_cam"]["FOV_V"] = kFovV;
|
||||
cfg["depth_cam"]["min_detect_distance"] = .15;
|
||||
cfg["depth_cam"]["max_detect_distance"] = 2.5;
|
||||
cfg["depth_cam"]["min_obstacle_height"] = .05;
|
||||
cfg["depth_cam"]["max_obstacle_height"] = 1.0;
|
||||
return cfg;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Frustum geometry
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
TEST(DepthCameraFrustum, InsideFollowsTheConfiguredPyramid)
|
||||
{
|
||||
DepthCameraFrustum f;
|
||||
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); // X forward
|
||||
const float half_w = std::tan(kFovW / 2), half_v = std::tan(kFovV / 2);
|
||||
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, 0)));
|
||||
EXPECT_FALSE(f.inside(Eigen::Vector3f(.1f, 0, 0))); // before the near plane
|
||||
EXPECT_FALSE(f.inside(Eigen::Vector3f(2.6f, 0, 0))); // beyond the far plane
|
||||
EXPECT_FALSE(f.inside(Eigen::Vector3f(-1, 0, 0)));
|
||||
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, .98f * half_w, 0)));
|
||||
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 1.02f * half_w, 0)));
|
||||
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, -1.02f * half_w, 0)));
|
||||
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, -.98f * half_v)));
|
||||
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 0, 1.02f * half_v)));
|
||||
}
|
||||
|
||||
TEST(DepthCameraFrustum, AttachBandIsTwelveCentimetresFromEveryFace)
|
||||
{
|
||||
DepthCameraFrustum f;
|
||||
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, 0, 0)));
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(2.4f, 0, 0))); // 10 cm before the far plane
|
||||
const float half_w = std::tan(kFovW / 2);
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0)));
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .3f, 0)));
|
||||
}
|
||||
|
||||
TEST(DepthCameraFrustum, OpticalFrameGivesTheSamePyramid)
|
||||
{
|
||||
DepthCameraFrustum link, optical;
|
||||
link.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
|
||||
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
|
||||
T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link
|
||||
optical.build(T, kFovW, kFovV, .15, 2.5, true);
|
||||
for (int i = 0; i < 8; ++i)
|
||||
EXPECT_LT((link.vertices[i] - optical.vertices[i]).norm(), 1e-5f) << "vertex " << i;
|
||||
EXPECT_TRUE(optical.inside(Eigen::Vector3f(1, 0, 0)));
|
||||
}
|
||||
|
||||
TEST(DepthCameraFrustum, AttachedUnlessWellInsideAnotherFrustum)
|
||||
{
|
||||
DepthCameraFrustum a, b;
|
||||
a.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
|
||||
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
|
||||
T.translation() << 0, .3, 0; // second camera 30 cm to the left
|
||||
b.build(T, kFovW, kFovV, .15, 2.5, false);
|
||||
const Eigen::Vector3f near_left_face_of_a(1, std::tan(kFovW / 2) - .05f, 0);
|
||||
EXPECT_TRUE(attachedToFrustums({a}, near_left_face_of_a));
|
||||
EXPECT_FALSE(attachedToFrustums({a, b}, near_left_face_of_a));
|
||||
EXPECT_FALSE(attachedToFrustums({a}, Eigen::Vector3f(1, 0, 0)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Layer
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
class DepthCameraLayerTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
tf3::BufferCore tf;
|
||||
LayeredCostmap parent{"odom", false, false};
|
||||
DepthCameraObstacleLayer layer;
|
||||
uint32_t tick = 0;
|
||||
double min_x = 0, min_y = 0, max_x = 0, max_y = 0;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
robot::Time::setNow(robot::Time(100, 0));
|
||||
YAML::Node cfg = baseConfig();
|
||||
configure(cfg);
|
||||
robot::NodeHandle nh("~");
|
||||
nh.setParam("dcam_test", cfg);
|
||||
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
|
||||
layer.initialize(&parent, "dcam_test", &tf);
|
||||
ASSERT_TRUE(layer.isEnabled());
|
||||
}
|
||||
virtual void configure(YAML::Node&) {}
|
||||
|
||||
robot::Time next()
|
||||
{
|
||||
return robot::Time(100, ++tick * 10000000);
|
||||
}
|
||||
void update()
|
||||
{
|
||||
min_x = min_y = 1e9;
|
||||
max_x = max_y = -1e9;
|
||||
layer.updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y);
|
||||
}
|
||||
void frame(const std::vector<Eigen::Vector3d>& pts, double yaw = 0, bool has_tf = true)
|
||||
{
|
||||
const robot::Time stamp = next();
|
||||
robot::Time::setNow(stamp);
|
||||
if (has_tf)
|
||||
ASSERT_TRUE(tf.setTransform(pose(stamp, yaw), "test"));
|
||||
layer.dataCallBack(cloud(stamp, pts), kTopic);
|
||||
update();
|
||||
}
|
||||
unsigned char master(double x = 1.01, double y = .11)
|
||||
{
|
||||
Costmap2D& m = *parent.getCostmap();
|
||||
m.resetMap(0, 0, m.getSizeInCellsX(), m.getSizeInCellsY());
|
||||
layer.updateCosts(m, 0, 0, m.getSizeInCellsX(), m.getSizeInCellsY());
|
||||
unsigned int a, b;
|
||||
EXPECT_TRUE(m.worldToMap(x, y, a, b));
|
||||
return m.getCost(a, b);
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(DepthCameraLayerTest, MarksAClusterInsideTheFrustum)
|
||||
{
|
||||
frame(object());
|
||||
EXPECT_EQ(layer.storedPoints(), 9u);
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
EXPECT_TRUE(layer.isCurrent());
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, SmallClusterAndOutOfHeightPointsAreNotMarked)
|
||||
{
|
||||
std::vector<Eigen::Vector3d> five = object();
|
||||
five.resize(5); // <= size_of_cluster_rejection
|
||||
frame(join(five, wall()));
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
frame(join(object(1.02, .13, 1.5), wall())); // above max_obstacle_height
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, KeptWhileSeenAgainAndClearedWhenGone)
|
||||
{
|
||||
frame(join(object(), wall()));
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame(join(object(), wall()));
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
frame(wall()); // no cloud point within check_radius of the stored points
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master(1.61, .11), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, OutsideTheFrustumIsKept)
|
||||
{
|
||||
frame(object());
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame({}, 1.57); // camera turned away, sees nothing
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, NearlyEmptyCloudClearsEverythingInViewWithoutProtection)
|
||||
{
|
||||
frame(object());
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
frame({});
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
class DepthCameraBlockedTest : public DepthCameraLayerTest
|
||||
{
|
||||
protected:
|
||||
void configure(YAML::Node& cfg) override
|
||||
{
|
||||
cfg["enable_near_blocked_protection"] = true;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(DepthCameraBlockedTest, NearlyEmptyCloudSkipsClearingWithProtection)
|
||||
{
|
||||
frame(object());
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame({});
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
frame(wall());
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, AttachBandIsNotMarked)
|
||||
{
|
||||
// 10 cm past the near plane (0.15 m) of a camera at x = 0: inside, but attached.
|
||||
frame(wall());
|
||||
const std::size_t wall_points = layer.storedPoints();
|
||||
ASSERT_GT(wall_points, 0u);
|
||||
frame(join(object(.25, .10, .19), wall()));
|
||||
EXPECT_EQ(layer.storedPoints(), wall_points);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, WaitsForTheMeasurementTfThenDropsAfterTheTolerance)
|
||||
{
|
||||
frame(object(), 0, false); // no TF at this stamp yet
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
const robot::Time stamp(100, tick * 10000000);
|
||||
ASSERT_TRUE(tf.setTransform(pose(stamp), "late_tf"));
|
||||
update();
|
||||
EXPECT_EQ(layer.storedPoints(), 9u);
|
||||
|
||||
frame(object(1.32, -.47, .3), 0, false);
|
||||
const robot::Time late(100, tick * 10000000);
|
||||
robot::Time::setNow(robot::Time(101, 0)); // older than transform_tolerance (0.2 s)
|
||||
update();
|
||||
ASSERT_TRUE(tf.setTransform(pose(late), "too_late_tf"));
|
||||
update();
|
||||
EXPECT_NE(master(1.31, -.44), LETHAL_OBSTACLE); // the waiting cloud was dropped
|
||||
EXPECT_EQ(layer.storedPoints(), 9u);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, OtherTopicsAndDepthImagesAreIgnored)
|
||||
{
|
||||
const robot::Time stamp = next();
|
||||
robot::Time::setNow(stamp);
|
||||
ASSERT_TRUE(tf.setTransform(pose(stamp), "test"));
|
||||
layer.dataCallBack(cloud(stamp, object()), "/other/points");
|
||||
robot_sensor_msgs::DepthCameraData::ConstPtr depth = boost::make_shared<robot_sensor_msgs::DepthCameraData>();
|
||||
layer.dataCallBack(depth, kTopic);
|
||||
update();
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, MarkingsThatLeaveTheWindowAreDropped)
|
||||
{
|
||||
frame(object());
|
||||
ASSERT_EQ(layer.storedPoints(), 9u);
|
||||
layer.updateOrigin(10, 10); // the stored cells are outside the layer now
|
||||
update();
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, ClearedCellLeavesTheMasterInsideTheBounds)
|
||||
{
|
||||
frame(join(object(), wall()));
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE); // master now holds the object cell
|
||||
frame(wall());
|
||||
EXPECT_LT(min_x, 1.05); // the cleared object cell is part of this cycle's bounds
|
||||
// What LayeredCostmap does: reset the master inside the bounds only, then merge the layer there.
|
||||
Costmap2D& m = *parent.getCostmap();
|
||||
int i0, j0, i1, j1;
|
||||
m.worldToMapEnforceBounds(min_x, min_y, i0, j0);
|
||||
m.worldToMapEnforceBounds(max_x, max_y, i1, j1);
|
||||
m.resetMap(i0, j0, i1 + 1, j1 + 1);
|
||||
layer.updateCosts(m, i0, j0, i1 + 1, j1 + 1);
|
||||
unsigned int a, b;
|
||||
ASSERT_TRUE(m.worldToMap(1.01, .11, a, b));
|
||||
EXPECT_NE(m.getCost(a, b), LETHAL_OBSTACLE);
|
||||
ASSERT_TRUE(m.worldToMap(1.61, .11, a, b));
|
||||
EXPECT_EQ(m.getCost(a, b), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, ClearAreaKeepsTheInsideByDefaultAndClearsItWhenInverted)
|
||||
{
|
||||
frame(join(object(), wall()));
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
ASSERT_EQ(master(1.61, .11), LETHAL_OBSTACLE);
|
||||
// Cells strictly inside (55, 35)-(65, 50) hold the object (cell x 60); the wall is at cell x 72.
|
||||
layer.clearArea(55, 35, 65, 50, false); // CostmapLayer contract: clears OUTSIDE the box
|
||||
EXPECT_EQ(layer.storedPoints(), 9u);
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
EXPECT_NE(master(1.61, .11), LETHAL_OBSTACLE);
|
||||
layer.clearArea(55, 35, 65, 50, true); // inverted: clears the inside
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, ResetDropsTheStoredPointsAndObservations)
|
||||
{
|
||||
frame(join(object(), wall()));
|
||||
ASSERT_GT(layer.storedPoints(), 0u);
|
||||
layer.reset();
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
update(); // no new cloud: the buffered observation is gone too, nothing comes back
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
}
|
||||
|
||||
class DepthCameraFootprintTest : public DepthCameraLayerTest
|
||||
{
|
||||
protected:
|
||||
void configure(YAML::Node& cfg) override
|
||||
{
|
||||
cfg["footprint_clearing_enabled"] = true;
|
||||
cfg["enable_near_blocked_protection"] = true; // an empty cycle must not clear by itself
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(DepthCameraFootprintTest, FootprintClearingErasesThePointsUnderTheRobot)
|
||||
{
|
||||
std::vector<robot_geometry_msgs::Point> square(4);
|
||||
square[0].x = -.3; square[0].y = -.3;
|
||||
square[1].x = .3; square[1].y = -.3;
|
||||
square[2].x = .3; square[2].y = .3;
|
||||
square[3].x = -.3; square[3].y = .3;
|
||||
parent.setFootprint(square);
|
||||
frame(object());
|
||||
ASSERT_EQ(layer.storedPoints(), 9u);
|
||||
layer.updateBounds(1.02, .13, 0, &min_x, &min_y, &max_x, &max_y); // robot drives onto it
|
||||
EXPECT_EQ(layer.storedPoints(), 0u);
|
||||
EXPECT_NE(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, HasItsOwnLayerType)
|
||||
{
|
||||
EXPECT_EQ(layer.getType(), LayerType::DEPTH_CAMERA_LAYER);
|
||||
EXPECT_NE(layer.getType(), LayerType::VOXEL_LAYER);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, MatchSizeKeepsAndReMarksTheStoredPoints)
|
||||
{
|
||||
frame(object());
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
layer.matchSize(); // rebuilds the own grid from scratch
|
||||
EXPECT_EQ(layer.storedPoints(), 9u);
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE); // re-marked without waiting for an update
|
||||
}
|
||||
|
||||
TEST(DepthCameraLayerConfig, RejectsUnportedModeAndOutOfRangeValues)
|
||||
{
|
||||
tf3::BufferCore tf;
|
||||
LayeredCostmap parent{"odom", false, false};
|
||||
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
|
||||
robot::NodeHandle nh("~");
|
||||
const auto expectThrow = [&](const YAML::Node& cfg) {
|
||||
nh.setParam("dcam_bad", cfg);
|
||||
DepthCameraObstacleLayer layer;
|
||||
EXPECT_THROW(layer.initialize(&parent, "dcam_bad", &tf), std::invalid_argument);
|
||||
};
|
||||
YAML::Node cfg = baseConfig();
|
||||
cfg["use_global_frame_to_mark"] = false;
|
||||
expectThrow(cfg);
|
||||
cfg = baseConfig();
|
||||
cfg["depth_cam"]["FOV_W"] = 3.5;
|
||||
expectThrow(cfg);
|
||||
cfg = baseConfig();
|
||||
cfg["depth_cam"]["min_detect_distance"] = 3.0;
|
||||
expectThrow(cfg);
|
||||
cfg = baseConfig();
|
||||
cfg["voxel_resolution"] = 0.0;
|
||||
expectThrow(cfg);
|
||||
}
|
||||
|
||||
TEST(DepthCameraLayerConfig, RefusesToStartWithoutItsDefaultFile)
|
||||
{
|
||||
tf3::BufferCore tf;
|
||||
LayeredCostmap parent{"odom", false, false};
|
||||
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
|
||||
robot::NodeHandle nh("~");
|
||||
nh.setParam("dcam_no_default", baseConfig());
|
||||
// An empty directory: it has no config/depth_camera_obstacle_layer_params.yaml.
|
||||
char empty_dir[] = "/tmp/dcam_no_default_XXXXXX";
|
||||
ASSERT_NE(mkdtemp(empty_dir), nullptr);
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", empty_dir, 1), 0);
|
||||
DepthCameraObstacleLayer layer;
|
||||
EXPECT_THROW(layer.initialize(&parent, "dcam_no_default", &tf), std::runtime_error);
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);
|
||||
rmdir(empty_dir);
|
||||
}
|
||||
Reference in New Issue
Block a user