Compare commits
16 Commits
dev_cam_in
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 55c7359632 | |||
| 2695eb4e55 | |||
| 74bc39b1f6 | |||
| 5034029c6e | |||
| f5d190a3d0 | |||
| b990ce0f25 | |||
| 40488b7632 | |||
| 3539afbfb4 | |||
| 757b381659 | |||
| 9b93a45b45 | |||
| e40e9c0104 | |||
| 3b89add5ee | |||
| 64974d48b7 | |||
| a63c084002 | |||
| 45c8227f5c | |||
| faa57d9c93 |
@@ -18,9 +18,15 @@ set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
# Find dependencies
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem)
|
||||
find_package(GTest REQUIRED)
|
||||
find_package(PCL REQUIRED COMPONENTS common io)
|
||||
# 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)
|
||||
find_package(Threads 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)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
@@ -78,7 +84,7 @@ else()
|
||||
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 PCL Boost
|
||||
DEPENDS Boost
|
||||
)
|
||||
|
||||
include_directories(
|
||||
@@ -87,17 +93,15 @@ else()
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${GTEST_INCLUDE_DIRS}
|
||||
${PCL_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
link_directories(${PCL_LIBRARY_DIRS})
|
||||
endif()
|
||||
|
||||
# Define macro để dùng trong code
|
||||
add_definitions(-DROBOT_COSTMAP_2D_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
|
||||
# Eigen và PCL definitions
|
||||
add_definitions(${EIGEN3_DEFINITIONS} ${PCL_DEFINITIONS})
|
||||
# Eigen definitions
|
||||
add_definitions(${EIGEN3_DEFINITIONS})
|
||||
|
||||
# ========================================================
|
||||
# Core library: robot_costmap_2d
|
||||
@@ -109,6 +113,9 @@ add_library(robot_costmap_2d SHARED
|
||||
src/observation_buffer.cpp
|
||||
src/layer.cpp
|
||||
src/layered_costmap.cpp
|
||||
src/direction_field.cpp
|
||||
src/reference_graph.cpp
|
||||
src/reference_graph_worker.cpp
|
||||
src/costmap_math.cpp
|
||||
src/footprint.cpp
|
||||
src/costmap_layer.cpp
|
||||
@@ -123,7 +130,6 @@ if(BUILDING_WITH_CATKIN)
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${PCL_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
@@ -132,8 +138,8 @@ if(BUILDING_WITH_CATKIN)
|
||||
PRIVATE Boost::boost Boost::system Boost::thread Boost::filesystem
|
||||
PRIVATE yaml-cpp
|
||||
PRIVATE dl
|
||||
PRIVATE ${PCL_LIBRARIES}
|
||||
PRIVATE ${TF3_LIBRARY}
|
||||
PUBLIC Threads::Threads
|
||||
)
|
||||
|
||||
else()
|
||||
@@ -144,7 +150,6 @@ else()
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${PCL_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
@@ -155,8 +160,8 @@ else()
|
||||
Boost::boost Boost::system Boost::thread Boost::filesystem
|
||||
yaml-cpp
|
||||
dl
|
||||
${PCL_LIBRARIES}
|
||||
${TF3_LIBRARY}
|
||||
Threads::Threads
|
||||
)
|
||||
|
||||
set_target_properties(robot_costmap_2d PROPERTIES
|
||||
@@ -179,7 +184,12 @@ add_library(plugins SHARED
|
||||
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})
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
@@ -235,6 +245,9 @@ if(BUILDING_WITH_CATKIN)
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(FILES config/directional_layer_params.yaml
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/config)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
@@ -251,6 +264,9 @@ else()
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
install(FILES config/directional_layer_params.yaml
|
||||
DESTINATION share/${PROJECT_NAME}/config)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
@@ -271,20 +287,43 @@ else()
|
||||
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, PCL, Boost, yaml-cpp")
|
||||
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
|
||||
# ========================================================
|
||||
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables" ON)
|
||||
# Tests are OFF by default in both build modes; enable with -DBUILD_COSTMAP_TESTS=ON.
|
||||
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables"
|
||||
OFF)
|
||||
|
||||
if(BUILD_COSTMAP_TESTS)
|
||||
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)
|
||||
|
||||
add_executable(costmap_common_root_test test/costmap_common_root_test.cpp)
|
||||
target_link_libraries(costmap_common_root_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main)
|
||||
|
||||
add_executable(obstacle_layer_scan_ranges_test test/obstacle_layer_scan_ranges_test.cpp)
|
||||
target_link_libraries(obstacle_layer_scan_ranges_test PRIVATE plugins robot_costmap_2d GTest::GTest GTest::Main)
|
||||
|
||||
add_executable(direction_field_test test/direction_field_test.cpp)
|
||||
target_link_libraries(direction_field_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main)
|
||||
|
||||
add_executable(reference_graph_test test/reference_graph_test.cpp)
|
||||
target_link_libraries(reference_graph_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main)
|
||||
|
||||
add_executable(reference_graph_worker_test test/reference_graph_worker_test.cpp)
|
||||
target_link_libraries(reference_graph_worker_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main Boost::thread)
|
||||
|
||||
add_executable(directional_layer_test test/directional_layer_test.cpp)
|
||||
target_link_libraries(directional_layer_test PRIVATE plugins robot_costmap_2d GTest::GTest GTest::Main Boost::thread ${TF3_LIBRARY})
|
||||
|
||||
add_executable(rolling_static_layer_test test/rolling_static_layer_test.cpp)
|
||||
target_link_libraries(rolling_static_layer_test PRIVATE plugins robot_costmap_2d GTest::GTest GTest::Main Boost::thread ${TF3_LIBRARY})
|
||||
|
||||
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
|
||||
@@ -299,6 +338,7 @@ if(BUILD_COSTMAP_TESTS)
|
||||
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
|
||||
@@ -321,4 +361,15 @@ if(BUILD_COSTMAP_TESTS)
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
endif()
|
||||
|
||||
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
|
||||
yaml-cpp
|
||||
GTest::GTest
|
||||
GTest::Main
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
668
README.md
Normal file
668
README.md
Normal file
@@ -0,0 +1,668 @@
|
||||
# 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`.
|
||||
|
||||
Các khóa chung có thể nằm trong map `root:` hoặc trực tiếp ở đầu cây YAML (flat).
|
||||
Khi có `root:`, costmap chỉ lấy khóa chung từ map đó; nếu không có thì dùng layout
|
||||
flat. Khóa trong `<costmap>/<plugin>` được ưu tiên, còn block plugin chung chỉ
|
||||
bổ sung những khóa chưa được costmap đặt.
|
||||
|
||||
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`. Bật `occlusion_guard` thì tia nhìn quyết định thêm:
|
||||
điểm có vật gần hơn che trên tia nhìn tới nó được **giữ**, điểm mà camera nhìn xuyên qua
|
||||
(thấy nền phía sau) bị **xóa** dù còn điểm khác trong `check_radius`.
|
||||
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
|
||||
`attach_distance` (mặc định 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. |
|
||||
| `occlusion_guard` | `false` | `true`: giữ điểm bị vật gần hơn che, xóa điểm mà camera nhìn xuyên qua. Dựng một ảnh khoảng cách nhỏ (bin 0.01 theo tang góc) từ cả cloud trước lọc chiều cao. Hằng số đã kiểm offline trên 10 bag robot KIT (22–23/10/2026). `false`: chỉ phép kd-tree như gói gốc. |
|
||||
| `debug/stats` | `true` | Log `[debug/stats]` định kỳ: số điểm, số điểm đánh dấu/xóa, TF chờ/bỏ, `kept_occluded` / `cleared_seen_through` của `occlusion_guard`, 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. |
|
||||
| `attach_distance` | `0.12 m` | Điểm cách bất kỳ mặt khối nhìn dưới mức này không được đánh dấu (mép vật bị cắt, nhiễu mép ảnh). Giảm: vật thấp sát mép dưới FOV được đánh dấu; quá nhỏ (0.05) làm tăng ô ma trước mũi robot. Miền `[0, (max_detect_distance - min_detect_distance) / 2)`. |
|
||||
| `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".
|
||||
- `occlusion_guard` chỉ có tác dụng trong khối nhìn: vết của vật động đã ra ngoài FOV vẫn được
|
||||
giữ như trên. Điểm bị che được giữ tới khi camera nhìn lại được chỗ đó.
|
||||
- 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
|
||||
```
|
||||
|
||||
## DirectionalLayer
|
||||
|
||||
Xem [hướng dẫn DirectionalLayer](doc/directional_layer.md) về grid hướng, cấu hình và hợp đồng host.
|
||||
@@ -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
|
||||
@@ -33,4 +35,4 @@ robot_costmap_2d:
|
||||
origin_y: 0.0
|
||||
|
||||
footprint_padding: 0.0
|
||||
robot_radius: 0.0
|
||||
robot_radius: 0.0
|
||||
|
||||
54
config/depth_camera_obstacle_layer_params.yaml
Normal file
54
config/depth_camera_obstacle_layer_params.yaml
Normal file
@@ -0,0 +1,54 @@
|
||||
# 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] Chống xoá khi bị che, dùng tia nhìn của ảnh depth (cả sàn, trước lọc chiều cao).
|
||||
# true: điểm đã lưu mà có vật gần hơn nằm trên tia nhìn tới nó thì GIỮ (người đi ngang trước thùng
|
||||
# không còn xoá thùng); điểm mà camera nhìn xuyên qua thấy nền phía sau thì XOÁ, kể cả khi còn điểm
|
||||
# khác trong check_radius (vết của vật vừa dịch đi biến nhanh hơn).
|
||||
# false: chỉ dùng phép kd-tree như gói gốc. Bật thì tốn thêm một ảnh khoảng cách nhỏ mỗi cloud.
|
||||
# Vết nằm NGOÀI FOV vẫn không xoá được dù bật hay tắt.
|
||||
occlusion_guard: false
|
||||
# [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, attach_distance...) KHÔNG
|
||||
# đặt ở đây mà trong khối <plugin>/<tên nguồn>/ của config costmap. attach_distance [m] mặc định
|
||||
# 0.12 như gói gốc: điểm cách mặt khối nhìn dưới mức này không được đánh dấu.
|
||||
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.
|
||||
24
config/directional_layer_params.yaml
Normal file
24
config/directional_layer_params.yaml
Normal file
@@ -0,0 +1,24 @@
|
||||
# Mặc định đóng gói của directional layer; cây chạy thực tế tùy host là
|
||||
# pnkx_nav_core/src/Navigations/Packages/move_base2/config/runtime hoặc
|
||||
# pnkx_nav_core/config.
|
||||
directional_layer:
|
||||
# Bật: sau mỗi static map, layer PENDING đến khi nhận grid hợp lệ và planner
|
||||
# phải từ chối lập đường trong lúc chờ. Host phải gửi grid sau mỗi static map;
|
||||
# dùng data rỗng nếu map không có zone. Tắt để bỏ ràng buộc hướng.
|
||||
enabled: false
|
||||
# Phải trùng map_topic của StaticLayer. Đặt sai khiến layer không thoát
|
||||
# PENDING hoặc không nhận biết khi map đổi.
|
||||
map_topic: "map"
|
||||
# Topic grid hướng: đổi theo tên host gửi; phải khác map_topic.
|
||||
direction_topic: "direction_map"
|
||||
# [deg] Góc lệch tối đa giữa hướng di chuyển và hướng zone, tính cả biên.
|
||||
# Áp chung cho mọi zone. 90 = được đi mọi hướng có thành phần cùng chiều zone
|
||||
# (đi ngang zone được, đi ngược bị cấm).
|
||||
# Giảm: robot phải đi sát hướng zone hơn, cấm cắt ngang làn, phải căn hướng
|
||||
# trước khi vào zone; quay tại chỗ luôn được phép. Dưới 22.5 (bước heading của
|
||||
# mprim 16 hướng) SBPL có thể không tìm được đường.
|
||||
# Tăng quá 90: cho phép cả hướng hơi ngược chiều zone, zone một chiều yếu đi.
|
||||
# Phạm vi hợp lệ: 0 < giá trị < 180; ngoài phạm vi nav core từ chối khởi động.
|
||||
max_deviation_deg: 90.0
|
||||
# Bật để ghi log chuyển trạng thái; tắt để giảm log bình thường.
|
||||
debug_state: true
|
||||
@@ -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.
|
||||
|
||||
@@ -7,6 +7,4 @@ voxel_layer:
|
||||
z_voxels: 16
|
||||
unknown_threshold: 15.0
|
||||
mark_threshold: 0
|
||||
combination_method: 1
|
||||
frustum_clearing_enabled: true
|
||||
frustum_clearing_pixel_step: 8
|
||||
combination_method: 1
|
||||
262
doc/directional_layer.md
Normal file
262
doc/directional_layer.md
Normal file
@@ -0,0 +1,262 @@
|
||||
# DirectionalLayer — grid hướng cho planner
|
||||
|
||||
`DirectionalLayer` giữ một direction field cho planner, **không ghi cost vào master costmap**:
|
||||
`updateCosts()` rỗng. Chỉ dùng với global costmap không rolling. Bật trên rolling costmap sẽ
|
||||
log lỗi và layer không lên READY.
|
||||
|
||||
## Dữ liệu host phải gửi
|
||||
|
||||
Gọi `addStaticMap(topic, robot_nav_msgs::OccupancyGrid)` cho bản đồ và cho grid hướng. Mỗi lần
|
||||
boot, đổi hoặc nạp lại map: **gửi static map trước, sau đó các zone grid, cuối cùng direction
|
||||
grid**. Ngay cả map không có zone hướng cũng phải gửi grid toàn 0; `data` rỗng cũng được coi là
|
||||
không ràng buộc. Không gửi thì layer tiếp tục PENDING và planner chờ hoặc từ chối.
|
||||
|
||||
| `data` | hướng trong map frame |
|
||||
|---|---|
|
||||
| `0` | không ràng buộc |
|
||||
| `1`, `2`, `3`, `4` | +X, +45°, +Y, +135° |
|
||||
| `5`, `6`, `7`, `8` | -X, -135°, -Y, -45° |
|
||||
|
||||
Các hướng tăng ngược chiều kim đồng hồ từ +X; giá trị là direction index `0..7` cộng 1. Không dùng
|
||||
`-1` để biểu diễn unknown: mọi giá trị ngoài `0..8` bị từ chối.
|
||||
|
||||
```cpp
|
||||
// map là static map hiện tại; topic phải khớp cấu hình thực tế.
|
||||
robot_nav_msgs::OccupancyGrid direction;
|
||||
direction.header.frame_id = map.header.frame_id;
|
||||
direction.info = map.info;
|
||||
direction.data.assign(static_cast<size_t>(map.info.width) * map.info.height, 0);
|
||||
// direction.data[y * map.info.width + x] = 1; // ví dụ ô hướng +X
|
||||
nav->addStaticMap("map", map);
|
||||
// Gửi từng zone grid đang bật ở đây.
|
||||
nav->addStaticMap("direction_map", direction);
|
||||
```
|
||||
|
||||
Grid được kiểm với **master geometry hiện tại**:
|
||||
|
||||
| trường | điều kiện |
|
||||
|---|---|
|
||||
| `header.frame_id` | không rỗng, bằng global frame sau khi bỏ tối đa một `/` đầu |
|
||||
| `info.width`, `info.height` | bằng master; tích phải vừa `vector<uint8_t>::max_size()` |
|
||||
| `info.resolution` | hữu hạn, dương và bằng master với sai số tối đa `1e-6` |
|
||||
| `info.origin.position.x/y` | hữu hạn và bằng master với sai số tối đa `1e-6` |
|
||||
| `info.origin.position.z` | hữu hạn; không so với master |
|
||||
| `info.origin.orientation` | hữu hạn; `abs(x/y/z) <= 1e-6`, `abs(abs(w)-1) <= 1e-6` hoặc `abs(w) <= 1e-6` (identity hoặc quaternion zero gần đúng) |
|
||||
| `data` | rỗng, hoặc đúng `width * height` phần tử, tất cả trong `0..8` |
|
||||
|
||||
Sai bất kỳ điều kiện nào log `DirectionalLayer <name>: invalid direction grid: <reason>` và grid
|
||||
bị bỏ. Field đang READY không bị xoá chỉ vì một grid hướng sai; gửi static map mới mới đưa nó về
|
||||
PENDING. Sau resize hoặc đổi origin, `matchSize()` cũng đưa layer về PENDING.
|
||||
|
||||
### Ví dụ một message chuẩn
|
||||
|
||||
Map đồ chơi 8 × 6 ô, resolution 0.5 m, tức 4 m × 3 m, origin `(-2.0, -1.5)`. Map thật lớn hơn nhiều,
|
||||
nhưng message có đúng cấu trúc này. Có hai zone:
|
||||
|
||||
- làn một chiều **+X** (mã `1`), rộng 1 m, ở hàng `y = 2..3`, cột `x = 1..6`, tức world
|
||||
`x ∈ [-1.5, 1.5)`, `y ∈ [-0.5, 0.5)`;
|
||||
- cột một chiều **+Y** (mã `3`) ở `x = 7`, tức world `x ∈ [1.5, 2.0)`, suốt chiều cao map.
|
||||
|
||||
Nhìn theo toạ độ map (hàng trên cùng là `y = 5`):
|
||||
|
||||
```text
|
||||
y=5 0 0 0 0 0 0 0 3
|
||||
y=4 0 0 0 0 0 0 0 3
|
||||
y=3 0 1 1 1 1 1 1 3
|
||||
y=2 0 1 1 1 1 1 1 3
|
||||
y=1 0 0 0 0 0 0 0 3
|
||||
y=0 0 0 0 0 0 0 0 3
|
||||
x=0 1 2 3 4 5 6 7
|
||||
```
|
||||
|
||||
`data[y * width + x]`, hàng `y = 0` đứng đầu mảng; **không** lật theo kiểu toạ độ ảnh. Ô `(x, y)` phủ
|
||||
world `[origin_x + x·res, origin_x + (x+1)·res) × [origin_y + y·res, origin_y + (y+1)·res)`.
|
||||
|
||||
Message gửi trên `direction_topic` (mặc định `direction_map`):
|
||||
|
||||
```yaml
|
||||
header:
|
||||
stamp: <tuỳ ý — không bị kiểm>
|
||||
frame_id: "map" # = global frame của costmap
|
||||
info:
|
||||
map_load_time: <tuỳ ý — không bị kiểm>
|
||||
resolution: 0.5 # = resolution của static map
|
||||
width: 8 # = width của static map
|
||||
height: 6 # = height của static map
|
||||
origin:
|
||||
position: {x: -2.0, y: -1.5, z: 0.0} # x, y = origin của static map
|
||||
orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0} # không xoay
|
||||
data: [0, 0, 0, 0, 0, 0, 0, 3, # y = 0
|
||||
0, 0, 0, 0, 0, 0, 0, 3, # y = 1
|
||||
0, 1, 1, 1, 1, 1, 1, 3, # y = 2
|
||||
0, 1, 1, 1, 1, 1, 1, 3, # y = 3
|
||||
0, 0, 0, 0, 0, 0, 0, 3, # y = 4
|
||||
0, 0, 0, 0, 0, 0, 0, 3] # y = 5 → 48 phần tử = 8 × 6
|
||||
```
|
||||
|
||||
Cách đơn giản nhất để khớp geometry: **chép nguyên `header.frame_id` và `info` của static map** vừa
|
||||
gửi, chỉ thay `data`. Code C++ dựng đúng message trên:
|
||||
|
||||
```cpp
|
||||
// `map` là static map đã gửi trên map_topic ("map"): frame "map", 8 × 6, res 0.5, origin (-2.0, -1.5).
|
||||
robot_nav_msgs::OccupancyGrid direction;
|
||||
direction.header.frame_id = map.header.frame_id;
|
||||
direction.info = map.info;
|
||||
const uint32_t w = map.info.width;
|
||||
const uint32_t h = map.info.height;
|
||||
direction.data.assign(static_cast<size_t>(w) * h, 0); // 0 = không ràng buộc
|
||||
for (uint32_t y = 2; y <= 3; ++y)
|
||||
for (uint32_t x = 1; x <= 6; ++x)
|
||||
direction.data[y * w + x] = 1; // +X
|
||||
for (uint32_t y = 0; y < h; ++y)
|
||||
direction.data[y * w + 7] = 3; // +Y
|
||||
|
||||
nav->addStaticMap("map", map); // 1. static map
|
||||
// 2. các zone grid khác (forbidden, preferred, ...) nếu layer của chúng đang bật
|
||||
nav->addStaticMap("direction_map", direction); // 3. direction grid, sau cùng
|
||||
```
|
||||
|
||||
Log khi layer nhận (với `debug_state: true`, tên layer ví dụ `direction_zones`):
|
||||
|
||||
```text
|
||||
[debug] DirectionalLayer direction_zones: PENDING generation=7 # khi static map tới
|
||||
[debug] DirectionalLayer direction_zones: READY generation=8 # khi direction grid hợp lệ tới
|
||||
```
|
||||
|
||||
**Map không có zone hướng:** gửi cùng `header` và `info`, để `data: []`. Layer lên READY và không
|
||||
ràng buộc ô nào. Grid toàn `0` đủ `width × height` phần tử cũng cho kết quả như vậy.
|
||||
|
||||
**Message bị từ chối và reason trong log** `DirectionalLayer <tên>: invalid direction grid: <reason>`:
|
||||
|
||||
| sai | reason |
|
||||
|---|---|
|
||||
| gửi nhầm static map vào `direction_topic` | ví dụ `data index=10 code=100`: index của ô `100` hoặc `-1` đầu tiên |
|
||||
| ô `-1` (unknown) | `data index=0 code=-1` |
|
||||
| `width: 9` | `width=9 height=6` |
|
||||
| `frame_id: "odom"` | `frame_id=odom expected=map` |
|
||||
| thiếu một phần tử (`data` 47 phần tử) | `data.size=47 expected=48` |
|
||||
| `origin` lệch, ví dụ `x: -2.05` | `origin.x=-2.05 origin.y=-1.5 origin.z=0` |
|
||||
| origin xoay 90° | `orientation.x=0 y=0 z=0.707107 w=0.707107` |
|
||||
|
||||
Chỉ phần tử sai **đầu tiên** được báo. Grid bị từ chối không thay field đang có: layer giữ nguyên
|
||||
state trước đó (PENDING nếu vừa có map mới).
|
||||
|
||||
Gateway chuyển **mỗi grid** theo type: global lần lượt `DIRECTIONAL_LAYER`, `STATIC_LAYER`,
|
||||
`PREFERRED_LAYER`, `UNPREFERRED_LAYER`; local nhận ba type sau, không nhận directional. Layer tự
|
||||
lọc topic, bỏ qua grid của topic khác. Directional đi trước để map mới có cùng geometry vẫn đặt
|
||||
field cũ về PENDING trước khi StaticLayer có thể báo current; tránh lập plan ghép map mới với
|
||||
zone cũ. Thứ tự này không đồng bộ revision của các zone StaticLayer khác: với map cùng geometry,
|
||||
chúng có thể vẫn current trên grid cũ. Host phải gửi lại toàn bộ zone trước direction grid.
|
||||
|
||||
## Cấu hình
|
||||
|
||||
Thêm `{name: directional_layer, type: "DirectionalLayer"}` vào `plugins:` của **global** costmap
|
||||
và bật block `directional_layer:` trong `directional_layer_params.yaml`:
|
||||
|
||||
| key | mặc định | ý nghĩa |
|
||||
|---|---|---|
|
||||
| `enabled` | `false` | bật kiểm tra hướng |
|
||||
| `map_topic` | `"map"` | phải khớp topic map của StaticLayer |
|
||||
| `direction_topic` | `"direction_map"` | phải khác `map_topic`; hai topic đều không rỗng khi bật |
|
||||
| `max_deviation_deg` | `90.0` | [deg], hữu hạn, `0 < x < 180`; sai thì throw lúc init, dưới `22.5` có warning |
|
||||
| `debug_state` | `true` | log chuyển state/generation |
|
||||
|
||||
Mặc định đóng gói nằm tại [`config/directional_layer_params.yaml`](../config/directional_layer_params.yaml).
|
||||
`DirectionalLayer::onInitialize()` lấy `PNKX_NAV_CORE_CONFIG_DIR` làm root nếu đường dẫn tồn tại,
|
||||
nếu không dùng root rỗng; `getSourceFile(root, filename)` chỉ duyệt đệ quy `root/config` và lấy
|
||||
file trùng tên đầu tiên theo thứ tự iterator, không có thứ tự ưu tiên xác định giữa các bản trùng.
|
||||
Root rỗng tương ứng `config` tương đối với working directory. Không tìm thấy file thì init lỗi.
|
||||
`robot::NodeHandle priv_nh(nh, name_)` override từng key khi `hasParam()` trả true. Topic khớp
|
||||
chính xác hoặc topic nhận bằng `"/" + topic_cau_hinh`; tránh cấu hình lẫn dấu `/`.
|
||||
|
||||
## State và quy tắc hướng
|
||||
|
||||
| state | ý nghĩa |
|
||||
|---|---|
|
||||
| `DISABLED` | layer tắt, không ràng buộc |
|
||||
| `PENDING` | bật nhưng chưa có field phù hợp; không current |
|
||||
| `READY` | đã nhận grid hợp lệ sau static map |
|
||||
|
||||
Mỗi lần publish state tăng `generation`, kể cả publish lại cùng state. Static map mới xoá field cũ
|
||||
và đưa layer về PENDING. Grid hướng đến trước static map bị bỏ. Khi PENDING kéo dài, `updateBounds`
|
||||
log sau 5 s rồi lặp mỗi 5 s. `reset()` giữ field READY nếu geometry chưa đổi, nếu khác thì PENDING.
|
||||
|
||||
Với displacement `v` và hướng đơn vị `d_hat`, ô cho phép khi
|
||||
`dot(v, d_hat) >= (cos(max_deviation_rad) - 1e-9) * |v|`. Biên được tính vào. Riêng đúng 90°
|
||||
giữ phép thử cũ `dot(v, d) >= -1e-9 * (|dx| + |dy|)`, với `d` là vector nguyên tám hướng
|
||||
(chéo chưa chuẩn hoá). Displacement bằng 0, kể cả quay tại chỗ, luôn được phép. Ví dụ code `1`
|
||||
với giới hạn 45°: đi `(1, 1)` đúng biên được phép; `(0, 1)` bị cấm; đi lùi `(-1, 0)` bị cấm.
|
||||
|
||||
## API cho planner
|
||||
|
||||
`LayeredCostmap::getDirectionFieldSnapshot()` lấy `DirectionFieldSnapshot` qua
|
||||
`DirectionFieldProvider::directionSnapshot()`: `state`, `generation`, và
|
||||
`std::shared_ptr<const DirectionField> field`. Field chỉ khác null khi READY; immutable nên planner
|
||||
có thể giữ snapshot suốt search mà không giữ costmap lock. Không có provider đang bật trả DISABLED;
|
||||
nhiều provider đang bật trả PENDING. Planner vẫn phải xử lý thay đổi generation khi bàn giao plan.
|
||||
|
||||
| API | công dụng |
|
||||
|---|---|
|
||||
| `codeAt(int64_t x, int64_t y, uint8_t* code_out) const` | đọc ô an toàn, `false` nếu ngoài grid hoặc output null |
|
||||
| `code(uint32_t x, uint32_t y) const` | đọc ô, caller phải bảo đảm trong grid |
|
||||
| `checkSegment(double wx0, double wy0, double wx1, double wy1, SegmentViolation* first = nullptr) const` | kiểm đoạn theo toạ độ thế giới [m]; trả `kAllowed`, `kViolation`, `kOutOfGrid` |
|
||||
| `geometry()`, `maxDeviationRad()`, `hasConstraints()` | geometry, ngưỡng [rad], có ô khác 0 hay không |
|
||||
|
||||
Hàm tự do trong namespace `robot_costmap_2d`:
|
||||
|
||||
```cpp
|
||||
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad);
|
||||
template <typename Visitor>
|
||||
bool traverseGridSegment(double x0, double y0, double x1, double y1, Visitor&& visitor);
|
||||
```
|
||||
|
||||
`traverseGridSegment` dùng toạ độ ô, visitor nhận `(int64_t x, int64_t y)` và trả `false` để
|
||||
dừng; caller tự kiểm bounds. Nó chỉ thăm phần giao có chiều dài dương, trừ đoạn dài 0 thăm ô chứa
|
||||
điểm. Đoạn nằm trên biên thuộc ô chỉ số lớn hơn; chạm góc không thăm hai ô kề; endpoint nằm trên
|
||||
biên không thăm ô phía sau endpoint.
|
||||
|
||||
```cpp
|
||||
using namespace robot_costmap_2d;
|
||||
const auto snap = layered_costmap->getDirectionFieldSnapshot();
|
||||
if (snap.state == DirectionFieldState::kPending) return false;
|
||||
if (snap.state == DirectionFieldState::kReady) {
|
||||
SegmentViolation first{};
|
||||
if (!snap.field || snap.field->checkSegment(x0, y0, x1, y1, &first) !=
|
||||
SegmentResult::kAllowed) return false;
|
||||
}
|
||||
// Trước khi bàn giao plan, lấy snapshot mới và kiểm state/generation vẫn khớp.
|
||||
```
|
||||
|
||||
## Planner nào áp dụng
|
||||
|
||||
`SBPLLatticePlanner` dùng `DirectionalEnvironmentNAVXYTHETALAT::GetActionCost()` và bảng mask
|
||||
tính trước cho từng motion primitive. PENDING hoặc geometry lệch thì từ chối plan; generation đổi
|
||||
thì tìm lại từ đầu; ngưỡng lệch đổi thì dựng lại bảng. Snapshot đổi trong lúc plan làm kết quả bị
|
||||
bỏ. Kiểm tra chỉ theo đường tâm điểm tham chiếu của primitive, **không kiểm footprint**.
|
||||
|
||||
`DetourPathRecovery`, khi dùng SBPL và `costmap_source: combined` hoặc `global`, khởi tạo planner
|
||||
với global costmap nên áp dụng field; `local` không có field này. `CustomPlanner`, `TwoPointsPlanner`,
|
||||
`DockPlanner`, local planner và các recovery khác không áp dụng quy tắc này. Trong runtime config
|
||||
đang có, SBPL là backup global planner: zone hướng chỉ tác dụng khi SBPL thực sự lập plan. Không
|
||||
coi đây là bảo đảm một chiều cho toàn bộ chuyển động robot.
|
||||
|
||||
## Log thường gặp
|
||||
|
||||
| log | nghĩa và việc host cần làm |
|
||||
|---|---|
|
||||
| `DirectionalLayer %s: direction grid arrived before static map` | Gửi lại static map rồi direction grid. |
|
||||
| `DirectionalLayer %s: invalid direction grid: %s` | Sửa geometry, frame, orientation, size hoặc code theo reason rồi gửi lại. |
|
||||
| `DirectionalLayer %s: grid discarded because map state changed during validation` | Map đổi trong lúc kiểm; gửi lại grid khớp map mới. |
|
||||
| `DirectionalLayer %s: PENDING for %.1f seconds` | Kiểm topic và gửi direction grid sau map. |
|
||||
| `DirectionalLayer %s: rolling costmap is unsupported` | Chỉ cấu hình trên global costmap không rolling. |
|
||||
| `[debug] DirectionalLayer %s: %s generation=%llu` | Theo dõi lifecycle; kiểm thứ tự gửi nếu không lên READY. |
|
||||
| `[sbpl_lattice_planner] direction field is not ready (%.1f s); refusing to plan` | Gửi lại grid hợp lệ sau static map. |
|
||||
| `[sbpl_lattice_planner] direction field geometry does not match the active grid` | Đồng bộ grid hướng với geometry của costmap planner dùng. |
|
||||
| `[sbpl_lattice_planner] direction state=%s generation=%llu rejected=%llu` | Debug số primitive bị chặn; kiểm hướng zone nếu không có đường. |
|
||||
| `[sbpl_lattice_planner] direction table max deviation changed %.3f -> %.3f deg` | Bảng được dựng lại theo ngưỡng mới; kiểm cấu hình nếu thay đổi ngoài ý muốn. |
|
||||
| `[move_base2] PlannerRunner: waiting for global costmap; not current: %s` | Kiểm và gửi dữ liệu cho từng layer được nêu. |
|
||||
| `[move_base2] PlannerRunner: still waiting for global costmap (%.2f s); not current: %s` | Vẫn chờ; kiểm topic và map đã gửi. |
|
||||
| `[move_base2] PlannerRunner: global costmap readiness timed out after %.2f s; not current: %s` | Lượt plan thất bại; sửa dữ liệu layer trước khi thử lại. |
|
||||
| `[move_base2] PlannerRunner: global costmap is ready; planning resumes.` | Dữ liệu đã current; planner tiếp tục. |
|
||||
|
||||
Xem thêm [hướng dẫn host C++](../../../../doc/cpp_host_guide.md) về readiness, TF và đổi map.
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -79,6 +79,14 @@ namespace robot_costmap_2d
|
||||
class Costmap2DROBOT
|
||||
{
|
||||
public:
|
||||
/** @brief Select the namespace containing shared costmap parameters. */
|
||||
static robot::NodeHandle commonParametersHandle(robot::NodeHandle& tree_nh);
|
||||
|
||||
/** @brief Fill missing costmap layer parameters from the shared layer block. */
|
||||
static void copyParentParameters(const std::string& costmap_name, const std::string& plugin_name,
|
||||
const std::string& plugin_type, robot::NodeHandle& source_nh,
|
||||
robot::NodeHandle& target_nh);
|
||||
|
||||
/**
|
||||
* @brief Constructor for the wrapper
|
||||
* @param name The name for this costmap
|
||||
@@ -157,6 +165,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
|
||||
@@ -174,6 +211,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_;
|
||||
@@ -255,7 +303,6 @@ 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
|
||||
@@ -279,6 +326,11 @@ private:
|
||||
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,const std::string& name, robot::NodeHandle& nh);
|
||||
};
|
||||
|
||||
@@ -72,6 +72,9 @@ public:
|
||||
void addExtraBounds(double mx0, double my0, double mx1, double my1);
|
||||
|
||||
protected:
|
||||
/// Merge one known layer cell with the same policy in aligned and transformed grids.
|
||||
static unsigned char mergeCost(unsigned char master_cost, unsigned char layer_cost, bool use_maximum);
|
||||
|
||||
/*
|
||||
* Updates the master_grid within the specified
|
||||
* bounding box using this layer's values.
|
||||
|
||||
307
include/robot_costmap_2d/depth_camera_obstacle_layer.h
Normal file
307
include/robot_costmap_2d/depth_camera_obstacle_layer.h
Normal file
@@ -0,0 +1,307 @@
|
||||
/*********************************************************************
|
||||
* 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).
|
||||
* Additions over the source, both off by default so the source behaviour stays the default:
|
||||
* the attach band width is a per-source parameter (`attach_distance`, the source hard-codes
|
||||
* 0.12 m), and `occlusion_guard` adds depth-ray evidence to the clearing (keep a stored point a
|
||||
* nearer return hides, clear one the camera sees past).
|
||||
*********************************************************************/
|
||||
#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 ("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]
|
||||
/// [m] Points this close to a face are not marked: an object cut by the image edge or the
|
||||
/// noisy image border. 0.12 in the source; a wide band hides low objects near the lower FOV edge.
|
||||
float attach_distance = 0.12f;
|
||||
|
||||
/**
|
||||
* @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
|
||||
* @param attach_d width of the attach band [m], see attach_distance
|
||||
*/
|
||||
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
|
||||
double max_d, bool optical, double attach_d = 0.12);
|
||||
|
||||
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
|
||||
bool inside(const Eigen::Vector3f& p) const;
|
||||
|
||||
/// Within attach_distance of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
|
||||
bool nearFace(const Eigen::Vector3f& p) const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Nearest depth return per viewing ray of one observation, for the occlusion guard.
|
||||
*
|
||||
* Rays are binned by their tangent (x / z and y / z in the optical frame); each bin keeps the
|
||||
* smallest range it saw. It is built from the whole cloud before the height gate: the floor the
|
||||
* gate drops is exactly what shows that a stored point is no longer there.
|
||||
*/
|
||||
struct DepthCameraRangeImage
|
||||
{
|
||||
/// What the returns around the ray to a stored point say about it.
|
||||
enum class Evidence
|
||||
{
|
||||
kNone, ///< no usable return around the ray, or a return at the point itself
|
||||
kOccluded, ///< something nearer hides the point: clearing must keep it
|
||||
kSeenThrough, ///< the camera sees past the point: it is gone
|
||||
};
|
||||
|
||||
/// Empty image covering the frustum of a sensor at T_global_sensor.
|
||||
void reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, bool optical);
|
||||
/// Adds one return given in the sensor frame.
|
||||
void addSensorPoint(const Eigen::Vector3f& p);
|
||||
/// Evidence about a point given in the global frame; kNone while the image is empty.
|
||||
Evidence test(const Eigen::Vector3f& p_global) const;
|
||||
bool empty() const
|
||||
{
|
||||
return min_range_.empty();
|
||||
}
|
||||
|
||||
private:
|
||||
Eigen::Vector3f toOptical(const Eigen::Vector3f& p) const;
|
||||
/// Bin of a point in optical coordinates; false when it is too close or outside the image.
|
||||
bool bin(const Eigen::Vector3f& q, int& u, int& v) const;
|
||||
std::size_t index(int u, int v) const
|
||||
{
|
||||
return static_cast<std::size_t>(v + half_v_) * (2 * half_u_ + 1) + static_cast<std::size_t>(u + half_u_);
|
||||
}
|
||||
|
||||
Eigen::Isometry3f sensor_from_global_ = Eigen::Isometry3f::Identity();
|
||||
bool optical_ = true;
|
||||
int half_u_ = 0;
|
||||
int half_v_ = 0;
|
||||
std::vector<float> min_range_; ///< [m] (2 half_u + 1) x (2 half_v + 1), +inf where nothing returned
|
||||
};
|
||||
|
||||
/// 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;
|
||||
DepthCameraRangeImage range; ///< whole cloud before the gate; empty unless occlusion_guard
|
||||
};
|
||||
|
||||
/// 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]
|
||||
double attach_distance = 0.12; ///< [m] marking-free band near each frustum face
|
||||
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;
|
||||
|
||||
/// range_images[i] belongs to frustums[i]; null when that observation has no range image.
|
||||
void clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
|
||||
const std::vector<DepthCameraFrustum>& frustums,
|
||||
const std::vector<const DepthCameraRangeImage*>& range_images, 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]
|
||||
bool occlusion_guard_ = false; ///< depth-ray evidence in the clearing, see clearMarkingByKdtree
|
||||
|
||||
/// (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;
|
||||
std::size_t kept_occluded = 0; ///< points the kd-tree test would clear, kept as hidden
|
||||
std::size_t cleared_seen_through = 0; ///< points the kd-tree test would keep, cleared as seen past
|
||||
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_
|
||||
225
include/robot_costmap_2d/direction_field.h
Normal file
225
include/robot_costmap_2d/direction_field.h
Normal file
@@ -0,0 +1,225 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
|
||||
#define ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_nav_msgs/OccupancyGrid.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief Geometry of an unrotated grid in its global frame. */
|
||||
struct DirectionGeometry
|
||||
{
|
||||
uint32_t width, height; ///< Grid dimensions [cells].
|
||||
double resolution; ///< Cell size [m/cell].
|
||||
double origin_x, origin_y; ///< Lower-left grid origin [m] in frame_id.
|
||||
std::string frame_id; ///< Global coordinate frame.
|
||||
};
|
||||
|
||||
/** @brief Reason a complete direction grid failed validation. */
|
||||
enum class DirectionValidationError
|
||||
{
|
||||
kNone, kOverflow, kGeometry, kFrame, kOrientation, kSize, kCode
|
||||
};
|
||||
|
||||
/** @brief Typed validation result with a human-readable offending value. */
|
||||
struct DirectionValidationResult
|
||||
{
|
||||
DirectionValidationError error;
|
||||
std::string message;
|
||||
explicit operator bool() const { return error == DirectionValidationError::kNone; }
|
||||
};
|
||||
|
||||
/** @brief Validate the entire message against the master geometry.
|
||||
* @param grid Grid in the expected global frame. Codes are 0 for unconstrained
|
||||
* and 1..8 for direction indices 0..7 in CCW order from +X:
|
||||
* (+1,0), (+1,+1), (0,+1), (-1,+1), (-1,0), (-1,-1), (0,-1), (+1,-1).
|
||||
* @param expected Required master dimensions, resolution [m/cell], origin [m], and frame.
|
||||
* @return Typed error and description; empty data is valid after geometry checks.
|
||||
* An identity quaternion or the default all-zero quaternion means no rotation.
|
||||
*/
|
||||
DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected);
|
||||
|
||||
/** @brief Traverse a segment in grid coordinates with allocation-free 2D DDA.
|
||||
* @param x0 Start x [cells] relative to the grid origin.
|
||||
* @param y0 Start y [cells] relative to the grid origin.
|
||||
* @param x1 End x [cells] relative to the grid origin.
|
||||
* @param y1 End y [cells] relative to the grid origin.
|
||||
* @param visitor Called in order with signed integer cell indices (x, y); return
|
||||
* false to stop. The visitor must perform its own grid bounds checks.
|
||||
* @return False for invalid coordinates or a visitor-requested stop.
|
||||
* Cells own [x,x+1) x [y,y+1). Only positive-length overlaps are visited:
|
||||
* a boundary-aligned segment belongs to the higher-index cell, a corner touch
|
||||
* does not visit the adjacent cells, and an endpoint on a boundary does not
|
||||
* visit the cell beyond it. A zero-length segment visits its point's cell.
|
||||
* Coordinates must fit within the documented int64_t safety range.
|
||||
*/
|
||||
template <typename Visitor>
|
||||
bool traverseGridSegment(double x0, double y0, double x1, double y1, Visitor&& visitor)
|
||||
{
|
||||
const double limit = static_cast<double>(std::numeric_limits<int64_t>::max()) / 2.0;
|
||||
if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1) ||
|
||||
std::abs(x0) >= limit || std::abs(y0) >= limit || std::abs(x1) >= limit || std::abs(y1) >= limit)
|
||||
return false;
|
||||
|
||||
const long double dx = static_cast<long double>(x1) - x0;
|
||||
const long double dy = static_cast<long double>(y1) - y0;
|
||||
int64_t x = static_cast<int64_t>(std::floor(x0));
|
||||
int64_t y = static_cast<int64_t>(std::floor(y0));
|
||||
if (dx < 0 && x0 == std::floor(x0))
|
||||
--x;
|
||||
if (dy < 0 && y0 == std::floor(y0))
|
||||
--y;
|
||||
if (dx == 0 && dy == 0)
|
||||
return visitor(x, y);
|
||||
|
||||
const int sx = (dx > 0) - (dx < 0);
|
||||
const int sy = (dy > 0) - (dy < 0);
|
||||
const long double adx = std::abs(dx);
|
||||
const long double ady = std::abs(dy);
|
||||
while (true)
|
||||
{
|
||||
if (!visitor(x, y))
|
||||
return false;
|
||||
// Recompute crossings from the original point to avoid accumulated error at corners.
|
||||
const long double distance_x = sx ? std::abs((sx > 0 ? x + 1 : x) - static_cast<long double>(x0)) : 0;
|
||||
const long double distance_y = sy ? std::abs((sy > 0 ? y + 1 : y) - static_cast<long double>(y0)) : 0;
|
||||
const bool cross_x = sx && distance_x < adx;
|
||||
const bool cross_y = sy && distance_y < ady;
|
||||
if (!cross_x && !cross_y)
|
||||
break;
|
||||
if (!cross_y)
|
||||
{
|
||||
x += sx;
|
||||
continue;
|
||||
}
|
||||
if (!cross_x)
|
||||
{
|
||||
y += sy;
|
||||
continue;
|
||||
}
|
||||
const long double left = distance_x * ady;
|
||||
const long double right = distance_y * adx;
|
||||
if (left <= right)
|
||||
x += sx;
|
||||
if (right <= left)
|
||||
y += sy;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @brief Return allowed direction indices for a displacement.
|
||||
* @param dx Displacement along +X [m or cells] in the global/grid frame.
|
||||
* @param dy Displacement along +Y [same units as dx] in the global/grid frame.
|
||||
* @param max_deviation_rad Maximum inclusive angular deviation [rad], in (0, pi).
|
||||
* @return Bit k is set when direction k accepts the displacement within relative tolerance.
|
||||
*/
|
||||
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad);
|
||||
|
||||
/** @brief Outcome of a world-space segment query. */
|
||||
enum class SegmentResult
|
||||
{
|
||||
kAllowed, ///< All visited constrained cells permit the displacement.
|
||||
kViolation, ///< At least one visited cell forbids the displacement.
|
||||
kOutOfGrid ///< Any point is outside the grid or coordinates are invalid.
|
||||
};
|
||||
|
||||
/** @brief First prohibited cell and world-frame segment displacement. */
|
||||
struct SegmentViolation
|
||||
{
|
||||
uint32_t x, y; ///< Cell indices [cells] relative to the grid origin.
|
||||
uint8_t code; ///< Direction code 1..8.
|
||||
double dx, dy; ///< Segment displacement [m] in the global frame.
|
||||
};
|
||||
|
||||
/** @brief Immutable validated grid, safe to share and hold for a whole search. */
|
||||
class DirectionField
|
||||
{
|
||||
public:
|
||||
DirectionField(const DirectionField&) = delete;
|
||||
DirectionField& operator=(const DirectionField&) = delete;
|
||||
|
||||
/** @brief Validate and construct a field; invalid input returns null.
|
||||
* @param grid Complete direction message in the global frame.
|
||||
* @param expected Master grid geometry in the global frame.
|
||||
* @param max_deviation_rad Maximum inclusive deviation [rad], in (0, pi).
|
||||
* @param result Optional output explaining validation success or failure.
|
||||
*/
|
||||
static std::shared_ptr<const DirectionField> create(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected,
|
||||
double max_deviation_rad,
|
||||
DirectionValidationResult* result = nullptr);
|
||||
|
||||
/** @brief Return cell code: 0 unconstrained, 1..8 direction_index + 1.
|
||||
* @param x Column [cells] from the grid origin; must be less than width.
|
||||
* @param y Row [cells] from the grid origin; must be less than height.
|
||||
* @pre Both indices are in bounds. Use codeAt() for untrusted indices.
|
||||
*/
|
||||
uint8_t code(uint32_t x, uint32_t y) const;
|
||||
|
||||
/** @brief Read a cell only when both signed indices are in bounds.
|
||||
* @param x Column [cells] from the grid origin.
|
||||
* @param y Row [cells] from the grid origin.
|
||||
* @param code_out Output code; must not be null. Unchanged on failure.
|
||||
* @return False for an out-of-grid index or null output pointer.
|
||||
*/
|
||||
bool codeAt(int64_t x, int64_t y, uint8_t* code_out) const;
|
||||
|
||||
/** @brief Return the immutable master geometry and global frame. */
|
||||
const DirectionGeometry& geometry() const { return geometry_; }
|
||||
/** @brief Return the immutable maximum angular deviation [rad]. */
|
||||
double maxDeviationRad() const { return max_deviation_rad_; }
|
||||
/** @brief True if at least one cell has a nonzero direction code. */
|
||||
bool hasConstraints() const { return has_constraints_; }
|
||||
|
||||
/** @brief Check all owned cells traversed by a world-space segment.
|
||||
* @param wx0 Start x [m] in the global frame.
|
||||
* @param wy0 Start y [m] in the global frame.
|
||||
* @param wx1 End x [m] in the global frame.
|
||||
* @param wy1 End y [m] in the global frame.
|
||||
* @param first Optional output populated on kViolation.
|
||||
* @return kAllowed, kViolation, or kOutOfGrid; see SegmentResult.
|
||||
*/
|
||||
SegmentResult checkSegment(double wx0, double wy0, double wx1, double wy1,
|
||||
SegmentViolation* first = nullptr) const;
|
||||
|
||||
private:
|
||||
DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry,
|
||||
double max_deviation_rad);
|
||||
DirectionGeometry geometry_;
|
||||
std::vector<uint8_t> codes_;
|
||||
double max_deviation_rad_;
|
||||
bool has_constraints_;
|
||||
};
|
||||
|
||||
/** @brief Disabled, waiting for a current grid, or ready for queries. */
|
||||
enum class DirectionFieldState { kDisabled, kPending, kReady };
|
||||
|
||||
/** @brief Consistent state and generation with an immutable, shared field.
|
||||
* The field is non-null only in kReady. Readers may hold it through a whole
|
||||
* search while the layer publishes a newer generation on another thread.
|
||||
*/
|
||||
struct DirectionFieldSnapshot
|
||||
{
|
||||
DirectionFieldState state = DirectionFieldState::kDisabled;
|
||||
std::shared_ptr<const DirectionField> field;
|
||||
uint64_t generation = 0;
|
||||
};
|
||||
|
||||
/** @brief Core-side snapshot contract; avoids linking core against libplugins. */
|
||||
class DirectionFieldProvider
|
||||
{
|
||||
public:
|
||||
virtual ~DirectionFieldProvider() = default;
|
||||
/** @brief Return a consistent snapshot safe to retain on a planner thread. */
|
||||
virtual DirectionFieldSnapshot directionSnapshot() const = 0;
|
||||
};
|
||||
} // namespace robot_costmap_2d
|
||||
#endif // ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
|
||||
@@ -1,40 +1,73 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_V1_H_
|
||||
#define ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_V1_H_
|
||||
#ifndef ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
#define ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
|
||||
#include <robot_costmap_2d/static_layer.h>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
#include <robot_costmap_2d/layer.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
class DirectionalLayer : public StaticLayer
|
||||
{
|
||||
public:
|
||||
DirectionalLayer();
|
||||
virtual ~DirectionalLayer();
|
||||
bool laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan);
|
||||
void resetMap();
|
||||
/** @brief Publish immutable direction snapshots without modifying master costs.
|
||||
* The host thread feeds map and direction messages through dataCallBack(); the
|
||||
* costmap update thread calls updateBounds()/updateCosts(); planner threads use
|
||||
* directionSnapshot() and may retain a snapshot for an entire search.
|
||||
* When both mutexes are required, acquire the master costmap mutex before the
|
||||
* layer mutex, never the reverse. Snapshot readers hold only the layer mutex
|
||||
* briefly. Layer::isCurrent() still reads the legacy non-atomic current_ flag.
|
||||
*/
|
||||
class DirectionalLayer : public Layer, public DirectionFieldProvider
|
||||
{
|
||||
public:
|
||||
DirectionalLayer();
|
||||
~DirectionalLayer() override = default;
|
||||
/** @brief Identify this plugin as a directional layer. */
|
||||
LayerType getType() const override { return LayerType::DIRECTIONAL_LAYER; }
|
||||
/** @brief Copy a consistent immutable snapshot for a planner thread. */
|
||||
DirectionFieldSnapshot directionSnapshot() const override;
|
||||
/** @brief Update thread: leave bounds unchanged and report a stuck pending state.
|
||||
* @param robot_x Robot x [m] in the global frame.
|
||||
* @param robot_y Robot y [m] in the global frame.
|
||||
* @param robot_yaw Robot yaw [rad] in the global frame.
|
||||
* @param min_x Lower x bound [m] in the global frame.
|
||||
* @param min_y Lower y bound [m] in the global frame.
|
||||
* @param max_x Upper x bound [m] in the global frame.
|
||||
* @param max_y Upper y bound [m] in the global frame.
|
||||
*/
|
||||
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y) override;
|
||||
/** @brief Update thread: leave master costs unchanged.
|
||||
* @param master Master costmap in the global frame.
|
||||
* @param min_i Lower x cell index relative to the grid origin.
|
||||
* @param min_j Lower y cell index relative to the grid origin.
|
||||
* @param max_i Upper x cell index relative to the grid origin.
|
||||
* @param max_j Upper y cell index relative to the grid origin.
|
||||
*/
|
||||
void updateCosts(Costmap2D& /*master*/, int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/) override {}
|
||||
/** @brief Resize path: invalidate an enabled layer's snapshot. */
|
||||
void matchSize() override;
|
||||
/** @brief Retain a ready snapshot if master geometry [m, cells, frame] is unchanged. */
|
||||
void reset() override;
|
||||
|
||||
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);
|
||||
unsigned char laneFilter(unsigned int x, unsigned int y, double yaw_robot);
|
||||
void laneFilter(std::vector<unsigned int> x, std::vector<unsigned int> y, std::vector<double> yaw_robot);
|
||||
void laneFilter(std::vector<std::pair<unsigned int, double>> x, std::vector<std::pair<unsigned int, double>> y, std::vector<double> yaw_robot);
|
||||
bool inSkipErea(double start_x, double start_y, double end_x, double end_y, double skip_distance);
|
||||
void convertToMap(unsigned char *costmap, robot_nav_msgs::OccupancyGrid &dir_map, double occ_th, double free_th);
|
||||
bool getRobotPose(double &x, double &y, double &yaw);
|
||||
protected:
|
||||
/** @brief Load plugin configuration and establish its initial state. */
|
||||
void onInitialize() override;
|
||||
/** @brief Host thread: process static-map and direction-grid callbacks. */
|
||||
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
|
||||
|
||||
std::vector<std::array<uint16_t, 2>> directional_areas_;
|
||||
double pose_x_, pose_y_, pose_yaw_;
|
||||
double distance_skip_ = 1.0;
|
||||
// ros::Publisher lane_mask_pub_;
|
||||
robot_nav_msgs::OccupancyGrid new_map_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
private:
|
||||
DirectionGeometry geometry() const;
|
||||
void publishLocked(DirectionFieldState state, std::shared_ptr<const DirectionField> field = {});
|
||||
mutable std::mutex mutex_;
|
||||
DirectionFieldSnapshot snapshot_;
|
||||
bool seen_map_;
|
||||
bool debug_state_;
|
||||
bool rolling_;
|
||||
double max_deviation_rad_; ///< Maximum angular deviation [rad].
|
||||
std::string map_topic_, direction_topic_;
|
||||
std::chrono::steady_clock::time_point pending_since_, last_pending_log_;
|
||||
};
|
||||
} // namespace robot_costmap_2d
|
||||
#endif // ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
|
||||
@@ -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();
|
||||
@@ -184,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_;
|
||||
|
||||
@@ -56,7 +56,10 @@ enum class LayerType
|
||||
DIRECTIONAL_LAYER,
|
||||
PREFERRED_LAYER,
|
||||
UNPREFERRED_LAYER,
|
||||
VOXEL_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;
|
||||
|
||||
@@ -38,15 +38,24 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_
|
||||
#define ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
#include <robot_costmap_2d/reference_graph.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <robot_costmap_2d/layer.h>
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
class Layer;
|
||||
class ReferenceGraphWorker;
|
||||
enum class LayerType; // layer.h includes this header before it defines the enum.
|
||||
|
||||
/**
|
||||
* @class LayeredCostmap
|
||||
@@ -71,6 +80,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_;
|
||||
@@ -89,6 +106,26 @@ public:
|
||||
|
||||
bool isCurrent();
|
||||
|
||||
/** Consistent snapshot; plugin list must be fixed before concurrent reads. */
|
||||
DirectionFieldSnapshot getDirectionFieldSnapshot() const;
|
||||
|
||||
/** @brief Start computing the coarse graph in the background. Call once, after the plugins are loaded.
|
||||
* The first computation starts by itself, so a map that arrived earlier still counts.
|
||||
* @return False, with an error logged, on a rolling costmap, bad parameters or a second call. */
|
||||
bool enableReferenceGraph(const ReferenceGraphParams& params);
|
||||
|
||||
/** @brief Consistent snapshot, safe to retain on a planner thread. Never takes the master mutex. */
|
||||
ReferenceGraphSnapshot getReferenceGraphSnapshot() const;
|
||||
|
||||
/** @brief Counts map changes per layer type, e.g. PREFERRED_LAYER, so a planner knows when to rebuild what it derives. */
|
||||
uint64_t getStaticMapRevision(LayerType type) const;
|
||||
|
||||
/** @brief Called by the StaticLayer family under the master mutex. Only STATIC_LAYER reruns steps 1 and 2. */
|
||||
void notifyStaticMapChanged(LayerType type);
|
||||
|
||||
/** @brief Called by DirectionalLayer whenever it publishes. Reruns step 2 only. */
|
||||
void notifyDirectionFieldChanged();
|
||||
|
||||
Costmap2D* getCostmap()
|
||||
{
|
||||
return &costmap_;
|
||||
@@ -155,6 +192,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 +222,29 @@ 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;
|
||||
|
||||
static constexpr std::size_t kMaxLayerTypes = 16; ///< Checked against LayerType in layered_costmap.cpp.
|
||||
std::array<std::atomic<std::uint64_t>, kMaxLayerTypes> static_map_revisions_{};
|
||||
std::unique_ptr<ReferenceGraphWorker> reference_graph_worker_; ///< Null when reference_graph_enabled is false: no thread at all.
|
||||
};
|
||||
|
||||
} // 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_;
|
||||
};
|
||||
|
||||
@@ -1,391 +1,3 @@
|
||||
// // /*********************************************************************
|
||||
// // *
|
||||
// // * Software License Agreement (BSD License)
|
||||
// // *
|
||||
// // * Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
// // * All rights reserved.
|
||||
// // *
|
||||
// // * Redistribution and use in source and binary forms, with or without
|
||||
// // * modification, are permitted provided that the following conditions
|
||||
// // * are met:
|
||||
// // *
|
||||
// // * * Redistributions of source code must retain the above copyright
|
||||
// // * notice, this list of conditions and the following disclaimer.
|
||||
// // * * Redistributions in binary form must reproduce the above
|
||||
// // * copyright notice, this list of conditions and the following
|
||||
// // * disclaimer in the documentation and/or other materials provided
|
||||
// // * with the distribution.
|
||||
// // * * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
// // * contributors may be used to endorse or promote products derived
|
||||
// // * from this software without specific prior written permission.
|
||||
// // *
|
||||
// // * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// // * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// // * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
// // * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
// // * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
// // * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
// // * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// // * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
// // * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
// // * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
// // * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
// // * POSSIBILITY OF SUCH DAMAGE.
|
||||
// // *
|
||||
// // * Author: Eitan Marder-Eppstein
|
||||
// // *********************************************************************/
|
||||
// // #ifndef ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_
|
||||
// // #define ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_
|
||||
|
||||
// // #include <vector>
|
||||
// // #include <list>
|
||||
// // #include <string>
|
||||
// // #include <robot/robot.h>
|
||||
// // #include <robot_costmap_2d/observation.h>
|
||||
// // #include <tf3/buffer_core.h>
|
||||
// // #include <robot_sensor_msgs/PointCloud2.h>
|
||||
|
||||
// // // Thread support
|
||||
// // #include <boost/thread.hpp>
|
||||
|
||||
// // namespace robot_costmap_2d
|
||||
// // {
|
||||
// // /**
|
||||
// // * @class ObservationBuffer
|
||||
// // * @brief Takes in point clouds from sensors, transforms them to the desired frame, and stores them
|
||||
// // */
|
||||
// // class ObservationBuffer
|
||||
// // {
|
||||
// // public:
|
||||
// // /**
|
||||
// // * @brief Constructs an observation buffer
|
||||
// // * @param topic_name The topic of the observations, used as an identifier for error and warning messages
|
||||
// // * @param observation_keep_time Defines the persistence of observations in seconds, 0 means only keep the latest
|
||||
// // * @param expected_update_rate How often this buffer is expected to be updated, 0 means there is no limit
|
||||
// // * @param min_obstacle_height The minimum height of a hitpoint to be considered legal
|
||||
// // * @param max_obstacle_height The minimum height of a hitpoint to be considered legal
|
||||
// // * @param obstacle_range The range to which the sensor should be trusted for inserting obstacles
|
||||
// // * @param raytrace_range The range to which the sensor should be trusted for raytracing to clear out space
|
||||
// // * @param tf2_buffer A reference to a tf2 Buffer
|
||||
// // * @param global_frame The frame to transform PointClouds into
|
||||
// // * @param sensor_frame The frame of the origin of the sensor, can be left blank to be read from the messages
|
||||
// // * @param tf_tolerance The amount of time to wait for a transform to be available when setting a new global frame
|
||||
// // */
|
||||
// // ObservationBuffer(std::string topic_name, double observation_keep_time, double expected_update_rate,
|
||||
// // double min_obstacle_height, double max_obstacle_height, double obstacle_range,
|
||||
// // double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
|
||||
// // std::string sensor_frame, double tf_tolerance);
|
||||
|
||||
// // /**
|
||||
// // * @brief Destructor... cleans up
|
||||
// // */
|
||||
// // ~ObservationBuffer();
|
||||
|
||||
// // /**
|
||||
// // * @brief Sets the global frame of an observation buffer. This will
|
||||
// // * transform all the currently cached observations to the new global
|
||||
// // * frame
|
||||
// // * @param new_global_frame The name of the new global frame.
|
||||
// // * @return True if the operation succeeds, false otherwise
|
||||
// // */
|
||||
// // bool setGlobalFrame(const std::string new_global_frame);
|
||||
|
||||
// // /**
|
||||
// // * @brief Transforms a PointCloud to the global frame and buffers it
|
||||
// // * <b>Note: The burden is on the user to make sure the transform is available... ie they should use a MessageNotifier</b>
|
||||
// // * @param cloud The cloud to be buffered
|
||||
// // */
|
||||
// // void bufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
|
||||
|
||||
// // /**
|
||||
// // * @brief Pushes copies of all current observations onto the end of the vector passed in
|
||||
// // * @param observations The vector to be filled
|
||||
// // */
|
||||
// // void getObservations(std::vector<Observation>& observations);
|
||||
|
||||
// // /**
|
||||
// // * @brief Check if the observation buffer is being update at its expected rate
|
||||
// // * @return True if it is being updated at the expected rate, false otherwise
|
||||
// // */
|
||||
// // bool isCurrent() const;
|
||||
|
||||
// // /**
|
||||
// // * @brief Lock the observation buffer
|
||||
// // */
|
||||
// // inline void lock()
|
||||
// // {
|
||||
// // lock_.lock();
|
||||
// // }
|
||||
|
||||
// // /**
|
||||
// // * @brief Lock the observation buffer
|
||||
// // */
|
||||
// // inline void unlock()
|
||||
// // {
|
||||
// // lock_.unlock();
|
||||
// // }
|
||||
|
||||
// // /**
|
||||
// // * @brief Reset last updated timestamp
|
||||
// // */
|
||||
// // void resetLastUpdated();
|
||||
|
||||
// // private:
|
||||
// // /**
|
||||
// // * @brief Removes any stale observations from the buffer list
|
||||
// // */
|
||||
// // void purgeStaleObservations();
|
||||
|
||||
// // // Helper: trích 4×4 transform matrix từ TransformStampedMsg
|
||||
// // // Tránh gọi tf3::doTransform per-point (overhead virtual dispatch + exception check)
|
||||
// // struct Transform4x4 {
|
||||
// // double m[4][4];
|
||||
// // };
|
||||
|
||||
// // static inline Transform4x4 extractMatrix(const tf3::TransformStampedMsg& tfm)
|
||||
// // {
|
||||
// // // Quaternion → rotation matrix + translation
|
||||
// // const auto& t = tfm.transform.translation;
|
||||
// // const auto& q = tfm.transform.rotation;
|
||||
|
||||
// // double qx = q.x, qy = q.y, qz = q.z, qw = q.w;
|
||||
// // Transform4x4 M;
|
||||
// // M.m[0][0] = 1 - 2*(qy*qy + qz*qz); M.m[0][1] = 2*(qx*qy - qz*qw); M.m[0][2] = 2*(qx*qz + qy*qw); M.m[0][3] = t.x;
|
||||
// // M.m[1][0] = 2*(qx*qy + qz*qw); M.m[1][1] = 1 - 2*(qx*qx + qz*qz); M.m[1][2] = 2*(qy*qz - qx*qw); M.m[1][3] = t.y;
|
||||
// // M.m[2][0] = 2*(qx*qz - qy*qw); M.m[2][1] = 2*(qy*qz + qx*qw); M.m[2][2] = 1 - 2*(qx*qx + qy*qy); M.m[2][3] = t.z;
|
||||
// // M.m[3][0] = 0; M.m[3][1] = 0; M.m[3][2] = 0; M.m[3][3] = 1;
|
||||
// // return M;
|
||||
// // }
|
||||
|
||||
// // double voxel_size_;
|
||||
// // tf3::BufferCore& tf3_buffer_;
|
||||
// // const robot::Duration observation_keep_time_;
|
||||
// // const robot::Duration expected_update_rate_;
|
||||
// // robot::Time last_updated_;
|
||||
// // std::string global_frame_;
|
||||
// // std::string sensor_frame_;
|
||||
// // std::list<Observation> observation_list_;
|
||||
// // std::string topic_name_;
|
||||
// // double min_obstacle_height_, max_obstacle_height_;
|
||||
// // boost::recursive_mutex lock_; ///< @brief A lock for accessing data in callbacks safely
|
||||
// // double obstacle_range_, raytrace_range_;
|
||||
// // double tf_tolerance_;
|
||||
// // };
|
||||
// // } // namespace robot_costmap_2d
|
||||
// // #endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_
|
||||
|
||||
// /*********************************************************************
|
||||
// *
|
||||
// * Software License Agreement (BSD License)
|
||||
// *
|
||||
// * Copyright (c) 2008, 2013, Willow Garage, Inc.
|
||||
// * All rights reserved.
|
||||
// *
|
||||
// * Redistribution and use in source and binary forms, with or without
|
||||
// * modification, are permitted provided that the following conditions
|
||||
// * are met:
|
||||
// *
|
||||
// * * Redistributions of source code must retain the above copyright
|
||||
// * notice, this list of conditions and the following disclaimer.
|
||||
// * * Redistributions in binary form must reproduce the above
|
||||
// * copyright notice, this list of conditions and the following
|
||||
// * disclaimer in the documentation and/or other materials provided
|
||||
// * with the distribution.
|
||||
// * * Neither the name of Willow Garage, Inc. nor the names of its
|
||||
// * contributors may be used to endorse or promote products derived
|
||||
// * from this software without specific prior written permission.
|
||||
// *
|
||||
// * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
||||
// * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
||||
// * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
// * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
// * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
// * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
// * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
// * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
// * POSSIBILITY OF SUCH DAMAGE.
|
||||
// *
|
||||
// * Author: Eitan Marder-Eppstein
|
||||
// *********************************************************************/
|
||||
// #ifndef ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_
|
||||
// #define ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_
|
||||
|
||||
// #include <vector>
|
||||
// #include <list>
|
||||
// #include <string>
|
||||
// #include <unordered_map>
|
||||
// #include <cmath>
|
||||
// #include <cstring>
|
||||
|
||||
// #include <robot/robot.h>
|
||||
// #include <robot_costmap_2d/observation.h>
|
||||
// #include <tf3/buffer_core.h>
|
||||
// #include <robot_sensor_msgs/PointCloud2.h>
|
||||
|
||||
// // Thread support
|
||||
// #include <boost/thread.hpp>
|
||||
|
||||
// namespace robot_costmap_2d
|
||||
// {
|
||||
// /**
|
||||
// * @class ObservationBuffer
|
||||
// * @brief Takes in point clouds from sensors, transforms them to the desired frame, and stores them.
|
||||
// *
|
||||
// * Optimizations vs original:
|
||||
// * - bufferCloud: single-pass transform+filter+voxel-downsample.
|
||||
// * Reduces 6.5 M points to at most (map_w × map_h) representative points,
|
||||
// * which cuts CPU in updateBounds/raytraceFreespace by ~100–200×.
|
||||
// * - extractMatrix: inline quaternion→rotation, avoids per-point virtual dispatch.
|
||||
// * - voxel_size_ (default = costmap resolution, 0.05 m): configurable via
|
||||
// * setVoxelSize() so ObstacleLayer can pass the real resolution.
|
||||
// */
|
||||
// class ObservationBuffer
|
||||
// {
|
||||
// public:
|
||||
// /**
|
||||
// * @brief Constructs an observation buffer
|
||||
// * @param topic_name The topic of the observations, used as an identifier for error and warning messages
|
||||
// * @param observation_keep_time Defines the persistence of observations in seconds, 0 means only keep the latest
|
||||
// * @param expected_update_rate How often this buffer is expected to be updated, 0 means there is no limit
|
||||
// * @param min_obstacle_height The minimum height of a hitpoint to be considered legal
|
||||
// * @param max_obstacle_height The maximum height of a hitpoint to be considered legal
|
||||
// * @param obstacle_range The range to which the sensor should be trusted for inserting obstacles
|
||||
// * @param raytrace_range The range to which the sensor should be trusted for raytracing to clear out space
|
||||
// * @param tf2_buffer A reference to a tf2 Buffer
|
||||
// * @param global_frame The frame to transform PointClouds into
|
||||
// * @param sensor_frame The frame of the origin of the sensor, can be left blank to be read from the messages
|
||||
// * @param tf_tolerance The amount of time to wait for a transform to be available when setting a new global frame
|
||||
// */
|
||||
// ObservationBuffer(std::string topic_name, double observation_keep_time, double expected_update_rate,
|
||||
// double min_obstacle_height, double max_obstacle_height, double obstacle_range,
|
||||
// double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
|
||||
// std::string sensor_frame, double tf_tolerance);
|
||||
|
||||
// /**
|
||||
// * @brief Destructor... cleans up
|
||||
// */
|
||||
// ~ObservationBuffer();
|
||||
|
||||
// /**
|
||||
// * @brief Sets the global frame of an observation buffer. This will
|
||||
// * transform all the currently cached observations to the new global frame
|
||||
// * @param new_global_frame The name of the new global frame.
|
||||
// * @return True if the operation succeeds, false otherwise
|
||||
// */
|
||||
// bool setGlobalFrame(const std::string new_global_frame);
|
||||
|
||||
// /**
|
||||
// * @brief Set the voxel size used for downsampling in bufferCloud().
|
||||
// * Should match the costmap resolution (default 0.05 m).
|
||||
// */
|
||||
// inline void setVoxelSize(double voxel_size)
|
||||
// {
|
||||
// voxel_size_ = voxel_size;
|
||||
// inv_voxel_size_ = (voxel_size > 1e-9) ? 1.0 / voxel_size : 20.0;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * @brief Transforms a PointCloud to the global frame, downsamples it via
|
||||
// * voxel grid (one representative point per costmap cell), applies
|
||||
// * height filtering, and buffers the result.
|
||||
// */
|
||||
// void bufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
|
||||
|
||||
// /**
|
||||
// * @brief Pushes copies of all current observations onto the end of the vector passed in
|
||||
// * @param observations The vector to be filled
|
||||
// */
|
||||
// void getObservations(std::vector<Observation>& observations);
|
||||
|
||||
// /**
|
||||
// * @brief Check if the observation buffer is being updated at its expected rate
|
||||
// * @return True if it is being updated at the expected rate, false otherwise
|
||||
// */
|
||||
// bool isCurrent() const;
|
||||
|
||||
// /**
|
||||
// * @brief Lock the observation buffer
|
||||
// */
|
||||
// inline void lock() { lock_.lock(); }
|
||||
|
||||
// /**
|
||||
// * @brief Unlock the observation buffer
|
||||
// */
|
||||
// inline void unlock() { lock_.unlock(); }
|
||||
|
||||
// /**
|
||||
// * @brief Reset last updated timestamp
|
||||
// */
|
||||
// void resetLastUpdated();
|
||||
|
||||
// private:
|
||||
// /**
|
||||
// * @brief Removes any stale observations from the buffer list
|
||||
// */
|
||||
// void purgeStaleObservations();
|
||||
|
||||
// // ── Transform helper ────────────────────────────────────────────────────
|
||||
// // Encode a TF transform as a plain 4×4 double matrix so the hot loop in
|
||||
// // bufferCloud can do a simple FMA multiply without any virtual dispatch,
|
||||
// // exception handling, or iterator overhead.
|
||||
// struct Transform4x4
|
||||
// {
|
||||
// double m[4][4];
|
||||
// };
|
||||
|
||||
// static inline Transform4x4 extractMatrix(const tf3::TransformStampedMsg& tfm)
|
||||
// {
|
||||
// const auto& t = tfm.transform.translation;
|
||||
// const auto& q = tfm.transform.rotation;
|
||||
|
||||
// const double qx = q.x, qy = q.y, qz = q.z, qw = q.w;
|
||||
// Transform4x4 M;
|
||||
// // Row 0
|
||||
// M.m[0][0] = 1.0 - 2.0*(qy*qy + qz*qz);
|
||||
// M.m[0][1] = 2.0*(qx*qy - qz*qw);
|
||||
// M.m[0][2] = 2.0*(qx*qz + qy*qw);
|
||||
// M.m[0][3] = t.x;
|
||||
// // Row 1
|
||||
// M.m[1][0] = 2.0*(qx*qy + qz*qw);
|
||||
// M.m[1][1] = 1.0 - 2.0*(qx*qx + qz*qz);
|
||||
// M.m[1][2] = 2.0*(qy*qz - qx*qw);
|
||||
// M.m[1][3] = t.y;
|
||||
// // Row 2
|
||||
// M.m[2][0] = 2.0*(qx*qz - qy*qw);
|
||||
// M.m[2][1] = 2.0*(qy*qz + qx*qw);
|
||||
// M.m[2][2] = 1.0 - 2.0*(qx*qx + qy*qy);
|
||||
// M.m[2][3] = t.z;
|
||||
// // Row 3 (homogeneous)
|
||||
// M.m[3][0] = 0.0; M.m[3][1] = 0.0; M.m[3][2] = 0.0; M.m[3][3] = 1.0;
|
||||
// return M;
|
||||
// }
|
||||
|
||||
// // ── Data members ────────────────────────────────────────────────────────
|
||||
// tf3::BufferCore& tf3_buffer_;
|
||||
// const robot::Duration observation_keep_time_;
|
||||
// const robot::Duration expected_update_rate_;
|
||||
// robot::Time last_updated_;
|
||||
// std::string global_frame_;
|
||||
// std::string sensor_frame_;
|
||||
// std::list<Observation> observation_list_;
|
||||
// std::string topic_name_;
|
||||
// double min_obstacle_height_;
|
||||
// double max_obstacle_height_;
|
||||
// boost::recursive_mutex lock_;
|
||||
// double obstacle_range_;
|
||||
// double raytrace_range_;
|
||||
// double tf_tolerance_;
|
||||
|
||||
// // Voxel-grid downsampling parameters (set via setVoxelSize)
|
||||
// double voxel_size_ = 0.05; // metres – match costmap resolution
|
||||
// double inv_voxel_size_ = 20.0; // 1/voxel_size_, cached
|
||||
// };
|
||||
|
||||
// } // namespace robot_costmap_2d
|
||||
// #endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
@@ -464,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
|
||||
*/
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
|
||||
#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>
|
||||
@@ -62,8 +64,12 @@ struct CallBackInfo
|
||||
std::string data_type;
|
||||
std::string topic;
|
||||
bool inf_is_valid;
|
||||
bool zero_is_valid = false;
|
||||
};
|
||||
|
||||
/** Replace enabled no-return ranges with range_max minus a small epsilon. */
|
||||
void replaceNoReturnRanges(robot_sensor_msgs::LaserScan& scan, bool inf_is_valid, bool zero_is_valid);
|
||||
|
||||
class ObstacleLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
@@ -105,12 +111,13 @@ protected:
|
||||
const boost::shared_ptr<ObservationBuffer>& buffer);
|
||||
|
||||
/**
|
||||
* @brief A callback to handle buffering LaserScan messages which need filtering to turn Inf values into range_max.
|
||||
* @brief Buffer LaserScan messages after replacing enabled no-return ranges.
|
||||
* @param message The message returned from a message notifier
|
||||
* @param buffer A pointer to the observation buffer to update
|
||||
*/
|
||||
void laserScanValidInfCallback(const robot_sensor_msgs::LaserScan& message,
|
||||
const boost::shared_ptr<ObservationBuffer>& buffer);
|
||||
const boost::shared_ptr<ObservationBuffer>& buffer,
|
||||
bool inf_is_valid, bool zero_is_valid);
|
||||
|
||||
/**
|
||||
* @brief A callback to handle buffering PointCloud messages
|
||||
|
||||
157
include/robot_costmap_2d/reference_graph.h
Normal file
157
include/robot_costmap_2d/reference_graph.h
Normal file
@@ -0,0 +1,157 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_REFERENCE_GRAPH_H_
|
||||
#define ROBOT_COSTMAP_2D_REFERENCE_GRAPH_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_geometry_msgs/Point.h>
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief Inputs of the coarse graph. All lengths are absolute, none is derived from the footprint. */
|
||||
struct ReferenceGraphParams
|
||||
{
|
||||
double min_clearance_m = 0.335; ///< [m] Ridge cells closer to a lethal cell than this are dropped.
|
||||
double ridge_min_separation_m = 0.7; ///< [m] Two nearest obstacles closer than this count as one.
|
||||
double spur_min_length_m = 1.0; ///< [m] Dead-end branches shorter than this are pruned.
|
||||
double lane_offset_step_m = 0.5; ///< [m] Spacing of the parallel lanes inside one zone.
|
||||
bool debug_log = true; ///< One [debug] line per finished computation. Errors always log.
|
||||
};
|
||||
|
||||
/** @brief Return an empty string for valid parameters, otherwise a description of the first bad value. */
|
||||
std::string validateReferenceGraphParams(const ReferenceGraphParams& params);
|
||||
|
||||
/** @brief Point [m] in ReferenceGraph::geometry.frame_id. */
|
||||
struct ReferencePoint
|
||||
{
|
||||
double x, y;
|
||||
};
|
||||
|
||||
/** @brief Undirected ridge segment, split at zone boundaries. Direction rules belong to the planner. */
|
||||
struct VoronoiEdge
|
||||
{
|
||||
uint32_t from, to; ///< Indices into ReferenceGraph::nodes.
|
||||
std::vector<ReferencePoint> points; ///< [m] Every fifth skeleton cell plus the exact end, from -> to.
|
||||
double length_m; ///< [m] Length of the polyline through points.
|
||||
double min_clearance_m; ///< [m] Smallest clearance at points. Infinity when no clearance grid was given.
|
||||
};
|
||||
|
||||
/** @brief Straight one-way lane inside one zone, in travel direction. */
|
||||
struct ReferenceLane
|
||||
{
|
||||
uint32_t zone_id; ///< Connected region of equal direction code. Unique inside one graph.
|
||||
uint8_t direction_index; ///< 0..7 CCW from +X, as in direction_field.h.
|
||||
ReferencePoint entry, exit; ///< [m]
|
||||
double length_m; ///< [m]
|
||||
double offset_from_centre_m; ///< [m] Absolute distance from the zone's main lane. The planner turns it into a penalty.
|
||||
};
|
||||
|
||||
/** @brief Plain grid input. A window crop passes the full-map clearance so obstacles just outside still count. */
|
||||
struct ReferenceGridView
|
||||
{
|
||||
const uint8_t* cost = nullptr; ///< width*height, row-major, cost_values.h.
|
||||
const uint16_t* clearance_mm = nullptr; ///< [mm] May be null: computed from `cost`.
|
||||
const uint8_t* direction_codes = nullptr; ///< May be null: no zones. 0 unconstrained, 1..8 as in direction_field.h.
|
||||
DirectionGeometry geometry{};
|
||||
};
|
||||
|
||||
/** @brief Output of step 1. Kept by the worker so a zone or footprint change reruns step 2 only. */
|
||||
struct VoronoiSkeleton
|
||||
{
|
||||
DirectionGeometry geometry{};
|
||||
std::vector<uint8_t> mask; ///< width*height, row-major, 1 on a skeleton cell. Empty when cancelled.
|
||||
std::vector<uint16_t> clearance_mm; ///< [mm] width*height. Distance to the nearest lethal cell, capped at 65535.
|
||||
};
|
||||
|
||||
/** @brief Coarse graph of one map and one direction grid. */
|
||||
struct ReferenceGraph
|
||||
{
|
||||
DirectionGeometry geometry{}; ///< Same grid layout as the master costmap.
|
||||
ReferenceGraphParams params; ///< Parameters this graph was built with.
|
||||
uint64_t direction_generation = 0; ///< DirectionFieldSnapshot::generation the lanes came from. Set by the worker.
|
||||
std::vector<ReferencePoint> nodes; ///< [m] Junctions, dead ends and zone-boundary points.
|
||||
std::vector<VoronoiEdge> edges; ///< Green lines in the review image.
|
||||
std::vector<ReferenceLane> lanes; ///< Red lines in the review image, before the lead extension.
|
||||
std::vector<uint8_t> static_cost; ///< width*height, row-major, cost_values.h. Empty when cancelled.
|
||||
std::vector<uint16_t> clearance_mm; ///< [mm] width*height.
|
||||
};
|
||||
|
||||
enum class ReferenceGraphState
|
||||
{
|
||||
kDisabled, ///< reference_graph_enabled is false.
|
||||
kPending, ///< A map, zone or footprint change is being processed.
|
||||
kReady ///< graph matches the current map and direction grid.
|
||||
};
|
||||
|
||||
/** @brief Consistent view of the graph, safe to retain on a planner thread. */
|
||||
struct ReferenceGraphSnapshot
|
||||
{
|
||||
ReferenceGraphState state = ReferenceGraphState::kDisabled;
|
||||
std::shared_ptr<const ReferenceGraph> graph; ///< Non-null only in kReady.
|
||||
uint64_t generation = 0; ///< Changes whenever state or graph changes.
|
||||
};
|
||||
|
||||
/** @brief Step 1: distance transform, ridge cells, thinning and spur pruning.
|
||||
*
|
||||
* Only LETHAL_OBSTACLE cells are obstacles. Ridge cells must have cost below
|
||||
* INSCRIBED_INFLATED_OBSTACLE, so unknown and inflated cells never join the skeleton.
|
||||
* @param grid Input grid. `direction_codes` is ignored here.
|
||||
* @param params Graph parameters.
|
||||
* @param cancel When non-null and set, returns early with an empty mask.
|
||||
* @throws std::invalid_argument on bad parameters, geometry or a null cost pointer.
|
||||
*/
|
||||
VoronoiSkeleton computeVoronoiSkeleton(const ReferenceGridView& grid, const ReferenceGraphParams& params,
|
||||
const std::atomic<bool>* cancel = nullptr);
|
||||
|
||||
/** @brief Centre line of a cell mask of any width, used by the planner for the `preferred` region in step 3.
|
||||
* @param mask width*height, row-major, nonzero inside the region.
|
||||
* @param geometry Grid layout of the mask.
|
||||
* @param params Only spur_min_length_m is used: the region's own boundary replaces the obstacle thresholds.
|
||||
* @return width*height mask of the centre line.
|
||||
* @throws std::invalid_argument on bad parameters or a size mismatch.
|
||||
*/
|
||||
std::vector<uint8_t> computeRegionCentreLine(const std::vector<uint8_t>& mask, const DirectionGeometry& geometry,
|
||||
const ReferenceGraphParams& params);
|
||||
|
||||
/** @brief Nodes and edges of a skeleton, split where the direction code changes. Part of step 2.
|
||||
*
|
||||
* A closed ring without a junction yields no node and no edge, and neither does a branch that
|
||||
* returns to the node it left. The graph search could not enter them through a node anyway.
|
||||
* @param skeleton_mask width*height, row-major, nonzero on a skeleton cell.
|
||||
* @param direction_codes May be null: no zones.
|
||||
* @param geometry Grid layout of the mask.
|
||||
* @param clearance_mm May be null: VoronoiEdge::min_clearance_m is then infinity.
|
||||
* @param nodes Output, replaced. Must not be null.
|
||||
* @param edges Output, replaced. Must not be null.
|
||||
* @param cancel When non-null and set, returns early with both outputs empty.
|
||||
* @throws std::invalid_argument on a size mismatch or a null output.
|
||||
*/
|
||||
void extractVoronoiEdges(const std::vector<uint8_t>& skeleton_mask, const uint8_t* direction_codes,
|
||||
const DirectionGeometry& geometry, const std::vector<uint16_t>* clearance_mm,
|
||||
std::vector<ReferencePoint>* nodes, std::vector<VoronoiEdge>* edges,
|
||||
const std::atomic<bool>* cancel = nullptr);
|
||||
|
||||
/** @brief Step 2: Voronoi edges split at zone boundaries, plus straight lanes from the direction grid.
|
||||
*
|
||||
* Lanes use the rectangle that bounds the footprint, centred on the robot origin, so an off-centre
|
||||
* or non-rectangular footprint is checked conservatively.
|
||||
* @param grid Input grid, the same one the skeleton came from.
|
||||
* @param skeleton Output of computeVoronoiSkeleton.
|
||||
* @param footprint Robot footprint [m]. Needs at least 3 points when `grid.direction_codes` is non-null.
|
||||
* @param params Graph parameters.
|
||||
* @param cancel When non-null and set, returns early with an empty graph.
|
||||
* @throws std::invalid_argument on bad parameters, a skeleton of another size or a bad footprint.
|
||||
*/
|
||||
ReferenceGraph buildReferenceGraph(const ReferenceGridView& grid, const VoronoiSkeleton& skeleton,
|
||||
const std::vector<robot_geometry_msgs::Point>& footprint,
|
||||
const ReferenceGraphParams& params, const std::atomic<bool>* cancel = nullptr);
|
||||
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
#endif // ROBOT_COSTMAP_2D_REFERENCE_GRAPH_H_
|
||||
133
include/robot_costmap_2d/reference_graph_worker.h
Normal file
133
include/robot_costmap_2d/reference_graph_worker.h
Normal file
@@ -0,0 +1,133 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_REFERENCE_GRAPH_WORKER_H_
|
||||
#define ROBOT_COSTMAP_2D_REFERENCE_GRAPH_WORKER_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_geometry_msgs/Point.h>
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
#include <robot_costmap_2d/reference_graph.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief Everything the worker reads from the costmap, taken in one short lock. */
|
||||
struct ReferenceGraphInput
|
||||
{
|
||||
DirectionGeometry geometry{}; ///< Master grid layout.
|
||||
std::vector<std::vector<uint8_t>> static_layers; ///< One width*height copy per enabled static layer.
|
||||
std::vector<robot_geometry_msgs::Point> footprint; ///< [m] Robot footprint.
|
||||
};
|
||||
|
||||
enum class ReferenceCaptureStatus
|
||||
{
|
||||
kReady, ///< The input is complete.
|
||||
kWait, ///< A static layer has not written its map yet. Try again later.
|
||||
kNoStaticLayer ///< Nothing to build a graph from: a configuration error.
|
||||
};
|
||||
|
||||
/** @brief Merge static layer copies into the grid the coarse graph is built from.
|
||||
*
|
||||
* A cell is lethal when any layer says so, because virtual walls and forbidden zones are static layers too. It is
|
||||
* unknown only when every layer says so. Everything else is free: soft values are read from the master at query time.
|
||||
* @throws std::invalid_argument when the layers differ in size.
|
||||
*/
|
||||
std::vector<uint8_t> mergeStaticLayers(const std::vector<std::vector<uint8_t>>& layers);
|
||||
|
||||
/** @brief Counters of finished work. */
|
||||
struct ReferenceGraphWorkerStats
|
||||
{
|
||||
uint64_t step1_runs = 0; ///< Finished runs of step 1.
|
||||
uint64_t step2_runs = 0; ///< Finished runs of step 2.
|
||||
uint64_t published = 0; ///< Graphs that reached kReady.
|
||||
uint64_t errors = 0; ///< Computations that threw.
|
||||
double capture_ms_max = 0.0; ///< [ms] Longest wait inside the capture callback, which holds the master mutex.
|
||||
double step1_ms_last = 0.0; ///< [ms] Duration of the last finished step 1.
|
||||
double step2_ms_last = 0.0; ///< [ms] Duration of the last finished step 2.
|
||||
};
|
||||
|
||||
/** @brief Background thread that keeps the coarse graph in step with the map, the zones and the footprint.
|
||||
*
|
||||
* Lock order is master mutex, then the mutex of DirectionalLayer, then the mutex of this class. The notify functions
|
||||
* may therefore be called while holding the first two. The thread never holds its own mutex while calling a callback.
|
||||
*/
|
||||
class ReferenceGraphWorker
|
||||
{
|
||||
public:
|
||||
struct Source
|
||||
{
|
||||
/** Called on the worker thread. Takes the master mutex itself and holds it only for the copy. */
|
||||
std::function<ReferenceCaptureStatus(bool with_grid, ReferenceGraphInput* input)> capture;
|
||||
/** Called on the worker thread, without the master mutex. */
|
||||
std::function<DirectionFieldSnapshot()> direction;
|
||||
};
|
||||
|
||||
/** @brief Starts the thread. The first computation starts by itself, so a map that arrived earlier counts.
|
||||
* @throws std::invalid_argument on bad parameters or a missing callback. */
|
||||
ReferenceGraphWorker(Source source, const ReferenceGraphParams& params);
|
||||
|
||||
/** @brief Cancels any computation and joins the thread. */
|
||||
~ReferenceGraphWorker();
|
||||
|
||||
ReferenceGraphWorker(const ReferenceGraphWorker&) = delete;
|
||||
ReferenceGraphWorker& operator=(const ReferenceGraphWorker&) = delete;
|
||||
|
||||
/** @brief The static map changed: reruns steps 1 and 2. */
|
||||
void notifyStaticChanged();
|
||||
/** @brief The direction grid changed: reruns step 2 only. */
|
||||
void notifyDirectionChanged();
|
||||
/** @brief The footprint changed: reruns step 2 only. */
|
||||
void notifyFootprintChanged();
|
||||
|
||||
/** @brief Consistent snapshot, safe to retain. Takes only this class's mutex, so a planner never waits for the costmap. */
|
||||
ReferenceGraphSnapshot snapshot() const;
|
||||
|
||||
ReferenceGraphWorkerStats stats() const;
|
||||
|
||||
private:
|
||||
enum class Outcome
|
||||
{
|
||||
kDone, ///< graph holds a new result.
|
||||
kWait, ///< An input is not ready yet.
|
||||
kCancelled, ///< An input changed during the computation.
|
||||
kFailed ///< It threw. Stay pending until the next change: the same input would throw again.
|
||||
};
|
||||
|
||||
void run();
|
||||
Outcome compute(uint64_t static_revision, ReferenceGraph* graph);
|
||||
void markPendingLocked();
|
||||
|
||||
const Source source_;
|
||||
const ReferenceGraphParams params_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable wake_;
|
||||
bool stop_ = false;
|
||||
uint64_t static_revision_ = 1; // Starts ahead of handled_, which starts the first computation.
|
||||
uint64_t step2_revision_ = 1;
|
||||
uint64_t handled_static_ = 0;
|
||||
uint64_t handled_step2_ = 0;
|
||||
ReferenceGraphSnapshot snapshot_;
|
||||
ReferenceGraphWorkerStats stats_;
|
||||
std::atomic<bool> cancel_{ false };
|
||||
|
||||
// Used only by the worker thread.
|
||||
std::vector<uint8_t> static_cost_;
|
||||
DirectionGeometry geometry_{};
|
||||
VoronoiSkeleton skeleton_;
|
||||
bool skeleton_valid_ = false;
|
||||
uint64_t skeleton_revision_ = 0;
|
||||
bool no_static_logged_ = false;
|
||||
|
||||
std::thread thread_; // Last member: it starts after everything above exists.
|
||||
};
|
||||
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
#endif // ROBOT_COSTMAP_2D_REFERENCE_GRAPH_WORKER_H_
|
||||
@@ -43,6 +43,7 @@
|
||||
|
||||
#include <robot_nav_msgs/OccupancyGrid.h>
|
||||
#include <robot_map_msgs/OccupancyGridUpdate.h>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
@@ -76,14 +77,16 @@ protected:
|
||||
virtual unsigned char interpretValue(unsigned char value);
|
||||
virtual void incomingMap(const robot_nav_msgs::OccupancyGrid& new_map);
|
||||
virtual void incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update);
|
||||
/// Called under the master costmap mutex after a nonempty region has been written.
|
||||
void markMapWritten(int min_i, int min_j, int max_i, int max_j);
|
||||
unsigned char* threshold_;
|
||||
std::string base_frame_id_;
|
||||
std::string global_frame_; ///< @brief The global frame for the costmap
|
||||
std::string map_frame_; /// @brief frame that map is located in
|
||||
std::string map_topic_; // Hiep thêm vào mục đich phân biết zones
|
||||
bool subscribe_to_updates_;
|
||||
bool map_received_;
|
||||
bool has_updated_data_;
|
||||
bool map_received_ = false;
|
||||
bool has_updated_data_ = false;
|
||||
unsigned int x_, y_, width_, height_;
|
||||
bool track_unknown_space_;
|
||||
bool use_maximum_;
|
||||
@@ -91,6 +94,7 @@ protected:
|
||||
bool trinary_costmap_;
|
||||
bool map_shutdown_ = false;
|
||||
bool map_update_shutdown_ = false;
|
||||
std::chrono::steady_clock::time_point last_invalid_update_log_;
|
||||
unsigned char lethal_threshold_, unknown_cost_value_;
|
||||
|
||||
private:
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -91,22 +94,14 @@ private:
|
||||
void clearNonLethal(double wx, double wy, double w_size_x, double w_size_y, bool clear_no_info);
|
||||
virtual void raytraceFreespace(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y);
|
||||
bool raytraceDepthFrustum(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y);
|
||||
bool getCloudPoint(const robot_sensor_msgs::PointCloud2& cloud, unsigned int u, unsigned int v,
|
||||
double& wx, double& wy, double& wz) const;
|
||||
bool clipRaytraceEndpoint(double ox, double oy, double oz, double& wx, double& wy, double& wz);
|
||||
bool clearVoxelRay(double ox, double oy, double oz, double wx, double wy, double wz,
|
||||
double raytrace_range, 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_;
|
||||
bool frustum_clearing_enabled_;
|
||||
unsigned int frustum_clearing_pixel_step_;
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
<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>
|
||||
|
||||
@@ -22,15 +22,7 @@ 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)
|
||||
{
|
||||
if (!map_received_)
|
||||
return;
|
||||
|
||||
// if not rolling, the layered costmap (master_grid) has same coordinates as this layer
|
||||
if (!use_maximum_)
|
||||
StaticLayer::CostmapLayer::updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
|
||||
else
|
||||
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
|
||||
|
||||
StaticLayer::updateCosts(master_grid, min_i, min_j, max_i, max_j);
|
||||
}
|
||||
|
||||
// Export factory function
|
||||
@@ -42,4 +34,4 @@ static boost::shared_ptr<Layer> create_critical_plugin() {
|
||||
BOOST_DLL_ALIAS(create_critical_plugin, CriticalLayer)
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
1172
plugins/depth_camera_obstacle_layer.cpp
Normal file
1172
plugins/depth_camera_obstacle_layer.cpp
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,428 +1,231 @@
|
||||
#include <robot_costmap_2d/directional_layer.h>
|
||||
#include <data_convert/data_convert.h>
|
||||
#include <tf3/convert.h>
|
||||
#include <tf3/utils.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
|
||||
|
||||
using robot_costmap_2d::CRITICAL_SPACE;
|
||||
using robot_costmap_2d::LETHAL_OBSTACLE;
|
||||
using robot_costmap_2d::NO_INFORMATION;
|
||||
#include <robot/console.h>
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot_costmap_2d/utils.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
DirectionalLayer::DirectionalLayer()
|
||||
{}
|
||||
|
||||
DirectionalLayer::~DirectionalLayer() {}
|
||||
namespace
|
||||
{
|
||||
constexpr auto kPendingErrorDelay = std::chrono::seconds(5);
|
||||
constexpr auto kPendingErrorPeriod = std::chrono::seconds(5);
|
||||
|
||||
bool DirectionalLayer::laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan)
|
||||
bool topicMatches(const std::string& topic, const std::string& configured)
|
||||
{
|
||||
return topic == configured || topic == "/" + configured;
|
||||
}
|
||||
|
||||
const char* stateName(DirectionFieldState state)
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
if (directional_areas_.empty())
|
||||
throw "Has no map data";
|
||||
robot_nav_msgs::Path path;
|
||||
path.header.stamp = robot::Time::now();
|
||||
path.header.frame_id = map_frame_;
|
||||
path.poses = plan;
|
||||
return this->laneFilter(directional_areas_, path);
|
||||
case DirectionFieldState::kDisabled:
|
||||
return "DISABLED";
|
||||
case DirectionFieldState::kPending:
|
||||
return "PENDING";
|
||||
case DirectionFieldState::kReady:
|
||||
return "READY";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DirectionalLayer::DirectionalLayer()
|
||||
: Layer(), mutex_(), snapshot_(), seen_map_(false), debug_state_(true), rolling_(false), max_deviation_rad_(M_PI / 2.0),
|
||||
map_topic_("map"), direction_topic_("direction_map"), pending_since_(), last_pending_log_()
|
||||
{
|
||||
}
|
||||
|
||||
void DirectionalLayer::onInitialize()
|
||||
{
|
||||
robot::NodeHandle nh("~");
|
||||
robot::NodeHandle priv_nh(nh, name_);
|
||||
const std::string filename = "directional_layer_params.yaml";
|
||||
double max_deviation_deg = 90.0;
|
||||
try
|
||||
{
|
||||
const char* env = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
const std::string folder = env && std::filesystem::exists(env) ? env : "";
|
||||
const YAML::Node layer = YAML::LoadFile(getSourceFile(folder, filename))["directional_layer"];
|
||||
enabled_ = loadParam(layer, "enabled", false);
|
||||
map_topic_ = loadParam(layer, "map_topic", std::string("map"));
|
||||
direction_topic_ = loadParam(layer, "direction_topic", std::string("direction_map"));
|
||||
max_deviation_deg = loadParam(layer, "max_deviation_deg", 90.0);
|
||||
debug_state_ = loadParam(layer, "debug_state", true);
|
||||
if (priv_nh.hasParam("enabled"))
|
||||
priv_nh.getParam("enabled", enabled_, enabled_);
|
||||
if (priv_nh.hasParam("map_topic"))
|
||||
priv_nh.getParam("map_topic", map_topic_);
|
||||
if (priv_nh.hasParam("direction_topic"))
|
||||
priv_nh.getParam("direction_topic", direction_topic_);
|
||||
if (priv_nh.hasParam("max_deviation_deg"))
|
||||
priv_nh.getParam("max_deviation_deg", max_deviation_deg);
|
||||
if (priv_nh.hasParam("debug_state"))
|
||||
priv_nh.getParam("debug_state", debug_state_);
|
||||
}
|
||||
catch (const YAML::BadFile&)
|
||||
{
|
||||
throw std::runtime_error("DirectionalLayer " + name_ + ": cannot open the default file " + filename);
|
||||
}
|
||||
if (!std::isfinite(max_deviation_deg) || max_deviation_deg < 0.0 || max_deviation_deg >= 180.0)
|
||||
throw std::runtime_error("DirectionalLayer " + name_ + ": max_deviation_deg must be finite and in (0, 180)");
|
||||
if (max_deviation_deg < 22.5)
|
||||
robot::log_warning("DirectionalLayer %s: max_deviation_deg < 22.5 may leave SBPL without a path", name_.c_str());
|
||||
max_deviation_rad_ = (max_deviation_deg / 180.0) * M_PI;
|
||||
// Preserve the open interval even when conversion rounds at an extreme value.
|
||||
if (max_deviation_rad_ <= 0.0)
|
||||
max_deviation_rad_ = std::nextafter(0.0, M_PI);
|
||||
else if (max_deviation_rad_ >= M_PI)
|
||||
max_deviation_rad_ = std::nextafter(M_PI, 0.0);
|
||||
rolling_ = layered_costmap_->isRolling();
|
||||
if (enabled_ && rolling_)
|
||||
robot::log_error("DirectionalLayer %s: rolling costmap is unsupported", name_.c_str());
|
||||
if (enabled_ && (map_topic_.empty() || direction_topic_.empty() || topicMatches(map_topic_, direction_topic_) ||
|
||||
topicMatches(direction_topic_, map_topic_)))
|
||||
throw std::runtime_error("DirectionalLayer " + name_ + ": topics must be nonempty and distinct");
|
||||
robot::log_info("DirectionalLayer %s: enabled=%d map_topic=%s direction_topic=%s max_deviation_deg=%g debug_state=%d",
|
||||
name_.c_str(), enabled_, map_topic_.c_str(), direction_topic_.c_str(), max_deviation_deg, debug_state_);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
publishLocked(enabled_ ? DirectionFieldState::kPending : DirectionFieldState::kDisabled);
|
||||
}
|
||||
|
||||
void DirectionalLayer::publishLocked(DirectionFieldState state, std::shared_ptr<const DirectionField> field)
|
||||
{
|
||||
snapshot_.state = state;
|
||||
snapshot_.field = std::move(field);
|
||||
++snapshot_.generation;
|
||||
// Layer::isCurrent() reads this non-atomic bool without this mutex (legacy API limitation).
|
||||
current_ = state != DirectionFieldState::kPending;
|
||||
if (state == DirectionFieldState::kPending)
|
||||
{
|
||||
pending_since_ = std::chrono::steady_clock::now();
|
||||
last_pending_log_ = {};
|
||||
}
|
||||
if (debug_state_)
|
||||
robot::log_info("[debug] DirectionalLayer %s: %s generation=%llu", name_.c_str(), stateName(state),
|
||||
static_cast<unsigned long long>(snapshot_.generation));
|
||||
layered_costmap_->notifyDirectionFieldChanged();
|
||||
}
|
||||
|
||||
DirectionFieldSnapshot DirectionalLayer::directionSnapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return snapshot_;
|
||||
}
|
||||
|
||||
DirectionGeometry DirectionalLayer::geometry() const
|
||||
{
|
||||
const auto* master = layered_costmap_->getCostmap();
|
||||
return {master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
|
||||
master->getOriginX(), master->getOriginY(), layered_costmap_->getGlobalFrameID()};
|
||||
}
|
||||
|
||||
void DirectionalLayer::handleImpl(const void* data, const std::type_info& type, const std::string& topic)
|
||||
{
|
||||
if (!enabled_ || type != typeid(robot_nav_msgs::OccupancyGrid) ||
|
||||
(!topicMatches(topic, map_topic_) && !topicMatches(topic, direction_topic_)))
|
||||
return;
|
||||
|
||||
if (topicMatches(topic, map_topic_))
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
seen_map_ = true;
|
||||
publishLocked(DirectionFieldState::kPending);
|
||||
return;
|
||||
}
|
||||
|
||||
void DirectionalLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
DirectionGeometry expected;
|
||||
uint64_t generation;
|
||||
{
|
||||
if(!map_shutdown_)
|
||||
{
|
||||
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
|
||||
|
||||
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();
|
||||
if (!layered_costmap_->isRolling() &&
|
||||
(master->getSizeInCellsX() != size_x / 2 ||
|
||||
master->getSizeInCellsY() != size_y / 2 ||
|
||||
master->getResolution() != new_map.info.resolution ||
|
||||
master->getOriginX() != new_map.info.origin.position.x ||
|
||||
master->getOriginY() != new_map.info.origin.position.y))
|
||||
{
|
||||
// Update the size of the layered costmap (and all layers, including this one)
|
||||
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*/);
|
||||
}
|
||||
else if (size_x_ != size_x / 2 || size_y_ != size_y / 2 ||
|
||||
resolution_ != new_map.info.resolution ||
|
||||
origin_x_ != new_map.info.origin.position.x ||
|
||||
origin_y_ != new_map.info.origin.position.y)
|
||||
{
|
||||
// only update the size of the costmap stored locally in this layer
|
||||
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);
|
||||
}
|
||||
unsigned char values[4];
|
||||
directional_areas_.clear();
|
||||
directional_areas_.resize(size_x / 2 * size_y / 2);
|
||||
// initialize the costmap with static data
|
||||
for (unsigned int iy = 0; iy < size_y; iy += 2)
|
||||
{
|
||||
for (unsigned int ix = 0; ix < size_x; ix += 2)
|
||||
{
|
||||
values[0] = new_map.data[MAP_IDX(size_x, ix, iy)];
|
||||
values[1] = new_map.data[MAP_IDX(size_x, ix + 1, iy)];
|
||||
values[2] = new_map.data[MAP_IDX(size_x, ix, iy + 1)];
|
||||
values[3] = new_map.data[MAP_IDX(size_x, ix + 1, iy + 1)];
|
||||
uint32_t color_avg = (uint32_t)(values[0] | values[1] << 8u | values[2] << 16u | values[3] << 24u);
|
||||
int index = getIndex(ix / 2, iy / 2);
|
||||
directional_areas_[index][0] = (uint16_t)(color_avg & 0xfff);
|
||||
directional_areas_[index][1] = (uint16_t)(color_avg >> 12u);
|
||||
costmap_[index] = robot_costmap_2d::NO_INFORMATION;
|
||||
}
|
||||
}
|
||||
map_frame_ = new_map.header.frame_id;
|
||||
|
||||
// we have a new map, update full size of map
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
map_received_ = true;
|
||||
has_updated_data_ = true;
|
||||
|
||||
new_map_.header = new_map.header;
|
||||
new_map_.header.stamp = robot::Time::now();
|
||||
new_map_.info = new_map.info;
|
||||
new_map_.info.width = width_;
|
||||
new_map_.info.height = height_;
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("Stop receive new map!\n");
|
||||
}
|
||||
// shutdown the map subscrber if firt_map_only_ flag is on
|
||||
if (first_map_only_)
|
||||
{
|
||||
robot::log_info("Shutting down the map subscriber. first_map_only flag is on\n");
|
||||
map_shutdown_ = true;
|
||||
// map_sub_.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
bool DirectionalLayer::laneFilter(std::vector<std::array<uint16_t, 2>> new_map, const robot_nav_msgs::Path path)
|
||||
{
|
||||
boost::unique_lock<mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if (new_map.empty())
|
||||
return false;
|
||||
|
||||
std::vector<std::pair<unsigned int, double>> X_List, Y_List;
|
||||
std::vector<double> Yaw_list;
|
||||
|
||||
const robot_geometry_msgs::PoseStamped &e = path.poses.back();
|
||||
|
||||
bool get_success = getRobotPose(pose_x_, pose_y_, pose_yaw_);
|
||||
if(!get_success) return false;
|
||||
for (auto it = path.poses.begin(); it != path.poses.end(); ++it)
|
||||
{
|
||||
const robot_geometry_msgs::PoseStamped &p = *it; // Get the pose from the iterator
|
||||
unsigned int mx, my;
|
||||
if (!worldToMap(p.pose.position.x, p.pose.position.y, mx, my))
|
||||
{
|
||||
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
|
||||
tf3::Quaternion quaternion = data_convert::convertQuaternion(p.pose.orientation);
|
||||
double theta = tf3::getYaw(quaternion);
|
||||
unsigned char value = laneFilter(mx, my, theta);
|
||||
if (get_success)
|
||||
{
|
||||
if (
|
||||
(!inSkipErea(pose_x_, pose_y_, p.pose.position.x, p.pose.position.y, distance_skip_) &
|
||||
!inSkipErea(p.pose.position.x, p.pose.position.y, e.pose.position.x, e.pose.position.y, distance_skip_))
|
||||
|| p == path.poses.back()
|
||||
)
|
||||
{
|
||||
if (value == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE || value == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
{
|
||||
std::pair<unsigned int, double> x_val(mx, p.pose.position.x);
|
||||
std::pair<unsigned int, double> y_val(my, p.pose.position.y);
|
||||
X_List.push_back(x_val);
|
||||
Y_List.push_back(y_val);
|
||||
Yaw_list.push_back(theta);
|
||||
// costmap_[getIndex(mx, my)] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!Yaw_list.empty())
|
||||
{
|
||||
laneFilter(X_List, Y_List, Yaw_list);
|
||||
robot_nav_msgs::OccupancyGrid lanes;
|
||||
convertToMap(costmap_, lanes, 0.65, 0.196);
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
void DirectionalLayer::convertToMap(unsigned char *costmap, robot_nav_msgs::OccupancyGrid &dir_map, double occ_th, double free_th)
|
||||
{
|
||||
dir_map.header = new_map_.header;
|
||||
dir_map.header.stamp = robot::Time::now();
|
||||
dir_map.info = new_map_.info;
|
||||
int size_costmap = new_map_.info.width * new_map_.info.height;
|
||||
dir_map.data.resize(size_costmap);
|
||||
for (int i = 0; i < size_costmap; i++)
|
||||
{
|
||||
int8_t value;
|
||||
if (costmap[i] == robot_costmap_2d::NO_INFORMATION)
|
||||
{
|
||||
value = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
double occ = (costmap[i]) / 255.0;
|
||||
if (occ > occ_th)
|
||||
value = +100;
|
||||
else if (occ < free_th)
|
||||
value = 0;
|
||||
else
|
||||
{
|
||||
double ratio = (occ - free_th) / (occ_th - free_th);
|
||||
value = 1 + 98 * ratio;
|
||||
}
|
||||
}
|
||||
dir_map.data[i] = value;
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char DirectionalLayer::laneFilter(unsigned int x, unsigned int y, double yaw_robot)
|
||||
{
|
||||
double yaw_lane;
|
||||
unsigned char cost = robot_costmap_2d::NO_INFORMATION;
|
||||
|
||||
int index = getIndex(x, y);
|
||||
for (auto &lane : directional_areas_[index])
|
||||
{
|
||||
if (lane > 359)
|
||||
{
|
||||
cost = std::min(cost, robot_costmap_2d::NO_INFORMATION);
|
||||
}
|
||||
else
|
||||
{
|
||||
double yaw_lane = (double)lane / 180 * M_PI;
|
||||
if (0.4 <= cos(yaw_robot - yaw_lane) && cos(yaw_robot - yaw_lane) <= 1.0)
|
||||
cost = std::min(cost, robot_costmap_2d::FREE_SPACE);
|
||||
else if (-1.0 <= cos(yaw_robot - yaw_lane) && cos(yaw_robot - yaw_lane) <= -0.4)
|
||||
cost = std::min(cost, robot_costmap_2d::LETHAL_OBSTACLE);
|
||||
else
|
||||
cost = std::min(cost, robot_costmap_2d::NO_INFORMATION);
|
||||
}
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
void DirectionalLayer::laneFilter(std::vector<std::pair<unsigned int, double>> x,
|
||||
std::vector<std::pair<unsigned int, double>> y,
|
||||
std::vector<double> yaw_robot)
|
||||
{
|
||||
if(x.empty() || y.empty() || yaw_robot.empty())
|
||||
boost::unique_lock<Costmap2D::mutex_t> master_lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (rolling_)
|
||||
return;
|
||||
|
||||
unsigned int x_min, y_min, x_max, y_max;
|
||||
double x_min_w, y_min_w, x_max_w, y_max_w;
|
||||
|
||||
x_min = x.front().first; y_min = y.front().first;
|
||||
x_max = x.front().first; y_max = y.front().first;
|
||||
x_min_w = x.front().second; y_min_w = y.front().second;
|
||||
x_max_w = x.front().second; y_max_w = y.front().second;
|
||||
for (int i = 1; i < yaw_robot.size(); i++)
|
||||
if (!seen_map_)
|
||||
{
|
||||
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
|
||||
continue;
|
||||
x_min = std::min(x_min, x[i].first);
|
||||
y_min = std::min(y_min, y[i].first);
|
||||
x_max = std::max(x_max, x[i].first);
|
||||
y_max = std::max(y_max, y[i].first);
|
||||
|
||||
x_min_w = std::min(x_min_w, x[i].second);
|
||||
y_min_w = std::min(y_min_w, y[i].second);
|
||||
x_max_w = std::max(x_max_w, x[i].second);
|
||||
y_max_w = std::max(y_max_w, y[i].second);
|
||||
|
||||
}
|
||||
|
||||
for (int i = 0; i < yaw_robot.size(); i++)
|
||||
{
|
||||
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
|
||||
continue;
|
||||
|
||||
double yaw_rad = (double)yaw_robot[i] / 180 * M_PI;
|
||||
if (fabs(cos(yaw_rad)) > fabs(sin(yaw_rad)))
|
||||
{
|
||||
int x_ = x[i].first;
|
||||
// Dưới lên trên
|
||||
for (int j = y[i].first; j <= y_max; j++)
|
||||
{
|
||||
int y_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trên xuống dưới
|
||||
for (int k = y[i].first; k >= y_min; k--)
|
||||
{
|
||||
int y_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
int y_ = y[i].first;
|
||||
// Phải qua trái
|
||||
for (int j = x[i].first; j < layered_costmap_->getCostmap()->getSizeInCellsX(); j++)
|
||||
{
|
||||
int x_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trái qua phải
|
||||
for (int k = x[i].first; k >= 0; k--)
|
||||
{
|
||||
int x_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if(fabs(cos(yaw_rad)) < fabs(sin(yaw_rad)))
|
||||
{
|
||||
int y_ = y[i].first;
|
||||
// Phải qua trái
|
||||
for (int j = x[i].first; j <= x_max; j++)
|
||||
{
|
||||
int x_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trái qua phải
|
||||
for (int k = x[i].first; k >= x_min; k--)
|
||||
{
|
||||
int x_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
int x_ = x[i].first;
|
||||
// Dưới lên trên
|
||||
for (int j = y[i].first; j < layered_costmap_->getCostmap()->getSizeInCellsY(); j++)
|
||||
{
|
||||
int y_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trên xuống dưới
|
||||
for (int k = y[i].first; k >= 0; k--)
|
||||
{
|
||||
int y_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
robot::log_error("DirectionalLayer %s: direction grid arrived before static map", name_.c_str());
|
||||
return;
|
||||
}
|
||||
expected = geometry();
|
||||
generation = snapshot_.generation;
|
||||
}
|
||||
|
||||
void DirectionalLayer::resetMap()
|
||||
DirectionValidationResult validation;
|
||||
auto field = DirectionField::create(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data), expected,
|
||||
max_deviation_rad_, &validation);
|
||||
if (!field)
|
||||
{
|
||||
unsigned int size_x = layered_costmap_->getCostmap()->getSizeInCellsX();
|
||||
unsigned int size_y = layered_costmap_->getCostmap()->getSizeInCellsY();
|
||||
for (unsigned int iy = 0; iy < size_y; iy++)
|
||||
{
|
||||
for (unsigned int ix = 0; ix < size_x; ix++)
|
||||
{
|
||||
int index = getIndex(ix, iy);
|
||||
costmap_[index] = robot_costmap_2d::NO_INFORMATION;
|
||||
}
|
||||
}
|
||||
robot::log_error("DirectionalLayer %s: invalid direction grid: %s", name_.c_str(), validation.message.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
bool DirectionalLayer::getRobotPose(double &x, double &y, double &yaw)
|
||||
// resizeMap holds the master mutex through matchSize(), which increments generation.
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (snapshot_.generation != generation)
|
||||
{
|
||||
tf3::TransformStampedMsg transformMsg;
|
||||
try
|
||||
{
|
||||
transformMsg = tf_->lookupTransform(map_frame_, base_frame_id_, tf3::Time());
|
||||
|
||||
// listener_.lookupTransform(map_frame_, base_frame_id_, tf3::Time(), transform);
|
||||
}
|
||||
catch (tf3::TransformException &ex)
|
||||
{
|
||||
robot::log_error("%s\n", ex.what());
|
||||
return false;
|
||||
}
|
||||
// Copy map data given proper transformations
|
||||
tf3::Transform tf3_transform;
|
||||
tf3_transform = data_convert::convertTotf3Transform(transformMsg.transform);
|
||||
x = tf3_transform.getOrigin().x();
|
||||
y = tf3_transform.getOrigin().y();
|
||||
// Extract the rotation as a quaternion from the transform
|
||||
tf3::Quaternion rotation = tf3_transform.getRotation();
|
||||
// Convert the quaternion to a yaw angle (in radians)
|
||||
yaw = tf3::getYaw(rotation);
|
||||
return true;
|
||||
robot::log_error("DirectionalLayer %s: grid discarded because map state changed during validation", name_.c_str());
|
||||
return;
|
||||
}
|
||||
publishLocked(DirectionFieldState::kReady, std::move(field));
|
||||
}
|
||||
|
||||
bool DirectionalLayer::inSkipErea(double start_x, double start_y, double end_x, double end_y, double skip_distance)
|
||||
void DirectionalLayer::matchSize()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (enabled_)
|
||||
publishLocked(DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
void DirectionalLayer::reset()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> master_lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!enabled_ || snapshot_.state != DirectionFieldState::kReady)
|
||||
return;
|
||||
const auto now = geometry();
|
||||
const auto& old = snapshot_.field->geometry();
|
||||
if (old.width != now.width || old.height != now.height || old.frame_id != now.frame_id ||
|
||||
!std::isfinite(now.resolution) || !std::isfinite(now.origin_x) || !std::isfinite(now.origin_y) ||
|
||||
std::abs(old.resolution - now.resolution) > 1e-6 || std::abs(old.origin_x - now.origin_x) > 1e-6 ||
|
||||
std::abs(old.origin_y - now.origin_y) > 1e-6)
|
||||
publishLocked(DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
void DirectionalLayer::updateBounds(double, double, double, double*, double*, double*, double*)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (snapshot_.state != DirectionFieldState::kPending)
|
||||
return;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - pending_since_ >= kPendingErrorDelay &&
|
||||
(last_pending_log_ == std::chrono::steady_clock::time_point() ||
|
||||
now - last_pending_log_ >= kPendingErrorPeriod))
|
||||
{
|
||||
return fabs(hypot(start_x - end_x, start_y - end_y)) <= skip_distance;
|
||||
robot::log_error("DirectionalLayer %s: PENDING for %.1f seconds", name_.c_str(),
|
||||
std::chrono::duration<double>(now - pending_since_).count());
|
||||
last_pending_log_ = now;
|
||||
}
|
||||
}
|
||||
} // namespace robot_costmap_2d
|
||||
|
||||
// Export factory function
|
||||
static boost::shared_ptr<Layer> create_directional_plugin() {
|
||||
return boost::make_shared<DirectionalLayer>();
|
||||
}
|
||||
|
||||
// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias)
|
||||
BOOST_DLL_ALIAS(create_directional_plugin, DirectionalLayer)
|
||||
}
|
||||
boost::shared_ptr<robot_costmap_2d::Layer> create_directional_plugin()
|
||||
{
|
||||
return boost::shared_ptr<robot_costmap_2d::Layer>(new robot_costmap_2d::DirectionalLayer());
|
||||
}
|
||||
BOOST_DLL_ALIAS(create_directional_plugin, DirectionalLayer)
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -144,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,
|
||||
@@ -203,26 +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)
|
||||
if(!inflation_cells_.empty())
|
||||
robot::log_error("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) {
|
||||
robot::log_error("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)
|
||||
{
|
||||
robot::log_error("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
|
||||
@@ -238,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++)
|
||||
@@ -258,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_;
|
||||
@@ -301,7 +301,6 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
}
|
||||
}
|
||||
|
||||
inflation_cells_.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -316,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);
|
||||
@@ -325,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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,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)
|
||||
@@ -367,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)
|
||||
|
||||
@@ -42,6 +42,8 @@
|
||||
|
||||
#include <tf3/exceptions.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
using robot_costmap_2d::NO_INFORMATION;
|
||||
@@ -54,6 +56,16 @@ using robot_costmap_2d::Observation;
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
void replaceNoReturnRanges(robot_sensor_msgs::LaserScan& scan, bool inf_is_valid, bool zero_is_valid)
|
||||
{
|
||||
constexpr float kEpsilon = 0.0001; // a tenth of a millimeter
|
||||
for (float& range : scan.ranges)
|
||||
{
|
||||
if ((inf_is_valid && !std::isfinite(range) && range > 0) || (zero_is_valid && range == 0.0f))
|
||||
range = scan.range_max - kEpsilon;
|
||||
}
|
||||
}
|
||||
|
||||
void ObstacleLayer::onInitialize()
|
||||
{
|
||||
robot::NodeHandle nh("~");
|
||||
@@ -66,7 +78,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()
|
||||
@@ -130,7 +143,7 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
// get the parameters for the specific topic
|
||||
double observation_keep_time = 0, expected_update_rate = 0, min_obstacle_height = 0, max_obstacle_height = 2;
|
||||
std::string topic = "map", sensor_frame = "laser_frame", data_type = "PointCloud";
|
||||
bool inf_is_valid = false, clearing=false, marking=true;
|
||||
bool inf_is_valid = false, zero_is_valid = false, clearing=false, marking=true;
|
||||
|
||||
robot::NodeHandle priv_nh(nh, source);
|
||||
topic = loadParam(layer[source],"topic", topic);
|
||||
@@ -141,6 +154,7 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
min_obstacle_height = loadParam(layer[source],"min_obstacle_height", 0.0);
|
||||
max_obstacle_height = loadParam(layer[source],"max_obstacle_height", 2.0);
|
||||
inf_is_valid = loadParam(layer[source],"inf_is_valid", false);
|
||||
zero_is_valid = loadParam(layer[source],"zero_is_valid", false);
|
||||
clearing = loadParam(layer[source],"clearing", false);
|
||||
marking = loadParam(layer[source],"marking", true);
|
||||
|
||||
@@ -160,11 +174,23 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
priv_nh.getParam("max_obstacle_height", max_obstacle_height);
|
||||
if (priv_nh.hasParam("inf_is_valid"))
|
||||
priv_nh.getParam("inf_is_valid", inf_is_valid);
|
||||
if (priv_nh.hasParam("zero_is_valid"))
|
||||
priv_nh.getParam("zero_is_valid", zero_is_valid);
|
||||
if (priv_nh.hasParam("clearing"))
|
||||
priv_nh.getParam("clearing", clearing);
|
||||
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");
|
||||
@@ -176,26 +202,13 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
|
||||
info_tmp.data_type = data_type;
|
||||
info_tmp.topic = topic;
|
||||
info_tmp.inf_is_valid = inf_is_valid;
|
||||
info_tmp.zero_is_valid = zero_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;
|
||||
|
||||
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
|
||||
priv_nh.getNamespace().c_str());
|
||||
robot::log_info("Creating an observation buffer for topic %s, frame %s, zero_is_valid=%s\n", topic.c_str(),
|
||||
priv_nh.getNamespace().c_str(), zero_is_valid ? "true" : "false");
|
||||
if (zero_is_valid && data_type != "LaserScan")
|
||||
robot::log_error("obstacle_layer: zero_is_valid option is not applicable to %s observations.\n", data_type.c_str());
|
||||
|
||||
// create an observation buffer
|
||||
observation_buffers_.push_back(
|
||||
@@ -209,7 +222,6 @@ 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());
|
||||
|
||||
robot::log_info(
|
||||
"Created an observation buffer for topic %s, global frame: %s, "
|
||||
"expected update rate: %.2f, observation persistence: %.2f\n",
|
||||
@@ -230,67 +242,64 @@ 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)
|
||||
{
|
||||
// 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;
|
||||
// }
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("Stop receiving data!\n");
|
||||
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 && !callback_infos_[i].zero_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 || callback_infos_[i].zero_is_valid))
|
||||
{
|
||||
|
||||
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer,
|
||||
callback_infos_[i].inf_is_valid, callback_infos_[i].zero_is_valid);
|
||||
}
|
||||
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;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,19 +334,11 @@ void ObstacleLayer::laserScanCallback(const robot_sensor_msgs::LaserScan& messag
|
||||
}
|
||||
|
||||
void ObstacleLayer::laserScanValidInfCallback(const robot_sensor_msgs::LaserScan& raw_message,
|
||||
const boost::shared_ptr<ObservationBuffer>& buffer)
|
||||
const boost::shared_ptr<ObservationBuffer>& buffer,
|
||||
bool inf_is_valid, bool zero_is_valid)
|
||||
{
|
||||
// Filter positive infinities ("Inf"s) to max_range.
|
||||
float epsilon = 0.0001; // a tenth of a millimeter
|
||||
robot_sensor_msgs::LaserScan message = raw_message;
|
||||
for (size_t i = 0; i < message.ranges.size(); i++)
|
||||
{
|
||||
float range = message.ranges[ i ];
|
||||
if (!std::isfinite(range) && range > 0)
|
||||
{
|
||||
message.ranges[ i ] = message.range_max - epsilon;
|
||||
}
|
||||
}
|
||||
replaceNoReturnRanges(message, inf_is_valid, zero_is_valid);
|
||||
|
||||
// project the laser into a point cloud
|
||||
robot_sensor_msgs::PointCloud2 cloud;
|
||||
@@ -430,6 +431,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;
|
||||
@@ -437,7 +441,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_)
|
||||
{
|
||||
robot::log_error("The point is too high\n");
|
||||
++rejected_height;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -448,7 +452,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)
|
||||
{
|
||||
robot::log_error("The point is too far away\n");
|
||||
++rejected_range;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -456,7 +460,7 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
|
||||
unsigned int mx, my;
|
||||
if (!worldToMap(px, py, mx, my))
|
||||
{
|
||||
robot::log_error("Computing map coords failed\n");
|
||||
++rejected_bounds;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -464,6 +468,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);
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <stdexcept>
|
||||
#include <fstream>
|
||||
#include <cxxabi.h>
|
||||
|
||||
@@ -64,14 +65,24 @@ StaticLayer::~StaticLayer()
|
||||
|
||||
void StaticLayer::onInitialize()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
robot::NodeHandle nh("~");
|
||||
robot::NodeHandle priv_nh(nh, name_);
|
||||
|
||||
current_ = true;
|
||||
current_ = false;
|
||||
if (map_received_)
|
||||
{
|
||||
// Reinitialization must request another master write even if the old map is retained.
|
||||
has_updated_data_ = true;
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -157,9 +168,16 @@ void StaticLayer::matchSize()
|
||||
// unrelated to the size of the layered costmap
|
||||
if (!layered_costmap_->isRolling())
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
// resizeMap discards this layer's cached cells, even when the geometry is unchanged.
|
||||
// A new map is required before the layer can write meaningful data again.
|
||||
current_ = false;
|
||||
map_received_ = false;
|
||||
has_updated_data_ = false;
|
||||
Costmap2D* master = layered_costmap_->getCostmap();
|
||||
resizeMap(master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
|
||||
master->getOriginX(), master->getOriginY());
|
||||
layered_costmap_->notifyStaticMapChanged(getType());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,9 +214,14 @@ void StaticLayer::handleImpl(const void* data,
|
||||
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) &&
|
||||
} 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 if (type == typeid(robot_nav_msgs::OccupancyGrid) ||
|
||||
type == typeid(robot_map_msgs::OccupancyGridUpdate)) {
|
||||
// Right type, another layer's topic: the gateway sends every grid to every layer of this
|
||||
// type (other StaticLayers, the direction grid). Normal traffic, not an error.
|
||||
return;
|
||||
} else {
|
||||
std::string readable = boost::core::demangle(type.name());
|
||||
|
||||
@@ -207,7 +230,6 @@ void StaticLayer::handleImpl(const void* data,
|
||||
{
|
||||
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;
|
||||
}
|
||||
@@ -215,8 +237,10 @@ void StaticLayer::handleImpl(const void* data,
|
||||
|
||||
void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if(!map_shutdown_)
|
||||
{
|
||||
current_ = false;
|
||||
std::cout << "[StaticLayer] Received new map!" << std::endl;
|
||||
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
|
||||
|
||||
@@ -282,6 +306,7 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
height_ = size_y_;
|
||||
map_received_ = true;
|
||||
has_updated_data_ = true;
|
||||
layered_costmap_->notifyStaticMapChanged(getType());
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -298,8 +323,25 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
|
||||
void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update)
|
||||
{
|
||||
if(!map_update_shutdown_)
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if(!map_update_shutdown_ && map_received_)
|
||||
{
|
||||
const bool outside = update.x < 0 || update.y < 0 || update.width == 0 || update.height == 0 ||
|
||||
static_cast<unsigned int>(update.x) > size_x_ || static_cast<unsigned int>(update.y) > size_y_ ||
|
||||
update.width > size_x_ - static_cast<unsigned int>(update.x) ||
|
||||
update.height > size_y_ - static_cast<unsigned int>(update.y);
|
||||
if (outside || update.data.size() != static_cast<std::size_t>(update.width) * update.height)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (last_invalid_update_log_ == std::chrono::steady_clock::time_point{} ||
|
||||
std::chrono::duration<double>(now - last_invalid_update_log_).count() >= 5.0)
|
||||
{
|
||||
robot::log_error("StaticLayer %s: ignoring an invalid map update", name_.c_str());
|
||||
last_invalid_update_log_ = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
current_ = false;
|
||||
robot::log_info("Update new map!\n");
|
||||
unsigned int di = 0;
|
||||
for (unsigned int y = 0; y < update.height ; y++)
|
||||
@@ -311,16 +353,35 @@ void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& upda
|
||||
costmap_[index] = interpretValue(update.data[di++]);
|
||||
}
|
||||
}
|
||||
x_ = update.x;
|
||||
y_ = update.y;
|
||||
width_ = update.width;
|
||||
height_ = update.height;
|
||||
if (has_updated_data_)
|
||||
{
|
||||
// A full map or another update may still be awaiting updateBounds(). Preserve all dirty
|
||||
// cells; otherwise a partial update could make the layer current while part of the new map
|
||||
// has never reached the master.
|
||||
const unsigned int update_x = static_cast<unsigned int>(update.x);
|
||||
const unsigned int update_y = static_cast<unsigned int>(update.y);
|
||||
const unsigned int max_x = std::max(x_ + width_, update_x + update.width);
|
||||
const unsigned int max_y = std::max(y_ + height_, update_y + update.height);
|
||||
x_ = std::min(x_, update_x);
|
||||
y_ = std::min(y_, update_y);
|
||||
width_ = max_x - x_;
|
||||
height_ = max_y - y_;
|
||||
}
|
||||
else
|
||||
{
|
||||
x_ = update.x;
|
||||
y_ = update.y;
|
||||
width_ = update.width;
|
||||
height_ = update.height;
|
||||
}
|
||||
has_updated_data_ = true;
|
||||
layered_costmap_->notifyStaticMapChanged(getType());
|
||||
}
|
||||
}
|
||||
|
||||
void StaticLayer::activate()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
map_shutdown_ = false;
|
||||
map_update_shutdown_ = false;
|
||||
onInitialize();
|
||||
@@ -328,6 +389,7 @@ void StaticLayer::activate()
|
||||
|
||||
void StaticLayer::deactivate()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
map_shutdown_ = true;
|
||||
if (subscribe_to_updates_)
|
||||
map_update_shutdown_ = true;
|
||||
@@ -335,11 +397,16 @@ void StaticLayer::deactivate()
|
||||
|
||||
void StaticLayer::reset()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if (first_map_only_)
|
||||
{
|
||||
map_shutdown_ = false;
|
||||
map_update_shutdown_ = false;
|
||||
current_ = false;
|
||||
has_updated_data_ = true;
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -358,6 +425,18 @@ void StaticLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
|
||||
|
||||
useExtraBounds(min_x, min_y, max_x, max_y);
|
||||
|
||||
if (layered_costmap_->isRolling())
|
||||
{
|
||||
// The layer extent is in map_frame_; redraw the moving window in the master frame.
|
||||
const Costmap2D& master = *layered_costmap_->getCostmap();
|
||||
*min_x = std::min(*min_x, master.getOriginX());
|
||||
*min_y = std::min(*min_y, master.getOriginY());
|
||||
*max_x = std::max(*max_x, master.getOriginX() + master.getSizeInCellsX() * master.getResolution());
|
||||
*max_y = std::max(*max_y, master.getOriginY() + master.getSizeInCellsY() * master.getResolution());
|
||||
has_updated_data_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
double wx, wy;
|
||||
|
||||
mapToWorld(x_, y_, wx, wy);
|
||||
@@ -373,7 +452,7 @@ void StaticLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
|
||||
|
||||
void StaticLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (!map_received_)
|
||||
if (!map_received_ || !enabled_)
|
||||
return;
|
||||
|
||||
if (!layered_costmap_->isRolling())
|
||||
@@ -411,21 +490,25 @@ void StaticLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_
|
||||
for (unsigned int j = min_j; j < max_j; ++j)
|
||||
{
|
||||
// Convert master_grid coordinates (i,j) into global_frame_(wx,wy) coordinates
|
||||
layered_costmap_->getCostmap()->mapToWorld(i, j, wx, wy);
|
||||
master_grid.mapToWorld(i, j, wx, wy);
|
||||
// Transform from global_frame_ to map_frame_
|
||||
tf3::Vector3 p(wx, wy, 0);
|
||||
p = tf3_transform*p;
|
||||
// Set master_grid with cell from map
|
||||
if (worldToMap(p.x(), p.y(), mx, my))
|
||||
{
|
||||
if (!use_maximum_)
|
||||
master_grid.setCost(i, j, getCost(mx, my));
|
||||
else
|
||||
master_grid.setCost(i, j, std::max(getCost(mx, my), master_grid.getCost(i, j)));
|
||||
master_grid.setCost(i, j, mergeCost(master_grid.getCost(i, j), getCost(mx, my), use_maximum_));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
markMapWritten(min_i, min_j, max_i, max_j);
|
||||
}
|
||||
|
||||
void StaticLayer::markMapWritten(int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (map_received_ && min_i < max_i && min_j < max_j)
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
// Export factory function
|
||||
|
||||
@@ -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()
|
||||
@@ -85,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"))
|
||||
@@ -100,25 +110,40 @@ 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();
|
||||
}
|
||||
catch (const YAML::BadFile& e) {
|
||||
@@ -231,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);
|
||||
}
|
||||
|
||||
@@ -327,14 +329,6 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
|
||||
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();
|
||||
@@ -409,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)
|
||||
@@ -438,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;
|
||||
@@ -458,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();
|
||||
@@ -480,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)
|
||||
|
||||
@@ -48,9 +48,14 @@
|
||||
#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
|
||||
@@ -58,13 +63,40 @@ 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))
|
||||
if (new_h.hasParam(name) || !old_h.hasParam(name))
|
||||
return;
|
||||
|
||||
old_h.getParam(name, value);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
robot::NodeHandle Costmap2DROBOT::commonParametersHandle(robot::NodeHandle& tree_nh)
|
||||
{
|
||||
if (!tree_nh.hasParam("root"))
|
||||
return tree_nh;
|
||||
// A scalar or list `root:` would still be selected, and every shared key (sensor sources, zone
|
||||
// topics, transform_tolerance) would then read as missing. Refuse it instead of running blind.
|
||||
if (!tree_nh.getParamValue("root").IsMap())
|
||||
throw std::invalid_argument("'root' must be a map of shared costmap parameters");
|
||||
return robot::NodeHandle("root");
|
||||
}
|
||||
|
||||
Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) :
|
||||
layered_costmap_(NULL),
|
||||
name_(name),
|
||||
@@ -105,7 +137,39 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
YAML::Node config = YAML::LoadFile(path_source);
|
||||
YAML::Node layer = config["robot_costmap_2d"];
|
||||
|
||||
robot::NodeHandle priv_nh(priv_nh, name);
|
||||
robot::NodeHandle priv_nh(nh, name);
|
||||
robot::NodeHandle tree_nh("~");
|
||||
const bool rooted = tree_nh.hasParam("root");
|
||||
robot::NodeHandle common_nh = commonParametersHandle(tree_nh);
|
||||
robot::log_info("costmap '%s': shared parameters use %s layout\n",
|
||||
name.c_str(), rooted ? "root" : "flat");
|
||||
if (rooted)
|
||||
{
|
||||
std::string ignored_keys;
|
||||
for (const char* key : {"robot_base_frame", "transform_tolerance", "footprint_padding"})
|
||||
{
|
||||
if (tree_nh.hasParam(key))
|
||||
{
|
||||
if (!ignored_keys.empty())
|
||||
ignored_keys += ", ";
|
||||
ignored_keys += key;
|
||||
}
|
||||
}
|
||||
if (!ignored_keys.empty())
|
||||
robot::log_warning("costmap '%s': root layout ignores file-root keys: %s\n",
|
||||
name.c_str(), ignored_keys.c_str());
|
||||
}
|
||||
|
||||
// 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"));
|
||||
@@ -115,8 +179,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
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);
|
||||
if (common_nh.hasParam("robot_base_frame"))
|
||||
common_nh.getParam("robot_base_frame", robot_base_frame);
|
||||
|
||||
global_frame_ = global_frame;
|
||||
robot_base_frame_ = robot_base_frame;
|
||||
@@ -129,10 +193,10 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
{
|
||||
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::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",
|
||||
robot::log_warning_throttle(5.0, "[%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());
|
||||
last_error = robot::Time::now();
|
||||
}
|
||||
@@ -155,9 +219,36 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
if (priv_nh.hasParam("track_unknown_space"))
|
||||
priv_nh.getParam("track_unknown_space", track_unknown_space);
|
||||
|
||||
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);
|
||||
@@ -195,44 +286,22 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
{
|
||||
my_list.clear();
|
||||
YAML::Node my_plugins = priv_nh.getParamValue("plugins");
|
||||
if (my_plugins && my_plugins.IsSequence())
|
||||
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
|
||||
@@ -248,12 +317,11 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
}
|
||||
}
|
||||
}
|
||||
robot::NodeHandle private_nh("~");
|
||||
for (auto& info : my_list)
|
||||
{
|
||||
try
|
||||
{
|
||||
copyParentParameters(name_, info.name, info.type, private_nh);
|
||||
copyParentParameters(name_, info.name, info.type, common_nh, tree_nh);
|
||||
creators_.push_back(
|
||||
boost::dll::import_alias<PluginLayerPtr()>(
|
||||
path_plugins, info.type, boost::dll::load_mode::append_decorations)
|
||||
@@ -264,10 +332,10 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,8 +349,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
new_footprint = makeFootprintFromParams(priv_nh);
|
||||
}
|
||||
|
||||
if (nh.hasParam("transform_tolerance"))
|
||||
nh.getParam("transform_tolerance", transform_tolerance_);
|
||||
if (common_nh.hasParam("transform_tolerance"))
|
||||
common_nh.getParam("transform_tolerance", transform_tolerance_);
|
||||
// robot::log_info("transform_tolerance: %d", transform_tolerance_);
|
||||
|
||||
setUnpaddedRobotFootprint(new_footprint);
|
||||
@@ -305,8 +373,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
// If the padding has changed, call setUnpaddedRobotFootprint() to
|
||||
// re-apply the padding.
|
||||
float footprint_padding = loadParam(layer, "footprint_padding", 0.0);
|
||||
if (nh.hasParam("footprint_padding"))
|
||||
nh.getParam("footprint_padding", footprint_padding);
|
||||
if (common_nh.hasParam("footprint_padding"))
|
||||
common_nh.getParam("footprint_padding", footprint_padding);
|
||||
if (footprint_padding_ != footprint_padding)
|
||||
{
|
||||
footprint_padding_ = footprint_padding;
|
||||
@@ -318,153 +386,174 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
|
||||
priv_nh.getParam("robot_radius", robot_radius);
|
||||
readFootprintFromConfig(new_footprint, unpadded_footprint_, robot_radius);
|
||||
|
||||
bool reference_graph_enabled = loadParam(layer, "reference_graph_enabled", false);
|
||||
if (priv_nh.hasParam("reference_graph_enabled"))
|
||||
priv_nh.getParam("reference_graph_enabled", reference_graph_enabled);
|
||||
if (reference_graph_enabled)
|
||||
{
|
||||
if (rolling_window)
|
||||
fail("reference_graph_enabled: true does not work with rolling_window: true");
|
||||
ReferenceGraphParams graph_params;
|
||||
const auto read_length = [&](const char* key, double* value) {
|
||||
*value = loadParam(layer, key, *value);
|
||||
if (priv_nh.hasParam(key))
|
||||
priv_nh.getParam(key, *value);
|
||||
};
|
||||
read_length("reference_graph_min_clearance_m", &graph_params.min_clearance_m);
|
||||
read_length("reference_graph_ridge_min_separation_m", &graph_params.ridge_min_separation_m);
|
||||
read_length("reference_graph_spur_min_length_m", &graph_params.spur_min_length_m);
|
||||
read_length("reference_graph_lane_offset_step_m", &graph_params.lane_offset_step_m);
|
||||
graph_params.debug_log = loadParam(layer, "reference_graph_debug_log", graph_params.debug_log);
|
||||
if (priv_nh.hasParam("reference_graph_debug_log"))
|
||||
priv_nh.getParam("reference_graph_debug_log", graph_params.debug_log);
|
||||
const std::string graph_error = validateReferenceGraphParams(graph_params);
|
||||
if (!graph_error.empty())
|
||||
fail("reference_graph: " + graph_error);
|
||||
if (!layered_costmap_->enableReferenceGraph(graph_params))
|
||||
fail("reference_graph: could not start");
|
||||
robot::log_info("costmap '%s': reference graph on, min_clearance=%.3f m ridge_separation=%.3f m spur=%.3f m lane_step=%.3f m debug_log=%d\n",
|
||||
name_.c_str(), graph_params.min_clearance_m, graph_params.ridge_min_separation_m, graph_params.spur_min_length_m,
|
||||
graph_params.lane_offset_step_m, graph_params.debug_log ? 1 : 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("costmap '%s': reference graph off\n", name_.c_str());
|
||||
}
|
||||
|
||||
// only construct the thread if the frequency is positive
|
||||
if(map_update_frequency > 0.0)
|
||||
map_update_thread_ = new boost::thread(boost::bind(&Costmap2DROBOT::mapUpdateLoop, this, map_update_frequency));
|
||||
}
|
||||
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)
|
||||
robot::NodeHandle& source_nh,
|
||||
robot::NodeHandle& target_nh)
|
||||
{
|
||||
robot::NodeHandle costmap_nh(nh, costmap_name);
|
||||
// Step 2 of the layer config flow. A layer reads its default file, then overrides each key found
|
||||
// in "<costmap>/<plugin>". Shared "<plugin>:" values fill only keys that the costmap block
|
||||
// does not set. The lists must cover every shared key read by the layer, with matching types.
|
||||
if (!source_nh.hasParam(plugin_name))
|
||||
return;
|
||||
// Child handles fall back to their parent when an intermediate namespace is missing.
|
||||
if (!target_nh.hasParam(costmap_name))
|
||||
target_nh.setParam(costmap_name, YAML::Node(YAML::NodeType::Map));
|
||||
robot::NodeHandle costmap_nh(target_nh, costmap_name);
|
||||
robot::NodeHandle costmap_plugin_nh(costmap_nh, plugin_name);
|
||||
robot::NodeHandle plugin_nh(nh, plugin_name);
|
||||
if(plugin_type == "StaticLayer")
|
||||
{
|
||||
std::string map_topic;
|
||||
int unknown_cost_value;
|
||||
int lethal_cost_threshold;
|
||||
bool track_unknown_space;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "map_topic", map_topic);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "unknown_cost_value", unknown_cost_value);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "lethal_cost_threshold", lethal_cost_threshold);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "track_unknown_space", track_unknown_space);
|
||||
}
|
||||
else if(plugin_type == "VoxelLayer")
|
||||
{
|
||||
double origin_z;
|
||||
double z_resolution;
|
||||
int z_voxels;
|
||||
int mark_threshold;
|
||||
int unknown_threshold;
|
||||
bool publish_voxel_map;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "origin_z", origin_z);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "z_resolution", z_resolution);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "z_voxels", z_voxels);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "mark_threshold", mark_threshold);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "unknown_threshold", unknown_threshold);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "publish_voxel_map", publish_voxel_map);
|
||||
if(plugin_nh.hasParam("observation_sources"))
|
||||
{
|
||||
std::string topics_string;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
|
||||
robot::log_error("topics_string: %s", topics_string.c_str());
|
||||
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);
|
||||
std::string topic;
|
||||
std::string data_type;
|
||||
bool clearing;
|
||||
bool marking;
|
||||
bool inf_is_valid;
|
||||
std::string sensor_frame;
|
||||
double observation_persistence;
|
||||
double expected_update_rate;
|
||||
double min_obstacle_height;
|
||||
double max_obstacle_height;
|
||||
double obstacle_range;
|
||||
double raytrace_range;
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "observation_persistence", observation_persistence);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "expected_update_rate", expected_update_rate);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "data_type", data_type);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "clearing", clearing);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "marking", marking);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "inf_is_valid", inf_is_valid);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "min_obstacle_height", min_obstacle_height);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
|
||||
robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(plugin_type == "ObstacleLayer")
|
||||
{
|
||||
double max_obstacle_height;
|
||||
double raytrace_range;
|
||||
double obstacle_range;
|
||||
bool track_unknown_space;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "max_obstacle_height", max_obstacle_height);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "raytrace_range", raytrace_range);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "obstacle_range", obstacle_range);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "track_unknown_space", track_unknown_space);
|
||||
if(plugin_nh.hasParam("observation_sources"))
|
||||
{
|
||||
std::string topics_string;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
|
||||
robot::log_error("topics_string: %s", topics_string.c_str());
|
||||
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);
|
||||
std::string topic;
|
||||
std::string data_type;
|
||||
bool clearing;
|
||||
bool marking;
|
||||
bool inf_is_valid;
|
||||
std::string sensor_frame;
|
||||
double observation_persistence;
|
||||
double expected_update_rate;
|
||||
double min_obstacle_height;
|
||||
double max_obstacle_height;
|
||||
double obstacle_range;
|
||||
double raytrace_range;
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "observation_persistence", observation_persistence);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "expected_update_rate", expected_update_rate);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "data_type", data_type);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "clearing", clearing);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "marking", marking);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "inf_is_valid", inf_is_valid);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "min_obstacle_height", min_obstacle_height);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
|
||||
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
|
||||
robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(plugin_type == "InflationLayer")
|
||||
{
|
||||
double cost_scaling_factor;
|
||||
double inflation_radius;
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "cost_scaling_factor", cost_scaling_factor);
|
||||
move_parameter(plugin_nh, costmap_plugin_nh, "inflation_radius", inflation_radius);
|
||||
}
|
||||
robot::NodeHandle plugin_nh(source_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);
|
||||
if (costmap_plugin_nh.hasParam("observation_sources"))
|
||||
costmap_plugin_nh.getParam("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);
|
||||
}
|
||||
};
|
||||
|
||||
// PreferredLayer and UnPreferredLayer inherit StaticLayer::getParams(), so they read the same keys.
|
||||
// Without them here a shared "preferred:" block is ignored and the layer keeps the default
|
||||
// map_topic "map", i.e. it would consume the static map itself.
|
||||
if (plugin_type == "StaticLayer" || plugin_type == "PreferredLayer" || plugin_type == "UnPreferredLayer")
|
||||
{
|
||||
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", "zero_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", "occlusion_guard"});
|
||||
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", "attach_distance"});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint)
|
||||
{
|
||||
{
|
||||
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;
|
||||
@@ -510,6 +599,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_);
|
||||
@@ -526,6 +616,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_)
|
||||
@@ -541,6 +636,7 @@ void Costmap2DROBOT::mapUpdateLoop(double frequency)
|
||||
|
||||
void Costmap2DROBOT::updateMap()
|
||||
{
|
||||
boost::recursive_mutex::scoped_lock lock(configuration_mutex_);
|
||||
if (!stop_updates_)
|
||||
{
|
||||
// get global pose
|
||||
@@ -672,35 +768,9 @@ 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_, tf3::Time()))
|
||||
{
|
||||
tf3::TransformStampedMsg transform = tf_.lookupTransform(global_frame_, robot_base_frame_,tf3::Time());
|
||||
tf3::doTransform(robot_pose, global_pose, transform);
|
||||
// robot::log_error("%s ||| %f | %f | %f ||| %f | %f | %f | %f", transform.child_frame_id.c_str(),
|
||||
// global_pose.pose.position.x,
|
||||
// global_pose.pose.position.y,
|
||||
// global_pose.pose.position.z,
|
||||
// global_pose.pose.orientation.x,
|
||||
// global_pose.pose.orientation.y,
|
||||
// global_pose.pose.orientation.z,
|
||||
// global_pose.pose.orientation.w);
|
||||
// transform.transform.rotation.x,
|
||||
// transform.transform.rotation.y,
|
||||
// transform.transform.rotation.z,
|
||||
// transform.transform.rotation.w);
|
||||
}
|
||||
// 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
|
||||
tf3::Time()
|
||||
);
|
||||
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)
|
||||
{
|
||||
@@ -721,7 +791,7 @@ bool Costmap2DROBOT::getRobotPose(robot_geometry_msgs::PoseStamped& global_pose)
|
||||
// check global_pose timeout
|
||||
if (!global_pose.header.stamp.isZero() && current_time.toSec() - global_pose.header.stamp.toSec() > transform_tolerance_)
|
||||
{
|
||||
robot::log_warning("Costmap2DROBOT %s transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n", name_.c_str(),
|
||||
robot::log_warning_throttle(1.0,"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;
|
||||
}
|
||||
|
||||
@@ -60,6 +60,18 @@ void CostmapLayer::useExtraBounds(double* min_x, double* min_y, double* max_x, d
|
||||
has_extra_bounds_ = false;
|
||||
}
|
||||
|
||||
unsigned char CostmapLayer::mergeCost(unsigned char master_cost, unsigned char layer_cost, bool use_maximum)
|
||||
{
|
||||
if (layer_cost == NO_INFORMATION)
|
||||
return master_cost;
|
||||
if (!use_maximum || layer_cost == CRITICAL_SPACE ||
|
||||
((layer_cost == PREFERRED_SPACE || layer_cost == UNPREFERRED_SPACE) &&
|
||||
master_cost < INSCRIBED_INFLATED_OBSTACLE) ||
|
||||
master_cost == NO_INFORMATION || master_cost < layer_cost)
|
||||
return layer_cost;
|
||||
return master_cost;
|
||||
}
|
||||
|
||||
void CostmapLayer::updateWithMax(robot_costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (!enabled_)
|
||||
@@ -73,28 +85,7 @@ void CostmapLayer::updateWithMax(robot_costmap_2d::Costmap2D& master_grid, int m
|
||||
unsigned int it = j * span + min_i;
|
||||
for (int i = min_i; i < max_i; i++)
|
||||
{
|
||||
if (costmap_[it] == NO_INFORMATION){
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
if (costmap_[it] == CRITICAL_SPACE){
|
||||
master_array[it] = costmap_[it];
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
if (costmap_[it] == PREFERRED_SPACE && master_array[it] < INSCRIBED_INFLATED_OBSTACLE ){
|
||||
master_array[it] = costmap_[it];
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
if (costmap_[it] == UNPREFERRED_SPACE && master_array[it] < INSCRIBED_INFLATED_OBSTACLE ){
|
||||
master_array[it] = costmap_[it];
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
unsigned char old_cost = master_array[it];
|
||||
if (old_cost == NO_INFORMATION || old_cost < costmap_[it])
|
||||
master_array[it] = costmap_[it];
|
||||
master_array[it] = mergeCost(master_array[it], costmap_[it], true);
|
||||
it++;
|
||||
}
|
||||
}
|
||||
@@ -131,8 +122,7 @@ void CostmapLayer::updateWithOverwrite(robot_costmap_2d::Costmap2D& master_grid,
|
||||
unsigned int it = span*j+min_i;
|
||||
for (int i = min_i; i < max_i; i++)
|
||||
{
|
||||
if (costmap_[it] != NO_INFORMATION)
|
||||
master[it] = costmap_[it];
|
||||
master[it] = mergeCost(master[it], costmap_[it], false);
|
||||
it++;
|
||||
}
|
||||
}
|
||||
|
||||
177
src/direction_field.cpp
Normal file
177
src/direction_field.cpp
Normal file
@@ -0,0 +1,177 @@
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <sstream>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr double kTolerance = 1e-6;
|
||||
|
||||
std::string frameName(const std::string& frame)
|
||||
{
|
||||
return !frame.empty() && frame[0] == '/' ? frame.substr(1) : frame;
|
||||
}
|
||||
|
||||
DirectionValidationResult fail(DirectionValidationError error, const std::string& message)
|
||||
{
|
||||
return {error, message};
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::string value(const char* name, T actual)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << name << "=" << actual;
|
||||
return out.str();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected)
|
||||
{
|
||||
const auto& info = grid.info;
|
||||
const uint64_t count = uint64_t(info.width) * uint64_t(info.height);
|
||||
if (count > std::vector<uint8_t>().max_size())
|
||||
return fail(DirectionValidationError::kOverflow, value("cell count", count));
|
||||
if (frameName(grid.header.frame_id).empty() || frameName(grid.header.frame_id) != frameName(expected.frame_id))
|
||||
return fail(DirectionValidationError::kFrame,
|
||||
"frame_id=" + grid.header.frame_id + " expected=" + expected.frame_id);
|
||||
if (info.width != expected.width || info.height != expected.height)
|
||||
return fail(DirectionValidationError::kGeometry,
|
||||
value("width", info.width) + " " + value("height", info.height));
|
||||
|
||||
const auto close = [](double a, double b)
|
||||
{
|
||||
return std::isfinite(a) && std::isfinite(b) && std::abs(a - b) <= kTolerance;
|
||||
};
|
||||
if (!close(info.resolution, expected.resolution) || info.resolution <= 0.0 || expected.resolution <= 0.0)
|
||||
return fail(DirectionValidationError::kGeometry, value("resolution", info.resolution));
|
||||
if (!close(info.origin.position.x, expected.origin_x) || !close(info.origin.position.y, expected.origin_y) ||
|
||||
!std::isfinite(info.origin.position.z))
|
||||
return fail(DirectionValidationError::kGeometry,
|
||||
value("origin.x", info.origin.position.x) + " " + value("origin.y", info.origin.position.y) +
|
||||
" " + value("origin.z", info.origin.position.z));
|
||||
|
||||
const auto& q = info.origin.orientation;
|
||||
// A default-constructed Pose has a zero quaternion; it denotes no rotation here.
|
||||
if (!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w) ||
|
||||
std::abs(q.x) > kTolerance || std::abs(q.y) > kTolerance || std::abs(q.z) > kTolerance ||
|
||||
!(std::abs(std::abs(q.w) - 1.0) <= kTolerance || std::abs(q.w) <= kTolerance))
|
||||
return fail(DirectionValidationError::kOrientation,
|
||||
value("orientation.x", q.x) + " " + value("y", q.y) + " " + value("z", q.z) +
|
||||
" " + value("w", q.w));
|
||||
if (!grid.data.empty() && grid.data.size() != count)
|
||||
return fail(DirectionValidationError::kSize, value("data.size", grid.data.size()) + " " + value("expected", count));
|
||||
for (size_t i = 0; i < grid.data.size(); ++i)
|
||||
{
|
||||
if (grid.data[i] < 0 || grid.data[i] > 8)
|
||||
return fail(DirectionValidationError::kCode, value("data index", i) + " " + value("code", int(grid.data[i])));
|
||||
}
|
||||
return {DirectionValidationError::kNone, "valid"};
|
||||
}
|
||||
|
||||
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad)
|
||||
{
|
||||
if (!std::isfinite(dx) || !std::isfinite(dy))
|
||||
return 0;
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
const long double x = dx, y = dy;
|
||||
const bool legacy_right_angle = max_deviation_rad == M_PI / 2.0;
|
||||
const long double length = std::hypot(x, y);
|
||||
const long double threshold = (std::cos(max_deviation_rad) - 1e-9L) * length;
|
||||
const long double legacy_tolerance = 1e-9L * (std::abs(x) + std::abs(y));
|
||||
constexpr long double kInverseSqrtTwo = 0.707106781186547524400844362104849L;
|
||||
uint8_t mask = 0;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const long double dot = vx[k] * x + vy[k] * y;
|
||||
// Preserve the exact legacy tolerance at 90 degrees, including near-boundary inputs.
|
||||
if (legacy_right_angle ? dot >= -legacy_tolerance :
|
||||
dot * (k % 2 ? kInverseSqrtTwo : 1.0L) >= threshold)
|
||||
mask |= uint8_t(1u << k);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
DirectionField::DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry,
|
||||
double max_deviation_rad)
|
||||
: geometry_(geometry), codes_(grid.data.begin(), grid.data.end()),
|
||||
max_deviation_rad_(max_deviation_rad),
|
||||
has_constraints_(std::any_of(codes_.begin(), codes_.end(), [](uint8_t c) { return c != 0; }))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<const DirectionField> DirectionField::create(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected,
|
||||
double max_deviation_rad,
|
||||
DirectionValidationResult* result)
|
||||
{
|
||||
auto validation = validateDirectionGrid(grid, expected);
|
||||
if (result)
|
||||
*result = validation;
|
||||
if (!validation)
|
||||
return {};
|
||||
return std::shared_ptr<const DirectionField>(new DirectionField(grid, expected, max_deviation_rad));
|
||||
}
|
||||
|
||||
uint8_t DirectionField::code(uint32_t x, uint32_t y) const
|
||||
{
|
||||
assert(x < geometry_.width && y < geometry_.height);
|
||||
return codes_.empty() ? 0 : codes_[size_t(y) * geometry_.width + x];
|
||||
}
|
||||
|
||||
bool DirectionField::codeAt(int64_t x, int64_t y, uint8_t* code_out) const
|
||||
{
|
||||
if (!code_out || x < 0 || y < 0 || x >= geometry_.width || y >= geometry_.height)
|
||||
return false;
|
||||
*code_out = code(static_cast<uint32_t>(x), static_cast<uint32_t>(y));
|
||||
return true;
|
||||
}
|
||||
|
||||
SegmentResult DirectionField::checkSegment(double wx0, double wy0, double wx1, double wy1,
|
||||
SegmentViolation* first) const
|
||||
{
|
||||
const auto gx = [this](double x) { return (x - geometry_.origin_x) / geometry_.resolution; };
|
||||
const auto gy = [this](double y) { return (y - geometry_.origin_y) / geometry_.resolution; };
|
||||
const double x0 = gx(wx0);
|
||||
const double y0 = gy(wy0);
|
||||
const double x1 = gx(wx1);
|
||||
const double y1 = gy(wy1);
|
||||
const auto inside = [this](double x, double y)
|
||||
{
|
||||
return std::isfinite(x) && std::isfinite(y) && x >= 0 && y >= 0 &&
|
||||
x < geometry_.width && y < geometry_.height;
|
||||
};
|
||||
if (!inside(x0, y0) || !inside(x1, y1))
|
||||
return SegmentResult::kOutOfGrid;
|
||||
const double dx = wx1 - wx0;
|
||||
const double dy = wy1 - wy0;
|
||||
if (!std::isfinite(dx) || !std::isfinite(dy))
|
||||
return SegmentResult::kOutOfGrid;
|
||||
|
||||
const uint8_t mask = allowedDirectionMask(dx, dy, max_deviation_rad_);
|
||||
SegmentResult result = SegmentResult::kAllowed;
|
||||
const bool completed = traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y)
|
||||
{
|
||||
uint8_t cell_code;
|
||||
if (!codeAt(x, y, &cell_code))
|
||||
{
|
||||
result = SegmentResult::kOutOfGrid;
|
||||
return false;
|
||||
}
|
||||
if (cell_code && !(mask & (1u << (cell_code - 1))))
|
||||
{
|
||||
if (first)
|
||||
*first = {uint32_t(x), uint32_t(y), cell_code, dx, dy};
|
||||
result = SegmentResult::kViolation;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return completed || result != SegmentResult::kAllowed ? result : SegmentResult::kOutOfGrid;
|
||||
}
|
||||
} // namespace robot_costmap_2d
|
||||
@@ -37,7 +37,10 @@
|
||||
*********************************************************************/
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
#include <robot_costmap_2d/footprint.h>
|
||||
#include <robot_costmap_2d/reference_graph_worker.h>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <utility>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
@@ -69,10 +72,125 @@ 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()
|
||||
{
|
||||
// The worker reads the plugins, so it stops first.
|
||||
reference_graph_worker_.reset();
|
||||
while (plugins_.size() > 0)
|
||||
{
|
||||
plugins_.pop_back();
|
||||
@@ -94,9 +212,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,23 +243,57 @@ namespace robot_costmap_2d
|
||||
|
||||
minx_ = miny_ = 1e30;
|
||||
maxx_ = maxy_ = -1e30;
|
||||
for (vector<boost::shared_ptr<Layer>>::iterator plugin = plugins_.begin(); plugin != plugins_.end();
|
||||
++plugin)
|
||||
if (performance_metrics_enabled_ && layer_performance_.size() != plugins_.size())
|
||||
layer_performance_.assign(plugins_.size(), LayerPerformance());
|
||||
|
||||
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)
|
||||
{
|
||||
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,15 +307,43 @@ namespace robot_costmap_2d
|
||||
yn = std::min(int(costmap_.getSizeInCellsY()), yn + 1);
|
||||
|
||||
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;
|
||||
@@ -158,6 +352,124 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
DirectionFieldSnapshot LayeredCostmap::getDirectionFieldSnapshot() const
|
||||
{
|
||||
DirectionFieldSnapshot result;
|
||||
unsigned int count = 0;
|
||||
for (const auto& plugin : plugins_)
|
||||
{
|
||||
if (!plugin->isEnabled()) continue;
|
||||
const auto* provider = dynamic_cast<const DirectionFieldProvider*>(plugin.get());
|
||||
if (!provider) continue;
|
||||
result = provider->directionSnapshot();
|
||||
if (++count > 1)
|
||||
{
|
||||
robot::log_error("Multiple enabled direction field providers; refusing direction queries");
|
||||
return {DirectionFieldState::kPending, {}, 0};
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool LayeredCostmap::enableReferenceGraph(const ReferenceGraphParams& params)
|
||||
{
|
||||
if (rolling_window_)
|
||||
{
|
||||
robot::log_error("Reference graph needs a static map; it cannot run on a rolling costmap\n");
|
||||
return false;
|
||||
}
|
||||
if (reference_graph_worker_)
|
||||
{
|
||||
robot::log_error("Reference graph is already enabled\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
ReferenceGraphWorker::Source source;
|
||||
source.capture = [this](bool with_grid, ReferenceGraphInput* input) {
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*costmap_.getMutex());
|
||||
input->geometry = {costmap_.getSizeInCellsX(), costmap_.getSizeInCellsY(), costmap_.getResolution(),
|
||||
costmap_.getOriginX(), costmap_.getOriginY(), global_frame_};
|
||||
input->footprint = footprint_;
|
||||
if (!with_grid)
|
||||
return ReferenceCaptureStatus::kReady;
|
||||
|
||||
// Copy under the lock and merge outside it: a large map must not stall the costmap update.
|
||||
std::vector<const Costmap2D*> grids;
|
||||
for (const auto& plugin : plugins_)
|
||||
{
|
||||
if (!plugin->isEnabled() || plugin->getType() != LayerType::STATIC_LAYER)
|
||||
continue;
|
||||
const auto* grid = dynamic_cast<const Costmap2D*>(plugin.get());
|
||||
if (grid == nullptr || !plugin->isCurrent() || grid->getSizeInCellsX() != costmap_.getSizeInCellsX() ||
|
||||
grid->getSizeInCellsY() != costmap_.getSizeInCellsY())
|
||||
return ReferenceCaptureStatus::kWait;
|
||||
grids.push_back(grid);
|
||||
}
|
||||
if (grids.empty())
|
||||
return ReferenceCaptureStatus::kNoStaticLayer;
|
||||
const std::size_t cells = static_cast<std::size_t>(costmap_.getSizeInCellsX()) * costmap_.getSizeInCellsY();
|
||||
if (cells == 0)
|
||||
return ReferenceCaptureStatus::kWait;
|
||||
input->static_layers.reserve(grids.size());
|
||||
for (const Costmap2D* grid : grids)
|
||||
input->static_layers.emplace_back(grid->getCharMap(), grid->getCharMap() + cells);
|
||||
return ReferenceCaptureStatus::kReady;
|
||||
};
|
||||
source.direction = [this]() { return getDirectionFieldSnapshot(); };
|
||||
try
|
||||
{
|
||||
reference_graph_worker_.reset(new ReferenceGraphWorker(std::move(source), params));
|
||||
}
|
||||
catch (const std::exception& error)
|
||||
{
|
||||
robot::log_error("Reference graph not started: %s\n", error.what());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ReferenceGraphSnapshot LayeredCostmap::getReferenceGraphSnapshot() const
|
||||
{
|
||||
return reference_graph_worker_ ? reference_graph_worker_->snapshot() : ReferenceGraphSnapshot{};
|
||||
}
|
||||
|
||||
static_assert(static_cast<std::size_t>(LayerType::DEPTH_CAMERA_LAYER) < 16, "grow kMaxLayerTypes");
|
||||
|
||||
uint64_t LayeredCostmap::getStaticMapRevision(LayerType type) const
|
||||
{
|
||||
return static_map_revisions_[static_cast<std::size_t>(type)].load();
|
||||
}
|
||||
|
||||
void LayeredCostmap::notifyStaticMapChanged(LayerType type)
|
||||
{
|
||||
++static_map_revisions_[static_cast<std::size_t>(type)];
|
||||
if (type == LayerType::STATIC_LAYER && reference_graph_worker_)
|
||||
reference_graph_worker_->notifyStaticChanged();
|
||||
}
|
||||
|
||||
void LayeredCostmap::notifyDirectionFieldChanged()
|
||||
{
|
||||
if (reference_graph_worker_)
|
||||
reference_graph_worker_->notifyDirectionChanged();
|
||||
}
|
||||
|
||||
bool LayeredCostmap::isCurrent()
|
||||
@@ -174,7 +486,16 @@ namespace robot_costmap_2d
|
||||
|
||||
void LayeredCostmap::setFootprint(const std::vector<robot_geometry_msgs::Point> &footprint_spec)
|
||||
{
|
||||
footprint_ = footprint_spec;
|
||||
bool changed = footprint_.size() != footprint_spec.size();
|
||||
for (std::size_t i = 0; !changed && i < footprint_.size(); ++i)
|
||||
changed = footprint_[i].x != footprint_spec[i].x || footprint_[i].y != footprint_spec[i].y;
|
||||
{
|
||||
// The reference graph thread copies the footprint under this lock.
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*costmap_.getMutex());
|
||||
footprint_ = footprint_spec;
|
||||
}
|
||||
if (changed && reference_graph_worker_)
|
||||
reference_graph_worker_->notifyFootprintChanged();
|
||||
robot_costmap_2d::calculateMinAndMaxDistances(footprint_spec, inscribed_radius_, circumscribed_radius_);
|
||||
|
||||
for (vector<boost::shared_ptr<Layer>>::iterator plugin = plugins_.begin(); plugin != plugins_.end();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
979
src/reference_graph.cpp
Normal file
979
src/reference_graph.cpp
Normal file
@@ -0,0 +1,979 @@
|
||||
#include <robot_costmap_2d/reference_graph.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
// Lane scan constants of the prototype. They are geometry of the search, not robot tuning, so they
|
||||
// stay out of YAML. A direction grid finer than 5 cm would need a smaller sample step.
|
||||
constexpr double kLaneScanStepM = 0.1;
|
||||
constexpr double kLaneSampleStepM = 0.05;
|
||||
constexpr double kLaneMatchToleranceM = 0.12;
|
||||
constexpr double kLaneMinLengthM = 0.3;
|
||||
constexpr double kLaneSameEntryM = 0.02;
|
||||
constexpr int kMaxSpurRounds = 20;
|
||||
constexpr int kKeepEveryCells = 5; // 0.25 m at 5 cm, enough for the route search.
|
||||
constexpr double kPi = 3.141592653589793;
|
||||
constexpr uint16_t kMaxClearanceMm = 65535;
|
||||
|
||||
bool cancelled(const std::atomic<bool>* cancel)
|
||||
{
|
||||
return cancel != nullptr && cancel->load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void checkGeometry(const DirectionGeometry& geometry)
|
||||
{
|
||||
if (geometry.width == 0 || geometry.height == 0 || !std::isfinite(geometry.resolution) || geometry.resolution <= 0.0 ||
|
||||
!std::isfinite(geometry.origin_x) || !std::isfinite(geometry.origin_y))
|
||||
throw std::invalid_argument("reference_graph: invalid grid geometry");
|
||||
// Cell indices are int32_t in this file, with a one-cell padding on each side.
|
||||
const uint64_t padded = (static_cast<uint64_t>(geometry.width) + 2) * (static_cast<uint64_t>(geometry.height) + 2);
|
||||
if (padded > static_cast<uint64_t>(std::numeric_limits<int32_t>::max()))
|
||||
throw std::invalid_argument("reference_graph: grid too large");
|
||||
}
|
||||
|
||||
void checkParams(const ReferenceGraphParams& params)
|
||||
{
|
||||
const std::string error = validateReferenceGraphParams(params);
|
||||
if (!error.empty())
|
||||
throw std::invalid_argument("reference_graph: " + error);
|
||||
}
|
||||
|
||||
/** Binary grid with a one-cell empty border, so neighbour lookups need no bounds checks. */
|
||||
class PaddedMask
|
||||
{
|
||||
public:
|
||||
PaddedMask(int32_t width, int32_t height)
|
||||
: width_(width), height_(height), stride_(width + 2),
|
||||
cells_(static_cast<std::size_t>(width + 2) * static_cast<std::size_t>(height + 2), 0)
|
||||
{
|
||||
}
|
||||
|
||||
int32_t index(int32_t x, int32_t y) const { return (y + 1) * stride_ + x + 1; }
|
||||
int32_t x(int32_t padded) const { return padded % stride_ - 1; }
|
||||
int32_t y(int32_t padded) const { return padded / stride_ - 1; }
|
||||
int32_t stride() const { return stride_; }
|
||||
int32_t width() const { return width_; }
|
||||
int32_t height() const { return height_; }
|
||||
std::size_t size() const { return cells_.size(); }
|
||||
uint8_t& operator[](int32_t padded) { return cells_[static_cast<std::size_t>(padded)]; }
|
||||
uint8_t operator[](int32_t padded) const { return cells_[static_cast<std::size_t>(padded)]; }
|
||||
|
||||
private:
|
||||
int32_t width_, height_, stride_;
|
||||
std::vector<uint8_t> cells_;
|
||||
};
|
||||
|
||||
/** Skeleton neighbours. A diagonal step is skipped when a 4-connected path already links the two cells. */
|
||||
int skeletonNeighbours(const PaddedMask& mask, int32_t cell, int32_t out[8])
|
||||
{
|
||||
const int32_t stride = mask.stride();
|
||||
int count = 0;
|
||||
for (int dy = -1; dy <= 1; ++dy)
|
||||
{
|
||||
for (int dx = -1; dx <= 1; ++dx)
|
||||
{
|
||||
if (dx == 0 && dy == 0)
|
||||
continue;
|
||||
const int32_t other = cell + dy * stride + dx;
|
||||
if (mask[other] == 0)
|
||||
continue;
|
||||
if (dx != 0 && dy != 0 && (mask[cell + dx] != 0 || mask[cell + dy * stride] != 0))
|
||||
continue;
|
||||
out[count++] = other;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Nearest feature cell per grid cell, as row-major index, -1 when the grid has no feature.
|
||||
*
|
||||
* Same tie-breaking as scipy.ndimage.distance_transform_edt, which the ridge test is sensitive to:
|
||||
* the lower row wins in the column pass, the lower column in the row pass.
|
||||
* @return False when cancelled. */
|
||||
template <typename IsFeature>
|
||||
bool nearestFeature(int32_t width, int32_t height, IsFeature is_feature, std::vector<int32_t>* nearest,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
nearest->assign(static_cast<std::size_t>(width) * static_cast<std::size_t>(height), -1);
|
||||
std::vector<int32_t>& result = *nearest;
|
||||
|
||||
// Column pass, walked row by row to stay cache friendly on a 3000 x 3000 grid. Holds the feature row.
|
||||
std::vector<int32_t> column_feature(static_cast<std::size_t>(width), -1);
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (is_feature(y * width + x))
|
||||
column_feature[static_cast<std::size_t>(x)] = y;
|
||||
row[x] = column_feature[static_cast<std::size_t>(x)];
|
||||
}
|
||||
}
|
||||
std::fill(column_feature.begin(), column_feature.end(), -1);
|
||||
for (int32_t y = height - 1; y >= 0; --y)
|
||||
{
|
||||
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (is_feature(y * width + x))
|
||||
column_feature[static_cast<std::size_t>(x)] = y;
|
||||
const int32_t below = column_feature[static_cast<std::size_t>(x)];
|
||||
if (below >= 0 && (row[x] < 0 || below - y < y - row[x]))
|
||||
row[x] = below;
|
||||
}
|
||||
}
|
||||
|
||||
// Row pass: lower envelope of the column results, as in Maurer's linear-time transform.
|
||||
std::vector<int32_t> feature_row(static_cast<std::size_t>(width));
|
||||
std::vector<int32_t> envelope(static_cast<std::size_t>(width));
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
|
||||
std::copy(row, row + width, feature_row.begin());
|
||||
const auto squared_row = [&](int32_t x) {
|
||||
const double dy = feature_row[static_cast<std::size_t>(x)] - y;
|
||||
return dy * dy;
|
||||
};
|
||||
int32_t last = -1;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (feature_row[static_cast<std::size_t>(x)] < 0)
|
||||
continue;
|
||||
const double new_row = squared_row(x);
|
||||
while (last >= 1)
|
||||
{
|
||||
const int32_t middle = envelope[static_cast<std::size_t>(last)];
|
||||
const int32_t before = envelope[static_cast<std::size_t>(last - 1)];
|
||||
const double a = middle - before;
|
||||
const double b = x - middle;
|
||||
const double c = a + b;
|
||||
if (c * squared_row(middle) - b * squared_row(before) - a * new_row - a * b * c <= 0.0)
|
||||
break;
|
||||
--last;
|
||||
}
|
||||
envelope[static_cast<std::size_t>(++last)] = x;
|
||||
}
|
||||
if (last < 0)
|
||||
continue;
|
||||
int32_t current = 0;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
const auto squared_distance = [&](int32_t slot) {
|
||||
const int32_t column = envelope[static_cast<std::size_t>(slot)];
|
||||
const double dx = column - x;
|
||||
return squared_row(column) + dx * dx;
|
||||
};
|
||||
double best = squared_distance(current);
|
||||
while (current < last)
|
||||
{
|
||||
const double next = squared_distance(current + 1);
|
||||
if (best <= next)
|
||||
break;
|
||||
best = next;
|
||||
++current;
|
||||
}
|
||||
const int32_t column = envelope[static_cast<std::size_t>(current)];
|
||||
row[x] = feature_row[static_cast<std::size_t>(column)] * width + column;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Zhang-Suen thinning. Only ridge cells are visited, so the cost follows the ridge size and not the map size.
|
||||
* A cell is re-tested in a phase only after a neighbour changed, since the test depends on nothing else.
|
||||
* @return False when cancelled. */
|
||||
bool thinSkeleton(PaddedMask* mask_ptr, std::vector<int32_t>* active, const std::atomic<bool>* cancel)
|
||||
{
|
||||
PaddedMask& mask = *mask_ptr;
|
||||
const int32_t stride = mask.stride();
|
||||
const int32_t offsets[8] = { -stride, -stride + 1, 1, stride + 1, stride, stride - 1, -1, -stride - 1 };
|
||||
std::vector<uint8_t> pending(mask.size(), 0);
|
||||
for (int32_t cell : *active)
|
||||
pending[static_cast<std::size_t>(cell)] = 3;
|
||||
|
||||
std::vector<int32_t> removal;
|
||||
while (true)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
bool changed = false;
|
||||
for (int phase = 0; phase < 2; ++phase)
|
||||
{
|
||||
const uint8_t bit = static_cast<uint8_t>(1U << phase);
|
||||
removal.clear();
|
||||
for (int32_t cell : *active)
|
||||
{
|
||||
uint8_t& flags = pending[static_cast<std::size_t>(cell)];
|
||||
if ((flags & bit) == 0 || mask[cell] == 0)
|
||||
continue;
|
||||
flags = static_cast<uint8_t>(flags & ~bit);
|
||||
const uint8_t n = mask[cell + offsets[0]], ne = mask[cell + offsets[1]], e = mask[cell + offsets[2]],
|
||||
se = mask[cell + offsets[3]], s = mask[cell + offsets[4]], sw = mask[cell + offsets[5]],
|
||||
w = mask[cell + offsets[6]], nw = mask[cell + offsets[7]];
|
||||
const int count = n + ne + e + se + s + sw + w + nw;
|
||||
if (count < 2 || count > 6)
|
||||
continue;
|
||||
const uint8_t sequence[9] = { n, ne, e, se, s, sw, w, nw, n };
|
||||
int transitions = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
transitions += (sequence[i] == 0 && sequence[i + 1] != 0) ? 1 : 0;
|
||||
if (transitions != 1)
|
||||
continue;
|
||||
const bool extra = phase == 0 ? ((n == 0 || e == 0 || s == 0) && (e == 0 || s == 0 || w == 0)) :
|
||||
((n == 0 || e == 0 || w == 0) && (n == 0 || s == 0 || w == 0));
|
||||
if (extra)
|
||||
removal.push_back(cell);
|
||||
}
|
||||
for (int32_t cell : removal)
|
||||
{
|
||||
mask[cell] = 0;
|
||||
for (int32_t offset : offsets)
|
||||
pending[static_cast<std::size_t>(cell + offset)] = 3;
|
||||
}
|
||||
changed = changed || !removal.empty();
|
||||
}
|
||||
active->erase(std::remove_if(active->begin(), active->end(), [&](int32_t cell) { return mask[cell] == 0; }),
|
||||
active->end());
|
||||
if (!changed)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove terminal branches shorter than `minimum` [m] that end on a junction. An isolated line stays.
|
||||
* @return False when cancelled. */
|
||||
bool pruneSpurs(PaddedMask* mask_ptr, std::vector<int32_t>* pixels, double resolution, double minimum,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
PaddedMask& mask = *mask_ptr;
|
||||
const int32_t stride = mask.stride();
|
||||
const double diagonal = std::hypot(1.0, 1.0);
|
||||
std::vector<int32_t> path;
|
||||
std::vector<int32_t> doomed;
|
||||
for (int round = 0; round < kMaxSpurRounds; ++round)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return false;
|
||||
doomed.clear();
|
||||
int32_t around[8];
|
||||
for (int32_t start : *pixels)
|
||||
{
|
||||
if (skeletonNeighbours(mask, start, around) != 1)
|
||||
continue;
|
||||
path.assign(1, start);
|
||||
int32_t previous = -1;
|
||||
int32_t current = start;
|
||||
double length = 0.0;
|
||||
int degree = 1;
|
||||
while (true)
|
||||
{
|
||||
int32_t next = -1;
|
||||
int others = 0;
|
||||
degree = skeletonNeighbours(mask, current, around);
|
||||
for (int i = 0; i < degree; ++i)
|
||||
{
|
||||
if (around[i] != previous)
|
||||
{
|
||||
next = around[i];
|
||||
++others;
|
||||
}
|
||||
}
|
||||
if (others != 1)
|
||||
break;
|
||||
const int32_t step = next - current;
|
||||
const bool straight = step == 1 || step == -1 || step == stride || step == -stride;
|
||||
length += resolution * (straight ? 1.0 : diagonal);
|
||||
previous = current;
|
||||
current = next;
|
||||
degree = skeletonNeighbours(mask, current, around);
|
||||
if (degree != 2)
|
||||
break;
|
||||
path.push_back(current);
|
||||
if (length >= minimum)
|
||||
break;
|
||||
}
|
||||
if (length < minimum && degree > 2)
|
||||
doomed.insert(doomed.end(), path.begin(), path.end());
|
||||
}
|
||||
if (doomed.empty())
|
||||
break;
|
||||
for (int32_t cell : doomed)
|
||||
mask[cell] = 0;
|
||||
pixels->erase(std::remove_if(pixels->begin(), pixels->end(), [&](int32_t cell) { return mask[cell] == 0; }),
|
||||
pixels->end());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
uint64_t linkKey(int32_t a, int32_t b)
|
||||
{
|
||||
const uint32_t low = static_cast<uint32_t>(std::min(a, b));
|
||||
const uint32_t high = static_cast<uint32_t>(std::max(a, b));
|
||||
return (static_cast<uint64_t>(high) << 32) | low;
|
||||
}
|
||||
|
||||
/** Rectangle against lethal and unknown cell squares, separating-axis test. Centre cell must also be free. */
|
||||
bool footprintFree(const uint8_t* cost, const DirectionGeometry& geometry, double x, double y, double c, double s,
|
||||
double half_x, double half_y)
|
||||
{
|
||||
const double resolution = geometry.resolution;
|
||||
const double abs_c = std::abs(c);
|
||||
const double abs_s = std::abs(s);
|
||||
const double reach_x = half_x * abs_c + half_y * abs_s;
|
||||
const double reach_y = half_x * abs_s + half_y * abs_c;
|
||||
const double x0 = std::floor((x - reach_x - geometry.origin_x) / resolution);
|
||||
const double x1 = std::floor((x + reach_x - geometry.origin_x) / resolution);
|
||||
const double y0 = std::floor((y - reach_y - geometry.origin_y) / resolution);
|
||||
const double y1 = std::floor((y + reach_y - geometry.origin_y) / resolution);
|
||||
if (x0 < 0.0 || y0 < 0.0 || x1 >= geometry.width || y1 >= geometry.height)
|
||||
return false;
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t centre_x = static_cast<int32_t>(std::floor((x - geometry.origin_x) / resolution));
|
||||
const int32_t centre_y = static_cast<int32_t>(std::floor((y - geometry.origin_y) / resolution));
|
||||
if (cost[centre_y * width + centre_x] >= INSCRIBED_INFLATED_OBSTACLE)
|
||||
return false;
|
||||
const double half_cell = resolution / 2.0;
|
||||
const double projected = half_cell * (abs_c + abs_s);
|
||||
for (int32_t iy = static_cast<int32_t>(y0); iy <= static_cast<int32_t>(y1); ++iy)
|
||||
{
|
||||
const uint8_t* row = cost + static_cast<std::ptrdiff_t>(iy) * width;
|
||||
for (int32_t ix = static_cast<int32_t>(x0); ix <= static_cast<int32_t>(x1); ++ix)
|
||||
{
|
||||
if (row[ix] != LETHAL_OBSTACLE && row[ix] != NO_INFORMATION)
|
||||
continue;
|
||||
const double dx = geometry.origin_x + (ix + 0.5) * resolution - x;
|
||||
const double dy = geometry.origin_y + (iy + 0.5) * resolution - y;
|
||||
if (std::abs(dx) <= reach_x + half_cell && std::abs(dy) <= reach_y + half_cell &&
|
||||
std::abs(c * dx + s * dy) <= half_x + projected && std::abs(-s * dx + c * dy) <= half_y + projected)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct LaneCandidate
|
||||
{
|
||||
ReferencePoint entry, exit;
|
||||
double lateral;
|
||||
double length;
|
||||
};
|
||||
|
||||
struct ZoneRegion
|
||||
{
|
||||
uint8_t direction_index;
|
||||
int32_t label;
|
||||
std::vector<int32_t> cells;
|
||||
};
|
||||
|
||||
/** 8-connected regions of equal nonzero code, ordered by direction, then by first cell in raster order. */
|
||||
std::vector<ZoneRegion> findZoneRegions(const uint8_t* codes, int32_t width, int32_t height, std::vector<int32_t>* labels)
|
||||
{
|
||||
labels->assign(static_cast<std::size_t>(width) * static_cast<std::size_t>(height), 0);
|
||||
std::vector<ZoneRegion> regions;
|
||||
std::vector<int32_t> stack;
|
||||
int32_t next_label = 0;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
const int32_t seed = y * width + x;
|
||||
const uint8_t code = codes[seed];
|
||||
if (code == 0 || code > 8 || (*labels)[static_cast<std::size_t>(seed)] != 0)
|
||||
continue;
|
||||
ZoneRegion region;
|
||||
region.direction_index = static_cast<uint8_t>(code - 1);
|
||||
region.label = ++next_label;
|
||||
(*labels)[static_cast<std::size_t>(seed)] = region.label;
|
||||
stack.assign(1, seed);
|
||||
while (!stack.empty())
|
||||
{
|
||||
const int32_t cell = stack.back();
|
||||
stack.pop_back();
|
||||
region.cells.push_back(cell);
|
||||
const int32_t cx = cell % width;
|
||||
const int32_t cy = cell / width;
|
||||
for (int32_t ny = std::max(cy - 1, 0); ny <= std::min(cy + 1, height - 1); ++ny)
|
||||
{
|
||||
for (int32_t nx = std::max(cx - 1, 0); nx <= std::min(cx + 1, width - 1); ++nx)
|
||||
{
|
||||
const int32_t other = ny * width + nx;
|
||||
if (codes[other] == code && (*labels)[static_cast<std::size_t>(other)] == 0)
|
||||
{
|
||||
(*labels)[static_cast<std::size_t>(other)] = region.label;
|
||||
stack.push_back(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
regions.push_back(std::move(region));
|
||||
}
|
||||
}
|
||||
std::stable_sort(regions.begin(), regions.end(), [](const ZoneRegion& a, const ZoneRegion& b) {
|
||||
return a.direction_index < b.direction_index;
|
||||
});
|
||||
return regions;
|
||||
}
|
||||
|
||||
/** Candidate lanes of one region: free stretches along the zone direction, at each lateral offset.
|
||||
* Fills `preferred_lateral` with the main lane's offset. */
|
||||
std::vector<LaneCandidate> compileRegionLanes(const ZoneRegion& region, const std::vector<int32_t>& labels,
|
||||
const uint8_t* cost, const DirectionGeometry& geometry, double half_x,
|
||||
double half_y, double offset_step, double* preferred_lateral)
|
||||
{
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(geometry.height);
|
||||
const double resolution = geometry.resolution;
|
||||
const double yaw = region.direction_index * kPi / 4.0;
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
|
||||
double lateral_min = std::numeric_limits<double>::infinity();
|
||||
double lateral_max = -lateral_min;
|
||||
double along_min = lateral_min;
|
||||
double along_max = -lateral_min;
|
||||
for (int32_t cell : region.cells)
|
||||
{
|
||||
const double x = geometry.origin_x + (cell % width + 0.5) * resolution;
|
||||
const double y = geometry.origin_y + (cell / width + 0.5) * resolution;
|
||||
const double along = x * c + y * s;
|
||||
const double lateral = -x * s + y * c;
|
||||
along_min = std::min(along_min, along);
|
||||
along_max = std::max(along_max, along);
|
||||
lateral_min = std::min(lateral_min, lateral);
|
||||
lateral_max = std::max(lateral_max, lateral);
|
||||
}
|
||||
const double pad = resolution * 0.5 * (std::abs(c) + std::abs(s));
|
||||
const double lo = lateral_min - pad;
|
||||
const double hi = lateral_max + pad;
|
||||
const double along_lo = along_min - pad;
|
||||
const double along_hi = along_max + pad;
|
||||
const double middle = (lo + hi) / 2.0;
|
||||
const double section = (along_lo + along_hi) / 2.0;
|
||||
|
||||
const auto usable = [&](double t, double v) {
|
||||
const double wx = t * c - v * s;
|
||||
const double wy = t * s + v * c;
|
||||
const double fx = std::floor((wx - geometry.origin_x) / resolution);
|
||||
const double fy = std::floor((wy - geometry.origin_y) / resolution);
|
||||
if (fx < 0.0 || fy < 0.0 || fx >= width || fy >= height)
|
||||
return false;
|
||||
const int32_t cell = static_cast<int32_t>(fy) * width + static_cast<int32_t>(fx);
|
||||
return labels[static_cast<std::size_t>(cell)] == region.label &&
|
||||
footprintFree(cost, geometry, wx, wy, c, s, half_x, half_y);
|
||||
};
|
||||
|
||||
// Offsets across the mid section, spaced like numpy.arange so the values match the prototype.
|
||||
std::vector<double> scan;
|
||||
const double scan_start = lo + kLaneScanStepM / 2.0;
|
||||
const double scan_delta = (scan_start + kLaneScanStepM) - scan_start;
|
||||
const double scan_count = std::ceil((hi - scan_start) / kLaneScanStepM);
|
||||
for (int64_t i = 0; i < static_cast<int64_t>(scan_count); ++i)
|
||||
scan.push_back(i == 1 ? scan_start + kLaneScanStepM : scan_start + static_cast<double>(i) * scan_delta);
|
||||
|
||||
std::vector<std::pair<double, double>> spans;
|
||||
int64_t begin = -1;
|
||||
for (std::size_t i = 0; i <= scan.size(); ++i)
|
||||
{
|
||||
const bool free = i < scan.size() && usable(section, scan[i]);
|
||||
if (free && begin < 0)
|
||||
{
|
||||
begin = static_cast<int64_t>(i);
|
||||
}
|
||||
else if (!free && begin >= 0)
|
||||
{
|
||||
spans.emplace_back(scan[static_cast<std::size_t>(begin)], scan[i - 1]);
|
||||
begin = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// The zone centre may be blocked. The main lane then moves to the free span closest to the centre.
|
||||
double preferred = middle;
|
||||
bool centre_free = spans.empty();
|
||||
for (const auto& span : spans)
|
||||
centre_free = centre_free || (span.first - kLaneScanStepM / 2.0 <= middle && middle <= span.second + kLaneScanStepM / 2.0);
|
||||
if (!centre_free)
|
||||
{
|
||||
double best = std::numeric_limits<double>::infinity();
|
||||
for (const auto& span : spans)
|
||||
{
|
||||
const double distance = std::abs((span.first + span.second) / 2.0 - middle);
|
||||
if (distance < best)
|
||||
{
|
||||
best = distance;
|
||||
preferred = (span.first + span.second) / 2.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
*preferred_lateral = preferred;
|
||||
|
||||
std::set<double> offsets{ middle, preferred };
|
||||
for (int64_t k = 1; preferred - k * offset_step > lo || preferred + k * offset_step < hi; ++k)
|
||||
{
|
||||
if (preferred - k * offset_step > lo)
|
||||
offsets.insert(preferred - k * offset_step);
|
||||
if (preferred + k * offset_step < hi)
|
||||
offsets.insert(preferred + k * offset_step);
|
||||
}
|
||||
offsets.insert(scan.begin(), scan.end());
|
||||
|
||||
// numpy.linspace layout: the last sample is exactly along_hi.
|
||||
const int64_t samples =
|
||||
std::max<int64_t>(2, static_cast<int64_t>(std::ceil((along_hi - along_lo) / kLaneSampleStepM)) + 1);
|
||||
const double sample_delta = (along_hi - along_lo) / static_cast<double>(samples - 1);
|
||||
const auto sample = [&](int64_t i) {
|
||||
return i == samples - 1 ? along_hi : static_cast<double>(i) * sample_delta + along_lo;
|
||||
};
|
||||
|
||||
std::vector<LaneCandidate> lanes;
|
||||
for (double v : offsets)
|
||||
{
|
||||
int64_t start = -1;
|
||||
for (int64_t i = 0; i <= samples; ++i)
|
||||
{
|
||||
const bool free = i < samples && usable(sample(i), v);
|
||||
if (free && start < 0)
|
||||
{
|
||||
start = i;
|
||||
}
|
||||
else if (!free && start >= 0)
|
||||
{
|
||||
const int64_t end = i - 1;
|
||||
if (end > start)
|
||||
{
|
||||
const double t0 = sample(start);
|
||||
const double t1 = sample(end);
|
||||
LaneCandidate lane;
|
||||
lane.entry = { t0 * c - v * s, t0 * s + v * c };
|
||||
lane.exit = { t1 * c - v * s, t1 * s + v * c };
|
||||
lane.lateral = v;
|
||||
lane.length = t1 - t0;
|
||||
lanes.push_back(lane);
|
||||
}
|
||||
start = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return lanes;
|
||||
}
|
||||
|
||||
/** Keep the main lane and up to two lanes on each side. */
|
||||
void selectLanes(const ZoneRegion& region, uint32_t zone_id, const std::vector<LaneCandidate>& lanes, double middle,
|
||||
double offset_step, std::vector<ReferenceLane>* out)
|
||||
{
|
||||
if (lanes.empty())
|
||||
return;
|
||||
const std::size_t first_of_zone = out->size();
|
||||
const double targets[5] = { 0.0, -offset_step, offset_step, -2.0 * offset_step, 2.0 * offset_step };
|
||||
for (double target : targets)
|
||||
{
|
||||
const LaneCandidate* chosen = nullptr;
|
||||
double best_distance = std::numeric_limits<double>::infinity();
|
||||
for (const LaneCandidate& lane : lanes)
|
||||
{
|
||||
const double distance = std::abs(lane.lateral - (middle + target));
|
||||
if (chosen == nullptr || distance < best_distance || (distance == best_distance && lane.length > chosen->length))
|
||||
{
|
||||
chosen = &lane;
|
||||
best_distance = distance;
|
||||
}
|
||||
}
|
||||
if (best_distance > kLaneMatchToleranceM || chosen->length < kLaneMinLengthM)
|
||||
continue;
|
||||
bool duplicate = false;
|
||||
for (std::size_t i = first_of_zone; i < out->size(); ++i)
|
||||
{
|
||||
const ReferencePoint& entry = (*out)[i].entry;
|
||||
duplicate = duplicate || std::hypot(chosen->entry.x - entry.x, chosen->entry.y - entry.y) < kLaneSameEntryM;
|
||||
}
|
||||
if (duplicate)
|
||||
continue;
|
||||
ReferenceLane lane;
|
||||
lane.zone_id = zone_id;
|
||||
lane.direction_index = region.direction_index;
|
||||
lane.entry = chosen->entry;
|
||||
lane.exit = chosen->exit;
|
||||
lane.length_m = chosen->length;
|
||||
lane.offset_from_centre_m = std::abs(chosen->lateral - middle);
|
||||
out->push_back(lane);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string validateReferenceGraphParams(const ReferenceGraphParams& params)
|
||||
{
|
||||
std::ostringstream error;
|
||||
if (!std::isfinite(params.min_clearance_m) || params.min_clearance_m < 0.0)
|
||||
error << "min_clearance_m must be finite and >= 0, got " << params.min_clearance_m;
|
||||
else if (!std::isfinite(params.ridge_min_separation_m) || params.ridge_min_separation_m <= 0.0)
|
||||
error << "ridge_min_separation_m must be finite and > 0, got " << params.ridge_min_separation_m;
|
||||
else if (!std::isfinite(params.spur_min_length_m) || params.spur_min_length_m < 0.0)
|
||||
error << "spur_min_length_m must be finite and >= 0, got " << params.spur_min_length_m;
|
||||
else if (!std::isfinite(params.lane_offset_step_m) || params.lane_offset_step_m <= 0.0)
|
||||
error << "lane_offset_step_m must be finite and > 0, got " << params.lane_offset_step_m;
|
||||
return error.str();
|
||||
}
|
||||
|
||||
VoronoiSkeleton computeVoronoiSkeleton(const ReferenceGridView& grid, const ReferenceGraphParams& params,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
checkParams(params);
|
||||
checkGeometry(grid.geometry);
|
||||
if (grid.cost == nullptr)
|
||||
throw std::invalid_argument("reference_graph: null cost grid");
|
||||
|
||||
const int32_t width = static_cast<int32_t>(grid.geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(grid.geometry.height);
|
||||
const double resolution = grid.geometry.resolution;
|
||||
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
||||
const uint8_t* cost = grid.cost;
|
||||
|
||||
VoronoiSkeleton result;
|
||||
result.geometry = grid.geometry;
|
||||
|
||||
std::vector<int32_t> nearest;
|
||||
if (!nearestFeature(width, height, [cost](int32_t cell) { return cost[cell] == LETHAL_OBSTACLE; }, &nearest, cancel))
|
||||
return result;
|
||||
|
||||
std::vector<uint16_t> clearance_mm(cell_count, kMaxClearanceMm);
|
||||
// A supplied clearance is already rounded down to millimetres, so it is compared in millimetres.
|
||||
const int64_t supplied_threshold_mm = static_cast<int64_t>(std::ceil(params.min_clearance_m * 1000.0 - 1e-9));
|
||||
PaddedMask mask(width, height);
|
||||
std::vector<int32_t> ridge_cells;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return result;
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
const int32_t cell = y * width + x;
|
||||
const int32_t feature = nearest[static_cast<std::size_t>(cell)];
|
||||
bool clear_enough = feature >= 0;
|
||||
if (grid.clearance_mm != nullptr)
|
||||
{
|
||||
clearance_mm[static_cast<std::size_t>(cell)] = grid.clearance_mm[cell];
|
||||
clear_enough = clear_enough && grid.clearance_mm[cell] >= supplied_threshold_mm;
|
||||
}
|
||||
else if (feature >= 0)
|
||||
{
|
||||
const double dy = feature / width - y;
|
||||
const double dx = feature % width - x;
|
||||
const double metres = std::sqrt(dy * dy + dx * dx) * resolution;
|
||||
clearance_mm[static_cast<std::size_t>(cell)] =
|
||||
static_cast<uint16_t>(std::min(std::floor(metres * 1000.0), static_cast<double>(kMaxClearanceMm)));
|
||||
clear_enough = metres >= params.min_clearance_m;
|
||||
}
|
||||
if (!clear_enough || cost[cell] >= INSCRIBED_INFLATED_OBSTACLE)
|
||||
continue;
|
||||
|
||||
// A ridge cell has a neighbour whose nearest obstacle lies far from its own.
|
||||
const auto separated = [&](int32_t other) {
|
||||
const int32_t other_feature = nearest[static_cast<std::size_t>(other)];
|
||||
if (other_feature == feature)
|
||||
return false;
|
||||
const double fy = feature / width - other_feature / width;
|
||||
const double fx = feature % width - other_feature % width;
|
||||
return std::hypot(fy, fx) * resolution >= params.ridge_min_separation_m;
|
||||
};
|
||||
if ((x + 1 < width && separated(cell + 1)) || (y + 1 < height && separated(cell + width)))
|
||||
{
|
||||
const int32_t padded = mask.index(x, y);
|
||||
mask[padded] = 1;
|
||||
ridge_cells.push_back(padded);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<int32_t>().swap(nearest);
|
||||
|
||||
if (!thinSkeleton(&mask, &ridge_cells, cancel) ||
|
||||
!pruneSpurs(&mask, &ridge_cells, resolution, params.spur_min_length_m, cancel))
|
||||
return result;
|
||||
|
||||
result.mask.assign(cell_count, 0);
|
||||
for (int32_t padded : ridge_cells)
|
||||
result.mask[static_cast<std::size_t>(mask.y(padded)) * static_cast<std::size_t>(width) + static_cast<std::size_t>(mask.x(padded))] = 1;
|
||||
result.clearance_mm = std::move(clearance_mm);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> computeRegionCentreLine(const std::vector<uint8_t>& region_mask, const DirectionGeometry& geometry,
|
||||
const ReferenceGraphParams& params)
|
||||
{
|
||||
checkParams(params);
|
||||
checkGeometry(geometry);
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(geometry.height);
|
||||
if (region_mask.size() != static_cast<std::size_t>(width) * static_cast<std::size_t>(height))
|
||||
throw std::invalid_argument("reference_graph: region mask size does not match the geometry");
|
||||
|
||||
std::vector<uint8_t> result(region_mask.size(), 0);
|
||||
int32_t x_min = width, x_max = -1, y_min = height, y_max = -1;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (region_mask[static_cast<std::size_t>(y * width + x)] == 0)
|
||||
continue;
|
||||
x_min = std::min(x_min, x);
|
||||
x_max = std::max(x_max, x);
|
||||
y_min = std::min(y_min, y);
|
||||
y_max = std::max(y_max, y);
|
||||
}
|
||||
}
|
||||
if (x_max < 0)
|
||||
return result;
|
||||
|
||||
// Two cells of margin so the region always has an outside to measure from.
|
||||
const int32_t crop_x = std::max(0, x_min - 2);
|
||||
const int32_t crop_y = std::max(0, y_min - 2);
|
||||
const int32_t crop_width = std::min(width, x_max + 3) - crop_x;
|
||||
const int32_t crop_height = std::min(height, y_max + 3) - crop_y;
|
||||
std::vector<uint8_t> crop(static_cast<std::size_t>(crop_width) * static_cast<std::size_t>(crop_height), 0);
|
||||
for (int32_t y = 0; y < crop_height; ++y)
|
||||
for (int32_t x = 0; x < crop_width; ++x)
|
||||
crop[static_cast<std::size_t>(y * crop_width + x)] =
|
||||
region_mask[static_cast<std::size_t>((y + crop_y) * width + x + crop_x)] != 0 ? 1 : 0;
|
||||
|
||||
std::vector<int32_t> nearest;
|
||||
nearestFeature(crop_width, crop_height, [&crop](int32_t cell) { return crop[static_cast<std::size_t>(cell)] == 0; },
|
||||
&nearest, nullptr);
|
||||
|
||||
// Two cells apart is the narrowest pair of boundary points that still has a centre.
|
||||
PaddedMask mask(crop_width, crop_height);
|
||||
std::vector<int32_t> cells;
|
||||
for (int32_t y = 0; y < crop_height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < crop_width; ++x)
|
||||
{
|
||||
const int32_t cell = y * crop_width + x;
|
||||
if (crop[static_cast<std::size_t>(cell)] == 0)
|
||||
continue;
|
||||
const int32_t feature = nearest[static_cast<std::size_t>(cell)];
|
||||
const auto separated = [&](int32_t other) {
|
||||
const int32_t other_feature = nearest[static_cast<std::size_t>(other)];
|
||||
const double fy = feature / crop_width - other_feature / crop_width;
|
||||
const double fx = feature % crop_width - other_feature % crop_width;
|
||||
return std::hypot(fy, fx) >= 2.0;
|
||||
};
|
||||
if (feature >= 0 && ((x + 1 < crop_width && separated(cell + 1)) || (y + 1 < crop_height && separated(cell + crop_width))))
|
||||
{
|
||||
const int32_t padded = mask.index(x, y);
|
||||
mask[padded] = 1;
|
||||
cells.push_back(padded);
|
||||
}
|
||||
}
|
||||
}
|
||||
thinSkeleton(&mask, &cells, nullptr);
|
||||
pruneSpurs(&mask, &cells, geometry.resolution, params.spur_min_length_m, nullptr);
|
||||
for (int32_t padded : cells)
|
||||
result[static_cast<std::size_t>((mask.y(padded) + crop_y) * width + mask.x(padded) + crop_x)] = 1;
|
||||
return result;
|
||||
}
|
||||
|
||||
void extractVoronoiEdges(const std::vector<uint8_t>& skeleton_mask, const uint8_t* direction_codes,
|
||||
const DirectionGeometry& geometry, const std::vector<uint16_t>* clearance_mm,
|
||||
std::vector<ReferencePoint>* nodes, std::vector<VoronoiEdge>* edges,
|
||||
const std::atomic<bool>* cancel)
|
||||
{
|
||||
checkGeometry(geometry);
|
||||
if (nodes == nullptr || edges == nullptr)
|
||||
throw std::invalid_argument("reference_graph: null output");
|
||||
const int32_t width = static_cast<int32_t>(geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(geometry.height);
|
||||
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
||||
if (skeleton_mask.size() != cell_count || (clearance_mm != nullptr && clearance_mm->size() != cell_count))
|
||||
throw std::invalid_argument("reference_graph: skeleton size does not match the geometry");
|
||||
nodes->clear();
|
||||
edges->clear();
|
||||
|
||||
PaddedMask mask(width, height);
|
||||
std::vector<int32_t> pixels;
|
||||
for (int32_t y = 0; y < height; ++y)
|
||||
{
|
||||
for (int32_t x = 0; x < width; ++x)
|
||||
{
|
||||
if (skeleton_mask[static_cast<std::size_t>(y * width + x)] != 0)
|
||||
{
|
||||
const int32_t padded = mask.index(x, y);
|
||||
mask[padded] = 1;
|
||||
pixels.push_back(padded);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto code_at = [&](int32_t padded) -> uint8_t {
|
||||
return direction_codes == nullptr ? 0 : direction_codes[mask.y(padded) * width + mask.x(padded)];
|
||||
};
|
||||
|
||||
// Node cells: anything but a plain chain link, and both sides of a zone boundary.
|
||||
PaddedMask critical(width, height);
|
||||
std::vector<int32_t> critical_cells;
|
||||
int32_t around[8];
|
||||
for (int32_t cell : pixels)
|
||||
{
|
||||
const int degree = skeletonNeighbours(mask, cell, around);
|
||||
bool is_critical = degree != 2;
|
||||
for (int i = 0; i < degree && !is_critical; ++i)
|
||||
is_critical = code_at(cell) != code_at(around[i]);
|
||||
if (is_critical)
|
||||
{
|
||||
critical[cell] = 1;
|
||||
critical_cells.push_back(cell);
|
||||
}
|
||||
}
|
||||
|
||||
const auto world = [&](int32_t padded) -> ReferencePoint {
|
||||
return { geometry.origin_x + (mask.x(padded) + 0.5) * geometry.resolution,
|
||||
geometry.origin_y + (mask.y(padded) + 0.5) * geometry.resolution };
|
||||
};
|
||||
std::unordered_map<int32_t, uint32_t> node_of;
|
||||
const auto node_index = [&](int32_t padded) {
|
||||
const auto inserted = node_of.emplace(padded, static_cast<uint32_t>(nodes->size()));
|
||||
if (inserted.second)
|
||||
nodes->push_back(world(padded));
|
||||
return inserted.first->second;
|
||||
};
|
||||
|
||||
std::unordered_set<uint64_t> visited;
|
||||
visited.reserve(pixels.size() * 2);
|
||||
std::vector<int32_t> chain;
|
||||
for (int32_t start : critical_cells)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
{
|
||||
nodes->clear();
|
||||
edges->clear();
|
||||
return;
|
||||
}
|
||||
int32_t first_steps[8];
|
||||
const int first_count = skeletonNeighbours(mask, start, first_steps);
|
||||
for (int i = 0; i < first_count; ++i)
|
||||
{
|
||||
if (!visited.insert(linkKey(start, first_steps[i])).second)
|
||||
continue;
|
||||
chain.assign({ start, first_steps[i] });
|
||||
int32_t previous = start;
|
||||
int32_t current = first_steps[i];
|
||||
// Every non-critical cell has exactly two neighbours, so the walk always ends on a critical cell.
|
||||
while (critical[current] == 0)
|
||||
{
|
||||
const int degree = skeletonNeighbours(mask, current, around);
|
||||
int32_t next = around[0] != previous ? around[0] : around[degree - 1];
|
||||
visited.insert(linkKey(current, next));
|
||||
chain.push_back(next);
|
||||
previous = current;
|
||||
current = next;
|
||||
}
|
||||
if (current == start)
|
||||
continue;
|
||||
|
||||
VoronoiEdge edge;
|
||||
edge.from = node_index(start);
|
||||
edge.to = node_index(current);
|
||||
edge.min_clearance_m = std::numeric_limits<double>::infinity();
|
||||
edge.length_m = 0.0;
|
||||
for (std::size_t k = 0; k < chain.size(); k += kKeepEveryCells)
|
||||
edge.points.push_back(world(chain[k]));
|
||||
if ((chain.size() - 1) % kKeepEveryCells != 0)
|
||||
edge.points.push_back(world(chain.back()));
|
||||
for (std::size_t k = 0; k < edge.points.size(); ++k)
|
||||
{
|
||||
if (k > 0)
|
||||
edge.length_m += std::hypot(edge.points[k].x - edge.points[k - 1].x, edge.points[k].y - edge.points[k - 1].y);
|
||||
}
|
||||
if (clearance_mm != nullptr)
|
||||
{
|
||||
for (std::size_t k = 0; k < chain.size(); ++k)
|
||||
{
|
||||
if (k % kKeepEveryCells != 0 && k + 1 != chain.size())
|
||||
continue;
|
||||
const std::size_t cell = static_cast<std::size_t>(mask.y(chain[k])) * static_cast<std::size_t>(width) +
|
||||
static_cast<std::size_t>(mask.x(chain[k]));
|
||||
edge.min_clearance_m = std::min(edge.min_clearance_m, (*clearance_mm)[cell] / 1000.0);
|
||||
}
|
||||
}
|
||||
edges->push_back(std::move(edge));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ReferenceGraph buildReferenceGraph(const ReferenceGridView& grid, const VoronoiSkeleton& skeleton,
|
||||
const std::vector<robot_geometry_msgs::Point>& footprint,
|
||||
const ReferenceGraphParams& params, const std::atomic<bool>* cancel)
|
||||
{
|
||||
checkParams(params);
|
||||
checkGeometry(grid.geometry);
|
||||
if (grid.cost == nullptr)
|
||||
throw std::invalid_argument("reference_graph: null cost grid");
|
||||
const int32_t width = static_cast<int32_t>(grid.geometry.width);
|
||||
const int32_t height = static_cast<int32_t>(grid.geometry.height);
|
||||
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
||||
if (skeleton.mask.size() != cell_count || skeleton.clearance_mm.size() != cell_count)
|
||||
throw std::invalid_argument("reference_graph: skeleton size does not match the grid");
|
||||
|
||||
double half_x = 0.0;
|
||||
double half_y = 0.0;
|
||||
if (grid.direction_codes != nullptr)
|
||||
{
|
||||
if (footprint.size() < 3)
|
||||
throw std::invalid_argument("reference_graph: footprint needs at least 3 points");
|
||||
for (const robot_geometry_msgs::Point& point : footprint)
|
||||
{
|
||||
if (!std::isfinite(point.x) || !std::isfinite(point.y))
|
||||
throw std::invalid_argument("reference_graph: footprint holds a non-finite point");
|
||||
half_x = std::max(half_x, std::abs(point.x));
|
||||
half_y = std::max(half_y, std::abs(point.y));
|
||||
}
|
||||
if (half_x <= 0.0 || half_y <= 0.0)
|
||||
throw std::invalid_argument("reference_graph: footprint has no area");
|
||||
}
|
||||
|
||||
ReferenceGraph graph;
|
||||
graph.geometry = grid.geometry;
|
||||
graph.params = params;
|
||||
extractVoronoiEdges(skeleton.mask, grid.direction_codes, grid.geometry, &skeleton.clearance_mm, &graph.nodes,
|
||||
&graph.edges, cancel);
|
||||
if (cancelled(cancel))
|
||||
return ReferenceGraph{};
|
||||
|
||||
if (grid.direction_codes != nullptr)
|
||||
{
|
||||
std::vector<int32_t> labels;
|
||||
const std::vector<ZoneRegion> regions = findZoneRegions(grid.direction_codes, width, height, &labels);
|
||||
for (std::size_t i = 0; i < regions.size(); ++i)
|
||||
{
|
||||
if (cancelled(cancel))
|
||||
return ReferenceGraph{};
|
||||
if (regions[i].cells.size() < 2)
|
||||
continue;
|
||||
double preferred = 0.0;
|
||||
const std::vector<LaneCandidate> candidates =
|
||||
compileRegionLanes(regions[i], labels, grid.cost, grid.geometry, half_x, half_y, params.lane_offset_step_m, &preferred);
|
||||
selectLanes(regions[i], static_cast<uint32_t>(i), candidates, preferred, params.lane_offset_step_m, &graph.lanes);
|
||||
}
|
||||
}
|
||||
|
||||
graph.static_cost.assign(grid.cost, grid.cost + cell_count);
|
||||
graph.clearance_mm = skeleton.clearance_mm;
|
||||
return graph;
|
||||
}
|
||||
|
||||
} // namespace robot_costmap_2d
|
||||
297
src/reference_graph_worker.cpp
Normal file
297
src/reference_graph_worker.cpp
Normal file
@@ -0,0 +1,297 @@
|
||||
#include <robot_costmap_2d/reference_graph_worker.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#ifdef __linux__
|
||||
#include <sys/resource.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <robot/robot.h>
|
||||
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
// While an input is not ready the thread takes the master mutex this often. It sleeps for good once the graph is ready.
|
||||
constexpr std::chrono::milliseconds kRetryPeriod(200);
|
||||
// The NUC has 2 cores, and this thread must not take time from the control loop or the sensors.
|
||||
constexpr int kThreadNice = 10;
|
||||
|
||||
double msSince(Clock::time_point begin) { return std::chrono::duration<double, std::milli>(Clock::now() - begin).count(); }
|
||||
|
||||
void lowerThreadPriority()
|
||||
{
|
||||
#ifdef __linux__
|
||||
// Without this the graph still comes out, only the control loop may feel it, so a refusal is not an error.
|
||||
if (setpriority(PRIO_PROCESS, static_cast<id_t>(syscall(SYS_gettid)), kThreadNice) != 0)
|
||||
robot::log_warning("ReferenceGraphWorker: could not lower the thread priority\n");
|
||||
#endif
|
||||
}
|
||||
|
||||
bool sameGeometry(const DirectionGeometry& a, const DirectionGeometry& b)
|
||||
{
|
||||
return a.width == b.width && a.height == b.height && a.resolution == b.resolution && a.origin_x == b.origin_x &&
|
||||
a.origin_y == b.origin_y && a.frame_id == b.frame_id;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> mergeStaticLayers(const std::vector<std::vector<uint8_t>>& layers)
|
||||
{
|
||||
if (layers.empty())
|
||||
return {};
|
||||
const std::size_t count = layers.front().size();
|
||||
for (const std::vector<uint8_t>& layer : layers)
|
||||
if (layer.size() != count)
|
||||
throw std::invalid_argument("reference_graph: static layers differ in size");
|
||||
|
||||
std::vector<uint8_t> merged(count, NO_INFORMATION);
|
||||
for (const std::vector<uint8_t>& layer : layers)
|
||||
{
|
||||
for (std::size_t i = 0; i < count; ++i)
|
||||
{
|
||||
if (layer[i] == LETHAL_OBSTACLE)
|
||||
merged[i] = LETHAL_OBSTACLE;
|
||||
else if (layer[i] != NO_INFORMATION && merged[i] == NO_INFORMATION)
|
||||
merged[i] = FREE_SPACE;
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
ReferenceGraphWorker::ReferenceGraphWorker(Source source, const ReferenceGraphParams& params)
|
||||
: source_(std::move(source)), params_(params)
|
||||
{
|
||||
const std::string error = validateReferenceGraphParams(params_);
|
||||
if (!error.empty())
|
||||
throw std::invalid_argument("reference_graph: " + error);
|
||||
if (!source_.capture || !source_.direction)
|
||||
throw std::invalid_argument("reference_graph: missing source callback");
|
||||
snapshot_.state = ReferenceGraphState::kPending;
|
||||
snapshot_.generation = 1;
|
||||
thread_ = std::thread(&ReferenceGraphWorker::run, this);
|
||||
}
|
||||
|
||||
ReferenceGraphWorker::~ReferenceGraphWorker()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stop_ = true;
|
||||
cancel_.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
wake_.notify_all();
|
||||
thread_.join();
|
||||
}
|
||||
|
||||
void ReferenceGraphWorker::markPendingLocked()
|
||||
{
|
||||
// Drop the old graph at once: it may hold the wrong map or the wrong zones, and the backup planner can run meanwhile.
|
||||
if (snapshot_.state != ReferenceGraphState::kPending)
|
||||
{
|
||||
snapshot_.state = ReferenceGraphState::kPending;
|
||||
snapshot_.graph.reset();
|
||||
++snapshot_.generation;
|
||||
}
|
||||
cancel_.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void ReferenceGraphWorker::notifyStaticChanged()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
++static_revision_;
|
||||
markPendingLocked();
|
||||
}
|
||||
wake_.notify_all();
|
||||
}
|
||||
|
||||
void ReferenceGraphWorker::notifyDirectionChanged()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
++step2_revision_;
|
||||
markPendingLocked();
|
||||
}
|
||||
wake_.notify_all();
|
||||
}
|
||||
|
||||
void ReferenceGraphWorker::notifyFootprintChanged() { notifyDirectionChanged(); }
|
||||
|
||||
ReferenceGraphSnapshot ReferenceGraphWorker::snapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return snapshot_;
|
||||
}
|
||||
|
||||
ReferenceGraphWorkerStats ReferenceGraphWorker::stats() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return stats_;
|
||||
}
|
||||
|
||||
ReferenceGraphWorker::Outcome ReferenceGraphWorker::compute(uint64_t static_revision, ReferenceGraph* graph)
|
||||
{
|
||||
const bool need_step1 = !skeleton_valid_ || skeleton_revision_ != static_revision;
|
||||
|
||||
ReferenceGraphInput input;
|
||||
const Clock::time_point capture_began = Clock::now();
|
||||
const ReferenceCaptureStatus status = source_.capture(need_step1, &input);
|
||||
const double capture_ms = msSince(capture_began);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stats_.capture_ms_max = std::max(stats_.capture_ms_max, capture_ms);
|
||||
}
|
||||
if (status == ReferenceCaptureStatus::kNoStaticLayer)
|
||||
{
|
||||
if (!no_static_logged_)
|
||||
robot::log_error("ReferenceGraphWorker: reference_graph_enabled is true but no static layer is enabled\n");
|
||||
no_static_logged_ = true;
|
||||
return Outcome::kWait;
|
||||
}
|
||||
if (status != ReferenceCaptureStatus::kReady)
|
||||
return Outcome::kWait;
|
||||
no_static_logged_ = false;
|
||||
|
||||
ReferenceGridView view;
|
||||
if (need_step1)
|
||||
{
|
||||
skeleton_valid_ = false;
|
||||
static_cost_ = mergeStaticLayers(input.static_layers);
|
||||
input.static_layers.clear();
|
||||
geometry_ = input.geometry;
|
||||
view.cost = static_cost_.data();
|
||||
view.geometry = geometry_;
|
||||
const Clock::time_point began = Clock::now();
|
||||
skeleton_ = computeVoronoiSkeleton(view, params_, &cancel_);
|
||||
if (cancel_.load(std::memory_order_relaxed))
|
||||
return Outcome::kCancelled;
|
||||
skeleton_valid_ = true;
|
||||
skeleton_revision_ = static_revision;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
++stats_.step1_runs;
|
||||
stats_.step1_ms_last = msSince(began);
|
||||
}
|
||||
|
||||
const DirectionFieldSnapshot direction = source_.direction();
|
||||
if (direction.state == DirectionFieldState::kPending)
|
||||
return Outcome::kWait;
|
||||
std::vector<uint8_t> codes;
|
||||
if (direction.state == DirectionFieldState::kReady && direction.field != nullptr)
|
||||
{
|
||||
// A grid for another map layout belongs to the previous map. The new one is on its way.
|
||||
if (!sameGeometry(direction.field->geometry(), geometry_))
|
||||
return Outcome::kWait;
|
||||
if (direction.field->hasConstraints())
|
||||
{
|
||||
codes.resize(static_cast<std::size_t>(geometry_.width) * geometry_.height);
|
||||
for (uint32_t y = 0; y < geometry_.height; ++y)
|
||||
{
|
||||
if (cancel_.load(std::memory_order_relaxed))
|
||||
return Outcome::kCancelled;
|
||||
for (uint32_t x = 0; x < geometry_.width; ++x)
|
||||
codes[static_cast<std::size_t>(y) * geometry_.width + x] = direction.field->code(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view.cost = static_cost_.data();
|
||||
view.geometry = geometry_;
|
||||
view.direction_codes = codes.empty() ? nullptr : codes.data();
|
||||
const Clock::time_point began = Clock::now();
|
||||
*graph = buildReferenceGraph(view, skeleton_, input.footprint, params_, &cancel_);
|
||||
if (cancel_.load(std::memory_order_relaxed))
|
||||
return Outcome::kCancelled;
|
||||
graph->direction_generation = direction.generation;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
++stats_.step2_runs;
|
||||
stats_.step2_ms_last = msSince(began);
|
||||
return Outcome::kDone;
|
||||
}
|
||||
|
||||
void ReferenceGraphWorker::run()
|
||||
{
|
||||
lowerThreadPriority();
|
||||
while (true)
|
||||
{
|
||||
uint64_t static_revision = 0;
|
||||
uint64_t step2_revision = 0;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
wake_.wait(lock, [this]() { return stop_ || static_revision_ != handled_static_ || step2_revision_ != handled_step2_; });
|
||||
if (stop_)
|
||||
return;
|
||||
static_revision = static_revision_;
|
||||
step2_revision = step2_revision_;
|
||||
cancel_.store(false, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
ReferenceGraph graph;
|
||||
Outcome outcome = Outcome::kFailed;
|
||||
std::string failure;
|
||||
try
|
||||
{
|
||||
outcome = compute(static_revision, &graph);
|
||||
}
|
||||
catch (const std::exception& error)
|
||||
{
|
||||
failure = error.what();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
failure = "unknown exception";
|
||||
}
|
||||
// An exception here must not take the whole navigation process down. The planner keeps failing over to its backup.
|
||||
if (outcome == Outcome::kFailed)
|
||||
robot::log_error("ReferenceGraphWorker: computation failed, staying pending until the next change: %s\n", failure.c_str());
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
if (stop_)
|
||||
return;
|
||||
if (outcome == Outcome::kFailed)
|
||||
++stats_.errors;
|
||||
if (static_revision_ != static_revision || step2_revision_ != step2_revision)
|
||||
continue; // Three maps in a row compute only the last one.
|
||||
if (outcome == Outcome::kCancelled)
|
||||
continue;
|
||||
if (outcome == Outcome::kWait)
|
||||
{
|
||||
wake_.wait_for(lock, kRetryPeriod, [&]() {
|
||||
return stop_ || static_revision_ != static_revision || step2_revision_ != step2_revision;
|
||||
});
|
||||
continue;
|
||||
}
|
||||
handled_static_ = static_revision;
|
||||
handled_step2_ = step2_revision;
|
||||
if (outcome != Outcome::kDone)
|
||||
continue;
|
||||
|
||||
const std::size_t nodes = graph.nodes.size();
|
||||
const std::size_t edges = graph.edges.size();
|
||||
const std::size_t lanes = graph.lanes.size();
|
||||
snapshot_.state = ReferenceGraphState::kReady;
|
||||
snapshot_.graph = std::make_shared<const ReferenceGraph>(std::move(graph));
|
||||
++snapshot_.generation;
|
||||
++stats_.published;
|
||||
const ReferenceGraphWorkerStats stats = stats_;
|
||||
const uint64_t generation = snapshot_.generation;
|
||||
lock.unlock();
|
||||
if (params_.debug_log)
|
||||
robot::log_info("[debug] ReferenceGraph ready: generation=%llu nodes=%zu edges=%zu lanes=%zu step1_ms=%.0f step2_ms=%.0f capture_ms_max=%.1f\n",
|
||||
static_cast<unsigned long long>(generation), nodes, edges, lanes, stats.step1_ms_last, stats.step2_ms_last,
|
||||
stats.capture_ms_max);
|
||||
}
|
||||
}
|
||||
|
||||
} // 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();
|
||||
}
|
||||
|
||||
|
||||
98
test/costmap_common_root_test.cpp
Normal file
98
test/costmap_common_root_test.cpp
Normal file
@@ -0,0 +1,98 @@
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using robot_costmap_2d::Costmap2DROBOT;
|
||||
|
||||
TEST(CostmapCommonParameters, SelectAndCopySharedValues)
|
||||
{
|
||||
const char* layout = std::getenv("COSTMAP_TEST_LAYOUT");
|
||||
ASSERT_NE(layout, nullptr);
|
||||
const std::string expected_layout(layout);
|
||||
ASSERT_TRUE(expected_layout == "rooted" || expected_layout == "flat");
|
||||
ASSERT_NE(std::getenv("PNKX_NAV_CORE_CONFIG_DIR"), nullptr);
|
||||
|
||||
robot::NodeHandle tree_nh("~");
|
||||
EXPECT_EQ(tree_nh.hasParam("root"), expected_layout == "rooted");
|
||||
robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh);
|
||||
|
||||
double tolerance = 0.0;
|
||||
ASSERT_TRUE(common_nh.getParam("transform_tolerance", tolerance));
|
||||
EXPECT_DOUBLE_EQ(tolerance, 1.0);
|
||||
std::string frame;
|
||||
ASSERT_TRUE(common_nh.getParam("robot_base_frame", frame));
|
||||
EXPECT_EQ(frame, "base_link");
|
||||
|
||||
Costmap2DROBOT::copyParentParameters("local_costmap", "obstacles", "VoxelLayer", common_nh, tree_nh);
|
||||
Costmap2DROBOT::copyParentParameters("global_costmap", "obstacles", "VoxelLayer", common_nh, tree_nh);
|
||||
Costmap2DROBOT::copyParentParameters("local_costmap", "forbidden", "StaticLayer", common_nh, tree_nh);
|
||||
Costmap2DROBOT::copyParentParameters("global_costmap", "preferred", "PreferredLayer", common_nh, tree_nh);
|
||||
|
||||
std::string value;
|
||||
ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/observation_sources", value));
|
||||
EXPECT_EQ(value, "f_scan b_scan");
|
||||
ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/f_scan/topic", value));
|
||||
EXPECT_EQ(value, "/f_scan");
|
||||
ASSERT_TRUE(tree_nh.getParam("local_costmap/forbidden/map_topic", value));
|
||||
EXPECT_EQ(value, "forbidden");
|
||||
ASSERT_TRUE(tree_nh.getParam("global_costmap/preferred/map_topic", value));
|
||||
EXPECT_EQ(value, "preferred");
|
||||
|
||||
int voxels = 0;
|
||||
double resolution = 0.0;
|
||||
ASSERT_TRUE(tree_nh.getParam("global_costmap/obstacles/z_voxels", voxels));
|
||||
EXPECT_EQ(voxels, 10);
|
||||
ASSERT_TRUE(tree_nh.getParam("global_costmap/obstacles/z_resolution", resolution));
|
||||
EXPECT_DOUBLE_EQ(resolution, 0.2);
|
||||
ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/z_voxels", voxels));
|
||||
EXPECT_EQ(voxels, 8);
|
||||
ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/z_resolution", resolution));
|
||||
EXPECT_DOUBLE_EQ(resolution, 0.15);
|
||||
}
|
||||
|
||||
TEST(CostmapCommonParameters, PreservesSourceOverridesAndFillsMissingSourceKeys)
|
||||
{
|
||||
robot::NodeHandle tree_nh("~");
|
||||
robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh);
|
||||
Costmap2DROBOT::copyParentParameters("override_costmap", "obstacles", "VoxelLayer", common_nh, tree_nh);
|
||||
|
||||
std::string value;
|
||||
ASSERT_TRUE(tree_nh.getParam("override_costmap/obstacles/observation_sources", value));
|
||||
EXPECT_EQ(value, "b_scan");
|
||||
ASSERT_TRUE(tree_nh.getParam("override_costmap/obstacles/b_scan/topic", value));
|
||||
EXPECT_EQ(value, "/local_override");
|
||||
ASSERT_TRUE(tree_nh.getParam("override_costmap/obstacles/b_scan/data_type", value));
|
||||
EXPECT_EQ(value, "LaserScan");
|
||||
EXPECT_FALSE(tree_nh.hasParam("override_costmap/obstacles/f_scan/topic"));
|
||||
}
|
||||
|
||||
TEST(CostmapCommonParameters, RejectsInvalidSharedTypeOnlyWhenCopied)
|
||||
{
|
||||
robot::NodeHandle tree_nh("~");
|
||||
robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh);
|
||||
EXPECT_THROW(Costmap2DROBOT::copyParentParameters("invalid_costmap", "bad_obstacles", "VoxelLayer",
|
||||
common_nh, tree_nh), std::invalid_argument);
|
||||
EXPECT_NO_THROW(Costmap2DROBOT::copyParentParameters("protected_costmap", "bad_obstacles", "VoxelLayer",
|
||||
common_nh, tree_nh));
|
||||
int voxels = 0;
|
||||
ASSERT_TRUE(tree_nh.getParam("protected_costmap/bad_obstacles/z_voxels", voxels));
|
||||
EXPECT_EQ(voxels, 12);
|
||||
}
|
||||
|
||||
TEST(CostmapCommonParameters, CreatesMissingCostmapNamespace)
|
||||
{
|
||||
robot::NodeHandle tree_nh("~");
|
||||
robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh);
|
||||
ASSERT_FALSE(tree_nh.hasParam("missing_costmap"));
|
||||
Costmap2DROBOT::copyParentParameters("missing_costmap", "forbidden", "StaticLayer", common_nh, tree_nh);
|
||||
std::string topic;
|
||||
ASSERT_TRUE(tree_nh.getParam("missing_costmap/forbidden/map_topic", topic));
|
||||
EXPECT_EQ(topic, "forbidden");
|
||||
}
|
||||
} // namespace
|
||||
30
test/data/costmap_common_root/flat/params.yaml
Normal file
30
test/data/costmap_common_root/flat/params.yaml
Normal file
@@ -0,0 +1,30 @@
|
||||
robot_base_frame: base_link
|
||||
transform_tolerance: 1.0
|
||||
footprint_padding: 0.0
|
||||
forbidden:
|
||||
map_topic: forbidden
|
||||
use_maximum: true
|
||||
preferred:
|
||||
map_topic: preferred
|
||||
obstacles:
|
||||
z_voxels: 8
|
||||
z_resolution: 0.15
|
||||
observation_sources: f_scan b_scan
|
||||
f_scan: {topic: /f_scan, data_type: LaserScan, marking: true}
|
||||
b_scan: {topic: /b_scan, data_type: LaserScan, clearing: true}
|
||||
bad_obstacles:
|
||||
z_voxels: invalid_integer
|
||||
global_costmap:
|
||||
obstacles: {enabled: false, z_voxels: 10, z_resolution: 0.2}
|
||||
preferred: {}
|
||||
local_costmap:
|
||||
obstacles: {enabled: true}
|
||||
forbidden: {}
|
||||
override_costmap:
|
||||
obstacles:
|
||||
observation_sources: b_scan
|
||||
b_scan: {topic: /local_override}
|
||||
invalid_costmap:
|
||||
bad_obstacles: {}
|
||||
protected_costmap:
|
||||
bad_obstacles: {z_voxels: 12}
|
||||
35
test/data/costmap_common_root/rooted/params.yaml
Normal file
35
test/data/costmap_common_root/rooted/params.yaml
Normal file
@@ -0,0 +1,35 @@
|
||||
root:
|
||||
robot_base_frame: base_link
|
||||
transform_tolerance: 1.0
|
||||
footprint_padding: 0.0
|
||||
forbidden:
|
||||
map_topic: forbidden
|
||||
use_maximum: true
|
||||
preferred:
|
||||
map_topic: preferred
|
||||
obstacles:
|
||||
z_voxels: 8
|
||||
z_resolution: 0.15
|
||||
observation_sources: f_scan b_scan
|
||||
f_scan: {topic: /f_scan, data_type: LaserScan, marking: true}
|
||||
b_scan: {topic: /b_scan, data_type: LaserScan, clearing: true}
|
||||
bad_obstacles:
|
||||
z_voxels: invalid_integer
|
||||
robot_base_frame: ignored_frame
|
||||
transform_tolerance: 9.0
|
||||
footprint_padding: 9.0
|
||||
obstacles: {z_voxels: 99}
|
||||
global_costmap:
|
||||
obstacles: {enabled: false, z_voxels: 10, z_resolution: 0.2}
|
||||
preferred: {}
|
||||
local_costmap:
|
||||
obstacles: {enabled: true}
|
||||
forbidden: {}
|
||||
override_costmap:
|
||||
obstacles:
|
||||
observation_sources: b_scan
|
||||
b_scan: {topic: /local_override}
|
||||
invalid_costmap:
|
||||
bad_obstacles: {}
|
||||
protected_costmap:
|
||||
bad_obstacles: {z_voxels: 12}
|
||||
17
test/data/reference_graph/corridor.fixture
Normal file
17
test/data/reference_graph/corridor.fixture
Normal file
@@ -0,0 +1,17 @@
|
||||
reference_graph_fixture 1
|
||||
size 200 60
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 3
|
||||
254 2000 60 8000 254 2000
|
||||
direction 1
|
||||
0 12000
|
||||
skeleton 200
|
||||
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
|
||||
nodes 2
|
||||
-2.475 2.725
|
||||
7.475000000000001 2.725
|
||||
edges 1
|
||||
0 1 41 -2.475 2.725 -2.225 2.725 -1.975 2.725 -1.725 2.725 -1.4749999999999999 2.725 -1.2249999999999999 2.725 -0.9749999999999999 2.725 -0.7249999999999999 2.725 -0.4750000000000001 2.725 -0.2250000000000001 2.725 0.025000000000000355 2.725 0.27500000000000036 2.725 0.5250000000000004 2.725 0.7750000000000004 2.725 1.0250000000000004 2.725 1.2750000000000004 2.725 1.5250000000000004 2.725 1.7750000000000004 2.725 2.0250000000000004 2.725 2.2750000000000004 2.725 2.5250000000000004 2.725 2.7750000000000004 2.725 3.0250000000000004 2.725 3.2750000000000004 2.725 3.5250000000000004 2.725 3.7750000000000004 2.725 4.025 2.725 4.275 2.725 4.525 2.725 4.775 2.725 5.025 2.725 5.275 2.725 5.525 2.725 5.775 2.725 6.025 2.725 6.275 2.725 6.525 2.725 6.775 2.725 7.025 2.725 7.275 2.725 7.475000000000001 2.725
|
||||
lanes 0
|
||||
64
test/data/reference_graph/crop.fixture
Normal file
64
test/data/reference_graph/crop.fixture
Normal file
File diff suppressed because one or more lines are too long
28
test/data/reference_graph/cut_zone.fixture
Normal file
28
test/data/reference_graph/cut_zone.fixture
Normal file
@@ -0,0 +1,28 @@
|
||||
reference_graph_fixture 1
|
||||
size 200 60
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 53
|
||||
254 2000 60 95 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 3095 254 2000
|
||||
direction 81
|
||||
0 2050 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 2050
|
||||
skeleton 214
|
||||
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6075 6076 6124 6276 6277 6323 6477 6478 6522 6678 6679 6721 6879 6880 6919 6920 7080 7081 7118 7281 7282 7317 7482 7483 7516 7683 7684 7685 7714 7715 7885 7886 7887 7913 8087 8088 8089 8110 8111 8112 8289 8290 8291 8292 8293 8294 8305 8306 8307 8308 8309 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504
|
||||
nodes 6
|
||||
4.9750000000000005 2.725
|
||||
0.025000000000000355 2.725
|
||||
5.025 2.725
|
||||
-0.02499999999999991 2.725
|
||||
-2.475 2.725
|
||||
7.475000000000001 2.725
|
||||
edges 5
|
||||
0 1 24 4.9750000000000005 2.725 4.7250000000000005 2.725 4.4750000000000005 2.725 4.2250000000000005 2.725 3.9750000000000005 2.725 3.7250000000000005 2.725 3.5250000000000004 2.975 3.2750000000000004 3.175 3.0250000000000004 3.275 2.7750000000000004 3.325 2.5250000000000004 3.375 2.2750000000000004 3.375 2.075 3.325 1.875 3.275 1.7250000000000005 3.175 1.5750000000000002 3.075 1.475 2.925 1.3250000000000002 2.825 1.1750000000000003 2.725 0.9250000000000003 2.725 0.6750000000000003 2.725 0.42500000000000027 2.725 0.17500000000000027 2.725 0.025000000000000355 2.725
|
||||
0 2 2 4.9750000000000005 2.725 5.025 2.725
|
||||
3 4 11 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725
|
||||
3 1 2 -0.02499999999999991 2.725 0.025000000000000355 2.725
|
||||
5 2 11 7.475000000000001 2.725 7.225000000000001 2.725 6.975 2.725 6.725 2.725 6.475 2.725 6.225 2.725 5.975 2.725 5.725 2.725 5.4750000000000005 2.725 5.2250000000000005 2.725 5.025 2.725
|
||||
lanes 3
|
||||
0 3.5388358909926865e-16 3.3500000000000014 4.950495049504951 3.3500000000000014 4.950495049504951 0.0
|
||||
0 3.5388358909926865e-16 2.8500000000000014 1.9306930693069315 2.8500000000000014 1.930693069306931 0.5
|
||||
0 3.5388358909926865e-16 2.3500000000000014 1.9306930693069315 2.3500000000000014 1.930693069306931 1.0
|
||||
28
test/data/reference_graph/one_zone.fixture
Normal file
28
test/data/reference_graph/one_zone.fixture
Normal file
@@ -0,0 +1,28 @@
|
||||
reference_graph_fixture 1
|
||||
size 200 60
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 3
|
||||
254 2000 60 8000 254 2000
|
||||
direction 81
|
||||
0 2050 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 2050
|
||||
skeleton 200
|
||||
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
|
||||
nodes 6
|
||||
4.9750000000000005 2.725
|
||||
0.025000000000000355 2.725
|
||||
5.025 2.725
|
||||
-0.02499999999999991 2.725
|
||||
-2.475 2.725
|
||||
7.475000000000001 2.725
|
||||
edges 5
|
||||
0 1 21 4.9750000000000005 2.725 4.7250000000000005 2.725 4.4750000000000005 2.725 4.2250000000000005 2.725 3.9750000000000005 2.725 3.7250000000000005 2.725 3.4750000000000005 2.725 3.2250000000000005 2.725 2.9750000000000005 2.725 2.7250000000000005 2.725 2.4750000000000005 2.725 2.2250000000000005 2.725 1.9750000000000005 2.725 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 0.025000000000000355 2.725
|
||||
0 2 2 4.9750000000000005 2.725 5.025 2.725
|
||||
3 4 11 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725
|
||||
3 1 2 -0.02499999999999991 2.725 0.025000000000000355 2.725
|
||||
5 2 11 7.475000000000001 2.725 7.225000000000001 2.725 6.975 2.725 6.725 2.725 6.475 2.725 6.225 2.725 5.975 2.725 5.725 2.725 5.4750000000000005 2.725 5.2250000000000005 2.725 5.025 2.725
|
||||
lanes 3
|
||||
0 3.5388358909926865e-16 2.75 4.950495049504951 2.75 4.950495049504951 0.0
|
||||
0 3.5388358909926865e-16 2.25 4.950495049504951 2.25 4.950495049504951 0.5
|
||||
0 3.5388358909926865e-16 3.25 4.950495049504951 3.25 4.950495049504951 0.5
|
||||
14
test/data/reference_graph/ring.fixture
Normal file
14
test/data/reference_graph/ring.fixture
Normal file
@@ -0,0 +1,14 @@
|
||||
reference_graph_fixture 1
|
||||
size 120 120
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 241
|
||||
254 1253 60 14 254 101 60 24 254 92 60 32 254 86 60 36 254 81 60 42 254 76 60 46 254 72 60 50 254 69 60 52 254 66 60 56 254 63 60 58 254 60 60 62 254 57 60 64 254 55 60 66 254 53 60 68 254 51 60 70 254 49 60 72 254 47 60 74 254 45 60 76 254 43 60 78 254 41 60 80 254 40 60 80 254 39 60 82 254 37 60 84 254 36 60 84 254 35 60 86 254 33 60 88 254 32 60 88 254 31 60 90 254 30 60 90 254 29 60 92 254 28 60 92 254 28 60 92 254 27 60 94 254 26 60 94 254 25 60 96 254 24 60 96 254 24 60 96 254 24 60 96 254 23 60 98 254 22 60 98 254 22 60 46 254 6 60 46 254 22 60 44 254 10 60 44 254 22 60 42 254 14 60 42 254 21 60 42 254 16 60 42 254 20 60 42 254 16 60 42 254 20 60 41 254 18 60 41 254 20 60 41 254 18 60 41 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 41 254 18 60 41 254 20 60 41 254 18 60 41 254 20 60 42 254 16 60 42 254 20 60 42 254 16 60 42 254 21 60 42 254 14 60 42 254 22 60 44 254 10 60 44 254 22 60 46 254 6 60 46 254 22 60 98 254 22 60 98 254 23 60 96 254 24 60 96 254 24 60 96 254 24 60 96 254 25 60 94 254 26 60 94 254 27 60 92 254 28 60 92 254 28 60 92 254 29 60 90 254 30 60 90 254 31 60 88 254 32 60 88 254 33 60 86 254 35 60 84 254 36 60 84 254 37 60 82 254 39 60 80 254 40 60 80 254 41 60 78 254 43 60 76 254 45 60 74 254 47 60 72 254 49 60 70 254 51 60 68 254 53 60 66 254 55 60 64 254 57 60 62 254 60 60 58 254 63 60 56 254 66 60 52 254 69 60 50 254 72 60 46 254 76 60 42 254 81 60 36 254 86 60 32 254 92 60 24 254 101 60 14 254 1253
|
||||
direction 1
|
||||
0 14400
|
||||
skeleton 205
|
||||
3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3651 3652 3653 3654 3664 3665 3666 3667 3668 3768 3769 3770 3788 3789 3790 3791 3886 3887 3911 3912 3913 4004 4005 4033 4034 4035 4123 4155 4156 4241 4242 4276 4277 4278 4360 4398 4399 4479 4519 4520 4598 4640 4641 4717 4761 4762 4836 4882 4883 4955 5003 5075 5123 5124 5194 5244 5245 5313 5365 5433 5485 5486 5552 5606 5672 5726 5727 5791 5847 5911 5967 6031 6087 6088 6150 6208 6270 6328 6390 6448 6510 6568 6569 6629 6689 6749 6809 6869 6929 6989 7049 7109 7169 7229 7289 7349 7409 7469 7529 7589 7649 7709 7710 7769 7830 7888 7950 8008 8070 8128 8190 8191 8248 8311 8367 8431 8487 8551 8552 8607 8672 8726 8792 8793 8846 8913 8965 9033 9034 9085 9154 9155 9204 9275 9323 9395 9396 9443 9516 9517 9562 9637 9638 9681 9758 9759 9800 9879 9880 9919 10000 10001 10002 10037 10038 10122 10123 10156 10243 10244 10245 10274 10275 10365 10366 10367 10392 10393 10487 10488 10489 10490 10509 10510 10511 10610 10611 10612 10613 10614 10625 10626 10627 10628 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744
|
||||
nodes 0
|
||||
edges 0
|
||||
lanes 0
|
||||
21
test/data/reference_graph/t_junction.fixture
Normal file
21
test/data/reference_graph/t_junction.fixture
Normal file
@@ -0,0 +1,21 @@
|
||||
reference_graph_fixture 1
|
||||
size 200 120
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 143
|
||||
254 2000 60 8000 254 80 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 80
|
||||
direction 1
|
||||
0 24000
|
||||
skeleton 290
|
||||
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6085 6086 6087 6088 6089 6090 6109 6110 6111 6112 6113 6290 6291 6292 6293 6306 6307 6308 6493 6494 6495 6504 6505 6695 6696 6697 6698 6701 6702 6703 6898 6899 6900 7099 7299 7499 7699 7899 8099 8299 8499 8699 8899 9099 9299 9499 9699 9899 10099 10299 10499 10699 10899 11099 11299 11499 11699 11899 12099 12299 12499 12699 12899 13099 13299 13499 13699 13899 14099 14299 14499 14699 14899 15099 15299 15499 15699 15899 16099 16299 16499 16699 16899 17099 17299 17499 17699 17899 18099 18299 18499 18699 18899 19099 19299 19499 19699 19899 20099 20299 20499 20699 20899 21099 21299 21499 21699 21899 22099 22299 22499 22699 22899 23099 23299 23499 23699 23899
|
||||
nodes 4
|
||||
2.4750000000000005 2.975
|
||||
-2.475 2.725
|
||||
7.475000000000001 2.725
|
||||
2.4750000000000005 7.2250000000000005
|
||||
edges 3
|
||||
0 1 22 2.4750000000000005 2.975 2.2750000000000004 2.925 2.125 2.825 1.9249999999999998 2.7750000000000004 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725
|
||||
0 2 21 2.4750000000000005 2.975 2.7250000000000005 2.875 2.9750000000000005 2.7750000000000004 3.2250000000000005 2.725 3.4750000000000005 2.725 3.7250000000000005 2.725 3.9750000000000005 2.725 4.2250000000000005 2.725 4.4750000000000005 2.725 4.7250000000000005 2.725 4.9750000000000005 2.725 5.2250000000000005 2.725 5.4750000000000005 2.725 5.725 2.725 5.975 2.725 6.225 2.725 6.475 2.725 6.725 2.725 6.975 2.725 7.225000000000001 2.725 7.475000000000001 2.725
|
||||
0 3 18 2.4750000000000005 2.975 2.4750000000000005 3.225 2.4750000000000005 3.475 2.4750000000000005 3.725 2.4750000000000005 3.975 2.4750000000000005 4.225 2.4750000000000005 4.475 2.4750000000000005 4.725 2.4750000000000005 4.975 2.4750000000000005 5.225 2.4750000000000005 5.4750000000000005 2.4750000000000005 5.7250000000000005 2.4750000000000005 5.9750000000000005 2.4750000000000005 6.2250000000000005 2.4750000000000005 6.4750000000000005 2.4750000000000005 6.7250000000000005 2.4750000000000005 6.9750000000000005 2.4750000000000005 7.2250000000000005
|
||||
lanes 0
|
||||
37
test/data/reference_graph/two_zones.fixture
Normal file
37
test/data/reference_graph/two_zones.fixture
Normal file
@@ -0,0 +1,37 @@
|
||||
reference_graph_fixture 1
|
||||
size 200 60
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 3
|
||||
254 2000 60 8000 254 2000
|
||||
direction 121
|
||||
0 2040 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 2040
|
||||
skeleton 200
|
||||
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
|
||||
nodes 8
|
||||
2.5250000000000004 2.725
|
||||
2.4750000000000005 2.725
|
||||
5.4750000000000005 2.725
|
||||
-0.5249999999999999 2.725
|
||||
-2.475 2.725
|
||||
-0.4750000000000001 2.725
|
||||
7.475000000000001 2.725
|
||||
5.525 2.725
|
||||
edges 7
|
||||
0 1 2 2.5250000000000004 2.725 2.4750000000000005 2.725
|
||||
0 2 13 2.5250000000000004 2.725 2.7750000000000004 2.725 3.0250000000000004 2.725 3.2750000000000004 2.725 3.5250000000000004 2.725 3.7750000000000004 2.725 4.025 2.725 4.275 2.725 4.525 2.725 4.775 2.725 5.025 2.725 5.275 2.725 5.4750000000000005 2.725
|
||||
3 4 9 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725
|
||||
3 5 2 -0.5249999999999999 2.725 -0.4750000000000001 2.725
|
||||
6 7 9 7.475000000000001 2.725 7.225000000000001 2.725 6.975 2.725 6.725 2.725 6.475 2.725 6.225 2.725 5.975 2.725 5.725 2.725 5.525 2.725
|
||||
7 2 2 5.525 2.725 5.4750000000000005 2.725
|
||||
1 5 13 2.4750000000000005 2.725 2.2250000000000005 2.725 1.9750000000000005 2.725 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.4750000000000001 2.725
|
||||
lanes 8
|
||||
0 -0.5000000000000001 2.75 2.4508196721311477 2.75 2.9508196721311477 0.0
|
||||
0 -0.5000000000000001 2.25 2.4508196721311477 2.25 2.9508196721311477 0.5
|
||||
0 -0.5000000000000001 3.25 2.4508196721311477 3.25 2.9508196721311477 0.5
|
||||
1 3.454225352112677 2.2042253521126765 4.545774647887324 3.2957746478873235 1.5436838180833075 0.0
|
||||
1 4.159891418762288 2.20278463757574 5.251440714536936 3.294333933350387 1.5436838180833075 0.5
|
||||
1 2.7485592854630645 2.205666066649612 3.8401085812377125 3.29721536242426 1.543683818083308 0.5
|
||||
1 4.8655574854119 2.201343923038804 5.499360302313308 2.835146739940213 0.8963325395322439 1.0
|
||||
1 2.500639697686692 2.664853260059787 3.134442514588101 3.2986560769611954 0.8963325395322439 1.0
|
||||
20
test/data/reference_graph/unknown_block.fixture
Normal file
20
test/data/reference_graph/unknown_block.fixture
Normal file
@@ -0,0 +1,20 @@
|
||||
reference_graph_fixture 1
|
||||
size 200 60
|
||||
resolution 0.05
|
||||
origin -2.5 1.25
|
||||
params 0.335 0.7 1.0 0.5 0.3 0.3
|
||||
cost 83
|
||||
254 2000 60 90 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 90 254 2000
|
||||
direction 1
|
||||
0 12000
|
||||
skeleton 180
|
||||
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
|
||||
nodes 4
|
||||
3.0250000000000004 2.725
|
||||
7.475000000000001 2.725
|
||||
1.9750000000000005 2.725
|
||||
-2.475 2.725
|
||||
edges 2
|
||||
0 1 19 3.0250000000000004 2.725 3.2750000000000004 2.725 3.5250000000000004 2.725 3.7750000000000004 2.725 4.025 2.725 4.275 2.725 4.525 2.725 4.775 2.725 5.025 2.725 5.275 2.725 5.525 2.725 5.775 2.725 6.025 2.725 6.275 2.725 6.525 2.725 6.775 2.725 7.025 2.725 7.275 2.725 7.475000000000001 2.725
|
||||
2 3 19 1.9750000000000005 2.725 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725
|
||||
lanes 0
|
||||
683
test/depth_camera_obstacle_layer_test.cpp
Normal file
683
test/depth_camera_obstacle_layer_test.cpp
Normal file
@@ -0,0 +1,683 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
// Dense vertical sheet at x (odom): with step / x <= 0.01 every ray bin it covers gets a return,
|
||||
// unlike object(), whose 6 cm gaps let the rays through.
|
||||
std::vector<Eigen::Vector3d> sheet(double x, double y0, double y1, double z0, double z1, double step = .01)
|
||||
{
|
||||
std::vector<Eigen::Vector3d> pts;
|
||||
for (double y = y0; y <= y1 + 1e-9; y += step)
|
||||
for (double z = z0; z <= z1 + 1e-9; z += step)
|
||||
pts.emplace_back(x, y, z);
|
||||
return pts;
|
||||
}
|
||||
|
||||
// Far backdrop 2 m ahead, behind everything the guard tests store.
|
||||
std::vector<Eigen::Vector3d> backdrop()
|
||||
{
|
||||
return sheet(2.0, -.10, .60, .05, .60, .015);
|
||||
}
|
||||
|
||||
// 21 x 21 returns 5 mm apart, centred on (x, y0, z0) of a camera_link frame (X forward).
|
||||
std::vector<Eigen::Vector3f> patch(float x, float y0, float z0)
|
||||
{
|
||||
std::vector<Eigen::Vector3f> pts;
|
||||
for (int i = -10; i <= 10; ++i)
|
||||
for (int j = -10; j <= 10; ++j)
|
||||
pts.emplace_back(x, y0 + i * .005f, z0 + j * .005f);
|
||||
return pts;
|
||||
}
|
||||
|
||||
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, AttachDistanceFollowsTheParameter)
|
||||
{
|
||||
DepthCameraFrustum f;
|
||||
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false, .08);
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.20f, 0, 0))); // 5 cm past it
|
||||
const float half_w = std::tan(kFovW / 2);
|
||||
// 5 cm / 15 cm inside the left face along y: ~4 cm / ~12 cm from its plane.
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0)));
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .15f, 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)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Range image (occlusion guard)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
TEST(DepthCameraRangeImage, NearerReturnsHideAndFartherReturnsShowThrough)
|
||||
{
|
||||
using Evidence = DepthCameraRangeImage::Evidence;
|
||||
DepthCameraRangeImage image;
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(1, 0, 0)), Evidence::kNone); // never built
|
||||
image.reset(Eigen::Isometry3d::Identity(), kFovW, kFovV, false); // X forward
|
||||
for (const Eigen::Vector3f& p : patch(1, 0, 0))
|
||||
image.addSensorPoint(p);
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(2, 0, 0)), Evidence::kOccluded); // behind the patch
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(.5f, 0, 0)), Evidence::kSeenThrough); // in front of it
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(1, 0, 0)), Evidence::kNone); // on it
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(1, .5f, 0)), Evidence::kNone); // no return on that ray
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(.05f, 0, 0)), Evidence::kNone); // too close to judge
|
||||
}
|
||||
|
||||
TEST(DepthCameraRangeImage, OpticalFrameGivesTheSameEvidence)
|
||||
{
|
||||
using Evidence = DepthCameraRangeImage::Evidence;
|
||||
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
|
||||
T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link
|
||||
DepthCameraRangeImage link, optical;
|
||||
link.reset(Eigen::Isometry3d::Identity(), kFovW, kFovV, false);
|
||||
optical.reset(T, kFovW, kFovV, true);
|
||||
const Eigen::Isometry3f optical_from_link = T.inverse().cast<float>();
|
||||
// Off-centre patch (left and up), so a mirrored axis would answer for the wrong ray.
|
||||
for (const Eigen::Vector3f& p : patch(1, .3f, .1f))
|
||||
{
|
||||
link.addSensorPoint(p);
|
||||
optical.addSensorPoint(optical_from_link * p);
|
||||
}
|
||||
const Eigen::Vector3f behind(2, .6f, .2f), mirrored(2, -.6f, -.2f), in_front(.5f, .15f, .05f);
|
||||
EXPECT_EQ(link.test(behind), Evidence::kOccluded);
|
||||
EXPECT_EQ(link.test(mirrored), Evidence::kNone);
|
||||
EXPECT_EQ(link.test(in_front), Evidence::kSeenThrough);
|
||||
EXPECT_EQ(optical.test(behind), Evidence::kOccluded);
|
||||
EXPECT_EQ(optical.test(mirrored), Evidence::kNone);
|
||||
EXPECT_EQ(optical.test(in_front), Evidence::kSeenThrough);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// 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);
|
||||
}
|
||||
|
||||
class DepthCameraAttachTest : public DepthCameraLayerTest
|
||||
{
|
||||
protected:
|
||||
void configure(YAML::Node& cfg) override
|
||||
{
|
||||
cfg["depth_cam"]["attach_distance"] = .08;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(DepthCameraAttachTest, NarrowerAttachBandMarksCloserToTheFaces)
|
||||
{
|
||||
// The scene of AttachBandIsNotMarked: 10 cm past the near plane is outside an 8 cm band.
|
||||
frame(wall());
|
||||
const std::size_t wall_points = layer.storedPoints();
|
||||
ASSERT_GT(wall_points, 0u);
|
||||
frame(join(object(.25, .10, .19), wall()));
|
||||
EXPECT_GT(layer.storedPoints(), wall_points);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Occlusion guard
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
class DepthCameraGuardTest : public DepthCameraLayerTest
|
||||
{
|
||||
protected:
|
||||
void configure(YAML::Node& cfg) override
|
||||
{
|
||||
cfg["number_clearing_threshold"] = 1; // as on the KIT robot
|
||||
cfg["occlusion_guard"] = guard();
|
||||
}
|
||||
virtual bool guard() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
class DepthCameraNoGuardTest : public DepthCameraGuardTest
|
||||
{
|
||||
protected:
|
||||
bool guard() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// A box 1.42 m ahead, then a screen 1 m ahead that hides it (a person walking past it).
|
||||
std::vector<Eigen::Vector3d> hiddenBox()
|
||||
{
|
||||
return object(1.42, .13, .30);
|
||||
}
|
||||
std::vector<Eigen::Vector3d> screen()
|
||||
{
|
||||
return sheet(1.0, -.02, .22, .16, .36);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraNoGuardTest, HiddenBoxIsClearedWithoutTheGuard)
|
||||
{
|
||||
frame(hiddenBox());
|
||||
ASSERT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
frame(screen()); // no cloud point near the box: the kd-tree test clears it
|
||||
EXPECT_NE(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraGuardTest, HiddenBoxIsKeptWithTheGuard)
|
||||
{
|
||||
frame(hiddenBox());
|
||||
ASSERT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame(screen());
|
||||
EXPECT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
frame(backdrop()); // the screen is gone and the camera sees past the box: now it goes
|
||||
EXPECT_NE(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
// A box in front of the backdrop moves 18 cm to the left. Its old column y = .22 (corner .20)
|
||||
// still has a point of the moved box (y = .28) within check_radius, so only the rays show that
|
||||
// the column is empty. Checked at (1.01, .21): stored corners sit on cell edges, and corner .20
|
||||
// is the only one that lands in that master cell (corner .15 falls back into the .10 cell).
|
||||
std::vector<Eigen::Vector3d> boxBefore()
|
||||
{
|
||||
return object(1.02, .16, .30);
|
||||
}
|
||||
std::vector<Eigen::Vector3d> boxAfter()
|
||||
{
|
||||
return object(1.02, .34, .30);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraNoGuardTest, MovedBoxLeavesAGhostWithoutTheGuard)
|
||||
{
|
||||
frame(join(boxBefore(), backdrop()));
|
||||
ASSERT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
frame(join(boxAfter(), backdrop()));
|
||||
EXPECT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraGuardTest, MovedBoxLeavesNoGhostWithTheGuard)
|
||||
{
|
||||
frame(join(boxBefore(), backdrop()));
|
||||
ASSERT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
frame(join(boxAfter(), backdrop()));
|
||||
EXPECT_NE(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master(1.01, .26), LETHAL_OBSTACLE); // the moved box itself (its y = .28 column)
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraGuardTest, SolidBoxSeenAgainIsKept)
|
||||
{
|
||||
// A real surface returns on every ray at its own range: no evidence, the kd-tree test keeps it.
|
||||
const std::vector<Eigen::Vector3d> box = sheet(1.02, .05, .20, .22, .38);
|
||||
frame(join(box, backdrop()));
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame(join(box, backdrop()));
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
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);
|
||||
cfg = baseConfig();
|
||||
cfg["depth_cam"]["attach_distance"] = -.01;
|
||||
expectThrow(cfg);
|
||||
cfg = baseConfig();
|
||||
cfg["depth_cam"]["attach_distance"] = 1.2; // near and far bands would meet: (2.5 - .15) / 2
|
||||
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);
|
||||
}
|
||||
280
test/direction_field_test.cpp
Normal file
280
test/direction_field_test.cpp
Normal file
@@ -0,0 +1,280 @@
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
namespace
|
||||
{
|
||||
DirectionGeometry geometry()
|
||||
{
|
||||
return {4, 4, 1.0, 0.0, 0.0, "map"};
|
||||
}
|
||||
|
||||
robot_nav_msgs::OccupancyGrid grid()
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid g;
|
||||
g.header.frame_id = "/map";
|
||||
g.info.width = 4;
|
||||
g.info.height = 4;
|
||||
g.info.resolution = 1;
|
||||
g.data.assign(16, 0);
|
||||
return g;
|
||||
}
|
||||
|
||||
auto field(const robot_nav_msgs::OccupancyGrid& g)
|
||||
{
|
||||
return DirectionField::create(g, geometry(), M_PI / 2.0);
|
||||
}
|
||||
|
||||
using Cell = std::pair<int64_t, int64_t>;
|
||||
std::vector<Cell> cells(double x0, double y0, double x1, double y1)
|
||||
{
|
||||
std::vector<Cell> out;
|
||||
EXPECT_TRUE(traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y)
|
||||
{
|
||||
out.emplace_back(x, y);
|
||||
return true;
|
||||
}));
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(DirectionContract, CodesAndSizes)
|
||||
{
|
||||
auto g = grid();
|
||||
ASSERT_TRUE(field(g));
|
||||
EXPECT_FALSE(field(g)->hasConstraints());
|
||||
for (int code = 0; code <= 8; ++code)
|
||||
{
|
||||
g.data[0] = code;
|
||||
auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
EXPECT_EQ(f->code(0, 0), code);
|
||||
}
|
||||
for (int code : {-128, -2, -1, 9, 100, 127})
|
||||
{
|
||||
g.data[0] = code;
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kCode);
|
||||
}
|
||||
g.data.clear();
|
||||
auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
EXPECT_FALSE(f->hasConstraints());
|
||||
EXPECT_EQ(f->code(3, 3), 0);
|
||||
g.data.assign(15, 0);
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kSize);
|
||||
g.info.width = UINT32_MAX;
|
||||
g.info.height = UINT32_MAX;
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kOverflow);
|
||||
}
|
||||
|
||||
TEST(DirectionContract, CheckedCellAccess)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data[15] = 8;
|
||||
const auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
uint8_t code = 99;
|
||||
EXPECT_TRUE(f->codeAt(3, 3, &code));
|
||||
EXPECT_EQ(code, 8);
|
||||
EXPECT_TRUE(f->codeAt(0, 0, &code));
|
||||
EXPECT_EQ(code, 0);
|
||||
code = 99;
|
||||
EXPECT_FALSE(f->codeAt(-1, 0, &code));
|
||||
EXPECT_FALSE(f->codeAt(0, -1, &code));
|
||||
EXPECT_FALSE(f->codeAt(4, 0, &code));
|
||||
EXPECT_FALSE(f->codeAt(0, 4, &code));
|
||||
EXPECT_FALSE(f->codeAt(INT64_MAX, INT64_MAX, &code));
|
||||
EXPECT_FALSE(f->codeAt(0, 0, nullptr));
|
||||
EXPECT_EQ(code, 99);
|
||||
g.data.clear();
|
||||
const auto empty = field(g);
|
||||
ASSERT_TRUE(empty);
|
||||
EXPECT_TRUE(empty->codeAt(3, 3, &code));
|
||||
EXPECT_EQ(code, 0);
|
||||
code = 99;
|
||||
EXPECT_FALSE(empty->codeAt(4, 3, &code));
|
||||
EXPECT_EQ(code, 99);
|
||||
}
|
||||
|
||||
TEST(DirectionContract, GeometryAndNonFinite)
|
||||
{
|
||||
auto g = grid();
|
||||
EXPECT_TRUE(field(g));
|
||||
g.header.frame_id = "";
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kFrame);
|
||||
g.header.frame_id = "other";
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.width = 3;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.resolution = 0.5;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.position.x = 0.01;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.position.y = 0.01;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.orientation.z = 0.1;
|
||||
g.info.origin.orientation.w = 1;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.orientation.w = 1;
|
||||
EXPECT_TRUE(field(g));
|
||||
g.info.origin.orientation.w = -1;
|
||||
EXPECT_TRUE(field(g));
|
||||
g = grid();
|
||||
EXPECT_TRUE(field(g)); // Default zero quaternion.
|
||||
g.info.origin.position.x = std::numeric_limits<double>::quiet_NaN();
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.resolution = std::numeric_limits<float>::infinity();
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.position.z = std::numeric_limits<double>::infinity();
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.orientation.w = std::numeric_limits<double>::quiet_NaN();
|
||||
EXPECT_FALSE(field(g));
|
||||
}
|
||||
|
||||
TEST(DirectionRule, AllDirectionsAndBoundaries)
|
||||
{
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data.assign(16, k + 1);
|
||||
auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
const double x = 1.5;
|
||||
const double y = 1.5;
|
||||
EXPECT_EQ(f->checkSegment(x, y, x + 0.2 * vx[k], y + 0.2 * vy[k]), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x - 0.2 * vx[k], y - 0.2 * vy[k]), SegmentResult::kViolation);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x - 0.2 * vy[k], y + 0.2 * vx[k]), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x + 0.2 * vy[k], y - 0.2 * vx[k]), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x, y), SegmentResult::kAllowed);
|
||||
}
|
||||
auto g = grid();
|
||||
g.data.assign(16, 1);
|
||||
auto f = field(g);
|
||||
EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 - 1e-6, 1.7), SegmentResult::kViolation);
|
||||
EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 + 1e-6, 1.7), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(allowedDirectionMask(-1e-11, 1.0, M_PI / 2.0) & 1, 1);
|
||||
EXPECT_EQ(allowedDirectionMask(-1e-6, 1.0, M_PI / 2.0) & 1, 0);
|
||||
}
|
||||
|
||||
TEST(DirectionRule, MaskMatchesDotProducts)
|
||||
{
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
for (int x = -12; x <= 12; ++x)
|
||||
{
|
||||
for (int y = -12; y <= 12; ++y)
|
||||
{
|
||||
auto mask = allowedDirectionMask(x, y, M_PI / 2.0);
|
||||
for (int k = 0; k < 8; ++k)
|
||||
EXPECT_EQ(bool(mask & (1u << k)), vx[k] * x + vy[k] * y >= 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(DirectionRule, RightAngleMatchesLegacySweep)
|
||||
{
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
const auto check = [&](double dx, double dy)
|
||||
{
|
||||
uint8_t reference = 0;
|
||||
const long double x = dx, y = dy;
|
||||
const long double tolerance = 1e-9L * (std::abs(x) + std::abs(y));
|
||||
for (int k = 0; k < 8; ++k)
|
||||
if (vx[k] * x + vy[k] * y >= -tolerance)
|
||||
reference |= uint8_t(1u << k);
|
||||
EXPECT_EQ(allowedDirectionMask(dx, dy, M_PI / 2.0), reference) << dx << "," << dy;
|
||||
};
|
||||
for (double magnitude : {1e-100, 0.01, 1.0, 1e100})
|
||||
{
|
||||
for (int degree = 0; degree < 360; ++degree)
|
||||
check(magnitude * std::cos(degree * M_PI / 180.0), magnitude * std::sin(degree * M_PI / 180.0));
|
||||
for (int k = 0; k < 8; ++k)
|
||||
check(magnitude * vx[k], magnitude * vy[k]);
|
||||
check(-1.0000000005e-9 * magnitude, magnitude); // Near the legacy tolerance boundary.
|
||||
}
|
||||
check(0, 0);
|
||||
EXPECT_EQ(allowedDirectionMask(std::numeric_limits<double>::infinity(), 0, M_PI / 2.0), 0);
|
||||
EXPECT_EQ(allowedDirectionMask(0, std::numeric_limits<double>::quiet_NaN(), M_PI / 2.0), 0);
|
||||
}
|
||||
|
||||
TEST(DirectionRule, ConfigurableAngularBoundaries)
|
||||
{
|
||||
const auto mask = allowedDirectionMask(1, 0.5, M_PI / 4.0);
|
||||
EXPECT_NE(mask & (1u << 0), 0);
|
||||
EXPECT_NE(mask & (1u << 1), 0);
|
||||
EXPECT_EQ(mask & (1u << 2), 0);
|
||||
const auto boundary = allowedDirectionMask(1, 1, M_PI / 4.0);
|
||||
EXPECT_NE(boundary & (1u << 0), 0);
|
||||
EXPECT_NE(boundary & (1u << 2), 0);
|
||||
EXPECT_EQ(allowedDirectionMask(1, 1.01, M_PI / 4.0) & 1u, 0);
|
||||
EXPECT_EQ(allowedDirectionMask(0, 1, M_PI / 6.0) & 1u, 0);
|
||||
EXPECT_EQ(allowedDirectionMask(0, 0, M_PI / 6.0), 255);
|
||||
}
|
||||
|
||||
TEST(DirectionRule, FieldUsesItsDeviationForCrossing)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data.assign(16, 3); // +Y zone, crossed along +X.
|
||||
const auto wide = DirectionField::create(g, geometry(), M_PI / 2.0);
|
||||
const auto narrow = DirectionField::create(g, geometry(), M_PI / 4.0);
|
||||
ASSERT_TRUE(wide && narrow);
|
||||
EXPECT_DOUBLE_EQ(narrow->maxDeviationRad(), M_PI / 4.0);
|
||||
EXPECT_EQ(wide->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(narrow->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kViolation);
|
||||
}
|
||||
|
||||
TEST(DirectionDDA, OwnedEdgesCornersEndpointsAndReverse)
|
||||
{
|
||||
EXPECT_EQ(cells(1, 0.2, 1, 2.8), (std::vector<Cell>{{1, 0}, {1, 1}, {1, 2}}));
|
||||
EXPECT_EQ(cells(1, 2.8, 1, 0.2), (std::vector<Cell>{{1, 2}, {1, 1}, {1, 0}}));
|
||||
EXPECT_EQ(cells(0.5, 0.5, 2.5, 2.5), (std::vector<Cell>{{0, 0}, {1, 1}, {2, 2}}));
|
||||
EXPECT_EQ(cells(0, 0, 6, 4),
|
||||
(std::vector<Cell>{{0, 0}, {1, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 2}, {4, 3}, {5, 3}}));
|
||||
EXPECT_EQ(cells(0.5, 0.5, 2.0, 0.5), (std::vector<Cell>{{0, 0}, {1, 0}}));
|
||||
EXPECT_EQ(cells(2.0, 0.5, 0.5, 0.5), (std::vector<Cell>{{1, 0}, {0, 0}}));
|
||||
for (auto p : std::vector<std::vector<double>>{{0.2, 0.3, 3.8, 2.7}, {1, 0.2, 1, 3.5}, {0.5, 0.5, 3.5, 3.5}})
|
||||
{
|
||||
auto a = cells(p[0], p[1], p[2], p[3]);
|
||||
auto b = cells(p[2], p[3], p[0], p[1]);
|
||||
std::reverse(b.begin(), b.end());
|
||||
EXPECT_EQ(a, b);
|
||||
EXPECT_EQ(std::set<Cell>(a.begin(), a.end()).size(), a.size());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(DirectionDDA, QueriesCrossZonesAndRejectOutside)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data[1] = 5;
|
||||
g.data[2] = 5;
|
||||
auto f = field(g);
|
||||
SegmentViolation v{};
|
||||
EXPECT_EQ(f->checkSegment(0.2, 0.5, 3.5, 0.5, &v), SegmentResult::kViolation);
|
||||
EXPECT_EQ(v.x, 1u);
|
||||
EXPECT_EQ(v.code, 5);
|
||||
EXPECT_EQ(f->checkSegment(3.5, 0.5, 0.2, 0.5), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(0.2, 0.5, 1.0, 0.5), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(0.2, 0.5, 4.0, 0.5), SegmentResult::kOutOfGrid);
|
||||
EXPECT_EQ(f->checkSegment(-0.1, 0.5, 0.1, 0.5), SegmentResult::kOutOfGrid);
|
||||
EXPECT_EQ(f->checkSegment(4, 0.5, 4, 0.5), SegmentResult::kOutOfGrid);
|
||||
}
|
||||
367
test/directional_layer_test.cpp
Normal file
367
test/directional_layer_test.cpp
Normal file
@@ -0,0 +1,367 @@
|
||||
#include <robot_costmap_2d/directional_layer.h>
|
||||
#include <robot_costmap_2d/critical_layer.h>
|
||||
#include <robot_costmap_2d/static_layer.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
namespace
|
||||
{
|
||||
class LayerTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
std::string directory_;
|
||||
std::string old_env_;
|
||||
bool had_env_ = false;
|
||||
tf3::BufferCore tf_{tf3::Duration(10.0)};
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
const char* old = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
if (old)
|
||||
{
|
||||
had_env_ = true;
|
||||
old_env_ = old;
|
||||
}
|
||||
char pattern[] = "/tmp/direction-layer-test-XXXXXX";
|
||||
char* path = mkdtemp(pattern);
|
||||
ASSERT_NE(path, nullptr);
|
||||
directory_ = path;
|
||||
std::filesystem::create_directory(directory_ + "/config");
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", directory_.c_str(), 1), 0);
|
||||
config(true);
|
||||
std::ofstream static_config(directory_ + "/config/static_layer_params.yaml");
|
||||
static_config << "static_layer:\n enabled: true\n map_topic: map\n"
|
||||
" first_map_only: false\n subscribe_to_updates: true\n";
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
if (had_env_)
|
||||
setenv("PNKX_NAV_CORE_CONFIG_DIR", old_env_.c_str(), 1);
|
||||
else
|
||||
unsetenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::filesystem::remove_all(directory_);
|
||||
}
|
||||
|
||||
void config(bool enabled, double max_deviation_deg = 90.0)
|
||||
{
|
||||
std::ofstream out(directory_ + "/config/directional_layer_params.yaml");
|
||||
out << "directional_layer:\n enabled: " << (enabled ? "true" : "false")
|
||||
<< "\n map_topic: map\n direction_topic: direction_map\n max_deviation_deg: " << max_deviation_deg
|
||||
<< "\n debug_state: false\n";
|
||||
}
|
||||
|
||||
robot_nav_msgs::OccupancyGrid grid()
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid g;
|
||||
g.header.frame_id = "map";
|
||||
g.info.width = 4;
|
||||
g.info.height = 4;
|
||||
g.info.resolution = 1;
|
||||
g.data.assign(16, 0);
|
||||
return g;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LayerTest, StaticAndCriticalReadinessTracksWrites)
|
||||
{
|
||||
for (bool critical : {false, true})
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
boost::shared_ptr<Layer> layer = critical
|
||||
? boost::static_pointer_cast<Layer>(boost::make_shared<CriticalLayer>())
|
||||
: boost::static_pointer_cast<Layer>(boost::make_shared<StaticLayer>());
|
||||
layer->initialize(&master, critical ? "critical" : "static", &tf_);
|
||||
master.addPlugin(layer);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
EXPECT_FALSE(master.isCurrent());
|
||||
|
||||
robot_map_msgs::OccupancyGridUpdate early_update;
|
||||
early_update.x = early_update.y = 0;
|
||||
early_update.width = early_update.height = 1;
|
||||
early_update.data.assign(1, 100);
|
||||
layer->dataCallBack(early_update, "map_updates");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
|
||||
auto map = grid();
|
||||
map.data[0] = 100;
|
||||
layer->dataCallBack(map, "map");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->updateCosts(*master.getCostmap(), 0, 0, 0, 0);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
|
||||
layer->reset();
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_TRUE(master.isCurrent());
|
||||
EXPECT_NE(master.getCostmap()->getCost(0, 0), FREE_SPACE);
|
||||
|
||||
map.data[1] = 100;
|
||||
map.data[15] = 100;
|
||||
layer->dataCallBack(map, "map");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
|
||||
robot_map_msgs::OccupancyGridUpdate update;
|
||||
update.x = 0;
|
||||
update.y = 0;
|
||||
update.width = 1;
|
||||
update.height = 1;
|
||||
update.data.assign(1, 100);
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_EQ(master.getCostmap()->getCost(3, 3), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
|
||||
|
||||
update.x = 0;
|
||||
update.y = 3;
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
update.x = 3;
|
||||
update.y = 0;
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_EQ(master.getCostmap()->getCost(0, 3), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(3, 0), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
|
||||
|
||||
update.x = -1;
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->dataCallBack(map, "map");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, InvalidMaxDeviationThrows)
|
||||
{
|
||||
for (double degrees : {0.0, 180.0, -5.0, 200.0})
|
||||
{
|
||||
config(true, degrees);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
EXPECT_THROW(layer.initialize(&master, "directional", &tf_), std::runtime_error) << degrees;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, ReadyFieldCarriesConfiguredDeviation)
|
||||
{
|
||||
config(true, 45.0);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
ASSERT_NO_THROW(layer.initialize(&master, "directional", &tf_));
|
||||
auto g = grid();
|
||||
layer.dataCallBack(g, "map");
|
||||
layer.dataCallBack(g, "direction_map");
|
||||
const auto snapshot = layer.directionSnapshot();
|
||||
ASSERT_EQ(snapshot.state, DirectionFieldState::kReady);
|
||||
ASSERT_TRUE(snapshot.field);
|
||||
EXPECT_DOUBLE_EQ(snapshot.field->maxDeviationRad(), M_PI / 4.0);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, LifecycleAndProvider)
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kDisabled);
|
||||
auto layer = boost::make_shared<DirectionalLayer>();
|
||||
layer->initialize(&master, "directional", &tf_);
|
||||
master.addPlugin(layer);
|
||||
auto g = grid();
|
||||
auto s = master.getDirectionFieldSnapshot();
|
||||
EXPECT_EQ(s.state, DirectionFieldState::kPending);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
EXPECT_EQ(layer->directionSnapshot().generation, s.generation);
|
||||
double min_x = 1;
|
||||
double min_y = 2;
|
||||
double max_x = 3;
|
||||
double max_y = 4;
|
||||
layer->updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y);
|
||||
EXPECT_DOUBLE_EQ(min_x, 1);
|
||||
EXPECT_DOUBLE_EQ(min_y, 2);
|
||||
EXPECT_DOUBLE_EQ(max_x, 3);
|
||||
EXPECT_DOUBLE_EQ(max_y, 4);
|
||||
auto& costs = *master.getCostmap();
|
||||
costs.setCost(0, 0, 42);
|
||||
layer->updateCosts(costs, 0, 0, 4, 4);
|
||||
EXPECT_EQ(costs.getCost(0, 0), 42);
|
||||
layer->dataCallBack(7, "map");
|
||||
layer->dataCallBack(g, "other_topic");
|
||||
EXPECT_EQ(layer->directionSnapshot().generation, s.generation);
|
||||
layer->dataCallBack(g, "/map");
|
||||
s = layer->directionSnapshot();
|
||||
EXPECT_EQ(s.state, DirectionFieldState::kPending);
|
||||
g.data[0] = 1;
|
||||
layer->dataCallBack(g, "/direction_map");
|
||||
auto ready = master.getDirectionFieldSnapshot();
|
||||
EXPECT_EQ(ready.state, DirectionFieldState::kReady);
|
||||
ASSERT_TRUE(ready.field);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_GT(ready.generation, s.generation);
|
||||
g.data[0] = 100;
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
s = layer->directionSnapshot();
|
||||
EXPECT_EQ(s.generation, ready.generation);
|
||||
EXPECT_EQ(s.field, ready.field);
|
||||
layer->reset();
|
||||
EXPECT_EQ(layer->directionSnapshot().field, ready.field);
|
||||
g.data.clear();
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
s = layer->directionSnapshot();
|
||||
ASSERT_TRUE(s.field);
|
||||
EXPECT_FALSE(s.field->hasConstraints());
|
||||
EXPECT_GT(s.generation, ready.generation);
|
||||
layer->dataCallBack(g, "map");
|
||||
s = layer->directionSnapshot();
|
||||
EXPECT_EQ(s.state, DirectionFieldState::kPending);
|
||||
EXPECT_FALSE(s.field);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
layer->matchSize();
|
||||
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
master.getCostmap()->resizeMap(3, 3, 1, 0, 0);
|
||||
layer->reset();
|
||||
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
master.resizeMap(3, 3, 1, 0, 0);
|
||||
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, DisabledAndMultipleProviders)
|
||||
{
|
||||
config(false);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
auto disabled = boost::make_shared<DirectionalLayer>();
|
||||
disabled->initialize(&master, "directional", &tf_);
|
||||
master.addPlugin(disabled);
|
||||
EXPECT_TRUE(disabled->isCurrent());
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kDisabled);
|
||||
config(true);
|
||||
auto a = boost::make_shared<DirectionalLayer>();
|
||||
a->initialize(&master, "first", &tf_);
|
||||
master.addPlugin(a);
|
||||
auto b = boost::make_shared<DirectionalLayer>();
|
||||
b->initialize(&master, "second", &tf_);
|
||||
master.addPlugin(b);
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, RollingCostmapStaysPending)
|
||||
{
|
||||
LayeredCostmap master("map", true, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
layer.initialize(&master, "directional", &tf_);
|
||||
auto g = grid();
|
||||
layer.dataCallBack(g, "map");
|
||||
layer.dataCallBack(g, "direction_map");
|
||||
EXPECT_EQ(layer.directionSnapshot().state, DirectionFieldState::kPending);
|
||||
EXPECT_FALSE(layer.isCurrent());
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, StaticMapCallbackDoesNotWaitForMasterMutex)
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
layer.initialize(&master, "directional", &tf_);
|
||||
auto g = grid();
|
||||
std::mutex completion_mutex;
|
||||
std::condition_variable completion;
|
||||
bool done = false;
|
||||
bool completed_while_locked = false;
|
||||
std::thread callback;
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> master_lock(*master.getCostmap()->getMutex());
|
||||
callback = std::thread([&]
|
||||
{
|
||||
layer.dataCallBack(g, "map");
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(completion_mutex);
|
||||
done = true;
|
||||
}
|
||||
completion.notify_one();
|
||||
});
|
||||
std::unique_lock<std::mutex> lock(completion_mutex);
|
||||
completed_while_locked = completion.wait_for(lock, std::chrono::seconds(2), [&] { return done; });
|
||||
}
|
||||
callback.join();
|
||||
EXPECT_TRUE(completed_while_locked);
|
||||
EXPECT_EQ(layer.directionSnapshot().state, DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, OldSnapshotSurvivesConcurrentReplacement)
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
auto layer = boost::make_shared<DirectionalLayer>();
|
||||
layer->initialize(&master, "directional", &tf_);
|
||||
master.addPlugin(layer);
|
||||
auto g = grid();
|
||||
g.data[0] = 1;
|
||||
layer->dataCallBack(g, "map");
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
auto old = master.getDirectionFieldSnapshot();
|
||||
ASSERT_TRUE(old.field);
|
||||
std::atomic<bool> start{false};
|
||||
std::atomic<bool> ok{true};
|
||||
std::thread reader([&]
|
||||
{
|
||||
while (!start.load())
|
||||
{
|
||||
}
|
||||
for (int i = 0; i < 1000; ++i)
|
||||
{
|
||||
auto s = master.getDirectionFieldSnapshot();
|
||||
if (!s.field || old.field->code(0, 0) != 1)
|
||||
ok = false;
|
||||
}
|
||||
});
|
||||
std::thread updater([&]
|
||||
{
|
||||
while (!start.load())
|
||||
{
|
||||
}
|
||||
for (int i = 0; i < 1000; ++i)
|
||||
layer->updateBounds(0, 0, 0, nullptr, nullptr, nullptr, nullptr);
|
||||
});
|
||||
start = true;
|
||||
g.data[0] = 3;
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
reader.join();
|
||||
updater.join();
|
||||
EXPECT_TRUE(ok.load());
|
||||
EXPECT_EQ(old.field->code(0, 0), 1);
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().field->code(0, 0), 3);
|
||||
}
|
||||
} // namespace
|
||||
39
test/obstacle_layer_scan_ranges_test.cpp
Normal file
39
test/obstacle_layer_scan_ranges_test.cpp
Normal file
@@ -0,0 +1,39 @@
|
||||
#include <robot_costmap_2d/obstacle_layer.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
TEST(ObstacleLayerScanRanges, FlagsIndependentlyReplaceOnlyEnabledNoReturns)
|
||||
{
|
||||
const float inf = std::numeric_limits<float>::infinity();
|
||||
const float nan = std::numeric_limits<float>::quiet_NaN();
|
||||
for (bool inf_is_valid : {false, true})
|
||||
{
|
||||
for (bool zero_is_valid : {false, true})
|
||||
{
|
||||
SCOPED_TRACE(::testing::Message() << "inf=" << inf_is_valid << " zero=" << zero_is_valid);
|
||||
robot_sensor_msgs::LaserScan scan;
|
||||
scan.range_min = 0.2f;
|
||||
scan.range_max = 10.0f;
|
||||
scan.ranges = {0.0f, -0.0f, inf, -inf, nan, -1.0f, 0.1f, 1.0f};
|
||||
robot_costmap_2d::replaceNoReturnRanges(scan, inf_is_valid, zero_is_valid);
|
||||
|
||||
const float replacement = scan.range_max - 0.0001f;
|
||||
EXPECT_FLOAT_EQ(scan.ranges[0], zero_is_valid ? replacement : 0.0f);
|
||||
EXPECT_FLOAT_EQ(scan.ranges[1], zero_is_valid ? replacement : -0.0f);
|
||||
if (!zero_is_valid)
|
||||
EXPECT_TRUE(std::signbit(scan.ranges[1]));
|
||||
EXPECT_FLOAT_EQ(scan.ranges[2], inf_is_valid ? replacement : inf);
|
||||
EXPECT_EQ(scan.ranges[3], -inf);
|
||||
EXPECT_TRUE(std::isnan(scan.ranges[4]));
|
||||
EXPECT_FLOAT_EQ(scan.ranges[5], -1.0f);
|
||||
EXPECT_FLOAT_EQ(scan.ranges[6], 0.1f);
|
||||
EXPECT_FLOAT_EQ(scan.ranges[7], 1.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
569
test/reference_graph_test.cpp
Normal file
569
test/reference_graph_test.cpp
Normal file
@@ -0,0 +1,569 @@
|
||||
#include <robot_costmap_2d/reference_graph.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr double kExactM = 1e-9;
|
||||
|
||||
/** Expected output written by the Python prototype, oneway_eval/r12_export_cpp_text.py. */
|
||||
struct Fixture
|
||||
{
|
||||
DirectionGeometry geometry{};
|
||||
ReferenceGraphParams params;
|
||||
double half_x = 0.0, half_y = 0.0;
|
||||
std::vector<uint8_t> cost, direction;
|
||||
std::vector<int64_t> skeleton;
|
||||
std::vector<ReferencePoint> nodes;
|
||||
struct Edge
|
||||
{
|
||||
uint32_t from, to;
|
||||
std::vector<ReferencePoint> points;
|
||||
};
|
||||
std::vector<Edge> edges;
|
||||
std::vector<ReferenceLane> lanes;
|
||||
};
|
||||
|
||||
std::vector<uint8_t> readRuns(std::istream& in, const std::string& name)
|
||||
{
|
||||
std::string key;
|
||||
std::size_t runs = 0;
|
||||
in >> key >> runs;
|
||||
if (key != name)
|
||||
throw std::runtime_error("expected " + name + ", got " + key);
|
||||
std::vector<uint8_t> out;
|
||||
for (std::size_t i = 0; i < runs; ++i)
|
||||
{
|
||||
int value = 0;
|
||||
std::size_t count = 0;
|
||||
in >> value >> count;
|
||||
out.insert(out.end(), count, static_cast<uint8_t>(value));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Fixture loadFixture(const std::string& path)
|
||||
{
|
||||
std::ifstream in(path);
|
||||
if (!in)
|
||||
throw std::runtime_error("cannot open " + path);
|
||||
Fixture f;
|
||||
std::string key;
|
||||
int version = 0;
|
||||
in >> key >> version;
|
||||
if (key != "reference_graph_fixture" || version != 1)
|
||||
throw std::runtime_error("bad fixture header in " + path);
|
||||
f.geometry.frame_id = "map";
|
||||
in >> key >> f.geometry.width >> f.geometry.height;
|
||||
in >> key >> f.geometry.resolution;
|
||||
in >> key >> f.geometry.origin_x >> f.geometry.origin_y;
|
||||
in >> key >> f.params.min_clearance_m >> f.params.ridge_min_separation_m >> f.params.spur_min_length_m >>
|
||||
f.params.lane_offset_step_m >> f.half_x >> f.half_y;
|
||||
f.cost = readRuns(in, "cost");
|
||||
f.direction = readRuns(in, "direction");
|
||||
std::size_t count = 0;
|
||||
in >> key >> count;
|
||||
f.skeleton.resize(count);
|
||||
for (int64_t& cell : f.skeleton)
|
||||
in >> cell;
|
||||
in >> key >> count;
|
||||
f.nodes.resize(count);
|
||||
for (ReferencePoint& node : f.nodes)
|
||||
in >> node.x >> node.y;
|
||||
in >> key >> count;
|
||||
f.edges.resize(count);
|
||||
for (Fixture::Edge& edge : f.edges)
|
||||
{
|
||||
std::size_t points = 0;
|
||||
in >> edge.from >> edge.to >> points;
|
||||
edge.points.resize(points);
|
||||
for (ReferencePoint& point : edge.points)
|
||||
in >> point.x >> point.y;
|
||||
}
|
||||
in >> key >> count;
|
||||
f.lanes.resize(count);
|
||||
for (ReferenceLane& lane : f.lanes)
|
||||
{
|
||||
int direction = 0;
|
||||
in >> direction >> lane.entry.x >> lane.entry.y >> lane.exit.x >> lane.exit.y >> lane.length_m >>
|
||||
lane.offset_from_centre_m;
|
||||
lane.direction_index = static_cast<uint8_t>(direction);
|
||||
}
|
||||
if (!in)
|
||||
throw std::runtime_error("truncated fixture " + path);
|
||||
return f;
|
||||
}
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> rectangle(double half_x, double half_y)
|
||||
{
|
||||
std::vector<robot_geometry_msgs::Point> out(4);
|
||||
out[0].x = half_x, out[0].y = half_y;
|
||||
out[1].x = -half_x, out[1].y = half_y;
|
||||
out[2].x = -half_x, out[2].y = -half_y;
|
||||
out[3].x = half_x, out[3].y = -half_y;
|
||||
return out;
|
||||
}
|
||||
|
||||
ReferenceGridView viewOf(const Fixture& f)
|
||||
{
|
||||
ReferenceGridView view;
|
||||
view.cost = f.cost.data();
|
||||
view.geometry = f.geometry;
|
||||
const bool zones = std::any_of(f.direction.begin(), f.direction.end(), [](uint8_t code) { return code != 0; });
|
||||
view.direction_codes = zones ? f.direction.data() : nullptr;
|
||||
return view;
|
||||
}
|
||||
|
||||
double pointToSegment(const ReferencePoint& p, const ReferencePoint& a, const ReferencePoint& b)
|
||||
{
|
||||
const double dx = b.x - a.x, dy = b.y - a.y;
|
||||
const double squared = dx * dx + dy * dy;
|
||||
const double t = squared <= 0.0 ? 0.0 : std::min(1.0, std::max(0.0, ((p.x - a.x) * dx + (p.y - a.y) * dy) / squared));
|
||||
return std::hypot(p.x - a.x - t * dx, p.y - a.y - t * dy);
|
||||
}
|
||||
|
||||
double pointToPolyline(const ReferencePoint& p, const std::vector<ReferencePoint>& line)
|
||||
{
|
||||
double best = std::numeric_limits<double>::infinity();
|
||||
for (std::size_t i = 0; i + 1 < line.size(); ++i)
|
||||
best = std::min(best, pointToSegment(p, line[i], line[i + 1]));
|
||||
return best;
|
||||
}
|
||||
|
||||
double polylineLength(const std::vector<ReferencePoint>& line)
|
||||
{
|
||||
double total = 0.0;
|
||||
for (std::size_t i = 0; i + 1 < line.size(); ++i)
|
||||
total += std::hypot(line[i + 1].x - line[i].x, line[i + 1].y - line[i].y);
|
||||
return total;
|
||||
}
|
||||
|
||||
std::vector<std::pair<double, double>> sortedPoints(const std::vector<ReferencePoint>& points)
|
||||
{
|
||||
std::vector<std::pair<double, double>> out;
|
||||
out.reserve(points.size());
|
||||
for (const ReferencePoint& point : points)
|
||||
out.emplace_back(point.x, point.y);
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Both sides read the same chain of cells, but a walk from the other end keeps different cells.
|
||||
* So edges are matched by end nodes and compared as polylines, within one and a half cells. */
|
||||
void expectEdgesMatch(const Fixture& f, const ReferenceGraph& graph)
|
||||
{
|
||||
using Ends = std::tuple<double, double, double, double>;
|
||||
const auto ends = [](const ReferencePoint& a, const ReferencePoint& b) {
|
||||
return a.x < b.x || (a.x == b.x && a.y < b.y) ? Ends(a.x, a.y, b.x, b.y) : Ends(b.x, b.y, a.x, a.y);
|
||||
};
|
||||
std::vector<std::pair<Ends, std::size_t>> expected, actual;
|
||||
for (std::size_t i = 0; i < f.edges.size(); ++i)
|
||||
expected.emplace_back(ends(f.nodes[f.edges[i].from], f.nodes[f.edges[i].to]), i);
|
||||
for (std::size_t i = 0; i < graph.edges.size(); ++i)
|
||||
actual.emplace_back(ends(graph.nodes[graph.edges[i].from], graph.nodes[graph.edges[i].to]), i);
|
||||
std::sort(expected.begin(), expected.end());
|
||||
std::sort(actual.begin(), actual.end());
|
||||
ASSERT_EQ(expected.size(), actual.size());
|
||||
|
||||
const double tolerance = 1.5 * f.geometry.resolution;
|
||||
for (std::size_t i = 0; i < expected.size(); ++i)
|
||||
{
|
||||
ASSERT_EQ(expected[i].first, actual[i].first) << "edge end nodes differ at sorted position " << i;
|
||||
// Parallel edges share their end nodes: pick the closest one among them.
|
||||
const Fixture::Edge& python = f.edges[expected[i].second];
|
||||
double best = std::numeric_limits<double>::infinity();
|
||||
for (std::size_t j = i; j < actual.size() && actual[j].first == expected[i].first; ++j)
|
||||
{
|
||||
double worst = 0.0;
|
||||
for (const ReferencePoint& point : graph.edges[actual[j].second].points)
|
||||
worst = std::max(worst, pointToPolyline(point, python.points));
|
||||
best = std::min(best, worst);
|
||||
}
|
||||
EXPECT_LE(best, tolerance) << "edge " << i << " leaves the Python polyline";
|
||||
const VoronoiEdge& edge = graph.edges[actual[i].second];
|
||||
EXPECT_NEAR(edge.length_m, polylineLength(edge.points), kExactM);
|
||||
}
|
||||
}
|
||||
|
||||
void expectLanesMatch(const Fixture& f, const ReferenceGraph& graph)
|
||||
{
|
||||
const auto order = [](const ReferenceLane& a, const ReferenceLane& b) {
|
||||
return std::make_tuple(a.direction_index, a.entry.x, a.entry.y) < std::make_tuple(b.direction_index, b.entry.x, b.entry.y);
|
||||
};
|
||||
std::vector<ReferenceLane> expected = f.lanes, actual = graph.lanes;
|
||||
std::sort(expected.begin(), expected.end(), order);
|
||||
std::sort(actual.begin(), actual.end(), order);
|
||||
ASSERT_EQ(expected.size(), actual.size());
|
||||
for (std::size_t i = 0; i < expected.size(); ++i)
|
||||
{
|
||||
EXPECT_EQ(expected[i].direction_index, actual[i].direction_index);
|
||||
EXPECT_NEAR(expected[i].entry.x, actual[i].entry.x, kExactM);
|
||||
EXPECT_NEAR(expected[i].entry.y, actual[i].entry.y, kExactM);
|
||||
EXPECT_NEAR(expected[i].exit.x, actual[i].exit.x, kExactM);
|
||||
EXPECT_NEAR(expected[i].exit.y, actual[i].exit.y, kExactM);
|
||||
EXPECT_NEAR(expected[i].length_m, actual[i].length_m, kExactM);
|
||||
EXPECT_NEAR(expected[i].offset_from_centre_m, actual[i].offset_from_centre_m, kExactM);
|
||||
}
|
||||
}
|
||||
|
||||
/** Run steps 1 and 2 on a fixture and compare every stage. Returns step times [ms] for the timing test. */
|
||||
std::pair<double, double> expectParity(const Fixture& f)
|
||||
{
|
||||
const ReferenceGridView view = viewOf(f);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params);
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
const ReferenceGraph graph = buildReferenceGraph(view, skeleton, rectangle(f.half_x, f.half_y), f.params);
|
||||
const auto t2 = std::chrono::steady_clock::now();
|
||||
|
||||
std::vector<int64_t> cells;
|
||||
for (std::size_t i = 0; i < skeleton.mask.size(); ++i)
|
||||
if (skeleton.mask[i] != 0)
|
||||
cells.push_back(static_cast<int64_t>(i));
|
||||
std::vector<int64_t> only_cpp, only_python;
|
||||
std::set_difference(cells.begin(), cells.end(), f.skeleton.begin(), f.skeleton.end(), std::back_inserter(only_cpp));
|
||||
std::set_difference(f.skeleton.begin(), f.skeleton.end(), cells.begin(), cells.end(), std::back_inserter(only_python));
|
||||
EXPECT_TRUE(only_cpp.empty()) << only_cpp.size() << " skeleton cells only in C++";
|
||||
EXPECT_TRUE(only_python.empty()) << only_python.size() << " skeleton cells only in Python";
|
||||
|
||||
const std::vector<std::pair<double, double>> expected_nodes = sortedPoints(f.nodes), actual_nodes = sortedPoints(graph.nodes);
|
||||
EXPECT_EQ(expected_nodes.size(), actual_nodes.size());
|
||||
for (std::size_t i = 0; i < std::min(expected_nodes.size(), actual_nodes.size()); ++i)
|
||||
{
|
||||
EXPECT_NEAR(expected_nodes[i].first, actual_nodes[i].first, kExactM);
|
||||
EXPECT_NEAR(expected_nodes[i].second, actual_nodes[i].second, kExactM);
|
||||
}
|
||||
expectEdgesMatch(f, graph);
|
||||
expectLanesMatch(f, graph);
|
||||
EXPECT_EQ(graph.static_cost, f.cost);
|
||||
EXPECT_EQ(graph.clearance_mm, skeleton.clearance_mm);
|
||||
|
||||
const auto ms = [](std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) {
|
||||
return std::chrono::duration<double, std::milli>(b - a).count();
|
||||
};
|
||||
return { ms(t0, t1), ms(t1, t2) };
|
||||
}
|
||||
|
||||
std::string packagedFixture(const std::string& name)
|
||||
{
|
||||
return std::string(ROBOT_COSTMAP_2D_DIR) + "/test/data/reference_graph/" + name + ".fixture";
|
||||
}
|
||||
|
||||
DirectionGeometry geometryOf(uint32_t width, uint32_t height)
|
||||
{
|
||||
return { width, height, 0.05, 0.0, 0.0, "map" };
|
||||
}
|
||||
|
||||
/** Free corridor 2 m wide between two lethal walls, as in the corridor fixture. */
|
||||
std::vector<uint8_t> corridorCost(uint32_t width, uint32_t height)
|
||||
{
|
||||
std::vector<uint8_t> cost(static_cast<std::size_t>(width) * height, FREE_SPACE);
|
||||
for (uint32_t y = 0; y < height; ++y)
|
||||
if (y < 10 || y >= height - 10)
|
||||
std::fill_n(cost.begin() + static_cast<std::ptrdiff_t>(y * width), width, LETHAL_OBSTACLE);
|
||||
return cost;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Exact answers from the Python prototype, one scene per behaviour.
|
||||
TEST(ReferenceGraphParity, Corridor)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("corridor"));
|
||||
expectParity(f);
|
||||
EXPECT_EQ(f.nodes.size(), 2u);
|
||||
EXPECT_EQ(f.edges.size(), 1u);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, TJunction)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("t_junction"));
|
||||
expectParity(f);
|
||||
EXPECT_EQ(f.nodes.size(), 4u);
|
||||
EXPECT_EQ(f.edges.size(), 3u);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, ClosedRingHasNoNode)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("ring"));
|
||||
expectParity(f);
|
||||
EXPECT_FALSE(f.skeleton.empty());
|
||||
EXPECT_TRUE(f.nodes.empty());
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, UnknownCellsSplitTheRidge)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("unknown_block"));
|
||||
expectParity(f);
|
||||
EXPECT_EQ(f.edges.size(), 2u);
|
||||
for (int64_t cell : f.skeleton)
|
||||
EXPECT_NE(f.cost[static_cast<std::size_t>(cell)], NO_INFORMATION);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, OneZoneSplitsEdgesAndAddsLanes)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("one_zone"));
|
||||
expectParity(f);
|
||||
EXPECT_EQ(f.edges.size(), 5u);
|
||||
ASSERT_EQ(f.lanes.size(), 3u);
|
||||
for (const ReferenceLane& lane : f.lanes)
|
||||
{
|
||||
EXPECT_EQ(lane.direction_index, 0);
|
||||
EXPECT_GT(lane.exit.x, lane.entry.x);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, TwoZones)
|
||||
{
|
||||
expectParity(loadFixture(packagedFixture("two_zones")));
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, ZoneCutByObstacle)
|
||||
{
|
||||
expectParity(loadFixture(packagedFixture("cut_zone")));
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphParity, MapCropWithZones)
|
||||
{
|
||||
expectParity(loadFixture(packagedFixture("crop")));
|
||||
}
|
||||
|
||||
// The whole-map fixtures stay outside the repo. Point REFERENCE_GRAPH_FIXTURE_DIR at them to run these.
|
||||
TEST(ReferenceGraphParity, WholeMaps)
|
||||
{
|
||||
const char* directory = std::getenv("REFERENCE_GRAPH_FIXTURE_DIR");
|
||||
if (directory == nullptr)
|
||||
{
|
||||
// The installed gtest predates GTEST_SKIP.
|
||||
std::cout << "[ SKIPPED ] REFERENCE_GRAPH_FIXTURE_DIR is not set" << std::endl;
|
||||
return;
|
||||
}
|
||||
for (const char* name : { "kit", "sehc" })
|
||||
{
|
||||
SCOPED_TRACE(name);
|
||||
const std::pair<double, double> times = expectParity(loadFixture(std::string(directory) + "/" + name + ".fixture"));
|
||||
std::cout << "[ TIMING ] " << name << " step 1 " << times.first << " ms, step 2 " << times.second << " ms" << std::endl;
|
||||
#ifdef NDEBUG
|
||||
// Pass condition of the plan on the dev machine. The workspace builds Debug by default, where it means nothing.
|
||||
EXPECT_LT(times.first + times.second, 5000.0);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, EmptyGridHasNoSkeleton)
|
||||
{
|
||||
const DirectionGeometry geometry = geometryOf(40, 30);
|
||||
const std::vector<uint8_t> cost(1200, FREE_SPACE);
|
||||
ReferenceGridView view;
|
||||
view.cost = cost.data();
|
||||
view.geometry = geometry;
|
||||
const ReferenceGraphParams params;
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, params);
|
||||
ASSERT_EQ(skeleton.mask.size(), 1200u);
|
||||
EXPECT_EQ(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0);
|
||||
EXPECT_EQ(skeleton.clearance_mm, std::vector<uint16_t>(1200, 65535));
|
||||
const ReferenceGraph graph = buildReferenceGraph(view, skeleton, {}, params);
|
||||
EXPECT_TRUE(graph.nodes.empty());
|
||||
EXPECT_TRUE(graph.edges.empty());
|
||||
EXPECT_TRUE(graph.lanes.empty());
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, AllLethalHasNoSkeleton)
|
||||
{
|
||||
const std::vector<uint8_t> cost(1200, LETHAL_OBSTACLE);
|
||||
ReferenceGridView view;
|
||||
view.cost = cost.data();
|
||||
view.geometry = geometryOf(40, 30);
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams());
|
||||
EXPECT_EQ(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0);
|
||||
EXPECT_EQ(skeleton.clearance_mm, std::vector<uint16_t>(1200, 0));
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, ClearanceIsInMillimetres)
|
||||
{
|
||||
const std::vector<uint8_t> cost = corridorCost(100, 60);
|
||||
ReferenceGridView view;
|
||||
view.cost = cost.data();
|
||||
view.geometry = geometryOf(100, 60);
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams());
|
||||
// Row 10 touches the wall at row 9, one cell away. Row 29 is 20 cells from the wall at row 9.
|
||||
EXPECT_EQ(skeleton.clearance_mm[10 * 100 + 50], 50);
|
||||
EXPECT_EQ(skeleton.clearance_mm[29 * 100 + 50], 1000);
|
||||
EXPECT_EQ(skeleton.clearance_mm[5 * 100 + 50], 0);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, InflatedCellsNeverJoinTheSkeleton)
|
||||
{
|
||||
std::vector<uint8_t> cost = corridorCost(100, 60);
|
||||
// A band of inflation across the middle of the corridor, as a master costmap crop would hold.
|
||||
for (uint32_t y = 25; y < 35; ++y)
|
||||
std::fill_n(cost.begin() + y * 100, 100, INSCRIBED_INFLATED_OBSTACLE);
|
||||
ReferenceGridView view;
|
||||
view.cost = cost.data();
|
||||
view.geometry = geometryOf(100, 60);
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams());
|
||||
for (std::size_t i = 0; i < cost.size(); ++i)
|
||||
if (skeleton.mask[i] != 0)
|
||||
EXPECT_LT(cost[i], INSCRIBED_INFLATED_OBSTACLE) << "cell " << i;
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, SuppliedClearanceReplacesTheComputedOne)
|
||||
{
|
||||
const std::vector<uint8_t> cost = corridorCost(100, 60);
|
||||
ReferenceGridView view;
|
||||
view.cost = cost.data();
|
||||
view.geometry = geometryOf(100, 60);
|
||||
|
||||
// An obstacle just outside a window crop: clearance from the full map rules out every cell.
|
||||
const std::vector<uint16_t> tight(6000, 100);
|
||||
view.clearance_mm = tight.data();
|
||||
VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams());
|
||||
EXPECT_EQ(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0);
|
||||
EXPECT_EQ(skeleton.clearance_mm, tight);
|
||||
|
||||
const std::vector<uint16_t> wide(6000, 2000);
|
||||
view.clearance_mm = wide.data();
|
||||
skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams());
|
||||
EXPECT_GT(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0);
|
||||
EXPECT_EQ(skeleton.clearance_mm, wide);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, RepeatedRunsGiveTheSameGraph)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("two_zones"));
|
||||
const ReferenceGridView view = viewOf(f);
|
||||
const VoronoiSkeleton a = computeVoronoiSkeleton(view, f.params);
|
||||
const VoronoiSkeleton b = computeVoronoiSkeleton(view, f.params);
|
||||
EXPECT_EQ(a.mask, b.mask);
|
||||
const ReferenceGraph first = buildReferenceGraph(view, a, rectangle(f.half_x, f.half_y), f.params);
|
||||
const ReferenceGraph second = buildReferenceGraph(view, b, rectangle(f.half_x, f.half_y), f.params);
|
||||
ASSERT_EQ(first.nodes.size(), second.nodes.size());
|
||||
ASSERT_EQ(first.edges.size(), second.edges.size());
|
||||
ASSERT_EQ(first.lanes.size(), second.lanes.size());
|
||||
for (std::size_t i = 0; i < first.edges.size(); ++i)
|
||||
EXPECT_EQ(first.edges[i].points.size(), second.edges[i].points.size());
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, BiggerFootprintDropsLanes)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("one_zone"));
|
||||
const ReferenceGridView view = viewOf(f);
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params);
|
||||
const ReferenceGraph fits = buildReferenceGraph(view, skeleton, rectangle(f.half_x, f.half_y), f.params);
|
||||
// Half width 1.1 m does not fit the 2 m corridor.
|
||||
const ReferenceGraph blocked = buildReferenceGraph(view, skeleton, rectangle(f.half_x, 1.1), f.params);
|
||||
EXPECT_FALSE(fits.lanes.empty());
|
||||
EXPECT_TRUE(blocked.lanes.empty());
|
||||
EXPECT_EQ(fits.edges.size(), blocked.edges.size());
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphGrid, RegionCentreLineMatchesPython)
|
||||
{
|
||||
const DirectionGeometry geometry = geometryOf(100, 40);
|
||||
std::vector<uint8_t> mask(4000, 0);
|
||||
for (uint32_t y = 16; y < 24; ++y)
|
||||
std::fill_n(mask.begin() + y * 100 + 10, 80, 1);
|
||||
const std::vector<uint8_t> line = computeRegionCentreLine(mask, geometry, ReferenceGraphParams());
|
||||
EXPECT_EQ(std::count(line.begin(), line.end(), 1), 81);
|
||||
uint32_t x_min = 100, x_max = 0;
|
||||
for (uint32_t y = 0; y < 40; ++y)
|
||||
{
|
||||
for (uint32_t x = 0; x < 100; ++x)
|
||||
{
|
||||
if (line[y * 100 + x] == 0)
|
||||
continue;
|
||||
EXPECT_NE(mask[y * 100 + x], 0) << "centre line left the region";
|
||||
x_min = std::min(x_min, x);
|
||||
x_max = std::max(x_max, x);
|
||||
}
|
||||
}
|
||||
EXPECT_EQ(x_min, 10u);
|
||||
EXPECT_EQ(x_max, 89u);
|
||||
|
||||
const std::vector<uint8_t> nothing(4000, 0);
|
||||
const std::vector<uint8_t> empty_line = computeRegionCentreLine(nothing, geometry, ReferenceGraphParams());
|
||||
EXPECT_EQ(std::count(empty_line.begin(), empty_line.end(), 1), 0);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphInput, BadParametersAreRefused)
|
||||
{
|
||||
const std::vector<uint8_t> cost(100, FREE_SPACE);
|
||||
ReferenceGridView view;
|
||||
view.cost = cost.data();
|
||||
view.geometry = geometryOf(10, 10);
|
||||
|
||||
ReferenceGraphParams params;
|
||||
params.min_clearance_m = -0.1;
|
||||
EXPECT_FALSE(validateReferenceGraphParams(params).empty());
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument);
|
||||
params = ReferenceGraphParams();
|
||||
params.ridge_min_separation_m = 0.0;
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument);
|
||||
params = ReferenceGraphParams();
|
||||
params.spur_min_length_m = std::numeric_limits<double>::quiet_NaN();
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument);
|
||||
params = ReferenceGraphParams();
|
||||
params.lane_offset_step_m = -1.0;
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument);
|
||||
EXPECT_TRUE(validateReferenceGraphParams(ReferenceGraphParams()).empty());
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphInput, BadGridsAreRefused)
|
||||
{
|
||||
const std::vector<uint8_t> cost(100, FREE_SPACE);
|
||||
ReferenceGridView view;
|
||||
view.geometry = geometryOf(10, 10);
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, ReferenceGraphParams()), std::invalid_argument);
|
||||
view.cost = cost.data();
|
||||
view.geometry.resolution = 0.0;
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, ReferenceGraphParams()), std::invalid_argument);
|
||||
view.geometry = geometryOf(0, 10);
|
||||
EXPECT_THROW(computeVoronoiSkeleton(view, ReferenceGraphParams()), std::invalid_argument);
|
||||
view.geometry = geometryOf(10, 10);
|
||||
VoronoiSkeleton wrong_size;
|
||||
EXPECT_THROW(buildReferenceGraph(view, wrong_size, {}, ReferenceGraphParams()), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphInput, ZonesNeedAFootprint)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("one_zone"));
|
||||
const ReferenceGridView view = viewOf(f);
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params);
|
||||
EXPECT_THROW(buildReferenceGraph(view, skeleton, {}, f.params), std::invalid_argument);
|
||||
EXPECT_THROW(buildReferenceGraph(view, skeleton, rectangle(0.0, 0.0), f.params), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphCancel, CancelGivesAnEmptyResult)
|
||||
{
|
||||
const Fixture f = loadFixture(packagedFixture("one_zone"));
|
||||
const ReferenceGridView view = viewOf(f);
|
||||
const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params);
|
||||
std::atomic<bool> cancel(true);
|
||||
EXPECT_TRUE(computeVoronoiSkeleton(view, f.params, &cancel).mask.empty());
|
||||
const ReferenceGraph graph = buildReferenceGraph(view, skeleton, rectangle(f.half_x, f.half_y), f.params, &cancel);
|
||||
EXPECT_TRUE(graph.static_cost.empty());
|
||||
EXPECT_TRUE(graph.nodes.empty());
|
||||
EXPECT_TRUE(graph.edges.empty());
|
||||
EXPECT_TRUE(graph.lanes.empty());
|
||||
}
|
||||
670
test/reference_graph_worker_test.cpp
Normal file
670
test/reference_graph_worker_test.cpp
Normal file
@@ -0,0 +1,670 @@
|
||||
#include <robot_costmap_2d/reference_graph_worker.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <robot_costmap_2d/costmap_layer.h>
|
||||
#include <robot_costmap_2d/layered_costmap.h>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
constexpr double kResolution = 0.05;
|
||||
|
||||
bool waitUntil(const std::function<bool()>& condition, double seconds = 60.0)
|
||||
{
|
||||
const Clock::time_point end = Clock::now() + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(seconds));
|
||||
while (Clock::now() < end)
|
||||
{
|
||||
if (condition())
|
||||
return true;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
return condition();
|
||||
}
|
||||
|
||||
DirectionGeometry geometryOf(uint32_t width, uint32_t height) { return { width, height, kResolution, 0.0, 0.0, "map" }; }
|
||||
|
||||
/** Free map with a lethal border, so its ridge runs along the middle. */
|
||||
std::vector<uint8_t> corridor(uint32_t width, uint32_t height)
|
||||
{
|
||||
std::vector<uint8_t> cost(static_cast<std::size_t>(width) * height, FREE_SPACE);
|
||||
for (uint32_t x = 0; x < width; ++x)
|
||||
cost[x] = cost[static_cast<std::size_t>(height - 1) * width + x] = LETHAL_OBSTACLE;
|
||||
for (uint32_t y = 0; y < height; ++y)
|
||||
cost[static_cast<std::size_t>(y) * width] = cost[static_cast<std::size_t>(y) * width + width - 1] = LETHAL_OBSTACLE;
|
||||
return cost;
|
||||
}
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> rectangle(double half_x, double half_y)
|
||||
{
|
||||
std::vector<robot_geometry_msgs::Point> footprint(4);
|
||||
const double xs[4] = { half_x, -half_x, -half_x, half_x };
|
||||
const double ys[4] = { half_y, half_y, -half_y, -half_y };
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
footprint[static_cast<std::size_t>(i)].x = xs[i];
|
||||
footprint[static_cast<std::size_t>(i)].y = ys[i];
|
||||
}
|
||||
return footprint;
|
||||
}
|
||||
|
||||
/** Zone with direction +X over a band in the middle of the map. */
|
||||
DirectionFieldSnapshot bandZone(uint32_t width, uint32_t height, uint64_t generation)
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid grid;
|
||||
grid.header.frame_id = "map";
|
||||
grid.info.width = width;
|
||||
grid.info.height = height;
|
||||
grid.info.resolution = kResolution;
|
||||
grid.data.assign(static_cast<std::size_t>(width) * height, 0);
|
||||
for (uint32_t y = height / 3; y < 2 * height / 3; ++y)
|
||||
for (uint32_t x = width / 4; x < 3 * width / 4; ++x)
|
||||
grid.data[static_cast<std::size_t>(y) * width + x] = 1;
|
||||
DirectionFieldSnapshot snapshot;
|
||||
snapshot.state = DirectionFieldState::kReady;
|
||||
snapshot.field = DirectionField::create(grid, geometryOf(width, height), 1.5);
|
||||
snapshot.generation = generation;
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
ReferenceGraphParams quietParams()
|
||||
{
|
||||
ReferenceGraphParams params;
|
||||
params.debug_log = false;
|
||||
return params;
|
||||
}
|
||||
|
||||
/** A costmap stand-in the test controls from its own thread. */
|
||||
class FakeCostmap
|
||||
{
|
||||
public:
|
||||
FakeCostmap(uint32_t width, uint32_t height) : geometry_(geometryOf(width, height)), grid_(corridor(width, height)), footprint_(rectangle(0.3, 0.3)) {}
|
||||
|
||||
ReferenceGraphWorker::Source source()
|
||||
{
|
||||
ReferenceGraphWorker::Source out;
|
||||
out.capture = [this](bool with_grid, ReferenceGraphInput* input) {
|
||||
++captures;
|
||||
if (on_capture)
|
||||
on_capture();
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (status_ != ReferenceCaptureStatus::kReady)
|
||||
return status_;
|
||||
input->geometry = geometry_;
|
||||
input->footprint = footprint_;
|
||||
if (with_grid)
|
||||
{
|
||||
++grid_captures;
|
||||
input->static_layers.push_back(grid_);
|
||||
}
|
||||
return ReferenceCaptureStatus::kReady;
|
||||
};
|
||||
out.direction = [this]() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return direction_;
|
||||
};
|
||||
return out;
|
||||
}
|
||||
|
||||
void setGrid(std::vector<uint8_t> grid)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
grid_ = std::move(grid);
|
||||
}
|
||||
void setStatus(ReferenceCaptureStatus status)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
status_ = status;
|
||||
}
|
||||
void setDirection(DirectionFieldSnapshot direction)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
direction_ = std::move(direction);
|
||||
}
|
||||
|
||||
std::atomic<int> captures{ 0 };
|
||||
std::atomic<int> grid_captures{ 0 };
|
||||
std::function<void()> on_capture; ///< Set before the worker starts.
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
DirectionGeometry geometry_;
|
||||
std::vector<uint8_t> grid_;
|
||||
std::vector<robot_geometry_msgs::Point> footprint_;
|
||||
ReferenceCaptureStatus status_ = ReferenceCaptureStatus::kReady;
|
||||
DirectionFieldSnapshot direction_;
|
||||
};
|
||||
|
||||
bool ready(const ReferenceGraphWorker& worker) { return worker.snapshot().state == ReferenceGraphState::kReady; }
|
||||
|
||||
/** Holds the worker inside a capture until the test lets it go. */
|
||||
class Gate
|
||||
{
|
||||
public:
|
||||
void hold()
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
reached_ = true;
|
||||
changed_.notify_all();
|
||||
changed_.wait(lock, [this]() { return open_; });
|
||||
}
|
||||
void waitReached()
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
changed_.wait(lock, [this]() { return reached_; });
|
||||
}
|
||||
void open()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
open_ = true;
|
||||
changed_.notify_all();
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
std::condition_variable changed_;
|
||||
bool reached_ = false;
|
||||
bool open_ = false;
|
||||
};
|
||||
|
||||
class FakeLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
explicit FakeLayer(LayerType type, bool current = true) : type_(type)
|
||||
{
|
||||
enabled_ = true;
|
||||
current_ = current;
|
||||
}
|
||||
LayerType getType() const override { return type_; }
|
||||
void setCurrent(bool current) { current_ = current; }
|
||||
void write(const std::vector<uint8_t>& cost) { std::copy(cost.begin(), cost.end(), getCharMap()); }
|
||||
|
||||
protected:
|
||||
void handleImpl(const void*, const std::type_info&, const std::string&) override {}
|
||||
|
||||
private:
|
||||
LayerType type_;
|
||||
};
|
||||
|
||||
class FakeDirectionLayer : public Layer, public DirectionFieldProvider
|
||||
{
|
||||
public:
|
||||
FakeDirectionLayer() { enabled_ = true; current_ = true; }
|
||||
LayerType getType() const override { return LayerType::DIRECTIONAL_LAYER; }
|
||||
DirectionFieldSnapshot directionSnapshot() const override
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return snapshot_;
|
||||
}
|
||||
void publish(DirectionFieldSnapshot snapshot)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
snapshot_ = std::move(snapshot);
|
||||
layered_costmap_->notifyDirectionFieldChanged();
|
||||
}
|
||||
|
||||
protected:
|
||||
void handleImpl(const void*, const std::type_info&, const std::string&) override {}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
DirectionFieldSnapshot snapshot_;
|
||||
};
|
||||
|
||||
/** A LayeredCostmap with one static layer that already holds a map. */
|
||||
struct Costmap
|
||||
{
|
||||
Costmap(uint32_t width, uint32_t height) : layered("map", false, true), layer(boost::make_shared<FakeLayer>(LayerType::STATIC_LAYER))
|
||||
{
|
||||
layer->initialize(&layered, "static", nullptr);
|
||||
layered.addPlugin(layer);
|
||||
layered.resizeMap(width, height, kResolution, 0.0, 0.0);
|
||||
layer->write(corridor(width, height));
|
||||
layered.setFootprint(rectangle(0.3, 0.3));
|
||||
}
|
||||
bool ready() const { return layered.getReferenceGraphSnapshot().state == ReferenceGraphState::kReady; }
|
||||
|
||||
LayeredCostmap layered;
|
||||
boost::shared_ptr<FakeLayer> layer;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(MergeStaticLayers, LethalWinsAndUnknownNeedsEveryLayer)
|
||||
{
|
||||
const std::vector<uint8_t> merged = mergeStaticLayers({ { FREE_SPACE, LETHAL_OBSTACLE, NO_INFORMATION, NO_INFORMATION, INSCRIBED_INFLATED_OBSTACLE },
|
||||
{ LETHAL_OBSTACLE, FREE_SPACE, FREE_SPACE, NO_INFORMATION, NO_INFORMATION } });
|
||||
EXPECT_EQ(merged, (std::vector<uint8_t>{ LETHAL_OBSTACLE, LETHAL_OBSTACLE, FREE_SPACE, NO_INFORMATION, FREE_SPACE }));
|
||||
EXPECT_TRUE(mergeStaticLayers({}).empty());
|
||||
EXPECT_THROW(mergeStaticLayers({ { FREE_SPACE }, { FREE_SPACE, FREE_SPACE } }), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, BadInputIsRefused)
|
||||
{
|
||||
FakeCostmap costmap(40, 40);
|
||||
ReferenceGraphParams bad = quietParams();
|
||||
bad.spur_min_length_m = -1.0;
|
||||
EXPECT_THROW(ReferenceGraphWorker(costmap.source(), bad), std::invalid_argument);
|
||||
EXPECT_THROW(ReferenceGraphWorker(ReferenceGraphWorker::Source{}, quietParams()), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, GoesFromPendingToReadyAndSleeps)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
Gate gate;
|
||||
costmap.on_capture = [&gate]() { gate.hold(); };
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
gate.waitReached();
|
||||
const ReferenceGraphSnapshot pending = worker.snapshot();
|
||||
EXPECT_EQ(pending.state, ReferenceGraphState::kPending);
|
||||
EXPECT_EQ(pending.graph, nullptr);
|
||||
gate.open();
|
||||
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
const ReferenceGraphSnapshot done = worker.snapshot();
|
||||
ASSERT_NE(done.graph, nullptr);
|
||||
EXPECT_NE(done.generation, pending.generation);
|
||||
EXPECT_FALSE(done.graph->edges.empty());
|
||||
EXPECT_EQ(done.graph->static_cost, mergeStaticLayers({ corridor(120, 60) }));
|
||||
EXPECT_EQ(done.graph->clearance_mm.size(), 120U * 60U);
|
||||
EXPECT_EQ(done.graph->geometry.frame_id, "map");
|
||||
|
||||
// A ready worker does no work at all, so it costs nothing on a 2-core robot.
|
||||
const int captures = costmap.captures;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(450));
|
||||
EXPECT_EQ(costmap.captures, captures);
|
||||
EXPECT_EQ(worker.snapshot().generation, done.generation);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, RetainedSnapshotSurvivesTheNextChange)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
const ReferenceGraphSnapshot held = worker.snapshot();
|
||||
costmap.setGrid(corridor(120, 60));
|
||||
worker.notifyStaticChanged();
|
||||
EXPECT_EQ(worker.snapshot().graph == held.graph, false);
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
EXPECT_FALSE(held.graph->static_cost.empty());
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, WaitsForTheStaticLayer)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
costmap.setStatus(ReferenceCaptureStatus::kWait);
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; }));
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
EXPECT_EQ(worker.stats().step1_runs, 0U);
|
||||
costmap.setStatus(ReferenceCaptureStatus::kReady);
|
||||
EXPECT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, NoStaticLayerStaysPending)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
costmap.setStatus(ReferenceCaptureStatus::kNoStaticLayer);
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; }));
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, WaitsForTheDirectionGridThenRunsOnlyStep2)
|
||||
{
|
||||
FakeCostmap costmap(200, 120);
|
||||
DirectionFieldSnapshot pending;
|
||||
pending.state = DirectionFieldState::kPending;
|
||||
costmap.setDirection(pending);
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return worker.stats().step1_runs == 1; }));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; }));
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
EXPECT_EQ(worker.stats().step2_runs, 0U);
|
||||
|
||||
costmap.setDirection(bandZone(200, 120, 7));
|
||||
worker.notifyDirectionChanged();
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
const ReferenceGraphSnapshot done = worker.snapshot();
|
||||
EXPECT_EQ(done.graph->direction_generation, 7U);
|
||||
EXPECT_FALSE(done.graph->lanes.empty());
|
||||
EXPECT_EQ(worker.stats().step1_runs, 1U);
|
||||
EXPECT_EQ(costmap.grid_captures, 1);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, GridOfTheOldMapIsNotUsed)
|
||||
{
|
||||
FakeCostmap costmap(200, 120);
|
||||
costmap.setDirection(bandZone(100, 60, 3));
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; }));
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
costmap.setDirection(bandZone(200, 120, 4));
|
||||
worker.notifyDirectionChanged();
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
EXPECT_EQ(worker.snapshot().graph->direction_generation, 4U);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, DirectionAndFootprintChangesRunOnlyStep2)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
ASSERT_EQ(worker.stats().step1_runs, 1U);
|
||||
|
||||
worker.notifyDirectionChanged();
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
EXPECT_EQ(worker.snapshot().graph, nullptr);
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
|
||||
worker.notifyFootprintChanged();
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
|
||||
const ReferenceGraphWorkerStats stats = worker.stats();
|
||||
EXPECT_EQ(stats.step1_runs, 1U);
|
||||
EXPECT_EQ(stats.step2_runs, 3U);
|
||||
EXPECT_EQ(stats.published, 3U);
|
||||
EXPECT_EQ(costmap.grid_captures, 1);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, StaticChangeRunsBothSteps)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
worker.notifyStaticChanged();
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
EXPECT_EQ(worker.stats().step1_runs, 2U);
|
||||
EXPECT_EQ(worker.stats().step2_runs, 2U);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, ThreeMapsInARowPublishOnlyTheLast)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
Gate gate;
|
||||
costmap.on_capture = [&gate]() { gate.hold(); };
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
gate.waitReached();
|
||||
std::vector<uint8_t> last = corridor(120, 60);
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
last[static_cast<std::size_t>(30 * 120 + 10 + i)] = LETHAL_OBSTACLE;
|
||||
costmap.setGrid(last);
|
||||
worker.notifyStaticChanged();
|
||||
}
|
||||
gate.open();
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
EXPECT_EQ(worker.snapshot().graph->static_cost, mergeStaticLayers({ last }));
|
||||
EXPECT_EQ(worker.stats().published, 1U);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, MapDuringAComputationRestartsIt)
|
||||
{
|
||||
const uint32_t size = 1500;
|
||||
FakeCostmap costmap(size, size);
|
||||
std::atomic<bool> first{ true };
|
||||
ReferenceGraphWorker* worker_ptr = nullptr;
|
||||
std::vector<uint8_t> changed = corridor(size, size);
|
||||
changed[static_cast<std::size_t>(size / 2) * size + size / 2] = LETHAL_OBSTACLE;
|
||||
std::mutex started_mutex;
|
||||
std::condition_variable started;
|
||||
bool started_flag = false;
|
||||
costmap.on_capture = [&]() {
|
||||
if (first.exchange(false))
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(started_mutex);
|
||||
started_flag = true;
|
||||
started.notify_all();
|
||||
}
|
||||
};
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
worker_ptr = &worker;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(started_mutex);
|
||||
started.wait(lock, [&]() { return started_flag; });
|
||||
}
|
||||
costmap.setGrid(changed);
|
||||
worker_ptr->notifyStaticChanged();
|
||||
ASSERT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
EXPECT_EQ(worker.snapshot().graph->static_cost, mergeStaticLayers({ changed }));
|
||||
EXPECT_EQ(worker.stats().published, 1U);
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, ExceptionStaysPendingUntilTheNextChange)
|
||||
{
|
||||
FakeCostmap costmap(120, 60);
|
||||
std::atomic<bool> fail{ true };
|
||||
costmap.on_capture = [&fail]() {
|
||||
if (fail)
|
||||
throw std::runtime_error("injected");
|
||||
};
|
||||
ReferenceGraphWorker worker(costmap.source(), quietParams());
|
||||
ASSERT_TRUE(waitUntil([&]() { return worker.stats().errors == 1; }));
|
||||
EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending);
|
||||
const int captures = costmap.captures;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(450));
|
||||
EXPECT_EQ(costmap.captures, captures);
|
||||
|
||||
fail = false;
|
||||
worker.notifyStaticChanged();
|
||||
EXPECT_TRUE(waitUntil([&]() { return ready(worker); }));
|
||||
}
|
||||
|
||||
TEST(ReferenceGraphWorker, StopsQuicklyDuringAComputation)
|
||||
{
|
||||
const uint32_t size = 3000;
|
||||
FakeCostmap costmap(size, size);
|
||||
std::unique_ptr<ReferenceGraphWorker> worker(new ReferenceGraphWorker(costmap.source(), quietParams()));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.grid_captures >= 1; }));
|
||||
// Let it get well into step 1, where the map is largest.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
const Clock::time_point began = Clock::now();
|
||||
worker.reset();
|
||||
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - began).count();
|
||||
std::printf("stopped in %.1f ms\n", ms);
|
||||
EXPECT_LT(ms, 100.0);
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, DisabledHasNoWork)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kDisabled);
|
||||
costmap.layered.notifyStaticMapChanged(LayerType::STATIC_LAYER);
|
||||
costmap.layered.notifyDirectionFieldChanged();
|
||||
costmap.layered.setFootprint(rectangle(0.4, 0.4));
|
||||
EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kDisabled);
|
||||
EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::STATIC_LAYER), 1U);
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, RollingCostmapIsRefused)
|
||||
{
|
||||
LayeredCostmap rolling("map", true, true);
|
||||
EXPECT_FALSE(rolling.enableReferenceGraph(quietParams()));
|
||||
EXPECT_EQ(rolling.getReferenceGraphSnapshot().state, ReferenceGraphState::kDisabled);
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, BadParametersAndASecondCallAreRefused)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
ReferenceGraphParams bad = quietParams();
|
||||
bad.min_clearance_m = -1.0;
|
||||
EXPECT_FALSE(costmap.layered.enableReferenceGraph(bad));
|
||||
EXPECT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
EXPECT_FALSE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, MapThatArrivedBeforeEnablingCounts)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
const auto graph = costmap.layered.getReferenceGraphSnapshot().graph;
|
||||
EXPECT_EQ(graph->geometry.width, 120U);
|
||||
EXPECT_EQ(graph->direction_generation, 0U);
|
||||
EXPECT_TRUE(graph->lanes.empty());
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, WaitsUntilTheLayerWroteItsMap)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
costmap.layer->setCurrent(false);
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending);
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*costmap.layered.getCostmap()->getMutex());
|
||||
costmap.layer->setCurrent(true);
|
||||
}
|
||||
EXPECT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, NoStaticLayerStaysPending)
|
||||
{
|
||||
LayeredCostmap layered("map", false, true);
|
||||
layered.resizeMap(120, 60, kResolution, 0.0, 0.0);
|
||||
ASSERT_TRUE(layered.enableReferenceGraph(quietParams()));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
EXPECT_EQ(layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending);
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, OtherLayerTypesOnlyCountARevision)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
const ReferenceGraphSnapshot before = costmap.layered.getReferenceGraphSnapshot();
|
||||
costmap.layered.notifyStaticMapChanged(LayerType::PREFERRED_LAYER);
|
||||
costmap.layered.notifyStaticMapChanged(LayerType::UNPREFERRED_LAYER);
|
||||
costmap.layered.notifyStaticMapChanged(LayerType::CRITICAL_LAYER);
|
||||
const ReferenceGraphSnapshot after = costmap.layered.getReferenceGraphSnapshot();
|
||||
EXPECT_EQ(after.state, ReferenceGraphState::kReady);
|
||||
EXPECT_EQ(after.generation, before.generation);
|
||||
EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::PREFERRED_LAYER), 1U);
|
||||
EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::STATIC_LAYER), 0U);
|
||||
|
||||
costmap.layered.notifyStaticMapChanged(LayerType::STATIC_LAYER);
|
||||
EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::STATIC_LAYER), 1U);
|
||||
EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending);
|
||||
EXPECT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, MergesStaticLayersAndIgnoresSoftOnes)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
auto walls = boost::make_shared<FakeLayer>(LayerType::STATIC_LAYER);
|
||||
auto preferred = boost::make_shared<FakeLayer>(LayerType::PREFERRED_LAYER);
|
||||
for (const auto& layer : { walls, preferred })
|
||||
{
|
||||
layer->initialize(&costmap.layered, "extra", nullptr);
|
||||
costmap.layered.addPlugin(layer);
|
||||
layer->matchSize();
|
||||
}
|
||||
std::vector<uint8_t> wall_cost(120 * 60, NO_INFORMATION);
|
||||
wall_cost[30 * 120 + 60] = LETHAL_OBSTACLE;
|
||||
walls->write(wall_cost);
|
||||
std::vector<uint8_t> soft_cost(120 * 60, NO_INFORMATION);
|
||||
soft_cost[20 * 120 + 40] = LETHAL_OBSTACLE;
|
||||
preferred->write(soft_cost);
|
||||
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
const auto graph = costmap.layered.getReferenceGraphSnapshot().graph;
|
||||
EXPECT_EQ(graph->static_cost[30 * 120 + 60], LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(graph->static_cost[20 * 120 + 40], FREE_SPACE);
|
||||
EXPECT_EQ(graph->static_cost[0], LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, OnlyARealFootprintChangeRecomputes)
|
||||
{
|
||||
Costmap costmap(120, 60);
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
const uint64_t generation = costmap.layered.getReferenceGraphSnapshot().generation;
|
||||
costmap.layered.setFootprint(rectangle(0.3, 0.3));
|
||||
EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().generation, generation);
|
||||
costmap.layered.setFootprint(rectangle(0.35, 0.3));
|
||||
EXPECT_NE(costmap.layered.getReferenceGraphSnapshot().generation, generation);
|
||||
EXPECT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, ReadsTheDirectionProviderAndFollowsIt)
|
||||
{
|
||||
Costmap costmap(200, 120);
|
||||
auto direction = boost::make_shared<FakeDirectionLayer>();
|
||||
direction->initialize(&costmap.layered, "direction", nullptr);
|
||||
costmap.layered.addPlugin(direction);
|
||||
DirectionFieldSnapshot pending;
|
||||
pending.state = DirectionFieldState::kPending;
|
||||
direction->publish(pending);
|
||||
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending);
|
||||
|
||||
direction->publish(bandZone(200, 120, 11));
|
||||
ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); }));
|
||||
const auto graph = costmap.layered.getReferenceGraphSnapshot().graph;
|
||||
EXPECT_EQ(graph->direction_generation, 11U);
|
||||
EXPECT_FALSE(graph->lanes.empty());
|
||||
|
||||
direction->publish(bandZone(200, 120, 12));
|
||||
ASSERT_TRUE(waitUntil([&]() {
|
||||
const auto now = costmap.layered.getReferenceGraphSnapshot();
|
||||
return now.state == ReferenceGraphState::kReady && now.graph->direction_generation == 12U;
|
||||
}));
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, MasterMutexStaysFreeWhileComputing)
|
||||
{
|
||||
// SEHC-sized map. The costmap update must not feel the graph, so the master mutex may be held only for the copy.
|
||||
const uint32_t size = 3060;
|
||||
Costmap costmap(size, size);
|
||||
ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams()));
|
||||
double worst_ms = 0.0;
|
||||
const Clock::time_point end = Clock::now() + std::chrono::seconds(120);
|
||||
while (!costmap.ready() && Clock::now() < end)
|
||||
{
|
||||
const Clock::time_point began = Clock::now();
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*costmap.layered.getCostmap()->getMutex());
|
||||
}
|
||||
worst_ms = std::max(worst_ms, std::chrono::duration<double, std::milli>(Clock::now() - began).count());
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(200));
|
||||
}
|
||||
ASSERT_TRUE(costmap.ready());
|
||||
std::printf("longest wait for the master mutex %.2f ms\n", worst_ms);
|
||||
EXPECT_LT(worst_ms, 10.0);
|
||||
}
|
||||
|
||||
TEST(LayeredCostmapReferenceGraph, DestroyedDuringAComputation)
|
||||
{
|
||||
const uint32_t size = 2000;
|
||||
std::unique_ptr<Costmap> costmap(new Costmap(size, size));
|
||||
ASSERT_TRUE(costmap->layered.enableReferenceGraph(quietParams()));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
const Clock::time_point began = Clock::now();
|
||||
costmap.reset();
|
||||
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - began).count();
|
||||
EXPECT_LT(ms, 100.0);
|
||||
}
|
||||
249
test/rolling_static_layer_test.cpp
Normal file
249
test/rolling_static_layer_test.cpp
Normal file
@@ -0,0 +1,249 @@
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <robot_costmap_2d/critical_layer.h>
|
||||
#include <robot_costmap_2d/preferred_layer.h>
|
||||
#include <robot_costmap_2d/static_layer.h>
|
||||
#include <robot_costmap_2d/unpreferred_layer.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// This deterministic obstacle producer leaves bounds to the zone layer, so the tests also
|
||||
// exercise whether the rolling zone requests a redraw of the master window.
|
||||
class ObstacleMarks : public Layer
|
||||
{
|
||||
public:
|
||||
void onInitialize() override { enabled_ = true; }
|
||||
void updateCosts(Costmap2D& master, int, int, int, int) override
|
||||
{
|
||||
master.setCost(0, 0, LETHAL_OBSTACLE);
|
||||
master.setCost(2, 1, LETHAL_OBSTACLE);
|
||||
}
|
||||
protected:
|
||||
void handleImpl(const void*, const std::type_info&, const std::string&) override {}
|
||||
};
|
||||
|
||||
class MergeLayer : public CostmapLayer
|
||||
{
|
||||
public:
|
||||
MergeLayer() { enabled_ = true; }
|
||||
using CostmapLayer::updateWithMax;
|
||||
using CostmapLayer::updateWithOverwrite;
|
||||
protected:
|
||||
void handleImpl(const void*, const std::type_info&, const std::string&) override {}
|
||||
};
|
||||
|
||||
class RollingStaticLayerTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
tf3::BufferCore tf_{tf3::Duration(10.0)};
|
||||
std::string directory_;
|
||||
std::string old_env_;
|
||||
bool had_env_ = false;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
if (const char* old = std::getenv("PNKX_NAV_CORE_CONFIG_DIR"))
|
||||
{
|
||||
had_env_ = true;
|
||||
old_env_ = old;
|
||||
}
|
||||
char pattern[] = "/tmp/rolling-static-layer-XXXXXX";
|
||||
char* path = mkdtemp(pattern);
|
||||
ASSERT_NE(path, nullptr);
|
||||
directory_ = path;
|
||||
std::filesystem::create_directory(directory_ + "/config");
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", directory_.c_str(), 1), 0);
|
||||
|
||||
tf3::TransformStampedMsg transform;
|
||||
transform.header.frame_id = "map";
|
||||
transform.child_frame_id = "odom";
|
||||
transform.transform.translation.x = 14.0;
|
||||
transform.transform.translation.y = 24.0;
|
||||
transform.transform.rotation.z = 1.0;
|
||||
transform.transform.rotation.w = 0.0;
|
||||
ASSERT_TRUE(tf_.setTransform(transform, "test", true));
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
if (had_env_)
|
||||
setenv("PNKX_NAV_CORE_CONFIG_DIR", old_env_.c_str(), 1);
|
||||
else
|
||||
unsetenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
if (!directory_.empty())
|
||||
std::filesystem::remove_all(directory_);
|
||||
}
|
||||
|
||||
void configure(bool maximum)
|
||||
{
|
||||
std::ofstream out(directory_ + "/config/static_layer_params.yaml");
|
||||
out << "static_layer:\n enabled: true\n map_topic: map\n"
|
||||
" track_unknown_space: true\n lethal_cost_threshold: 100\n use_maximum: "
|
||||
<< (maximum ? "true\n" : "false\n");
|
||||
}
|
||||
|
||||
robot_nav_msgs::OccupancyGrid grid(int outside)
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid map;
|
||||
map.header.frame_id = "map";
|
||||
map.info.width = map.info.height = 4;
|
||||
map.info.resolution = 1.0;
|
||||
map.info.origin.position.x = 10.0;
|
||||
map.info.origin.position.y = 20.0;
|
||||
map.info.origin.orientation.w = 1.0;
|
||||
map.data.assign(16, outside);
|
||||
// map (2,2) and (1,2) correspond to odom (1,1) and (2,1).
|
||||
map.data[2 * 4 + 2] = 100;
|
||||
map.data[2 * 4 + 1] = 100;
|
||||
return map;
|
||||
}
|
||||
|
||||
template <class Zone>
|
||||
void runZone(bool maximum, int outside, unsigned char zone_cost, bool obstacle_survives)
|
||||
{
|
||||
configure(maximum);
|
||||
LayeredCostmap master("odom", true, false);
|
||||
master.resizeMap(4, 4, 1.0, 0.0, 0.0);
|
||||
auto obstacles = boost::make_shared<ObstacleMarks>();
|
||||
obstacles->initialize(&master, "obstacles", &tf_);
|
||||
master.addPlugin(obstacles);
|
||||
auto zone = boost::make_shared<Zone>();
|
||||
zone->initialize(&master, "zone", &tf_);
|
||||
master.addPlugin(zone);
|
||||
zone->dataCallBack(grid(outside), "map");
|
||||
Costmap2D& costs = *master.getCostmap();
|
||||
const auto check_costs = [&]
|
||||
{
|
||||
EXPECT_EQ(costs.getCost(1, 1), zone_cost);
|
||||
EXPECT_EQ(costs.getCost(2, 1), obstacle_survives ? LETHAL_OBSTACLE : zone_cost);
|
||||
EXPECT_EQ(costs.getCost(0, 0), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(costs.getCost(3, 3), FREE_SPACE);
|
||||
for (unsigned int y = 0; y < 4; ++y)
|
||||
for (unsigned int x = 0; x < 4; ++x)
|
||||
EXPECT_NE(costs.getCost(x, y), NO_INFORMATION) << x << "," << y;
|
||||
};
|
||||
// Check the transformed merge independently of the bounds calculation.
|
||||
obstacles->updateCosts(costs, 0, 0, 4, 4);
|
||||
boost::static_pointer_cast<Layer>(zone)->updateCosts(costs, 0, 0, 4, 4);
|
||||
check_costs();
|
||||
|
||||
master.updateMap(1.75, 1.75, 0.0);
|
||||
EXPECT_DOUBLE_EQ(costs.getOriginX(), 0.0);
|
||||
EXPECT_DOUBLE_EQ(costs.getOriginY(), 0.0);
|
||||
check_costs();
|
||||
unsigned int x0, xn, y0, yn;
|
||||
master.getBounds(&x0, &xn, &y0, &yn);
|
||||
EXPECT_EQ(x0, 0u);
|
||||
EXPECT_EQ(y0, 0u);
|
||||
EXPECT_EQ(xn, 4u);
|
||||
EXPECT_EQ(yn, 4u);
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(RollingStaticLayerTest, ForbiddenMaxPreservesObstaclesAndFreeCells)
|
||||
{
|
||||
runZone<StaticLayer>(true, -1, LETHAL_OBSTACLE, true);
|
||||
}
|
||||
|
||||
TEST_F(RollingStaticLayerTest, ForbiddenOverwriteSkipsUnknown)
|
||||
{
|
||||
runZone<StaticLayer>(false, -1, LETHAL_OBSTACLE, true);
|
||||
}
|
||||
|
||||
TEST_F(RollingStaticLayerTest, PreferredAndUnpreferredRespectObstaclesInMaxMode)
|
||||
{
|
||||
runZone<PreferredLayer>(true, 0, PREFERRED_SPACE, true);
|
||||
runZone<UnPreferredLayer>(true, 0, UNPREFERRED_SPACE, true);
|
||||
}
|
||||
|
||||
TEST_F(RollingStaticLayerTest, CriticalIsTransformedAndOverridesObstaclesInBothModes)
|
||||
{
|
||||
runZone<CriticalLayer>(true, 0, CRITICAL_SPACE, false);
|
||||
runZone<CriticalLayer>(false, 0, CRITICAL_SPACE, false);
|
||||
}
|
||||
|
||||
TEST_F(RollingStaticLayerTest, BoundsCoverWindowWhenMapExtentIsElsewhere)
|
||||
{
|
||||
configure(true);
|
||||
LayeredCostmap master("odom", true, false);
|
||||
master.resizeMap(4, 4, 1.0, 0.0, 0.0);
|
||||
auto zone = boost::make_shared<StaticLayer>();
|
||||
zone->initialize(&master, "zone", &tf_);
|
||||
master.addPlugin(zone);
|
||||
zone->dataCallBack(grid(-1), "map");
|
||||
master.updateMap(1.75, 1.75, 0.0);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(1, 1), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(3, 3), FREE_SPACE);
|
||||
}
|
||||
|
||||
TEST_F(RollingStaticLayerTest, NonRollingPreferredRetainsMaxAndOverwriteSemantics)
|
||||
{
|
||||
for (bool maximum : {false, true})
|
||||
{
|
||||
configure(maximum);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1.0, 0.0, 0.0);
|
||||
auto obstacles = boost::make_shared<ObstacleMarks>();
|
||||
obstacles->initialize(&master, "obstacles", &tf_);
|
||||
master.addPlugin(obstacles);
|
||||
auto zone = boost::make_shared<PreferredLayer>();
|
||||
zone->initialize(&master, "zone", &tf_);
|
||||
master.addPlugin(zone);
|
||||
auto map = grid(0);
|
||||
map.info.origin.position.x = map.info.origin.position.y = 0.0;
|
||||
map.data.assign(16, 0);
|
||||
map.data[1 * 4 + 1] = 100;
|
||||
map.data[1 * 4 + 2] = 100;
|
||||
zone->dataCallBack(map, "map");
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(1, 1), PREFERRED_SPACE);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(2, 1), maximum ? LETHAL_OBSTACLE : PREFERRED_SPACE);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(0, 0), LETHAL_OBSTACLE);
|
||||
}
|
||||
}
|
||||
|
||||
// Enumerate every possible byte pair against the original aligned-grid policies.
|
||||
TEST(StaticLayerMergeRegression, NonRollingOverwriteAndMaxRetainAllByteResults)
|
||||
{
|
||||
MergeLayer layer;
|
||||
layer.resizeMap(256, 256, 1.0, 0.0, 0.0);
|
||||
Costmap2D master(256, 256, 1.0, 0.0, 0.0, FREE_SPACE);
|
||||
for (bool maximum : {false, true})
|
||||
{
|
||||
for (unsigned int old = 0; old < 256; ++old)
|
||||
for (unsigned int value = 0; value < 256; ++value)
|
||||
{
|
||||
master.setCost(value, old, old);
|
||||
layer.setCost(value, old, value);
|
||||
}
|
||||
if (maximum)
|
||||
layer.updateWithMax(master, 0, 0, 256, 256);
|
||||
else
|
||||
layer.updateWithOverwrite(master, 0, 0, 256, 256);
|
||||
for (unsigned int old = 0; old < 256; ++old)
|
||||
for (unsigned int value = 0; value < 256; ++value)
|
||||
{
|
||||
unsigned int expected = old;
|
||||
if (value != NO_INFORMATION &&
|
||||
(!maximum || value == CRITICAL_SPACE ||
|
||||
((value == PREFERRED_SPACE || value == UNPREFERRED_SPACE) && old < INSCRIBED_INFLATED_OBSTACLE) ||
|
||||
old == NO_INFORMATION || old < value))
|
||||
expected = value;
|
||||
ASSERT_EQ(master.getCost(value, old), expected) << "old=" << old << " layer=" << value
|
||||
<< " maximum=" << maximum;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
} // namespace robot_costmap_2d
|
||||
Reference in New Issue
Block a user