Compare commits
2 Commits
feature/di
...
fix/config
| Author | SHA1 | Date | |
|---|---|---|---|
| f8705e1c49 | |||
| ae7fce9e77 |
@@ -112,7 +112,6 @@ add_library(robot_costmap_2d SHARED
|
||||
src/observation_buffer.cpp
|
||||
src/layer.cpp
|
||||
src/layered_costmap.cpp
|
||||
src/direction_field.cpp
|
||||
src/costmap_math.cpp
|
||||
src/footprint.cpp
|
||||
src/costmap_layer.cpp
|
||||
@@ -240,9 +239,6 @@ if(BUILDING_WITH_CATKIN)
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(FILES config/directional_layer_params.yaml
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/config)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
@@ -259,9 +255,6 @@ else()
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
install(FILES config/directional_layer_params.yaml
|
||||
DESTINATION share/${PROJECT_NAME}/config)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
@@ -301,12 +294,6 @@ if(BUILD_COSTMAP_TESTS)
|
||||
find_package(Boost REQUIRED COMPONENTS system thread filesystem)
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
|
||||
add_executable(direction_field_test test/direction_field_test.cpp)
|
||||
target_link_libraries(direction_field_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main)
|
||||
|
||||
add_executable(directional_layer_test test/directional_layer_test.cpp)
|
||||
target_link_libraries(directional_layer_test PRIVATE plugins robot_costmap_2d GTest::GTest GTest::Main Boost::thread ${TF3_LIBRARY})
|
||||
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/array_parser_test.cpp)
|
||||
add_executable(test_array_parser test/array_parser_test.cpp)
|
||||
target_link_libraries(test_array_parser PRIVATE
|
||||
@@ -350,7 +337,6 @@ if(BUILD_COSTMAP_TESTS)
|
||||
target_link_libraries(depth_camera_obstacle_layer_test PRIVATE
|
||||
plugins
|
||||
robot_costmap_2d
|
||||
yaml-cpp
|
||||
GTest::GTest
|
||||
GTest::Main
|
||||
)
|
||||
|
||||
12
README.md
12
README.md
@@ -472,12 +472,10 @@ phản chiếu các điểm đó theo từng ô (cột có điểm là `LETHAL`,
|
||||
hiện tại có ít hơn `number_clearing_threshold` điểm trong bán kính `check_radius`,
|
||||
hoặc nếu điểm cách tâm robot dưới `forced_clearing_distance`. Cloud có
|
||||
`<= number_points_considered_as_blocked` điểm thì xóa hết trong khối nhìn, trừ khi
|
||||
bật `enable_near_blocked_protection`. Bật `occlusion_guard` thì tia nhìn quyết định thêm:
|
||||
điểm có vật gần hơn che trên tia nhìn tới nó được **giữ**, điểm mà camera nhìn xuyên qua
|
||||
(thấy nền phía sau) bị **xóa** dù còn điểm khác trong `check_radius`.
|
||||
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
|
||||
`attach_distance` (mặc định 12 cm) thì được lưu.
|
||||
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`.
|
||||
|
||||
@@ -507,8 +505,7 @@ Tham số chung của layer:
|
||||
| `footprint_clearing_enabled` | `true` | Xóa ô và điểm đã lưu nằm dưới footprint robot. |
|
||||
| `combination_method` | `1` | Như các layer khác. |
|
||||
| `use_global_frame_to_mark` | `true` | Chỉ hỗ trợ `true`; `false` báo lỗi. |
|
||||
| `occlusion_guard` | `false` | `true`: giữ điểm bị vật gần hơn che, xóa điểm mà camera nhìn xuyên qua. Dựng một ảnh khoảng cách nhỏ (bin 0.01 theo tang góc) từ cả cloud trước lọc chiều cao. Hằng số đã kiểm offline trên 10 bag robot KIT (22–23/10/2026). `false`: chỉ phép kd-tree như gói gốc. |
|
||||
| `debug/stats` | `true` | Log `[debug/stats]` định kỳ: số điểm, số điểm đánh dấu/xóa, TF chờ/bỏ, `kept_occluded` / `cleared_seen_through` của `occlusion_guard`, thời gian. |
|
||||
| `debug/stats` | `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):
|
||||
@@ -521,7 +518,6 @@ Tham số của từng source (camera):
|
||||
| `FOV_W`, `FOV_V` | `1.5`, `1.0 rad` | Góc nhìn ngang/dọc của khối nhìn. Tính từ `camera_info`. |
|
||||
| `min_detect_distance`, `max_detect_distance` | `0.15`, `2.5 m` | Mặt gần/xa của khối nhìn. Ngoài khoảng này không đánh dấu, không xóa. |
|
||||
| `min_obstacle_height`, `max_obstacle_height` | `0.0`, `2.0 m` | Lọc độ cao trong frame global. |
|
||||
| `attach_distance` | `0.12 m` | Điểm cách bất kỳ mặt khối nhìn dưới mức này không được đánh dấu (mép vật bị cắt, nhiễu mép ảnh). Giảm: vật thấp sát mép dưới FOV được đánh dấu; quá nhỏ (0.05) làm tăng ô ma trước mũi robot. Miền `[0, (max_detect_distance - min_detect_distance) / 2)`. |
|
||||
| `marking` | `true` | `false`: bỏ qua source. |
|
||||
| `observation_persistence` | `0.0 s` | `0`: chỉ dùng cloud mới nhất. |
|
||||
| `expected_update_rate` | `0.0 s` | Quá lâu không có cloud thì costmap báo không current. `0`: tắt. |
|
||||
@@ -534,8 +530,6 @@ Giới hạn đã biết:
|
||||
hai.
|
||||
- Khối nhìn đối xứng và trùng mép ảnh; dải mép ảnh không có depth (lọc mép, dải stereo
|
||||
bên trái) vẫn được coi là "nhìn thấy trống".
|
||||
- `occlusion_guard` chỉ có tác dụng trong khối nhìn: vết của vật động đã ra ngoài FOV vẫn được
|
||||
giữ như trên. Điểm bị che được giữ tới khi camera nhìn lại được chỗ đó.
|
||||
- Layer không dùng ảnh depth (`DepthCameraData`): host phải đổi ảnh sang `PointCloud2` trước khi đẩy vào.
|
||||
|
||||
### 5.7. InflationLayer
|
||||
|
||||
@@ -25,13 +25,6 @@ depth_camera_obstacle_layer:
|
||||
# false: cloud ít điểm như vậy thì xoá hết điểm trong FOV ("không thấy gì").
|
||||
enable_near_blocked_protection: true
|
||||
number_points_considered_as_blocked: 5 # [điểm] >= 0.
|
||||
# [bool] Chống xoá khi bị che, dùng tia nhìn của ảnh depth (cả sàn, trước lọc chiều cao).
|
||||
# true: điểm đã lưu mà có vật gần hơn nằm trên tia nhìn tới nó thì GIỮ (người đi ngang trước thùng
|
||||
# không còn xoá thùng); điểm mà camera nhìn xuyên qua thấy nền phía sau thì XOÁ, kể cả khi còn điểm
|
||||
# khác trong check_radius (vết của vật vừa dịch đi biến nhanh hơn).
|
||||
# false: chỉ dùng phép kd-tree như gói gốc. Bật thì tốn thêm một ảnh khoảng cách nhỏ mỗi cloud.
|
||||
# Vết nằm NGOÀI FOV vẫn không xoá được dù bật hay tắt.
|
||||
occlusion_guard: false
|
||||
# [bool] VoxelGrid 5 cm trên cloud gộp trước khi xoá/đánh dấu (nhẹ CPU).
|
||||
use_voxelized_observation: true
|
||||
# [bool] Chỉ hỗ trợ true (lưu điểm theo toạ độ global). false thì nav từ chối khởi động.
|
||||
@@ -44,9 +37,8 @@ depth_camera_obstacle_layer:
|
||||
# cập nhật. Giá trị khác: layer không tác động gì lên costmap.
|
||||
combination_method: 1
|
||||
# Danh sách nguồn, cách nhau bằng dấu cách. Rỗng = layer không đánh dấu gì. Khoá của từng nguồn
|
||||
# (topic, FOV_W, FOV_V, min/max_detect_distance, min/max_obstacle_height, attach_distance...) KHÔNG
|
||||
# đặt ở đây mà trong khối <plugin>/<tên nguồn>/ của config costmap. attach_distance [m] mặc định
|
||||
# 0.12 như gói gốc: điểm cách mặt khối nhìn dưới mức này không được đánh dấu.
|
||||
# (topic, FOV_W, FOV_V, min/max_detect_distance, min/max_obstacle_height...) KHÔNG đặt ở đây mà
|
||||
# trong khối <plugin>/<tên nguồn>/ của config costmap.
|
||||
observation_sources: ""
|
||||
# track_unknown_space cố ý KHÔNG có ở đây: không đặt thì layer theo track_unknown_space của costmap.
|
||||
debug:
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# Mặc định đóng gói của directional layer; cây chạy thực tế tùy host là
|
||||
# pnkx_nav_core/src/Navigations/Packages/move_base2/config/runtime hoặc
|
||||
# pnkx_nav_core/config.
|
||||
directional_layer:
|
||||
# Bật: sau mỗi static map, layer PENDING đến khi nhận grid hợp lệ và planner
|
||||
# phải từ chối lập đường trong lúc chờ. Host phải gửi grid sau mỗi static map;
|
||||
# dùng data rỗng nếu map không có zone. Tắt để bỏ ràng buộc hướng.
|
||||
enabled: false
|
||||
# Phải trùng map_topic của StaticLayer. Đặt sai khiến layer không thoát
|
||||
# PENDING hoặc không nhận biết khi map đổi.
|
||||
map_topic: "map"
|
||||
# Topic grid hướng: đổi theo tên host gửi; phải khác map_topic.
|
||||
direction_topic: "direction_map"
|
||||
# [deg] Góc lệch tối đa giữa hướng di chuyển và hướng zone, tính cả biên.
|
||||
# Áp chung cho mọi zone. 90 = được đi mọi hướng có thành phần cùng chiều zone
|
||||
# (đi ngang zone được, đi ngược bị cấm).
|
||||
# Giảm: robot phải đi sát hướng zone hơn, cấm cắt ngang làn, phải căn hướng
|
||||
# trước khi vào zone; quay tại chỗ luôn được phép. Dưới 22.5 (bước heading của
|
||||
# mprim 16 hướng) SBPL có thể không tìm được đường.
|
||||
# Tăng quá 90: cho phép cả hướng hơi ngược chiều zone, zone một chiều yếu đi.
|
||||
# Phạm vi hợp lệ: 0 < giá trị < 180; ngoài phạm vi nav core từ chối khởi động.
|
||||
max_deviation_deg: 90.0
|
||||
# Bật để ghi log chuyển trạng thái; tắt để giảm log bình thường.
|
||||
debug_state: true
|
||||
@@ -20,10 +20,6 @@
|
||||
* getType() is its own DEPTH_CAMERA_LAYER, which SensorGateway feeds PointCloud2 and
|
||||
* DepthCameraData; no ROS publishers or dynamic_reconfigure; `sensor_frame_is_optical` builds the frustum in a Z-forward
|
||||
* optical frame; markings that leave the rolling window are dropped (B6).
|
||||
* Additions over the source, both off by default so the source behaviour stays the default:
|
||||
* the attach band width is a per-source parameter (`attach_distance`, the source hard-codes
|
||||
* 0.12 m), and `occlusion_guard` adds depth-ray evidence to the clearing (keep a stored point a
|
||||
* nearer return hides, clear one the camera sees past).
|
||||
*********************************************************************/
|
||||
#ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
|
||||
#define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
|
||||
@@ -56,7 +52,7 @@ namespace robot_costmap_2d
|
||||
*
|
||||
* Same construction as costmap_depth_camera::Observation: 8 vertices from the configured
|
||||
* FOV and detect range in the sensor frame, transformed to the global frame, then 6 inward
|
||||
* normals (inside test) and 6 plane equations ("attach" band test).
|
||||
* normals (inside test) and 6 plane equations (12 cm "attach" band test).
|
||||
*/
|
||||
struct DepthCameraFrustum
|
||||
{
|
||||
@@ -65,9 +61,6 @@ struct DepthCameraFrustum
|
||||
std::array<Eigen::Vector3f, 6> normals; ///< near right bottom left far top
|
||||
std::array<Eigen::Vector4f, 6> planes; ///< a, b, c, d of each face
|
||||
double max_detect_distance = 2.5; ///< [m]
|
||||
/// [m] Points this close to a face are not marked: an object cut by the image edge or the
|
||||
/// noisy image border. 0.12 in the source; a wide band hides low objects near the lower FOV edge.
|
||||
float attach_distance = 0.12f;
|
||||
|
||||
/**
|
||||
* @brief Build the frustum.
|
||||
@@ -76,62 +69,17 @@ struct DepthCameraFrustum
|
||||
* @param min_d, max_d near / far plane distance along the viewing axis [m]
|
||||
* @param optical true: sensor frame is Z forward, X right, Y down (REP 103 optical);
|
||||
* false: X forward, Y left, Z up (camera_link), as the source assumes
|
||||
* @param attach_d width of the attach band [m], see attach_distance
|
||||
*/
|
||||
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
|
||||
double max_d, bool optical, double attach_d = 0.12);
|
||||
double max_d, bool optical);
|
||||
|
||||
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
|
||||
bool inside(const Eigen::Vector3f& p) const;
|
||||
|
||||
/// Within attach_distance of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
|
||||
/// 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;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Nearest depth return per viewing ray of one observation, for the occlusion guard.
|
||||
*
|
||||
* Rays are binned by their tangent (x / z and y / z in the optical frame); each bin keeps the
|
||||
* smallest range it saw. It is built from the whole cloud before the height gate: the floor the
|
||||
* gate drops is exactly what shows that a stored point is no longer there.
|
||||
*/
|
||||
struct DepthCameraRangeImage
|
||||
{
|
||||
/// What the returns around the ray to a stored point say about it.
|
||||
enum class Evidence
|
||||
{
|
||||
kNone, ///< no usable return around the ray, or a return at the point itself
|
||||
kOccluded, ///< something nearer hides the point: clearing must keep it
|
||||
kSeenThrough, ///< the camera sees past the point: it is gone
|
||||
};
|
||||
|
||||
/// Empty image covering the frustum of a sensor at T_global_sensor.
|
||||
void reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, bool optical);
|
||||
/// Adds one return given in the sensor frame.
|
||||
void addSensorPoint(const Eigen::Vector3f& p);
|
||||
/// Evidence about a point given in the global frame; kNone while the image is empty.
|
||||
Evidence test(const Eigen::Vector3f& p_global) const;
|
||||
bool empty() const
|
||||
{
|
||||
return min_range_.empty();
|
||||
}
|
||||
|
||||
private:
|
||||
Eigen::Vector3f toOptical(const Eigen::Vector3f& p) const;
|
||||
/// Bin of a point in optical coordinates; false when it is too close or outside the image.
|
||||
bool bin(const Eigen::Vector3f& q, int& u, int& v) const;
|
||||
std::size_t index(int u, int v) const
|
||||
{
|
||||
return static_cast<std::size_t>(v + half_v_) * (2 * half_u_ + 1) + static_cast<std::size_t>(u + half_u_);
|
||||
}
|
||||
|
||||
Eigen::Isometry3f sensor_from_global_ = Eigen::Isometry3f::Identity();
|
||||
bool optical_ = true;
|
||||
int half_u_ = 0;
|
||||
int half_v_ = 0;
|
||||
std::vector<float> min_range_; ///< [m] (2 half_u + 1) x (2 half_v + 1), +inf where nothing returned
|
||||
};
|
||||
|
||||
/// FrustumUtils::isInsideFRUSTUMs: inside at least one frustum.
|
||||
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
|
||||
|
||||
@@ -184,7 +132,6 @@ private:
|
||||
robot::Time stamp;
|
||||
std::vector<Eigen::Vector3f> points;
|
||||
DepthCameraFrustum frustum;
|
||||
DepthCameraRangeImage range; ///< whole cloud before the gate; empty unless occlusion_guard
|
||||
};
|
||||
|
||||
/// ObservationBuffer of the source, one per entry of observation_sources.
|
||||
@@ -202,7 +149,6 @@ private:
|
||||
double fov_v = 1.0; ///< [rad]
|
||||
double min_detect_distance = 0.15; ///< [m]
|
||||
double max_detect_distance = 2.5; ///< [m]
|
||||
double attach_distance = 0.12; ///< [m] marking-free band near each frustum face
|
||||
bool marking = true;
|
||||
|
||||
std::list<Observation> observations; ///< newest first
|
||||
@@ -218,10 +164,8 @@ private:
|
||||
void purgeStale(Source& source) const;
|
||||
bool sourceIsCurrent(const Source& source) const;
|
||||
|
||||
/// range_images[i] belongs to frustums[i]; null when that observation has no range image.
|
||||
void clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
|
||||
const std::vector<DepthCameraFrustum>& frustums,
|
||||
const std::vector<const DepthCameraRangeImage*>& range_images, double robot_x,
|
||||
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,
|
||||
@@ -276,7 +220,6 @@ private:
|
||||
// Additions of this port.
|
||||
bool debug_stats_ = true; ///< debug/stats: periodic counters log
|
||||
double debug_stats_period_ = 5.0; ///< [s]
|
||||
bool occlusion_guard_ = false; ///< depth-ray evidence in the clearing, see clearMarkingByKdtree
|
||||
|
||||
/// (ix, iy) of the cell corner -> {height index -> label}, global frame (use_global_frame_to_mark).
|
||||
std::map<std::pair<int, int>, std::map<int, float>> pc_3d_map_global_;
|
||||
@@ -294,8 +237,6 @@ private:
|
||||
std::size_t tf_waits = 0;
|
||||
std::size_t tf_drops = 0;
|
||||
std::size_t dropped_out_of_window = 0;
|
||||
std::size_t kept_occluded = 0; ///< points the kd-tree test would clear, kept as hidden
|
||||
std::size_t cleared_seen_through = 0; ///< points the kd-tree test would keep, cleared as seen past
|
||||
double bounds_ms_sum = 0.0;
|
||||
double bounds_ms_max = 0.0;
|
||||
} stats_;
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
|
||||
#define ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_nav_msgs/OccupancyGrid.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
|
||||
/** @brief Geometry of an unrotated grid in its global frame. */
|
||||
struct DirectionGeometry
|
||||
{
|
||||
uint32_t width, height; ///< Grid dimensions [cells].
|
||||
double resolution; ///< Cell size [m/cell].
|
||||
double origin_x, origin_y; ///< Lower-left grid origin [m] in frame_id.
|
||||
std::string frame_id; ///< Global coordinate frame.
|
||||
};
|
||||
|
||||
/** @brief Reason a complete direction grid failed validation. */
|
||||
enum class DirectionValidationError
|
||||
{
|
||||
kNone, kOverflow, kGeometry, kFrame, kOrientation, kSize, kCode
|
||||
};
|
||||
|
||||
/** @brief Typed validation result with a human-readable offending value. */
|
||||
struct DirectionValidationResult
|
||||
{
|
||||
DirectionValidationError error;
|
||||
std::string message;
|
||||
explicit operator bool() const { return error == DirectionValidationError::kNone; }
|
||||
};
|
||||
|
||||
/** @brief Validate the entire message against the master geometry.
|
||||
* @param grid Grid in the expected global frame. Codes are 0 for unconstrained
|
||||
* and 1..8 for direction indices 0..7 in CCW order from +X:
|
||||
* (+1,0), (+1,+1), (0,+1), (-1,+1), (-1,0), (-1,-1), (0,-1), (+1,-1).
|
||||
* @param expected Required master dimensions, resolution [m/cell], origin [m], and frame.
|
||||
* @return Typed error and description; empty data is valid after geometry checks.
|
||||
* An identity quaternion or the default all-zero quaternion means no rotation.
|
||||
*/
|
||||
DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected);
|
||||
|
||||
/** @brief Traverse a segment in grid coordinates with allocation-free 2D DDA.
|
||||
* @param x0 Start x [cells] relative to the grid origin.
|
||||
* @param y0 Start y [cells] relative to the grid origin.
|
||||
* @param x1 End x [cells] relative to the grid origin.
|
||||
* @param y1 End y [cells] relative to the grid origin.
|
||||
* @param visitor Called in order with signed integer cell indices (x, y); return
|
||||
* false to stop. The visitor must perform its own grid bounds checks.
|
||||
* @return False for invalid coordinates or a visitor-requested stop.
|
||||
* Cells own [x,x+1) x [y,y+1). Only positive-length overlaps are visited:
|
||||
* a boundary-aligned segment belongs to the higher-index cell, a corner touch
|
||||
* does not visit the adjacent cells, and an endpoint on a boundary does not
|
||||
* visit the cell beyond it. A zero-length segment visits its point's cell.
|
||||
* Coordinates must fit within the documented int64_t safety range.
|
||||
*/
|
||||
template <typename Visitor>
|
||||
bool traverseGridSegment(double x0, double y0, double x1, double y1, Visitor&& visitor)
|
||||
{
|
||||
const double limit = static_cast<double>(std::numeric_limits<int64_t>::max()) / 2.0;
|
||||
if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1) ||
|
||||
std::abs(x0) >= limit || std::abs(y0) >= limit || std::abs(x1) >= limit || std::abs(y1) >= limit)
|
||||
return false;
|
||||
|
||||
const long double dx = static_cast<long double>(x1) - x0;
|
||||
const long double dy = static_cast<long double>(y1) - y0;
|
||||
int64_t x = static_cast<int64_t>(std::floor(x0));
|
||||
int64_t y = static_cast<int64_t>(std::floor(y0));
|
||||
if (dx < 0 && x0 == std::floor(x0))
|
||||
--x;
|
||||
if (dy < 0 && y0 == std::floor(y0))
|
||||
--y;
|
||||
if (dx == 0 && dy == 0)
|
||||
return visitor(x, y);
|
||||
|
||||
const int sx = (dx > 0) - (dx < 0);
|
||||
const int sy = (dy > 0) - (dy < 0);
|
||||
const long double adx = std::abs(dx);
|
||||
const long double ady = std::abs(dy);
|
||||
while (true)
|
||||
{
|
||||
if (!visitor(x, y))
|
||||
return false;
|
||||
// Recompute crossings from the original point to avoid accumulated error at corners.
|
||||
const long double distance_x = sx ? std::abs((sx > 0 ? x + 1 : x) - static_cast<long double>(x0)) : 0;
|
||||
const long double distance_y = sy ? std::abs((sy > 0 ? y + 1 : y) - static_cast<long double>(y0)) : 0;
|
||||
const bool cross_x = sx && distance_x < adx;
|
||||
const bool cross_y = sy && distance_y < ady;
|
||||
if (!cross_x && !cross_y)
|
||||
break;
|
||||
if (!cross_y)
|
||||
{
|
||||
x += sx;
|
||||
continue;
|
||||
}
|
||||
if (!cross_x)
|
||||
{
|
||||
y += sy;
|
||||
continue;
|
||||
}
|
||||
const long double left = distance_x * ady;
|
||||
const long double right = distance_y * adx;
|
||||
if (left <= right)
|
||||
x += sx;
|
||||
if (right <= left)
|
||||
y += sy;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @brief Return allowed direction indices for a displacement.
|
||||
* @param dx Displacement along +X [m or cells] in the global/grid frame.
|
||||
* @param dy Displacement along +Y [same units as dx] in the global/grid frame.
|
||||
* @param max_deviation_rad Maximum inclusive angular deviation [rad], in (0, pi).
|
||||
* @return Bit k is set when direction k accepts the displacement within relative tolerance.
|
||||
*/
|
||||
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad);
|
||||
|
||||
/** @brief Outcome of a world-space segment query. */
|
||||
enum class SegmentResult
|
||||
{
|
||||
kAllowed, ///< All visited constrained cells permit the displacement.
|
||||
kViolation, ///< At least one visited cell forbids the displacement.
|
||||
kOutOfGrid ///< Any point is outside the grid or coordinates are invalid.
|
||||
};
|
||||
|
||||
/** @brief First prohibited cell and world-frame segment displacement. */
|
||||
struct SegmentViolation
|
||||
{
|
||||
uint32_t x, y; ///< Cell indices [cells] relative to the grid origin.
|
||||
uint8_t code; ///< Direction code 1..8.
|
||||
double dx, dy; ///< Segment displacement [m] in the global frame.
|
||||
};
|
||||
|
||||
/** @brief Immutable validated grid, safe to share and hold for a whole search. */
|
||||
class DirectionField
|
||||
{
|
||||
public:
|
||||
DirectionField(const DirectionField&) = delete;
|
||||
DirectionField& operator=(const DirectionField&) = delete;
|
||||
|
||||
/** @brief Validate and construct a field; invalid input returns null.
|
||||
* @param grid Complete direction message in the global frame.
|
||||
* @param expected Master grid geometry in the global frame.
|
||||
* @param max_deviation_rad Maximum inclusive deviation [rad], in (0, pi).
|
||||
* @param result Optional output explaining validation success or failure.
|
||||
*/
|
||||
static std::shared_ptr<const DirectionField> create(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected,
|
||||
double max_deviation_rad,
|
||||
DirectionValidationResult* result = nullptr);
|
||||
|
||||
/** @brief Return cell code: 0 unconstrained, 1..8 direction_index + 1.
|
||||
* @param x Column [cells] from the grid origin; must be less than width.
|
||||
* @param y Row [cells] from the grid origin; must be less than height.
|
||||
* @pre Both indices are in bounds. Use codeAt() for untrusted indices.
|
||||
*/
|
||||
uint8_t code(uint32_t x, uint32_t y) const;
|
||||
|
||||
/** @brief Read a cell only when both signed indices are in bounds.
|
||||
* @param x Column [cells] from the grid origin.
|
||||
* @param y Row [cells] from the grid origin.
|
||||
* @param code_out Output code; must not be null. Unchanged on failure.
|
||||
* @return False for an out-of-grid index or null output pointer.
|
||||
*/
|
||||
bool codeAt(int64_t x, int64_t y, uint8_t* code_out) const;
|
||||
|
||||
/** @brief Return the immutable master geometry and global frame. */
|
||||
const DirectionGeometry& geometry() const { return geometry_; }
|
||||
/** @brief Return the immutable maximum angular deviation [rad]. */
|
||||
double maxDeviationRad() const { return max_deviation_rad_; }
|
||||
/** @brief True if at least one cell has a nonzero direction code. */
|
||||
bool hasConstraints() const { return has_constraints_; }
|
||||
|
||||
/** @brief Check all owned cells traversed by a world-space segment.
|
||||
* @param wx0 Start x [m] in the global frame.
|
||||
* @param wy0 Start y [m] in the global frame.
|
||||
* @param wx1 End x [m] in the global frame.
|
||||
* @param wy1 End y [m] in the global frame.
|
||||
* @param first Optional output populated on kViolation.
|
||||
* @return kAllowed, kViolation, or kOutOfGrid; see SegmentResult.
|
||||
*/
|
||||
SegmentResult checkSegment(double wx0, double wy0, double wx1, double wy1,
|
||||
SegmentViolation* first = nullptr) const;
|
||||
|
||||
private:
|
||||
DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry,
|
||||
double max_deviation_rad);
|
||||
DirectionGeometry geometry_;
|
||||
std::vector<uint8_t> codes_;
|
||||
double max_deviation_rad_;
|
||||
bool has_constraints_;
|
||||
};
|
||||
|
||||
/** @brief Disabled, waiting for a current grid, or ready for queries. */
|
||||
enum class DirectionFieldState { kDisabled, kPending, kReady };
|
||||
|
||||
/** @brief Consistent state and generation with an immutable, shared field.
|
||||
* The field is non-null only in kReady. Readers may hold it through a whole
|
||||
* search while the layer publishes a newer generation on another thread.
|
||||
*/
|
||||
struct DirectionFieldSnapshot
|
||||
{
|
||||
DirectionFieldState state = DirectionFieldState::kDisabled;
|
||||
std::shared_ptr<const DirectionField> field;
|
||||
uint64_t generation = 0;
|
||||
};
|
||||
|
||||
/** @brief Core-side snapshot contract; avoids linking core against libplugins. */
|
||||
class DirectionFieldProvider
|
||||
{
|
||||
public:
|
||||
virtual ~DirectionFieldProvider() = default;
|
||||
/** @brief Return a consistent snapshot safe to retain on a planner thread. */
|
||||
virtual DirectionFieldSnapshot directionSnapshot() const = 0;
|
||||
};
|
||||
} // namespace robot_costmap_2d
|
||||
#endif // ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
|
||||
@@ -1,73 +1,40 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
#define ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
#ifndef ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_V1_H_
|
||||
#define ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_V1_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
#include <robot_costmap_2d/layer.h>
|
||||
#include <robot_costmap_2d/static_layer.h>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
/** @brief Publish immutable direction snapshots without modifying master costs.
|
||||
* The host thread feeds map and direction messages through dataCallBack(); the
|
||||
* costmap update thread calls updateBounds()/updateCosts(); planner threads use
|
||||
* directionSnapshot() and may retain a snapshot for an entire search.
|
||||
* When both mutexes are required, acquire the master costmap mutex before the
|
||||
* layer mutex, never the reverse. Snapshot readers hold only the layer mutex
|
||||
* briefly. Layer::isCurrent() still reads the legacy non-atomic current_ flag.
|
||||
*/
|
||||
class DirectionalLayer : public Layer, public DirectionFieldProvider
|
||||
{
|
||||
public:
|
||||
DirectionalLayer();
|
||||
~DirectionalLayer() override = default;
|
||||
/** @brief Identify this plugin as a directional layer. */
|
||||
LayerType getType() const override { return LayerType::DIRECTIONAL_LAYER; }
|
||||
/** @brief Copy a consistent immutable snapshot for a planner thread. */
|
||||
DirectionFieldSnapshot directionSnapshot() const override;
|
||||
/** @brief Update thread: leave bounds unchanged and report a stuck pending state.
|
||||
* @param robot_x Robot x [m] in the global frame.
|
||||
* @param robot_y Robot y [m] in the global frame.
|
||||
* @param robot_yaw Robot yaw [rad] in the global frame.
|
||||
* @param min_x Lower x bound [m] in the global frame.
|
||||
* @param min_y Lower y bound [m] in the global frame.
|
||||
* @param max_x Upper x bound [m] in the global frame.
|
||||
* @param max_y Upper y bound [m] in the global frame.
|
||||
*/
|
||||
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
|
||||
double* max_x, double* max_y) override;
|
||||
/** @brief Update thread: leave master costs unchanged.
|
||||
* @param master Master costmap in the global frame.
|
||||
* @param min_i Lower x cell index relative to the grid origin.
|
||||
* @param min_j Lower y cell index relative to the grid origin.
|
||||
* @param max_i Upper x cell index relative to the grid origin.
|
||||
* @param max_j Upper y cell index relative to the grid origin.
|
||||
*/
|
||||
void updateCosts(Costmap2D& /*master*/, int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/) override {}
|
||||
/** @brief Resize path: invalidate an enabled layer's snapshot. */
|
||||
void matchSize() override;
|
||||
/** @brief Retain a ready snapshot if master geometry [m, cells, frame] is unchanged. */
|
||||
void reset() override;
|
||||
class DirectionalLayer : public StaticLayer
|
||||
{
|
||||
public:
|
||||
DirectionalLayer();
|
||||
virtual ~DirectionalLayer();
|
||||
bool laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan);
|
||||
void resetMap();
|
||||
|
||||
protected:
|
||||
/** @brief Load plugin configuration and establish its initial state. */
|
||||
void onInitialize() override;
|
||||
/** @brief Host thread: process static-map and direction-grid callbacks. */
|
||||
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
|
||||
LayerType getType() const override
|
||||
{
|
||||
return LayerType::DIRECTIONAL_LAYER;
|
||||
}
|
||||
|
||||
private:
|
||||
void incomingMap(const robot_nav_msgs::OccupancyGrid &new_map);
|
||||
bool laneFilter(std::vector<std::array<uint16_t, 2>> new_map, const robot_nav_msgs::Path path);
|
||||
unsigned char laneFilter(unsigned int x, unsigned int y, double yaw_robot);
|
||||
void laneFilter(std::vector<unsigned int> x, std::vector<unsigned int> y, std::vector<double> yaw_robot);
|
||||
void laneFilter(std::vector<std::pair<unsigned int, double>> x, std::vector<std::pair<unsigned int, double>> y, std::vector<double> yaw_robot);
|
||||
bool inSkipErea(double start_x, double start_y, double end_x, double end_y, double skip_distance);
|
||||
void convertToMap(unsigned char *costmap, robot_nav_msgs::OccupancyGrid &dir_map, double occ_th, double free_th);
|
||||
bool getRobotPose(double &x, double &y, double &yaw);
|
||||
|
||||
private:
|
||||
DirectionGeometry geometry() const;
|
||||
void publishLocked(DirectionFieldState state, std::shared_ptr<const DirectionField> field = {});
|
||||
mutable std::mutex mutex_;
|
||||
DirectionFieldSnapshot snapshot_;
|
||||
bool seen_map_;
|
||||
bool debug_state_;
|
||||
bool rolling_;
|
||||
double max_deviation_rad_; ///< Maximum angular deviation [rad].
|
||||
std::string map_topic_, direction_topic_;
|
||||
std::chrono::steady_clock::time_point pending_since_, last_pending_log_;
|
||||
};
|
||||
} // namespace robot_costmap_2d
|
||||
#endif // ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
std::vector<std::array<uint16_t, 2>> directional_areas_;
|
||||
double pose_x_, pose_y_, pose_yaw_;
|
||||
double distance_skip_ = 1.0;
|
||||
// ros::Publisher lane_mask_pub_;
|
||||
robot_nav_msgs::OccupancyGrid new_map_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
|
||||
@@ -38,7 +38,6 @@
|
||||
#ifndef ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_
|
||||
#define ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
#include <robot_costmap_2d/cost_values.h>
|
||||
#include <robot_costmap_2d/layer.h>
|
||||
#include <robot_costmap_2d/costmap_2d.h>
|
||||
@@ -100,9 +99,6 @@ public:
|
||||
|
||||
bool isCurrent();
|
||||
|
||||
/** Consistent snapshot; plugin list must be fixed before concurrent reads. */
|
||||
DirectionFieldSnapshot getDirectionFieldSnapshot() const;
|
||||
|
||||
Costmap2D* getCostmap()
|
||||
{
|
||||
return &costmap_;
|
||||
|
||||
@@ -43,7 +43,6 @@
|
||||
|
||||
#include <robot_nav_msgs/OccupancyGrid.h>
|
||||
#include <robot_map_msgs/OccupancyGridUpdate.h>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
@@ -77,16 +76,14 @@ protected:
|
||||
virtual unsigned char interpretValue(unsigned char value);
|
||||
virtual void incomingMap(const robot_nav_msgs::OccupancyGrid& new_map);
|
||||
virtual void incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update);
|
||||
/// Called under the master costmap mutex after a nonempty region has been written.
|
||||
void markMapWritten(int min_i, int min_j, int max_i, int max_j);
|
||||
unsigned char* threshold_;
|
||||
std::string base_frame_id_;
|
||||
std::string global_frame_; ///< @brief The global frame for the costmap
|
||||
std::string map_frame_; /// @brief frame that map is located in
|
||||
std::string map_topic_; // Hiep thêm vào mục đich phân biết zones
|
||||
bool subscribe_to_updates_;
|
||||
bool map_received_ = false;
|
||||
bool has_updated_data_ = false;
|
||||
bool map_received_;
|
||||
bool has_updated_data_;
|
||||
unsigned int x_, y_, width_, height_;
|
||||
bool track_unknown_space_;
|
||||
bool use_maximum_;
|
||||
@@ -94,7 +91,6 @@ protected:
|
||||
bool trinary_costmap_;
|
||||
bool map_shutdown_ = false;
|
||||
bool map_update_shutdown_ = false;
|
||||
std::chrono::steady_clock::time_point last_invalid_update_log_;
|
||||
unsigned char lethal_threshold_, unknown_cost_value_;
|
||||
|
||||
private:
|
||||
|
||||
@@ -30,7 +30,6 @@ void CriticalLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int mi
|
||||
StaticLayer::CostmapLayer::updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
|
||||
else
|
||||
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
|
||||
markMapWritten(min_i, min_j, max_i, max_j);
|
||||
|
||||
}
|
||||
|
||||
@@ -43,4 +42,4 @@ static boost::shared_ptr<Layer> create_critical_plugin() {
|
||||
BOOST_DLL_ALIAS(create_critical_plugin, CriticalLayer)
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -66,26 +66,13 @@ 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;
|
||||
|
||||
// Occlusion guard. The values were checked on 10 KIT robot bags (22-23/10/2026) with an offline
|
||||
// replay of this layer; change them only with a new replay.
|
||||
// Ray bin in tangent units: 0.01 is ~0.57 deg, ~1.7 px of the D410 at fx = 300.
|
||||
constexpr float kRangeBin = 0.01f;
|
||||
// Returns and stored points closer than this along the viewing axis carry no evidence [m].
|
||||
constexpr float kRangeMinDepth = 0.1f;
|
||||
// Depth noise band around a stored point at range r: kRangeMargin + kRangeMarginPerSqM * r^2 [m].
|
||||
// Stereo depth error grows with r^2.
|
||||
constexpr float kRangeMargin = 0.05f;
|
||||
constexpr float kRangeMarginPerSqM = 0.02f;
|
||||
// Of the 3 x 3 bins around the ray: this many nearer bins hide the point...
|
||||
constexpr int kOccludingBins = 2;
|
||||
// ...and this many farther bins, the centre one among them, show that the camera sees past it.
|
||||
constexpr int kSeeThroughBins = 6;
|
||||
|
||||
Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t)
|
||||
{
|
||||
const auto& q = t.transform.rotation;
|
||||
@@ -96,6 +83,27 @@ Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t)
|
||||
return iso;
|
||||
}
|
||||
|
||||
// Steps 1 and 3 of the costmap layer config flow for one key: the value in the layer's default
|
||||
// file, overridden by "<costmap>/<plugin>/<key>", which Costmap2DROBOT::copyParentParameters() has
|
||||
// filled from the shared "<plugin>:" block. A value that does not convert to T is a configuration
|
||||
// error: getParam() would otherwise replace it with 0, false or "" without a word.
|
||||
template <typename T>
|
||||
T readParam(const YAML::Node& file_node, const std::string& file_key, const robot::NodeHandle& nh,
|
||||
const std::string& key, const T& fallback)
|
||||
{
|
||||
T value = loadParam(file_node, file_key, fallback);
|
||||
if (nh.hasParam(key) && !nh.getParam(key, value, value))
|
||||
throw std::invalid_argument("DepthCameraObstacleLayer: '" + nh.getNamespace() + "/" + key +
|
||||
"' does not convert to the type the layer reads");
|
||||
return value;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T readParam(const YAML::Node& file_node, const robot::NodeHandle& nh, const std::string& key, const T& fallback)
|
||||
{
|
||||
return readParam(file_node, key, nh, key, fallback);
|
||||
}
|
||||
|
||||
void requireRange(bool ok, const std::string& what)
|
||||
{
|
||||
if (!ok)
|
||||
@@ -108,10 +116,9 @@ void requireRange(bool ok, const std::string& what)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
void DepthCameraFrustum::build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
|
||||
double min_d, double max_d, bool optical, double attach_d)
|
||||
double min_d, double max_d, bool optical)
|
||||
{
|
||||
max_detect_distance = max_d;
|
||||
attach_distance = static_cast<float>(attach_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.
|
||||
@@ -178,7 +185,7 @@ bool DepthCameraFrustum::nearFace(const Eigen::Vector3f& p) const
|
||||
{
|
||||
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 <= attach_distance &&
|
||||
if (dis <= kAttachDistance &&
|
||||
std::hypot(p.x() - origin.x(), p.y() - origin.y()) < max_detect_distance + 0.5)
|
||||
return true;
|
||||
}
|
||||
@@ -208,84 +215,6 @@ bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const E
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Range image (occlusion guard, an addition of this port)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
void DepthCameraRangeImage::reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
|
||||
bool optical)
|
||||
{
|
||||
sensor_from_global_ = T_global_sensor.inverse().cast<float>();
|
||||
optical_ = optical;
|
||||
// One spare bin on each side: a ray on the frustum edge still has all its 3 x 3 neighbours.
|
||||
half_u_ = static_cast<int>(std::ceil(std::tan(fov_w / 2.0) / kRangeBin)) + 1;
|
||||
half_v_ = static_cast<int>(std::ceil(std::tan(fov_v / 2.0) / kRangeBin)) + 1;
|
||||
min_range_.assign(static_cast<std::size_t>(2 * half_u_ + 1) * static_cast<std::size_t>(2 * half_v_ + 1),
|
||||
std::numeric_limits<float>::infinity());
|
||||
}
|
||||
|
||||
Eigen::Vector3f DepthCameraRangeImage::toOptical(const Eigen::Vector3f& p) const
|
||||
{
|
||||
// Same axes as DepthCameraFrustum::build: camera_link X forward, Y left, Z up.
|
||||
return optical_ ? p : Eigen::Vector3f(-p.y(), -p.z(), p.x());
|
||||
}
|
||||
|
||||
bool DepthCameraRangeImage::bin(const Eigen::Vector3f& q, int& u, int& v) const
|
||||
{
|
||||
if (min_range_.empty() || !(q.z() > kRangeMinDepth))
|
||||
return false;
|
||||
const float fu = q.x() / q.z() / kRangeBin;
|
||||
const float fv = q.y() / q.z() / kRangeBin;
|
||||
if (!(std::fabs(fu) <= half_u_ + 0.5f) || !(std::fabs(fv) <= half_v_ + 0.5f))
|
||||
return false;
|
||||
u = static_cast<int>(std::lround(fu));
|
||||
v = static_cast<int>(std::lround(fv));
|
||||
return std::abs(u) <= half_u_ && std::abs(v) <= half_v_;
|
||||
}
|
||||
|
||||
void DepthCameraRangeImage::addSensorPoint(const Eigen::Vector3f& p)
|
||||
{
|
||||
const Eigen::Vector3f q = toOptical(p);
|
||||
int u, v;
|
||||
if (!bin(q, u, v))
|
||||
return;
|
||||
float& slot = min_range_[index(u, v)];
|
||||
slot = std::min(slot, q.norm());
|
||||
}
|
||||
|
||||
DepthCameraRangeImage::Evidence DepthCameraRangeImage::test(const Eigen::Vector3f& p_global) const
|
||||
{
|
||||
const Eigen::Vector3f q = toOptical(sensor_from_global_ * p_global);
|
||||
int u, v;
|
||||
if (!bin(q, u, v))
|
||||
return Evidence::kNone;
|
||||
const float r = q.norm();
|
||||
const float margin = kRangeMargin + kRangeMarginPerSqM * r * r;
|
||||
int nearer = 0, farther = 0;
|
||||
for (int du = -1; du <= 1; ++du)
|
||||
{
|
||||
for (int dv = -1; dv <= 1; ++dv)
|
||||
{
|
||||
const int a = u + du, b = v + dv;
|
||||
if (std::abs(a) > half_u_ || std::abs(b) > half_v_)
|
||||
continue;
|
||||
// Only the nearest return of a bin counts: a bin that grazes the floor spans tens of
|
||||
// centimetres of range, so its farthest return says nothing. +inf (no return) counts for neither.
|
||||
const float m = min_range_[index(a, b)];
|
||||
if (m < r - margin)
|
||||
++nearer;
|
||||
else if (std::isfinite(m) && m > r + margin)
|
||||
++farther;
|
||||
}
|
||||
}
|
||||
const float centre = min_range_[index(u, v)];
|
||||
if (nearer >= kOccludingBins || centre < r - margin)
|
||||
return Evidence::kOccluded;
|
||||
if (farther >= kSeeThroughBins && std::isfinite(centre) && centre > r + margin)
|
||||
return Evidence::kSeenThrough;
|
||||
return Evidence::kNone;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Layer
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -329,83 +258,36 @@ void DepthCameraObstacleLayer::loadParameters()
|
||||
throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": " + config_file_name +
|
||||
" has no depth_camera_obstacle_layer: block");
|
||||
|
||||
// ===== 1. Defaults from the layer's file =====
|
||||
// track_unknown_space is not in the file on purpose: unset, the layer follows the costmap.
|
||||
bool track_unknown_space = loadParam(layer, "track_unknown_space", layered_costmap_->isTrackingUnknown());
|
||||
enabled_ = loadParam(layer, "enabled", true);
|
||||
footprint_clearing_enabled_ = loadParam(layer, "footprint_clearing_enabled", true);
|
||||
combination_method_ = loadParam(layer, "combination_method", 1);
|
||||
enable_near_blocked_protection_ = loadParam(layer, "enable_near_blocked_protection", true);
|
||||
number_points_considered_as_blocked_ = loadParam(layer, "number_points_considered_as_blocked", 5);
|
||||
forced_clearing_distance_ = loadParam(layer, "forced_clearing_distance", 0.1);
|
||||
ec_seg_distance_ = loadParam(layer, "ec_seg_distance", 0.2);
|
||||
ec_cluster_min_size_ = loadParam(layer, "ec_cluster_min_size", 5);
|
||||
size_of_cluster_rejection_ = loadParam(layer, "size_of_cluster_rejection", 5);
|
||||
voxel_resolution_ = loadParam(layer, "voxel_resolution", 0.01);
|
||||
check_radius_ = loadParam(layer, "check_radius", 0.1);
|
||||
number_clearing_threshold_ = loadParam(layer, "number_clearing_threshold", 2);
|
||||
use_voxelized_observation_ = loadParam(layer, "use_voxelized_observation", true);
|
||||
transform_tolerance_ = loadParam(layer, "transform_tolerance", 0.2);
|
||||
bool use_global_frame_to_mark = loadParam(layer, "use_global_frame_to_mark", true);
|
||||
std::string topics_string = loadParam(layer, "observation_sources", std::string(""));
|
||||
debug_stats_ = loadParam(layer["debug"], "stats", true);
|
||||
debug_stats_period_ = loadParam(layer["debug"], "stats_period", 5.0);
|
||||
occlusion_guard_ = loadParam(layer, "occlusion_guard", false);
|
||||
|
||||
// ===== 2. Override from "<costmap>/<plugin>", which copyParentParameters() filled from the
|
||||
// shared "<plugin>:" block (only when the key exists) =====
|
||||
// getParam() gets the current value as its default: a value of the wrong type then keeps the
|
||||
// file default instead of becoming 0/false/"". A wrong type in the shared block already stopped
|
||||
// copyParentParameters().
|
||||
// Step 3: "<costmap>/<plugin>", filled by copyParentParameters() from the shared block.
|
||||
robot::NodeHandle nh("~");
|
||||
robot::NodeHandle priv_nh(nh, name_);
|
||||
if (priv_nh.hasParam("track_unknown_space"))
|
||||
priv_nh.getParam("track_unknown_space", track_unknown_space, track_unknown_space);
|
||||
if (priv_nh.hasParam("enabled"))
|
||||
priv_nh.getParam("enabled", enabled_, enabled_);
|
||||
if (priv_nh.hasParam("footprint_clearing_enabled"))
|
||||
priv_nh.getParam("footprint_clearing_enabled", footprint_clearing_enabled_, footprint_clearing_enabled_);
|
||||
if (priv_nh.hasParam("combination_method"))
|
||||
priv_nh.getParam("combination_method", combination_method_, combination_method_);
|
||||
if (priv_nh.hasParam("enable_near_blocked_protection"))
|
||||
priv_nh.getParam("enable_near_blocked_protection", enable_near_blocked_protection_,
|
||||
enable_near_blocked_protection_);
|
||||
if (priv_nh.hasParam("number_points_considered_as_blocked"))
|
||||
priv_nh.getParam("number_points_considered_as_blocked", number_points_considered_as_blocked_,
|
||||
number_points_considered_as_blocked_);
|
||||
if (priv_nh.hasParam("forced_clearing_distance"))
|
||||
priv_nh.getParam("forced_clearing_distance", forced_clearing_distance_, forced_clearing_distance_);
|
||||
if (priv_nh.hasParam("ec_seg_distance"))
|
||||
priv_nh.getParam("ec_seg_distance", ec_seg_distance_, ec_seg_distance_);
|
||||
if (priv_nh.hasParam("ec_cluster_min_size"))
|
||||
priv_nh.getParam("ec_cluster_min_size", ec_cluster_min_size_, ec_cluster_min_size_);
|
||||
if (priv_nh.hasParam("size_of_cluster_rejection"))
|
||||
priv_nh.getParam("size_of_cluster_rejection", size_of_cluster_rejection_, size_of_cluster_rejection_);
|
||||
if (priv_nh.hasParam("voxel_resolution"))
|
||||
priv_nh.getParam("voxel_resolution", voxel_resolution_, voxel_resolution_);
|
||||
if (priv_nh.hasParam("check_radius"))
|
||||
priv_nh.getParam("check_radius", check_radius_, check_radius_);
|
||||
if (priv_nh.hasParam("number_clearing_threshold"))
|
||||
priv_nh.getParam("number_clearing_threshold", number_clearing_threshold_, number_clearing_threshold_);
|
||||
if (priv_nh.hasParam("use_voxelized_observation"))
|
||||
priv_nh.getParam("use_voxelized_observation", use_voxelized_observation_, use_voxelized_observation_);
|
||||
if (priv_nh.hasParam("transform_tolerance"))
|
||||
priv_nh.getParam("transform_tolerance", transform_tolerance_, transform_tolerance_);
|
||||
if (priv_nh.hasParam("use_global_frame_to_mark"))
|
||||
priv_nh.getParam("use_global_frame_to_mark", use_global_frame_to_mark, use_global_frame_to_mark);
|
||||
if (priv_nh.hasParam("observation_sources"))
|
||||
priv_nh.getParam("observation_sources", topics_string, topics_string);
|
||||
if (priv_nh.hasParam("debug/stats"))
|
||||
priv_nh.getParam("debug/stats", debug_stats_, debug_stats_);
|
||||
if (priv_nh.hasParam("debug/stats_period"))
|
||||
priv_nh.getParam("debug/stats_period", debug_stats_period_, debug_stats_period_);
|
||||
if (priv_nh.hasParam("occlusion_guard"))
|
||||
priv_nh.getParam("occlusion_guard", occlusion_guard_, occlusion_guard_);
|
||||
const robot::NodeHandle priv_nh(nh, name_);
|
||||
|
||||
// Not in the default file on purpose: unset, the layer follows the costmap's track_unknown_space.
|
||||
const bool track_unknown_space =
|
||||
readParam(layer, priv_nh, "track_unknown_space", layered_costmap_->isTrackingUnknown());
|
||||
default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE;
|
||||
|
||||
enabled_ = readParam(layer, priv_nh, "enabled", true);
|
||||
footprint_clearing_enabled_ = readParam(layer, priv_nh, "footprint_clearing_enabled", true);
|
||||
combination_method_ = readParam(layer, priv_nh, "combination_method", 1);
|
||||
enable_near_blocked_protection_ = readParam(layer, priv_nh, "enable_near_blocked_protection", true);
|
||||
number_points_considered_as_blocked_ = readParam(layer, priv_nh, "number_points_considered_as_blocked", 5);
|
||||
forced_clearing_distance_ = readParam(layer, priv_nh, "forced_clearing_distance", 0.1);
|
||||
ec_seg_distance_ = readParam(layer, priv_nh, "ec_seg_distance", 0.2);
|
||||
ec_cluster_min_size_ = readParam(layer, priv_nh, "ec_cluster_min_size", 5);
|
||||
size_of_cluster_rejection_ = readParam(layer, priv_nh, "size_of_cluster_rejection", 5);
|
||||
voxel_resolution_ = readParam(layer, priv_nh, "voxel_resolution", 0.01);
|
||||
check_radius_ = readParam(layer, priv_nh, "check_radius", 0.1);
|
||||
number_clearing_threshold_ = readParam(layer, priv_nh, "number_clearing_threshold", 2);
|
||||
use_voxelized_observation_ = readParam(layer, priv_nh, "use_voxelized_observation", true);
|
||||
transform_tolerance_ = readParam(layer, priv_nh, "transform_tolerance", 0.2);
|
||||
const bool use_global_frame_to_mark = readParam(layer, priv_nh, "use_global_frame_to_mark", true);
|
||||
if (layer["clear_touches_bounds"] || priv_nh.hasParam("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());
|
||||
YAML::Node debug = layer["debug"];
|
||||
debug_stats_ = readParam(debug, "stats", priv_nh, "debug/stats", true);
|
||||
debug_stats_period_ = readParam(debug, "stats_period", priv_nh, "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.
|
||||
@@ -424,61 +306,29 @@ void DepthCameraObstacleLayer::loadParameters()
|
||||
marking_height_under_ground_ = 100.0;
|
||||
marking_height_above_ground_ = -100.0;
|
||||
|
||||
std::stringstream ss(topics_string);
|
||||
std::stringstream ss(readParam(layer, priv_nh, "observation_sources", std::string("")));
|
||||
std::string name;
|
||||
while (ss >> name)
|
||||
{
|
||||
// Like obstacle_layer_params.yaml, the default file has no block per source, so a source key
|
||||
// comes from "<costmap>/<plugin>/<source>/" or falls back to the C++ default below.
|
||||
YAML::Node source_defaults = layer[name];
|
||||
const robot::NodeHandle s(priv_nh, name);
|
||||
std::unique_ptr<Source> src(new Source());
|
||||
src->name = name;
|
||||
|
||||
// ===== 1. Defaults. Like obstacle_layer_params.yaml, the file has no block per source, so
|
||||
// these are the C++ defaults unless the file gains one =====
|
||||
src->topic = loadParam(layer[name], "topic", name);
|
||||
src->sensor_frame = loadParam(layer[name], "sensor_frame", std::string(""));
|
||||
src->sensor_frame_is_optical = loadParam(layer[name], "sensor_frame_is_optical", false);
|
||||
src->observation_keep_time = loadParam(layer[name], "observation_persistence", 0.0);
|
||||
src->expected_update_rate = loadParam(layer[name], "expected_update_rate", 0.0);
|
||||
src->min_obstacle_height = loadParam(layer[name], "min_obstacle_height", 0.0);
|
||||
src->max_obstacle_height = loadParam(layer[name], "max_obstacle_height", 2.0);
|
||||
src->marking = loadParam(layer[name], "marking", true);
|
||||
src->fov_v = loadParam(layer[name], "FOV_V", 1.0);
|
||||
src->fov_w = loadParam(layer[name], "FOV_W", 1.5);
|
||||
src->min_detect_distance = loadParam(layer[name], "min_detect_distance", 0.15);
|
||||
src->max_detect_distance = loadParam(layer[name], "max_detect_distance", 2.5);
|
||||
src->attach_distance = loadParam(layer[name], "attach_distance", 0.12);
|
||||
bool inf_is_valid = loadParam(layer[name], "inf_is_valid", false);
|
||||
|
||||
// ===== 2. Override from "<costmap>/<plugin>/<source>" =====
|
||||
robot::NodeHandle source_nh(priv_nh, name);
|
||||
if (source_nh.hasParam("topic"))
|
||||
source_nh.getParam("topic", src->topic, src->topic);
|
||||
if (source_nh.hasParam("sensor_frame"))
|
||||
source_nh.getParam("sensor_frame", src->sensor_frame, src->sensor_frame);
|
||||
if (source_nh.hasParam("sensor_frame_is_optical"))
|
||||
source_nh.getParam("sensor_frame_is_optical", src->sensor_frame_is_optical, src->sensor_frame_is_optical);
|
||||
if (source_nh.hasParam("observation_persistence"))
|
||||
source_nh.getParam("observation_persistence", src->observation_keep_time, src->observation_keep_time);
|
||||
if (source_nh.hasParam("expected_update_rate"))
|
||||
source_nh.getParam("expected_update_rate", src->expected_update_rate, src->expected_update_rate);
|
||||
if (source_nh.hasParam("min_obstacle_height"))
|
||||
source_nh.getParam("min_obstacle_height", src->min_obstacle_height, src->min_obstacle_height);
|
||||
if (source_nh.hasParam("max_obstacle_height"))
|
||||
source_nh.getParam("max_obstacle_height", src->max_obstacle_height, src->max_obstacle_height);
|
||||
if (source_nh.hasParam("marking"))
|
||||
source_nh.getParam("marking", src->marking, src->marking);
|
||||
if (source_nh.hasParam("FOV_V"))
|
||||
source_nh.getParam("FOV_V", src->fov_v, src->fov_v);
|
||||
if (source_nh.hasParam("FOV_W"))
|
||||
source_nh.getParam("FOV_W", src->fov_w, src->fov_w);
|
||||
if (source_nh.hasParam("min_detect_distance"))
|
||||
source_nh.getParam("min_detect_distance", src->min_detect_distance, src->min_detect_distance);
|
||||
if (source_nh.hasParam("max_detect_distance"))
|
||||
source_nh.getParam("max_detect_distance", src->max_detect_distance, src->max_detect_distance);
|
||||
if (source_nh.hasParam("attach_distance"))
|
||||
source_nh.getParam("attach_distance", src->attach_distance, src->attach_distance);
|
||||
if (source_nh.hasParam("inf_is_valid"))
|
||||
source_nh.getParam("inf_is_valid", inf_is_valid, inf_is_valid);
|
||||
if (inf_is_valid)
|
||||
src->topic = readParam(source_defaults, s, "topic", name);
|
||||
src->sensor_frame = readParam(source_defaults, s, "sensor_frame", std::string(""));
|
||||
src->sensor_frame_is_optical = readParam(source_defaults, s, "sensor_frame_is_optical", false);
|
||||
src->observation_keep_time = readParam(source_defaults, s, "observation_persistence", 0.0);
|
||||
src->expected_update_rate = readParam(source_defaults, s, "expected_update_rate", 0.0);
|
||||
src->min_obstacle_height = readParam(source_defaults, s, "min_obstacle_height", 0.0);
|
||||
src->max_obstacle_height = readParam(source_defaults, s, "max_obstacle_height", 2.0);
|
||||
src->marking = readParam(source_defaults, s, "marking", true);
|
||||
src->fov_v = readParam(source_defaults, s, "FOV_V", 1.0);
|
||||
src->fov_w = readParam(source_defaults, s, "FOV_W", 1.5);
|
||||
src->min_detect_distance = readParam(source_defaults, s, "min_detect_distance", 0.15);
|
||||
src->max_detect_distance = readParam(source_defaults, s, "max_detect_distance", 2.5);
|
||||
if (readParam(source_defaults, s, "inf_is_valid", false))
|
||||
robot::log_warning("DepthCameraObstacleLayer: inf_is_valid is not applicable to PointCloud observations\n");
|
||||
|
||||
const std::string what = "source " + name + ": ";
|
||||
@@ -486,10 +336,6 @@ void DepthCameraObstacleLayer::loadParameters()
|
||||
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]");
|
||||
// At half the frustum depth the near and far bands meet and nothing along the axis is marked.
|
||||
requireRange(src->attach_distance >= 0.0 &&
|
||||
src->attach_distance < (src->max_detect_distance - src->min_detect_distance) / 2.0,
|
||||
what + "attach_distance must be in [0, (max_detect_distance - min_detect_distance) / 2) [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,
|
||||
@@ -501,14 +347,14 @@ void DepthCameraObstacleLayer::loadParameters()
|
||||
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 attach=%.3f m "
|
||||
"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->attach_distance, src->observation_keep_time,
|
||||
src->expected_update_rate, src->marking ? "true" : "false");
|
||||
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())
|
||||
@@ -520,7 +366,7 @@ void DepthCameraObstacleLayer::loadParameters()
|
||||
"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 occlusion_guard=%s debug/stats=%s\n",
|
||||
"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_,
|
||||
@@ -528,8 +374,7 @@ void DepthCameraObstacleLayer::loadParameters()
|
||||
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_,
|
||||
occlusion_guard_ ? "true" : "false", debug_stats_ ? "on" : "off");
|
||||
marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off");
|
||||
}
|
||||
|
||||
void DepthCameraObstacleLayer::handleImpl(const void* data, const std::type_info& type,
|
||||
@@ -616,14 +461,7 @@ bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_ms
|
||||
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, source.attach_distance);
|
||||
// Occlusion guard: nearest return per ray from every point, before the height gate below.
|
||||
Eigen::Isometry3f T_sensor_cloud = Eigen::Isometry3f::Identity();
|
||||
if (occlusion_guard_)
|
||||
{
|
||||
obs.range.reset(T_origin, source.fov_w, source.fov_v, source.sensor_frame_is_optical);
|
||||
T_sensor_cloud = (T_origin.inverse() * T_cloud).cast<float>();
|
||||
}
|
||||
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);
|
||||
@@ -635,8 +473,6 @@ bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_ms
|
||||
// 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;
|
||||
if (occlusion_guard_)
|
||||
obs.range.addSensorPoint(T_sensor_cloud * Eigen::Vector3f(*iter_x, *iter_y, *iter_z));
|
||||
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>());
|
||||
@@ -696,8 +532,6 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
|
||||
|
||||
bool current = true;
|
||||
std::vector<DepthCameraFrustum> frustums;
|
||||
// Points into source->observations, which nothing changes until the end of this cycle.
|
||||
std::vector<const DepthCameraRangeImage*> range_images;
|
||||
std::vector<Eigen::Vector3f> combined;
|
||||
for (const auto& source : sources_)
|
||||
{
|
||||
@@ -708,7 +542,6 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
|
||||
for (const Observation& obs : source->observations)
|
||||
{
|
||||
frustums.push_back(obs.frustum);
|
||||
range_images.push_back(obs.range.empty() ? nullptr : &obs.range);
|
||||
combined.insert(combined.end(), obs.points.begin(), obs.points.end());
|
||||
}
|
||||
current = sourceIsCurrent(*source) && current;
|
||||
@@ -746,7 +579,7 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
|
||||
points.emplace_back(pt.x, pt.y, pt.z);
|
||||
stats_.cloud_points += points.size();
|
||||
|
||||
clearMarkingByKdtree(points, frustums, range_images, robot_x, robot_y, min_x, min_y, max_x, max_y);
|
||||
clearMarkingByKdtree(points, frustums, robot_x, robot_y, min_x, min_y, max_x, max_y);
|
||||
|
||||
if (cloud->points.size() > 5)
|
||||
{
|
||||
@@ -783,7 +616,6 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
|
||||
|
||||
void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
|
||||
const std::vector<DepthCameraFrustum>& frustums,
|
||||
const std::vector<const DepthCameraRangeImage*>& range_images,
|
||||
double robot_x, double robot_y, double* min_x,
|
||||
double* min_y, double* max_x, double* max_y)
|
||||
{
|
||||
@@ -861,34 +693,6 @@ void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vec
|
||||
q.z = search.z();
|
||||
erase = kdtree.radiusSearch(q, check_radius_, indices, sq_distances) < number_clearing_threshold_;
|
||||
}
|
||||
// The kd-tree test cannot tell "gone" from "hidden by something nearer": a person walking in
|
||||
// front of a box cleared the box. With the guard, the depth rays decide where they can.
|
||||
if (occlusion_guard_ && !bypass_clearing)
|
||||
{
|
||||
// The middle of the cell, not its corner: indices are truncated toward zero, so the corner
|
||||
// can lie outside a small object and its ray would see the floor behind it.
|
||||
const Eigen::Vector3f centre(static_cast<float>(wx + std::copysign(0.5 * resolution, wx)),
|
||||
static_cast<float>(wy + std::copysign(0.5 * resolution, wy)), search.z());
|
||||
bool occluded = false, seen_through = false;
|
||||
for (std::size_t i = 0; i < frustums.size() && i < range_images.size(); ++i)
|
||||
{
|
||||
if (range_images[i] == nullptr || !frustums[i].inside(search))
|
||||
continue;
|
||||
const DepthCameraRangeImage::Evidence evidence = range_images[i]->test(centre);
|
||||
occluded = occluded || evidence == DepthCameraRangeImage::Evidence::kOccluded;
|
||||
seen_through = seen_through || evidence == DepthCameraRangeImage::Evidence::kSeenThrough;
|
||||
}
|
||||
if (erase && occluded)
|
||||
{
|
||||
erase = false;
|
||||
++stats_.kept_occluded;
|
||||
}
|
||||
else if (!erase && seen_through && !occluded)
|
||||
{
|
||||
erase = true;
|
||||
++stats_.cleared_seen_through;
|
||||
}
|
||||
}
|
||||
if (!erase)
|
||||
continue;
|
||||
heights.erase(it);
|
||||
@@ -1081,13 +885,11 @@ void DepthCameraObstacleLayer::logStats()
|
||||
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 kept_occluded=%zu cleared_seen_through=%zu "
|
||||
"bounds_ms avg=%.1f max=%.1f\n",
|
||||
"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_.kept_occluded, stats_.cleared_seen_through,
|
||||
stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
|
||||
stats_.dropped_out_of_window, stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
|
||||
stats_ = Stats();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,230 +1,428 @@
|
||||
#include <robot_costmap_2d/directional_layer.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
#include <data_convert/data_convert.h>
|
||||
#include <tf3/convert.h>
|
||||
#include <tf3/utils.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <robot/console.h>
|
||||
#include <robot/node_handle.h>
|
||||
#include <robot_costmap_2d/utils.h>
|
||||
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
|
||||
|
||||
using robot_costmap_2d::CRITICAL_SPACE;
|
||||
using robot_costmap_2d::LETHAL_OBSTACLE;
|
||||
using robot_costmap_2d::NO_INFORMATION;
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr auto kPendingErrorDelay = std::chrono::seconds(5);
|
||||
constexpr auto kPendingErrorPeriod = std::chrono::seconds(5);
|
||||
DirectionalLayer::DirectionalLayer()
|
||||
{}
|
||||
|
||||
DirectionalLayer::~DirectionalLayer() {}
|
||||
|
||||
bool topicMatches(const std::string& topic, const std::string& configured)
|
||||
{
|
||||
return topic == configured || topic == "/" + configured;
|
||||
}
|
||||
|
||||
const char* stateName(DirectionFieldState state)
|
||||
{
|
||||
switch (state)
|
||||
bool DirectionalLayer::laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan)
|
||||
{
|
||||
case DirectionFieldState::kDisabled:
|
||||
return "DISABLED";
|
||||
case DirectionFieldState::kPending:
|
||||
return "PENDING";
|
||||
case DirectionFieldState::kReady:
|
||||
return "READY";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DirectionalLayer::DirectionalLayer()
|
||||
: Layer(), mutex_(), snapshot_(), seen_map_(false), debug_state_(true), rolling_(false), max_deviation_rad_(M_PI / 2.0),
|
||||
map_topic_("map"), direction_topic_("direction_map"), pending_since_(), last_pending_log_()
|
||||
{
|
||||
}
|
||||
|
||||
void DirectionalLayer::onInitialize()
|
||||
{
|
||||
robot::NodeHandle nh("~");
|
||||
robot::NodeHandle priv_nh(nh, name_);
|
||||
const std::string filename = "directional_layer_params.yaml";
|
||||
double max_deviation_deg = 90.0;
|
||||
try
|
||||
{
|
||||
const char* env = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
const std::string folder = env && std::filesystem::exists(env) ? env : "";
|
||||
const YAML::Node layer = YAML::LoadFile(getSourceFile(folder, filename))["directional_layer"];
|
||||
enabled_ = loadParam(layer, "enabled", false);
|
||||
map_topic_ = loadParam(layer, "map_topic", std::string("map"));
|
||||
direction_topic_ = loadParam(layer, "direction_topic", std::string("direction_map"));
|
||||
max_deviation_deg = loadParam(layer, "max_deviation_deg", 90.0);
|
||||
debug_state_ = loadParam(layer, "debug_state", true);
|
||||
if (priv_nh.hasParam("enabled"))
|
||||
priv_nh.getParam("enabled", enabled_, enabled_);
|
||||
if (priv_nh.hasParam("map_topic"))
|
||||
priv_nh.getParam("map_topic", map_topic_);
|
||||
if (priv_nh.hasParam("direction_topic"))
|
||||
priv_nh.getParam("direction_topic", direction_topic_);
|
||||
if (priv_nh.hasParam("max_deviation_deg"))
|
||||
priv_nh.getParam("max_deviation_deg", max_deviation_deg);
|
||||
if (priv_nh.hasParam("debug_state"))
|
||||
priv_nh.getParam("debug_state", debug_state_);
|
||||
}
|
||||
catch (const YAML::BadFile&)
|
||||
{
|
||||
throw std::runtime_error("DirectionalLayer " + name_ + ": cannot open the default file " + filename);
|
||||
}
|
||||
if (!std::isfinite(max_deviation_deg) || max_deviation_deg <= 0.0 || max_deviation_deg >= 180.0)
|
||||
throw std::runtime_error("DirectionalLayer " + name_ + ": max_deviation_deg must be finite and in (0, 180)");
|
||||
if (max_deviation_deg < 22.5)
|
||||
robot::log_warning("DirectionalLayer %s: max_deviation_deg < 22.5 may leave SBPL without a path", name_.c_str());
|
||||
max_deviation_rad_ = (max_deviation_deg / 180.0) * M_PI;
|
||||
// Preserve the open interval even when conversion rounds at an extreme value.
|
||||
if (max_deviation_rad_ <= 0.0)
|
||||
max_deviation_rad_ = std::nextafter(0.0, M_PI);
|
||||
else if (max_deviation_rad_ >= M_PI)
|
||||
max_deviation_rad_ = std::nextafter(M_PI, 0.0);
|
||||
rolling_ = layered_costmap_->isRolling();
|
||||
if (enabled_ && rolling_)
|
||||
robot::log_error("DirectionalLayer %s: rolling costmap is unsupported", name_.c_str());
|
||||
if (enabled_ && (map_topic_.empty() || direction_topic_.empty() || topicMatches(map_topic_, direction_topic_) ||
|
||||
topicMatches(direction_topic_, map_topic_)))
|
||||
throw std::runtime_error("DirectionalLayer " + name_ + ": topics must be nonempty and distinct");
|
||||
robot::log_info("DirectionalLayer %s: enabled=%d map_topic=%s direction_topic=%s max_deviation_deg=%g debug_state=%d",
|
||||
name_.c_str(), enabled_, map_topic_.c_str(), direction_topic_.c_str(), max_deviation_deg, debug_state_);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
publishLocked(enabled_ ? DirectionFieldState::kPending : DirectionFieldState::kDisabled);
|
||||
}
|
||||
|
||||
void DirectionalLayer::publishLocked(DirectionFieldState state, std::shared_ptr<const DirectionField> field)
|
||||
{
|
||||
snapshot_.state = state;
|
||||
snapshot_.field = std::move(field);
|
||||
++snapshot_.generation;
|
||||
// Layer::isCurrent() reads this non-atomic bool without this mutex (legacy API limitation).
|
||||
current_ = state != DirectionFieldState::kPending;
|
||||
if (state == DirectionFieldState::kPending)
|
||||
{
|
||||
pending_since_ = std::chrono::steady_clock::now();
|
||||
last_pending_log_ = {};
|
||||
}
|
||||
if (debug_state_)
|
||||
robot::log_info("[debug] DirectionalLayer %s: %s generation=%llu", name_.c_str(), stateName(state),
|
||||
static_cast<unsigned long long>(snapshot_.generation));
|
||||
}
|
||||
|
||||
DirectionFieldSnapshot DirectionalLayer::directionSnapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return snapshot_;
|
||||
}
|
||||
|
||||
DirectionGeometry DirectionalLayer::geometry() const
|
||||
{
|
||||
const auto* master = layered_costmap_->getCostmap();
|
||||
return {master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
|
||||
master->getOriginX(), master->getOriginY(), layered_costmap_->getGlobalFrameID()};
|
||||
}
|
||||
|
||||
void DirectionalLayer::handleImpl(const void* data, const std::type_info& type, const std::string& topic)
|
||||
{
|
||||
if (!enabled_ || type != typeid(robot_nav_msgs::OccupancyGrid) ||
|
||||
(!topicMatches(topic, map_topic_) && !topicMatches(topic, direction_topic_)))
|
||||
return;
|
||||
|
||||
if (topicMatches(topic, map_topic_))
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
seen_map_ = true;
|
||||
publishLocked(DirectionFieldState::kPending);
|
||||
return;
|
||||
if (directional_areas_.empty())
|
||||
throw "Has no map data";
|
||||
robot_nav_msgs::Path path;
|
||||
path.header.stamp = robot::Time::now();
|
||||
path.header.frame_id = map_frame_;
|
||||
path.poses = plan;
|
||||
return this->laneFilter(directional_areas_, path);
|
||||
}
|
||||
|
||||
DirectionGeometry expected;
|
||||
uint64_t generation;
|
||||
void DirectionalLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> master_lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (rolling_)
|
||||
return;
|
||||
if (!seen_map_)
|
||||
if(!map_shutdown_)
|
||||
{
|
||||
robot::log_error("DirectionalLayer %s: direction grid arrived before static map", name_.c_str());
|
||||
return;
|
||||
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
|
||||
|
||||
robot::log_info("Received a %d X %d map at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
|
||||
// resize costmap if size, resolution or origin do not match
|
||||
Costmap2D *master = layered_costmap_->getCostmap();
|
||||
if (!layered_costmap_->isRolling() &&
|
||||
(master->getSizeInCellsX() != size_x / 2 ||
|
||||
master->getSizeInCellsY() != size_y / 2 ||
|
||||
master->getResolution() != new_map.info.resolution ||
|
||||
master->getOriginX() != new_map.info.origin.position.x ||
|
||||
master->getOriginY() != new_map.info.origin.position.y))
|
||||
{
|
||||
// Update the size of the layered costmap (and all layers, including this one)
|
||||
robot::log_info("Resizing costmap to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
layered_costmap_->resizeMap(size_x / 2, size_y / 2, new_map.info.resolution, new_map.info.origin.position.x,
|
||||
new_map.info.origin.position.y,
|
||||
true /* set size_locked to true, prevents reconfigureCb from overriding map size*/);
|
||||
}
|
||||
else if (size_x_ != size_x / 2 || size_y_ != size_y / 2 ||
|
||||
resolution_ != new_map.info.resolution ||
|
||||
origin_x_ != new_map.info.origin.position.x ||
|
||||
origin_y_ != new_map.info.origin.position.y)
|
||||
{
|
||||
// only update the size of the costmap stored locally in this layer
|
||||
robot::log_info("Resizing static layer to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
|
||||
resizeMap(size_x / 2, size_y / 2, new_map.info.resolution,
|
||||
new_map.info.origin.position.x, new_map.info.origin.position.y);
|
||||
}
|
||||
unsigned char values[4];
|
||||
directional_areas_.clear();
|
||||
directional_areas_.resize(size_x / 2 * size_y / 2);
|
||||
// initialize the costmap with static data
|
||||
for (unsigned int iy = 0; iy < size_y; iy += 2)
|
||||
{
|
||||
for (unsigned int ix = 0; ix < size_x; ix += 2)
|
||||
{
|
||||
values[0] = new_map.data[MAP_IDX(size_x, ix, iy)];
|
||||
values[1] = new_map.data[MAP_IDX(size_x, ix + 1, iy)];
|
||||
values[2] = new_map.data[MAP_IDX(size_x, ix, iy + 1)];
|
||||
values[3] = new_map.data[MAP_IDX(size_x, ix + 1, iy + 1)];
|
||||
uint32_t color_avg = (uint32_t)(values[0] | values[1] << 8u | values[2] << 16u | values[3] << 24u);
|
||||
int index = getIndex(ix / 2, iy / 2);
|
||||
directional_areas_[index][0] = (uint16_t)(color_avg & 0xfff);
|
||||
directional_areas_[index][1] = (uint16_t)(color_avg >> 12u);
|
||||
costmap_[index] = robot_costmap_2d::NO_INFORMATION;
|
||||
}
|
||||
}
|
||||
map_frame_ = new_map.header.frame_id;
|
||||
|
||||
// we have a new map, update full size of map
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
map_received_ = true;
|
||||
has_updated_data_ = true;
|
||||
|
||||
new_map_.header = new_map.header;
|
||||
new_map_.header.stamp = robot::Time::now();
|
||||
new_map_.info = new_map.info;
|
||||
new_map_.info.width = width_;
|
||||
new_map_.info.height = height_;
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_info("Stop receive new map!\n");
|
||||
}
|
||||
// shutdown the map subscrber if firt_map_only_ flag is on
|
||||
if (first_map_only_)
|
||||
{
|
||||
robot::log_info("Shutting down the map subscriber. first_map_only flag is on\n");
|
||||
map_shutdown_ = true;
|
||||
// map_sub_.shutdown();
|
||||
}
|
||||
expected = geometry();
|
||||
generation = snapshot_.generation;
|
||||
}
|
||||
DirectionValidationResult validation;
|
||||
auto field = DirectionField::create(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data), expected,
|
||||
max_deviation_rad_, &validation);
|
||||
if (!field)
|
||||
|
||||
bool DirectionalLayer::laneFilter(std::vector<std::array<uint16_t, 2>> new_map, const robot_nav_msgs::Path path)
|
||||
{
|
||||
robot::log_error("DirectionalLayer %s: invalid direction grid: %s", name_.c_str(), validation.message.c_str());
|
||||
return;
|
||||
boost::unique_lock<mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if (new_map.empty())
|
||||
return false;
|
||||
|
||||
std::vector<std::pair<unsigned int, double>> X_List, Y_List;
|
||||
std::vector<double> Yaw_list;
|
||||
|
||||
const robot_geometry_msgs::PoseStamped &e = path.poses.back();
|
||||
|
||||
bool get_success = getRobotPose(pose_x_, pose_y_, pose_yaw_);
|
||||
if(!get_success) return false;
|
||||
for (auto it = path.poses.begin(); it != path.poses.end(); ++it)
|
||||
{
|
||||
const robot_geometry_msgs::PoseStamped &p = *it; // Get the pose from the iterator
|
||||
unsigned int mx, my;
|
||||
if (!worldToMap(p.pose.position.x, p.pose.position.y, mx, my))
|
||||
{
|
||||
robot::log_error("ERROR: trying to set a start cell %f %f that is outside of map\n", p.pose.position.x, p.pose.position.y);
|
||||
return false;
|
||||
}
|
||||
// Convert to yaw
|
||||
tf3::Quaternion quaternion = data_convert::convertQuaternion(p.pose.orientation);
|
||||
double theta = tf3::getYaw(quaternion);
|
||||
unsigned char value = laneFilter(mx, my, theta);
|
||||
if (get_success)
|
||||
{
|
||||
if (
|
||||
(!inSkipErea(pose_x_, pose_y_, p.pose.position.x, p.pose.position.y, distance_skip_) &
|
||||
!inSkipErea(p.pose.position.x, p.pose.position.y, e.pose.position.x, e.pose.position.y, distance_skip_))
|
||||
|| p == path.poses.back()
|
||||
)
|
||||
{
|
||||
if (value == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE || value == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
{
|
||||
std::pair<unsigned int, double> x_val(mx, p.pose.position.x);
|
||||
std::pair<unsigned int, double> y_val(my, p.pose.position.y);
|
||||
X_List.push_back(x_val);
|
||||
Y_List.push_back(y_val);
|
||||
Yaw_list.push_back(theta);
|
||||
// costmap_[getIndex(mx, my)] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!Yaw_list.empty())
|
||||
{
|
||||
laneFilter(X_List, Y_List, Yaw_list);
|
||||
robot_nav_msgs::OccupancyGrid lanes;
|
||||
convertToMap(costmap_, lanes, 0.65, 0.196);
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
// resizeMap holds the master mutex through matchSize(), which increments generation.
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (snapshot_.generation != generation)
|
||||
void DirectionalLayer::convertToMap(unsigned char *costmap, robot_nav_msgs::OccupancyGrid &dir_map, double occ_th, double free_th)
|
||||
{
|
||||
robot::log_error("DirectionalLayer %s: grid discarded because map state changed during validation", name_.c_str());
|
||||
return;
|
||||
dir_map.header = new_map_.header;
|
||||
dir_map.header.stamp = robot::Time::now();
|
||||
dir_map.info = new_map_.info;
|
||||
int size_costmap = new_map_.info.width * new_map_.info.height;
|
||||
dir_map.data.resize(size_costmap);
|
||||
for (int i = 0; i < size_costmap; i++)
|
||||
{
|
||||
int8_t value;
|
||||
if (costmap[i] == robot_costmap_2d::NO_INFORMATION)
|
||||
{
|
||||
value = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
double occ = (costmap[i]) / 255.0;
|
||||
if (occ > occ_th)
|
||||
value = +100;
|
||||
else if (occ < free_th)
|
||||
value = 0;
|
||||
else
|
||||
{
|
||||
double ratio = (occ - free_th) / (occ_th - free_th);
|
||||
value = 1 + 98 * ratio;
|
||||
}
|
||||
}
|
||||
dir_map.data[i] = value;
|
||||
}
|
||||
}
|
||||
publishLocked(DirectionFieldState::kReady, std::move(field));
|
||||
}
|
||||
|
||||
void DirectionalLayer::matchSize()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (enabled_)
|
||||
publishLocked(DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
void DirectionalLayer::reset()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> master_lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!enabled_ || snapshot_.state != DirectionFieldState::kReady)
|
||||
return;
|
||||
const auto now = geometry();
|
||||
const auto& old = snapshot_.field->geometry();
|
||||
if (old.width != now.width || old.height != now.height || old.frame_id != now.frame_id ||
|
||||
!std::isfinite(now.resolution) || !std::isfinite(now.origin_x) || !std::isfinite(now.origin_y) ||
|
||||
std::abs(old.resolution - now.resolution) > 1e-6 || std::abs(old.origin_x - now.origin_x) > 1e-6 ||
|
||||
std::abs(old.origin_y - now.origin_y) > 1e-6)
|
||||
publishLocked(DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
void DirectionalLayer::updateBounds(double, double, double, double*, double*, double*, double*)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (snapshot_.state != DirectionFieldState::kPending)
|
||||
return;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - pending_since_ >= kPendingErrorDelay &&
|
||||
(last_pending_log_ == std::chrono::steady_clock::time_point() ||
|
||||
now - last_pending_log_ >= kPendingErrorPeriod))
|
||||
unsigned char DirectionalLayer::laneFilter(unsigned int x, unsigned int y, double yaw_robot)
|
||||
{
|
||||
robot::log_error("DirectionalLayer %s: PENDING for %.1f seconds", name_.c_str(),
|
||||
std::chrono::duration<double>(now - pending_since_).count());
|
||||
last_pending_log_ = now;
|
||||
}
|
||||
}
|
||||
} // namespace robot_costmap_2d
|
||||
double yaw_lane;
|
||||
unsigned char cost = robot_costmap_2d::NO_INFORMATION;
|
||||
|
||||
boost::shared_ptr<robot_costmap_2d::Layer> create_directional_plugin()
|
||||
{
|
||||
return boost::shared_ptr<robot_costmap_2d::Layer>(new robot_costmap_2d::DirectionalLayer());
|
||||
}
|
||||
BOOST_DLL_ALIAS(create_directional_plugin, DirectionalLayer)
|
||||
int index = getIndex(x, y);
|
||||
for (auto &lane : directional_areas_[index])
|
||||
{
|
||||
if (lane > 359)
|
||||
{
|
||||
cost = std::min(cost, robot_costmap_2d::NO_INFORMATION);
|
||||
}
|
||||
else
|
||||
{
|
||||
double yaw_lane = (double)lane / 180 * M_PI;
|
||||
if (0.4 <= cos(yaw_robot - yaw_lane) && cos(yaw_robot - yaw_lane) <= 1.0)
|
||||
cost = std::min(cost, robot_costmap_2d::FREE_SPACE);
|
||||
else if (-1.0 <= cos(yaw_robot - yaw_lane) && cos(yaw_robot - yaw_lane) <= -0.4)
|
||||
cost = std::min(cost, robot_costmap_2d::LETHAL_OBSTACLE);
|
||||
else
|
||||
cost = std::min(cost, robot_costmap_2d::NO_INFORMATION);
|
||||
}
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
void DirectionalLayer::laneFilter(std::vector<std::pair<unsigned int, double>> x,
|
||||
std::vector<std::pair<unsigned int, double>> y,
|
||||
std::vector<double> yaw_robot)
|
||||
{
|
||||
if(x.empty() || y.empty() || yaw_robot.empty())
|
||||
return;
|
||||
|
||||
unsigned int x_min, y_min, x_max, y_max;
|
||||
double x_min_w, y_min_w, x_max_w, y_max_w;
|
||||
|
||||
x_min = x.front().first; y_min = y.front().first;
|
||||
x_max = x.front().first; y_max = y.front().first;
|
||||
x_min_w = x.front().second; y_min_w = y.front().second;
|
||||
x_max_w = x.front().second; y_max_w = y.front().second;
|
||||
for (int i = 1; i < yaw_robot.size(); i++)
|
||||
{
|
||||
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
|
||||
continue;
|
||||
x_min = std::min(x_min, x[i].first);
|
||||
y_min = std::min(y_min, y[i].first);
|
||||
x_max = std::max(x_max, x[i].first);
|
||||
y_max = std::max(y_max, y[i].first);
|
||||
|
||||
x_min_w = std::min(x_min_w, x[i].second);
|
||||
y_min_w = std::min(y_min_w, y[i].second);
|
||||
x_max_w = std::max(x_max_w, x[i].second);
|
||||
y_max_w = std::max(y_max_w, y[i].second);
|
||||
|
||||
}
|
||||
|
||||
for (int i = 0; i < yaw_robot.size(); i++)
|
||||
{
|
||||
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
|
||||
continue;
|
||||
|
||||
double yaw_rad = (double)yaw_robot[i] / 180 * M_PI;
|
||||
if (fabs(cos(yaw_rad)) > fabs(sin(yaw_rad)))
|
||||
{
|
||||
int x_ = x[i].first;
|
||||
// Dưới lên trên
|
||||
for (int j = y[i].first; j <= y_max; j++)
|
||||
{
|
||||
int y_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trên xuống dưới
|
||||
for (int k = y[i].first; k >= y_min; k--)
|
||||
{
|
||||
int y_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
int y_ = y[i].first;
|
||||
// Phải qua trái
|
||||
for (int j = x[i].first; j < layered_costmap_->getCostmap()->getSizeInCellsX(); j++)
|
||||
{
|
||||
int x_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trái qua phải
|
||||
for (int k = x[i].first; k >= 0; k--)
|
||||
{
|
||||
int x_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if(fabs(cos(yaw_rad)) < fabs(sin(yaw_rad)))
|
||||
{
|
||||
int y_ = y[i].first;
|
||||
// Phải qua trái
|
||||
for (int j = x[i].first; j <= x_max; j++)
|
||||
{
|
||||
int x_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trái qua phải
|
||||
for (int k = x[i].first; k >= x_min; k--)
|
||||
{
|
||||
int x_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
int x_ = x[i].first;
|
||||
// Dưới lên trên
|
||||
for (int j = y[i].first; j < layered_costmap_->getCostmap()->getSizeInCellsY(); j++)
|
||||
{
|
||||
int y_ = j;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Trên xuống dưới
|
||||
for (int k = y[i].first; k >= 0; k--)
|
||||
{
|
||||
int y_ = k;
|
||||
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
|
||||
continue;
|
||||
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
|
||||
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
|
||||
costmap_[getIndex(x_, y_)] = value;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DirectionalLayer::resetMap()
|
||||
{
|
||||
unsigned int size_x = layered_costmap_->getCostmap()->getSizeInCellsX();
|
||||
unsigned int size_y = layered_costmap_->getCostmap()->getSizeInCellsY();
|
||||
for (unsigned int iy = 0; iy < size_y; iy++)
|
||||
{
|
||||
for (unsigned int ix = 0; ix < size_x; ix++)
|
||||
{
|
||||
int index = getIndex(ix, iy);
|
||||
costmap_[index] = robot_costmap_2d::NO_INFORMATION;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool DirectionalLayer::getRobotPose(double &x, double &y, double &yaw)
|
||||
{
|
||||
tf3::TransformStampedMsg transformMsg;
|
||||
try
|
||||
{
|
||||
transformMsg = tf_->lookupTransform(map_frame_, base_frame_id_, tf3::Time());
|
||||
|
||||
// listener_.lookupTransform(map_frame_, base_frame_id_, tf3::Time(), transform);
|
||||
}
|
||||
catch (tf3::TransformException &ex)
|
||||
{
|
||||
robot::log_error("%s\n", ex.what());
|
||||
return false;
|
||||
}
|
||||
// Copy map data given proper transformations
|
||||
tf3::Transform tf3_transform;
|
||||
tf3_transform = data_convert::convertTotf3Transform(transformMsg.transform);
|
||||
x = tf3_transform.getOrigin().x();
|
||||
y = tf3_transform.getOrigin().y();
|
||||
// Extract the rotation as a quaternion from the transform
|
||||
tf3::Quaternion rotation = tf3_transform.getRotation();
|
||||
// Convert the quaternion to a yaw angle (in radians)
|
||||
yaw = tf3::getYaw(rotation);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DirectionalLayer::inSkipErea(double start_x, double start_y, double end_x, double end_y, double skip_distance)
|
||||
{
|
||||
return fabs(hypot(start_x - end_x, start_y - end_y)) <= skip_distance;
|
||||
}
|
||||
|
||||
// Export factory function
|
||||
static boost::shared_ptr<Layer> create_directional_plugin() {
|
||||
return boost::make_shared<DirectionalLayer>();
|
||||
}
|
||||
|
||||
// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias)
|
||||
BOOST_DLL_ALIAS(create_directional_plugin, DirectionalLayer)
|
||||
}
|
||||
@@ -65,19 +65,10 @@ StaticLayer::~StaticLayer()
|
||||
|
||||
void StaticLayer::onInitialize()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
robot::NodeHandle nh("~");
|
||||
robot::NodeHandle priv_nh(nh, name_);
|
||||
|
||||
current_ = false;
|
||||
if (map_received_)
|
||||
{
|
||||
// Reinitialization must request another master write even if the old map is retained.
|
||||
has_updated_data_ = true;
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
}
|
||||
current_ = true;
|
||||
|
||||
global_frame_ = layered_costmap_->getGlobalFrameID();
|
||||
std::string config_file_name = "static_layer_params.yaml";
|
||||
@@ -168,12 +159,6 @@ void StaticLayer::matchSize()
|
||||
// unrelated to the size of the layered costmap
|
||||
if (!layered_costmap_->isRolling())
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
// resizeMap discards this layer's cached cells, even when the geometry is unchanged.
|
||||
// A new map is required before the layer can write meaningful data again.
|
||||
current_ = false;
|
||||
map_received_ = false;
|
||||
has_updated_data_ = false;
|
||||
Costmap2D* master = layered_costmap_->getCostmap();
|
||||
resizeMap(master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
|
||||
master->getOriginX(), master->getOriginY());
|
||||
@@ -213,14 +198,9 @@ void StaticLayer::handleImpl(const void* data,
|
||||
if (type == typeid(robot_nav_msgs::OccupancyGrid) &&
|
||||
(topic == map_topic_ || topic == "/" + map_topic_)) {
|
||||
incomingMap(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data));
|
||||
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) &&
|
||||
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) &&
|
||||
(topic == map_topic_ + "_updates" || topic == "/" + map_topic_ + "_updates")) {
|
||||
incomingUpdate(*static_cast<const robot_map_msgs::OccupancyGridUpdate*>(data));
|
||||
} else if (type == typeid(robot_nav_msgs::OccupancyGrid) ||
|
||||
type == typeid(robot_map_msgs::OccupancyGridUpdate)) {
|
||||
// Right type, another layer's topic: the gateway sends every grid to every layer of this
|
||||
// type (other StaticLayers, the direction grid). Normal traffic, not an error.
|
||||
return;
|
||||
} else {
|
||||
std::string readable = boost::core::demangle(type.name());
|
||||
|
||||
@@ -229,6 +209,7 @@ void StaticLayer::handleImpl(const void* data,
|
||||
{
|
||||
readable = readable.substr(0, pos);
|
||||
}
|
||||
robot::log_error("[] con1: %x, con2: %x ", type == typeid(robot_nav_msgs::OccupancyGrid), (topic == map_topic_ || topic == "/" + map_topic_));
|
||||
robot::log_error("[StaticLayer] Received data of unknown type: %s on topic: %s, map_topic_: %s\n", readable.c_str(), topic.c_str(), map_topic_.c_str());
|
||||
// std::cout << "[StaticLayer] Unknown type: " << type.name() << " on topic: " << topic << std::endl;
|
||||
}
|
||||
@@ -236,10 +217,8 @@ void StaticLayer::handleImpl(const void* data,
|
||||
|
||||
void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if(!map_shutdown_)
|
||||
{
|
||||
current_ = false;
|
||||
std::cout << "[StaticLayer] Received new map!" << std::endl;
|
||||
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
|
||||
|
||||
@@ -321,25 +300,8 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
|
||||
|
||||
void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update)
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if(!map_update_shutdown_ && map_received_)
|
||||
if(!map_update_shutdown_)
|
||||
{
|
||||
const bool outside = update.x < 0 || update.y < 0 || update.width == 0 || update.height == 0 ||
|
||||
static_cast<unsigned int>(update.x) > size_x_ || static_cast<unsigned int>(update.y) > size_y_ ||
|
||||
update.width > size_x_ - static_cast<unsigned int>(update.x) ||
|
||||
update.height > size_y_ - static_cast<unsigned int>(update.y);
|
||||
if (outside || update.data.size() != static_cast<std::size_t>(update.width) * update.height)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (last_invalid_update_log_ == std::chrono::steady_clock::time_point{} ||
|
||||
std::chrono::duration<double>(now - last_invalid_update_log_).count() >= 5.0)
|
||||
{
|
||||
robot::log_error("StaticLayer %s: ignoring an invalid map update", name_.c_str());
|
||||
last_invalid_update_log_ = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
current_ = false;
|
||||
robot::log_info("Update new map!\n");
|
||||
unsigned int di = 0;
|
||||
for (unsigned int y = 0; y < update.height ; y++)
|
||||
@@ -351,34 +313,16 @@ void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& upda
|
||||
costmap_[index] = interpretValue(update.data[di++]);
|
||||
}
|
||||
}
|
||||
if (has_updated_data_)
|
||||
{
|
||||
// A full map or another update may still be awaiting updateBounds(). Preserve all dirty
|
||||
// cells; otherwise a partial update could make the layer current while part of the new map
|
||||
// has never reached the master.
|
||||
const unsigned int update_x = static_cast<unsigned int>(update.x);
|
||||
const unsigned int update_y = static_cast<unsigned int>(update.y);
|
||||
const unsigned int max_x = std::max(x_ + width_, update_x + update.width);
|
||||
const unsigned int max_y = std::max(y_ + height_, update_y + update.height);
|
||||
x_ = std::min(x_, update_x);
|
||||
y_ = std::min(y_, update_y);
|
||||
width_ = max_x - x_;
|
||||
height_ = max_y - y_;
|
||||
}
|
||||
else
|
||||
{
|
||||
x_ = update.x;
|
||||
y_ = update.y;
|
||||
width_ = update.width;
|
||||
height_ = update.height;
|
||||
}
|
||||
x_ = update.x;
|
||||
y_ = update.y;
|
||||
width_ = update.width;
|
||||
height_ = update.height;
|
||||
has_updated_data_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void StaticLayer::activate()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
map_shutdown_ = false;
|
||||
map_update_shutdown_ = false;
|
||||
onInitialize();
|
||||
@@ -386,7 +330,6 @@ void StaticLayer::activate()
|
||||
|
||||
void StaticLayer::deactivate()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
map_shutdown_ = true;
|
||||
if (subscribe_to_updates_)
|
||||
map_update_shutdown_ = true;
|
||||
@@ -394,16 +337,11 @@ void StaticLayer::deactivate()
|
||||
|
||||
void StaticLayer::reset()
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
|
||||
if (first_map_only_)
|
||||
{
|
||||
map_shutdown_ = false;
|
||||
map_update_shutdown_ = false;
|
||||
current_ = false;
|
||||
has_updated_data_ = true;
|
||||
x_ = y_ = 0;
|
||||
width_ = size_x_;
|
||||
height_ = size_y_;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -490,13 +428,6 @@ void StaticLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_
|
||||
}
|
||||
}
|
||||
}
|
||||
markMapWritten(min_i, min_j, max_i, max_j);
|
||||
}
|
||||
|
||||
void StaticLayer::markMapWritten(int min_i, int min_j, int max_i, int max_j)
|
||||
{
|
||||
if (map_received_ && min_i < max_i && min_j < max_j)
|
||||
current_ = true;
|
||||
}
|
||||
|
||||
// Export factory function
|
||||
|
||||
@@ -434,7 +434,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
|
||||
move_parameters<bool>(plugin_nh, costmap_plugin_nh,
|
||||
{"track_unknown_space", "enabled", "footprint_clearing_enabled",
|
||||
"enable_near_blocked_protection", "use_voxelized_observation", "use_global_frame_to_mark",
|
||||
"clear_touches_bounds", "debug/stats", "occlusion_guard"});
|
||||
"clear_touches_bounds", "debug/stats"});
|
||||
move_parameters<int>(plugin_nh, costmap_plugin_nh,
|
||||
{"combination_method", "number_points_considered_as_blocked", "ec_cluster_min_size",
|
||||
"size_of_cluster_rejection", "number_clearing_threshold"});
|
||||
@@ -446,7 +446,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
|
||||
move_parameters<bool>(from, to, {"sensor_frame_is_optical", "marking", "inf_is_valid"});
|
||||
move_parameters<double>(from, to, {"observation_persistence", "expected_update_rate", "min_obstacle_height",
|
||||
"max_obstacle_height", "FOV_V", "FOV_W", "min_detect_distance",
|
||||
"max_detect_distance", "attach_distance"});
|
||||
"max_detect_distance"});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <sstream>
|
||||
|
||||
namespace robot_costmap_2d
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr double kTolerance = 1e-6;
|
||||
|
||||
std::string frameName(const std::string& frame)
|
||||
{
|
||||
return !frame.empty() && frame[0] == '/' ? frame.substr(1) : frame;
|
||||
}
|
||||
|
||||
DirectionValidationResult fail(DirectionValidationError error, const std::string& message)
|
||||
{
|
||||
return {error, message};
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::string value(const char* name, T actual)
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << name << "=" << actual;
|
||||
return out.str();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected)
|
||||
{
|
||||
const auto& info = grid.info;
|
||||
const uint64_t count = uint64_t(info.width) * uint64_t(info.height);
|
||||
if (count > std::vector<uint8_t>().max_size())
|
||||
return fail(DirectionValidationError::kOverflow, value("cell count", count));
|
||||
if (frameName(grid.header.frame_id).empty() || frameName(grid.header.frame_id) != frameName(expected.frame_id))
|
||||
return fail(DirectionValidationError::kFrame,
|
||||
"frame_id=" + grid.header.frame_id + " expected=" + expected.frame_id);
|
||||
if (info.width != expected.width || info.height != expected.height)
|
||||
return fail(DirectionValidationError::kGeometry,
|
||||
value("width", info.width) + " " + value("height", info.height));
|
||||
|
||||
const auto close = [](double a, double b)
|
||||
{
|
||||
return std::isfinite(a) && std::isfinite(b) && std::abs(a - b) <= kTolerance;
|
||||
};
|
||||
if (!close(info.resolution, expected.resolution) || info.resolution <= 0.0 || expected.resolution <= 0.0)
|
||||
return fail(DirectionValidationError::kGeometry, value("resolution", info.resolution));
|
||||
if (!close(info.origin.position.x, expected.origin_x) || !close(info.origin.position.y, expected.origin_y) ||
|
||||
!std::isfinite(info.origin.position.z))
|
||||
return fail(DirectionValidationError::kGeometry,
|
||||
value("origin.x", info.origin.position.x) + " " + value("origin.y", info.origin.position.y) +
|
||||
" " + value("origin.z", info.origin.position.z));
|
||||
|
||||
const auto& q = info.origin.orientation;
|
||||
// A default-constructed Pose has a zero quaternion; it denotes no rotation here.
|
||||
if (!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w) ||
|
||||
std::abs(q.x) > kTolerance || std::abs(q.y) > kTolerance || std::abs(q.z) > kTolerance ||
|
||||
!(std::abs(std::abs(q.w) - 1.0) <= kTolerance || std::abs(q.w) <= kTolerance))
|
||||
return fail(DirectionValidationError::kOrientation,
|
||||
value("orientation.x", q.x) + " " + value("y", q.y) + " " + value("z", q.z) +
|
||||
" " + value("w", q.w));
|
||||
if (!grid.data.empty() && grid.data.size() != count)
|
||||
return fail(DirectionValidationError::kSize, value("data.size", grid.data.size()) + " " + value("expected", count));
|
||||
for (size_t i = 0; i < grid.data.size(); ++i)
|
||||
{
|
||||
if (grid.data[i] < 0 || grid.data[i] > 8)
|
||||
return fail(DirectionValidationError::kCode, value("data index", i) + " " + value("code", int(grid.data[i])));
|
||||
}
|
||||
return {DirectionValidationError::kNone, "valid"};
|
||||
}
|
||||
|
||||
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad)
|
||||
{
|
||||
if (!std::isfinite(dx) || !std::isfinite(dy))
|
||||
return 0;
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
const long double x = dx, y = dy;
|
||||
const bool legacy_right_angle = max_deviation_rad == M_PI / 2.0;
|
||||
const long double length = std::hypot(x, y);
|
||||
const long double threshold = (std::cos(max_deviation_rad) - 1e-9L) * length;
|
||||
const long double legacy_tolerance = 1e-9L * (std::abs(x) + std::abs(y));
|
||||
constexpr long double kInverseSqrtTwo = 0.707106781186547524400844362104849L;
|
||||
uint8_t mask = 0;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const long double dot = vx[k] * x + vy[k] * y;
|
||||
// Preserve the exact legacy tolerance at 90 degrees, including near-boundary inputs.
|
||||
if (legacy_right_angle ? dot >= -legacy_tolerance :
|
||||
dot * (k % 2 ? kInverseSqrtTwo : 1.0L) >= threshold)
|
||||
mask |= uint8_t(1u << k);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
DirectionField::DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry,
|
||||
double max_deviation_rad)
|
||||
: geometry_(geometry), codes_(grid.data.begin(), grid.data.end()),
|
||||
max_deviation_rad_(max_deviation_rad),
|
||||
has_constraints_(std::any_of(codes_.begin(), codes_.end(), [](uint8_t c) { return c != 0; }))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<const DirectionField> DirectionField::create(const robot_nav_msgs::OccupancyGrid& grid,
|
||||
const DirectionGeometry& expected,
|
||||
double max_deviation_rad,
|
||||
DirectionValidationResult* result)
|
||||
{
|
||||
auto validation = validateDirectionGrid(grid, expected);
|
||||
if (result)
|
||||
*result = validation;
|
||||
if (!validation)
|
||||
return {};
|
||||
return std::shared_ptr<const DirectionField>(new DirectionField(grid, expected, max_deviation_rad));
|
||||
}
|
||||
|
||||
uint8_t DirectionField::code(uint32_t x, uint32_t y) const
|
||||
{
|
||||
assert(x < geometry_.width && y < geometry_.height);
|
||||
return codes_.empty() ? 0 : codes_[size_t(y) * geometry_.width + x];
|
||||
}
|
||||
|
||||
bool DirectionField::codeAt(int64_t x, int64_t y, uint8_t* code_out) const
|
||||
{
|
||||
if (!code_out || x < 0 || y < 0 || x >= geometry_.width || y >= geometry_.height)
|
||||
return false;
|
||||
*code_out = code(static_cast<uint32_t>(x), static_cast<uint32_t>(y));
|
||||
return true;
|
||||
}
|
||||
|
||||
SegmentResult DirectionField::checkSegment(double wx0, double wy0, double wx1, double wy1,
|
||||
SegmentViolation* first) const
|
||||
{
|
||||
const auto gx = [this](double x) { return (x - geometry_.origin_x) / geometry_.resolution; };
|
||||
const auto gy = [this](double y) { return (y - geometry_.origin_y) / geometry_.resolution; };
|
||||
const double x0 = gx(wx0);
|
||||
const double y0 = gy(wy0);
|
||||
const double x1 = gx(wx1);
|
||||
const double y1 = gy(wy1);
|
||||
const auto inside = [this](double x, double y)
|
||||
{
|
||||
return std::isfinite(x) && std::isfinite(y) && x >= 0 && y >= 0 &&
|
||||
x < geometry_.width && y < geometry_.height;
|
||||
};
|
||||
if (!inside(x0, y0) || !inside(x1, y1))
|
||||
return SegmentResult::kOutOfGrid;
|
||||
const double dx = wx1 - wx0;
|
||||
const double dy = wy1 - wy0;
|
||||
if (!std::isfinite(dx) || !std::isfinite(dy))
|
||||
return SegmentResult::kOutOfGrid;
|
||||
|
||||
const uint8_t mask = allowedDirectionMask(dx, dy, max_deviation_rad_);
|
||||
SegmentResult result = SegmentResult::kAllowed;
|
||||
const bool completed = traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y)
|
||||
{
|
||||
uint8_t cell_code;
|
||||
if (!codeAt(x, y, &cell_code))
|
||||
{
|
||||
result = SegmentResult::kOutOfGrid;
|
||||
return false;
|
||||
}
|
||||
if (cell_code && !(mask & (1u << (cell_code - 1))))
|
||||
{
|
||||
if (first)
|
||||
*first = {uint32_t(x), uint32_t(y), cell_code, dx, dy};
|
||||
result = SegmentResult::kViolation;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return completed || result != SegmentResult::kAllowed ? result : SegmentResult::kOutOfGrid;
|
||||
}
|
||||
} // namespace robot_costmap_2d
|
||||
@@ -366,25 +366,6 @@ namespace robot_costmap_2d
|
||||
}
|
||||
}
|
||||
|
||||
DirectionFieldSnapshot LayeredCostmap::getDirectionFieldSnapshot() const
|
||||
{
|
||||
DirectionFieldSnapshot result;
|
||||
unsigned int count = 0;
|
||||
for (const auto& plugin : plugins_)
|
||||
{
|
||||
if (!plugin->isEnabled()) continue;
|
||||
const auto* provider = dynamic_cast<const DirectionFieldProvider*>(plugin.get());
|
||||
if (!provider) continue;
|
||||
result = provider->directionSnapshot();
|
||||
if (++count > 1)
|
||||
{
|
||||
robot::log_error("Multiple enabled direction field providers; refusing direction queries");
|
||||
return {DirectionFieldState::kPending, {}, 0};
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool LayeredCostmap::isCurrent()
|
||||
{
|
||||
current_ = true;
|
||||
|
||||
@@ -99,33 +99,6 @@ std::vector<Eigen::Vector3d> join(std::vector<Eigen::Vector3d> a, const std::vec
|
||||
return a;
|
||||
}
|
||||
|
||||
// Dense vertical sheet at x (odom): with step / x <= 0.01 every ray bin it covers gets a return,
|
||||
// unlike object(), whose 6 cm gaps let the rays through.
|
||||
std::vector<Eigen::Vector3d> sheet(double x, double y0, double y1, double z0, double z1, double step = .01)
|
||||
{
|
||||
std::vector<Eigen::Vector3d> pts;
|
||||
for (double y = y0; y <= y1 + 1e-9; y += step)
|
||||
for (double z = z0; z <= z1 + 1e-9; z += step)
|
||||
pts.emplace_back(x, y, z);
|
||||
return pts;
|
||||
}
|
||||
|
||||
// Far backdrop 2 m ahead, behind everything the guard tests store.
|
||||
std::vector<Eigen::Vector3d> backdrop()
|
||||
{
|
||||
return sheet(2.0, -.10, .60, .05, .60, .015);
|
||||
}
|
||||
|
||||
// 21 x 21 returns 5 mm apart, centred on (x, y0, z0) of a camera_link frame (X forward).
|
||||
std::vector<Eigen::Vector3f> patch(float x, float y0, float z0)
|
||||
{
|
||||
std::vector<Eigen::Vector3f> pts;
|
||||
for (int i = -10; i <= 10; ++i)
|
||||
for (int j = -10; j <= 10; ++j)
|
||||
pts.emplace_back(x, y0 + i * .005f, z0 + j * .005f);
|
||||
return pts;
|
||||
}
|
||||
|
||||
YAML::Node baseConfig()
|
||||
{
|
||||
YAML::Node cfg;
|
||||
@@ -179,18 +152,6 @@ TEST(DepthCameraFrustum, AttachBandIsTwelveCentimetresFromEveryFace)
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .3f, 0)));
|
||||
}
|
||||
|
||||
TEST(DepthCameraFrustum, AttachDistanceFollowsTheParameter)
|
||||
{
|
||||
DepthCameraFrustum f;
|
||||
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false, .08);
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.20f, 0, 0))); // 5 cm past it
|
||||
const float half_w = std::tan(kFovW / 2);
|
||||
// 5 cm / 15 cm inside the left face along y: ~4 cm / ~12 cm from its plane.
|
||||
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0)));
|
||||
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .15f, 0)));
|
||||
}
|
||||
|
||||
TEST(DepthCameraFrustum, OpticalFrameGivesTheSamePyramid)
|
||||
{
|
||||
DepthCameraFrustum link, optical;
|
||||
@@ -216,49 +177,6 @@ TEST(DepthCameraFrustum, AttachedUnlessWellInsideAnotherFrustum)
|
||||
EXPECT_FALSE(attachedToFrustums({a}, Eigen::Vector3f(1, 0, 0)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Range image (occlusion guard)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
TEST(DepthCameraRangeImage, NearerReturnsHideAndFartherReturnsShowThrough)
|
||||
{
|
||||
using Evidence = DepthCameraRangeImage::Evidence;
|
||||
DepthCameraRangeImage image;
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(1, 0, 0)), Evidence::kNone); // never built
|
||||
image.reset(Eigen::Isometry3d::Identity(), kFovW, kFovV, false); // X forward
|
||||
for (const Eigen::Vector3f& p : patch(1, 0, 0))
|
||||
image.addSensorPoint(p);
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(2, 0, 0)), Evidence::kOccluded); // behind the patch
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(.5f, 0, 0)), Evidence::kSeenThrough); // in front of it
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(1, 0, 0)), Evidence::kNone); // on it
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(1, .5f, 0)), Evidence::kNone); // no return on that ray
|
||||
EXPECT_EQ(image.test(Eigen::Vector3f(.05f, 0, 0)), Evidence::kNone); // too close to judge
|
||||
}
|
||||
|
||||
TEST(DepthCameraRangeImage, OpticalFrameGivesTheSameEvidence)
|
||||
{
|
||||
using Evidence = DepthCameraRangeImage::Evidence;
|
||||
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
|
||||
T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link
|
||||
DepthCameraRangeImage link, optical;
|
||||
link.reset(Eigen::Isometry3d::Identity(), kFovW, kFovV, false);
|
||||
optical.reset(T, kFovW, kFovV, true);
|
||||
const Eigen::Isometry3f optical_from_link = T.inverse().cast<float>();
|
||||
// Off-centre patch (left and up), so a mirrored axis would answer for the wrong ray.
|
||||
for (const Eigen::Vector3f& p : patch(1, .3f, .1f))
|
||||
{
|
||||
link.addSensorPoint(p);
|
||||
optical.addSensorPoint(optical_from_link * p);
|
||||
}
|
||||
const Eigen::Vector3f behind(2, .6f, .2f), mirrored(2, -.6f, -.2f), in_front(.5f, .15f, .05f);
|
||||
EXPECT_EQ(link.test(behind), Evidence::kOccluded);
|
||||
EXPECT_EQ(link.test(mirrored), Evidence::kNone);
|
||||
EXPECT_EQ(link.test(in_front), Evidence::kSeenThrough);
|
||||
EXPECT_EQ(optical.test(behind), Evidence::kOccluded);
|
||||
EXPECT_EQ(optical.test(mirrored), Evidence::kNone);
|
||||
EXPECT_EQ(optical.test(in_front), Evidence::kSeenThrough);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Layer
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -392,122 +310,6 @@ TEST_F(DepthCameraLayerTest, AttachBandIsNotMarked)
|
||||
EXPECT_EQ(layer.storedPoints(), wall_points);
|
||||
}
|
||||
|
||||
class DepthCameraAttachTest : public DepthCameraLayerTest
|
||||
{
|
||||
protected:
|
||||
void configure(YAML::Node& cfg) override
|
||||
{
|
||||
cfg["depth_cam"]["attach_distance"] = .08;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(DepthCameraAttachTest, NarrowerAttachBandMarksCloserToTheFaces)
|
||||
{
|
||||
// The scene of AttachBandIsNotMarked: 10 cm past the near plane is outside an 8 cm band.
|
||||
frame(wall());
|
||||
const std::size_t wall_points = layer.storedPoints();
|
||||
ASSERT_GT(wall_points, 0u);
|
||||
frame(join(object(.25, .10, .19), wall()));
|
||||
EXPECT_GT(layer.storedPoints(), wall_points);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Occlusion guard
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
class DepthCameraGuardTest : public DepthCameraLayerTest
|
||||
{
|
||||
protected:
|
||||
void configure(YAML::Node& cfg) override
|
||||
{
|
||||
cfg["number_clearing_threshold"] = 1; // as on the KIT robot
|
||||
cfg["occlusion_guard"] = guard();
|
||||
}
|
||||
virtual bool guard() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
class DepthCameraNoGuardTest : public DepthCameraGuardTest
|
||||
{
|
||||
protected:
|
||||
bool guard() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// A box 1.42 m ahead, then a screen 1 m ahead that hides it (a person walking past it).
|
||||
std::vector<Eigen::Vector3d> hiddenBox()
|
||||
{
|
||||
return object(1.42, .13, .30);
|
||||
}
|
||||
std::vector<Eigen::Vector3d> screen()
|
||||
{
|
||||
return sheet(1.0, -.02, .22, .16, .36);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraNoGuardTest, HiddenBoxIsClearedWithoutTheGuard)
|
||||
{
|
||||
frame(hiddenBox());
|
||||
ASSERT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
frame(screen()); // no cloud point near the box: the kd-tree test clears it
|
||||
EXPECT_NE(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraGuardTest, HiddenBoxIsKeptWithTheGuard)
|
||||
{
|
||||
frame(hiddenBox());
|
||||
ASSERT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame(screen());
|
||||
EXPECT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
frame(backdrop()); // the screen is gone and the camera sees past the box: now it goes
|
||||
EXPECT_NE(master(1.41, .11), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
// A box in front of the backdrop moves 18 cm to the left. Its old column y = .22 (corner .20)
|
||||
// still has a point of the moved box (y = .28) within check_radius, so only the rays show that
|
||||
// the column is empty. Checked at (1.01, .21): stored corners sit on cell edges, and corner .20
|
||||
// is the only one that lands in that master cell (corner .15 falls back into the .10 cell).
|
||||
std::vector<Eigen::Vector3d> boxBefore()
|
||||
{
|
||||
return object(1.02, .16, .30);
|
||||
}
|
||||
std::vector<Eigen::Vector3d> boxAfter()
|
||||
{
|
||||
return object(1.02, .34, .30);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraNoGuardTest, MovedBoxLeavesAGhostWithoutTheGuard)
|
||||
{
|
||||
frame(join(boxBefore(), backdrop()));
|
||||
ASSERT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
frame(join(boxAfter(), backdrop()));
|
||||
EXPECT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraGuardTest, MovedBoxLeavesNoGhostWithTheGuard)
|
||||
{
|
||||
frame(join(boxBefore(), backdrop()));
|
||||
ASSERT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
frame(join(boxAfter(), backdrop()));
|
||||
EXPECT_NE(master(1.01, .21), LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master(1.01, .26), LETHAL_OBSTACLE); // the moved box itself (its y = .28 column)
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraGuardTest, SolidBoxSeenAgainIsKept)
|
||||
{
|
||||
// A real surface returns on every ray at its own range: no evidence, the kd-tree test keeps it.
|
||||
const std::vector<Eigen::Vector3d> box = sheet(1.02, .05, .20, .22, .38);
|
||||
frame(join(box, backdrop()));
|
||||
ASSERT_EQ(master(), LETHAL_OBSTACLE);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
frame(join(box, backdrop()));
|
||||
EXPECT_EQ(master(), LETHAL_OBSTACLE);
|
||||
}
|
||||
|
||||
TEST_F(DepthCameraLayerTest, WaitsForTheMeasurementTfThenDropsAfterTheTolerance)
|
||||
{
|
||||
frame(object(), 0, false); // no TF at this stamp yet
|
||||
@@ -657,11 +459,12 @@ TEST(DepthCameraLayerConfig, RejectsUnportedModeAndOutOfRangeValues)
|
||||
cfg = baseConfig();
|
||||
cfg["voxel_resolution"] = 0.0;
|
||||
expectThrow(cfg);
|
||||
// A value of the wrong type stops the layer instead of becoming 0.
|
||||
cfg = baseConfig();
|
||||
cfg["depth_cam"]["attach_distance"] = -.01;
|
||||
cfg["number_clearing_threshold"] = "many";
|
||||
expectThrow(cfg);
|
||||
cfg = baseConfig();
|
||||
cfg["depth_cam"]["attach_distance"] = 1.2; // near and far bands would meet: (2.5 - .15) / 2
|
||||
cfg["depth_cam"]["FOV_W"] = "wide";
|
||||
expectThrow(cfg);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,280 +0,0 @@
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
namespace
|
||||
{
|
||||
DirectionGeometry geometry()
|
||||
{
|
||||
return {4, 4, 1.0, 0.0, 0.0, "map"};
|
||||
}
|
||||
|
||||
robot_nav_msgs::OccupancyGrid grid()
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid g;
|
||||
g.header.frame_id = "/map";
|
||||
g.info.width = 4;
|
||||
g.info.height = 4;
|
||||
g.info.resolution = 1;
|
||||
g.data.assign(16, 0);
|
||||
return g;
|
||||
}
|
||||
|
||||
auto field(const robot_nav_msgs::OccupancyGrid& g)
|
||||
{
|
||||
return DirectionField::create(g, geometry(), M_PI / 2.0);
|
||||
}
|
||||
|
||||
using Cell = std::pair<int64_t, int64_t>;
|
||||
std::vector<Cell> cells(double x0, double y0, double x1, double y1)
|
||||
{
|
||||
std::vector<Cell> out;
|
||||
EXPECT_TRUE(traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y)
|
||||
{
|
||||
out.emplace_back(x, y);
|
||||
return true;
|
||||
}));
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(DirectionContract, CodesAndSizes)
|
||||
{
|
||||
auto g = grid();
|
||||
ASSERT_TRUE(field(g));
|
||||
EXPECT_FALSE(field(g)->hasConstraints());
|
||||
for (int code = 0; code <= 8; ++code)
|
||||
{
|
||||
g.data[0] = code;
|
||||
auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
EXPECT_EQ(f->code(0, 0), code);
|
||||
}
|
||||
for (int code : {-128, -2, -1, 9, 100, 127})
|
||||
{
|
||||
g.data[0] = code;
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kCode);
|
||||
}
|
||||
g.data.clear();
|
||||
auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
EXPECT_FALSE(f->hasConstraints());
|
||||
EXPECT_EQ(f->code(3, 3), 0);
|
||||
g.data.assign(15, 0);
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kSize);
|
||||
g.info.width = UINT32_MAX;
|
||||
g.info.height = UINT32_MAX;
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kOverflow);
|
||||
}
|
||||
|
||||
TEST(DirectionContract, CheckedCellAccess)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data[15] = 8;
|
||||
const auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
uint8_t code = 99;
|
||||
EXPECT_TRUE(f->codeAt(3, 3, &code));
|
||||
EXPECT_EQ(code, 8);
|
||||
EXPECT_TRUE(f->codeAt(0, 0, &code));
|
||||
EXPECT_EQ(code, 0);
|
||||
code = 99;
|
||||
EXPECT_FALSE(f->codeAt(-1, 0, &code));
|
||||
EXPECT_FALSE(f->codeAt(0, -1, &code));
|
||||
EXPECT_FALSE(f->codeAt(4, 0, &code));
|
||||
EXPECT_FALSE(f->codeAt(0, 4, &code));
|
||||
EXPECT_FALSE(f->codeAt(INT64_MAX, INT64_MAX, &code));
|
||||
EXPECT_FALSE(f->codeAt(0, 0, nullptr));
|
||||
EXPECT_EQ(code, 99);
|
||||
g.data.clear();
|
||||
const auto empty = field(g);
|
||||
ASSERT_TRUE(empty);
|
||||
EXPECT_TRUE(empty->codeAt(3, 3, &code));
|
||||
EXPECT_EQ(code, 0);
|
||||
code = 99;
|
||||
EXPECT_FALSE(empty->codeAt(4, 3, &code));
|
||||
EXPECT_EQ(code, 99);
|
||||
}
|
||||
|
||||
TEST(DirectionContract, GeometryAndNonFinite)
|
||||
{
|
||||
auto g = grid();
|
||||
EXPECT_TRUE(field(g));
|
||||
g.header.frame_id = "";
|
||||
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kFrame);
|
||||
g.header.frame_id = "other";
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.width = 3;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.resolution = 0.5;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.position.x = 0.01;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.position.y = 0.01;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.orientation.z = 0.1;
|
||||
g.info.origin.orientation.w = 1;
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.orientation.w = 1;
|
||||
EXPECT_TRUE(field(g));
|
||||
g.info.origin.orientation.w = -1;
|
||||
EXPECT_TRUE(field(g));
|
||||
g = grid();
|
||||
EXPECT_TRUE(field(g)); // Default zero quaternion.
|
||||
g.info.origin.position.x = std::numeric_limits<double>::quiet_NaN();
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.resolution = std::numeric_limits<float>::infinity();
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.position.z = std::numeric_limits<double>::infinity();
|
||||
EXPECT_FALSE(field(g));
|
||||
g = grid();
|
||||
g.info.origin.orientation.w = std::numeric_limits<double>::quiet_NaN();
|
||||
EXPECT_FALSE(field(g));
|
||||
}
|
||||
|
||||
TEST(DirectionRule, AllDirectionsAndBoundaries)
|
||||
{
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data.assign(16, k + 1);
|
||||
auto f = field(g);
|
||||
ASSERT_TRUE(f);
|
||||
const double x = 1.5;
|
||||
const double y = 1.5;
|
||||
EXPECT_EQ(f->checkSegment(x, y, x + 0.2 * vx[k], y + 0.2 * vy[k]), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x - 0.2 * vx[k], y - 0.2 * vy[k]), SegmentResult::kViolation);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x - 0.2 * vy[k], y + 0.2 * vx[k]), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x + 0.2 * vy[k], y - 0.2 * vx[k]), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(x, y, x, y), SegmentResult::kAllowed);
|
||||
}
|
||||
auto g = grid();
|
||||
g.data.assign(16, 1);
|
||||
auto f = field(g);
|
||||
EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 - 1e-6, 1.7), SegmentResult::kViolation);
|
||||
EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 + 1e-6, 1.7), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(allowedDirectionMask(-1e-11, 1.0, M_PI / 2.0) & 1, 1);
|
||||
EXPECT_EQ(allowedDirectionMask(-1e-6, 1.0, M_PI / 2.0) & 1, 0);
|
||||
}
|
||||
|
||||
TEST(DirectionRule, MaskMatchesDotProducts)
|
||||
{
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
for (int x = -12; x <= 12; ++x)
|
||||
{
|
||||
for (int y = -12; y <= 12; ++y)
|
||||
{
|
||||
auto mask = allowedDirectionMask(x, y, M_PI / 2.0);
|
||||
for (int k = 0; k < 8; ++k)
|
||||
EXPECT_EQ(bool(mask & (1u << k)), vx[k] * x + vy[k] * y >= 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(DirectionRule, RightAngleMatchesLegacySweep)
|
||||
{
|
||||
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
|
||||
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
|
||||
const auto check = [&](double dx, double dy)
|
||||
{
|
||||
uint8_t reference = 0;
|
||||
const long double x = dx, y = dy;
|
||||
const long double tolerance = 1e-9L * (std::abs(x) + std::abs(y));
|
||||
for (int k = 0; k < 8; ++k)
|
||||
if (vx[k] * x + vy[k] * y >= -tolerance)
|
||||
reference |= uint8_t(1u << k);
|
||||
EXPECT_EQ(allowedDirectionMask(dx, dy, M_PI / 2.0), reference) << dx << "," << dy;
|
||||
};
|
||||
for (double magnitude : {1e-100, 0.01, 1.0, 1e100})
|
||||
{
|
||||
for (int degree = 0; degree < 360; ++degree)
|
||||
check(magnitude * std::cos(degree * M_PI / 180.0), magnitude * std::sin(degree * M_PI / 180.0));
|
||||
for (int k = 0; k < 8; ++k)
|
||||
check(magnitude * vx[k], magnitude * vy[k]);
|
||||
check(-1.0000000005e-9 * magnitude, magnitude); // Near the legacy tolerance boundary.
|
||||
}
|
||||
check(0, 0);
|
||||
EXPECT_EQ(allowedDirectionMask(std::numeric_limits<double>::infinity(), 0, M_PI / 2.0), 0);
|
||||
EXPECT_EQ(allowedDirectionMask(0, std::numeric_limits<double>::quiet_NaN(), M_PI / 2.0), 0);
|
||||
}
|
||||
|
||||
TEST(DirectionRule, ConfigurableAngularBoundaries)
|
||||
{
|
||||
const auto mask = allowedDirectionMask(1, 0.5, M_PI / 4.0);
|
||||
EXPECT_NE(mask & (1u << 0), 0);
|
||||
EXPECT_NE(mask & (1u << 1), 0);
|
||||
EXPECT_EQ(mask & (1u << 2), 0);
|
||||
const auto boundary = allowedDirectionMask(1, 1, M_PI / 4.0);
|
||||
EXPECT_NE(boundary & (1u << 0), 0);
|
||||
EXPECT_NE(boundary & (1u << 2), 0);
|
||||
EXPECT_EQ(allowedDirectionMask(1, 1.01, M_PI / 4.0) & 1u, 0);
|
||||
EXPECT_EQ(allowedDirectionMask(0, 1, M_PI / 6.0) & 1u, 0);
|
||||
EXPECT_EQ(allowedDirectionMask(0, 0, M_PI / 6.0), 255);
|
||||
}
|
||||
|
||||
TEST(DirectionRule, FieldUsesItsDeviationForCrossing)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data.assign(16, 3); // +Y zone, crossed along +X.
|
||||
const auto wide = DirectionField::create(g, geometry(), M_PI / 2.0);
|
||||
const auto narrow = DirectionField::create(g, geometry(), M_PI / 4.0);
|
||||
ASSERT_TRUE(wide && narrow);
|
||||
EXPECT_DOUBLE_EQ(narrow->maxDeviationRad(), M_PI / 4.0);
|
||||
EXPECT_EQ(wide->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(narrow->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kViolation);
|
||||
}
|
||||
|
||||
TEST(DirectionDDA, OwnedEdgesCornersEndpointsAndReverse)
|
||||
{
|
||||
EXPECT_EQ(cells(1, 0.2, 1, 2.8), (std::vector<Cell>{{1, 0}, {1, 1}, {1, 2}}));
|
||||
EXPECT_EQ(cells(1, 2.8, 1, 0.2), (std::vector<Cell>{{1, 2}, {1, 1}, {1, 0}}));
|
||||
EXPECT_EQ(cells(0.5, 0.5, 2.5, 2.5), (std::vector<Cell>{{0, 0}, {1, 1}, {2, 2}}));
|
||||
EXPECT_EQ(cells(0, 0, 6, 4),
|
||||
(std::vector<Cell>{{0, 0}, {1, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 2}, {4, 3}, {5, 3}}));
|
||||
EXPECT_EQ(cells(0.5, 0.5, 2.0, 0.5), (std::vector<Cell>{{0, 0}, {1, 0}}));
|
||||
EXPECT_EQ(cells(2.0, 0.5, 0.5, 0.5), (std::vector<Cell>{{1, 0}, {0, 0}}));
|
||||
for (auto p : std::vector<std::vector<double>>{{0.2, 0.3, 3.8, 2.7}, {1, 0.2, 1, 3.5}, {0.5, 0.5, 3.5, 3.5}})
|
||||
{
|
||||
auto a = cells(p[0], p[1], p[2], p[3]);
|
||||
auto b = cells(p[2], p[3], p[0], p[1]);
|
||||
std::reverse(b.begin(), b.end());
|
||||
EXPECT_EQ(a, b);
|
||||
EXPECT_EQ(std::set<Cell>(a.begin(), a.end()).size(), a.size());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(DirectionDDA, QueriesCrossZonesAndRejectOutside)
|
||||
{
|
||||
auto g = grid();
|
||||
g.data[1] = 5;
|
||||
g.data[2] = 5;
|
||||
auto f = field(g);
|
||||
SegmentViolation v{};
|
||||
EXPECT_EQ(f->checkSegment(0.2, 0.5, 3.5, 0.5, &v), SegmentResult::kViolation);
|
||||
EXPECT_EQ(v.x, 1u);
|
||||
EXPECT_EQ(v.code, 5);
|
||||
EXPECT_EQ(f->checkSegment(3.5, 0.5, 0.2, 0.5), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(0.2, 0.5, 1.0, 0.5), SegmentResult::kAllowed);
|
||||
EXPECT_EQ(f->checkSegment(0.2, 0.5, 4.0, 0.5), SegmentResult::kOutOfGrid);
|
||||
EXPECT_EQ(f->checkSegment(-0.1, 0.5, 0.1, 0.5), SegmentResult::kOutOfGrid);
|
||||
EXPECT_EQ(f->checkSegment(4, 0.5, 4, 0.5), SegmentResult::kOutOfGrid);
|
||||
}
|
||||
@@ -1,367 +0,0 @@
|
||||
#include <robot_costmap_2d/directional_layer.h>
|
||||
#include <robot_costmap_2d/critical_layer.h>
|
||||
#include <robot_costmap_2d/static_layer.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
#include <boost/make_shared.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
#include <gtest/gtest.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
using namespace robot_costmap_2d;
|
||||
namespace
|
||||
{
|
||||
class LayerTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
std::string directory_;
|
||||
std::string old_env_;
|
||||
bool had_env_ = false;
|
||||
tf3::BufferCore tf_{tf3::Duration(10.0)};
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
const char* old = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
if (old)
|
||||
{
|
||||
had_env_ = true;
|
||||
old_env_ = old;
|
||||
}
|
||||
char pattern[] = "/tmp/direction-layer-test-XXXXXX";
|
||||
char* path = mkdtemp(pattern);
|
||||
ASSERT_NE(path, nullptr);
|
||||
directory_ = path;
|
||||
std::filesystem::create_directory(directory_ + "/config");
|
||||
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", directory_.c_str(), 1), 0);
|
||||
config(true);
|
||||
std::ofstream static_config(directory_ + "/config/static_layer_params.yaml");
|
||||
static_config << "static_layer:\n enabled: true\n map_topic: map\n"
|
||||
" first_map_only: false\n subscribe_to_updates: true\n";
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
if (had_env_)
|
||||
setenv("PNKX_NAV_CORE_CONFIG_DIR", old_env_.c_str(), 1);
|
||||
else
|
||||
unsetenv("PNKX_NAV_CORE_CONFIG_DIR");
|
||||
std::filesystem::remove_all(directory_);
|
||||
}
|
||||
|
||||
void config(bool enabled, double max_deviation_deg = 90.0)
|
||||
{
|
||||
std::ofstream out(directory_ + "/config/directional_layer_params.yaml");
|
||||
out << "directional_layer:\n enabled: " << (enabled ? "true" : "false")
|
||||
<< "\n map_topic: map\n direction_topic: direction_map\n max_deviation_deg: " << max_deviation_deg
|
||||
<< "\n debug_state: false\n";
|
||||
}
|
||||
|
||||
robot_nav_msgs::OccupancyGrid grid()
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid g;
|
||||
g.header.frame_id = "map";
|
||||
g.info.width = 4;
|
||||
g.info.height = 4;
|
||||
g.info.resolution = 1;
|
||||
g.data.assign(16, 0);
|
||||
return g;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LayerTest, StaticAndCriticalReadinessTracksWrites)
|
||||
{
|
||||
for (bool critical : {false, true})
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
boost::shared_ptr<Layer> layer = critical
|
||||
? boost::static_pointer_cast<Layer>(boost::make_shared<CriticalLayer>())
|
||||
: boost::static_pointer_cast<Layer>(boost::make_shared<StaticLayer>());
|
||||
layer->initialize(&master, critical ? "critical" : "static", &tf_);
|
||||
master.addPlugin(layer);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
EXPECT_FALSE(master.isCurrent());
|
||||
|
||||
robot_map_msgs::OccupancyGridUpdate early_update;
|
||||
early_update.x = early_update.y = 0;
|
||||
early_update.width = early_update.height = 1;
|
||||
early_update.data.assign(1, 100);
|
||||
layer->dataCallBack(early_update, "map_updates");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
|
||||
auto map = grid();
|
||||
map.data[0] = 100;
|
||||
layer->dataCallBack(map, "map");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->updateCosts(*master.getCostmap(), 0, 0, 0, 0);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
|
||||
layer->reset();
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_TRUE(master.isCurrent());
|
||||
EXPECT_NE(master.getCostmap()->getCost(0, 0), FREE_SPACE);
|
||||
|
||||
map.data[1] = 100;
|
||||
map.data[15] = 100;
|
||||
layer->dataCallBack(map, "map");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
|
||||
robot_map_msgs::OccupancyGridUpdate update;
|
||||
update.x = 0;
|
||||
update.y = 0;
|
||||
update.width = 1;
|
||||
update.height = 1;
|
||||
update.data.assign(1, 100);
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_EQ(master.getCostmap()->getCost(3, 3), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
|
||||
|
||||
update.x = 0;
|
||||
update.y = 3;
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
update.x = 3;
|
||||
update.y = 0;
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_EQ(master.getCostmap()->getCost(0, 3), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
|
||||
EXPECT_EQ(master.getCostmap()->getCost(3, 0), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
|
||||
|
||||
update.x = -1;
|
||||
layer->dataCallBack(update, "map_updates");
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->dataCallBack(map, "map");
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
master.updateMap(0, 0, 0);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, InvalidMaxDeviationThrows)
|
||||
{
|
||||
for (double degrees : {0.0, 180.0, -5.0, 200.0})
|
||||
{
|
||||
config(true, degrees);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
EXPECT_THROW(layer.initialize(&master, "directional", &tf_), std::runtime_error) << degrees;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, ReadyFieldCarriesConfiguredDeviation)
|
||||
{
|
||||
config(true, 45.0);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
ASSERT_NO_THROW(layer.initialize(&master, "directional", &tf_));
|
||||
auto g = grid();
|
||||
layer.dataCallBack(g, "map");
|
||||
layer.dataCallBack(g, "direction_map");
|
||||
const auto snapshot = layer.directionSnapshot();
|
||||
ASSERT_EQ(snapshot.state, DirectionFieldState::kReady);
|
||||
ASSERT_TRUE(snapshot.field);
|
||||
EXPECT_DOUBLE_EQ(snapshot.field->maxDeviationRad(), M_PI / 4.0);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, LifecycleAndProvider)
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kDisabled);
|
||||
auto layer = boost::make_shared<DirectionalLayer>();
|
||||
layer->initialize(&master, "directional", &tf_);
|
||||
master.addPlugin(layer);
|
||||
auto g = grid();
|
||||
auto s = master.getDirectionFieldSnapshot();
|
||||
EXPECT_EQ(s.state, DirectionFieldState::kPending);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
EXPECT_EQ(layer->directionSnapshot().generation, s.generation);
|
||||
double min_x = 1;
|
||||
double min_y = 2;
|
||||
double max_x = 3;
|
||||
double max_y = 4;
|
||||
layer->updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y);
|
||||
EXPECT_DOUBLE_EQ(min_x, 1);
|
||||
EXPECT_DOUBLE_EQ(min_y, 2);
|
||||
EXPECT_DOUBLE_EQ(max_x, 3);
|
||||
EXPECT_DOUBLE_EQ(max_y, 4);
|
||||
auto& costs = *master.getCostmap();
|
||||
costs.setCost(0, 0, 42);
|
||||
layer->updateCosts(costs, 0, 0, 4, 4);
|
||||
EXPECT_EQ(costs.getCost(0, 0), 42);
|
||||
layer->dataCallBack(7, "map");
|
||||
layer->dataCallBack(g, "other_topic");
|
||||
EXPECT_EQ(layer->directionSnapshot().generation, s.generation);
|
||||
layer->dataCallBack(g, "/map");
|
||||
s = layer->directionSnapshot();
|
||||
EXPECT_EQ(s.state, DirectionFieldState::kPending);
|
||||
g.data[0] = 1;
|
||||
layer->dataCallBack(g, "/direction_map");
|
||||
auto ready = master.getDirectionFieldSnapshot();
|
||||
EXPECT_EQ(ready.state, DirectionFieldState::kReady);
|
||||
ASSERT_TRUE(ready.field);
|
||||
EXPECT_TRUE(layer->isCurrent());
|
||||
EXPECT_GT(ready.generation, s.generation);
|
||||
g.data[0] = 100;
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
s = layer->directionSnapshot();
|
||||
EXPECT_EQ(s.generation, ready.generation);
|
||||
EXPECT_EQ(s.field, ready.field);
|
||||
layer->reset();
|
||||
EXPECT_EQ(layer->directionSnapshot().field, ready.field);
|
||||
g.data.clear();
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
s = layer->directionSnapshot();
|
||||
ASSERT_TRUE(s.field);
|
||||
EXPECT_FALSE(s.field->hasConstraints());
|
||||
EXPECT_GT(s.generation, ready.generation);
|
||||
layer->dataCallBack(g, "map");
|
||||
s = layer->directionSnapshot();
|
||||
EXPECT_EQ(s.state, DirectionFieldState::kPending);
|
||||
EXPECT_FALSE(s.field);
|
||||
EXPECT_FALSE(layer->isCurrent());
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
layer->matchSize();
|
||||
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
master.getCostmap()->resizeMap(3, 3, 1, 0, 0);
|
||||
layer->reset();
|
||||
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
master.resizeMap(3, 3, 1, 0, 0);
|
||||
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, DisabledAndMultipleProviders)
|
||||
{
|
||||
config(false);
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
auto disabled = boost::make_shared<DirectionalLayer>();
|
||||
disabled->initialize(&master, "directional", &tf_);
|
||||
master.addPlugin(disabled);
|
||||
EXPECT_TRUE(disabled->isCurrent());
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kDisabled);
|
||||
config(true);
|
||||
auto a = boost::make_shared<DirectionalLayer>();
|
||||
a->initialize(&master, "first", &tf_);
|
||||
master.addPlugin(a);
|
||||
auto b = boost::make_shared<DirectionalLayer>();
|
||||
b->initialize(&master, "second", &tf_);
|
||||
master.addPlugin(b);
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, RollingCostmapStaysPending)
|
||||
{
|
||||
LayeredCostmap master("map", true, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
layer.initialize(&master, "directional", &tf_);
|
||||
auto g = grid();
|
||||
layer.dataCallBack(g, "map");
|
||||
layer.dataCallBack(g, "direction_map");
|
||||
EXPECT_EQ(layer.directionSnapshot().state, DirectionFieldState::kPending);
|
||||
EXPECT_FALSE(layer.isCurrent());
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, StaticMapCallbackDoesNotWaitForMasterMutex)
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
DirectionalLayer layer;
|
||||
layer.initialize(&master, "directional", &tf_);
|
||||
auto g = grid();
|
||||
std::mutex completion_mutex;
|
||||
std::condition_variable completion;
|
||||
bool done = false;
|
||||
bool completed_while_locked = false;
|
||||
std::thread callback;
|
||||
{
|
||||
boost::unique_lock<Costmap2D::mutex_t> master_lock(*master.getCostmap()->getMutex());
|
||||
callback = std::thread([&]
|
||||
{
|
||||
layer.dataCallBack(g, "map");
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(completion_mutex);
|
||||
done = true;
|
||||
}
|
||||
completion.notify_one();
|
||||
});
|
||||
std::unique_lock<std::mutex> lock(completion_mutex);
|
||||
completed_while_locked = completion.wait_for(lock, std::chrono::seconds(2), [&] { return done; });
|
||||
}
|
||||
callback.join();
|
||||
EXPECT_TRUE(completed_while_locked);
|
||||
EXPECT_EQ(layer.directionSnapshot().state, DirectionFieldState::kPending);
|
||||
}
|
||||
|
||||
TEST_F(LayerTest, OldSnapshotSurvivesConcurrentReplacement)
|
||||
{
|
||||
LayeredCostmap master("map", false, false);
|
||||
master.resizeMap(4, 4, 1, 0, 0);
|
||||
auto layer = boost::make_shared<DirectionalLayer>();
|
||||
layer->initialize(&master, "directional", &tf_);
|
||||
master.addPlugin(layer);
|
||||
auto g = grid();
|
||||
g.data[0] = 1;
|
||||
layer->dataCallBack(g, "map");
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
auto old = master.getDirectionFieldSnapshot();
|
||||
ASSERT_TRUE(old.field);
|
||||
std::atomic<bool> start{false};
|
||||
std::atomic<bool> ok{true};
|
||||
std::thread reader([&]
|
||||
{
|
||||
while (!start.load())
|
||||
{
|
||||
}
|
||||
for (int i = 0; i < 1000; ++i)
|
||||
{
|
||||
auto s = master.getDirectionFieldSnapshot();
|
||||
if (!s.field || old.field->code(0, 0) != 1)
|
||||
ok = false;
|
||||
}
|
||||
});
|
||||
std::thread updater([&]
|
||||
{
|
||||
while (!start.load())
|
||||
{
|
||||
}
|
||||
for (int i = 0; i < 1000; ++i)
|
||||
layer->updateBounds(0, 0, 0, nullptr, nullptr, nullptr, nullptr);
|
||||
});
|
||||
start = true;
|
||||
g.data[0] = 3;
|
||||
layer->dataCallBack(g, "direction_map");
|
||||
reader.join();
|
||||
updater.join();
|
||||
EXPECT_TRUE(ok.load());
|
||||
EXPECT_EQ(old.field->code(0, 0), 1);
|
||||
EXPECT_EQ(master.getDirectionFieldSnapshot().field->code(0, 0), 3);
|
||||
}
|
||||
} // namespace
|
||||
Reference in New Issue
Block a user