diff --git a/README.md b/README.md index 6de9e76..563d53b 100644 --- a/README.md +++ b/README.md @@ -3,28 +3,36 @@ Global planner sinh đường vào dock, implement `robot_nav_core::BaseGlobalPlanner` và export bằng `BOOST_DLL_ALIAS` với symbol `DockPlanner`. -Planner chỉ sinh **hình học**. Collision / free-space checking chưa được -implement — xem "Phạm vi an toàn hiện tại". +Planner chủ yếu sinh **hình học**. Có thể bật kiểm tra `LETHAL_OBSTACLE` trong +costmap cho các đoạn tiếp cận và điểm xoay của hai kiểu pivot; terminal đi vào +dock không được kiểm tra vì LETHAL gần charger/chân trolley có thể là tiếp xúc +dự kiến. Direct entry và single cusp vẫn chỉ kiểm tra hình học — xem "Phạm vi +an toàn hiện tại". -## Ba kiểu đường +## Các kiểu đường -Planner thử theo thứ tự và lấy kiểu **đầu tiên dựng được**. Kiểu nào không dựng -được thì **rơi xuống kiểu kế tiếp**, không bao giờ trở thành lỗi. Chỉ khi mọi -kiểu đều trượt mới trả `false` kèm một dòng log liệt kê đủ số đo. +Planner thử các kiểu legacy theo ladder hiện có và lấy kiểu **đầu tiên dựng +được**. Kiểu nào không dựng được thì **rơi xuống kiểu kế tiếp**, không bao giờ +trở thành lỗi. Chỉ khi mọi kiểu legacy đều trượt mới thử back-off pivot, nếu +được bật. Chỉ khi cả ladder và back-off đều trượt mới trả `false` kèm một dòng +log liệt kê đủ số đo. ```text 1. direct_entry start ──── cung ────╮ ╰─ thẳng ─► goal -2. single_cusp goal ◄─ thẳng ─ ✖cusp +2. straight_pivot_straight start ── thẳng ─ ⟳B ─ thẳng ─ V ⟳xoay⟳ ─► goal + đoạn thẳng đầu có thể lấn ra sau điểm start + +3. single_cusp goal ◄─ thẳng ─ ✖cusp ╰─ cung ─── start lấn thêm `cusp_extension` mét về phía XA dock -3. straight_pivot_straight goal ◄─ thẳng ─ V ⟳xoay⟳ ─ thẳng ─ start - điểm xoay nằm GIỮA robot và dock: lấn thêm 0 mét +4. backoff_pivot_straight start ── back-off ─ ⟳B ─ thẳng ─ V ⟳xoay⟳ ─► goal + chỉ dùng khi mọi kiểu legacy thất bại; cần differential ``` -Đoạn cuối của cả ba kiểu luôn **thẳng** và trùng hướng yaw của goal: robot phải +Đoạn cuối của cả bốn kiểu luôn **thẳng** và trùng hướng yaw của goal: robot phải đạt đúng hướng trước khi chui vào dock. ### Kiểu nào được chọn @@ -40,10 +48,20 @@ prefer_pivot = pivot_enabled && ( turns_in_place | tình huống | thứ tự thử | |---|---| | `turns_in_place` | direct_entry → **pivot** → cusp | -| ackermann, `cusp_extension` vượt ngưỡng | direct_entry → **pivot** → cusp | -| ackermann, cusp rẻ | direct_entry → **cusp** → pivot | +| `cusp_extension` vượt ngưỡng hoặc cusp không đặt được | direct_entry → **pivot** → cusp | +| cusp rẻ | direct_entry → **cusp** → pivot | | `pivot_fallback_extension = 0`, không turns_in_place | direct_entry → **cusp** | +`backoff_pivot_straight` nằm sau toàn bộ ladder trên. Nó chỉ được thử khi +`model: differential`, pivot đang bật theo quy tắc hiện có, và +`pivot_backoff_max_distance > 0`. Đường này không dùng `minimum_turning_radius` +hay `max_steering_angle`: nó giữ nguyên yaw thân xe khi back-off, dừng ở +`pivot_vertex_distance + path_point_spacing`, rồi dùng đoạn pivot và terminal +hiện có. Nếu hướng thân xe cách vuông góc với trục tiếp cận dưới 15° (chiếu dọc +trục nhỏ hơn 0.26 m trên mỗi mét) hoặc quãng back-off vượt giới hạn, kiểu này +bị loại. Một rotation block tại B để local planner đổi sang hướng của đoạn pivot +khi cần; rotation block tại vertex vẫn theo cách cũ. + `cusp_extension = cusp_distance − start_longitudinal`, tức cusp bắt robot chạy ra xa dock thêm bao nhiêu **so với chỗ nó đang đứng**. Đại lượng này cố ý là **tương đối**: một số tuyệt đối kiểu "chiều sâu lối đi" sẽ tính cả chỗ robot đang đứng @@ -66,6 +84,9 @@ chỗ còn lại cho cung vượt ngưỡng đó. `R_min == 0` là **giá trị hợp lệ**, không phải lỗi: đó là thứ cho phép planner đặt một cú xoay tại chỗ vào path. Chỉ số âm hoặc không hữu hạn mới là lỗi. +Back-off pivot chỉ dành cho `model: differential`. Ackermann giữ nguyên ladder +và không thử kiểu này, kể cả khi `pivot_backoff_max_distance` lớn hơn 0. + Khai nhầm `ackermann` cho robot vi sai thì plugin **không nạp được** — nó đi tra frame `steer_link` mà robot vi sai không có. @@ -134,10 +155,12 @@ File mặc định đi kèm gói: `config/dock_global_params.yaml`. Cây đang c | `kinematics/max_steering_angle` | `0.50` | rad | ackermann | Góc lái bicycle lớn nhất | | `kinematics/minimum_turning_radius` | `0.0` | m | differential | 0 = xoay tại chỗ được | | `maneuver/minimum_forward_distance` | `0.25` | m | cả hai | Đoạn dẫn tối thiểu trước cusp | -| `maneuver/maximum_forward_extension` | `3.0` | m | cả hai | Trần `cusp_extension`; vượt thì LOẠI kiểu 2 | +| `maneuver/maximum_forward_extension` | `3.0` | m | cả hai | Trần `cusp_extension`; vượt thì LOẠI kiểu 3 | | `maneuver/direct_entry_min_curve_room` | `0.0` | m | cả hai | 0 = tắt kiểu 1 | -| `maneuver/pivot_fallback_extension` | `0.0` | m | cả hai | 0 = tắt kiểu 3 (bỏ qua khi `turns_in_place`) | +| `maneuver/pivot_fallback_extension` | `0.0` | m | cả hai | 0 = tắt kiểu 2 (bỏ qua khi `turns_in_place`) | | `maneuver/pivot_safety_margin` | `0.15` | m | cả hai | Khe hở vòng quét khi xoay ↔ mặt dock | +| `maneuver/pivot_backoff_max_distance` | `0.0` | m | differential | 0 = tắt back-off pivot; tối đa 3 m | +| `maneuver/pivot_check_costmap` | `false` | bool | cả hai pivot | Kiểm tra lethal trên các đoạn thẳng và vùng xoay | | `terminal/reverse_distance_padding` | `0.0` | m | cả hai | Khoảng hở cộng thêm cho đoạn cuối | | `terminal/straight_length` | `0.0` | m | cả hai | Độ dài đoạn thẳng cuối mong muốn | | `sampling/path_point_spacing` | `0.05` | m | cả hai | Khoảng cách lấy mẫu | @@ -156,7 +179,8 @@ từng marker rồi rót vào namespace `DockPlanner` trước khi dựng plugin - `differential`: `minimum_turning_radius >= 0`. - Chung: `0 < minimum_forward_distance <= maximum_forward_extension`, `direct_entry_min_curve_room >= 0`, `pivot_fallback_extension >= 0`, - `pivot_safety_margin >= 0`, `reverse_distance_padding >= 0`, + `pivot_safety_margin >= 0`, `0 <= pivot_backoff_max_distance <= 3 m`, + `reverse_distance_padding >= 0`, `straight_length >= 0`, `0 < path_point_spacing <= 1.0`. `max_steering_angle` phải là góc lái tương đương theo bicycle model, không phải @@ -185,15 +209,30 @@ chênh nhau hơn một mét ở đầu xe là chuyện có thật, và chênh đ ## Phạm vi an toàn hiện tại +`pivot_check_costmap` mặc định `false`. Khi bật, cả `straight_pivot_straight` +và `backoff_pivot_straight` kiểm tra: + +- Vùng tròn bán kính `circumscribed_radius + pivot_safety_margin` tại mỗi điểm + xoay; mọi cell LETHAL giao với vùng tròn hoặc phần vùng quét ngoài bản đồ sẽ + loại kiểu pivot. +- Footprint đã rasterize tại mọi sample của các đoạn tiếp cận: back-off và đoạn + thẳng từ B tới đỉnh pivot (hoặc đoạn thẳng tiếp cận của pivot cũ); cell LETHAL + hoặc footprint đi ra ngoài bản đồ sẽ loại kiểu pivot. Bỏ qua sample bắt đầu. +- Không kiểm tra đoạn terminal từ đỉnh pivot vào dock. Charger có thể là LETHAL + gần điểm dừng, còn trolley có chân LETHAL sát footprint khi robot đi giữa hai + chân; va chạm trên terminal tiếp tục thuộc trách nhiệm local planner. +- `NO_INFORMATION` được xem là trống. Các cost khác LETHAL cũng không bị coi là + va chạm bởi kiểm tra này. + `check_free_space`, `cost_threshold`, `allow_unknown` và `calib_safety_distance` -**không được đọc**. Path hợp lệ về hình học **không** đồng nghĩa với không va -chạm: +**không được đọc**. Kiểm tra pivot không làm các path hình học khác thành path +đã kiểm tra va chạm: - `pivot_safety_margin` chỉ chặn phía **gần dock** — bảo đảm vòng quét khi xoay không chạm mặt dock. Nó không biết gì về tường, kệ hay người bên cạnh. -- Không có ràng buộc nào về phía **xa dock**. Kiểu 3 không lấn thêm chỗ theo - thiết kế, nhưng kiểu 1 và 2 thì có, và không ai kiểm. -- Cung của kiểu 1 và 2 quét một vùng rộng ở hai bên hông robot. +- Kiểu 1 và 3 không được kiểm tra costmap. Kiểu back-off có giới hạn chiều dài, + nhưng vẫn cần đủ không gian trống phía sau robot. +- Cung của kiểu 1 và 3 quét một vùng rộng ở hai bên hông robot. Đừng thêm khoá cấu hình cho những tính năng an toàn chưa hiện thực — YAML khai một khoá không ai đọc thì nguy hiểm hơn là không khai. diff --git a/config/dock_global_params.yaml b/config/dock_global_params.yaml index e1d5e2d..9891dfb 100644 --- a/config/dock_global_params.yaml +++ b/config/dock_global_params.yaml @@ -6,19 +6,22 @@ # Cây config đang chạy nằm ở move_base2/config/runtime/ và pnkx_nav_core/config/. # Sửa tham số ở hai cây đó thì phải đồng bộ khoá (và tài liệu) về đây. # -# Ba kiểu đường. Planner thử theo thứ tự và lấy kiểu ĐẦU TIÊN dựng được; kiểu nào +# Bốn kiểu đường. Planner thử theo ladder cấu hình và lấy kiểu ĐẦU TIÊN dựng được; kiểu nào # không dựng được thì rơi xuống kiểu kế tiếp, KHÔNG bao giờ biến thành lỗi: # 1. direct_entry — một cung hội tụ vào trục goal rồi đi thẳng vào. Một chiều # chạy, không dừng, không xoay. Rẻ nhất khi chạy. -# 2. single_cusp — cua rời XA dock tới điểm đổi chiều (cusp) rồi lùi thẳng vào. -# Lấn thêm chỗ về phía xa dock đúng bằng quãng phải đi ra. -# 3. straight_pivot_straight — một đoạn thẳng, một cú XOAY TẠI CHỖ ghi tường +# 2. straight_pivot_straight — một đoạn thẳng, một cú XOAY TẠI CHỖ ghi tường # minh vào path (một khối pose cùng vị trí, yaw tăng dần), rồi một đoạn # thẳng vào goal. Điểm xoay nằm GIỮA robot và dock nên KHÔNG lấn thêm một # mét nào, đổi lại có thêm một lần dừng để xoay. +# 3. single_cusp — cua rời XA dock tới điểm đổi chiều (cusp) rồi lùi thẳng vào. +# Lấn thêm chỗ về phía xa dock đúng bằng quãng phải đi ra. +# 4. backoff_pivot_straight — chỉ cho differential, lùi/tiến thẳng theo hướng +# thân xe hiện tại tới khi đủ chỗ xoay, rồi dùng hình học pivot ở trên. +# Chỉ thử sau khi mọi kiểu cũ đều thất bại; mặc định bị tắt. # Thứ tự ưu tiên giữa 2 và 3 do `kinematics/model` và `maneuver/*` quyết định — # xem comment của từng khoá. -# Đoạn cuối của cả ba kiểu luôn THẲNG và trùng hướng yaw của goal: robot phải đạt +# Đoạn cuối của cả bốn kiểu luôn THẲNG và trùng hướng yaw của goal: robot phải đạt # đúng hướng trước khi chui vào dock — đi cong vào gầm trolley rất dễ va. # # Mép nào của robot áp vào dock được SUY RA theo từng lần lập plan, dựa vào phía @@ -30,9 +33,8 @@ # Suy được như vậy vì goal đã được offset sẵn từ tầng trên, sao cho base_link # dừng đúng tại goal khi manơ hoàn tất. # -# Kiểm tra va chạm / vùng trống CỐ Ý chưa cấu hình ở đây: DockPlanner hiện chỉ -# sinh hình học. Đừng thêm cost_threshold, allow_unknown hay check_free_space -# cho tới khi phần kiểm va chạm được hiện thực. +# Kiểm tra costmap chỉ áp dụng cho các kiểu pivot khi bật `pivot_check_costmap`; +# các kiểu direct_entry và single_cusp vẫn chỉ kiểm tra hình học. DockPlanner: # Thư viện Boost.DLL chứa symbol export tên "DockPlanner". library_path: libdock_planner @@ -79,11 +81,11 @@ DockPlanner: # [m] Bán kính cua nhỏ nhất, khai trực tiếp vì robot vi sai không có góc lái. # 0 — CHO PHÉP xoay tại chỗ. Đây là giá trị bình thường của robot vi sai, - # và nó bật kiểu đường 3 (thẳng + xoay + thẳng) làm kiểu CHÍNH: kiểu + # và nó bật kiểu đường 2 (thẳng + xoay + thẳng) làm kiểu CHÍNH: kiểu # này không lấn thêm một mét nào về phía xa dock. # > 0 — CẤM xoay tại chỗ (ví dụ đang chở tải cao, xoay tại chỗ dễ đổ). # Planner quay về dùng cung y như ackermann, bán kính tối thiểu đúng - # bằng số này, và kiểu 3 chỉ còn bật qua pivot_fallback_extension. + # bằng số này, và kiểu 2 chỉ còn bật qua pivot_fallback_extension. minimum_turning_radius: 0.0 maneuver: @@ -92,11 +94,11 @@ DockPlanner: # trùng ngay vị trí robot. minimum_forward_distance: 0.25 - # [m] Cusp phải nằm xa hơn khoảng này so với điểm xuất phát thì kiểu 2 bị + # [m] Cusp phải nằm xa hơn khoảng này so với điểm xuất phát thì kiểu 3 bị # LOẠI (không phải fail): planner chuyển sang kiểu khác, chỉ khi không kiểu # nào dựng được mới trả lỗi. # Tăng lên nếu robot đứng lệch nhiều mà vẫn muốn giữ đường có cusp; giảm - # xuống để đẩy sớm sang kiểu 3. + # xuống để đẩy sớm sang kiểu 2. maximum_forward_extension: 3.0 # [m] Bật kiểu 1 (direct_entry — một cung hội tụ vào trục goal rồi đi thẳng @@ -107,21 +109,21 @@ DockPlanner: # 0 = tắt hẳn kiểu 1. direct_entry_min_curve_room: 0.0 - # [m] Chuyển từ kiểu 2 (cusp) sang kiểu 3 (thẳng + xoay + thẳng) khi cusp bắt + # [m] Chuyển từ kiểu 3 (cusp) sang kiểu 2 (thẳng + xoay + thẳng) khi cusp bắt # robot chạy RA XA dock thêm quá số này, đo từ chỗ robot ĐANG ĐỨNG. # So sánh cố ý là TƯƠNG ĐỐI. Lấy một con số tuyệt đối kiểu "chiều sâu lối đi" # rồi so với vị trí robot là tính cả chỗ robot đang đứng vào phần "cần thêm", # và mọi manơ xuất phát từ khoảng cách bình thường đều bị loại sạch. - # 0 — TẮT hẳn kiểu 3 (hành vi cũ, luôn lập đường có cusp). + # 0 — TẮT hẳn chuyển sang kiểu 2 (hành vi cũ, ưu tiên đường cusp). # nhỏ hơn — chuyển sang xoay tại chỗ sớm hơn: tiết kiệm lối đi, thêm 1 lần dừng. # lớn hơn — ưu tiên cusp: chạy mượt hơn, chiếm nhiều lối đi hơn. # ⚠ Chỉ khai > 0 khi CHẮC robot xoay tại chỗ được quanh base_link. # KHÔNG có tác dụng khi model=differential VÀ minimum_turning_radius=0 — lúc - # đó kiểu 3 đã là kiểu chính rồi, không cần ngưỡng nào bật nó. + # đó kiểu 2 đã là kiểu chính rồi, không cần ngưỡng nào bật nó. pivot_fallback_extension: 0.0 # [m] Khoảng hở giữa vòng tròn thân robot quét khi xoay tại chỗ và mặt gần - # của dock. Áp dụng cho CẢ HAI model, mỗi khi kiểu 3 được dùng. + # của dock. Áp dụng cho CẢ HAI model, mỗi khi kiểu 2 được dùng. # Xoay tại chỗ quay MỌI điểm footprint quanh base_link, nên kích thước phải # tính là BÁN KÍNH NGOẠI TIẾP, luôn lớn hơn phần nhô mép dùng cho đoạn thẳng # cuối. Ví dụ footprint 1.65/0.35 x ±0.40: ngoại tiếp 1.698 m trong khi mép @@ -129,9 +131,20 @@ DockPlanner: # Điểm xoay đặt tại: max(độ dài đoạn thẳng cuối, ngoại tiếp + nửa thân dock # phía tiếp cận + số này). # Tăng lên: điểm xoay lùi ra xa dock hơn, an toàn hơn. Tăng quá thì điểm xoay - # vượt qua chỗ robot đứng, kiểu 3 bị loại và planner quay về cusp. + # vượt qua chỗ robot đứng, kiểu 2 bị loại và planner quay về cusp. pivot_safety_margin: 0.15 + # [m] Quãng back-off tối đa cho kiểu backoff_pivot_straight cuối cùng, chỉ dùng khi model=differential. + # Tăng lên cho phép cứu robot đang đứng gần điểm xoay; giảm xuống hoặc 0 sẽ làm ít trường hợp được cứu hơn. + # ⚠ Đặt quá lớn có thể lấn vào lối đi phía sau robot. + pivot_backoff_max_distance: 0.0 + + # Bật kiểm tra LETHAL trên các đoạn tiếp cận (back-off, tới đỉnh pivot) và vòng quét tại điểm xoay. + # Không kiểm tra terminal vào dock: cell LETHAL gần charger/chân trolley có thể là tiếp xúc dự kiến. + # NO_INFORMATION được xem là trống; LETHAL và ngoài bản đồ chặn các phần được kiểm tra. + # false bỏ qua vật cản costmap, có thể sinh đường đâm vào chướng ngại vật. + pivot_check_costmap: false + terminal: # [m] Khoảng hở CỘNG THÊM cho đoạn thẳng cuối, ngoài phần thân robot nhô ra ở # mép áp dock (rear_extent khi đoạn cuối đi lùi, front_extent khi đi tiến) và, diff --git a/include/dock_planner/dock_calc.h b/include/dock_planner/dock_calc.h index 247ea6b..ba8da36 100644 --- a/include/dock_planner/dock_calc.h +++ b/include/dock_planner/dock_calc.h @@ -1,7 +1,9 @@ #ifndef DOCK_PLANNER_DOCK_CALC_H_ #define DOCK_PLANNER_DOCK_CALC_H_ +#include #include +#include #include #include @@ -27,16 +29,23 @@ struct RobotGeometry double circumscribed_radius = 0.0; // [m] }; -/** Pure docking-path geometry. Collision checking is intentionally out of scope. */ +/** Docking geometry with optional external checks; this class stays costmap-agnostic. */ class DockCalc { public: + using RotationClear = std::function; + using FootprintClear = std::function; + DockCalc(); explicit DockCalc(const DockPlannerConfig& config); ~DockCalc(); void setConfig(const DockPlannerConfig& config); + /** Install optional costmap-backed checks without adding costmap types to this geometry class. */ + void setCostmapCheckCallbacks(RotationClear rotation_clear, + FootprintClear footprint_clear); + bool makePlanMoveToDock( const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, @@ -46,6 +55,8 @@ public: private: DockPlannerConfig config_; + RotationClear rotation_clear_; + FootprintClear footprint_clear_; std::mutex calculation_mutex_; static double distance(const robot_geometry_msgs::Pose& first, @@ -115,7 +126,8 @@ private: double start_longitudinal, double start_lateral, double vertex_distance, std::vector& path, - double& pivot_angle) const; + double& pivot_angle, + bool allow_one_spacing_leg = false) const; /** * @brief No-cusp entry: one arc that converges onto the goal axis, then the @@ -140,6 +152,10 @@ private: const robot_geometry_msgs::Pose& goal, double goal_yaw, std::vector& path) const; + + bool checkPivotPathCostmap(const std::vector& path, + double rotation_radius, bool skip_start_pose, + std::string& reason) const; }; } // namespace dock_planner diff --git a/include/dock_planner/dock_planner.h b/include/dock_planner/dock_planner.h index 5f044d2..a91154e 100644 --- a/include/dock_planner/dock_planner.h +++ b/include/dock_planner/dock_planner.h @@ -5,6 +5,7 @@ #include #include +#include #include "dock_planner/dock_calc.h" #include "dock_planner/dock_planner_config.h" @@ -27,10 +28,15 @@ public: static robot_nav_core::BaseGlobalPlanner::Ptr create(); private: + bool rotationClear(const robot_geometry_msgs::Pose& pose, double radius) const; + bool footprintClear(const robot_geometry_msgs::Pose& pose); + robot_costmap_2d::Costmap2DROBOT* costmap_robot_ = nullptr; // non-owning bool initialized_ = false; std::string global_frame_; std::vector footprint_dock_; + std::vector footprint_map_polygon_; + std::vector footprint_map_cells_; DockCalc dock_calc_; }; diff --git a/include/dock_planner/dock_planner_config.h b/include/dock_planner/dock_planner_config.h index db627b0..ad102d7 100644 --- a/include/dock_planner/dock_planner_config.h +++ b/include/dock_planner/dock_planner_config.h @@ -44,8 +44,7 @@ enum class KinematicModel /** * @brief Runtime parameters that materially affect the docking path geometry. * - * Collision checking is intentionally not part of this contract yet. Adding a - * parameter for an unimplemented safety feature would make the YAML misleading. + * Costmap checking is opt-in and applies only to pivot maneuvers. */ struct DockPlannerConfig { @@ -115,6 +114,12 @@ struct DockPlannerConfig */ double pivot_safety_margin = 0.15; + /** [m] Maximum straight back-off distance for the differential-only last-resort pivot. 0 disables it. */ + double pivot_backoff_max_distance = 0.0; + + /** Check pivot rotations and straight legs against lethal costmap cells. */ + bool pivot_check_costmap = false; + /** * Per-marker key copied down by move_base2 (like footprint_dock). * Default kCenter keeps the legacy formula for existing profiles. diff --git a/src/dock_calc.cpp b/src/dock_calc.cpp index 346366c..cd0c82c 100644 --- a/src/dock_calc.cpp +++ b/src/dock_calc.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -34,6 +35,7 @@ enum class Shape kDirectEntry, kPivot, kCusp, + kBackoffPivot, }; const char* shapeName(Shape shape) @@ -46,6 +48,8 @@ const char* shapeName(Shape shape) return "straight_pivot_straight"; case Shape::kCusp: return "single_cusp"; + case Shape::kBackoffPivot: + return "backoff_pivot_straight"; default: return "none"; } @@ -105,6 +109,14 @@ void DockCalc::setConfig(const DockPlannerConfig& config) config_ = config; } +void DockCalc::setCostmapCheckCallbacks(RotationClear rotation_clear, + FootprintClear footprint_clear) +{ + std::lock_guard lock(calculation_mutex_); + rotation_clear_ = std::move(rotation_clear); + footprint_clear_ = std::move(footprint_clear); +} + double DockCalc::distance(const robot_geometry_msgs::Pose& first, const robot_geometry_msgs::Pose& second) { @@ -341,7 +353,8 @@ bool DockCalc::samplePivotPolyline( double start_lateral, double vertex_distance, std::vector& path, - double& pivot_angle) const + double& pivot_angle, + bool allow_one_spacing_leg) const { path.clear(); pivot_angle = 0.0; @@ -357,8 +370,12 @@ bool DockCalc::samplePivotPolyline( const double leg_length = std::hypot(start_longitudinal - vertex_distance, start_lateral); - if (!std::isfinite(leg_length) || - leg_length <= 2.0 * config_.path_point_spacing) + // Keep the old pivot's sampling threshold unchanged. Back-off B is placed + // one point spacing beyond the vertex, so that fallback can use one segment. + const bool too_short = allow_one_spacing_leg + ? leg_length + kEpsilon < config_.path_point_spacing + : leg_length <= 2.0 * config_.path_point_spacing; + if (!std::isfinite(leg_length) || too_short) { // Too short to sample into a usable leg; another shape fits better. return false; @@ -574,6 +591,63 @@ bool DockCalc::sampleTerminal( return path.size() >= 2; } +bool DockCalc::checkPivotPathCostmap( + const std::vector& path, + double rotation_radius, bool skip_start_pose, std::string& reason) const +{ + reason.clear(); + if (!config_.pivot_check_costmap || + (!rotation_clear_ && !footprint_clear_)) + { + return true; + } + + bool rotation_checked = false; + for (std::size_t index = 0; index < path.size(); ++index) + { + const auto& pose = path[index]; + bool same_position_as_previous = false; + if (index > 0) + { + const auto& previous = path[index - 1]; + same_position_as_previous = + std::hypot(pose.position.x - previous.position.x, + pose.position.y - previous.position.y) <= kEpsilon; + if (same_position_as_previous) + { + const double yaw_change = normalizeAngle( + data_convert::getYaw(pose.orientation) - + data_convert::getYaw(previous.orientation)); + if (std::fabs(yaw_change) > kNegligiblePivot && + !rotation_checked && rotation_clear_ && + !rotation_clear_(pose, rotation_radius)) + { + reason = "rotation sweep is blocked at (" + + std::to_string(pose.position.x) + ", " + + std::to_string(pose.position.y) + ")"; + return false; + } + if (std::fabs(yaw_change) > kNegligiblePivot) + { + rotation_checked = true; + } + continue; + } + rotation_checked = false; + } + + if ((!skip_start_pose || index != 0) && footprint_clear_ && + !footprint_clear_(pose)) + { + reason = "footprint is blocked at (" + + std::to_string(pose.position.x) + ", " + + std::to_string(pose.position.y) + ")"; + return false; + } + } + return true; +} + bool DockCalc::makePlanMoveToDock( const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, @@ -827,7 +901,23 @@ bool DockCalc::makePlanMoveToDock( start_lateral, pivot_vertex_distance, approach_segment, pivot_angle)) { - selected = Shape::kPivot; + std::string safety_reason; + bool safe = checkPivotPathCostmap( + approach_segment, + robot.circumscribed_radius + config_.pivot_safety_margin, + true, safety_reason); + if (safe) + { + selected = Shape::kPivot; + } + else + { + robot::log_info( + "[dock_calc] straight_pivot_straight failed costmap check: %s; " + "trying another shape.\n", + safety_reason.c_str()); + approach_segment.clear(); + } } break; @@ -847,6 +937,206 @@ bool DockCalc::makePlanMoveToDock( } } + std::string backoff_status = "not enabled"; + if (selected == Shape::kNone) + { + if (!differential) + { + backoff_status = "not enabled: model is ackermann"; + } + else if (!pivot_enabled) + { + backoff_status = "not enabled: pivot is disabled"; + } + else if (config_.pivot_backoff_max_distance <= 0.0) + { + backoff_status = "not enabled: pivot_backoff_max_distance is 0"; + } + else + { + backoff_status = "tried, rejected"; + std::string backoff_reason; + const double start_yaw = normalizeAngle( + data_convert::getYaw(start.pose.orientation)); + const double longitudinal_gain = + std::cos(normalizeAngle(start_yaw - approach_yaw)); + const double backoff_target_longitudinal = + pivot_vertex_distance + config_.path_point_spacing; + + if (!std::isfinite(longitudinal_gain) || + std::fabs(longitudinal_gain) <= 0.26) + { + backoff_reason = + "current heading is within 15 degrees of perpendicular to the approach axis " + "(longitudinal gain per metre <= 0.26)"; + } + else if (backoff_target_longitudinal <= start_longitudinal + kEpsilon) + { + backoff_reason = + "start is already at or beyond the minimum back-off target"; + } + else + { + const double backoff_length = + (backoff_target_longitudinal - start_longitudinal) / + std::fabs(longitudinal_gain); + double closest_footprint_projection = + std::numeric_limits::max(); + const double relative_yaw = normalizeAngle(start_yaw - approach_yaw); + const double cos_relative_yaw = std::cos(relative_yaw); + const double sin_relative_yaw = std::sin(relative_yaw); + for (const auto& point : footprint_robot) + { + const double projection = point.x * cos_relative_yaw - + point.y * sin_relative_yaw; + closest_footprint_projection = std::min( + closest_footprint_projection, projection); + } + + if (!std::isfinite(backoff_length) || + backoff_length > config_.pivot_backoff_max_distance + kEpsilon) + { + backoff_reason = + "required back-off length " + std::to_string(backoff_length) + + " m exceeds pivot_backoff_max_distance " + + std::to_string(config_.pivot_backoff_max_distance) + " m"; + } + else if (start_longitudinal + closest_footprint_projection < + dock_extent + config_.reverse_distance_padding - kEpsilon) + { + backoff_reason = + "current footprint does not clear the dock along the approach axis"; + } + else + { + const int sample_count = std::max( + 1, static_cast(std::ceil( + backoff_length / config_.path_point_spacing))); + std::vector backoff_samples; + backoff_samples.reserve(static_cast(sample_count + 1)); + const double signed_distance = longitudinal_gain > 0.0 + ? backoff_length + : -backoff_length; + for (int sample = 0; sample <= sample_count; ++sample) + { + const double ratio = static_cast(sample) / sample_count; + robot_geometry_msgs::Pose backoff_pose = offsetPoint( + start.pose, start_yaw, signed_distance * ratio); + backoff_pose.orientation = + data_convert::createQuaternionMsgFromYaw(start_yaw); + appendUnique(backoff_samples, backoff_pose); + } + backoff_samples.front() = start.pose; + + const robot_geometry_msgs::Pose& point_b = backoff_samples.back(); + const double point_b_relative_x = point_b.position.x - goal.pose.position.x; + const double point_b_relative_y = point_b.position.y - goal.pose.position.y; + const double point_b_longitudinal = + point_b_relative_x * std::cos(approach_yaw) + + point_b_relative_y * std::sin(approach_yaw); + const double point_b_lateral = + -point_b_relative_x * std::sin(approach_yaw) + + point_b_relative_y * std::cos(approach_yaw); + std::vector pivot_samples; + double backoff_pivot_angle = 0.0; + if (!samplePivotPolyline( + point_b, goal.pose, approach_yaw, heading_offset, + point_b_longitudinal, point_b_lateral, + pivot_vertex_distance, pivot_samples, + backoff_pivot_angle, true)) + { + backoff_reason = + "the existing pivot leg cannot be built from point B"; + } + else + { + std::vector backoff_path; + backoff_path.reserve( + backoff_samples.size() + pivot_samples.size() + + static_cast(kPivotBlockSteps)); + for (const auto& sample : backoff_samples) + { + appendUnique(backoff_path, sample); + } + + const double leg_yaw = normalizeAngle( + data_convert::getYaw(pivot_samples.front().orientation)); + const double backoff_rotation = + normalizeAngle(leg_yaw - start_yaw); + if (std::fabs(backoff_rotation) > kNegligiblePivot) + { + for (int step = 1; step <= kPivotBlockSteps; ++step) + { + const double ratio = static_cast(step) / + static_cast(kPivotBlockSteps); + robot_geometry_msgs::Pose rotation_pose = point_b; + rotation_pose.orientation = + data_convert::createQuaternionMsgFromYaw( + normalizeAngle(start_yaw + ratio * backoff_rotation)); + backoff_path.push_back(rotation_pose); + } + } + + for (std::size_t sample = 1; + sample < pivot_samples.size(); ++sample) + { + const auto& pivot_pose = pivot_samples[sample]; + const bool same_position = !backoff_path.empty() && + std::hypot( + backoff_path.back().position.x - pivot_pose.position.x, + backoff_path.back().position.y - pivot_pose.position.y) <= + kEpsilon; + const double yaw_change = same_position + ? normalizeAngle( + data_convert::getYaw(pivot_pose.orientation) - + data_convert::getYaw(backoff_path.back().orientation)) + : 0.0; + if (same_position && + std::fabs(yaw_change) > kNegligiblePivot) + { + backoff_path.push_back(pivot_pose); + } + else + { + appendUnique(backoff_path, pivot_pose); + } + } + + bool safe = true; + if (config_.pivot_check_costmap && + (rotation_clear_ || footprint_clear_)) + { + safe = checkPivotPathCostmap( + backoff_path, + robot.circumscribed_radius + config_.pivot_safety_margin, + true, backoff_reason); + } + + if (safe) + { + approach_segment = std::move(backoff_path); + pivot_angle = backoff_pivot_angle; + selected = Shape::kBackoffPivot; + backoff_status = "tried, succeeded"; + } + } + } + } + + if (selected == Shape::kNone) + { + if (backoff_reason.empty()) + { + backoff_reason = "costmap safety check rejected the path"; + } + backoff_status += ": " + backoff_reason; + robot::log_info( + "[dock_calc] backoff_pivot_straight failed: %s; no further shapes.\n", + backoff_reason.c_str()); + } + } + } + if (selected == Shape::kNone || approach_segment.empty()) { robot::log_error( @@ -854,12 +1144,14 @@ bool DockCalc::makePlanMoveToDock( "start=(long=%.3f m, lateral=%.3f m in approach frame), " "min_radius=%.3f m, straight_distance=%.3f m, " "cusp_reachable=%s (extension=%.3f m, max=%.3f m), " - "pivot_enabled=%s (vertex=%.3f m, circumscribed=%.3f m).\n", + "pivot_enabled=%s (vertex=%.3f m, circumscribed=%.3f m), " + "backoff_pivot=%s.\n", differential ? "differential" : "ackermann", start_longitudinal, start_lateral, minimum_turning_radius, straight_distance, cusp_reachable ? "yes" : "no", cusp_extension, config_.maximum_forward_extension, pivot_enabled ? "yes" : "no", - pivot_vertex_distance, robot.circumscribed_radius); + pivot_vertex_distance, robot.circumscribed_radius, + backoff_status.c_str()); return false; } diff --git a/src/dock_planner.cpp b/src/dock_planner.cpp index b47af18..877ad44 100644 --- a/src/dock_planner.cpp +++ b/src/dock_planner.cpp @@ -5,7 +5,10 @@ #include #include +#include +#include #include +#include namespace dock_planner { @@ -94,6 +97,135 @@ FootprintLoadStatus loadDockFootprint( DockPlanner::DockPlanner() = default; +bool DockPlanner::rotationClear(const robot_geometry_msgs::Pose& pose, + double radius) const +{ + // getCostmap() may return a replacement map after a resize. Keep this + // pointer local to the callback and protect every read with that map's mutex. + robot_costmap_2d::Costmap2D* costmap = + costmap_robot_ == nullptr ? nullptr : costmap_robot_->getCostmap(); + if (costmap == nullptr || !std::isfinite(pose.position.x) || + !std::isfinite(pose.position.y) || !std::isfinite(radius) || radius < 0.0) + { + return false; + } + + boost::unique_lock lock( + *costmap->getMutex()); + const double resolution = costmap->getResolution(); + const unsigned int size_x = costmap->getSizeInCellsX(); + const unsigned int size_y = costmap->getSizeInCellsY(); + if (!std::isfinite(resolution) || resolution <= 0.0 || size_x == 0 || size_y == 0) + { + return false; + } + + const double map_min_x = costmap->getOriginX(); + const double map_min_y = costmap->getOriginY(); + const double map_max_x = map_min_x + resolution * size_x; + const double map_max_y = map_min_y + resolution * size_y; + if (pose.position.x - radius < map_min_x || + pose.position.y - radius < map_min_y || + pose.position.x + radius >= map_max_x || + pose.position.y + radius >= map_max_y) + { + return false; + } + + int min_mx = 0; + int min_my = 0; + int max_mx = 0; + int max_my = 0; + costmap->worldToMapNoBounds(pose.position.x - radius, + pose.position.y - radius, min_mx, min_my); + costmap->worldToMapNoBounds(pose.position.x + radius, + pose.position.y + radius, max_mx, max_my); + min_mx = std::max(0, min_mx); + min_my = std::max(0, min_my); + max_mx = std::min(static_cast(size_x) - 1, max_mx); + max_my = std::min(static_cast(size_y) - 1, max_my); + + const double half_cell = resolution * 0.5; + const double radius_squared = radius * radius; + for (int my = min_my; my <= max_my; ++my) + { + for (int mx = min_mx; mx <= max_mx; ++mx) + { + double cell_x = 0.0; + double cell_y = 0.0; + costmap->mapToWorld(static_cast(mx), + static_cast(my), cell_x, cell_y); + const double dx = std::max( + std::fabs(cell_x - pose.position.x) - half_cell, 0.0); + const double dy = std::max( + std::fabs(cell_y - pose.position.y) - half_cell, 0.0); + if (dx * dx + dy * dy <= radius_squared && + costmap->getCost(static_cast(mx), + static_cast(my)) == + robot_costmap_2d::LETHAL_OBSTACLE) + { + return false; + } + } + } + return true; +} + +bool DockPlanner::footprintClear(const robot_geometry_msgs::Pose& pose) +{ + // As above, never retain getCostmap() across calls: the master can be + // replaced while a planner is running. + robot_costmap_2d::Costmap2D* costmap = + costmap_robot_ == nullptr ? nullptr : costmap_robot_->getCostmap(); + if (costmap == nullptr || !std::isfinite(pose.position.x) || + !std::isfinite(pose.position.y)) + { + return false; + } + + const auto& footprint = costmap_robot_->getRobotFootprint(); + if (footprint.size() < 3) + { + return false; + } + + boost::unique_lock lock( + *costmap->getMutex()); + footprint_map_polygon_.clear(); + footprint_map_cells_.clear(); + footprint_map_polygon_.reserve(footprint.size()); + const double yaw = data_convert::getYaw(pose.orientation); + if (!std::isfinite(yaw)) + { + return false; + } + const double cos_yaw = std::cos(yaw); + const double sin_yaw = std::sin(yaw); + for (const auto& point : footprint) + { + const double world_x = pose.position.x + + cos_yaw * point.x - sin_yaw * point.y; + const double world_y = pose.position.y + + sin_yaw * point.x + cos_yaw * point.y; + robot_costmap_2d::MapLocation map_point; + if (!costmap->worldToMap(world_x, world_y, map_point.x, map_point.y)) + { + return false; + } + footprint_map_polygon_.push_back(map_point); + } + + costmap->convexFillCells(footprint_map_polygon_, footprint_map_cells_); + for (const auto& cell : footprint_map_cells_) + { + if (costmap->getCost(cell.x, cell.y) == robot_costmap_2d::LETHAL_OBSTACLE) + { + return false; + } + } + return !footprint_map_cells_.empty(); +} + bool DockPlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) { @@ -219,19 +351,31 @@ bool DockPlanner::initialize(std::string name, global_frame_ = costmap_robot->getGlobalFrameID(); footprint_dock_ = std::move(loaded_footprint); dock_calc_.setConfig(loaded_config); + dock_calc_.setCostmapCheckCallbacks( + [this](const robot_geometry_msgs::Pose& pose, double radius) + { + return rotationClear(pose, radius); + }, + [this](const robot_geometry_msgs::Pose& pose) + { + return footprintClear(pose); + }); initialized_ = true; robot::log_info( "[dock_planner] Initialized dock maneuver (docking edge is derived per plan " "from the side the robot stands on): model=%s, TF %s -> %s, wheel_base=%.4f m, " "max_steering_angle=%.4f rad, minimum_turning_radius=%.4f m, " - "pivot_fallback_extension=%.3f m, pivot_safety_margin=%.3f m.\n", + "pivot_fallback_extension=%.3f m, pivot_safety_margin=%.3f m, " + "pivot_backoff_max_distance=%.3f m, pivot_check_costmap=%s.\n", loaded_config.requiresAxleTf() ? "ackermann" : "differential", loaded_config.requiresAxleTf() ? loaded_config.front_axle_frame.c_str() : "-", loaded_config.requiresAxleTf() ? loaded_config.rear_axle_frame.c_str() : "-", loaded_config.wheel_base, loaded_config.max_steering_angle, minimum_turning_radius, loaded_config.pivot_fallback_extension, - loaded_config.pivot_safety_margin); + loaded_config.pivot_safety_margin, + loaded_config.pivot_backoff_max_distance, + loaded_config.pivot_check_costmap ? "true" : "false"); return true; } diff --git a/src/dock_planner_config.cpp b/src/dock_planner_config.cpp index 62b9725..e4784a7 100644 --- a/src/dock_planner_config.cpp +++ b/src/dock_planner_config.cpp @@ -26,6 +26,24 @@ bool readOptionalDouble(const robot::NodeHandle& nh, const std::string& key, return true; } +bool readOptionalBool(const robot::NodeHandle& nh, const std::string& key, + bool& value, std::string& error) +{ + if (!nh.hasParam(key)) + { + return true; + } + + bool parsed = value; + if (!nh.getParam(key, parsed, value)) + { + error = "parameter '" + key + "' must be a boolean"; + return false; + } + value = parsed; + return true; +} + bool readOptionalString(const robot::NodeHandle& nh, const std::string& key, std::string& value, std::string& error) { @@ -123,6 +141,10 @@ bool DockPlannerConfig::load(const robot::NodeHandle& nh, DockPlannerConfig& con loaded.pivot_fallback_extension, error) || !readOptionalDouble(nh, "maneuver/pivot_safety_margin", loaded.pivot_safety_margin, error) || + !readOptionalDouble(nh, "maneuver/pivot_backoff_max_distance", + loaded.pivot_backoff_max_distance, error) || + !readOptionalBool(nh, "maneuver/pivot_check_costmap", + loaded.pivot_check_costmap, error) || !readOptionalString(nh, "kinematics/front_axle_frame", loaded.front_axle_frame, error) || !readOptionalString(nh, "kinematics/rear_axle_frame", @@ -172,6 +194,7 @@ bool DockPlannerConfig::validate(std::string& error) const {"kinematics/minimum_turning_radius", minimum_turning_radius}, {"maneuver/pivot_fallback_extension", pivot_fallback_extension}, {"maneuver/pivot_safety_margin", pivot_safety_margin}, + {"maneuver/pivot_backoff_max_distance", pivot_backoff_max_distance}, {"terminal/reverse_distance_padding", reverse_distance_padding}, {"terminal/straight_length", straight_length}, {"maneuver/minimum_forward_distance", minimum_forward_distance}, @@ -257,6 +280,11 @@ bool DockPlannerConfig::validate(std::string& error) const error = "parameter 'maneuver/pivot_safety_margin' must be >= 0 m"; return false; } + if (pivot_backoff_max_distance < 0.0 || pivot_backoff_max_distance > 3.0) + { + error = "parameter 'maneuver/pivot_backoff_max_distance' must be in [0, 3] m"; + return false; + } if (path_point_spacing <= 0.0 || path_point_spacing > 1.0) { error = "parameter 'sampling/path_point_spacing' must be in (0, 1] m"; diff --git a/test/dock_planner_test.cpp b/test/dock_planner_test.cpp index 5ae0915..1b3cd59 100644 --- a/test/dock_planner_test.cpp +++ b/test/dock_planner_test.cpp @@ -50,6 +50,35 @@ bool near(double first, double second, double tolerance = 1e-8) return std::fabs(first - second) <= tolerance; } +bool samePoseExactly(const robot_geometry_msgs::Pose& first, + const robot_geometry_msgs::Pose& second) +{ + return first.position.x == second.position.x && + first.position.y == second.position.y && + first.position.z == second.position.z && + first.orientation.x == second.orientation.x && + first.orientation.y == second.orientation.y && + first.orientation.z == second.orientation.z && + first.orientation.w == second.orientation.w; +} + +bool pathsEqualExactly(const std::vector& first, + const std::vector& second) +{ + if (first.size() != second.size()) + { + return false; + } + for (std::size_t index = 0; index < first.size(); ++index) + { + if (!samePoseExactly(first[index], second[index])) + { + return false; + } + } + return true; +} + double normalizeAngle(double angle) { return std::remainder(angle, 2.0 * kPi); @@ -347,6 +376,8 @@ void testConfig() CHECK(config.validate(error)); CHECK(error.empty()); CHECK(std::isnan(config.minimumTurningRadius())); + CHECK(near(config.pivot_backoff_max_distance, 0.0)); + CHECK(!config.pivot_check_costmap); config.wheel_base = 1.3268; CHECK(near(config.minimumTurningRadius(), @@ -369,6 +400,18 @@ void testConfig() config = dock_planner::DockPlannerConfig{}; config.pivot_safety_margin = -0.01; CHECK(!config.validate(error)); + config = dock_planner::DockPlannerConfig{}; + config.pivot_backoff_max_distance = -0.01; + CHECK(!config.validate(error)); + config = dock_planner::DockPlannerConfig{}; + config.pivot_backoff_max_distance = 3.01; + CHECK(!config.validate(error)); + config = dock_planner::DockPlannerConfig{}; + config.pivot_backoff_max_distance = std::numeric_limits::infinity(); + CHECK(!config.validate(error)); + config = dock_planner::DockPlannerConfig{}; + config.pivot_backoff_max_distance = 3.0; + CHECK(config.validate(error)); // A differential base has no steered axle, so empty axle frames and a zero // steering angle must NOT stop it loading -- validating them there would @@ -407,6 +450,375 @@ std::vector apmDockFootprint() point(-0.50, 0.40), point(-0.50, -0.40)}; } +std::vector robotFootprint065x069() +{ + return {point(0.325, -0.345), point(0.325, 0.345), + point(-0.325, 0.345), point(-0.325, -0.345)}; +} + +dock_planner::DockPlannerConfig differentialBackoffConfig() +{ + dock_planner::DockPlannerConfig config; + config.kinematic_model = dock_planner::KinematicModel::kDifferential; + config.minimum_turning_radius = 1.0; + config.maximum_forward_extension = 0.5; + config.direct_entry_min_curve_room = 0.3; + config.pivot_fallback_extension = 1.2; + config.pivot_safety_margin = 0.15; + config.straight_length = 0.4; + config.path_point_spacing = 0.05; + return config; +} + +void checkBackoffPivotPath(const std::vector& path, + const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + double pivot_vertex_distance) +{ + CHECK(path.size() > 12); + CHECK(samePoseExactly(path.front(), start.pose)); + CHECK(samePoseExactly(path.back(), goal.pose)); + + const double start_yaw = data_convert::getYaw(start.pose.orientation); + std::size_t first_rotation_begin = path.size(); + for (std::size_t index = 1; index < path.size(); ++index) + { + const bool same_position = + std::hypot(path[index].position.x - path[index - 1].position.x, + path[index].position.y - path[index - 1].position.y) <= 1e-9; + const double yaw_change = normalizeAngle( + data_convert::getYaw(path[index].orientation) - + data_convert::getYaw(path[index - 1].orientation)); + if (same_position && std::fabs(yaw_change) > 1e-6) + { + first_rotation_begin = index - 1; + break; + } + } + CHECK(first_rotation_begin > 0); + CHECK(first_rotation_begin < path.size()); + if (first_rotation_begin >= path.size()) + { + return; + } + + double previous_longitudinal = longitudinal(path.front(), goal.pose); + for (std::size_t index = 0; index <= first_rotation_begin; ++index) + { + CHECK(std::fabs(normalizeAngle( + data_convert::getYaw(path[index].orientation) - start_yaw)) < 1e-7); + const double current_longitudinal = longitudinal(path[index], goal.pose); + CHECK(current_longitudinal + 1e-8 >= previous_longitudinal); + previous_longitudinal = current_longitudinal; + } + CHECK(longitudinal(path[first_rotation_begin], goal.pose) >= + pivot_vertex_distance + 0.05 - 1e-7); + + int rotation_blocks = 0; + bool in_rotation = false; + std::size_t last_rotation_end = 0; + for (std::size_t index = 1; index < path.size(); ++index) + { + const bool same_position = + std::hypot(path[index].position.x - path[index - 1].position.x, + path[index].position.y - path[index - 1].position.y) <= 1e-9; + const double yaw_change = normalizeAngle( + data_convert::getYaw(path[index].orientation) - + data_convert::getYaw(path[index - 1].orientation)); + if (same_position && std::fabs(yaw_change) > 1e-6) + { + if (!in_rotation) + { + ++rotation_blocks; + } + in_rotation = true; + last_rotation_end = index; + } + else if (!same_position) + { + in_rotation = false; + } + } + CHECK(rotation_blocks >= 2); + CHECK(last_rotation_end + 1 < path.size()); + for (std::size_t index = last_rotation_end; index + 1 < path.size(); ++index) + { + CHECK(!edgeIsForward(path[index], path[index + 1])); + CHECK(std::fabs(lateral(path[index], goal.pose)) < 1e-7); + CHECK(std::fabs(normalizeAngle( + data_convert::getYaw(path[index].orientation) - + data_convert::getYaw(goal.pose.orientation))) < 1e-7); + } +} + +void testBackoffPivotRobotFailures() +{ + const auto robot_footprint = robotFootprint065x069(); + const std::vector no_dock_footprint; + const auto goal = pose(0.0, 0.0, 0.0); + const double pivot_vertex = std::hypot(0.325, 0.345) + 0.15; + const std::vector starts = { + pose(0.579, 0.292, 0.0), + pose(0.427, 0.155, 0.0), + }; + + for (const auto& start : starts) + { + auto config = differentialBackoffConfig(); + dock_planner::DockCalc disabled(config); + std::vector failed_path; + CHECK(!disabled.makePlanMoveToDock(start, goal, robot_footprint, + no_dock_footprint, failed_path)); + CHECK(failed_path.empty()); + + config.pivot_backoff_max_distance = 1.0; + dock_planner::DockCalc enabled(config); + std::vector path; + CHECK(enabled.makePlanMoveToDock(start, goal, robot_footprint, + no_dock_footprint, path)); + checkBackoffPivotPath(path, start, goal, pivot_vertex); + } +} + +void testExistingPlansUnchangedByBackoff() +{ + const auto robot_footprint = apmFootprint(); + const auto dock_footprint = apmDockFootprint(); + const auto goal = pose(0.0, 0.0, 0.0); + + struct Case + { + dock_planner::DockPlannerConfig config; + robot_geometry_msgs::PoseStamped start; + }; + std::vector cases; + + auto cusp_config = apmConfig(); + cases.push_back({cusp_config, pose(2.8, 0.6, -1.2)}); + cases.push_back({cusp_config, pose(-2.8, 0.6, 0.0)}); + + auto direct_config = apmConfig(); + direct_config.direct_entry_min_curve_room = 0.5; + cases.push_back({direct_config, pose(2.8, 0.6, -1.2)}); + cases.push_back({direct_config, pose(-4.0, 0.6, 0.0)}); + + auto pivot_config = apmConfig(); + pivot_config.pivot_fallback_extension = 1.0; + cases.push_back({pivot_config, pose(2.8, 0.6, -1.2)}); + cases.push_back({pivot_config, pose(-2.8, 0.6, 0.0)}); + + for (const auto& test_case : cases) + { + auto baseline_config = test_case.config; + baseline_config.pivot_backoff_max_distance = 0.0; + baseline_config.pivot_check_costmap = false; + auto candidate_config = baseline_config; + candidate_config.pivot_backoff_max_distance = 1.0; + + dock_planner::DockCalc baseline(baseline_config); + dock_planner::DockCalc candidate(candidate_config); + std::vector baseline_path; + std::vector candidate_path; + CHECK(baseline.makePlanMoveToDock(test_case.start, goal, robot_footprint, + dock_footprint, baseline_path)); + CHECK(candidate.makePlanMoveToDock(test_case.start, goal, robot_footprint, + dock_footprint, candidate_path)); + // A key-zero plan is the pre-feature behavior: the fallback is only + // reached after every old ladder candidate fails. Exact field equality + // catches even changes to sampling, quaternion signs, or endpoints. + CHECK(pathsEqualExactly(baseline_path, candidate_path)); + } +} + +void testBackoffPivotGates() +{ + const auto robot_footprint = robotFootprint065x069(); + const std::vector no_dock_footprint; + const auto goal = pose(0.0, 0.0, 0.0); + auto config = differentialBackoffConfig(); + config.pivot_backoff_max_distance = 1.0; + + dock_planner::DockCalc perpendicular(config); + std::vector path; + CHECK(!perpendicular.makePlanMoveToDock( + pose(0.579, 0.292, kPi / 2.0), goal, robot_footprint, + no_dock_footprint, path)); + CHECK(path.empty()); + + config.pivot_backoff_max_distance = 0.3; + dock_planner::DockCalc too_far(config); + CHECK(!too_far.makePlanMoveToDock( + pose(0.1, 0.4, 0.0), goal, robot_footprint, + no_dock_footprint, path)); + CHECK(path.empty()); + + auto ackermann_config = config; + ackermann_config.kinematic_model = dock_planner::KinematicModel::kAckermann; + ackermann_config.wheel_base = std::tan(0.5); + ackermann_config.max_steering_angle = 0.5; + dock_planner::DockCalc ackermann(ackermann_config); + CHECK(!ackermann.makePlanMoveToDock( + pose(0.579, 0.292, 0.0), goal, robot_footprint, + no_dock_footprint, path)); + CHECK(path.empty()); +} + +void testCostmapCheckCallbacks() +{ + const auto robot_footprint = robotFootprint065x069(); + const std::vector no_dock_footprint; + const auto goal = pose(0.0, 0.0, 0.0); + const auto start = pose(0.579, 0.292, 0.0); + auto config = differentialBackoffConfig(); + config.pivot_backoff_max_distance = 1.0; + config.pivot_check_costmap = true; + const double expected_rotation_radius = + std::hypot(0.325, 0.345) + config.pivot_safety_margin; + + int rotation_calls = 0; + dock_planner::DockCalc rotation_blocked(config); + rotation_blocked.setCostmapCheckCallbacks( + [&rotation_calls, expected_rotation_radius]( + const robot_geometry_msgs::Pose&, double radius) + { + ++rotation_calls; + CHECK(near(radius, expected_rotation_radius)); + return false; + }, + [](const robot_geometry_msgs::Pose&) { return true; }); + std::vector path; + CHECK(!rotation_blocked.makePlanMoveToDock( + start, goal, robot_footprint, no_dock_footprint, path)); + CHECK(path.empty()); + CHECK(rotation_calls > 0); + + int footprint_calls = 0; + dock_planner::DockCalc footprint_blocked(config); + footprint_blocked.setCostmapCheckCallbacks( + [](const robot_geometry_msgs::Pose&, double) { return true; }, + [&footprint_calls](const robot_geometry_msgs::Pose& sample) + { + ++footprint_calls; + return !(sample.position.x > 0.60 && sample.position.x < 0.67 && + sample.position.y > 0.25 && sample.position.y < 0.33); + }); + CHECK(!footprint_blocked.makePlanMoveToDock( + start, goal, robot_footprint, no_dock_footprint, path)); + CHECK(path.empty()); + CHECK(footprint_calls > 0); + + int start_pose_checks = 0; + dock_planner::DockCalc start_pose_skipped(config); + start_pose_skipped.setCostmapCheckCallbacks( + [](const robot_geometry_msgs::Pose&, double) { return true; }, + [&start_pose_checks, &start](const robot_geometry_msgs::Pose& sample) + { + if (near(sample.position.x, start.pose.position.x) && + near(sample.position.y, start.pose.position.y)) + { + ++start_pose_checks; + return false; + } + return true; + }); + CHECK(start_pose_skipped.makePlanMoveToDock( + start, goal, robot_footprint, no_dock_footprint, path)); + CHECK(start_pose_checks == 0); + + // A blocked old pivot falls through to the old cusp when that cusp remains + // feasible, proving the check also gates straight_pivot_straight. + auto old_pivot_config = apmConfig(); + old_pivot_config.wheel_base = std::tan(0.5); + old_pivot_config.max_steering_angle = 0.5; + old_pivot_config.maximum_forward_extension = 3.0; + old_pivot_config.pivot_fallback_extension = 0.5; + old_pivot_config.pivot_check_costmap = true; + dock_planner::DockCalc old_pivot(old_pivot_config); + old_pivot.setCostmapCheckCallbacks( + [](const robot_geometry_msgs::Pose&, double) { return false; }, + [](const robot_geometry_msgs::Pose&) { return true; }); + const auto old_pivot_path = generatePath( + old_pivot, pose(2.8, 0.6, -1.2), goal, apmFootprint(), + apmDockFootprint()); + checkSingleCuspPath(old_pivot_path, goal.pose, 1.0, false); + + // A lethal cell in the terminal corridor is expected at the charger/dock + // interface. Pivot approach legs and rotation remain clear, so the old + // pivot plan must stay exactly the same as with the check switched off. + auto terminal_pivot_config = apmConfig(); + terminal_pivot_config.kinematic_model = + dock_planner::KinematicModel::kDifferential; + terminal_pivot_config.minimum_turning_radius = 0.0; + const auto terminal_pivot_start = pose(2.8, 0.6, -1.2); + dock_planner::DockCalc terminal_pivot_unchecked(terminal_pivot_config); + std::vector terminal_pivot_baseline; + CHECK(terminal_pivot_unchecked.makePlanMoveToDock( + terminal_pivot_start, goal, apmFootprint(), apmDockFootprint(), + terminal_pivot_baseline)); + checkPivotPath(terminal_pivot_baseline, goal.pose, false, + std::hypot(1.65, 0.40) + 0.50 + + terminal_pivot_config.pivot_safety_margin); + + terminal_pivot_config.pivot_check_costmap = true; + const double terminal_pivot_distance = std::max( + 0.35 + 0.50 + terminal_pivot_config.reverse_distance_padding, + terminal_pivot_config.straight_length); + dock_planner::DockCalc terminal_pivot_checked(terminal_pivot_config); + terminal_pivot_checked.setCostmapCheckCallbacks( + [](const robot_geometry_msgs::Pose&, double) { return true; }, + [&goal, terminal_pivot_distance](const robot_geometry_msgs::Pose& sample) + { + return std::hypot(sample.position.x - goal.pose.position.x, + sample.position.y - goal.pose.position.y) > + terminal_pivot_distance; + }); + std::vector terminal_pivot_path; + CHECK(terminal_pivot_checked.makePlanMoveToDock( + terminal_pivot_start, goal, apmFootprint(), apmDockFootprint(), + terminal_pivot_path)); + checkPivotPath(terminal_pivot_path, goal.pose, false, + std::hypot(1.65, 0.40) + 0.50 + + terminal_pivot_config.pivot_safety_margin); + CHECK(pathsEqualExactly(terminal_pivot_baseline, terminal_pivot_path)); + + auto check_off_config = differentialBackoffConfig(); + check_off_config.pivot_backoff_max_distance = 1.0; + dock_planner::DockCalc no_callbacks(check_off_config); + dock_planner::DockCalc ignored_callbacks(check_off_config); + ignored_callbacks.setCostmapCheckCallbacks( + [](const robot_geometry_msgs::Pose&, double) { return false; }, + [](const robot_geometry_msgs::Pose&) { return false; }); + std::vector no_callback_path; + std::vector ignored_callback_path; + CHECK(no_callbacks.makePlanMoveToDock(start, goal, robot_footprint, + no_dock_footprint, no_callback_path)); + CHECK(ignored_callbacks.makePlanMoveToDock( + start, goal, robot_footprint, no_dock_footprint, + ignored_callback_path)); + CHECK(pathsEqualExactly(no_callback_path, ignored_callback_path)); + + // The back-off fallback also ignores cells in the terminal corridor while + // still checking its rotation and both approach legs. + dock_planner::DockCalc terminal_corridor_blocked(config); + const double backoff_terminal_distance = config.straight_length; + terminal_corridor_blocked.setCostmapCheckCallbacks( + [](const robot_geometry_msgs::Pose&, double) { return true; }, + [&goal, backoff_terminal_distance](const robot_geometry_msgs::Pose& sample) + { + return std::hypot(sample.position.x - goal.pose.position.x, + sample.position.y - goal.pose.position.y) > + backoff_terminal_distance; + }); + std::vector terminal_corridor_backoff_path; + CHECK(terminal_corridor_blocked.makePlanMoveToDock( + start, goal, robot_footprint, no_dock_footprint, + terminal_corridor_backoff_path)); + checkBackoffPivotPath(terminal_corridor_backoff_path, start, goal, + std::hypot(0.325, 0.345) + config.pivot_safety_margin); + CHECK(pathsEqualExactly(ignored_callback_path, + terminal_corridor_backoff_path)); +} + /** * Where the rotation has to happen for the footprints above. The swept circle * is the binding constraint, not the mating extent: hypot(1.65, 0.40) is @@ -759,6 +1171,10 @@ void testDockAnchor() int main() { testConfig(); + testBackoffPivotRobotFailures(); + testExistingPlansUnchangedByBackoff(); + testBackoffPivotGates(); + testCostmapCheckCallbacks(); testPathGeneration(); testDirectEntry(); testPivotFallback();