12 Commits

Author SHA1 Message Date
74a02bd4a8 refactor(obstacle_layer): drop the DepthCameraData startup guard
ObstacleLayer and VoxelLayer no longer carry any depth code, so the check
that rejected a DepthCameraData source or frustum_clearing_enabled goes too.
A DepthCameraData source still fails at startup through the generic
data_type check; frustum_clearing_enabled is now an unknown key.

The README and the LayerType comment now say the gateway feeds
DepthCameraObstacleLayer PointCloud2 only.
2026-10-21 13:39:41 +07:00
40dc70e758 feat(depth): DepthCameraObstacleLayer gets its own LayerType
The plugin reported VOXEL_LAYER only because SensorGateway feeds sensor data
to that type. It is its own layer, so LayerType gains DEPTH_CAMERA_LAYER
(appended last: the values of the existing types do not move) and the plugin
returns it. move_base2's SensorGateway delivers PointCloud2 and
DepthCameraData to the new type in the matching commit; without that commit
the layer receives nothing.

matchSize() is overridden as well: CostmapLayer::matchSize() rebuilds the own
grid with the default value, so the stored columns are re-marked under the
layer mutex right away and the whole layer is queued for the next merge.
2026-10-20 14:28:14 +07:00
a5f548f0d7 refactor(depth): DepthCameraObstacleLayer follows the CostmapLayer contract
The port wrote LETHAL straight into the master from its stored 3D points and
left its own grid empty, as costmap_depth_camera does. Everything CostmapLayer
offers on top of the own grid therefore missed the layer: clearArea() (the
ClearCostmapRecovery path), reset() (Costmap2DROBOT::resetLayers()), footprint
clearing and combination_method all acted on an empty grid, and the next cycle
wrote the ghosts back. Cleared cells also stayed on the master until another
layer's bounds covered them (the source's B7).

The stored points stay the source of truth; the clearing and marking
algorithm is unchanged. The own grid now mirrors them cell by cell, the way
VoxelLayer keeps a voxel grid next to its 2D grid:

- marking sets the column's cell LETHAL, the last point of a column leaving
  sets it FREE_SPACE, and both touch the bounds, so a cleared cell leaves the
  master in the same cycle (clear_touches_bounds is gone, always on);
- updateCosts() only merges the own grid with combination_method, like
  ObstacleLayer; combination_method other than 0/1 now means "no effect";
- reset() drops the stored points and buffered observations;
- clearArea() follows CostmapLayer::clearArea(): invert_area false clears
  outside the box and keeps the inside, true clears the inside;
- footprint clearing erases the stored columns under the robot;
- markings that leave the window are dropped in updateBounds() (B6), and a
  column whose cell went missing is re-marked;
- the layer mutex guards the point map, since ClearCostmapRecovery and
  resetLayers() reach it from other threads (recursive mutex, held by the
  recovery around clearArea()).

Tests: the two clear_touches_bounds cases become one bounded-update case, and
clearArea (both directions), reset and footprint clearing get their own.
2026-10-20 13:34:08 +07:00
b23ff27a3c refactor(depth): keep DepthCameraObstacleLayer, drop the legacy depth clearing
Two depth-image clearing designs lived in this package: the frustum ray
clearing inherited from dev_cam_intel (DepthCameraData sources of
ObstacleLayer/VoxelLayer, frustum_* and column_* keys) and the observed_volume
evidence clearing (ROC) on top of it. Both are replaced on the robot by
DepthCameraObstacleLayer, a port of costmap_depth_camera that takes the
filtered PointCloud2 directly, so both are removed and the tree is rebuilt
from main (a63c084) plus the plugin.

- observation.h / observation_buffer: DepthFrustumConfig, DepthCameraObservation
  and the depth buffering API are gone; buffers hold point clouds only.
- ObstacleLayer/VoxelLayer: no frustum ray casting, column clearing or depth
  ray cache. A DepthCameraData source or frustum_clearing_enabled: true now
  fails at startup with a message pointing to DepthCameraObstacleLayer
  instead of silently dropping the camera; DepthCameraData reaching the layer
  through the gateway is ignored.
- copyParentParameters no longer forwards the frustum_* / column_* keys.
- ROC files (depth_evidence_store, depth_visibility, depth_frame_pairer) and
  their tests are not carried over; CloudProcessingConfig goes with them.
- PCL is needed by the plugin library only. The plugin test moves under
  BUILD_COSTMAP_TESTS; BUILD_DEPTH_MARKING_TESTS is gone.
- README documents DepthCameraObstacleLayer and its known limits.

The plugin code is unchanged from the version running on the KIT robot.
2026-10-20 09:47:33 +07:00
9a67eee148 wip: state before depth cleanup
Uncommitted work as it ran on the KIT robot until 2026-10-20: the ROC observed_volume tuning patch on top of 63707c9 and the DepthCameraObstacleLayer plugin (clone of tsengapola/costmap_depth_camera noetic, B6 window fix), its 17 unit tests and the CMake wiring. Kept as one commit so the cleanup that follows has a recoverable starting point; not meant to be pushed.
2026-10-20 09:36:53 +07:00
63707c968c fix(depth): free voxels on clearArea/footprint, accept far returns as behind
clearArea and footprint clearing only wrote the 2D cells, so the voxels and
evidence points stayed MARKED and the next column update brought the phantom
back. VoxelLayer now frees the voxel column and its evidence in both paths
(footprint only for observed_volume; legacy unchanged).

A valid return deeper than depth_valid_max_z_m kept every evidence point
unknown, so phantoms with nothing within 3 m behind never cleared. New key
depth_far_return_is_behind (default false) counts such a return as behind a
point that lies at least free_margin_m inside the trusted range.

Replay of the 2026-10-15 bags: real phantoms 62 -> 53, static-cell dropouts
unchanged, object kept on 10/11 FOV exits as before.
2026-10-15 16:58:23 +07:00
6340838dac fix(depth): forward the evidence-point keys to the layer namespace
Costmap2DROBOT copies a fixed list of observed_volume keys from obstacles/<source>
into <costmap>/obstacles/<source>. The three phase-1 keys were missing, so the
live layer always ran with their C++ defaults (evidence off, marking border 0)
whatever the runtime YAML said. Unit tests set the layer params directly and did
not catch it.

The factory test now checks that the runtime YAML values reach the layer.
2026-10-15 13:40:26 +07:00
5e38857e48 feat(depth): certify evidence points instead of whole voxels (phase 1)
The whole-voxel rule never clears a voxel whose box crosses the image edge.
A person bending over to lift an object leaves high voxels at the top edge
of the image: in the 2026-10-15 lift bag 0 of 54 phantom cells cleared.

- DepthEvidenceStore keeps, per marked voxel, the 6 per-axis extreme points
  plus the most recent ones, keyed by a window-independent cell index.
- DepthVisibilityChecker::classifyPoints: Free only when every evidence
  point projects with a full patch inside the usable image and sees valid
  depth behind it; any surface in front keeps it, invalid depth keeps it.
- Paired marking drops points within depth_marking_border_px of the image
  edge, so every kept point can be re-checked from the pose that saw it.
- Voxels without evidence keep the whole-voxel rule; evidence is erased on
  clear, pruned on rolling shift and every 50 frames.
- New keys depth_evidence_points_enabled (default false),
  depth_evidence_points_per_voxel (8, 6..16), depth_marking_border_px
  (must be > depth_projection_margin_px when enabled); startup log and
  counters (by_evidence, border_dropped_points, evidence_voxels).
- Tests: depth_evidence_store_test; checker and layer tests for the image
  top cut, border drop, rolling shift and a still-visible object.
2026-10-15 13:22:28 +07:00
2ca0bcc1c1 feat(depth): observed_volume depth clearing as deployed 2026-10-14
Baseline commit of the working-tree refactor built on 2026-10-14 17:24 and
running on the KIT robot, recorded in one commit before further changes.

- VoxelLayer clearing looks up TF at the depth image stamp.
- ObservationBuffer: per-source cloud preparation at the measurement stamp,
  height/range gate before the PCL VoxelGrid.
- DepthFramePairer: pairs the marking cloud with the clearing image by
  source and stamp, bounded queue and age.
- DepthVisibilityChecker and the observed_volume clearing mode in VoxelLayer;
  the legacy frustum mode stays the default.
- Tests: depth_observation_buffer_test, depth_visibility_test.
2026-10-15 11:37:56 +07:00
a63c084002 Bring main up to the dev_cam_intel line
main had not moved since 11 July, while the depth-camera work continued on
dev_cam_intel for six weeks. The two branches did not diverge by accident: they
ended up holding two different clearing designs for the same layer.

main carried frustum clearing as VoxelLayer members - frustum_clearing_enabled_,
a pixel step and a min/max range - driven from costmap_2d_robot. dev_cam_intel
replaced that with a full-column clearing pass whose configuration lives per
observation, so the layer keeps no frustum state of its own.

This commit takes the dev_cam_intel tree whole. It is the line running on the
robot, the one rb_ws points at, and the one the NUC measurements were taken
against; the frustum design is superseded rather than merged, and stays in
history at 45c8227 if it is ever wanted back.

Squashed deliberately: the nineteen commits behind it are a working diary -
metrics that were added and removed, test toggles, an optimal-run series - and
none of that is worth carrying onto a branch other trees track.
2026-08-27 13:41:42 +07:00
45c8227f5c change topic and msg depth camera 2026-07-11 10:09:55 +07:00
faa57d9c93 change topic and msg depth camera 2026-07-11 09:50:40 +07:00
25 changed files with 3215 additions and 1623 deletions

View File

@@ -18,9 +18,14 @@ set(CMAKE_CXX_EXTENSIONS OFF)
# Find dependencies # Find dependencies
find_package(Eigen3 REQUIRED) find_package(Eigen3 REQUIRED)
find_package(Boost REQUIRED COMPONENTS system thread filesystem) find_package(Boost REQUIRED COMPONENTS system thread filesystem)
find_package(GTest REQUIRED) # GTest is only needed by the test executables, which the robot deployment build
find_package(PCL REQUIRED COMPONENTS common io) # 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(yaml-cpp REQUIRED)
# DepthCameraObstacleLayer only (voxel grid, kd-tree clearing, Euclidean clustering); the core
# library and the other layers do not use PCL.
find_package(PCL REQUIRED COMPONENTS common filters kdtree search segmentation)
if (NOT BUILDING_WITH_CATKIN) if (NOT BUILDING_WITH_CATKIN)
@@ -78,7 +83,7 @@ else()
INCLUDE_DIRS include INCLUDE_DIRS include
LIBRARIES robot_costmap_2d plugins 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 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( include_directories(
@@ -87,17 +92,15 @@ else()
${EIGEN3_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}
${GTEST_INCLUDE_DIRS} ${GTEST_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
${TF3_INCLUDE_DIR} ${TF3_INCLUDE_DIR}
) )
link_directories(${PCL_LIBRARY_DIRS})
endif() endif()
# Define macro để dùng trong code # Define macro để dùng trong code
add_definitions(-DROBOT_COSTMAP_2D_DIR="${CMAKE_CURRENT_SOURCE_DIR}") add_definitions(-DROBOT_COSTMAP_2D_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
# Eigen và PCL definitions # Eigen definitions
add_definitions(${EIGEN3_DEFINITIONS} ${PCL_DEFINITIONS}) add_definitions(${EIGEN3_DEFINITIONS})
# ======================================================== # ========================================================
# Core library: robot_costmap_2d # Core library: robot_costmap_2d
@@ -123,7 +126,6 @@ if(BUILDING_WITH_CATKIN)
$<INSTALL_INTERFACE:include> $<INSTALL_INTERFACE:include>
${EIGEN3_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
${TF3_INCLUDE_DIR} ${TF3_INCLUDE_DIR}
) )
@@ -132,7 +134,6 @@ if(BUILDING_WITH_CATKIN)
PRIVATE Boost::boost Boost::system Boost::thread Boost::filesystem PRIVATE Boost::boost Boost::system Boost::thread Boost::filesystem
PRIVATE yaml-cpp PRIVATE yaml-cpp
PRIVATE dl PRIVATE dl
PRIVATE ${PCL_LIBRARIES}
PRIVATE ${TF3_LIBRARY} PRIVATE ${TF3_LIBRARY}
) )
@@ -144,7 +145,6 @@ else()
$<INSTALL_INTERFACE:include> $<INSTALL_INTERFACE:include>
${EIGEN3_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
${TF3_INCLUDE_DIR} ${TF3_INCLUDE_DIR}
) )
@@ -155,7 +155,6 @@ else()
Boost::boost Boost::system Boost::thread Boost::filesystem Boost::boost Boost::system Boost::thread Boost::filesystem
yaml-cpp yaml-cpp
dl dl
${PCL_LIBRARIES}
${TF3_LIBRARY} ${TF3_LIBRARY}
) )
@@ -179,7 +178,12 @@ add_library(plugins SHARED
plugins/directional_layer.cpp plugins/directional_layer.cpp
plugins/preferred_layer.cpp plugins/preferred_layer.cpp
plugins/unpreferred_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) if(BUILDING_WITH_CATKIN)
add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
@@ -271,14 +275,19 @@ else()
message(STATUS "Version: ${PROJECT_VERSION}") message(STATUS "Version: ${PROJECT_VERSION}")
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS "Libraries: robot_costmap_2d, plugins") 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 "=================================") message(STATUS "=================================")
endif() endif()
# ======================================================== # ========================================================
# Test executables # Test executables
# ======================================================== # ========================================================
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables" ON) # Default follows the build mode, not a fixed value: a catkin workspace is a
# development machine and gets the tests, while the standalone CMake build is how
# the robot is deployed and must not need GTest installed at all. Force it on with
# -DBUILD_COSTMAP_TESTS=ON to run the tests from a standalone build.
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables"
${BUILDING_WITH_CATKIN})
if(BUILD_COSTMAP_TESTS) if(BUILD_COSTMAP_TESTS)
find_package(GTest REQUIRED) find_package(GTest REQUIRED)
@@ -299,6 +308,7 @@ if(BUILD_COSTMAP_TESTS)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/coordinates_test.cpp) if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/coordinates_test.cpp)
add_executable(test_costmap test/coordinates_test.cpp) add_executable(test_costmap test/coordinates_test.cpp)
target_link_libraries(test_costmap PRIVATE target_link_libraries(test_costmap PRIVATE
plugins
robot_costmap_2d robot_costmap_2d
GTest::GTest GTest::GTest
GTest::Main GTest::Main
@@ -321,4 +331,14 @@ if(BUILD_COSTMAP_TESTS)
${TF3_LIBRARY} ${TF3_LIBRARY}
) )
endif() 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
GTest::GTest
GTest::Main
)
endif()
endif() endif()

653
README.md Normal file
View File

@@ -0,0 +1,653 @@
# robot_costmap_2d
`robot_costmap_2d` là thư viện costmap dạng nhiều lớp của T800. Package duy trì
lưới chi phí 2D dùng cho global/local planner, nhận bản đồ tĩnh và dữ liệu cảm
biến, xóa vùng trống, đánh dấu vật cản, sau đó tạo vùng chi phí an toàn quanh
vật cản.
Package hỗ trợ C++17, catkin và standalone CMake. Các plugin được nạp bằng
`boost::dll` từ thư viện `libplugins`.
## 1. Luồng dữ liệu và kiến trúc
Luồng cập nhật chính:
```text
OccupancyGrid -------------------------> StaticLayer ---------+
LaserScan / PointCloud / PointCloud2 --> ObstacleLayer -------+--> master costmap
LaserScan / PointCloud2 ---------------> VoxelLayer ----------+
PointCloud2 từ depth camera -----------> DepthCameraObstacleLayer
master costmap ------------------------> InflationLayer -------+
```
Mỗi chu kỳ, `LayeredCostmap` gọi lần lượt:
1. `updateBounds()` để từng layer mở rộng vùng cần cập nhật.
2. Reset vùng tương ứng trên master costmap.
3. `updateCosts()` theo đúng thứ tự trong danh sách `plugins`.
Vì vậy thứ tự plugin có ảnh hưởng trực tiếp tới kết quả. Trong cấu hình chạy
thực tế, nên đặt layer bản đồ trước, layer vật cản sau và `InflationLayer` cuối
cùng để cả vật cản tĩnh lẫn vật cản động đều được inflation.
Các plugin được build trong package:
| Plugin | Vai trò |
| --- | --- |
| `StaticLayer` | Đưa `OccupancyGrid` tĩnh vào costmap. |
| `ObstacleLayer` | Marking/clearing 2D từ `LaserScan`, `PointCloud`, `PointCloud2`. |
| `VoxelLayer` | Lưu vật cản theo voxel 3D, chiếu kết quả xuống costmap 2D, xóa bằng raytrace (laser/point cloud). |
| `DepthCameraObstacleLayer` | Vật cản từ depth camera: lưu điểm 3D, xóa trong khối nhìn của camera bằng kd-tree, đánh dấu theo cụm Euclidean. Xem mục 5.6. |
| `InflationLayer` | Tạo vùng chi phí giảm dần quanh ô vật cản. |
| `CriticalLayer` | Gộp vùng critical do hệ thống T800 cung cấp. |
| `DirectionalLayer` | Gộp thông tin vùng có hướng di chuyển. |
| `PreferredLayer` | Gộp vùng ưu tiên. |
| `UnPreferredLayer` | Gộp vùng không ưu tiên. |
## 2. Cách package nạp cấu hình
Tham số có ba tầng ưu tiên, tầng sau ghi đè tầng trước:
1. Giá trị fallback trong code khi một key không tồn tại trong YAML.
2. Các file YAML tên cố định nằm dưới thư mục `config/`.
3. Tham số trong `robot::NodeHandle`, thường được launch nạp cho
`global_costmap` hoặc `local_costmap`.
Biến môi trường `PNKX_NAV_CORE_CONFIG_DIR` phải trỏ tới thư mục cha có thư mục
con `config/`. Hàm nạp sẽ tìm đệ quy các file sau:
- `costmap_params.yaml`
- `static_layer_params.yaml`
- `obstacle_layer_params.yaml`
- `voxel_layer_params.yaml`
- `inflation_layer_params.yaml`
Ví dụ dùng các file mặc định nằm ngay trong package:
```bash
export PNKX_NAV_CORE_CONFIG_DIR=/home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/src/Libraries/costmap_2d
```
Ở hệ thống chạy thật, cấu hình launch-facing nằm trong
`Controllers/Packages/amr_startup/config/`; launch nạp
`costmap_common_params.yaml` riêng vào namespace `global_costmap` và
`local_costmap`, sau đó nạp file global/local tương ứng.
> Không đặt nhiều file trùng tên trong các nhánh con của cùng một thư mục
> `config/`. Hàm tìm kiếm dừng ở file đầu tiên tìm thấy, nên nguồn cấu hình sẽ
> khó xác định.
## 3. Cấu hình mặc định của package
Các file trong `config/` là fallback và cũng được test của package sử dụng.
Chúng mô tả giá trị mặc định, không phải cấu hình hoàn chỉnh để chạy robot.
### 3.1. Costmap chính
File `config/costmap_params.yaml`:
```yaml
robot_costmap_2d:
global_frame: map
robot_base_frame: base_link
rolling_window: false
track_unknown_space: false
plugins:
- name: static_layer
type: StaticLayer
- name: inflation_layer
type: InflationLayer
- name: obstacle_layer
type: ObstacleLayer
- name: voxel_layer
type: VoxelLayer
library_path: ./libplugins.so
footprint:
- [0.3, 0.3]
- [0.3, -0.3]
- [-0.3, -0.3]
- [-0.3, 0.3]
transform_tolerance: 0.0
performance_metrics_enabled: false
performance_metrics_period: 5.0
update_frequency: 1.0
width: 0.0
height: 0.0
resolution: 0.0
origin_x: 0.0
origin_y: 0.0
footprint_padding: 0.0
robot_radius: 0.0
```
Các giá trị `width`, `height` và `resolution` bằng `0.0` chỉ là placeholder.
Khi không có `StaticLayer` resize costmap từ bản đồ, bắt buộc ghi đè cả ba giá
trị bằng số dương trước khi chạy.
Danh sách plugin fallback ở trên phản ánh file hiện tại. Cấu hình deployment
nên khai báo lại plugin và đặt `InflationLayer` cuối danh sách.
### 3.2. Static layer
File `config/static_layer_params.yaml`:
```yaml
static_layer:
enabled: true
map_topic: map
first_map_only: false
subscribe_to_updates: false
track_unknown_space: true
use_maximum: false
lethal_cost_threshold: 100
unknown_cost_value: -1
trinary_costmap: true
base_frame_id: map
```
### 3.3. Obstacle layer
File `config/obstacle_layer_params.yaml` hiện chứa các giá trị cơ sở:
```yaml
obstacle_layer:
track_unknown_space: true
transform_tolerance: 0.2
topic: map
sensor_frame: laser_frame
observation_persistence: 0.0
expected_update_rate: 0.0
data_type: PointCloud
min_obstacle_height: 0.0
max_obstacle_height: 2.0
inf_is_valid: false
clearing: false
marking: true
obstacle_range: 2.5
raytrace_range: 3.0
footprint_clearing_enabled: true
combination_method: 1
```
`ObstacleLayer` chỉ tạo buffer khi có `observation_sources`. Các tham số
`topic`, `data_type`, `marking`, `clearing`, range và height phải được đặt dưới
từng source. Do file fallback trên chưa khai báo `observation_sources`, nó không
tự đăng ký nguồn cảm biến nào.
### 3.4. Voxel layer
File `config/voxel_layer_params.yaml`:
```yaml
voxel_layer:
enabled: true
footprint_clearing_enabled: true
max_obstacle_height: 3.0
origin_z: 0.0
z_resolution: 0.2
z_voxels: 16
unknown_threshold: 15.0
mark_threshold: 0
combination_method: 1
```
Depth camera dùng plugin `DepthCameraObstacleLayer` (mục 5.6), không đi qua `VoxelLayer`.
### 3.5. Inflation layer
File `config/inflation_layer_params.yaml`:
```yaml
inflation_layer:
enabled: true
inflate_unknown: false
cost_scaling_factor: 15.0
inflation_radius: 0.55
```
## 4. Cấu hình tham khảo cho T800
Ví dụ sau dùng laser cho `VoxelLayer` (marking + raytrace clearing) và point cloud đã
xử lý của depth camera cho `DepthCameraObstacleLayer`.
### 4.1. Tham số dùng chung cho global và local costmap
```yaml
robot_base_frame: base_link
transform_tolerance: 1.0
footprint_padding: 0.0
# Polygon phải đo theo robot thật, đơn vị mét, trong robot_base_frame.
footprint:
- [0.583, -0.48]
- [0.583, 0.48]
- [-0.583, 0.48]
- [-0.583, -0.48]
lidar_obstacles:
observation_sources: f_scan
f_scan:
topic: /f_scan
data_type: LaserScan
sensor_frame: ""
marking: true
clearing: true
inf_is_valid: true
observation_persistence: 0.0
expected_update_rate: 0.0
obstacle_range: 2.5
raytrace_range: 3.0
min_obstacle_height: 0.0
max_obstacle_height: 0.25
depth_obstacles:
observation_sources: depth_cam
# tham số chung cho mọi camera của layer: xem mục 5.6
check_radius: 0.1
number_clearing_threshold: 2
ec_seg_distance: 0.2
ec_cluster_min_size: 1
size_of_cluster_rejection: 0
depth_cam:
topic: /camera/depth/points_proc
sensor_frame: ""
sensor_frame_is_optical: true
observation_persistence: 0.0
expected_update_rate: 0.8
FOV_W: 1.23
FOV_V: 0.76
min_detect_distance: 0.15
max_detect_distance: 2.5
min_obstacle_height: 0.04
max_obstacle_height: 1.0
```
### 4.2. Global costmap
```yaml
global_costmap:
library_path: libplugins
global_frame: map
robot_base_frame: base_link
update_frequency: 1.0
rolling_window: false
track_unknown_space: true
resolution: 0.05
plugins:
- {name: navigation_map, type: StaticLayer}
- {name: obstacles, type: VoxelLayer}
- {name: inflation, type: InflationLayer}
navigation_map:
enabled: true
map_topic: /map
track_unknown_space: true
trinary_costmap: true
lethal_cost_threshold: 100
obstacles:
enabled: true
footprint_clearing_enabled: true
origin_z: 0.0
z_resolution: 0.2
z_voxels: 16
unknown_threshold: 15
mark_threshold: 0
combination_method: 1
inflation:
enabled: true
inflate_unknown: false
inflation_radius: 0.60
cost_scaling_factor: 10.0
```
Khi dùng static map, kích thước, resolution và origin có thể được lấy từ
`OccupancyGrid`. Nếu tắt static map, phải khai báo `width`, `height`,
`resolution`, `origin_x` và `origin_y` hợp lệ.
### 4.3. Local costmap
```yaml
local_costmap:
library_path: libplugins
global_frame: odom
robot_base_frame: base_link
update_frequency: 6.0
rolling_window: true
track_unknown_space: false
width: 8.0
height: 8.0
resolution: 0.05
origin_x: 0.0
origin_y: 0.0
plugins:
- {name: lidar_obstacles, type: VoxelLayer}
- {name: depth_obstacles, type: DepthCameraObstacleLayer}
- {name: inflation, type: InflationLayer}
lidar_obstacles:
enabled: true
footprint_clearing_enabled: true
origin_z: 0.0
z_resolution: 0.15
z_voxels: 8
unknown_threshold: 7
mark_threshold: 0
combination_method: 1
inflation:
enabled: true
inflate_unknown: false
inflation_radius: 0.55
cost_scaling_factor: 10.0
```
Với rolling window, code tự cập nhật origin theo pose robot; `origin_x` và
`origin_y` ban đầu không phải tâm cửa sổ cố định quanh robot.
## 5. Ý nghĩa và cách chỉnh từng nhóm tham số
### 5.1. Hình học và kích thước costmap
| Tham số | Đơn vị | Mặc định package | Ý nghĩa và cách chỉnh |
| --- | ---: | ---: | --- |
| `global_frame` | frame | `map` | Global costmap thường dùng `map`; local costmap thường dùng `odom`. |
| `robot_base_frame` | frame | `base_link` | Phải có TF ổn định từ frame này tới `global_frame`. |
| `rolling_window` | bool | `false` | Bật cho local costmap để cửa sổ đi theo robot. |
| `track_unknown_space` | bool | `false` | Bật khi planner cần phân biệt vùng chưa biết với vùng trống. |
| `width`, `height` | m | `0.0` | Kích thước cửa sổ. Tăng để nhìn xa hơn nhưng tăng CPU/RAM theo diện tích. |
| `resolution` | m/cell | `0.0` | Giảm để chi tiết hơn nhưng số cell tăng theo nghịch đảo bình phương. Giá trị chạy T800 thường là `0.05`. |
| `origin_x`, `origin_y` | m | `0.0` | Góc dưới trái của costmap không rolling. Với static map thường lấy từ map. |
| `update_frequency` | Hz | `1.0` | Tốc độ tính costmap. Local cần nhanh hơn global nhưng không nên cao hơn khả năng cấp dữ liệu/CPU. |
| `transform_tolerance` | s | `0.0` | Dung sai TF. Chỉ tăng vừa đủ cho jitter; không dùng để che lỗi timestamp hoặc TF bị mất. |
| `footprint_padding` | m | `0.0` | Biên an toàn cộng đều quanh footprint. |
| `robot_radius` | m | `0.0` | Dùng cho robot tròn. Với T800 dạng chữ nhật nên khai báo polygon `footprint`. |
Số cell 2D xấp xỉ:
```text
(width / resolution) * (height / resolution)
```
Ví dụ cửa sổ `8 m x 8 m`, resolution `0.05 m` có `160 x 160 = 25,600`
cell. Nếu dùng `16` lớp voxel thì phần voxel có khoảng `409,600` ô.
### 5.2. Footprint
`footprint` là polygon theo mét trong `robot_base_frame`. Đây là tham số an toàn,
phải đo theo kích thước ngoài cùng thực tế của robot và tải hàng, không đo theo
khung chassis bên trong.
Quy trình chỉnh:
1. Đo khoảng cách từ tâm `robot_base_frame` tới mép trước, sau, trái, phải.
2. Khai báo các đỉnh theo thứ tự quanh polygon, không tự cắt nhau.
3. Kiểm tra pose quay tại chỗ gần tường và góc kệ.
4. Chỉ dùng `footprint_padding` cho sai số nhỏ; không dùng padding để bù một
footprint sai lớn.
### 5.3. StaticLayer
| Tham số | Mặc định | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `enabled` | `true` | Bật/tắt layer. |
| `map_topic` | `map` | Topic `OccupancyGrid`. |
| `first_map_only` | `false` | `true` nếu map không thay đổi và muốn bỏ các map gửi lại. |
| `subscribe_to_updates` | `false` | Bật nếu map server gửi `OccupancyGridUpdate`. |
| `track_unknown_space` | `true` | Giữ ô `unknown_cost_value` là `NO_INFORMATION`; tắt để coi unknown là free. |
| `use_maximum` | `false` | `false`: overwrite master; `true`: lấy max để không làm mất cost đã có. |
| `lethal_cost_threshold` | `100` | Occupancy value từ ngưỡng này trở lên được coi là lethal; code clamp trong `[0, 100]`. |
| `unknown_cost_value` | `-1` | Giá trị unknown trong map đầu vào. |
| `trinary_costmap` | `true` | Chỉ phân loại free/lethal/unknown; tắt để scale dải occupancy thành cost. |
| `base_frame_id` | `map` | Frame dùng bởi layer map trong implementation T800. |
### 5.4. Observation source của ObstacleLayer/VoxelLayer
`observation_sources` là chuỗi các tên source cách nhau bằng khoảng trắng, ví
dụ `f_scan b_scan`. Mỗi tên phải có một map tham số cùng tên.
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `topic` | `map` | Topic input. Đây cũng là key dispatch callback, phải khớp tuyệt đối. |
| `data_type` | `PointCloud` | Một trong `LaserScan`, `PointCloud`, `PointCloud2`; giá trị khác báo lỗi lúc khởi động. |
| `sensor_frame` | rỗng | Để rỗng để dùng `header.frame_id`; chỉ đặt khi cần ép origin của sensor. |
| `marking` | `true` | Đánh dấu điểm quan sát thành vật cản. |
| `clearing` | `false` | Raytrace PointCloud/LaserScan để xóa vùng trống. |
| `inf_is_valid` | `false` | Với `LaserScan`, coi `+Inf` là tia không gặp vật cản để clearing. Không áp dụng cho point cloud. |
| `observation_persistence` | `0.0 s` | `0`: chỉ giữ mẫu mới nhất; tăng khi sensor thưa nhưng có thể tạo ghost obstacle. |
| `expected_update_rate` | `0.0 s` | Khoảng thời gian cập nhật mong đợi; `0`: không kiểm tra stale. Trong code đây là duration, không phải Hz. |
| `min_obstacle_height` | `0.0 m` | Bỏ điểm thấp hơn ngưỡng, hữu ích để lọc sàn. |
| `max_obstacle_height` | `2.0 m` | Bỏ điểm cao hơn ngưỡng. Phải phù hợp chiều cao robot/kệ và dải z của voxel. |
| `obstacle_range` | `2.5 m` | Khoảng cách tối đa dùng để marking. |
| `raytrace_range` | `3.0 m` | Khoảng cách tối đa dùng để clearing. Thường đặt lớn hơn `obstacle_range`. |
Lưu ý `expected_update_rate` được truyền vào `robot::Duration`. Ví dụ `0.5`
nghĩa là kỳ vọng có dữ liệu ít nhất mỗi `0.5 s`, tương đương tối thiểu `2 Hz`.
### 5.5. VoxelLayer
| Tham số | Mặc định YAML | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `enabled` | `true` | Bật/tắt layer. |
| `origin_z` | `0.0 m` | Đáy của voxel grid trong hệ tọa độ costmap. |
| `z_resolution` | `0.2 m` | Chiều cao mỗi voxel. Giảm để phân giải z tốt hơn nhưng dễ nhiễu và tốn xử lý hơn. |
| `z_voxels` | `16` | Số lớp z; implementation dùng tối đa 16 bit cho mỗi cột, nên giữ trong `1..16`. |
| `max_obstacle_height` | `3.0 m` | Trần điểm hợp lệ của layer. |
| `unknown_threshold` | `15` | Số voxel unknown cần để cột 2D còn unknown; cần chỉnh cùng `z_voxels`. |
| `mark_threshold` | `0` | Số voxel marked cần để cột 2D thành vật cản. Tăng nếu một điểm nhiễu đơn lẻ thường tạo vật cản giả. |
| `combination_method` | `1` | `0`: overwrite master, `1`: lấy maximum. Thường dùng `1` để không xóa cost layer trước. |
| `footprint_clearing_enabled` | `true` | Xóa vật cản nằm trong footprint hiện tại của robot. |
Dải z của voxel xấp xỉ:
```text
[origin_z, origin_z + z_resolution * z_voxels)
```
Dải này phải bao phủ vùng `min_obstacle_height..max_obstacle_height` mà robot
cần quan sát. Không tăng `max_obstacle_height` vượt khỏi voxel grid mà không
đồng thời kiểm tra `origin_z`, `z_resolution` và `z_voxels`.
### 5.6. DepthCameraObstacleLayer
Port thuật toán của `costmap_depth_camera` (noetic). Layer có loại riêng `LayerType::DEPTH_CAMERA_LAYER`:
`SensorGateway` của `move_base2` chỉ đẩy `PointCloud2` vào nó (không đẩy `LaserScan`, `PointCloud`, `DepthCameraData`).
Layer nhận `PointCloud2` đã lọc của từng depth camera và giữ các điểm vật cản 3D trong frame global của costmap. Lưới riêng của layer
phản chiếu các điểm đó theo từng ô (cột có điểm là `LETHAL`, cột mất điểm cuối cùng thành
`FREE_SPACE`), rồi được gộp lên master như `ObstacleLayer` (`combination_method`). Mỗi chu kỳ:
1. Cloud mới nhất của từng source được biến đổi sang frame global bằng TF **tại đúng
stamp của cloud** (chờ tối đa `transform_tolerance`, quá hạn thì bỏ cloud và log lỗi),
lọc theo `min/max_obstacle_height`, rồi gộp voxel 5 cm.
2. **Xóa:** điểm đã lưu nằm trong khối nhìn (frustum) của bất kỳ camera nào bị xóa nếu cloud
hiện tại có ít hơn `number_clearing_threshold` điểm trong bán kính `check_radius`,
hoặc nếu điểm cách tâm robot dưới `forced_clearing_distance`. Cloud có
`<= number_points_considered_as_blocked` điểm thì xóa hết trong khối nhìn, trừ khi
bật `enable_near_blocked_protection`.
3. **Đánh dấu:** gom cụm Euclidean (`ec_seg_distance`); cụm có `<= size_of_cluster_rejection`
điểm bị bỏ; điểm của cụm còn lại nằm trong khối nhìn và cách mọi mặt khối nhìn hơn
12 cm thì được lưu.
4. Điểm ra ngoài cửa sổ costmap (rolling window) bị bỏ; điểm dưới footprint robot bị xóa khi
bật `footprint_clearing_enabled`.
Mọi ô đổi trạng thái (đánh dấu hoặc xóa) đều được đưa vào vùng cập nhật, nên ô vừa xóa biến
khỏi master ngay trong chu kỳ đó. `reset()` (dùng bởi `Costmap2DROBOT::resetLayers()`) xóa toàn
bộ điểm đã lưu; `clearArea()` (dùng bởi `ClearCostmapRecovery`) xóa điểm theo đúng ngữ nghĩa
của `CostmapLayer::clearArea()`: `invert_area: false` xóa các ô **ngoài** hình chữ nhật và giữ
các ô bên trong, `true` xóa các ô **bên trong**.
Tham số chung của layer:
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `enabled` | `true` | Bật/tắt layer. |
| `observation_sources` | rỗng | Danh sách tên source, mỗi camera một source. |
| `check_radius` | `0.1 m` | Bán kính tìm điểm cloud quanh điểm đã lưu khi xét xóa. |
| `number_clearing_threshold` | `2` | Ít hơn số điểm này trong `check_radius` thì xóa. Giảm xuống `1`: giữ vật nhỏ tốt hơn, ma xóa chậm hơn một chút. |
| `ec_seg_distance` | `0.2 m` | Khoảng cách gom cụm. |
| `ec_cluster_min_size` | `5` | Cụm nhỏ nhất PCL trả về. Vật nhỏ (vài voxel) cần `1`. |
| `size_of_cluster_rejection` | `5` | Bỏ cụm có số điểm không vượt quá giá trị này. Vật nhỏ cần `0`. |
| `forced_clearing_distance` | `0.1 m` | Điểm trong khối nhìn gần tâm robot hơn mức này luôn bị xóa. |
| `enable_near_blocked_protection` | `true` | `false`: cloud gần như trống thì xóa hết trong khối nhìn. |
| `number_points_considered_as_blocked` | `5` | Ngưỡng "cloud gần như trống". |
| `voxel_resolution` | `0.01 m` | Bước lượng tử độ cao của điểm lưu. |
| `use_voxelized_observation` | `true` | Gộp voxel 5 cm trước khi xử lý. |
| `transform_tolerance` | `0.2 s` | Thời gian chờ TF tại stamp của cloud. |
| `footprint_clearing_enabled` | `true` | Xóa ô và điểm đã lưu nằm dưới footprint robot. |
| `combination_method` | `1` | Như các layer khác. |
| `use_global_frame_to_mark` | `true` | Chỉ hỗ trợ `true`; `false` báo lỗi. |
| `debug/stats` | `true` | Log `[debug/stats]` định kỳ: số điểm, số điểm đánh dấu/xóa, TF chờ/bỏ, thời gian. |
| `debug/stats_period` | `5.0 s` | Chu kỳ log trên. |
Tham số của từng source (camera):
| Tham số | Mặc định code | Ý nghĩa |
| --- | ---: | --- |
| `topic` | tên source | Topic `PointCloud2`, phải khớp tên topic mà gateway đẩy vào. |
| `sensor_frame` | rỗng | Rỗng: dùng frame của cloud để dựng khối nhìn. |
| `sensor_frame_is_optical` | `false` | `true` khi frame là frame quang học (Z hướng nhìn). |
| `FOV_W`, `FOV_V` | `1.5`, `1.0 rad` | Góc nhìn ngang/dọc của khối nhìn. Tính từ `camera_info`. |
| `min_detect_distance`, `max_detect_distance` | `0.15`, `2.5 m` | Mặt gần/xa của khối nhìn. Ngoài khoảng này không đánh dấu, không xóa. |
| `min_obstacle_height`, `max_obstacle_height` | `0.0`, `2.0 m` | Lọc độ cao trong frame global. |
| `marking` | `true` | `false`: bỏ qua source. |
| `observation_persistence` | `0.0 s` | `0`: chỉ dùng cloud mới nhất. |
| `expected_update_rate` | `0.0 s` | Quá lâu không có cloud thì costmap báo không current. `0`: tắt. |
Giới hạn đã biết:
- Điểm chỉ được xét xóa khi nằm **trong khối nhìn**. Điểm ra ngoài khối nhìn (robot quay đi,
vật đi ra ngoài FOV, hoặc điểm cao vượt mép trên ảnh khi robot tới gần) được giữ cho tới
khi ra khỏi cửa sổ costmap. Đặt `max_obstacle_height` sát chiều cao robot để giảm loại thứ
hai.
- Khối nhìn đối xứng và trùng mép ảnh; dải mép ảnh không có depth (lọc mép, dải stereo
bên trái) vẫn được coi là "nhìn thấy trống".
- Layer không dùng ảnh depth (`DepthCameraData`): host phải đổi ảnh sang `PointCloud2` trước khi đẩy vào.
### 5.7. InflationLayer
| Tham số | Mặc định | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `enabled` | `true` | Bật/tắt inflation. |
| `inflation_radius` | `0.55 m` | Bán kính tối đa có cost quanh vật cản. Tăng để robot tránh xa hơn. |
| `cost_scaling_factor` | `15.0` | Hệ số suy giảm mũ. **Tăng** giá trị làm cost giảm nhanh hơn và vùng cost mạnh hẹp hơn; **giảm** giá trị làm robot giữ khoảng cách mềm xa hơn. |
| `inflate_unknown` | `false` | Có inflation vùng unknown hay không. Bật có thể làm planner thận trọng hơn nhưng dễ chặn đường trong map chưa hoàn chỉnh. |
`inflation_radius` phải được chọn sau khi footprint đúng. Bán kính này nên lớn
hơn inscribed radius cộng biên an toàn mong muốn; tăng radius không thể sửa một
footprint sai.
### 5.8. Performance metrics
| Tham số | Mặc định | Ý nghĩa |
| --- | ---: | --- |
| `performance_metrics_enabled` | `false` | Log thời gian `updateBounds` và `updateCosts` theo từng layer. |
| `performance_metrics_period` | `5.0 s` | Chu kỳ tổng hợp và in metrics. |
Bật metrics trong lúc tuning CPU, sau đó có thể tắt để giảm log runtime.
## 6. Quy trình tuning khuyến nghị
Chỉ thay một nhóm tham số mỗi lần và lưu lại bag/log trước khi chỉnh.
1. **Kiểm tra TF và timestamp**: phải có transform liên tục từ từng sensor frame
tới `map`/`odom`. Không tuning costmap khi TF còn lỗi.
2. **Chốt footprint**: đo robot và tải hàng thật, kiểm tra quay tại chỗ.
3. **Chọn resolution và kích thước cửa sổ**: bắt đầu `0.05 m`; local thường
`6..10 m` tùy vận tốc và khoảng phanh.
4. **Chỉ bật marking**: xác nhận vật cản xuất hiện đúng vị trí, đúng height và
range.
5. **Bật clearing**: laser/point cloud dùng raytrace; depth camera dùng
`DepthCameraObstacleLayer`.
6. **Chỉnh voxel**: đặt dải z, sau đó tăng `mark_threshold` nếu nhiễu đơn điểm.
7. **Chỉnh inflation**: chỉnh `inflation_radius` trước, sau đó mới chỉnh
`cost_scaling_factor` theo khoảng cách đường đi mong muốn.
8. **Đo tải CPU**: bật performance metrics; chỉ tăng frequency hoặc giảm
resolution khi chu kỳ cập nhật vẫn hoàn thành ổn định.
Các ràng buộc nên giữ:
```text
resolution > 0
width > 0 và height > 0 nếu không lấy size từ static map
raytrace_range >= obstacle_range
max_detect_distance > min_detect_distance >= 0 (DepthCameraObstacleLayer)
1 <= z_voxels <= 16
origin_z + z_resolution * z_voxels đủ bao phủ dải vật cản cần quan sát
InflationLayer nằm sau các layer tạo vật cản
```
## 7. Tuning theo triệu chứng
| Triệu chứng | Kiểm tra trước | Hướng chỉnh |
| --- | --- | --- |
| Vật cản đã đi nhưng vẫn còn trên costmap | TF, topic clearing, dữ liệu có còn cập nhật; với depth: điểm có nằm trong khối nhìn không | Bật đúng `clearing`; giảm `observation_persistence`; với depth xem giới hạn ở mục 5.6. |
| Vật cản thật không được đánh dấu | Topic/type/frame, range và height | Kiểm tra `marking`, `min/max_obstacle_height`, `obstacle_range`; với voxel thử `mark_threshold: 0` trước. |
| Vật cản chớp tắt | Tần số sensor, packet drop, TF | Đặt `expected_update_rate` đúng chu kỳ; tăng nhẹ `observation_persistence` nhưng phải kiểm tra ghost obstacle. |
| Robot đi quá sát vật cản | Footprint trước, inflation sau | Tăng `inflation_radius` hoặc giảm `cost_scaling_factor`. |
| Robot tránh quá xa/không tìm được đường | Footprint, unknown space, inflation | Giảm `inflation_radius` hoặc tăng `cost_scaling_factor`; kiểm tra `inflate_unknown`. |
| Costmap local trễ hoặc CPU cao | Metrics theo layer | Tăng `resolution`, giảm `width/height`, giảm `update_frequency`, giảm `max_detect_distance` hoặc giảm mật độ `/camera/depth/points_proc`. |
| Costmap báo stale/not current | Sensor thực tế có đúng chu kỳ không | Tăng giá trị `expected_update_rate` theo đơn vị giây hoặc đặt `0` để tắt kiểm tra trong lúc chẩn đoán. |
| Vật nhỏ/thấp từ depth bị mất | Số điểm trên vật sau lọc độ cao | `ec_cluster_min_size: 1`, `size_of_cluster_rejection: 0`, cân nhắc `number_clearing_threshold: 1` và `min_obstacle_height` (đổi lại: dễ có sàn ma nếu TF camera lệch). |
| Sensor origin nằm ngoài voxel map | `global_frame`, rolling window, TF z | Sửa TF/origin, tăng cửa sổ phù hợp; không chỉ tăng tolerance. |
| Vật cản sàn/nhiễu thấp xuất hiện | Height filter và calibration | Tăng `min_obstacle_height` từng bước nhỏ; không tăng quá đáy vật cản robot cần tránh. |
## 8. Lưu ý cho depth camera
- Layer chỉ dùng `PointCloud2` đã lọc (ví dụ `/camera/depth/points_proc`); bridge đổi ảnh
depth sang cloud trước khi đẩy vào nav core.
- Mỗi camera là một source trong `observation_sources` của cùng một
`DepthCameraObstacleLayer`, với topic, frame, FOV và dải độ cao riêng.
- Ngưỡng độ cao làm việc trong frame global: sai số lắp camera (roll, pitch, chiều cao)
quyết định ngưỡng thấp nhất dùng được trước khi sàn bị đánh dấu.
- Khi mất marking, kiểm tra lần lượt cloud sau bridge, TF tại stamp của cloud (dòng
`[debug/stats]`: `tf_wait`, `tf_drop`) và ngưỡng cụm trước khi đổi ngưỡng độ cao.
## 9. Build và kiểm tra
Build package trong workspace:
```bash
cd /home/duongtd/T800_ws
catkin_make --pkg robot_costmap_2d
```
Các executable test được tạo khi `BUILD_COSTMAP_TESTS=ON`:
```bash
./devel/lib/robot_costmap_2d/test_array_parser
./devel/lib/robot_costmap_2d/test_costmap
./devel/lib/robot_costmap_2d/test_plugin
./devel/lib/robot_costmap_2d/depth_camera_obstacle_layer_test
```
Kiểm tra tối thiểu trước khi chạy robot:
- YAML parse được và đúng namespace global/local.
- `library_path` tìm thấy `libplugins`.
- Plugin được tạo đúng tên và đúng thứ tự.
- TF giữa sensor, `robot_base_frame` và `global_frame` sẵn sàng.
- Sensor topic, `data_type` và `header.frame_id` khớp cấu hình.
- Costmap update ổn định, không stale và không vượt ngân sách chu kỳ.
- Footprint và inflation đã được kiểm tra ở tốc độ thấp trước.
## 10. Cấu trúc package
```text
costmap_2d/
├── config/ # Fallback YAML của package
├── include/robot_costmap_2d/ # Public headers
├── plugins/ # Layer implementations
├── src/ # Costmap core và observation buffer
├── test/ # Unit/integration tests
├── CMakeLists.txt
└── package.xml
```

View File

@@ -25,6 +25,8 @@ robot_costmap_2d:
- [-0.3, 0.3] - [-0.3, 0.3]
transform_tolerance: 0.0 transform_tolerance: 0.0
performance_metrics_enabled: false
performance_metrics_period: 5.0
update_frequency: 1.0 update_frequency: 1.0
width: 0.0 width: 0.0
height: 0.0 height: 0.0
@@ -33,4 +35,4 @@ robot_costmap_2d:
origin_y: 0.0 origin_y: 0.0
footprint_padding: 0.0 footprint_padding: 0.0
robot_radius: 0.0 robot_radius: 0.0

View File

@@ -7,6 +7,4 @@ voxel_layer:
z_voxels: 16 z_voxels: 16
unknown_threshold: 15.0 unknown_threshold: 15.0
mark_threshold: 0 mark_threshold: 0
combination_method: 1 combination_method: 1
frustum_clearing_enabled: true
frustum_clearing_pixel_step: 8

View File

@@ -86,6 +86,18 @@ public:
*/ */
Costmap2D& operator=(const Costmap2D& map); 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 * @brief Turn this costmap into a copy of a window of a costmap passed in
* @param map The costmap to copy * @param map The costmap to copy
@@ -425,6 +437,7 @@ protected:
double origin_y_; double origin_y_;
unsigned char* costmap_; unsigned char* costmap_;
unsigned char default_value_; unsigned char default_value_;
std::vector<unsigned char> rolling_window_scratch_;
class MarkCell class MarkCell
{ {

View File

@@ -157,6 +157,35 @@ public:
return layered_costmap_->getCostmap(); 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 * @brief Returns the global frame of the costmap
* @return The global frame of the costmap * @return The global frame of the costmap
@@ -174,6 +203,17 @@ public:
{ {
return robot_base_frame_; 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 LayeredCostmap* getLayeredCostmap() const
{ {
return layered_costmap_; return layered_costmap_;
@@ -279,6 +319,11 @@ private:
robot_geometry_msgs::PolygonStamped footprint_; robot_geometry_msgs::PolygonStamped footprint_;
float footprint_padding_; 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: private:
void getParams(const std::string& config_file_name,const std::string& name, robot::NodeHandle& nh); void getParams(const std::string& config_file_name,const std::string& name, robot::NodeHandle& nh);
}; };

View File

@@ -0,0 +1,248 @@
/*********************************************************************
* Port of costmap_depth_camera::DepthCameraObstacleLayer (BSD, Apola),
* https://github.com/tsengapola/costmap_depth_camera, noetic branch 59b7737,
* onto robot_costmap_2d (boost::dll, robot::NodeHandle, tf3).
*
* The clearing and marking algorithm is the source's (kd-tree "seen again" test inside the
* frustums, Euclidean clusters away from the frustum faces). How the result reaches the costmap
* follows the CostmapLayer contract of ObstacleLayer/VoxelLayer instead of the source, which
* wrote LETHAL straight into the master and left its own grid empty:
* - the stored 3D points (pc_3d_map_global_) stay the source of truth, and this layer's own
* grid mirrors them cell by cell: a column with points is LETHAL, a column that loses its
* last point becomes FREE_SPACE, and every such change touches the update bounds, so a
* cleared cell leaves the master in the same cycle (the source's B7);
* - updateCosts() only merges the own grid (combination_method), like ObstacleLayer;
* - reset(), clearArea() and footprint clearing also erase the stored points, so
* Costmap2DROBOT::resetLayers() and ClearCostmapRecovery work on this layer (the source's
* reset() kept its global-mode points, B9).
* Host adaptations: data arrives through handleImpl() and a cloud is processed in
* updateBounds() once TF at its stamp exists (the role of the tf2_ros::MessageFilter);
* getType() is its own DEPTH_CAMERA_LAYER, which SensorGateway feeds PointCloud2 and
* DepthCameraData; no ROS publishers or dynamic_reconfigure; `sensor_frame_is_optical` builds the frustum in a Z-forward
* optical frame; markings that leave the rolling window are dropped (B6).
*********************************************************************/
#ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
#define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_layer.h>
#include <robot_costmap_2d/layered_costmap.h>
#include <robot_costmap_2d/footprint.h>
#include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <tf3/buffer_core.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <array>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
namespace robot_costmap_2d
{
/**
* @brief Truncated pyramid of one depth camera observation, in the global frame.
*
* Same construction as costmap_depth_camera::Observation: 8 vertices from the configured
* FOV and detect range in the sensor frame, transformed to the global frame, then 6 inward
* normals (inside test) and 6 plane equations (12 cm "attach" band test).
*/
struct DepthCameraFrustum
{
Eigen::Vector3f origin = Eigen::Vector3f::Zero(); ///< sensor origin, global frame [m]
std::array<Eigen::Vector3f, 8> vertices; ///< TLNear TRNear BLNear BRNear TLFar TRFar BLFar BRFar
std::array<Eigen::Vector3f, 6> normals; ///< near right bottom left far top
std::array<Eigen::Vector4f, 6> planes; ///< a, b, c, d of each face
double max_detect_distance = 2.5; ///< [m]
/**
* @brief Build the frustum.
* @param T_global_sensor pose of the sensor frame in the global frame
* @param fov_w, fov_v full horizontal / vertical field of view [rad]
* @param min_d, max_d near / far plane distance along the viewing axis [m]
* @param optical true: sensor frame is Z forward, X right, Y down (REP 103 optical);
* false: X forward, Y left, Z up (camera_link), as the source assumes
*/
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
double max_d, bool optical);
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
bool inside(const Eigen::Vector3f& p) const;
/// Within 0.12 m of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
bool nearFace(const Eigen::Vector3f& p) const;
};
/// FrustumUtils::isInsideFRUSTUMs: inside at least one frustum.
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
/// FrustumUtils::isAttachFRUSTUMs: near a face of one frustum and not well inside another.
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
class DepthCameraObstacleLayer : public CostmapLayer
{
public:
DepthCameraObstacleLayer();
~DepthCameraObstacleLayer() override;
void onInitialize() override;
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
double* max_x, double* max_y) override;
void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override;
void activate() override;
void deactivate() override;
/// Drops the stored points and the buffered observations as well as the own grid.
void reset() override;
/**
* @brief Same contract as CostmapLayer::clearArea(), applied to the stored points too.
*
* Cells strictly inside (start, end) are kept and the rest is cleared when invert_area is
* false; invert_area true clears the inside instead. Called by ClearCostmapRecovery with the
* layer mutex held (recursive).
*/
void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override;
/// Own type: SensorGateway delivers PointCloud2 and DepthCameraData to it, not LaserScan.
LayerType getType() const override
{
return LayerType::DEPTH_CAMERA_LAYER;
}
/// Resizes the own grid to the master and re-marks the stored columns right away.
void matchSize() override;
/// Number of stored (column, height) points, for tests and the stats log.
std::size_t storedPoints() const;
protected:
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
private:
/// One observation: cloud after TF and the height gate, plus its frustum (both global frame).
struct Observation
{
robot::Time stamp;
std::vector<Eigen::Vector3f> points;
DepthCameraFrustum frustum;
};
/// ObservationBuffer of the source, one per entry of observation_sources.
struct Source
{
std::string name;
std::string topic;
std::string sensor_frame;
bool sensor_frame_is_optical = false;
double observation_keep_time = 0.0; ///< [s] 0 keeps only the newest observation
double expected_update_rate = 0.0; ///< [s] 0 disables the staleness check
double min_obstacle_height = 0.0; ///< [m] global-frame z gate
double max_obstacle_height = 2.0; ///< [m]
double fov_w = 1.5; ///< [rad]
double fov_v = 1.0; ///< [rad]
double min_detect_distance = 0.15; ///< [m]
double max_detect_distance = 2.5; ///< [m]
bool marking = true;
std::list<Observation> observations; ///< newest first
robot::Time last_updated;
std::mutex pending_mutex; ///< guards pending: handleImpl runs on the producer thread
std::shared_ptr<const robot_sensor_msgs::PointCloud2> pending;
};
void loadParameters();
bool processPending(Source& source);
bool bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud);
void purgeStale(Source& source) const;
bool sourceIsCurrent(const Source& source) const;
void clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
const std::vector<DepthCameraFrustum>& frustums, double robot_x,
double robot_y, double* min_x, double* min_y, double* max_x,
double* max_y);
void processCluster(const std::vector<DepthCameraFrustum>& frustums,
const std::vector<Eigen::Vector3f>& cluster, double* min_x, double* min_y,
double* max_x, double* max_y);
void updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y);
bool isValid(int mx, int my) const;
/// Own-grid cell of a stored column; false when it is outside the window or on its edge.
bool columnCell(const std::pair<int, int>& column, unsigned int& mx, unsigned int& my) const;
/// Drops columns that left the window (B6), frees edge cells, re-marks cells a column lost.
void dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, double* max_y);
/// The column became empty: erase it, free its own-grid cell and touch the bounds.
std::map<std::pair<int, int>, std::map<int, float>>::iterator eraseColumn(
std::map<std::pair<int, int>, std::map<int, float>>::iterator it, double* min_x, double* min_y,
double* max_x, double* max_y);
void logStats();
// (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points.
void worldToIntIndex(double wx, double wy, int& mx, int& my, double resolution) const
{
mx = static_cast<int>(wx / resolution);
my = static_cast<int>(wy / resolution);
}
void intIndexToWorld(double& wx, double& wy, int mx, int my, double resolution) const
{
wx = mx * resolution;
wy = my * resolution;
}
std::string global_frame_;
bool rolling_window_ = false;
std::vector<std::unique_ptr<Source>> sources_;
// Parameters, names and defaults as in the source.
bool footprint_clearing_enabled_ = true;
int combination_method_ = 1; ///< 0 overwrite, 1 maximum, other: nothing
bool enable_near_blocked_protection_ = true;
int number_points_considered_as_blocked_ = 5;
double forced_clearing_distance_ = 0.1; ///< [m] from robot_base_frame
double ec_seg_distance_ = 0.2; ///< [m] Euclidean cluster tolerance
int ec_cluster_min_size_ = 5;
int size_of_cluster_rejection_ = 5; ///< clusters with <= this many points are not marked
double voxel_resolution_ = 0.01; ///< [m] height quantization of stored points
double check_radius_ = 0.1; ///< [m] kd-tree radius of the "seen again" test
int number_clearing_threshold_ = 2; ///< fewer neighbours than this clears the point
bool use_voxelized_observation_ = true; ///< VoxelGrid 5 cm on the combined cloud
double transform_tolerance_ = 0.2; ///< [s] how long a cloud may wait for its TF
double marking_height_under_ground_ = 100.0;
double marking_height_above_ground_ = -100.0;
// Additions of this port.
bool debug_stats_ = true; ///< debug/stats: periodic counters log
double debug_stats_period_ = 5.0; ///< [s]
/// (ix, iy) of the cell corner -> {height index -> label}, global frame (use_global_frame_to_mark).
std::map<std::pair<int, int>, std::map<int, float>> pc_3d_map_global_;
std::vector<robot_geometry_msgs::Point> transformed_footprint_;
struct Stats
{
std::size_t cycles = 0;
std::size_t cloud_points = 0;
std::size_t marked = 0;
std::size_t cleared = 0;
std::size_t footprint_cleared = 0; ///< columns erased under the robot footprint
std::size_t cleared_all_frames = 0;
std::size_t bypassed_frames = 0;
std::size_t tf_waits = 0;
std::size_t tf_drops = 0;
std::size_t dropped_out_of_window = 0;
double bounds_ms_sum = 0.0;
double bounds_ms_max = 0.0;
} stats_;
robot::Time last_stats_log_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_

View File

@@ -42,6 +42,9 @@
#include <robot_costmap_2d/layered_costmap.h> #include <robot_costmap_2d/layered_costmap.h>
#include <boost/thread.hpp> #include <boost/thread.hpp>
#include <cstdint>
#include <vector>
namespace robot_costmap_2d namespace robot_costmap_2d
{ {
/** /**
@@ -77,8 +80,7 @@ public:
virtual ~InflationLayer() virtual ~InflationLayer()
{ {
deleteKernels(); deleteKernels();
if (seen_) delete inflation_access_;
delete[] seen_;
} }
virtual void onInitialize(); virtual void onInitialize();
@@ -184,10 +186,13 @@ private:
unsigned int cell_inflation_radius_; unsigned int cell_inflation_radius_;
unsigned int cached_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_; std::vector<std::uint32_t> seen_;
int seen_size_; std::uint32_t seen_generation_ = 0;
unsigned char** cached_costs_; unsigned char** cached_costs_;
double** cached_distances_; double** cached_distances_;

View File

@@ -56,7 +56,10 @@ enum class LayerType
DIRECTIONAL_LAYER, DIRECTIONAL_LAYER,
PREFERRED_LAYER, PREFERRED_LAYER,
UNPREFERRED_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; class LayeredCostmap;

View File

@@ -43,6 +43,8 @@
#include <robot_costmap_2d/costmap_2d.h> #include <robot_costmap_2d/costmap_2d.h>
#include <vector> #include <vector>
#include <string> #include <string>
#include <chrono>
#include <cstdint>
namespace robot_costmap_2d namespace robot_costmap_2d
{ {
@@ -71,6 +73,14 @@ public:
*/ */
void updateMap(double robot_x, double robot_y, double robot_yaw); 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 inline const std::string& getGlobalFrameID() const noexcept
{ {
return global_frame_; return global_frame_;
@@ -155,6 +165,21 @@ public:
double getInscribedRadius() { return inscribed_radius_; } double getInscribedRadius() { return inscribed_radius_; }
private: 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_; Costmap2D costmap_;
std::string global_frame_; std::string global_frame_;
@@ -170,6 +195,25 @@ private:
bool size_locked_; bool size_locked_;
double circumscribed_radius_, inscribed_radius_; double circumscribed_radius_, inscribed_radius_;
std::vector<robot_geometry_msgs::Point> footprint_; std::vector<robot_geometry_msgs::Point> footprint_;
bool performance_metrics_enabled_ = false;
double performance_metrics_period_seconds_ = 5.0;
int debug_level_ = 0;
std::chrono::steady_clock::time_point performance_window_start_;
std::uint64_t performance_cycle_nanoseconds_ = 0;
std::uint64_t performance_reset_nanoseconds_ = 0;
std::uint64_t performance_cycles_ = 0;
std::vector<std::uint64_t> performance_cycle_samples_;
std::vector<LayerPerformance> layer_performance_;
// debug_level >= 1: master-mutex acquisition time is the contention signal
// (planners hold the same mutex while reading costs), hold time is our own
// cost; empty cycles are updates that found no dirty bounds and did no work.
std::uint64_t lock_wait_nanoseconds_ = 0;
std::uint64_t lock_wait_max_nanoseconds_ = 0;
std::uint64_t lock_hold_nanoseconds_ = 0;
std::uint64_t window_cells_sum_ = 0;
std::uint64_t window_cells_max_ = 0;
std::uint64_t performance_empty_cycles_ = 0;
}; };
} // namespace robot_costmap_2d } // namespace robot_costmap_2d

View File

@@ -34,6 +34,9 @@
#include <robot_geometry_msgs/Point.h> #include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h> #include <robot_sensor_msgs/PointCloud2.h>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <utility>
namespace robot_costmap_2d namespace robot_costmap_2d
{ {
@@ -50,14 +53,12 @@ public:
* @brief Creates an empty observation * @brief Creates an empty observation
*/ */
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() virtual ~Observation() = default;
{
delete cloud_;
}
/** /**
* @brief Creates an observation from an origin point and a point cloud * @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, Observation(robot_geometry_msgs::Point& origin, const robot_sensor_msgs::PointCloud2 &cloud,
double obstacle_range, double raytrace_range) : 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) obstacle_range_(obstacle_range), raytrace_range_(raytrace_range)
{ {
} }
@@ -78,22 +89,59 @@ public:
* @param obs The observation to copy * @param obs The observation to copy
*/ */
Observation(const Observation& obs) : 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_) 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 * @brief Creates an observation from a point cloud
* @param cloud The point cloud of the observation * @param cloud The point cloud of the observation
* @param obstacle_range The range out to which an observation should be able to insert obstacles * @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) : 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_; robot_geometry_msgs::Point origin_;
boost::shared_ptr<robot_sensor_msgs::PointCloud2> cloud_handle_;
robot_sensor_msgs::PointCloud2* cloud_; robot_sensor_msgs::PointCloud2* cloud_;
double obstacle_range_, raytrace_range_; double obstacle_range_, raytrace_range_;
}; };

View File

@@ -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) * Software License Agreement (BSD License)
@@ -464,6 +76,7 @@ public:
double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame, double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
std::string sensor_frame, double tf_tolerance); std::string sensor_frame, double tf_tolerance);
/** /**
* @brief Destructor... cleans up * @brief Destructor... cleans up
*/ */

View File

@@ -46,6 +46,8 @@
#include <robot_nav_msgs/OccupancyGrid.h> #include <robot_nav_msgs/OccupancyGrid.h>
#include <mutex>
#include <robot_sensor_msgs/LaserScan.h> #include <robot_sensor_msgs/LaserScan.h>
#include <robot_laser_geometry/laser_geometry.hpp> #include <robot_laser_geometry/laser_geometry.hpp>
#include <robot_sensor_msgs/PointCloud.h> #include <robot_sensor_msgs/PointCloud.h>

View File

@@ -51,6 +51,9 @@
#include <robot_costmap_2d/obstacle_layer.h> #include <robot_costmap_2d/obstacle_layer.h>
#include <robot_voxel_grid/voxel_grid.h> #include <robot_voxel_grid/voxel_grid.h>
#include <limits>
#include <vector>
namespace robot_costmap_2d 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); 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, virtual void raytraceFreespace(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_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_; bool publish_voxel_;
robot_voxel_grid::VoxelGrid robot_voxel_grid_; robot_voxel_grid::VoxelGrid robot_voxel_grid_;
double z_resolution_, origin_z_; double z_resolution_, origin_z_;
unsigned int unknown_threshold_, mark_threshold_, size_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_; 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) inline bool worldToMap3DFloat(double wx, double wy, double wz, double& mx, double& my, double& mz)
{ {

View File

@@ -20,6 +20,8 @@
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend> <buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>libconsole-bridge-dev</build_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> <run_depend>libconsole-bridge-dev</run_depend>
<build_depend>robot_std_msgs</build_depend> <build_depend>robot_std_msgs</build_depend>

View File

@@ -0,0 +1,960 @@
/*********************************************************************
* 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: Apola (costmap_depth_camera); port to robot_costmap_2d.
*********************************************************************/
#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 <tf3/exceptions.h>
#include <data_convert/data_convert.h>
#include <boost/dll/alias.hpp>
#include <boost/make_shared.hpp>
#include <boost/thread/locks.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/extract_clusters.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <unordered_set>
namespace robot_costmap_2d
{
namespace
{
// Distance of the "attach" band around each frustum face, hard-coded in the source [m].
constexpr float kAttachDistance = 0.12f;
// Stored columns farther than this from the robot are not tested for clearing [m].
constexpr double kClearingSkipDistance = 10.0;
// VoxelGrid leaf of the combined observation, hard-coded in the source [m].
constexpr float kObservationLeaf = 0.05f;
Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t)
{
const auto& q = t.transform.rotation;
const auto& p = t.transform.translation;
Eigen::Isometry3d iso = Eigen::Isometry3d::Identity();
iso.linear() = Eigen::Quaterniond(q.w, q.x, q.y, q.z).normalized().toRotationMatrix();
iso.translation() << p.x, p.y, p.z;
return iso;
}
// The source keeps parameters in the plugin namespace. Costmap2DROBOT only copies the keys of
// known layer types from the shared namespace into "<costmap>/<plugin>", so read the scoped
// value first and fall back to the shared block with the plugin's own name.
class ParamReader
{
public:
ParamReader(const robot::NodeHandle& scoped, const robot::NodeHandle& shared)
: scoped_(scoped), shared_(shared)
{
}
ParamReader child(const std::string& ns) const
{
return ParamReader(robot::NodeHandle(scoped_, ns), robot::NodeHandle(shared_, ns));
}
bool has(const std::string& key) const
{
return scoped_.hasParam(key) || shared_.hasParam(key);
}
template <typename T>
T get(const std::string& key, const T& default_value) const
{
T value = default_value;
if (scoped_.hasParam(key))
scoped_.getParam(key, value, default_value);
else if (shared_.hasParam(key))
shared_.getParam(key, value, default_value);
return value;
}
private:
robot::NodeHandle scoped_;
robot::NodeHandle shared_;
};
void requireRange(bool ok, const std::string& what)
{
if (!ok)
throw std::invalid_argument("DepthCameraObstacleLayer: " + what);
}
} // namespace
// ---------------------------------------------------------------------------------------------
// Frustum (costmap_depth_camera::Observation::findFrustum* and FrustumUtils)
// ---------------------------------------------------------------------------------------------
void DepthCameraFrustum::build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
double min_d, double max_d, bool optical)
{
max_detect_distance = max_d;
const double tw = std::tan(fov_w / 2.0);
const double tv = std::tan(fov_v / 2.0);
// findFrustumVertex(): X forward, +Y left, +Z up. TL = +Y +Z, BR = -Y -Z.
const std::array<Eigen::Vector3d, 8> local = {
Eigen::Vector3d(min_d, min_d * tw, min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, min_d * tv),
Eigen::Vector3d(min_d, min_d * tw, -min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, -min_d * tv),
Eigen::Vector3d(max_d, max_d * tw, max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, max_d * tv),
Eigen::Vector3d(max_d, max_d * tw, -max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, -max_d * tv)};
for (std::size_t i = 0; i < local.size(); ++i)
{
Eigen::Vector3d v = local[i];
// Same pyramid expressed in an optical frame: forward = +Z, left = -X, up = -Y.
if (optical)
v = Eigen::Vector3d(-local[i].y(), -local[i].z(), local[i].x());
vertices[i] = (T_global_sensor * v).cast<float>();
}
origin = T_global_sensor.translation().cast<float>();
const Eigen::Vector3f& TLNear = vertices[0];
const Eigen::Vector3f& TRNear = vertices[1];
const Eigen::Vector3f& BLNear = vertices[2];
const Eigen::Vector3f& BRNear = vertices[3];
const Eigen::Vector3f& TLFar = vertices[4];
const Eigen::Vector3f& TRFar = vertices[5];
const Eigen::Vector3f& BLFar = vertices[6];
const Eigen::Vector3f& BRFar = vertices[7];
// findFrustumNormal(): getVec(a, b) = b - a, inward normals in this order.
normals[0] = (TRNear - TLNear).cross(BRNear - TRNear); // near
normals[1] = (TRFar - TRNear).cross(BRFar - TRFar); // right
normals[2] = (BRFar - BRNear).cross(BLFar - BRFar); // bottom
normals[3] = (BLFar - BLNear).cross(TLFar - BLFar); // left
normals[4] = (TRFar - BRFar).cross(TLFar - TRFar); // far
normals[5] = (TRFar - TLFar).cross(TRNear - TRFar); // top
// findFrustumPlane(): getPlaneN(p1, p2, p3) = cross(p2 - p1, p3 - p1), d = -n . p1.
const auto plane = [](const Eigen::Vector3f& p1, const Eigen::Vector3f& p2, const Eigen::Vector3f& p3) {
const Eigen::Vector3f n = (p2 - p1).cross(p3 - p1);
return Eigen::Vector4f(n.x(), n.y(), n.z(), -n.dot(p1));
};
planes[0] = plane(TLNear, TLFar, BLNear);
planes[1] = plane(BLNear, BRNear, BLFar);
planes[2] = plane(TRNear, BRNear, BRFar);
planes[3] = plane(TLNear, TRNear, TLFar);
planes[4] = plane(TLNear, BLNear, BRNear);
planes[5] = plane(TLFar, TRFar, BRFar);
}
bool DepthCameraFrustum::inside(const Eigen::Vector3f& p) const
{
// Faces 0..2 pass through BRNear, faces 3..5 through TLFar.
for (int i = 0; i < 6; ++i)
{
const Eigen::Vector3f& corner = i < 3 ? vertices[3] : vertices[4];
if ((p - corner).dot(normals[i]) < 0.f)
return false;
}
return true;
}
bool DepthCameraFrustum::nearFace(const Eigen::Vector3f& p) const
{
for (const Eigen::Vector4f& pl : planes)
{
const float dis = std::fabs(pl[0] * p.x() + pl[1] * p.y() + pl[2] * p.z() + pl[3]) /
std::sqrt(pl[0] * pl[0] + pl[1] * pl[1] + pl[2] * pl[2]);
if (dis <= kAttachDistance &&
std::hypot(p.x() - origin.x(), p.y() - origin.y()) < max_detect_distance + 0.5)
return true;
}
return false;
}
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p)
{
for (const DepthCameraFrustum& f : frustums)
if (f.inside(p))
return true;
return false;
}
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p)
{
for (std::size_t i = 0; i < frustums.size(); ++i)
{
if (!frustums[i].nearFace(p))
continue;
// Attached to this one; not attached overall if it lies well inside another camera's frustum.
for (std::size_t j = 0; j < frustums.size(); ++j)
if (j != i && !frustums[j].nearFace(p) && frustums[j].inside(p))
return false;
return true;
}
return false;
}
// ---------------------------------------------------------------------------------------------
// Layer
// ---------------------------------------------------------------------------------------------
DepthCameraObstacleLayer::DepthCameraObstacleLayer()
{
costmap_ = NULL; // the unsigned char* of the parent Costmap2D
}
DepthCameraObstacleLayer::~DepthCameraObstacleLayer() = default;
void DepthCameraObstacleLayer::onInitialize()
{
rolling_window_ = layered_costmap_->isRolling();
global_frame_ = layered_costmap_->getGlobalFrameID();
loadParameters();
matchSize();
current_ = true;
last_stats_log_ = robot::Time::now();
}
void DepthCameraObstacleLayer::loadParameters()
{
robot::NodeHandle nh("~");
const std::string short_name = name_.substr(name_.find_last_of('/') + 1);
const ParamReader p(robot::NodeHandle(nh, name_), robot::NodeHandle(nh, short_name));
const bool track_unknown_space = p.get("track_unknown_space", layered_costmap_->isTrackingUnknown());
default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE;
enabled_ = p.get("enabled", true);
footprint_clearing_enabled_ = p.get("footprint_clearing_enabled", true);
combination_method_ = p.get("combination_method", 1);
enable_near_blocked_protection_ = p.get("enable_near_blocked_protection", true);
number_points_considered_as_blocked_ = p.get("number_points_considered_as_blocked", 5);
forced_clearing_distance_ = p.get("forced_clearing_distance", 0.1);
ec_seg_distance_ = p.get("ec_seg_distance", 0.2);
ec_cluster_min_size_ = p.get("ec_cluster_min_size", 5);
size_of_cluster_rejection_ = p.get("size_of_cluster_rejection", 5);
voxel_resolution_ = p.get("voxel_resolution", 0.01);
check_radius_ = p.get("check_radius", 0.1);
number_clearing_threshold_ = p.get("number_clearing_threshold", 2);
use_voxelized_observation_ = p.get("use_voxelized_observation", true);
transform_tolerance_ = p.get("transform_tolerance", 0.2);
const bool use_global_frame_to_mark = p.get("use_global_frame_to_mark", true);
if (p.has("clear_touches_bounds"))
robot::log_warning("DepthCameraObstacleLayer %s: clear_touches_bounds is obsolete and ignored: a cleared "
"cell now always resets its master cell\n", name_.c_str());
debug_stats_ = p.get("debug/stats", true);
debug_stats_period_ = p.get("debug/stats_period", 5.0);
// The source's local mode keys points by costmap index, so markings move with a rolling
// window (its README shows it). Only the global mode is ported.
requireRange(use_global_frame_to_mark, "use_global_frame_to_mark: false is not ported");
requireRange(voxel_resolution_ > 0.0 && std::isfinite(voxel_resolution_), "voxel_resolution must be > 0");
requireRange(check_radius_ > 0.0 && std::isfinite(check_radius_), "check_radius must be > 0");
requireRange(ec_seg_distance_ > 0.0 && std::isfinite(ec_seg_distance_), "ec_seg_distance must be > 0");
requireRange(ec_cluster_min_size_ >= 1, "ec_cluster_min_size must be >= 1");
requireRange(size_of_cluster_rejection_ >= 0, "size_of_cluster_rejection must be >= 0");
requireRange(number_clearing_threshold_ >= 1, "number_clearing_threshold must be >= 1");
requireRange(number_points_considered_as_blocked_ >= 0, "number_points_considered_as_blocked must be >= 0");
requireRange(forced_clearing_distance_ >= 0.0, "forced_clearing_distance must be >= 0");
requireRange(transform_tolerance_ >= 0.0 && std::isfinite(transform_tolerance_), "transform_tolerance must be >= 0");
requireRange(debug_stats_period_ > 0.0, "debug/stats_period must be > 0");
marking_height_under_ground_ = 100.0;
marking_height_above_ground_ = -100.0;
std::stringstream ss(p.get("observation_sources", std::string("")));
std::string name;
while (ss >> name)
{
const ParamReader s = p.child(name);
std::unique_ptr<Source> src(new Source());
src->name = name;
src->topic = s.get("topic", name);
src->sensor_frame = s.get("sensor_frame", std::string(""));
src->sensor_frame_is_optical = s.get("sensor_frame_is_optical", false);
src->observation_keep_time = s.get("observation_persistence", 0.0);
src->expected_update_rate = s.get("expected_update_rate", 0.0);
src->min_obstacle_height = s.get("min_obstacle_height", 0.0);
src->max_obstacle_height = s.get("max_obstacle_height", 2.0);
src->marking = s.get("marking", true);
src->fov_v = s.get("FOV_V", 1.0);
src->fov_w = s.get("FOV_W", 1.5);
src->min_detect_distance = s.get("min_detect_distance", 0.15);
src->max_detect_distance = s.get("max_detect_distance", 2.5);
if (s.get("inf_is_valid", false))
robot::log_warning("DepthCameraObstacleLayer: inf_is_valid is not applicable to PointCloud observations\n");
const std::string what = "source " + name + ": ";
requireRange(src->fov_w > 0.0 && src->fov_w < M_PI, what + "FOV_W must be in (0, pi) [rad]");
requireRange(src->fov_v > 0.0 && src->fov_v < M_PI, what + "FOV_V must be in (0, pi) [rad]");
requireRange(src->min_detect_distance >= 0.0 && src->max_detect_distance > src->min_detect_distance,
what + "need 0 <= min_detect_distance < max_detect_distance [m]");
requireRange(src->min_obstacle_height <= src->max_obstacle_height,
what + "min_obstacle_height must be <= max_obstacle_height [m]");
requireRange(src->observation_keep_time >= 0.0 && src->expected_update_rate >= 0.0,
what + "observation_persistence and expected_update_rate must be >= 0 [s]");
// Update minimum height and maximum height for overall marking.
marking_height_above_ground_ = std::max(marking_height_above_ground_, src->max_obstacle_height);
marking_height_under_ground_ = std::min(marking_height_under_ground_, src->min_obstacle_height);
src->last_updated = robot::Time::now();
robot::log_info("DepthCameraObstacleLayer %s: source %s topic=%s sensor_frame=%s optical=%s "
"FOV_W=%.3f FOV_V=%.3f rad detect=[%.2f, %.2f] m height=[%.2f, %.2f] m "
"persistence=%.2f s expected_update_rate=%.2f s marking=%s\n",
name_.c_str(), name.c_str(), src->topic.c_str(),
src->sensor_frame.empty() ? "(cloud frame)" : src->sensor_frame.c_str(),
src->sensor_frame_is_optical ? "true" : "false", src->fov_w, src->fov_v,
src->min_detect_distance, src->max_detect_distance, src->min_obstacle_height,
src->max_obstacle_height, src->observation_keep_time, src->expected_update_rate,
src->marking ? "true" : "false");
sources_.push_back(std::move(src));
}
if (sources_.empty())
robot::log_warning("DepthCameraObstacleLayer %s: observation_sources is empty, the layer marks nothing\n",
name_.c_str());
robot::log_info("DepthCameraObstacleLayer %s: global_frame=%s rolling=%s track_unknown=%s "
"voxel_resolution=%.3f m check_radius=%.3f m number_clearing_threshold=%d "
"ec_seg_distance=%.2f m ec_cluster_min_size=%d size_of_cluster_rejection=%d "
"forced_clearing_distance=%.2f m near_blocked_protection=%s (%d pts) "
"voxelized_observation=%s transform_tolerance=%.2f s combination_method=%d "
"footprint_clearing=%s marking_height=[%.2f, %.2f] m debug/stats=%s\n",
name_.c_str(), global_frame_.c_str(), rolling_window_ ? "true" : "false",
track_unknown_space ? "true" : "false", voxel_resolution_, check_radius_,
number_clearing_threshold_, ec_seg_distance_, ec_cluster_min_size_,
size_of_cluster_rejection_, forced_clearing_distance_,
enable_near_blocked_protection_ ? "true" : "false", number_points_considered_as_blocked_,
use_voxelized_observation_ ? "true" : "false", transform_tolerance_, combination_method_,
footprint_clearing_enabled_ ? "true" : "false",
marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off");
}
void DepthCameraObstacleLayer::handleImpl(const void* data, const std::type_info& type,
const std::string& topic)
{
// DepthCameraData, LaserScan, ... are meant for other layers of the same type.
if (type != typeid(robot_sensor_msgs::PointCloud2))
return;
const auto& cloud = *static_cast<const robot_sensor_msgs::PointCloud2*>(data);
std::shared_ptr<const robot_sensor_msgs::PointCloud2> copy;
for (const auto& source : sources_)
{
if (source->topic != topic)
continue;
if (!copy)
copy = std::make_shared<const robot_sensor_msgs::PointCloud2>(cloud);
// Newest only: the source buffer keeps one observation, and a cloud still waiting for its
// TF is superseded by a newer one, like a full tf2_ros::MessageFilter queue.
std::lock_guard<std::mutex> lock(source->pending_mutex);
source->pending = copy;
}
}
bool DepthCameraObstacleLayer::processPending(Source& source)
{
std::shared_ptr<const robot_sensor_msgs::PointCloud2> cloud;
{
std::lock_guard<std::mutex> lock(source.pending_mutex);
cloud = source.pending;
}
if (!cloud)
return false;
bool done = true;
try
{
bufferCloud(source, *cloud);
}
catch (const tf3::TransformException& ex)
{
// Measurement TF only, never the latest TF. Wait while the cloud is younger than the
// tolerance, then drop it.
const double age = (robot::Time::now() - cloud->header.stamp).toSec();
if (age <= transform_tolerance_)
{
++stats_.tf_waits;
done = false;
}
else
{
++stats_.tf_drops;
robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: no TF %s <- %s at the cloud stamp "
"(%.3f s old), cloud dropped: %s\n", name_.c_str(), global_frame_.c_str(),
cloud->header.frame_id.c_str(), age, ex.what());
}
}
catch (const std::exception& ex)
{
robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: malformed cloud on %s dropped: %s\n",
name_.c_str(), source.topic.c_str(), ex.what());
}
if (done)
{
std::lock_guard<std::mutex> lock(source.pending_mutex);
if (source.pending == cloud)
source.pending.reset();
}
return done;
}
bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud)
{
if (cloud.header.frame_id.empty())
throw std::invalid_argument("cloud has no frame_id");
const std::string origin_frame = source.sensor_frame.empty() ? cloud.header.frame_id : source.sensor_frame;
const tf3::Time stamp = data_convert::convertTime(cloud.header.stamp);
const Eigen::Isometry3d T_cloud = toIsometry(tf_->lookupTransform(global_frame_, cloud.header.frame_id, stamp));
const Eigen::Isometry3d T_origin = origin_frame == cloud.header.frame_id
? T_cloud : toIsometry(tf_->lookupTransform(global_frame_, origin_frame, stamp));
Observation obs;
obs.stamp = cloud.header.stamp;
// Frustum vertices are given in the sensor frame, then everything is in the global frame.
obs.frustum.build(T_origin, source.fov_w, source.fov_v, source.min_detect_distance,
source.max_detect_distance, source.sensor_frame_is_optical);
const std::size_t size = static_cast<std::size_t>(cloud.width) * cloud.height;
obs.points.reserve(size);
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
for (std::size_t i = 0; i < size; ++i, ++iter_x, ++iter_y, ++iter_z)
{
// The source relies on dense clouds; NaN would only disappear later in PCL. Drop it here.
if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z))
continue;
const Eigen::Vector3d g = T_cloud * Eigen::Vector3d(*iter_x, *iter_y, *iter_z);
if (g.z() <= source.max_obstacle_height && g.z() >= source.min_obstacle_height)
obs.points.push_back(g.cast<float>());
}
source.observations.push_front(std::move(obs));
source.last_updated = robot::Time::now();
purgeStale(source);
return true;
}
void DepthCameraObstacleLayer::purgeStale(Source& source) const
{
if (source.observations.empty())
return;
// Keeping observations for no time keeps exactly one.
if (source.observation_keep_time == 0.0)
{
source.observations.erase(std::next(source.observations.begin()), source.observations.end());
return;
}
for (auto it = source.observations.begin(); it != source.observations.end(); ++it)
{
if ((source.last_updated - it->stamp).toSec() > source.observation_keep_time)
{
source.observations.erase(it, source.observations.end());
return;
}
}
}
bool DepthCameraObstacleLayer::sourceIsCurrent(const Source& source) const
{
if (source.expected_update_rate == 0.0)
return true;
const double since = (robot::Time::now() - source.last_updated).toSec();
const bool current = since <= source.expected_update_rate;
if (!current)
robot::log_warning_throttle(5.0, "DepthCameraObstacleLayer %s: source %s not updated for %.2f s, expected "
"every %.2f s\n", name_.c_str(), source.name.c_str(), since,
source.expected_update_rate);
return current;
}
void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
// ClearCostmapRecovery and resetLayers() reach the stored points from other threads.
boost::unique_lock<mutex_t> lock(*getMutex());
if (rolling_window_)
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
if (!enabled_)
return;
const auto start = std::chrono::steady_clock::now();
useExtraBounds(min_x, min_y, max_x, max_y);
dropColumnsOutsideWindow(min_x, min_y, max_x, max_y);
bool current = true;
std::vector<DepthCameraFrustum> frustums;
std::vector<Eigen::Vector3f> combined;
for (const auto& source : sources_)
{
if (!source->marking)
continue; // the source marks and clears with marking observations only
processPending(*source);
purgeStale(*source);
for (const Observation& obs : source->observations)
{
frustums.push_back(obs.frustum);
combined.insert(combined.end(), obs.points.begin(), obs.points.end());
}
current = sourceIsCurrent(*source) && current;
}
current_ = current;
pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
cloud->points.reserve(combined.size());
for (const Eigen::Vector3f& q : combined)
{
pcl::PointXYZI pt;
pt.x = q.x();
pt.y = q.y();
pt.z = q.z();
pt.intensity = 0.f;
cloud->points.push_back(pt);
}
cloud->width = static_cast<std::uint32_t>(cloud->points.size());
cloud->height = 1;
cloud->is_dense = true;
// Voxelized combined observation to save computation.
if (use_voxelized_observation_ && !cloud->points.empty())
{
pcl::VoxelGrid<pcl::PointXYZI> voxel;
voxel.setLeafSize(kObservationLeaf, kObservationLeaf, kObservationLeaf);
voxel.setInputCloud(cloud);
pcl::PointCloud<pcl::PointXYZI>::Ptr filtered(new pcl::PointCloud<pcl::PointXYZI>);
voxel.filter(*filtered);
cloud = filtered;
}
std::vector<Eigen::Vector3f> points;
points.reserve(cloud->points.size());
for (const auto& pt : cloud->points)
points.emplace_back(pt.x, pt.y, pt.z);
stats_.cloud_points += points.size();
clearMarkingByKdtree(points, frustums, robot_x, robot_y, min_x, min_y, max_x, max_y);
if (cloud->points.size() > 5)
{
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZI>);
tree->setInputCloud(cloud);
std::vector<pcl::PointIndices> clusters;
pcl::EuclideanClusterExtraction<pcl::PointXYZI> ec;
ec.setClusterTolerance(ec_seg_distance_);
ec.setMinClusterSize(ec_cluster_min_size_);
ec.setMaxClusterSize(static_cast<int>(cloud->points.size()));
ec.setSearchMethod(tree);
ec.setInputCloud(cloud);
ec.extract(clusters);
std::vector<Eigen::Vector3f> cluster;
for (const pcl::PointIndices& indices : clusters)
{
// PCL can still output clusters below ec_cluster_min_size; the source rejects them here.
if (static_cast<int>(indices.indices.size()) <= size_of_cluster_rejection_)
continue;
cluster.clear();
for (int idx : indices.indices)
cluster.push_back(points[idx]);
processCluster(frustums, cluster, min_x, min_y, max_x, max_y);
}
}
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
++stats_.cycles;
stats_.bounds_ms_sum += ms;
stats_.bounds_ms_max = std::max(stats_.bounds_ms_max, ms);
logStats();
}
void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
const std::vector<DepthCameraFrustum>& frustums,
double robot_x, double robot_y, double* min_x,
double* min_y, double* max_x, double* max_y)
{
bool bypass_clearing = false;
if (enable_near_blocked_protection_ &&
static_cast<int>(cloud.size()) < number_points_considered_as_blocked_)
{
robot::log_warning_throttle(30.0, "DepthCameraObstacleLayer %s: blocked by something, clearing is skipped\n",
name_.c_str());
bypass_clearing = true;
}
bool clear_all_marking_in_this_frame = false;
pcl::KdTreeFLANN<pcl::PointXYZI> kdtree;
if (cloud.size() > 5)
{
pcl::PointCloud<pcl::PointXYZI>::Ptr input(new pcl::PointCloud<pcl::PointXYZI>);
input->points.reserve(cloud.size());
for (const Eigen::Vector3f& q : cloud)
{
pcl::PointXYZI pt;
pt.x = q.x();
pt.y = q.y();
pt.z = q.z();
pt.intensity = 0.f;
input->points.push_back(pt);
}
input->width = static_cast<std::uint32_t>(input->points.size());
input->height = 1;
kdtree.setInputCloud(input);
}
else if (!enable_near_blocked_protection_)
clear_all_marking_in_this_frame = true; // we really see nothing in the space
else
bypass_clearing = true;
if (clear_all_marking_in_this_frame)
++stats_.cleared_all_frames;
else if (bypass_clearing)
++stats_.bypassed_frames;
const double resolution = layered_costmap_->getCostmap()->getResolution();
std::vector<int> indices;
std::vector<float> sq_distances;
for (auto column = pc_3d_map_global_.begin(); column != pc_3d_map_global_.end();)
{
double wx, wy;
intIndexToWorld(wx, wy, column->first.first, column->first.second, resolution);
// Marked points this far from the robot are out of every frustum.
const double pc_dis = std::hypot(wx - robot_x, wy - robot_y);
if (pc_dis > kClearingSkipDistance)
{
++column;
continue;
}
auto& heights = column->second;
for (auto it = heights.begin(), next_it = it; it != heights.end(); it = next_it)
{
++next_it;
// Clearing tests the stored cell-corner position; the attach band is cleared too.
const Eigen::Vector3f search(static_cast<float>(wx), static_cast<float>(wy),
static_cast<float>(it->first * voxel_resolution_));
if (!insideAnyFrustum(frustums, search))
continue;
bool erase = false;
if (clear_all_marking_in_this_frame)
erase = true;
else if (!bypass_clearing && pc_dis <= forced_clearing_distance_)
erase = true;
else if (!bypass_clearing)
{
pcl::PointXYZI q;
q.x = search.x();
q.y = search.y();
q.z = search.z();
erase = kdtree.radiusSearch(q, check_radius_, indices, sq_distances) < number_clearing_threshold_;
}
if (!erase)
continue;
heights.erase(it);
++stats_.cleared;
}
// The last point of the column is gone: the cell is free again, in the own grid and,
// through the bounds, in the master this cycle.
column = heights.empty() ? eraseColumn(column, min_x, min_y, max_x, max_y) : std::next(column);
}
}
void DepthCameraObstacleLayer::processCluster(const std::vector<DepthCameraFrustum>& frustums,
const std::vector<Eigen::Vector3f>& cluster, double* min_x,
double* min_y, double* max_x, double* max_y)
{
const double resolution = layered_costmap_->getCostmap()->getResolution();
const int h_max = static_cast<int>(marking_height_above_ground_ / voxel_resolution_);
const int h_min = static_cast<int>(marking_height_under_ground_ / voxel_resolution_);
for (const Eigen::Vector3f& p : cluster)
{
// Robust marking condition: the raw point, inside a frustum and away from its faces.
if (!insideAnyFrustum(frustums, p) || attachedToFrustums(frustums, p))
continue;
int mmx, mmy;
worldToIntIndex(p.x(), p.y(), mmx, mmy, resolution);
const int h_ind = static_cast<int>(std::round(p.z() * (1 / voxel_resolution_)));
if (h_ind > h_max || h_ind < h_min)
continue;
const std::pair<int, int> key(mmx, mmy);
unsigned int cx, cy;
if (!columnCell(key, cx, cy))
continue; // would be dropped as out of the window anyway
auto& slot = pc_3d_map_global_[key];
auto inserted = slot.insert(std::make_pair(h_ind, 0.f));
if (inserted.second)
++stats_.marked;
setCost(cx, cy, LETHAL_OBSTACLE);
double wx, wy;
intIndexToWorld(wx, wy, mmx, mmy, resolution);
touch(wx, wy, min_x, min_y, max_x, max_y);
}
}
void DepthCameraObstacleLayer::updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
if (!footprint_clearing_enabled_)
return;
transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
for (const auto& pt : transformed_footprint_)
touch(pt.x, pt.y, min_x, min_y, max_x, max_y);
// updateCosts() frees the footprint in the own grid like ObstacleLayer; the stored points under
// it must go too, or the next marking pass would not bring them back but nothing would ever
// remove them either.
std::vector<MapLocation> polygon, cells;
for (const auto& pt : transformed_footprint_)
{
MapLocation loc;
if (!worldToMap(pt.x, pt.y, loc.x, loc.y))
return; // footprint leaves the window: same give-up as setConvexPolygonCost
polygon.push_back(loc);
}
if (polygon.size() < 3)
return;
convexFillCells(polygon, cells);
std::unordered_set<unsigned int> under;
for (const MapLocation& c : cells)
under.insert(getIndex(c.x, c.y));
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my) && under.count(getIndex(mx, my)))
{
++stats_.footprint_cleared;
it = eraseColumn(it, min_x, min_y, max_x, max_y);
}
else
++it;
}
}
bool DepthCameraObstacleLayer::isValid(int mx, int my) const
{
// Same result as the source's unsigned test: mx - 1 of cell 0 is out of range.
return mx >= 0 && my >= 0 && mx <= static_cast<int>(getSizeInCellsX()) &&
my <= static_cast<int>(getSizeInCellsY());
}
bool DepthCameraObstacleLayer::columnCell(const std::pair<int, int>& column, unsigned int& mx,
unsigned int& my) const
{
double wx, wy;
intIndexToWorld(wx, wy, column.first, column.second, getResolution());
if (!worldToMap(wx, wy, mx, my))
return false;
// The +-1 cells guard the rounding of the stored corner, as in the source.
const int x = static_cast<int>(mx), y = static_cast<int>(my);
return isValid(x - 1, y - 1) && isValid(x - 1, y + 1) && isValid(x + 1, y - 1) && isValid(x + 1, y + 1);
}
std::map<std::pair<int, int>, std::map<int, float>>::iterator DepthCameraObstacleLayer::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)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my))
{
setCost(mx, my, FREE_SPACE);
double wx, wy;
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
touch(wx, wy, min_x, min_y, max_x, max_y);
}
return pc_3d_map_global_.erase(it);
}
void DepthCameraObstacleLayer::dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x,
double* max_y)
{
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my))
{
// Keep the own grid in step with the points even after matchSize() or a cleared area
// wiped the cell: one O(columns) pass that writes only when something is missing.
if (getCost(mx, my) != LETHAL_OBSTACLE)
{
setCost(mx, my, LETHAL_OBSTACLE);
double wx, wy;
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
touch(wx, wy, min_x, min_y, max_x, max_y);
}
++it;
continue;
}
// B6: the source keeps such points forever, so the map and every loop over it grow.
++stats_.dropped_out_of_window;
double wx, wy;
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
if (worldToMap(wx, wy, mx, my))
{
// Still inside the window, on its edge row/column: free that cell as well.
setCost(mx, my, FREE_SPACE);
touch(wx, wy, min_x, min_y, max_x, max_y);
}
it = pc_3d_map_global_.erase(it);
}
}
void DepthCameraObstacleLayer::updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
{
boost::unique_lock<mutex_t> lock(*getMutex());
if (!enabled_)
return;
// The own grid mirrors the stored points (see updateBounds), so the layer merges like
// ObstacleLayer and the master is only changed inside the update bounds.
if (footprint_clearing_enabled_)
setConvexPolygonCost(transformed_footprint_, FREE_SPACE);
switch (combination_method_)
{
case 0: // Overwrite
updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
break;
case 1: // Maximum
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
break;
default: // Nothing
break;
}
}
std::size_t DepthCameraObstacleLayer::storedPoints() const
{
std::size_t n = 0;
for (const auto& column : pc_3d_map_global_)
n += column.second.size();
return n;
}
void DepthCameraObstacleLayer::logStats()
{
const robot::Time now = robot::Time::now();
const double since = (now - last_stats_log_).toSec();
if (since < debug_stats_period_ && since >= 0.0)
return;
last_stats_log_ = now;
if (debug_stats_ && stats_.cycles > 0)
robot::log_info("[debug/stats] DepthCameraObstacleLayer %s: cycles=%zu cloud_pts/cycle=%.0f stored=%zu "
"columns=%zu marked=%zu cleared=%zu footprint_cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu "
"tf_wait=%zu tf_drop=%zu out_of_window=%zu bounds_ms avg=%.1f max=%.1f\n",
name_.c_str(), stats_.cycles, static_cast<double>(stats_.cloud_points) / stats_.cycles,
storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.cleared, stats_.footprint_cleared,
stats_.cleared_all_frames, stats_.bypassed_frames, stats_.tf_waits, stats_.tf_drops,
stats_.dropped_out_of_window, stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
stats_ = Stats();
}
void DepthCameraObstacleLayer::activate()
{
for (const auto& source : sources_)
source->last_updated = robot::Time::now();
}
void DepthCameraObstacleLayer::deactivate()
{
// The source unsubscribes and clears its local-mode map only; the global-mode map stays.
for (const auto& source : sources_)
{
std::lock_guard<std::mutex> lock(source->pending_mutex);
source->pending.reset();
}
}
void DepthCameraObstacleLayer::reset()
{
boost::unique_lock<mutex_t> lock(*getMutex());
deactivate();
resetMaps();
// The source keeps its global-mode points here (B9), so a reset changed nothing on the master.
pc_3d_map_global_.clear();
for (const auto& source : sources_)
source->observations.clear();
current_ = true;
activate();
}
void DepthCameraObstacleLayer::matchSize()
{
// The master was resized (or this is onInitialize): CostmapLayer::matchSize() rebuilds the own
// grid with default_value_, so put the stored columns back now instead of waiting a cycle, and
// ask the next update to merge the whole layer.
boost::unique_lock<mutex_t> lock(*getMutex());
CostmapLayer::matchSize();
for (const auto& column : pc_3d_map_global_)
{
unsigned int mx, my;
if (columnCell(column.first, mx, my))
setCost(mx, my, LETHAL_OBSTACLE);
}
if (!pc_3d_map_global_.empty())
addExtraBounds(getOriginX(), getOriginY(), getOriginX() + getSizeInMetersX(),
getOriginY() + getSizeInMetersY());
}
void DepthCameraObstacleLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area)
{
boost::unique_lock<mutex_t> lock(*getMutex());
CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area);
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my))
{
// Same test as CostmapLayer::clearArea: keep what it keeps.
const int x = static_cast<int>(mx), y = static_cast<int>(my);
const bool inside = x > start_x && x < end_x && y > start_y && y < end_y;
if (inside != invert_area)
{
++it;
continue;
}
}
// The own grid cell is already NO_INFORMATION from CostmapLayer::clearArea.
it = pc_3d_map_global_.erase(it);
}
}
// Export factory function
static boost::shared_ptr<Layer> create_depth_camera_obstacle_plugin()
{
return boost::make_shared<DepthCameraObstacleLayer>();
}
BOOST_DLL_ALIAS(create_depth_camera_obstacle_plugin, DepthCameraObstacleLayer)
} // namespace robot_costmap_2d

View File

@@ -58,7 +58,6 @@ InflationLayer::InflationLayer()
, inflate_unknown_(false) , inflate_unknown_(false)
, cell_inflation_radius_(0) , cell_inflation_radius_(0)
, cached_cell_inflation_radius_(0) , cached_cell_inflation_radius_(0)
, seen_(NULL)
, cached_costs_(NULL) , cached_costs_(NULL)
, cached_distances_(NULL) , cached_distances_(NULL)
, last_min_x_(-std::numeric_limits<float>::max()) , last_min_x_(-std::numeric_limits<float>::max())
@@ -76,10 +75,8 @@ void InflationLayer::onInitialize()
boost::unique_lock < boost::recursive_mutex > lock(*inflation_access_); boost::unique_lock < boost::recursive_mutex > lock(*inflation_access_);
current_ = true; current_ = true;
if (seen_) seen_.clear();
delete[] seen_; seen_generation_ = 0;
seen_ = NULL;
seen_size_ = 0;
need_reinflation_ = false; need_reinflation_ = false;
std::string config_file_name = "inflation_layer_params.yaml"; std::string config_file_name = "inflation_layer_params.yaml";
// std::cout << "InflationLayer: " << config_file_name << std::endl; // std::cout << "InflationLayer: " << config_file_name << std::endl;
@@ -144,10 +141,8 @@ void InflationLayer::matchSize()
computeCaches(); computeCaches();
unsigned int size_x = costmap->getSizeInCellsX(), size_y = costmap->getSizeInCellsY(); unsigned int size_x = costmap->getSizeInCellsX(), size_y = costmap->getSizeInCellsY();
if (seen_) seen_.assign(static_cast<std::size_t>(size_x) * size_y, 0);
delete[] seen_; seen_generation_ = 0;
seen_size_ = size_x * size_y;
seen_ = new bool[seen_size_];
} }
void InflationLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, void InflationLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
@@ -203,26 +198,28 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
if (cell_inflation_radius_ == 0) if (cell_inflation_radius_ == 0)
return; return;
// make sure the inflation list is empty at the beginning of the cycle (should always be true) for (std::vector<CellData>& cells : inflation_cells_)
if(!inflation_cells_.empty()) cells.clear();
robot::log_error("The inflation list must be empty at the beginning of inflation\n");
unsigned char* master_array = master_grid.getCharMap(); unsigned char* master_array = master_grid.getCharMap();
unsigned int size_x = master_grid.getSizeInCellsX(), size_y = master_grid.getSizeInCellsY(); unsigned int size_x = master_grid.getSizeInCellsX(), size_y = master_grid.getSizeInCellsY();
if (seen_ == NULL) { const std::size_t map_size = static_cast<std::size_t>(size_x) * size_y;
robot::log_error("InflationLayer::updateCosts(): seen_ array is NULL\n"); if (seen_.size() != map_size)
seen_size_ = size_x * size_y;
seen_ = new bool[seen_size_];
}
else if (seen_size_ != size_x * size_y)
{ {
robot::log_error("InflationLayer::updateCosts(): seen_ array size is wrong\n"); seen_.assign(map_size, 0);
delete[] seen_; seen_generation_ = 0;
seen_size_ = size_x * size_y; }
seen_ = new bool[seen_size_];
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 // We need to include in the inflation cells outside the bounding
// box min_i...max_j, by the amount cell_inflation_radius_. Cells // box min_i...max_j, by the amount cell_inflation_radius_. Cells
@@ -238,11 +235,13 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
max_i = std::min(int(size_x), max_i); max_i = std::min(int(size_x), max_i);
max_j = std::min(int(size_y), max_j); 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 // Precomputed distance buckets preserve priority ordering without a tree lookup
// We use a map<distance, list> to emulate the priority queue used before, with a notable performance boost // for every enqueued cell.
// Start with lethal obstacles: by definition distance is 0.0 // 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 j = min_j; j < max_j; j++)
{ {
for (int i = min_i; i < max_i; i++) for (int i = min_i; i < max_i; i++)
@@ -258,23 +257,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 // Process cells by increasing distance; new cells are appended to the corresponding distance bin, so they
// can overtake previously inserted but farther away cells // can overtake previously inserted but farther away cells
std::map<double, std::vector<CellData> >::iterator bin; for (std::vector<CellData>& bin : inflation_cells_)
for (bin = inflation_cells_.begin(); bin != inflation_cells_.end(); ++bin)
{ {
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 // process all cells at distance dist_bin.first
const CellData& cell = bin->second[i]; const CellData& cell = bin[i];
unsigned int index = cell.index_; unsigned int index = cell.index_;
// ignore if already visited // ignore if already visited
if (seen_[index]) if (seen_[index] == seen_generation_)
{ {
continue; continue;
} }
seen_[index] = true; seen_[index] = seen_generation_;
unsigned int mx = cell.x_; unsigned int mx = cell.x_;
unsigned int my = cell.y_; unsigned int my = cell.y_;
@@ -301,7 +299,6 @@ void InflationLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int m
} }
} }
inflation_cells_.clear();
} }
/** /**
@@ -316,7 +313,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, inline void InflationLayer::enqueue(unsigned int index, unsigned int mx, unsigned int my,
unsigned int src_x, unsigned int src_y) 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 // 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); double distance = distanceLookup(mx, my, src_x, src_y);
@@ -325,8 +322,10 @@ inline void InflationLayer::enqueue(unsigned int index, unsigned int mx, unsigne
if (distance > cell_inflation_radius_) if (distance > cell_inflation_radius_)
return; return;
// push the cell data onto the inflation list and mark const unsigned int dx = std::abs(static_cast<int>(mx) - static_cast<int>(src_x));
inflation_cells_[distance].push_back(CellData(index, mx, my, src_x, src_y)); 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 +353,38 @@ void InflationLayer::computeCaches()
} }
cached_cell_inflation_radius_ = cell_inflation_radius_; 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) for (unsigned int i = 0; i <= cell_inflation_radius_ + 1; ++i)
@@ -367,6 +398,10 @@ void InflationLayer::computeCaches()
void InflationLayer::deleteKernels() void InflationLayer::deleteKernels()
{ {
inflation_cells_.clear();
distance_levels_.clear();
distance_bin_lookup_.clear();
distance_lookup_size_ = 0;
if (cached_distances_ != NULL) if (cached_distances_ != NULL)
{ {
for (unsigned int i = 0; i <= cached_cell_inflation_radius_ + 1; ++i) for (unsigned int i = 0; i <= cached_cell_inflation_radius_ + 1; ++i)

View File

@@ -165,6 +165,16 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
if (priv_nh.hasParam("marking")) if (priv_nh.hasParam("marking"))
priv_nh.getParam("marking", 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")) 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"); robot::log_error("Only topics that use point clouds or laser scans are currently supported\n");
@@ -178,22 +188,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
info_tmp.inf_is_valid = inf_is_valid; info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp); 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(), robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str()); priv_nh.getNamespace().c_str());
@@ -209,7 +203,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 // check if we'll also add this buffer to our clearing observation buffers
if (clearing) if (clearing)
clearing_buffers_.push_back(observation_buffers_.back()); clearing_buffers_.push_back(observation_buffers_.back());
robot::log_info( robot::log_info(
"Created an observation buffer for topic %s, global frame: %s, " "Created an observation buffer for topic %s, global frame: %s, "
"expected update rate: %.2f, observation persistence: %.2f\n", "expected update rate: %.2f, observation persistence: %.2f\n",
@@ -230,67 +223,63 @@ void ObstacleLayer::handleImpl(const void* data,
const std::type_info& type, const std::type_info& type,
const std::string& topic) const std::string& topic)
{ {
if(!stop_receiving_data_) if (!enabled_ || 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");
return; return;
// Samples that match no configured source (type and topic) are ignored.
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
{
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
} }
} }
@@ -430,6 +419,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_y(cloud, "y");
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z"); 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) for (; iter_x !=iter_x.end(); ++iter_x, ++iter_y, ++iter_z)
{ {
double px = *iter_x, py = *iter_y, pz = *iter_z; double px = *iter_x, py = *iter_y, pz = *iter_z;
@@ -437,7 +429,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 the obstacle is too high or too far away from the robot we won't add it
if (pz > max_obstacle_height_) if (pz > max_obstacle_height_)
{ {
robot::log_error("The point is too high\n"); ++rejected_height;
continue; continue;
} }
@@ -448,7 +440,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 the point is far enough away... we won't consider it
if (sq_dist >= sq_obstacle_range) if (sq_dist >= sq_obstacle_range)
{ {
robot::log_error("The point is too far away\n"); ++rejected_range;
continue; continue;
} }
@@ -456,7 +448,7 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
unsigned int mx, my; unsigned int mx, my;
if (!worldToMap(px, py, mx, my)) if (!worldToMap(px, py, mx, my))
{ {
robot::log_error("Computing map coords failed\n"); ++rejected_bounds;
continue; continue;
} }
@@ -464,6 +456,14 @@ void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_ya
costmap_[index] = LETHAL_OBSTACLE; costmap_[index] = LETHAL_OBSTACLE;
touch(px, py, min_x, min_y, max_x, max_y); 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); updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);

View File

@@ -37,7 +37,14 @@
*********************************************************************/ *********************************************************************/
#include <robot_costmap_2d/voxel_layer.h> #include <robot_costmap_2d/voxel_layer.h>
#include <robot_sensor_msgs/point_cloud2_iterator.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 <boost/dll/alias.hpp>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#define VOXEL_BITS 16 #define VOXEL_BITS 16
@@ -231,29 +238,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); updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
} }
@@ -327,14 +311,6 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
ox, oy, oz); ox, oy, oz);
return; 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 // 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_x = origin_x_ + getSizeInMetersX();
double map_end_y = origin_y_ + getSizeInMetersY(); double map_end_y = origin_y_ + getSizeInMetersY();
@@ -409,26 +385,8 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
cell_raytrace_range); cell_raytrace_range);
updateRaytraceBounds(ox, oy, wpx, wpy, clearing_observation.raytrace_range_, min_x, min_y, max_x, max_y); 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) void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
@@ -438,6 +396,11 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
cell_ox = int((new_origin_x - origin_x_) / resolution_); cell_ox = int((new_origin_x - origin_x_) / resolution_);
cell_oy = int((new_origin_y - origin_y_) / 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 // compute the associated world coordinates for the origin cell
// beacuase we want to keep things grid-aligned // beacuase we want to keep things grid-aligned
double new_grid_ox, new_grid_oy; double new_grid_ox, new_grid_oy;
@@ -458,15 +421,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_x = upper_right_x - lower_left_x;
unsigned int cell_size_y = upper_right_y - lower_left_y; unsigned int cell_size_y = upper_right_y - lower_left_y;
// we need a map to store the obstacles in the window temporarily const std::size_t overlap_size = static_cast<std::size_t>(cell_size_x) * cell_size_y;
unsigned char* local_map = new unsigned char[cell_size_x * cell_size_y]; rolling_costmap_scratch_.resize(overlap_size);
unsigned int* local_voxel_map = new unsigned int[cell_size_x * cell_size_y]; 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(); unsigned int* voxel_map = robot_voxel_grid_.getData();
// copy the local window in the costmap to the local map 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, copyMapRegion(costmap_, lower_left_x, lower_left_y, size_x_, local_map, 0, 0,
cell_size_y); 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 // we'll reset our maps to unknown space if appropriate
resetMaps(); resetMaps();
@@ -480,12 +448,14 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
int start_y = lower_left_y - cell_oy; 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 // 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_voxel_map, 0, 0, cell_size_x, voxel_map, start_x, start_y, size_x_, cell_size_x, cell_size_y); {
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 // Export factory function

View File

@@ -165,6 +165,28 @@ Costmap2D::Costmap2D(const Costmap2D& map) :
*this = 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 // just initialize everything to NULL by default
Costmap2D::Costmap2D() : Costmap2D::Costmap2D() :
size_x_(0), size_y_(0), resolution_(0.0), origin_x_(0.0), origin_y_(0.0), costmap_(NULL) 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_x = upper_right_x - lower_left_x;
unsigned int cell_size_y = upper_right_y - lower_left_y; unsigned int cell_size_y = upper_right_y - lower_left_y;
// we need a map to store the obstacles in the window temporarily const std::size_t overlap_size = static_cast<std::size_t>(cell_size_x) * cell_size_y;
unsigned char* local_map = new unsigned char[cell_size_x * cell_size_y];
// copy the local window in the costmap to the local map // Reuse the temporary window to avoid allocating on every rolling-window shift.
copyMapRegion(costmap_, lower_left_x, lower_left_y, size_x_, local_map, 0, 0, cell_size_x, cell_size_x, cell_size_y); 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 // now we'll set the costmap to be completely unknown if we track unknown space
resetMaps(); resetMaps();
@@ -306,10 +334,12 @@ void Costmap2D::updateOrigin(double new_origin_x, double new_origin_y)
int start_y = lower_left_y - cell_oy; 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 // 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) bool Costmap2D::setConvexPolygonCost(const std::vector<robot_geometry_msgs::Point>& polygon, unsigned char cost_value)

View File

@@ -51,6 +51,8 @@
#include <boost/dll/import.hpp> #include <boost/dll/import.hpp>
#include <pthread.h>
using namespace std; using namespace std;
namespace robot_costmap_2d namespace robot_costmap_2d
@@ -105,7 +107,7 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
YAML::Node config = YAML::LoadFile(path_source); YAML::Node config = YAML::LoadFile(path_source);
YAML::Node layer = config["robot_costmap_2d"]; YAML::Node layer = config["robot_costmap_2d"];
robot::NodeHandle priv_nh(priv_nh, name); robot::NodeHandle priv_nh(nh, name);
std::string global_frame = std::string global_frame =
loadParam(layer, "global_frame", std::string("map")); loadParam(layer, "global_frame", std::string("map"));
@@ -155,9 +157,36 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
if (priv_nh.hasParam("track_unknown_space")) if (priv_nh.hasParam("track_unknown_space"))
priv_nh.getParam("track_unknown_space", 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")) if (priv_nh.hasParam("library_path"))
path_plugins = loader.findLibraryPath(name_); path_plugins = loader.findLibraryPath(name_);
layered_costmap_ = new LayeredCostmap(global_frame_, rolling_window, track_unknown_space); 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 // find size parameters
double map_width_meters = loadParam(layer, "width", 0.0); double map_width_meters = loadParam(layer, "width", 0.0);
@@ -385,6 +414,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
double max_obstacle_height; double max_obstacle_height;
double obstacle_range; double obstacle_range;
double raytrace_range; double raytrace_range;
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic); 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, "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, "observation_persistence", observation_persistence);
@@ -434,6 +464,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
double max_obstacle_height; double max_obstacle_height;
double obstacle_range; double obstacle_range;
double raytrace_range; double raytrace_range;
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic); 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, "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, "observation_persistence", observation_persistence);
@@ -461,10 +492,34 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
} }
void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint) void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint)
{ {
setUnpaddedRobotFootprint(toPointVector(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() Costmap2DROBOT::~Costmap2DROBOT()
{ {
map_update_thread_shutdown_ = true; map_update_thread_shutdown_ = true;
@@ -510,6 +565,7 @@ void Costmap2DROBOT::readFootprintFromConfig(const std::vector<robot_geometry_ms
void Costmap2DROBOT::setUnpaddedRobotFootprint(const std::vector<robot_geometry_msgs::Point>& points) void Costmap2DROBOT::setUnpaddedRobotFootprint(const std::vector<robot_geometry_msgs::Point>& points)
{ {
boost::recursive_mutex::scoped_lock lock(configuration_mutex_);
unpadded_footprint_ = points; unpadded_footprint_ = points;
padded_footprint_ = points; padded_footprint_ = points;
padFootprint(padded_footprint_, footprint_padding_); padFootprint(padded_footprint_, footprint_padding_);
@@ -526,6 +582,11 @@ void Costmap2DROBOT::checkMovement()
void Costmap2DROBOT::mapUpdateLoop(double frequency) 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"; std::cout << robot::Time::now().toNSec()<< " :Costmap2DROBOT::mapUpdateLoop updateMap\n";
robot::Rate r(frequency); robot::Rate r(frequency);
while (!map_update_thread_shutdown_) while (!map_update_thread_shutdown_)
@@ -541,6 +602,7 @@ void Costmap2DROBOT::mapUpdateLoop(double frequency)
void Costmap2DROBOT::updateMap() void Costmap2DROBOT::updateMap()
{ {
boost::recursive_mutex::scoped_lock lock(configuration_mutex_);
if (!stop_updates_) if (!stop_updates_)
{ {
// get global pose // get global pose
@@ -672,35 +734,9 @@ bool Costmap2DROBOT::getRobotPose(robot_geometry_msgs::PoseStamped& global_pose)
// get the global pose of the robot // get the global pose of the robot
try try
{ {
// use current time if possible (makes sure it's not in the future) const tf3::TransformStampedMsg transform =
if (tf_.canTransform(global_frame_, robot_base_frame_, tf3::Time())) tf_.lookupTransform(global_frame_, robot_base_frame_, tf3::Time());
{ tf3::doTransform(robot_pose, global_pose, transform);
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);
}
} }
catch (tf3::LookupException& ex) catch (tf3::LookupException& ex)
{ {

View File

@@ -69,6 +69,119 @@ namespace robot_costmap_2d
costmap_.setDefaultValue(NO_INFORMATION); costmap_.setDefaultValue(NO_INFORMATION);
else else
costmap_.setDefaultValue(FREE_SPACE); 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() LayeredCostmap::~LayeredCostmap()
@@ -94,9 +207,23 @@ namespace robot_costmap_2d
void LayeredCostmap::updateMap(double robot_x, double robot_y, double robot_yaw) 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) // Lock for the remainder of this function, some plugins (e.g. VoxelLayer)
// implement thread unsafe updateBounds() functions. // implement thread unsafe updateBounds() functions.
boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_.getMutex())); 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 we're using a rolling buffer costmap... we need to update the origin using the robot's position
if (rolling_window_) if (rolling_window_)
@@ -111,23 +238,57 @@ namespace robot_costmap_2d
minx_ = miny_ = 1e30; minx_ = miny_ = 1e30;
maxx_ = maxy_ = -1e30; maxx_ = maxy_ = -1e30;
for (vector<boost::shared_ptr<Layer>>::iterator plugin = plugins_.begin(); plugin != plugins_.end(); if (performance_metrics_enabled_ && layer_performance_.size() != plugins_.size())
++plugin) 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; continue;
double prev_minx = minx_; double prev_minx = minx_;
double prev_miny = miny_; double prev_miny = miny_;
double prev_maxx = maxx_; double prev_maxx = maxx_;
double prev_maxy = maxy_; 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) 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 " 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", "is now [tl: (%f, %f), br: (%f, %f)]. The offending layer is %s\n",
prev_minx, prev_miny, prev_maxx, prev_maxy, prev_minx, prev_miny, prev_maxx, prev_maxy,
minx_, miny_, maxx_, maxy_, minx_, miny_, maxx_, maxy_,
(*plugin)->getName().c_str()); plugin->getName().c_str());
} }
} }
@@ -141,15 +302,43 @@ namespace robot_costmap_2d
yn = std::min(int(costmap_.getSizeInCellsY()), yn + 1); yn = std::min(int(costmap_.getSizeInCellsY()), yn + 1);
if (xn < x0 || yn < y0) 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()) // No dirty region this cycle (idle costmap): count it so the debug
(*plugin)->updateCosts(costmap_, x0, y0, xn, yn); // 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; bx0_ = x0;
@@ -158,6 +347,23 @@ namespace robot_costmap_2d
byn_ = yn; byn_ = yn;
initialized_ = true; initialized_ = true;
if (performance_metrics_enabled_)
{
const auto cycle_end = std::chrono::steady_clock::now();
const std::uint64_t cycle_nanoseconds = static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(cycle_end - cycle_start).count());
performance_cycle_nanoseconds_ += cycle_nanoseconds;
performance_cycle_samples_.push_back(cycle_nanoseconds);
++performance_cycles_;
lock_hold_nanoseconds_ += static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(cycle_end - lock_acquired).count());
const std::uint64_t window_cells =
static_cast<std::uint64_t>(xn - x0) * static_cast<std::uint64_t>(yn - y0);
window_cells_sum_ += window_cells;
window_cells_max_ = std::max(window_cells_max_, window_cells);
maybeReportPerformance();
}
} }
bool LayeredCostmap::isCurrent() bool LayeredCostmap::isCurrent()

File diff suppressed because it is too large Load Diff

View File

@@ -36,6 +36,14 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <robot_costmap_2d/costmap_2d.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; using namespace robot_costmap_2d;
@@ -124,9 +132,129 @@ TEST(CostmapCoordinates, hard_coordinates_test)
EXPECT_EQ(my, 2); 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) int main(int argc, char** argv)
{ {
testing::InitGoogleTest( &argc, argv ); testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

View File

@@ -0,0 +1,447 @@
#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 <cmath>
#include <memory>
#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";
// Optical frame "camera" 0.19 m above odom, looking along +x of odom (rotated by yaw).
tf3::TransformStampedMsg pose(robot::Time stamp, double yaw = 0)
{
tf3::TransformStampedMsg p;
p.header.frame_id = "odom";
p.child_frame_id = "camera";
p.header.stamp = tf3::Time(stamp.sec, stamp.nsec);
Eigen::Matrix3d optical;
optical << 0, 0, 1, -1, 0, 0, 0, -1, 0;
Eigen::Quaterniond q(Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ()) * optical);
p.transform.rotation.x = q.x();
p.transform.rotation.y = q.y();
p.transform.rotation.z = q.z();
p.transform.rotation.w = q.w();
p.transform.translation.z = .19;
return p;
}
// Points given in odom for a camera at yaw 0; stored in the optical frame of the cloud.
robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, const std::vector<Eigen::Vector3d>& odom_points)
{
robot_sensor_msgs::PointCloud2 c;
c.header.stamp = stamp;
c.header.frame_id = "camera";
c.height = 1;
robot_sensor_msgs::PointCloud2Modifier m(c);
m.setPointCloud2FieldsByString(1, "xyz");
m.resize(odom_points.size());
robot_sensor_msgs::PointCloud2Iterator<float> x(c, "x"), y(c, "y"), z(c, "z");
for (const auto& p : odom_points)
{
*x = -p.y();
*y = .19 - p.z();
*z = p.x();
++x;
++y;
++z;
}
return c;
}
// 3 x 3 points, 6 cm apart (one per 5 cm voxel), one Euclidean cluster. Kept away from cell
// boundaries: the source stores (int)(x / 0.05), so y = .07 .13 .19 are columns 1 2 3.
std::vector<Eigen::Vector3d> object(double x = 1.02, double y = .13, double z = .30)
{
std::vector<Eigen::Vector3d> pts;
for (double dy : {-.06, 0., .06})
for (double dz : {-.06, 0., .06})
pts.emplace_back(x, y + dy, z + dz);
return pts;
}
// 11 points in a row 0.6 m behind the object: keeps the cloud above 5 points, own cluster.
std::vector<Eigen::Vector3d> wall()
{
std::vector<Eigen::Vector3d> pts;
for (int i = -5; i <= 5; ++i)
pts.emplace_back(1.62, i * .06 + .13, .30);
return pts;
}
std::vector<Eigen::Vector3d> join(std::vector<Eigen::Vector3d> a, const std::vector<Eigen::Vector3d>& b)
{
a.insert(a.end(), b.begin(), b.end());
return a;
}
YAML::Node baseConfig()
{
YAML::Node cfg;
cfg["enabled"] = true;
cfg["footprint_clearing_enabled"] = false;
cfg["use_global_frame_to_mark"] = true;
cfg["enable_near_blocked_protection"] = false;
cfg["observation_sources"] = "depth_cam";
cfg["debug"]["stats"] = false;
cfg["depth_cam"]["topic"] = kTopic;
cfg["depth_cam"]["sensor_frame_is_optical"] = true;
cfg["depth_cam"]["FOV_W"] = kFovW;
cfg["depth_cam"]["FOV_V"] = kFovV;
cfg["depth_cam"]["min_detect_distance"] = .15;
cfg["depth_cam"]["max_detect_distance"] = 2.5;
cfg["depth_cam"]["min_obstacle_height"] = .05;
cfg["depth_cam"]["max_obstacle_height"] = 1.0;
return cfg;
}
} // namespace
// ---------------------------------------------------------------------------------------------
// Frustum geometry
// ---------------------------------------------------------------------------------------------
TEST(DepthCameraFrustum, InsideFollowsTheConfiguredPyramid)
{
DepthCameraFrustum f;
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); // X forward
const float half_w = std::tan(kFovW / 2), half_v = std::tan(kFovV / 2);
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, 0)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(.1f, 0, 0))); // before the near plane
EXPECT_FALSE(f.inside(Eigen::Vector3f(2.6f, 0, 0))); // beyond the far plane
EXPECT_FALSE(f.inside(Eigen::Vector3f(-1, 0, 0)));
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, .98f * half_w, 0)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 1.02f * half_w, 0)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, -1.02f * half_w, 0)));
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, -.98f * half_v)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 0, 1.02f * half_v)));
}
TEST(DepthCameraFrustum, AttachBandIsTwelveCentimetresFromEveryFace)
{
DepthCameraFrustum f;
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, 0, 0)));
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(2.4f, 0, 0))); // 10 cm before the far plane
const float half_w = std::tan(kFovW / 2);
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0)));
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .3f, 0)));
}
TEST(DepthCameraFrustum, OpticalFrameGivesTheSamePyramid)
{
DepthCameraFrustum link, optical;
link.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link
optical.build(T, kFovW, kFovV, .15, 2.5, true);
for (int i = 0; i < 8; ++i)
EXPECT_LT((link.vertices[i] - optical.vertices[i]).norm(), 1e-5f) << "vertex " << i;
EXPECT_TRUE(optical.inside(Eigen::Vector3f(1, 0, 0)));
}
TEST(DepthCameraFrustum, AttachedUnlessWellInsideAnotherFrustum)
{
DepthCameraFrustum a, b;
a.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
T.translation() << 0, .3, 0; // second camera 30 cm to the left
b.build(T, kFovW, kFovV, .15, 2.5, false);
const Eigen::Vector3f near_left_face_of_a(1, std::tan(kFovW / 2) - .05f, 0);
EXPECT_TRUE(attachedToFrustums({a}, near_left_face_of_a));
EXPECT_FALSE(attachedToFrustums({a, b}, near_left_face_of_a));
EXPECT_FALSE(attachedToFrustums({a}, Eigen::Vector3f(1, 0, 0)));
}
// ---------------------------------------------------------------------------------------------
// Layer
// ---------------------------------------------------------------------------------------------
class DepthCameraLayerTest : public ::testing::Test
{
protected:
tf3::BufferCore tf;
LayeredCostmap parent{"odom", false, false};
DepthCameraObstacleLayer layer;
uint32_t tick = 0;
double min_x = 0, min_y = 0, max_x = 0, max_y = 0;
void SetUp() override
{
robot::Time::setNow(robot::Time(100, 0));
YAML::Node cfg = baseConfig();
configure(cfg);
robot::NodeHandle nh("~");
nh.setParam("dcam_test", cfg);
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
layer.initialize(&parent, "dcam_test", &tf);
ASSERT_TRUE(layer.isEnabled());
}
virtual void configure(YAML::Node&) {}
robot::Time next()
{
return robot::Time(100, ++tick * 10000000);
}
void update()
{
min_x = min_y = 1e9;
max_x = max_y = -1e9;
layer.updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y);
}
void frame(const std::vector<Eigen::Vector3d>& pts, double yaw = 0, bool has_tf = true)
{
const robot::Time stamp = next();
robot::Time::setNow(stamp);
if (has_tf)
ASSERT_TRUE(tf.setTransform(pose(stamp, yaw), "test"));
layer.dataCallBack(cloud(stamp, pts), kTopic);
update();
}
unsigned char master(double x = 1.01, double y = .11)
{
Costmap2D& m = *parent.getCostmap();
m.resetMap(0, 0, m.getSizeInCellsX(), m.getSizeInCellsY());
layer.updateCosts(m, 0, 0, m.getSizeInCellsX(), m.getSizeInCellsY());
unsigned int a, b;
EXPECT_TRUE(m.worldToMap(x, y, a, b));
return m.getCost(a, b);
}
};
TEST_F(DepthCameraLayerTest, MarksAClusterInsideTheFrustum)
{
frame(object());
EXPECT_EQ(layer.storedPoints(), 9u);
EXPECT_EQ(master(), LETHAL_OBSTACLE);
EXPECT_TRUE(layer.isCurrent());
}
TEST_F(DepthCameraLayerTest, SmallClusterAndOutOfHeightPointsAreNotMarked)
{
std::vector<Eigen::Vector3d> five = object();
five.resize(5); // <= size_of_cluster_rejection
frame(join(five, wall()));
EXPECT_NE(master(), LETHAL_OBSTACLE);
frame(join(object(1.02, .13, 1.5), wall())); // above max_obstacle_height
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, KeptWhileSeenAgainAndClearedWhenGone)
{
frame(join(object(), wall()));
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame(join(object(), wall()));
EXPECT_EQ(master(), LETHAL_OBSTACLE);
frame(wall()); // no cloud point within check_radius of the stored points
EXPECT_NE(master(), LETHAL_OBSTACLE);
EXPECT_EQ(master(1.61, .11), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, OutsideTheFrustumIsKept)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame({}, 1.57); // camera turned away, sees nothing
EXPECT_EQ(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, NearlyEmptyCloudClearsEverythingInViewWithoutProtection)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
frame({});
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
class DepthCameraBlockedTest : public DepthCameraLayerTest
{
protected:
void configure(YAML::Node& cfg) override
{
cfg["enable_near_blocked_protection"] = true;
}
};
TEST_F(DepthCameraBlockedTest, NearlyEmptyCloudSkipsClearingWithProtection)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame({});
EXPECT_EQ(master(), LETHAL_OBSTACLE);
frame(wall());
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, AttachBandIsNotMarked)
{
// 10 cm past the near plane (0.15 m) of a camera at x = 0: inside, but attached.
frame(wall());
const std::size_t wall_points = layer.storedPoints();
ASSERT_GT(wall_points, 0u);
frame(join(object(.25, .10, .19), wall()));
EXPECT_EQ(layer.storedPoints(), wall_points);
}
TEST_F(DepthCameraLayerTest, WaitsForTheMeasurementTfThenDropsAfterTheTolerance)
{
frame(object(), 0, false); // no TF at this stamp yet
EXPECT_EQ(layer.storedPoints(), 0u);
const robot::Time stamp(100, tick * 10000000);
ASSERT_TRUE(tf.setTransform(pose(stamp), "late_tf"));
update();
EXPECT_EQ(layer.storedPoints(), 9u);
frame(object(1.32, -.47, .3), 0, false);
const robot::Time late(100, tick * 10000000);
robot::Time::setNow(robot::Time(101, 0)); // older than transform_tolerance (0.2 s)
update();
ASSERT_TRUE(tf.setTransform(pose(late), "too_late_tf"));
update();
EXPECT_NE(master(1.31, -.44), LETHAL_OBSTACLE); // the waiting cloud was dropped
EXPECT_EQ(layer.storedPoints(), 9u);
}
TEST_F(DepthCameraLayerTest, OtherTopicsAndDepthImagesAreIgnored)
{
const robot::Time stamp = next();
robot::Time::setNow(stamp);
ASSERT_TRUE(tf.setTransform(pose(stamp), "test"));
layer.dataCallBack(cloud(stamp, object()), "/other/points");
robot_sensor_msgs::DepthCameraData::ConstPtr depth = boost::make_shared<robot_sensor_msgs::DepthCameraData>();
layer.dataCallBack(depth, kTopic);
update();
EXPECT_EQ(layer.storedPoints(), 0u);
}
TEST_F(DepthCameraLayerTest, MarkingsThatLeaveTheWindowAreDropped)
{
frame(object());
ASSERT_EQ(layer.storedPoints(), 9u);
layer.updateOrigin(10, 10); // the stored cells are outside the layer now
update();
EXPECT_EQ(layer.storedPoints(), 0u);
}
TEST_F(DepthCameraLayerTest, ClearedCellLeavesTheMasterInsideTheBounds)
{
frame(join(object(), wall()));
ASSERT_EQ(master(), LETHAL_OBSTACLE); // master now holds the object cell
frame(wall());
EXPECT_LT(min_x, 1.05); // the cleared object cell is part of this cycle's bounds
// What LayeredCostmap does: reset the master inside the bounds only, then merge the layer there.
Costmap2D& m = *parent.getCostmap();
int i0, j0, i1, j1;
m.worldToMapEnforceBounds(min_x, min_y, i0, j0);
m.worldToMapEnforceBounds(max_x, max_y, i1, j1);
m.resetMap(i0, j0, i1 + 1, j1 + 1);
layer.updateCosts(m, i0, j0, i1 + 1, j1 + 1);
unsigned int a, b;
ASSERT_TRUE(m.worldToMap(1.01, .11, a, b));
EXPECT_NE(m.getCost(a, b), LETHAL_OBSTACLE);
ASSERT_TRUE(m.worldToMap(1.61, .11, a, b));
EXPECT_EQ(m.getCost(a, b), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, ClearAreaKeepsTheInsideByDefaultAndClearsItWhenInverted)
{
frame(join(object(), wall()));
ASSERT_EQ(master(), LETHAL_OBSTACLE);
ASSERT_EQ(master(1.61, .11), LETHAL_OBSTACLE);
// Cells strictly inside (55, 35)-(65, 50) hold the object (cell x 60); the wall is at cell x 72.
layer.clearArea(55, 35, 65, 50, false); // CostmapLayer contract: clears OUTSIDE the box
EXPECT_EQ(layer.storedPoints(), 9u);
EXPECT_EQ(master(), LETHAL_OBSTACLE);
EXPECT_NE(master(1.61, .11), LETHAL_OBSTACLE);
layer.clearArea(55, 35, 65, 50, true); // inverted: clears the inside
EXPECT_EQ(layer.storedPoints(), 0u);
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, ResetDropsTheStoredPointsAndObservations)
{
frame(join(object(), wall()));
ASSERT_GT(layer.storedPoints(), 0u);
layer.reset();
EXPECT_EQ(layer.storedPoints(), 0u);
EXPECT_NE(master(), LETHAL_OBSTACLE);
update(); // no new cloud: the buffered observation is gone too, nothing comes back
EXPECT_EQ(layer.storedPoints(), 0u);
}
class DepthCameraFootprintTest : public DepthCameraLayerTest
{
protected:
void configure(YAML::Node& cfg) override
{
cfg["footprint_clearing_enabled"] = true;
cfg["enable_near_blocked_protection"] = true; // an empty cycle must not clear by itself
}
};
TEST_F(DepthCameraFootprintTest, FootprintClearingErasesThePointsUnderTheRobot)
{
std::vector<robot_geometry_msgs::Point> square(4);
square[0].x = -.3; square[0].y = -.3;
square[1].x = .3; square[1].y = -.3;
square[2].x = .3; square[2].y = .3;
square[3].x = -.3; square[3].y = .3;
parent.setFootprint(square);
frame(object());
ASSERT_EQ(layer.storedPoints(), 9u);
layer.updateBounds(1.02, .13, 0, &min_x, &min_y, &max_x, &max_y); // robot drives onto it
EXPECT_EQ(layer.storedPoints(), 0u);
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, HasItsOwnLayerType)
{
EXPECT_EQ(layer.getType(), LayerType::DEPTH_CAMERA_LAYER);
EXPECT_NE(layer.getType(), LayerType::VOXEL_LAYER);
}
TEST_F(DepthCameraLayerTest, MatchSizeKeepsAndReMarksTheStoredPoints)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
layer.matchSize(); // rebuilds the own grid from scratch
EXPECT_EQ(layer.storedPoints(), 9u);
EXPECT_EQ(master(), LETHAL_OBSTACLE); // re-marked without waiting for an update
}
TEST(DepthCameraLayerConfig, RejectsUnportedModeAndOutOfRangeValues)
{
tf3::BufferCore tf;
LayeredCostmap parent{"odom", false, false};
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
robot::NodeHandle nh("~");
const auto expectThrow = [&](const YAML::Node& cfg) {
nh.setParam("dcam_bad", cfg);
DepthCameraObstacleLayer layer;
EXPECT_THROW(layer.initialize(&parent, "dcam_bad", &tf), std::invalid_argument);
};
YAML::Node cfg = baseConfig();
cfg["use_global_frame_to_mark"] = false;
expectThrow(cfg);
cfg = baseConfig();
cfg["depth_cam"]["FOV_W"] = 3.5;
expectThrow(cfg);
cfg = baseConfig();
cfg["depth_cam"]["min_detect_distance"] = 3.0;
expectThrow(cfg);
cfg = baseConfig();
cfg["voxel_resolution"] = 0.0;
expectThrow(cfg);
}