diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/.gitmodules b/.gitmodules old mode 100644 new mode 100755 diff --git a/CATKIN_BUILD_README.md b/CATKIN_BUILD_README.md old mode 100644 new mode 100755 index 6add951..8526d26 --- a/CATKIN_BUILD_README.md +++ b/CATKIN_BUILD_README.md @@ -56,6 +56,22 @@ Project này hỗ trợ **2 build systems**: - Cần tạo workspace riêng (xem hướng dẫn trên) - Packages tự động detect catkin mode khi build trong workspace +## Test + +Các package có cờ test chung mặc định tắt test, kể cả khi catkin bật +`CATKIN_ENABLE_TESTING`. Trong workspace, bật các package hỗ trợ bằng: + +```bash +catkin_make -DPNKX_NAV_CORE_BUILD_TESTS=ON +# Hoặc chỉ bật một package: +catkin_make -DBUILD_COSTMAP_TESTS=ON +``` + +CMake cache giữ giá trị các cờ; dùng build directory mới hoặc đặt lại cờ khi đổi +lựa chọn. `robot_cpp` và C API giữ cờ riêng `BUILD_TESTS` và `BUILD_C_API_TESTS` +(C API cũng nhận `BUILD_TESTS`), không theo cờ chung. Các test catkin còn yêu cầu +`CATKIN_ENABLE_TESTING=ON`; một số test cần GTest. + ## Chi tiết Xem `src/Navigations/Packages/move_base/BUILD_INSTRUCTIONS.md` để biết chi tiết về cách build package `move_base` với cả hai hệ thống. diff --git a/CMAKE_BUILD_README.md b/CMAKE_BUILD_README.md old mode 100644 new mode 100755 index 4361fd5..00c6c06 --- a/CMAKE_BUILD_README.md +++ b/CMAKE_BUILD_README.md @@ -157,10 +157,18 @@ cmake -DCMAKE_CXX_COMPILER=g++-9 .. # Chỉ định install prefix cmake -DCMAKE_INSTALL_PREFIX=/usr/local .. -# Build tests (nếu có) -cmake -DBUILD_TESTS=ON .. +# Các test được cấu hình qua cờ chung mặc định tắt; bật các package hỗ trợ: +cmake -DPNKX_NAV_CORE_BUILD_TESTS=ON .. + +# Hoặc chỉ bật một package, ví dụ costmap: +cmake -DBUILD_COSTMAP_TESTS=ON .. ``` +Các tùy chọn test được lưu trong CMake cache; dùng build directory mới hoặc đặt lại cờ +khi thay đổi lựa chọn. `robot_cpp` và C API giữ cờ riêng `BUILD_TESTS` và +`BUILD_C_API_TESTS` (C API cũng nhận `BUILD_TESTS`); cờ chung không bật chúng. +Một số test còn yêu cầu GTest hoặc catkin và `CATKIN_ENABLE_TESTING=ON`. + --- ## Install diff --git a/CMakeLists.txt b/CMakeLists.txt old mode 100644 new mode 100755 index 7360a33..175d32a --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -149,8 +149,8 @@ endif() # Local planner đang chạy trên robot thật: cả bốn profile trong move_base_common_params.yaml đều # trỏ `StanleyLocalPlanner`. Thiếu libstanley_local_planner.so là move_base2 chết ngay ở # `initialize()` ("could not load the initial local planner"). -if (NOT TARGET stanley_local_planner) - add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/local_planners/stanley_local_planner) +if (NOT TARGET hybrid_local_planner) + add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/local_planners/hybrid_local_planner) endif() if (NOT TARGET robot_actionlib_msgs) @@ -189,7 +189,7 @@ endif() # keep the current sibling Test directory buildable from this root CMake file. option(PNKX_NAV_CORE_BUILD_TEST_PACKAGES "Build navigation packages currently kept in AMR_T800/Test" - ON) + OFF) option(PNKX_NAV_CORE_BUILD_CATKIN_TEST_PACKAGES "Build Test packages that require a catkin workspace instead of standalone CMake" diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/config/runtime/action_handlers_params.yaml b/config/runtime/action_handlers_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/compound_actions_params.yaml b/config/runtime/compound_actions_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/config/costmap_params.yaml b/config/runtime/config/costmap_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/config/inflation_layer_params.yaml b/config/runtime/config/inflation_layer_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/config/obstacle_layer_params.yaml b/config/runtime/config/obstacle_layer_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/config/static_layer_params.yaml b/config/runtime/config/static_layer_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/config/voxel_layer_params.yaml b/config/runtime/config/voxel_layer_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/costmap_common_params.yaml b/config/runtime/costmap_common_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/costmap_global_params.yaml b/config/runtime/costmap_global_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/costmap_global_params_plugins_no_virtual_walls.yaml b/config/runtime/costmap_global_params_plugins_no_virtual_walls.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/costmap_local_params.yaml b/config/runtime/costmap_local_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/costmap_local_params_plugins_no_virtual_walls.yaml b/config/runtime/costmap_local_params_plugins_no_virtual_walls.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/custom_global_params.yaml b/config/runtime/custom_global_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/dock_global_params.yaml b/config/runtime/dock_global_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/hybrid_local_planner_params.yaml b/config/runtime/hybrid_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/maker_sources.yaml b/config/runtime/maker_sources.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mission_adapters_params.yaml b/config/runtime/mission_adapters_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/move_base_common_params.yaml b/config/runtime/move_base_common_params.yaml old mode 100644 new mode 100755 index 7b3ddf4..a67e9b8 --- a/config/runtime/move_base_common_params.yaml +++ b/config/runtime/move_base_common_params.yaml @@ -24,7 +24,7 @@ position: global_planner: CustomPlanner # vật chất hoá tuyến NURBS từ edge của VDA5050 Order. # MÙ VẬT CẢN theo thiết kế — nó là route materializer, không # phải search planner. Chỉ có bản makePlan(Order, ...). - local_planner: HybridLocalPlanner + local_planner: PNKXLocalPlanner docking: # goal_frame đã được ControlLoop quy thành pose tuyệt đối. DockPlanner dùng đúng contract diff --git a/config/runtime/mppi_local_planner_params.yaml b/config/runtime/mppi_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/base_local_planner_params.yaml b/config/runtime/mprim/base_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/dwa_local_planner_params.yaml b/config/runtime/mprim/dwa_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/ekf.yaml b/config/runtime/mprim/ekf.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/genmprim_unicycle_highcost_5cm.m b/config/runtime/mprim/genmprim_unicycle_highcost_5cm.m old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/genmprim_unicycle_highcost_5cm.py b/config/runtime/mprim/genmprim_unicycle_highcost_5cm.py old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/localization.yaml b/config/runtime/mprim/localization.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/mapping.yaml b/config/runtime/mprim/mapping.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/mpc_local_planner_params.yaml b/config/runtime/mprim/mpc_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/mqtt_general.yaml b/config/runtime/mprim/mqtt_general.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/ros_diff_drive_controller.yaml b/config/runtime/mprim/ros_diff_drive_controller.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/sbpl_global_params.yaml b/config/runtime/mprim/sbpl_global_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/sick_line_guidance_mls.yaml b/config/runtime/mprim/sick_line_guidance_mls.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_5cm.mprim b/config/runtime/mprim/unicycle_5cm.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_5cm_expensive_turn_in_place.mprim b/config/runtime/mprim/unicycle_5cm_expensive_turn_in_place.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_5cm_expensive_turn_in_place_highcost.mprim b/config/runtime/mprim/unicycle_5cm_expensive_turn_in_place_highcost.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_5cm_noreverse_trolley.mprim b/config/runtime/mprim/unicycle_5cm_noreverse_trolley.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_highcost_10cm.mprim b/config/runtime/mprim/unicycle_highcost_10cm.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_highcost_1cm.mprim b/config/runtime/mprim/unicycle_highcost_1cm.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_highcost_2_5cm.mprim b/config/runtime/mprim/unicycle_highcost_2_5cm.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_highcost_2cm.mprim b/config/runtime/mprim/unicycle_highcost_2cm.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/mprim/unicycle_highcost_5cm.mprim b/config/runtime/mprim/unicycle_highcost_5cm.mprim old mode 100644 new mode 100755 diff --git a/config/runtime/pnkx_local_planner_params.yaml b/config/runtime/pnkx_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/priest_local_planner_params.yaml b/config/runtime/priest_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/recovery_behaviors_params.yaml b/config/runtime/recovery_behaviors_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/sbpl_global_params.yaml b/config/runtime/sbpl_global_params.yaml old mode 100644 new mode 100755 index dc4d1c0..58d19d8 --- a/config/runtime/sbpl_global_params.yaml +++ b/config/runtime/sbpl_global_params.yaml @@ -12,4 +12,4 @@ SBPLLatticePlanner: free_start_heading: true nominalvel_mpersecs: 0.3 timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s - primitive_filename: /home/duongtd/rl_ws/mir_robot/mir_navigation/mprim/unicycle_highcost_5cm.mprim \ No newline at end of file + primitive_filename: /home/robotics/AGV/Diff_Wheel_Prj/t800_v2_ws/src/pnkx_nav_core/config/runtime/mprim/unicycle_highcost_5cm.mprim \ No newline at end of file diff --git a/config/runtime/stanley_local_planner_params.yaml b/config/runtime/stanley_local_planner_params.yaml old mode 100644 new mode 100755 diff --git a/config/runtime/two_points_global_params.yaml b/config/runtime/two_points_global_params.yaml old mode 100644 new mode 100755 diff --git a/doc/architecture_discussion.md b/doc/architecture_discussion.md old mode 100644 new mode 100755 diff --git a/doc/folders.md b/doc/folders.md old mode 100644 new mode 100755 diff --git a/doc/implementation_plan.md b/doc/implementation_plan.md old mode 100644 new mode 100755 diff --git a/doc/readme.md b/doc/readme.md old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/NavigationAPI.cs b/examples/NavigationExample/NavigationAPI.cs old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/NavigationExample.csproj b/examples/NavigationExample/NavigationExample.csproj old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/Program.cs b/examples/NavigationExample/Program.cs old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/TF3API.cs b/examples/NavigationExample/TF3API.cs old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/maze.png b/examples/NavigationExample/maze.png old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/maze.yaml b/examples/NavigationExample/maze.yaml old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/msgs/CommonMsgs.cs b/examples/NavigationExample/msgs/CommonMsgs.cs old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/msgs/ProtocolMsgsTypes.cs b/examples/NavigationExample/msgs/ProtocolMsgsTypes.cs old mode 100644 new mode 100755 diff --git a/examples/NavigationExample/msgs/SensorMsgs.cs b/examples/NavigationExample/msgs/SensorMsgs.cs old mode 100644 new mode 100755 diff --git a/examples/QUICK_START.md b/examples/QUICK_START.md old mode 100644 new mode 100755 diff --git a/examples/README.md b/examples/README.md old mode 100644 new mode 100755 diff --git a/examples/START_HERE.md b/examples/START_HERE.md old mode 100644 new mode 100755 diff --git a/pnkx_nav_core.sln b/pnkx_nav_core.sln old mode 100644 new mode 100755 diff --git a/robotapp.db b/robotapp.db old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/CMakeLists.txt b/src/APIs/c_api/CMakeLists.txt old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/C_API_AUDIT.md b/src/APIs/c_api/C_API_AUDIT.md old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/NAV_C_API_2_GUIDE.md b/src/APIs/c_api/NAV_C_API_2_GUIDE.md old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/convertor.h b/src/APIs/c_api/include/convertor.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/convertor_2.h b/src/APIs/c_api/include/convertor_2.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Accel.h b/src/APIs/c_api/include/geometry_msgs/Accel.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/AccelStamped.h b/src/APIs/c_api/include/geometry_msgs/AccelStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/AccelWithCovariance.h b/src/APIs/c_api/include/geometry_msgs/AccelWithCovariance.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/AccelWithCovarianceStamped.h b/src/APIs/c_api/include/geometry_msgs/AccelWithCovarianceStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Inertia.h b/src/APIs/c_api/include/geometry_msgs/Inertia.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/InertiaStamped.h b/src/APIs/c_api/include/geometry_msgs/InertiaStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Point.h b/src/APIs/c_api/include/geometry_msgs/Point.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Point32.h b/src/APIs/c_api/include/geometry_msgs/Point32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/PointStamped.h b/src/APIs/c_api/include/geometry_msgs/PointStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Polygon.h b/src/APIs/c_api/include/geometry_msgs/Polygon.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/PolygonStamped.h b/src/APIs/c_api/include/geometry_msgs/PolygonStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Pose.h b/src/APIs/c_api/include/geometry_msgs/Pose.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Pose2D.h b/src/APIs/c_api/include/geometry_msgs/Pose2D.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/PoseArray.h b/src/APIs/c_api/include/geometry_msgs/PoseArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/PoseStamped.h b/src/APIs/c_api/include/geometry_msgs/PoseStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/PoseWithCovariance.h b/src/APIs/c_api/include/geometry_msgs/PoseWithCovariance.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/PoseWithCovarianceStamped.h b/src/APIs/c_api/include/geometry_msgs/PoseWithCovarianceStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Quaternion.h b/src/APIs/c_api/include/geometry_msgs/Quaternion.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/QuaternionStamped.h b/src/APIs/c_api/include/geometry_msgs/QuaternionStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Transform.h b/src/APIs/c_api/include/geometry_msgs/Transform.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/TransformStamped.h b/src/APIs/c_api/include/geometry_msgs/TransformStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Twist.h b/src/APIs/c_api/include/geometry_msgs/Twist.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/TwistStamped.h b/src/APIs/c_api/include/geometry_msgs/TwistStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/TwistWithCovariance.h b/src/APIs/c_api/include/geometry_msgs/TwistWithCovariance.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/TwistWithCovarianceStamped.h b/src/APIs/c_api/include/geometry_msgs/TwistWithCovarianceStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Vector3.h b/src/APIs/c_api/include/geometry_msgs/Vector3.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Vector3Stamped.h b/src/APIs/c_api/include/geometry_msgs/Vector3Stamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/Wrench.h b/src/APIs/c_api/include/geometry_msgs/Wrench.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/geometry_msgs/WrenchStamped.h b/src/APIs/c_api/include/geometry_msgs/WrenchStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/map_msgs/OccupancyGridUpdate.h b/src/APIs/c_api/include/map_msgs/OccupancyGridUpdate.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/ComplexPolygon2D.h b/src/APIs/c_api/include/nav_2d_msgs/ComplexPolygon2D.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/NavGridInfo.h b/src/APIs/c_api/include/nav_2d_msgs/NavGridInfo.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/NavGridOfChars.h b/src/APIs/c_api/include/nav_2d_msgs/NavGridOfChars.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/NavGridOfCharsUpdate.h b/src/APIs/c_api/include/nav_2d_msgs/NavGridOfCharsUpdate.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/NavGridOfDoubles.h b/src/APIs/c_api/include/nav_2d_msgs/NavGridOfDoubles.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/NavGridOfDoublesUpdate.h b/src/APIs/c_api/include/nav_2d_msgs/NavGridOfDoublesUpdate.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Path2D.h b/src/APIs/c_api/include/nav_2d_msgs/Path2D.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Point2D.h b/src/APIs/c_api/include/nav_2d_msgs/Point2D.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Polygon2D.h b/src/APIs/c_api/include/nav_2d_msgs/Polygon2D.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Polygon2DCollection.h b/src/APIs/c_api/include/nav_2d_msgs/Polygon2DCollection.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Polygon2DStamped.h b/src/APIs/c_api/include/nav_2d_msgs/Polygon2DStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Pose2D32.h b/src/APIs/c_api/include/nav_2d_msgs/Pose2D32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Pose2DStamped.h b/src/APIs/c_api/include/nav_2d_msgs/Pose2DStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/SwitchPlugin.h b/src/APIs/c_api/include/nav_2d_msgs/SwitchPlugin.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/SwitchPluginRequest.h b/src/APIs/c_api/include/nav_2d_msgs/SwitchPluginRequest.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/SwitchPluginResponse.h b/src/APIs/c_api/include/nav_2d_msgs/SwitchPluginResponse.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Twist2D.h b/src/APIs/c_api/include/nav_2d_msgs/Twist2D.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Twist2D32.h b/src/APIs/c_api/include/nav_2d_msgs/Twist2D32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/Twist2DStamped.h b/src/APIs/c_api/include/nav_2d_msgs/Twist2DStamped.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_2d_msgs/UIntBounds.h b/src/APIs/c_api/include/nav_2d_msgs/UIntBounds.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_c_api.h b/src/APIs/c_api/include/nav_c_api.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_c_api_2.h b/src/APIs/c_api/include/nav_c_api_2.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/ActionTypes.h b/src/APIs/c_api/include/nav_msgs/ActionTypes.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMap.h b/src/APIs/c_api/include/nav_msgs/GetMap.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapAction.h b/src/APIs/c_api/include/nav_msgs/GetMapAction.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapActionFeedback.h b/src/APIs/c_api/include/nav_msgs/GetMapActionFeedback.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapActionGoal.h b/src/APIs/c_api/include/nav_msgs/GetMapActionGoal.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapActionResult.h b/src/APIs/c_api/include/nav_msgs/GetMapActionResult.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapFeedback.h b/src/APIs/c_api/include/nav_msgs/GetMapFeedback.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapGoal.h b/src/APIs/c_api/include/nav_msgs/GetMapGoal.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapRequest.h b/src/APIs/c_api/include/nav_msgs/GetMapRequest.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapResponse.h b/src/APIs/c_api/include/nav_msgs/GetMapResponse.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetMapResult.h b/src/APIs/c_api/include/nav_msgs/GetMapResult.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetPlan.h b/src/APIs/c_api/include/nav_msgs/GetPlan.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetPlanRequest.h b/src/APIs/c_api/include/nav_msgs/GetPlanRequest.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GetPlanResponse.h b/src/APIs/c_api/include/nav_msgs/GetPlanResponse.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/GridCells.h b/src/APIs/c_api/include/nav_msgs/GridCells.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/LoadMap.h b/src/APIs/c_api/include/nav_msgs/LoadMap.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/LoadMapRequest.h b/src/APIs/c_api/include/nav_msgs/LoadMapRequest.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/LoadMapResponse.h b/src/APIs/c_api/include/nav_msgs/LoadMapResponse.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/MapMetaData.h b/src/APIs/c_api/include/nav_msgs/MapMetaData.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/OccupancyGrid.h b/src/APIs/c_api/include/nav_msgs/OccupancyGrid.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/Odometry.h b/src/APIs/c_api/include/nav_msgs/Odometry.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/Path.h b/src/APIs/c_api/include/nav_msgs/Path.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/SetMap.h b/src/APIs/c_api/include/nav_msgs/SetMap.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/SetMapRequest.h b/src/APIs/c_api/include/nav_msgs/SetMapRequest.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/nav_msgs/SetMapResponse.h b/src/APIs/c_api/include/nav_msgs/SetMapResponse.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Action.h b/src/APIs/c_api/include/protocol_msgs/Action.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/ActionParameter.h b/src/APIs/c_api/include/protocol_msgs/ActionParameter.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/ControlPoint.h b/src/APIs/c_api/include/protocol_msgs/ControlPoint.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Edge.h b/src/APIs/c_api/include/protocol_msgs/Edge.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Error.h b/src/APIs/c_api/include/protocol_msgs/Error.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/ErrorReference.h b/src/APIs/c_api/include/protocol_msgs/ErrorReference.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Info.h b/src/APIs/c_api/include/protocol_msgs/Info.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/InfoReference.h b/src/APIs/c_api/include/protocol_msgs/InfoReference.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Information.h b/src/APIs/c_api/include/protocol_msgs/Information.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Node.h b/src/APIs/c_api/include/protocol_msgs/Node.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/NodePosition.h b/src/APIs/c_api/include/protocol_msgs/NodePosition.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Order.h b/src/APIs/c_api/include/protocol_msgs/Order.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/protocol_msgs/Trajectory.h b/src/APIs/c_api/include/protocol_msgs/Trajectory.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/BatteryState.h b/src/APIs/c_api/include/sensor_msgs/BatteryState.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/CameraInfo.h b/src/APIs/c_api/include/sensor_msgs/CameraInfo.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/ChannelFloat32.h b/src/APIs/c_api/include/sensor_msgs/ChannelFloat32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/CompressedImage.h b/src/APIs/c_api/include/sensor_msgs/CompressedImage.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/DepthCameraData.h b/src/APIs/c_api/include/sensor_msgs/DepthCameraData.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/FluidPressure.h b/src/APIs/c_api/include/sensor_msgs/FluidPressure.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/Illuminance.h b/src/APIs/c_api/include/sensor_msgs/Illuminance.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/Image.h b/src/APIs/c_api/include/sensor_msgs/Image.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/Imu.h b/src/APIs/c_api/include/sensor_msgs/Imu.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/JointState.h b/src/APIs/c_api/include/sensor_msgs/JointState.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/Joy.h b/src/APIs/c_api/include/sensor_msgs/Joy.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/JoyFeedback.h b/src/APIs/c_api/include/sensor_msgs/JoyFeedback.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/JoyFeedbackArray.h b/src/APIs/c_api/include/sensor_msgs/JoyFeedbackArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/LaserEcho.h b/src/APIs/c_api/include/sensor_msgs/LaserEcho.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/LaserScan.h b/src/APIs/c_api/include/sensor_msgs/LaserScan.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/MultiEchoLaserScan.h b/src/APIs/c_api/include/sensor_msgs/MultiEchoLaserScan.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/PointCloud.h b/src/APIs/c_api/include/sensor_msgs/PointCloud.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/PointCloud2.h b/src/APIs/c_api/include/sensor_msgs/PointCloud2.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/PointField.h b/src/APIs/c_api/include/sensor_msgs/PointField.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/Range.h b/src/APIs/c_api/include/sensor_msgs/Range.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/RegionOfInterest.h b/src/APIs/c_api/include/sensor_msgs/RegionOfInterest.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/RelativeHumidity.h b/src/APIs/c_api/include/sensor_msgs/RelativeHumidity.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/Temperature.h b/src/APIs/c_api/include/sensor_msgs/Temperature.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/sensor_msgs/TimeReference.h b/src/APIs/c_api/include/sensor_msgs/TimeReference.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Bool.h b/src/APIs/c_api/include/std_msgs/Bool.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Byte.h b/src/APIs/c_api/include/std_msgs/Byte.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/ByteMultiArray.h b/src/APIs/c_api/include/std_msgs/ByteMultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Char.h b/src/APIs/c_api/include/std_msgs/Char.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/ColorRGBA.h b/src/APIs/c_api/include/std_msgs/ColorRGBA.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Duration.h b/src/APIs/c_api/include/std_msgs/Duration.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Empty.h b/src/APIs/c_api/include/std_msgs/Empty.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Float32.h b/src/APIs/c_api/include/std_msgs/Float32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Float32MultiArray.h b/src/APIs/c_api/include/std_msgs/Float32MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Float64.h b/src/APIs/c_api/include/std_msgs/Float64.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Float64MultiArray.h b/src/APIs/c_api/include/std_msgs/Float64MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Header.h b/src/APIs/c_api/include/std_msgs/Header.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int16.h b/src/APIs/c_api/include/std_msgs/Int16.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int16MultiArray.h b/src/APIs/c_api/include/std_msgs/Int16MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int32.h b/src/APIs/c_api/include/std_msgs/Int32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int32MultiArray.h b/src/APIs/c_api/include/std_msgs/Int32MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int64.h b/src/APIs/c_api/include/std_msgs/Int64.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int64MultiArray.h b/src/APIs/c_api/include/std_msgs/Int64MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int8.h b/src/APIs/c_api/include/std_msgs/Int8.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Int8MultiArray.h b/src/APIs/c_api/include/std_msgs/Int8MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/MultiArrayDimension.h b/src/APIs/c_api/include/std_msgs/MultiArrayDimension.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/MultiArrayLayout.h b/src/APIs/c_api/include/std_msgs/MultiArrayLayout.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/String.h b/src/APIs/c_api/include/std_msgs/String.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/Time.h b/src/APIs/c_api/include/std_msgs/Time.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt16.h b/src/APIs/c_api/include/std_msgs/UInt16.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt16MultiArray.h b/src/APIs/c_api/include/std_msgs/UInt16MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt32.h b/src/APIs/c_api/include/std_msgs/UInt32.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt32MultiArray.h b/src/APIs/c_api/include/std_msgs/UInt32MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt64.h b/src/APIs/c_api/include/std_msgs/UInt64.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt64MultiArray.h b/src/APIs/c_api/include/std_msgs/UInt64MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt8.h b/src/APIs/c_api/include/std_msgs/UInt8.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/include/std_msgs/UInt8MultiArray.h b/src/APIs/c_api/include/std_msgs/UInt8MultiArray.h old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/nav-c-api-2-csharp-integration-report.md b/src/APIs/c_api/nav-c-api-2-csharp-integration-report.md old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/src/convertor.cpp b/src/APIs/c_api/src/convertor.cpp old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/src/convertor_2.cpp b/src/APIs/c_api/src/convertor_2.cpp old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/src/nav_c_api.cpp b/src/APIs/c_api/src/nav_c_api.cpp old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/src/nav_c_api_2.cpp b/src/APIs/c_api/src/nav_c_api_2.cpp old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/src/std_msgs/Header.cpp b/src/APIs/c_api/src/std_msgs/Header.cpp old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/src/std_msgs/Time.cpp b/src/APIs/c_api/src/std_msgs/Time.cpp old mode 100644 new mode 100755 diff --git a/src/APIs/c_api/test/test_convertor.cpp b/src/APIs/c_api/test/test_convertor.cpp old mode 100644 new mode 100755 diff --git a/src/Algorithms/Cores/score_algorithm/CMakeLists.txt b/src/Algorithms/Cores/score_algorithm/CMakeLists.txt index 7b0869a..12f6753 100644 --- a/src/Algorithms/Cores/score_algorithm/CMakeLists.txt +++ b/src/Algorithms/Cores/score_algorithm/CMakeLists.txt @@ -1,162 +1,162 @@ -cmake_minimum_required(VERSION 3.0.2) -project(score_algorithm VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building score_algorithm with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building score_algorithm with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -# Find dependencies -find_package(Boost REQUIRED COMPONENTS filesystem system) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - - set(PACKAGES_DIR - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core2 - robot_nav_core - robot_cpp - mkt_msgs - angles - ) - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED COMPONENTS - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core2 - robot_nav_core - robot_cpp - mkt_msgs - angles - ) - - catkin_package( - INCLUDE_DIRS include - LIBRARIES ${PROJECT_NAME} - CATKIN_DEPENDS robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core robot_nav_core2 robot_cpp mkt_msgs angles - DEPENDS Boost - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ) -endif() - -# Libraries -add_library(${PROJECT_NAME} SHARED - src/score_algorithm.cpp -) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - target_compile_definitions(${PROJECT_NAME} - PUBLIC BUILD_WITH_ROS - ) - - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME} - PUBLIC ${catkin_LIBRARIES} - PRIVATE Boost::filesystem Boost::system - ) - -else() - - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME} - PUBLIC - ${PACKAGES_DIR} - PRIVATE - Boost::filesystem Boost::system - ) - - set_target_properties(${PROJECT_NAME} PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - -endif() - -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME} - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - -else() - - install(TARGETS ${PROJECT_NAME} - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME}") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Dependencies: robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core, robot_nav_core2, robot_cpp, mkt_msgs, angles, Boost") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(score_algorithm VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building score_algorithm with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building score_algorithm with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Find dependencies +find_package(Boost REQUIRED COMPONENTS filesystem system) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + set(PACKAGES_DIR + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core2 + robot_nav_core + robot_cpp + mkt_msgs + angles + ) + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED COMPONENTS + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core2 + robot_nav_core + robot_cpp + mkt_msgs + angles + ) + + catkin_package( + INCLUDE_DIRS include + LIBRARIES ${PROJECT_NAME} + CATKIN_DEPENDS robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core robot_nav_core2 robot_cpp mkt_msgs angles + DEPENDS Boost + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) +endif() + +# Libraries +add_library(${PROJECT_NAME} SHARED + src/score_algorithm.cpp +) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + target_compile_definitions(${PROJECT_NAME} + PUBLIC BUILD_WITH_ROS + ) + + target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME} + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::filesystem Boost::system + ) + +else() + + target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME} + PUBLIC + ${PACKAGES_DIR} + PRIVATE + Boost::filesystem Boost::system + ) + + set_target_properties(${PROJECT_NAME} PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + +endif() + +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME} + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + +else() + + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME}") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Dependencies: robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core, robot_nav_core2, robot_cpp, mkt_msgs, angles, Boost") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Cores/score_algorithm/README.md b/src/Algorithms/Cores/score_algorithm/README.md index b86fc66..1a17519 100644 --- a/src/Algorithms/Cores/score_algorithm/README.md +++ b/src/Algorithms/Cores/score_algorithm/README.md @@ -1,44 +1,44 @@ -# score_algorithm - -## Giới thiệu -`score_algorithm` là lớp nền (base class) cho các thuật toán đánh giá và sinh lệnh điều khiển (local planning) trong `pnkx_nav_core`. Module này không tự sinh quỹ đạo cụ thể, mà cung cấp bộ khung và các hàm dùng chung để các thuật toán con triển khai. - -## Vai trò chính -- Chuẩn hóa giao diện (interface) cho các thuật toán tính toán quỹ đạo/lệnh. -- Cắt đoạn `global_plan` thành đoạn con phù hợp với `local costmap`. -- Chọn `sub-goal` và `start` để theo đuổi theo từng bước đường đi. -- Cung cấp các hàm tiện ích: kiểm tra dừng/đi, tính quãng đường, tìm mục tiêu theo góc và khoảng cách. - -## API chính -Được khai báo trong `include/score_algorithm/score_algorithm.h`: -- `initialize(...)`: khởi tạo tham số, TF, costmap, bộ sinh quỹ đạo. -- `prepare(...)`: chuẩn bị dữ liệu dùng chung trước khi đánh giá. -- `calculator(...)`: tính toán ra `mkt_msgs::Trajectory2D`. -- `computePlanCommand(...)`: cắt `global_plan` thành đoạn kết quả và chọn `start/goal`. -- `findSubGoalIndex(...)`, `getGoalIndex(...)`, `journey(...)`, `stopped(...)`: hàm phụ trợ. - -## Nguyên lý `computePlanCommand(...)` -Hàm này nhận `robot_pose`, `velocity`, độ dài xem trước `S` và `global_plan`, sau đó: -1) Tìm các mốc `sub-goal` (đổi hướng / điểm gãy) bằng `findSubGoalIndex`. -2) Khôi phục `sub_goal_index` và `sub_start_index` đã lưu (nếu có), cập nhật nếu robot đang dừng và đã vượt mốc. -3) Tìm `start_index` gần nhất với robot trong đoạn con hợp lệ. -4) Tìm `goal_index` dựa trên quy tắc "đi đủ xa `S` hoặc đổi hướng vượt ngưỡng". -5) Xuất `result` là đoạn từ `closet_index` đến `goal_index`. - -Kết quả được sử dụng bởi các local planner để sinh lệnh điều khiển tiếp theo. - -## Sử dụng trong hệ thống -`score_algorithm` được nạp qua pluginlib trong các local planner, ví dụ: -- `pnkx_local_planner` -- `pnkx_go_straight_local_planner` -- `pnkx_rotate_local_planner` -- `pnkx_docking_local_planner` - -Mỗi thuật toán cụ thể sẽ kế thừa `ScoreAlgorithm` và triển khai `initialize`, `prepare`, `calculator`. - -## Thư mục liên quan -- `include/score_algorithm/score_algorithm.h`: giao diện chính. -- `src/score_algorithm.cpp`: các hàm dùng chung (getGoalIndex, computePlanCommand, ...). - -## Ghi chú -Module này phụ thuộc vào `robot_nav_2d_msgs`, `robot_costmap_2d`, `mkt_msgs` và hệ thống TF/ROS. +# score_algorithm + +## Giới thiệu +`score_algorithm` là lớp nền (base class) cho các thuật toán đánh giá và sinh lệnh điều khiển (local planning) trong `pnkx_nav_core`. Module này không tự sinh quỹ đạo cụ thể, mà cung cấp bộ khung và các hàm dùng chung để các thuật toán con triển khai. + +## Vai trò chính +- Chuẩn hóa giao diện (interface) cho các thuật toán tính toán quỹ đạo/lệnh. +- Cắt đoạn `global_plan` thành đoạn con phù hợp với `local costmap`. +- Chọn `sub-goal` và `start` để theo đuổi theo từng bước đường đi. +- Cung cấp các hàm tiện ích: kiểm tra dừng/đi, tính quãng đường, tìm mục tiêu theo góc và khoảng cách. + +## API chính +Được khai báo trong `include/score_algorithm/score_algorithm.h`: +- `initialize(...)`: khởi tạo tham số, TF, costmap, bộ sinh quỹ đạo. +- `prepare(...)`: chuẩn bị dữ liệu dùng chung trước khi đánh giá. +- `calculator(...)`: tính toán ra `mkt_msgs::Trajectory2D`. +- `computePlanCommand(...)`: cắt `global_plan` thành đoạn kết quả và chọn `start/goal`. +- `findSubGoalIndex(...)`, `getGoalIndex(...)`, `journey(...)`, `stopped(...)`: hàm phụ trợ. + +## Nguyên lý `computePlanCommand(...)` +Hàm này nhận `robot_pose`, `velocity`, độ dài xem trước `S` và `global_plan`, sau đó: +1) Tìm các mốc `sub-goal` (đổi hướng / điểm gãy) bằng `findSubGoalIndex`. +2) Khôi phục `sub_goal_index` và `sub_start_index` đã lưu (nếu có), cập nhật nếu robot đang dừng và đã vượt mốc. +3) Tìm `start_index` gần nhất với robot trong đoạn con hợp lệ. +4) Tìm `goal_index` dựa trên quy tắc "đi đủ xa `S` hoặc đổi hướng vượt ngưỡng". +5) Xuất `result` là đoạn từ `closet_index` đến `goal_index`. + +Kết quả được sử dụng bởi các local planner để sinh lệnh điều khiển tiếp theo. + +## Sử dụng trong hệ thống +`score_algorithm` được nạp qua pluginlib trong các local planner, ví dụ: +- `pnkx_local_planner` +- `pnkx_go_straight_local_planner` +- `pnkx_rotate_local_planner` +- `pnkx_docking_local_planner` + +Mỗi thuật toán cụ thể sẽ kế thừa `ScoreAlgorithm` và triển khai `initialize`, `prepare`, `calculator`. + +## Thư mục liên quan +- `include/score_algorithm/score_algorithm.h`: giao diện chính. +- `src/score_algorithm.cpp`: các hàm dùng chung (getGoalIndex, computePlanCommand, ...). + +## Ghi chú +Module này phụ thuộc vào `robot_nav_2d_msgs`, `robot_costmap_2d`, `mkt_msgs` và hệ thống TF/ROS. diff --git a/src/Algorithms/Cores/score_algorithm/include/score_algorithm/goal_checker.h b/src/Algorithms/Cores/score_algorithm/include/score_algorithm/goal_checker.h old mode 100755 new mode 100644 index 3322dee..718e52f --- a/src/Algorithms/Cores/score_algorithm/include/score_algorithm/goal_checker.h +++ b/src/Algorithms/Cores/score_algorithm/include/score_algorithm/goal_checker.h @@ -1,56 +1,56 @@ -#ifndef _SCORE_GOAL_CHECKER_H_INCLUDED__ -#define _SCORE_GOAL_CHECKER_H_INCLUDED__ - -#include -#include -#include -#include -#include -#include -#include - -namespace score_algorithm -{ - - /** - * @class GoalChecker - * @brief Function-object for checking whether a goal has been reached - * - * This class defines the plugin interface for determining whether you have reached - * the goal state. This primarily consists of checking the relative positions of two poses - * (which are presumed to be in the same frame). It can also check the velocity, as some - * applications require that robot be stopped to be considered as having reached the goal. - */ - class GoalChecker - { - public: - using Ptr = std::shared_ptr; - - virtual ~GoalChecker() {} - - /** - * @brief Initialize any parameters from the NodeHandle - * @param nh NodeHandle for grabbing parameters - */ - virtual void initialize(const robot::NodeHandle& nh) = 0; - - /** - * @brief Reset the state of the goal checker (if any) - */ - virtual void reset() {} - - /** - * @brief Check whether the goal should be considered reached - * @param query_pose The pose to check - * @param goal_pose The pose to check against - * - * @param velocity The robot's current velocity - * @return True if goal is reached - */ - virtual bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& query_pose, const robot_nav_2d_msgs::Pose2DStamped& goal_pose, - const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D& velocity) = 0; - }; - -} // namespace score_algorithm - +#ifndef _SCORE_GOAL_CHECKER_H_INCLUDED__ +#define _SCORE_GOAL_CHECKER_H_INCLUDED__ + +#include +#include +#include +#include +#include +#include +#include + +namespace score_algorithm +{ + + /** + * @class GoalChecker + * @brief Function-object for checking whether a goal has been reached + * + * This class defines the plugin interface for determining whether you have reached + * the goal state. This primarily consists of checking the relative positions of two poses + * (which are presumed to be in the same frame). It can also check the velocity, as some + * applications require that robot be stopped to be considered as having reached the goal. + */ + class GoalChecker + { + public: + using Ptr = std::shared_ptr; + + virtual ~GoalChecker() {} + + /** + * @brief Initialize any parameters from the NodeHandle + * @param nh NodeHandle for grabbing parameters + */ + virtual void initialize(const robot::NodeHandle& nh) = 0; + + /** + * @brief Reset the state of the goal checker (if any) + */ + virtual void reset() {} + + /** + * @brief Check whether the goal should be considered reached + * @param query_pose The pose to check + * @param goal_pose The pose to check against + * + * @param velocity The robot's current velocity + * @return True if goal is reached + */ + virtual bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& query_pose, const robot_nav_2d_msgs::Pose2DStamped& goal_pose, + const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D& velocity) = 0; + }; + +} // namespace score_algorithm + #endif // _SCORE_GOAL_CHECKER_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Cores/score_algorithm/include/score_algorithm/score_algorithm.h b/src/Algorithms/Cores/score_algorithm/include/score_algorithm/score_algorithm.h old mode 100755 new mode 100644 index e5c72fd..ae5d711 --- a/src/Algorithms/Cores/score_algorithm/include/score_algorithm/score_algorithm.h +++ b/src/Algorithms/Cores/score_algorithm/include/score_algorithm/score_algorithm.h @@ -1,178 +1,178 @@ -#ifndef _SCORE_ALGORITHM_H_INCLUDED__ -#define _SCORE_ALGORITHM_H_INCLUDED__ - -#ifdef BUILD_WITH_ROS -#include -#include -#endif -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -#define FORWARD 1 -#define BACKWARD -1 - -namespace score_algorithm -{ - class ScoreAlgorithm - { - public: - using Ptr = std::shared_ptr; - - inline double smoothstep(double x) - { - x = std::clamp(x, 0.0, 1.0); - return x * x * (3 - 2 * x); - } - - /** - * @brief Initialize parameters as needed - * @param name Namespace for this planner - * @param tf TFListener pointer - * @param costmap_robot Costmap pointer - */ - virtual void initialize(robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, - const score_algorithm::TrajectoryGenerator::Ptr &traj) = 0; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, - double &x_direction, double &y_direction, double &theta_direction) = 0; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - * @param traj - */ - virtual mkt_msgs::Trajectory2D calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) = 0; - - /** - * @brief Reset all data - */ - virtual void reset() {}; - - /** - * @brief Stoping move navigation - */ - virtual void stop() {}; - - /** - * @brief resume move navigation after stopped - */ - virtual void resume() {}; - - std::string getName() - { - return name_; - } - - protected: - double sign(double x) - { - return x < 0.0 ? -1.0 : 1.0; - } - - /** - * @brief Get goal index - * @param robot_pose - * @param plan - * @param distance - * @param start_index - * @param last_valid_index - * @return goal index - */ - virtual unsigned int getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, - const double distance, unsigned int start_index, unsigned int last_valid_index) const; - - /** - * @brief Get goal pose - * @param robot_pose - * @param velocity - * @param global_plan - * @param sub_goal - * @param S - * @return true if goal pose is found, false otherwise - */ - virtual bool computePlanCommand(const robot_nav_2d_msgs::Pose2DStamped &robot_pose, const robot_nav_2d_msgs::Twist2D &velocity, const double &S, - const robot_nav_2d_msgs::Path2D &global_plan, unsigned int &start_index_global_plan, unsigned int &goal_index_global_plan, robot_nav_2d_msgs::Path2D &result); - - /** - * @brief Find sub goal index - * @param plan - * @param index_s - * @return true if sub goal index is found, false otherwise - */ - virtual bool findSubGoalIndex(const std::vector &plan, std::vector &seq_s, std::vector &mutes); - - /** - * @brief Calculate journey - * @param plan - * @param start_index - * @param last_valid_index - * @return journey - */ - double journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const; - - /** - * @brief Check whether the robot is stopped or not - * @param velocity The current odometry information for the robot - * @param rot_stopped_velocity The rotational velocity below which the robot is considered stopped - * @param trans_stopped_velocity The translational velocity below which the robot is considered stopped - * @return True if the robot is stopped, false otherwise - */ - bool stopped(const robot_nav_2d_msgs::Twist2D &velocity, const double &rot_stopped_velocity, const double &trans_stopped_velocity); - - void clear(); - - std::string name_; - TFListenerPtr tf_; - robot_costmap_2d::Costmap2DROBOT *costmap_robot_; - TrajectoryGenerator::Ptr traj_; - - int index_samples_; - bool follow_step_path_; - double xy_local_goal_tolerance_; - double old_xy_goal_tolerance_; - double angle_threshold_; - -#ifdef BUILD_WITH_ROS - ros::Publisher current_goal_pub_; - ros::Publisher closet_robot_goal_pub_; -#endif - - std::vector reached_intermediate_goals_; - std::vector start_index_saved_vt_; - unsigned int sub_goal_index_saved_, sub_goal_seq_saved_; - unsigned int sub_start_index_saved_, sub_start_seq_saved_; - - double max_vel_x_, min_vel_x_, acc_lim_x_, decel_lim_x_; - double max_vel_y_, min_vel_y_, acc_lim_y_, decel_lim_y_; - double max_vel_theta_, min_vel_theta_, acc_lim_theta_, decel_lim_theta_; - double min_speed_xy_, max_speed_xy_; - double rot_stopped_velocity_, trans_stopped_velocity_; - }; -} // namespace score_algorithm - +#ifndef _SCORE_ALGORITHM_H_INCLUDED__ +#define _SCORE_ALGORITHM_H_INCLUDED__ + +#ifdef BUILD_WITH_ROS +#include +#include +#endif +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#define FORWARD 1 +#define BACKWARD -1 + +namespace score_algorithm +{ + class ScoreAlgorithm + { + public: + using Ptr = std::shared_ptr; + + inline double smoothstep(double x) + { + x = std::clamp(x, 0.0, 1.0); + return x * x * (3 - 2 * x); + } + + /** + * @brief Initialize parameters as needed + * @param name Namespace for this planner + * @param tf TFListener pointer + * @param costmap_robot Costmap pointer + */ + virtual void initialize(robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, + const score_algorithm::TrajectoryGenerator::Ptr &traj) = 0; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, + double &x_direction, double &y_direction, double &theta_direction) = 0; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + * @param traj + */ + virtual mkt_msgs::Trajectory2D calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) = 0; + + /** + * @brief Reset all data + */ + virtual void reset() {}; + + /** + * @brief Stoping move navigation + */ + virtual void stop() {}; + + /** + * @brief resume move navigation after stopped + */ + virtual void resume() {}; + + std::string getName() + { + return name_; + } + + protected: + double sign(double x) + { + return x < 0.0 ? -1.0 : 1.0; + } + + /** + * @brief Get goal index + * @param robot_pose + * @param plan + * @param distance + * @param start_index + * @param last_valid_index + * @return goal index + */ + virtual unsigned int getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, + const double distance, unsigned int start_index, unsigned int last_valid_index) const; + + /** + * @brief Get goal pose + * @param robot_pose + * @param velocity + * @param global_plan + * @param sub_goal + * @param S + * @return true if goal pose is found, false otherwise + */ + virtual bool computePlanCommand(const robot_nav_2d_msgs::Pose2DStamped &robot_pose, const robot_nav_2d_msgs::Twist2D &velocity, const double &S, + const robot_nav_2d_msgs::Path2D &global_plan, unsigned int &start_index_global_plan, unsigned int &goal_index_global_plan, robot_nav_2d_msgs::Path2D &result); + + /** + * @brief Find sub goal index + * @param plan + * @param index_s + * @return true if sub goal index is found, false otherwise + */ + virtual bool findSubGoalIndex(const std::vector &plan, std::vector &seq_s, std::vector &mutes); + + /** + * @brief Calculate journey + * @param plan + * @param start_index + * @param last_valid_index + * @return journey + */ + double journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const; + + /** + * @brief Check whether the robot is stopped or not + * @param velocity The current odometry information for the robot + * @param rot_stopped_velocity The rotational velocity below which the robot is considered stopped + * @param trans_stopped_velocity The translational velocity below which the robot is considered stopped + * @return True if the robot is stopped, false otherwise + */ + bool stopped(const robot_nav_2d_msgs::Twist2D &velocity, const double &rot_stopped_velocity, const double &trans_stopped_velocity); + + void clear(); + + std::string name_; + TFListenerPtr tf_; + robot_costmap_2d::Costmap2DROBOT *costmap_robot_; + TrajectoryGenerator::Ptr traj_; + + int index_samples_; + bool follow_step_path_; + double xy_local_goal_tolerance_; + double old_xy_goal_tolerance_; + double angle_threshold_; + +#ifdef BUILD_WITH_ROS + ros::Publisher current_goal_pub_; + ros::Publisher closet_robot_goal_pub_; +#endif + + std::vector reached_intermediate_goals_; + std::vector start_index_saved_vt_; + unsigned int sub_goal_index_saved_, sub_goal_seq_saved_; + unsigned int sub_start_index_saved_, sub_start_seq_saved_; + + double max_vel_x_, min_vel_x_, acc_lim_x_, decel_lim_x_; + double max_vel_y_, min_vel_y_, acc_lim_y_, decel_lim_y_; + double max_vel_theta_, min_vel_theta_, acc_lim_theta_, decel_lim_theta_; + double min_speed_xy_, max_speed_xy_; + double rot_stopped_velocity_, trans_stopped_velocity_; + }; +} // namespace score_algorithm + #endif // SCORE_ALGORITHM_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Cores/score_algorithm/include/score_algorithm/trajectory_generator.h b/src/Algorithms/Cores/score_algorithm/include/score_algorithm/trajectory_generator.h old mode 100755 new mode 100644 index 8dcb577..654e20e --- a/src/Algorithms/Cores/score_algorithm/include/score_algorithm/trajectory_generator.h +++ b/src/Algorithms/Cores/score_algorithm/include/score_algorithm/trajectory_generator.h @@ -1,143 +1,143 @@ -#ifndef _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H -#define _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace score_algorithm -{ - - /** - * @class TrajectoryGenerator - * @brief Interface for iterating through possible velocities and creating trajectories - * - * This class defines the plugin interface for two separate but related components. - * - * First, this class provides an iterator interface for exploring all of the velocities - * to search, given the current velocity. - * - * Second, the class gives an independent interface for creating a trajectory from a twist, - * i.e. projecting it out in time and space. - * - * Both components rely heavily on the robot's kinematic model, and can share many parameters, - * which is why they are grouped into a singular class. - */ - class TrajectoryGenerator - { - public: - using Ptr = std::shared_ptr; - - virtual ~TrajectoryGenerator() {} - - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize(const robot::NodeHandle &nh) = 0; - - /** - * @brief Reset the state (if any) when the planner gets a new goal - */ - virtual void reset() {} - - /** - * @brief Start a new iteration based on the current velocity - * @param current_velocity - */ - virtual void startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) = 0; - - /** - * @brief Set direct of robot based on the current velocity - * @param direct - */ - virtual void setDirect(int *xytheta_direct) = 0; - - /** - * @brief set velocity for x, y asix of the robot - * @param linear the velocity command - * @return True if set is done, false otherwise - */ - virtual bool setTwistLinear(robot_geometry_msgs::Vector3 linear) = 0; - - /** - * @brief get velocity for x, y asix of the robot - * @param linear The velocity command - * @return True if set is done, false otherwise - */ - virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) = 0; - - /** - * @brief Set velocity theta for z asix of the robot - * @param angular the command velocity - * @return True if set is done, false otherwise - */ - virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) = 0; - - /** - * @brief Get velocity theta for z asix of the robot - * @param direct The velocity command - * @return True if set is done, false otherwise - */ - virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) = 0; - - /** - * @brief Test to see whether there are more twists to test - * @return True if more twists, false otherwise - */ - virtual bool hasMoreTwists() = 0; - - /** - * @brief Return the next twist and advance the iteration - * @return The Twist! - */ - virtual robot_nav_2d_msgs::Twist2D nextTwist() = 0; - - /** - * @brief Get the current twist - * @return The current twist - */ - virtual robot_nav_2d_msgs::Twist2D getTwist() = 0; - - /** - * @brief Get all the twists for an iteration. - * - * Note: Resets the iterator if one is in process - * - * @param current_velocity - * @return all the twists - */ - virtual std::vector getTwists(const robot_nav_2d_msgs::Twist2D ¤t_velocity) - { - std::vector twists; - startNewIteration(current_velocity); - while (hasMoreTwists()) - { - twists.push_back(nextTwist()); - } - return twists; - } - - /** - * @brief Given a cmd_vel in the robot's frame and initial conditions, generate a Trajectory2D - * @param start_pose Current robot location - * @param start_vel Current robot velocity - * @param cmd_vel The desired command velocity - */ - virtual mkt_msgs::Trajectory2D generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose, - const robot_nav_2d_msgs::Path2D &transformed_plan, - const robot_nav_2d_msgs::Twist2D &start_vel, - const robot_nav_2d_msgs::Twist2D &cmd_vel) = 0; - - virtual robot::NodeHandle getNodeHandle() = 0; - - }; - -} // namespace score_algorithm - -#endif // _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H +#ifndef _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H +#define _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace score_algorithm +{ + + /** + * @class TrajectoryGenerator + * @brief Interface for iterating through possible velocities and creating trajectories + * + * This class defines the plugin interface for two separate but related components. + * + * First, this class provides an iterator interface for exploring all of the velocities + * to search, given the current velocity. + * + * Second, the class gives an independent interface for creating a trajectory from a twist, + * i.e. projecting it out in time and space. + * + * Both components rely heavily on the robot's kinematic model, and can share many parameters, + * which is why they are grouped into a singular class. + */ + class TrajectoryGenerator + { + public: + using Ptr = std::shared_ptr; + + virtual ~TrajectoryGenerator() {} + + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize(const robot::NodeHandle &nh) = 0; + + /** + * @brief Reset the state (if any) when the planner gets a new goal + */ + virtual void reset() {} + + /** + * @brief Start a new iteration based on the current velocity + * @param current_velocity + */ + virtual void startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) = 0; + + /** + * @brief Set direct of robot based on the current velocity + * @param direct + */ + virtual void setDirect(int *xytheta_direct) = 0; + + /** + * @brief set velocity for x, y asix of the robot + * @param linear the velocity command + * @return True if set is done, false otherwise + */ + virtual bool setTwistLinear(robot_geometry_msgs::Vector3 linear) = 0; + + /** + * @brief get velocity for x, y asix of the robot + * @param linear The velocity command + * @return True if set is done, false otherwise + */ + virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) = 0; + + /** + * @brief Set velocity theta for z asix of the robot + * @param angular the command velocity + * @return True if set is done, false otherwise + */ + virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) = 0; + + /** + * @brief Get velocity theta for z asix of the robot + * @param direct The velocity command + * @return True if set is done, false otherwise + */ + virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) = 0; + + /** + * @brief Test to see whether there are more twists to test + * @return True if more twists, false otherwise + */ + virtual bool hasMoreTwists() = 0; + + /** + * @brief Return the next twist and advance the iteration + * @return The Twist! + */ + virtual robot_nav_2d_msgs::Twist2D nextTwist() = 0; + + /** + * @brief Get the current twist + * @return The current twist + */ + virtual robot_nav_2d_msgs::Twist2D getTwist() = 0; + + /** + * @brief Get all the twists for an iteration. + * + * Note: Resets the iterator if one is in process + * + * @param current_velocity + * @return all the twists + */ + virtual std::vector getTwists(const robot_nav_2d_msgs::Twist2D ¤t_velocity) + { + std::vector twists; + startNewIteration(current_velocity); + while (hasMoreTwists()) + { + twists.push_back(nextTwist()); + } + return twists; + } + + /** + * @brief Given a cmd_vel in the robot's frame and initial conditions, generate a Trajectory2D + * @param start_pose Current robot location + * @param start_vel Current robot velocity + * @param cmd_vel The desired command velocity + */ + virtual mkt_msgs::Trajectory2D generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose, + const robot_nav_2d_msgs::Path2D &transformed_plan, + const robot_nav_2d_msgs::Twist2D &start_vel, + const robot_nav_2d_msgs::Twist2D &cmd_vel) = 0; + + virtual robot::NodeHandle getNodeHandle() = 0; + + }; + +} // namespace score_algorithm + +#endif // _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H diff --git a/src/Algorithms/Cores/score_algorithm/package.xml b/src/Algorithms/Cores/score_algorithm/package.xml index f607334..672fcc0 100644 --- a/src/Algorithms/Cores/score_algorithm/package.xml +++ b/src/Algorithms/Cores/score_algorithm/package.xml @@ -1,37 +1,37 @@ - - score_algorithm - 0.7.10 - - score_algorithm is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. score_algorithm - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/score_algorithm - - catkin - - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core - robot_nav_core2 - robot_cpp - mkt_msgs - angles - - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core - robot_nav_core2 - robot_cpp - mkt_msgs - angles + + score_algorithm + 0.7.10 + + score_algorithm is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. score_algorithm + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/score_algorithm + + catkin + + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core + robot_nav_core2 + robot_cpp + mkt_msgs + angles + + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core + robot_nav_core2 + robot_cpp + mkt_msgs + angles \ No newline at end of file diff --git a/src/Algorithms/Cores/score_algorithm/src/score_algorithm.cpp b/src/Algorithms/Cores/score_algorithm/src/score_algorithm.cpp index 770b81f..1998165 100644 --- a/src/Algorithms/Cores/score_algorithm/src/score_algorithm.cpp +++ b/src/Algorithms/Cores/score_algorithm/src/score_algorithm.cpp @@ -1,487 +1,486 @@ -#include -#include -#include -#include -#include - -unsigned int score_algorithm::ScoreAlgorithm::getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, - const double distance, unsigned int start_index, unsigned int last_valid_index) const -{ - if (start_index >= last_valid_index) - return last_valid_index; - - unsigned int goal_index = start_index + 1; - const double start_direction_x = plan[goal_index].pose.x - plan[start_index].pose.x; - const double start_direction_y = plan[goal_index].pose.y - plan[start_index].pose.y; - if (fabs(start_direction_x) > 1e-9 || fabs(start_direction_y) > 1e-9) - { // make sure that atan2 is defined - double start_angle = atan2(start_direction_y, start_direction_x); - double S = sqrt(pow(start_direction_x, 2) + pow(start_direction_y, 2)); - // double angle_threshold = 0.0; - for (unsigned int i = start_index + 1; i <= last_valid_index; i++) - { - const double current_direction_x = plan[i].pose.x - plan[i - 1].pose.x; - const double current_direction_y = plan[i].pose.y - plan[i - 1].pose.y; - const double dd = sqrt(pow(current_direction_x, 2) + pow(current_direction_y, 2)); - S += dd; - if (fabs(current_direction_x) > 1e-9 || fabs(current_direction_y) > 1e-9) - { - double current_angle = atan2(current_direction_y, current_direction_x); - goal_index = i; - if (fabs(remainder(start_angle - current_angle, 2 * M_PI)) >= angle_threshold_ || S >= distance) - { - break; - } - } - } - } - if (last_valid_index - goal_index == 1) - goal_index = last_valid_index; - return goal_index; -} - -bool score_algorithm::ScoreAlgorithm::findSubGoalIndex(const std::vector &plan, std::vector &seq_s, std::vector &mutes) -{ - if (plan.empty()) - { - return false; - } - double x_direction_saved = 0.0; - robot_geometry_msgs::PoseArray poseArrayMsg; - poseArrayMsg.header.stamp = robot::Time::now(); - poseArrayMsg.header.frame_id = costmap_robot_->getGlobalFrameID(); - - robot_nav_2d_msgs::Pose2DStamped p1, p2, p3; - - if (plan.size() < 3) - { - seq_s.push_back(plan.back().header.seq); - mutes.push_back(plan.back()); - } - else - { - unsigned int i = 0; - p1 = plan[i]; - for (i = 0; i < (unsigned int)plan.size() - 2; i++) - { - double egde1_angle, egde2_angle; - p2 = plan[i + 1]; - if ((fabs(p2.pose.y - p1.pose.y) > 1e-9 || fabs(p2.pose.x - p1.pose.x) > 1e-9)) - { - egde1_angle = atan2(p2.pose.y - p1.pose.y, p2.pose.x - p1.pose.x); - } - else - continue; - - const double target_direction = cos(fabs(egde1_angle - p2.pose.theta)); - - if (target_direction * x_direction_saved < 0.0) - { - if (std::find(seq_s.begin(), seq_s.end(), plan[i].header.seq) == seq_s.end()) - { - seq_s.push_back(plan[i].header.seq); - mutes.push_back(plan[i]); - robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan[i]).pose; - poseArrayMsg.poses.push_back(pose); - } - } - x_direction_saved = target_direction; - - p3 = plan[i + 2]; - if ((fabs(p3.pose.y - p2.pose.y) > 1e-9 || fabs(p3.pose.x - p2.pose.x) > 1e-9)) - { - egde2_angle = atan2(p3.pose.y - p2.pose.y, p3.pose.x - p2.pose.x); - p1 = p2; - } - else - continue; - - double thresh_angle = 0.3; - double angle = fabs(remainder(egde1_angle - egde2_angle, 2 * M_PI)); - if (angle >= thresh_angle || angle >= M_PI - thresh_angle) - { - if (std::find(seq_s.begin(), seq_s.end(), plan[i].header.seq) == seq_s.end()) - { - seq_s.push_back(plan[i + 1].header.seq); - mutes.push_back(plan[i + 1]); - robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan[i + 1]).pose; - poseArrayMsg.poses.push_back(pose); - } - p2 = p3; - } - } - } - - if (seq_s.empty()) - { - seq_s.push_back(plan.back().header.seq); - mutes.push_back(plan.back()); - robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan.back()).pose; - poseArrayMsg.poses.push_back(pose); - } - else - { - if (seq_s.back() < plan.back().header.seq) - { - seq_s.push_back(plan.back().header.seq); - mutes.push_back(plan.back()); - robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan.back()).pose; - poseArrayMsg.poses.push_back(pose); - } - } - return true; -} - -bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs::Pose2DStamped &robot_pose, const robot_nav_2d_msgs::Twist2D &velocity, const double &S, - const robot_nav_2d_msgs::Path2D &global_plan, unsigned int &start_index_global_plan, unsigned int &goal_index_global_plan, robot_nav_2d_msgs::Path2D &result) -{ - result.poses.clear(); - if (global_plan.poses.empty()) - { - robot::log_error("ScoreAlgorithm: The global plan was empty."); - return false; - } - - std::vector seq_s; - std::vector mutes; - if (!this->findSubGoalIndex(global_plan.poses, seq_s, mutes)) - { - robot::log_error("ScoreAlgorithm: Cannot find SubGoal Index"); - return false; - } - - unsigned int sub_goal_index; - unsigned int sub_start_index; - - bool found_sub_goal_index_saved = false, found_sub_start_index_saved = false; - for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); ++i) - { - if (global_plan.poses[i].header.seq == sub_goal_seq_saved_) - { - sub_goal_index_saved_ = i; - found_sub_goal_index_saved = true; - } - if (global_plan.poses[i].header.seq == sub_start_seq_saved_) - { - sub_start_index_saved_ = i; - found_sub_start_index_saved = true; - } - if (found_sub_goal_index_saved && found_sub_start_index_saved) - { - break; - } - } - - sub_goal_index = !found_sub_goal_index_saved ? (unsigned int)global_plan.poses.size() : sub_goal_index_saved_; - sub_start_index = !found_sub_start_index_saved ? 0 : sub_start_index_saved_; - - std::vector index_s; - for (auto seq : seq_s) - { - for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); ++i) - { - if (global_plan.poses[i].header.seq == seq) - { - index_s.push_back(i); - break; - } - } - } - - if (index_s.empty()) - { - sub_goal_index = (unsigned int)global_plan.poses.size(); - sub_goal_seq_saved_ = global_plan.poses.back().header.seq; - } - else - { - bool is_stopped = stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_); - if (is_stopped && index_s.front() > sub_goal_index_saved_ && index_s.front() < (unsigned int)global_plan.poses.size()) - { - // sub_goal_index = (unsigned int)index_s.front() > 0 ? (unsigned int)index_s.front() - 1 : (unsigned int)index_s.front(); - sub_goal_index = index_s.front(); - sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; - } - - // Process index_s with multiple elements - if (index_s.size() > 1) - { - for (size_t i = 1; i < index_s.size(); ++i) - { - if (index_s[i - 1] >= (unsigned int)global_plan.poses.size() || index_s[i] >= (unsigned int)global_plan.poses.size()) - { - continue; - } - - double dx = robot_pose.pose.x - global_plan.poses[index_s[i - 1]].pose.x; - double dy = robot_pose.pose.y - global_plan.poses[index_s[i - 1]].pose.y; - double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[index_s[i - 1]].pose.theta); - double x = cos(global_plan.poses[index_s[i - 1]].pose.theta) * dx + sin(global_plan.poses[index_s[i - 1]].pose.theta) * dy; - double y = -sin(global_plan.poses[index_s[i - 1]].pose.theta) * dx + cos(global_plan.poses[index_s[i - 1]].pose.theta) * dy; - - if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.2) - { - double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; - if (fabs(tolerance) <= xy_local_goal_tolerance_) - { - - if (index_s[i] > sub_goal_index_saved_) - { - sub_goal_index = (i < index_s.size() - 1) ? index_s[i] : (unsigned int)global_plan.poses.size() - 1; - sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; - old_xy_goal_tolerance_ = 0.0; - if (follow_step_path_) - { - sub_start_index = index_s[i - 1]; - sub_start_seq_saved_ = global_plan.poses[sub_start_index].header.seq; - } - break; - } - } - } - else - old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; - } - } - else - { - // Validate sub_goal_index - if (sub_goal_index >= (unsigned int)global_plan.poses.size() - 1) - { - sub_goal_index = (unsigned int)global_plan.poses.size() - 1; - sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; - } - else - { - double dx = robot_pose.pose.x - global_plan.poses[sub_goal_index].pose.x; - double dy = robot_pose.pose.y - global_plan.poses[sub_goal_index].pose.y; - double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[sub_goal_index].pose.theta); - double x = cos(global_plan.poses[sub_goal_index].pose.theta) * dx + sin(global_plan.poses[sub_goal_index].pose.theta) * dy; - double y = -sin(global_plan.poses[sub_goal_index].pose.theta) * dx + cos(global_plan.poses[sub_goal_index].pose.theta) * dy; - if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.2) - { - double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; - if (fabs(tolerance) <= xy_local_goal_tolerance_) - { - sub_goal_index = (unsigned int)global_plan.poses.size() - 1; - sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; - old_xy_goal_tolerance_ = 0.0; - robot::log_info("ScoreAlgorithm: Single sub-goal reached, setting sub_goal_index to %d", sub_goal_index); - } - } - else - old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; - } - } - } - if (sub_start_index >= sub_goal_index) - { - robot::log_error("ScoreAlgorithm: Sub path is empty"); - return false; - } - - // find the "start pose", i.e. the pose on the plan closest to the robot that is also on the local map - // Tìm điểm pose bắt đầu trên kế hoạch đường đi gần nhất với robot đồng thời có tồn tại trong local map - unsigned int start_index = 0; // số vị trí pose trong kế hoạch đường đi - unsigned int closet_index = 0; - double distance_to_start = std::numeric_limits::infinity(); // Xét giá trị là vô cùng oo - bool started_path = false; - for (unsigned int i = sub_start_index; i < sub_goal_index; ++i) - { - // Still on the costmap. Continue. - double distance = fabs(robot_nav_2d_utils::poseDistance(global_plan.poses[i].pose, robot_pose.pose)); // Tính khoảng cách từ vị trí của robot đến pose đang xét - if (distance_to_start > distance) - { - start_index = i; - closet_index = start_index; - distance_to_start = distance; - started_path = true; - } - } - - // Nếu khồng tìm được điểm gần với robot nhất thì trả về false - if (!started_path) - { - robot::log_error("ScoreAlgorithm: None of the points of the global plan were in the local costmap."); - return false; - } - std::stringstream ss; - start_index_saved_vt_.push_back(global_plan.poses[start_index].header.seq); - if (start_index_saved_vt_.size() > index_samples_) - start_index_saved_vt_.erase(start_index_saved_vt_.begin()); - - unsigned num = 0; - if (!start_index_saved_vt_.empty()) - { - for (int i = 0; i < (int)start_index_saved_vt_.size() - 1; i++) - { - if (start_index_saved_vt_[i] == start_index_saved_vt_[i + 1]) - num++; - ss << start_index_saved_vt_[i] << " "; - } - } - if (num < index_samples_ - 1 && !start_index_saved_vt_.empty()) - { - auto max_iter = *(std::max_element(start_index_saved_vt_.begin(), start_index_saved_vt_.end())); - unsigned int max_start_index = start_index; - for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); i++) - { - if (global_plan.poses[i].header.seq == max_iter) - { - max_start_index = i; - break; - } - } - double S1 = journey(global_plan.poses, start_index, (unsigned int)global_plan.poses.size() - 1); - double S2 = journey(global_plan.poses, max_start_index, (unsigned int)global_plan.poses.size() - 1); - - if (S2 - S1) - { - start_index = max_start_index; - } - } - // ROS_INFO_STREAM_THROTTLE(0.1, ss.str() << "\n"); - - // find the "last valid pose", i.e. the last pose on the plan after the start pose that is still on the local map - // Tìm điểm pose cuôi cùng sau điểm pose bắt đầu và có tồn tại trong local map - if (start_index < 1) - start_index = 1; - // unsigned int last_valid_index = (unsigned int)global_plan.poses.size() - 1; - unsigned int last_valid_index = sub_goal_index; - - // find the "goal pose" by walking along the plan as long as each step leads far enough away from the starting point, - // i.e. is within angle_threshold_ of the starting direction. - // Tìm điểm mục tiêu chạy từ điểm start pose đến last valid pose dọc thep plan - unsigned int goal_index = start_index; - while (goal_index < last_valid_index) - { - // Tìm kiếm vị trí điểm mục tiêu phù hợp - goal_index = getGoalIndex(robot_pose.pose, global_plan.poses, S, start_index, last_valid_index); - - // check if goal already reached - bool goal_already_reached = false; - - for (auto &reached_intermediate_goal : reached_intermediate_goals_) - { - double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal.pose, global_plan.poses[goal_index].pose)); - if (distance < xy_local_goal_tolerance_) - { - goal_already_reached = true; - // choose a new start_index by walking along the plan until we're outside xy_local_goal_tolerance_ and try again - // (start_index is now > goal_index) - for (start_index = goal_index; start_index < last_valid_index; ++start_index) - { - distance = robot_nav_2d_utils::poseDistance(reached_intermediate_goal.pose, global_plan.poses[start_index].pose); - if (distance >= xy_local_goal_tolerance_) - break; - } - break; - } - } - - if (!goal_already_reached) - { - // new goal not in reached_intermediate_goals_ - double distance = fabs(robot_nav_2d_utils::poseDistance(global_plan.poses[start_index].pose, global_plan.poses[goal_index].pose)); - if (distance < xy_local_goal_tolerance_) - { - // the robot has currently reached the goal - reached_intermediate_goals_.push_back(global_plan.poses[goal_index]); - robot::log_info("ScoreAlgorithm: Number of reached_intermediate goals: %d", reached_intermediate_goals_.size()); - } - else - { - // we've found a new goal! - break; - } - } - } - - if (start_index > goal_index) - start_index = goal_index; - if (goal_index > last_valid_index) - goal_index = last_valid_index; - if ((unsigned int)global_plan.poses.size() == 2 && !global_plan.poses.empty()) - { - start_index = 0; - goal_index = 1; - } - - if (goal_index == (unsigned int)global_plan.poses.size() - 1) - start_index = (unsigned int)global_plan.poses.size() - 2; - - start_index_global_plan = start_index; - goal_index_global_plan = goal_index; - - robot_nav_2d_msgs::Pose2DStamped sub_pose; - sub_pose = global_plan.poses[closet_index]; - -#ifdef BUILD_WITH_ROS - { - robot_geometry_msgs::PoseStamped sub_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_pose); - geometry_msgs::PoseStamped sub_pose_stamped_ros; - sub_pose_stamped_ros.header.stamp = ros::Time::now(); - sub_pose_stamped_ros.header.frame_id = sub_pose_stamped.header.frame_id; - sub_pose_stamped_ros.pose.position.x = sub_pose_stamped.pose.position.x; - sub_pose_stamped_ros.pose.position.y = sub_pose_stamped.pose.position.y; - sub_pose_stamped_ros.pose.position.z = 0.9; - sub_pose_stamped_ros.pose.orientation.x = sub_pose_stamped.pose.orientation.x; - sub_pose_stamped_ros.pose.orientation.y = sub_pose_stamped.pose.orientation.y; - sub_pose_stamped_ros.pose.orientation.z = sub_pose_stamped.pose.orientation.z; - sub_pose_stamped_ros.pose.orientation.w = sub_pose_stamped.pose.orientation.w; - closet_robot_goal_pub_.publish(sub_pose_stamped_ros); - } -#endif - - robot_nav_2d_msgs::Pose2DStamped sub_goal; - sub_goal = global_plan.poses[goal_index]; -#ifdef BUILD_WITH_ROS - { - robot_geometry_msgs::PoseStamped sub_goal_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_goal); - geometry_msgs::PoseStamped sub_goal_stamped_ros; - sub_goal_stamped_ros.header.stamp = ros::Time::now(); - sub_goal_stamped_ros.header.frame_id = sub_goal_stamped.header.frame_id; - sub_goal_stamped_ros.pose.position.x = sub_goal_stamped.pose.position.x; - sub_goal_stamped_ros.pose.position.y = sub_goal_stamped.pose.position.y; - sub_goal_stamped_ros.pose.position.z = 0.9; - sub_goal_stamped_ros.pose.orientation.x = sub_goal_stamped.pose.orientation.x; - sub_goal_stamped_ros.pose.orientation.y = sub_goal_stamped.pose.orientation.y; - sub_goal_stamped_ros.pose.orientation.z = sub_goal_stamped.pose.orientation.z; - sub_goal_stamped_ros.pose.orientation.w = sub_goal_stamped.pose.orientation.w; - current_goal_pub_.publish(sub_goal_stamped_ros); - } -#endif - - result.header = global_plan.header; - for (int i = closet_index; i <= goal_index; i++) - { - result.poses.push_back(global_plan.poses[i]); - } - return true; -} - -double score_algorithm::ScoreAlgorithm::journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const -{ - double S = 0; - if (last_valid_index - start_index > 1) - { - for (int i = start_index; i < last_valid_index; i++) - { - S += robot_nav_2d_utils::poseDistance(plan[i].pose, plan[i + 1].pose); - } - } - return S; -} - -bool score_algorithm::ScoreAlgorithm::stopped(const robot_nav_2d_msgs::Twist2D &velocity, const double &rot_stopped_velocity, const double &trans_stopped_velocity) -{ - return fabs(velocity.theta) <= rot_stopped_velocity && fabs(velocity.x) <= trans_stopped_velocity && fabs(velocity.y) <= trans_stopped_velocity; -} - -void score_algorithm::ScoreAlgorithm::clear() -{ - reached_intermediate_goals_.clear(); - start_index_saved_vt_.clear(); - sub_goal_index_saved_ = sub_goal_seq_saved_ = 0; - sub_start_index_saved_, sub_start_seq_saved_ = 0; +#include +#include +#include +#include +#include + +unsigned int score_algorithm::ScoreAlgorithm::getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, + const double distance, unsigned int start_index, unsigned int last_valid_index) const +{ + if (start_index >= last_valid_index) + return last_valid_index; + + unsigned int goal_index = start_index + 1; + const double start_direction_x = plan[goal_index].pose.x - plan[start_index].pose.x; + const double start_direction_y = plan[goal_index].pose.y - plan[start_index].pose.y; + if (fabs(start_direction_x) > 1e-9 || fabs(start_direction_y) > 1e-9) + { // make sure that atan2 is defined + double start_angle = atan2(start_direction_y, start_direction_x); + double S = sqrt(pow(start_direction_x, 2) + pow(start_direction_y, 2)); + // double angle_threshold = 0.0; + for (unsigned int i = start_index + 1; i <= last_valid_index; i++) + { + const double current_direction_x = plan[i].pose.x - plan[i - 1].pose.x; + const double current_direction_y = plan[i].pose.y - plan[i - 1].pose.y; + const double dd = sqrt(pow(current_direction_x, 2) + pow(current_direction_y, 2)); + S += dd; + if (fabs(current_direction_x) > 1e-9 || fabs(current_direction_y) > 1e-9) + { + double current_angle = atan2(current_direction_y, current_direction_x); + goal_index = i; + if (fabs(remainder(start_angle - current_angle, 2 * M_PI)) >= angle_threshold_ || S >= distance) + { + break; + } + } + } + } + if (last_valid_index - goal_index == 1) + goal_index = last_valid_index; + return goal_index; +} + +bool score_algorithm::ScoreAlgorithm::findSubGoalIndex(const std::vector &plan, std::vector &seq_s, std::vector &mutes) +{ + if (plan.empty()) + { + return false; + } + double x_direction_saved = 0.0; + robot_geometry_msgs::PoseArray poseArrayMsg; + poseArrayMsg.header.stamp = robot::Time::now(); + poseArrayMsg.header.frame_id = costmap_robot_->getGlobalFrameID(); + + robot_nav_2d_msgs::Pose2DStamped p1, p2, p3; + + if (plan.size() < 3) + { + seq_s.push_back(plan.back().header.seq); + mutes.push_back(plan.back()); + } + else + { + unsigned int i = 0; + p1 = plan[i]; + for (i = 0; i < (unsigned int)plan.size() - 2; i++) + { + double egde1_angle, egde2_angle; + p2 = plan[i + 1]; + if ((fabs(p2.pose.y - p1.pose.y) > 1e-9 || fabs(p2.pose.x - p1.pose.x) > 1e-9)) + { + egde1_angle = atan2(p2.pose.y - p1.pose.y, p2.pose.x - p1.pose.x); + } + else + continue; + + const double target_direction = cos(fabs(egde1_angle - p2.pose.theta)); + + if (target_direction * x_direction_saved < 0.0) + { + if (std::find(seq_s.begin(), seq_s.end(), plan[i].header.seq) == seq_s.end()) + { + seq_s.push_back(plan[i].header.seq); + mutes.push_back(plan[i]); + robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan[i]).pose; + poseArrayMsg.poses.push_back(pose); + } + } + x_direction_saved = target_direction; + + p3 = plan[i + 2]; + if ((fabs(p3.pose.y - p2.pose.y) > 1e-9 || fabs(p3.pose.x - p2.pose.x) > 1e-9)) + { + egde2_angle = atan2(p3.pose.y - p2.pose.y, p3.pose.x - p2.pose.x); + p1 = p2; + } + else + continue; + + double thresh_angle = 0.3; + double angle = fabs(remainder(egde1_angle - egde2_angle, 2 * M_PI)); + if (angle >= thresh_angle || angle >= M_PI - thresh_angle) + { + if (std::find(seq_s.begin(), seq_s.end(), plan[i].header.seq) == seq_s.end()) + { + seq_s.push_back(plan[i + 1].header.seq); + mutes.push_back(plan[i + 1]); + robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan[i + 1]).pose; + poseArrayMsg.poses.push_back(pose); + } + p2 = p3; + } + } + } + + if (seq_s.empty()) + { + seq_s.push_back(plan.back().header.seq); + mutes.push_back(plan.back()); + robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan.back()).pose; + poseArrayMsg.poses.push_back(pose); + } + else + { + if (seq_s.back() < plan.back().header.seq) + { + seq_s.push_back(plan.back().header.seq); + mutes.push_back(plan.back()); + robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan.back()).pose; + poseArrayMsg.poses.push_back(pose); + } + } + return true; +} + +bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs::Pose2DStamped &robot_pose, const robot_nav_2d_msgs::Twist2D &velocity, const double &S, + const robot_nav_2d_msgs::Path2D &global_plan, unsigned int &start_index_global_plan, unsigned int &goal_index_global_plan, robot_nav_2d_msgs::Path2D &result) +{ + result.poses.clear(); + if (global_plan.poses.empty()) + { + robot::log_error("ScoreAlgorithm: The global plan was empty."); + return false; + } + + std::vector seq_s; + std::vector mutes; + if (!this->findSubGoalIndex(global_plan.poses, seq_s, mutes)) + { + robot::log_error("ScoreAlgorithm: Cannot find SubGoal Index"); + return false; + } + + unsigned int sub_goal_index; + unsigned int sub_start_index; + + bool found_sub_goal_index_saved = false, found_sub_start_index_saved = false; + for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); ++i) + { + if (global_plan.poses[i].header.seq == sub_goal_seq_saved_) + { + sub_goal_index_saved_ = i; + found_sub_goal_index_saved = true; + } + if (global_plan.poses[i].header.seq == sub_start_seq_saved_) + { + sub_start_index_saved_ = i; + found_sub_start_index_saved = true; + } + if (found_sub_goal_index_saved && found_sub_start_index_saved) + { + break; + } + } + + sub_goal_index = !found_sub_goal_index_saved ? (unsigned int)global_plan.poses.size() : sub_goal_index_saved_; + sub_start_index = !found_sub_start_index_saved ? 0 : sub_start_index_saved_; + + std::vector index_s; + for (auto seq : seq_s) + { + for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); ++i) + { + if (global_plan.poses[i].header.seq == seq) + { + index_s.push_back(i); + break; + } + } + } + + if (index_s.empty()) + { + sub_goal_index = (unsigned int)global_plan.poses.size(); + sub_goal_seq_saved_ = global_plan.poses.back().header.seq; + } + else + { + bool is_stopped = stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_); + if (is_stopped && index_s.front() > sub_goal_index_saved_ && index_s.front() < (unsigned int)global_plan.poses.size()) + { + // sub_goal_index = (unsigned int)index_s.front() > 0 ? (unsigned int)index_s.front() - 1 : (unsigned int)index_s.front(); + sub_goal_index = index_s.front(); + sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; + } + + // Process index_s with multiple elements + if (index_s.size() > 1) + { + for (size_t i = 0; i < index_s.size(); ++i) + { + if (index_s[i - 1] >= (unsigned int)global_plan.poses.size() || index_s[i] >= (unsigned int)global_plan.poses.size()) + { + continue; + } + + double dx = robot_pose.pose.x - global_plan.poses[index_s[i - 1]].pose.x; + double dy = robot_pose.pose.y - global_plan.poses[index_s[i - 1]].pose.y; + double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[index_s[i - 1]].pose.theta); + double x = cos(global_plan.poses[index_s[i - 1]].pose.theta) * dx + sin(global_plan.poses[index_s[i - 1]].pose.theta) * dy; + double y = -sin(global_plan.poses[index_s[i - 1]].pose.theta) * dx + cos(global_plan.poses[index_s[i - 1]].pose.theta) * dy; + + if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.1) + { + double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; + if (fabs(tolerance) <= xy_local_goal_tolerance_) + { + if (index_s[i] > sub_goal_index_saved_) + { + sub_goal_index = (i < index_s.size() - 1) ? index_s[i] : (unsigned int)global_plan.poses.size() - 1; + sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; + old_xy_goal_tolerance_ = 0.0; + if (follow_step_path_) + { + sub_start_index = index_s[i - 1]; + sub_start_seq_saved_ = global_plan.poses[sub_start_index].header.seq; + } + break; + } + } + } + else + old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; + } + } + else + { + // Validate sub_goal_index + if (sub_goal_index >= (unsigned int)global_plan.poses.size() - 1) + { + sub_goal_index = (unsigned int)global_plan.poses.size() - 1; + sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; + } + else + { + double dx = robot_pose.pose.x - global_plan.poses[sub_goal_index].pose.x; + double dy = robot_pose.pose.y - global_plan.poses[sub_goal_index].pose.y; + double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[sub_goal_index].pose.theta); + double x = cos(global_plan.poses[sub_goal_index].pose.theta) * dx + sin(global_plan.poses[sub_goal_index].pose.theta) * dy; + double y = -sin(global_plan.poses[sub_goal_index].pose.theta) * dx + cos(global_plan.poses[sub_goal_index].pose.theta) * dy; + if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.1) + { + double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; + if (fabs(tolerance) <= xy_local_goal_tolerance_) + { + sub_goal_index = (unsigned int)global_plan.poses.size() - 1; + sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq; + old_xy_goal_tolerance_ = 0.0; + robot::log_info("ScoreAlgorithm: Single sub-goal reached, setting sub_goal_index to %d", sub_goal_index); + } + } + else + old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; + } + } + } + if (sub_start_index >= sub_goal_index) + { + robot::log_error("ScoreAlgorithm: Sub path is empty"); + return false; + } + + // find the "start pose", i.e. the pose on the plan closest to the robot that is also on the local map + // Tìm điểm pose bắt đầu trên kế hoạch đường đi gần nhất với robot đồng thời có tồn tại trong local map + unsigned int start_index = 0; // số vị trí pose trong kế hoạch đường đi + unsigned int closet_index = 0; + double distance_to_start = std::numeric_limits::infinity(); // Xét giá trị là vô cùng oo + bool started_path = false; + for (unsigned int i = sub_start_index; i < sub_goal_index; ++i) + { + // Still on the costmap. Continue. + double distance = fabs(robot_nav_2d_utils::poseDistance(global_plan.poses[i].pose, robot_pose.pose)); // Tính khoảng cách từ vị trí của robot đến pose đang xét + if (distance_to_start > distance) + { + start_index = i; + closet_index = start_index; + distance_to_start = distance; + started_path = true; + } + } + + // Nếu khồng tìm được điểm gần với robot nhất thì trả về false + if (!started_path) + { + robot::log_error("ScoreAlgorithm: None of the points of the global plan were in the local costmap."); + return false; + } + std::stringstream ss; + start_index_saved_vt_.push_back(global_plan.poses[start_index].header.seq); + if (start_index_saved_vt_.size() > index_samples_) + start_index_saved_vt_.erase(start_index_saved_vt_.begin()); + + unsigned num = 0; + if (!start_index_saved_vt_.empty()) + { + for (int i = 0; i < (int)start_index_saved_vt_.size() - 1; i++) + { + if (start_index_saved_vt_[i] == start_index_saved_vt_[i + 1]) + num++; + ss << start_index_saved_vt_[i] << " "; + } + } + if (num < index_samples_ - 1 && !start_index_saved_vt_.empty()) + { + auto max_iter = *(std::max_element(start_index_saved_vt_.begin(), start_index_saved_vt_.end())); + unsigned int max_start_index = start_index; + for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); i++) + { + if (global_plan.poses[i].header.seq == max_iter) + { + max_start_index = i; + break; + } + } + double S1 = journey(global_plan.poses, start_index, (unsigned int)global_plan.poses.size() - 1); + double S2 = journey(global_plan.poses, max_start_index, (unsigned int)global_plan.poses.size() - 1); + + if (S2 - S1) + { + start_index = max_start_index; + } + } + // ROS_INFO_STREAM_THROTTLE(0.1, ss.str() << "\n"); + + // find the "last valid pose", i.e. the last pose on the plan after the start pose that is still on the local map + // Tìm điểm pose cuôi cùng sau điểm pose bắt đầu và có tồn tại trong local map + if (start_index < 1) + start_index = 1; + // unsigned int last_valid_index = (unsigned int)global_plan.poses.size() - 1; + unsigned int last_valid_index = sub_goal_index; + + // find the "goal pose" by walking along the plan as long as each step leads far enough away from the starting point, + // i.e. is within angle_threshold_ of the starting direction. + // Tìm điểm mục tiêu chạy từ điểm start pose đến last valid pose dọc thep plan + unsigned int goal_index = start_index; + while (goal_index < last_valid_index) + { + // Tìm kiếm vị trí điểm mục tiêu phù hợp + goal_index = getGoalIndex(robot_pose.pose, global_plan.poses, S, start_index, last_valid_index); + + // check if goal already reached + bool goal_already_reached = false; + + for (auto &reached_intermediate_goal : reached_intermediate_goals_) + { + double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal.pose, global_plan.poses[goal_index].pose)); + if (distance < xy_local_goal_tolerance_) + { + goal_already_reached = true; + // choose a new start_index by walking along the plan until we're outside xy_local_goal_tolerance_ and try again + // (start_index is now > goal_index) + for (start_index = goal_index; start_index < last_valid_index; ++start_index) + { + distance = robot_nav_2d_utils::poseDistance(reached_intermediate_goal.pose, global_plan.poses[start_index].pose); + if (distance >= xy_local_goal_tolerance_) + break; + } + break; + } + } + + if (!goal_already_reached) + { + // new goal not in reached_intermediate_goals_ + double distance = fabs(robot_nav_2d_utils::poseDistance(global_plan.poses[start_index].pose, global_plan.poses[goal_index].pose)); + if (distance < xy_local_goal_tolerance_) + { + // the robot has currently reached the goal + reached_intermediate_goals_.push_back(global_plan.poses[goal_index]); + robot::log_info("ScoreAlgorithm: Number of reached_intermediate goals: %d", reached_intermediate_goals_.size()); + } + else + { + // we've found a new goal! + break; + } + } + } + + if (start_index > goal_index) + start_index = goal_index; + if (goal_index > last_valid_index) + goal_index = last_valid_index; + if ((unsigned int)global_plan.poses.size() == 2 && !global_plan.poses.empty()) + { + start_index = 0; + goal_index = 1; + } + + if (goal_index == (unsigned int)global_plan.poses.size() - 1) + start_index = (unsigned int)global_plan.poses.size() - 2; + + start_index_global_plan = start_index; + goal_index_global_plan = goal_index; + + robot_nav_2d_msgs::Pose2DStamped sub_pose; + sub_pose = global_plan.poses[closet_index]; + +#ifdef SCORE_ALGORITHM_WITH_ROS + { + robot_geometry_msgs::PoseStamped sub_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_pose); + geometry_msgs::PoseStamped sub_pose_stamped_ros; + sub_pose_stamped_ros.header.stamp = ros::Time::now(); + sub_pose_stamped_ros.header.frame_id = sub_pose_stamped.header.frame_id; + sub_pose_stamped_ros.pose.position.x = sub_pose_stamped.pose.position.x; + sub_pose_stamped_ros.pose.position.y = sub_pose_stamped.pose.position.y; + sub_pose_stamped_ros.pose.position.z = sub_pose_stamped.pose.position.z; + sub_pose_stamped_ros.pose.orientation.x = sub_pose_stamped.pose.orientation.x; + sub_pose_stamped_ros.pose.orientation.y = sub_pose_stamped.pose.orientation.y; + sub_pose_stamped_ros.pose.orientation.z = sub_pose_stamped.pose.orientation.z; + sub_pose_stamped_ros.pose.orientation.w = sub_pose_stamped.pose.orientation.w; + closet_robot_goal_pub_.publish(sub_pose_stamped_ros); + } +#endif + + robot_nav_2d_msgs::Pose2DStamped sub_goal; + sub_goal = global_plan.poses[goal_index]; +#ifdef SCORE_ALGORITHM_WITH_ROS + { + robot_geometry_msgs::PoseStamped sub_goal_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_goal); + geometry_msgs::PoseStamped sub_goal_stamped_ros; + sub_goal_stamped_ros.header.stamp = ros::Time::now(); + sub_goal_stamped_ros.header.frame_id = sub_goal_stamped.header.frame_id; + sub_goal_stamped_ros.pose.position.x = sub_goal_stamped.pose.position.x; + sub_goal_stamped_ros.pose.position.y = sub_goal_stamped.pose.position.y; + sub_goal_stamped_ros.pose.position.z = sub_goal_stamped.pose.position.z; + sub_goal_stamped_ros.pose.orientation.x = sub_goal_stamped.pose.orientation.x; + sub_goal_stamped_ros.pose.orientation.y = sub_goal_stamped.pose.orientation.y; + sub_goal_stamped_ros.pose.orientation.z = sub_goal_stamped.pose.orientation.z; + sub_goal_stamped_ros.pose.orientation.w = sub_goal_stamped.pose.orientation.w; + current_goal_pub_.publish(sub_goal_stamped_ros); + } +#endif + + result.header = global_plan.header; + for (int i = closet_index; i <= goal_index; i++) + { + result.poses.push_back(global_plan.poses[i]); + } + return true; +} + +double score_algorithm::ScoreAlgorithm::journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const +{ + double S = 0; + if (last_valid_index - start_index > 1) + { + for (int i = start_index; i < last_valid_index; i++) + { + S += robot_nav_2d_utils::poseDistance(plan[i].pose, plan[i + 1].pose); + } + } + return S; +} + +bool score_algorithm::ScoreAlgorithm::stopped(const robot_nav_2d_msgs::Twist2D &velocity, const double &rot_stopped_velocity, const double &trans_stopped_velocity) +{ + return fabs(velocity.theta) <= rot_stopped_velocity && fabs(velocity.x) <= trans_stopped_velocity && fabs(velocity.y) <= trans_stopped_velocity; +} + +void score_algorithm::ScoreAlgorithm::clear() +{ + reached_intermediate_goals_.clear(); + start_index_saved_vt_.clear(); + sub_goal_index_saved_ = sub_goal_seq_saved_ = 0; + sub_start_index_saved_, sub_start_seq_saved_ = 0; } \ No newline at end of file diff --git a/src/Algorithms/Libraries/angles/CMakeLists.txt b/src/Algorithms/Libraries/angles/CMakeLists.txt index 3eb856a..81a0a74 100644 --- a/src/Algorithms/Libraries/angles/CMakeLists.txt +++ b/src/Algorithms/Libraries/angles/CMakeLists.txt @@ -1,129 +1,129 @@ -cmake_minimum_required(VERSION 3.0.2) -project(angles VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building angles with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building angles with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED) - - catkin_package( - INCLUDE_DIRS include - # LIBRARIES không cần vì đây là header-only library - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ) -endif() - -# Tìm tất cả header files -file(GLOB_RECURSE HEADERS "include/angles/*.h") - -# Tạo INTERFACE library (header-only) -add_library(${PROJECT_NAME} INTERFACE) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - # Set include directories - target_include_directories(${PROJECT_NAME} - INTERFACE - $ - $ - ) - - # Link dependencies (header-only, chỉ cần include paths) - target_link_libraries(${PROJECT_NAME} - INTERFACE - ${catkin_LIBRARIES} - ) - -else() - - # Set include directories - target_include_directories(${PROJECT_NAME} - INTERFACE - $ - $ - ) - -endif() - -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME} - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - -else() - - install(TARGETS ${PROJECT_NAME} - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME} (Header-Only)") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Headers found:") - foreach(hdr ${HEADERS}) - message(STATUS " - ${hdr}") - endforeach() - message(STATUS "Dependencies: None") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(angles VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building angles with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building angles with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED) + + catkin_package( + INCLUDE_DIRS include + # LIBRARIES không cần vì đây là header-only library + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ) +endif() + +# Tìm tất cả header files +file(GLOB_RECURSE HEADERS "include/angles/*.h") + +# Tạo INTERFACE library (header-only) +add_library(${PROJECT_NAME} INTERFACE) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + # Set include directories + target_include_directories(${PROJECT_NAME} + INTERFACE + $ + $ + ) + + # Link dependencies (header-only, chỉ cần include paths) + target_link_libraries(${PROJECT_NAME} + INTERFACE + ${catkin_LIBRARIES} + ) + +else() + + # Set include directories + target_include_directories(${PROJECT_NAME} + INTERFACE + $ + $ + ) + +endif() + +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME} + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + +else() + + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME} (Header-Only)") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Headers found:") + foreach(hdr ${HEADERS}) + message(STATUS " - ${hdr}") + endforeach() + message(STATUS "Dependencies: None") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Libraries/angles/include/angles/angles.h b/src/Algorithms/Libraries/angles/include/angles/angles.h index 4efd80e..79e250a 100644 --- a/src/Algorithms/Libraries/angles/include/angles/angles.h +++ b/src/Algorithms/Libraries/angles/include/angles/angles.h @@ -1,48 +1,48 @@ -#ifndef ANGLES_ANGLES_H -#define ANGLES_ANGLES_H - -#include - -namespace angles -{ - -/** - * @brief Normalize an angle to the range [-π, π] - * @param angle The angle in radians to normalize - * @return The normalized angle in the range [-π, π] - */ -inline double normalize_angle(double angle) -{ - while (angle > M_PI) - angle -= 2.0 * M_PI; - while (angle < -M_PI) - angle += 2.0 * M_PI; - return angle; -} - -/** - * @brief Calculate the shortest angular distance between two angles - * - * Computes the shortest angular distance from angle 'from' to angle 'to'. - * The result is in the range [-π, π], where positive values indicate - * counter-clockwise rotation and negative values indicate clockwise rotation. - * - * @param from The starting angle in radians - * @param to The target angle in radians - * @return The shortest angular distance in radians, in the range [-π, π] - * - * @code - * double diff = angles::shortest_angular_distance(0.0, M_PI/2); // Returns π/2 - * double diff2 = angles::shortest_angular_distance(M_PI, 0.0); // Returns -π (or π, normalized) - * @endcode - */ -inline double shortest_angular_distance(double from, double to) -{ - double diff = to - from; - return normalize_angle(diff); -} - -} // namespace angles - -#endif // ANGLES_ANGLES_H - +#ifndef ANGLES_ANGLES_H +#define ANGLES_ANGLES_H + +#include + +namespace angles +{ + +/** + * @brief Normalize an angle to the range [-π, π] + * @param angle The angle in radians to normalize + * @return The normalized angle in the range [-π, π] + */ +inline double normalize_angle(double angle) +{ + while (angle > M_PI) + angle -= 2.0 * M_PI; + while (angle < -M_PI) + angle += 2.0 * M_PI; + return angle; +} + +/** + * @brief Calculate the shortest angular distance between two angles + * + * Computes the shortest angular distance from angle 'from' to angle 'to'. + * The result is in the range [-π, π], where positive values indicate + * counter-clockwise rotation and negative values indicate clockwise rotation. + * + * @param from The starting angle in radians + * @param to The target angle in radians + * @return The shortest angular distance in radians, in the range [-π, π] + * + * @code + * double diff = angles::shortest_angular_distance(0.0, M_PI/2); // Returns π/2 + * double diff2 = angles::shortest_angular_distance(M_PI, 0.0); // Returns -π (or π, normalized) + * @endcode + */ +inline double shortest_angular_distance(double from, double to) +{ + double diff = to - from; + return normalize_angle(diff); +} + +} // namespace angles + +#endif // ANGLES_ANGLES_H + diff --git a/src/Algorithms/Libraries/angles/package.xml b/src/Algorithms/Libraries/angles/package.xml index 9eddac1..31dcf44 100644 --- a/src/Algorithms/Libraries/angles/package.xml +++ b/src/Algorithms/Libraries/angles/package.xml @@ -1,22 +1,22 @@ - - angles - 0.7.10 - - angles is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. angles - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/angles - - catkin - + + angles + 0.7.10 + + angles is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. angles + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/angles + + catkin + \ No newline at end of file diff --git a/src/Algorithms/Libraries/kalman/CMakeLists.txt b/src/Algorithms/Libraries/kalman/CMakeLists.txt old mode 100755 new mode 100644 index 7742396..1688461 --- a/src/Algorithms/Libraries/kalman/CMakeLists.txt +++ b/src/Algorithms/Libraries/kalman/CMakeLists.txt @@ -1,181 +1,181 @@ -cmake_minimum_required(VERSION 3.0.2) -project(kalman VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building kalman with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building kalman with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -# Find dependencies -find_package(Eigen3 REQUIRED) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED) - - catkin_package( - INCLUDE_DIRS include - LIBRARIES ${PROJECT_NAME} - DEPENDS Eigen3 - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ${EIGEN3_INCLUDE_DIRS} - ) -endif() - -# ======================================================== -# Libraries -# ======================================================== -add_library(${PROJECT_NAME} SHARED - src/kalman.cpp -) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME} - PUBLIC ${catkin_LIBRARIES} - PRIVATE Eigen3::Eigen - ) - -else() - - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME} - PUBLIC - Eigen3::Eigen - ) - - set_target_properties(${PROJECT_NAME} PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - -endif() - -# ======================================================== -# Test executable -# ======================================================== -if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/kalman-test.cpp) - add_executable(${PROJECT_NAME}_node src/kalman-test.cpp) - - target_link_libraries(${PROJECT_NAME}_node PRIVATE - ${PROJECT_NAME} - Eigen3::Eigen - ) - - if(NOT BUILDING_WITH_CATKIN) - # Configure RPATH to find libraries in devel space - set_target_properties(${PROJECT_NAME}_node PROPERTIES - BUILD_WITH_INSTALL_RPATH FALSE - INSTALL_RPATH_USE_LINK_PATH TRUE - BUILD_RPATH "${CMAKE_BINARY_DIR}" - ) - endif() -endif() - -# ======================================================== -# Install -# ======================================================== -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME} - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - ## Install test executable if it exists - if(TARGET ${PROJECT_NAME}_node) - install(TARGETS ${PROJECT_NAME}_node - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - endif() - -else() - - install(TARGETS ${PROJECT_NAME} - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - ## Install test executable if it exists - if(TARGET ${PROJECT_NAME}_node) - install(TARGETS ${PROJECT_NAME}_node - RUNTIME DESTINATION bin - ) - endif() - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME}") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Libraries: ${PROJECT_NAME}") - if(TARGET ${PROJECT_NAME}_node) - message(STATUS "Executables: ${PROJECT_NAME}_node") - endif() - message(STATUS "Dependencies: Eigen3") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(kalman VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building kalman with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building kalman with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Find dependencies +find_package(Eigen3 REQUIRED) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED) + + catkin_package( + INCLUDE_DIRS include + LIBRARIES ${PROJECT_NAME} + DEPENDS Eigen3 + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ${EIGEN3_INCLUDE_DIRS} + ) +endif() + +# ======================================================== +# Libraries +# ======================================================== +add_library(${PROJECT_NAME} SHARED + src/kalman.cpp +) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME} + PUBLIC ${catkin_LIBRARIES} + PRIVATE Eigen3::Eigen + ) + +else() + + target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME} + PUBLIC + Eigen3::Eigen + ) + + set_target_properties(${PROJECT_NAME} PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + +endif() + +# ======================================================== +# Test executable +# ======================================================== +if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/kalman-test.cpp) + add_executable(${PROJECT_NAME}_node src/kalman-test.cpp) + + target_link_libraries(${PROJECT_NAME}_node PRIVATE + ${PROJECT_NAME} + Eigen3::Eigen + ) + + if(NOT BUILDING_WITH_CATKIN) + # Configure RPATH to find libraries in devel space + set_target_properties(${PROJECT_NAME}_node PROPERTIES + BUILD_WITH_INSTALL_RPATH FALSE + INSTALL_RPATH_USE_LINK_PATH TRUE + BUILD_RPATH "${CMAKE_BINARY_DIR}" + ) + endif() +endif() + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME} + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + ## Install test executable if it exists + if(TARGET ${PROJECT_NAME}_node) + install(TARGETS ${PROJECT_NAME}_node + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + endif() + +else() + + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + ## Install test executable if it exists + if(TARGET ${PROJECT_NAME}_node) + install(TARGETS ${PROJECT_NAME}_node + RUNTIME DESTINATION bin + ) + endif() + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME}") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Libraries: ${PROJECT_NAME}") + if(TARGET ${PROJECT_NAME}_node) + message(STATUS "Executables: ${PROJECT_NAME}_node") + endif() + message(STATUS "Dependencies: Eigen3") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Libraries/kalman/README.md b/src/Algorithms/Libraries/kalman/README.md old mode 100755 new mode 100644 index 17613be..432eb81 --- a/src/Algorithms/Libraries/kalman/README.md +++ b/src/Algorithms/Libraries/kalman/README.md @@ -1,18 +1,18 @@ -Kalman Filter -============= -This is a basic Kalman filter implementation in C++ using the -[Eigen](http://eigen.tuxfamily.org/) library. It implements the algorithm -directly as found in [An Introduction to the Kalman Filter](http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf). - -There is a test program that estimates the motion of a projectile based on -noisy observations. To run it, use CMake: - - cd kalman-cpp - mkdir build - cd build - cmake .. - make - ./kalman-test - -Note: You may have to specify the path to your Eigen library in -`CMakeLists.txt`. +Kalman Filter +============= +This is a basic Kalman filter implementation in C++ using the +[Eigen](http://eigen.tuxfamily.org/) library. It implements the algorithm +directly as found in [An Introduction to the Kalman Filter](http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf). + +There is a test program that estimates the motion of a projectile based on +noisy observations. To run it, use CMake: + + cd kalman-cpp + mkdir build + cd build + cmake .. + make + ./kalman-test + +Note: You may have to specify the path to your Eigen library in +`CMakeLists.txt`. diff --git a/src/Algorithms/Libraries/kalman/include/kalman/kalman.h b/src/Algorithms/Libraries/kalman/include/kalman/kalman.h old mode 100755 new mode 100644 index 7fa1525..55c1bbf --- a/src/Algorithms/Libraries/kalman/include/kalman/kalman.h +++ b/src/Algorithms/Libraries/kalman/include/kalman/kalman.h @@ -1,91 +1,91 @@ -/** -* Kalman filter implementation using Eigen. Based on the following -* introductory paper: -* -* http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf -* -* @author: Hayk Martirosyan -* @date: 2014.11.15 -*/ - -#include - -#pragma once - -class KalmanFilter { - -public: - - /** - * Create a Kalman filter with the specified matrices. - * A - System dynamics matrix - * C - Output matrix - * Q - Process noise covariance - * R - Measurement noise covariance - * P - Estimate error covariance - */ - KalmanFilter( - double dt, - const Eigen::MatrixXd& A, - const Eigen::MatrixXd& C, - const Eigen::MatrixXd& Q, - const Eigen::MatrixXd& R, - const Eigen::MatrixXd& P - ); - - /** - * Create a blank estimator. - */ - KalmanFilter(); - - /** - * Initialize the filter with initial states as zero. - */ - void init(); - - /** - * Initialize the filter with a guess for initial states. - */ - void init(double t0, const Eigen::VectorXd& x0); - - /** - * Update the estimated state based on measured values. The - * time step is assumed to remain constant. - */ - void update(const Eigen::VectorXd& y); - - /** - * Update the estimated state based on measured values, - * using the given time step and dynamics matrix. - */ - void update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A); - - /** - * Return the current state and time. - */ - Eigen::VectorXd state() { return x_hat; }; - double time() { return t; }; - -private: - - // Matrices for computation - Eigen::MatrixXd A, C, Q, R, P, K, P0; - - // System dimensions - int m, n; - - // Initial and current time - double t0, t; - - // Discrete time step - double dt; - - // Is the filter initialized? - bool initialized; - - // n-size identity - Eigen::MatrixXd I; - - // Estimated states - Eigen::VectorXd x_hat, x_hat_new; -}; +/** +* Kalman filter implementation using Eigen. Based on the following +* introductory paper: +* +* http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf +* +* @author: Hayk Martirosyan +* @date: 2014.11.15 +*/ + +#include + +#pragma once + +class KalmanFilter { + +public: + + /** + * Create a Kalman filter with the specified matrices. + * A - System dynamics matrix + * C - Output matrix + * Q - Process noise covariance + * R - Measurement noise covariance + * P - Estimate error covariance + */ + KalmanFilter( + double dt, + const Eigen::MatrixXd& A, + const Eigen::MatrixXd& C, + const Eigen::MatrixXd& Q, + const Eigen::MatrixXd& R, + const Eigen::MatrixXd& P + ); + + /** + * Create a blank estimator. + */ + KalmanFilter(); + + /** + * Initialize the filter with initial states as zero. + */ + void init(); + + /** + * Initialize the filter with a guess for initial states. + */ + void init(double t0, const Eigen::VectorXd& x0); + + /** + * Update the estimated state based on measured values. The + * time step is assumed to remain constant. + */ + void update(const Eigen::VectorXd& y); + + /** + * Update the estimated state based on measured values, + * using the given time step and dynamics matrix. + */ + void update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A); + + /** + * Return the current state and time. + */ + Eigen::VectorXd state() { return x_hat; }; + double time() { return t; }; + +private: + + // Matrices for computation + Eigen::MatrixXd A, C, Q, R, P, K, P0; + + // System dimensions + int m, n; + + // Initial and current time + double t0, t; + + // Discrete time step + double dt; + + // Is the filter initialized? + bool initialized; + + // n-size identity + Eigen::MatrixXd I; + + // Estimated states + Eigen::VectorXd x_hat, x_hat_new; +}; diff --git a/src/Algorithms/Libraries/kalman/package.xml b/src/Algorithms/Libraries/kalman/package.xml index 9391990..d60fffe 100644 --- a/src/Algorithms/Libraries/kalman/package.xml +++ b/src/Algorithms/Libraries/kalman/package.xml @@ -1,22 +1,22 @@ - - kalman - 0.7.10 - - kalman is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. kalman - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/kalman - - catkin - + + kalman + 0.7.10 + + kalman is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. kalman + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/kalman + + catkin + \ No newline at end of file diff --git a/src/Algorithms/Libraries/kalman/src/kalman-test.cpp b/src/Algorithms/Libraries/kalman/src/kalman-test.cpp old mode 100755 new mode 100644 index fa2cdda..0e4b89c --- a/src/Algorithms/Libraries/kalman/src/kalman-test.cpp +++ b/src/Algorithms/Libraries/kalman/src/kalman-test.cpp @@ -1,77 +1,77 @@ -/** - * Test for the KalmanFilter class with 1D projectile motion. - * - * @author: Hayk Martirosyan - * @date: 2014.11.15 - */ - -#include -#include -#include - -#include - -int main(int argc, char* argv[]) { - - int n = 3; // Number of states - int m = 1; // Number of measurements - - double dt = 1.0/30; // Time step - - Eigen::MatrixXd A(n, n); // System dynamics matrix - Eigen::MatrixXd C(m, n); // Output matrix - Eigen::MatrixXd Q(n, n); // Process noise covariance - Eigen::MatrixXd R(m, m); // Measurement noise covariance - Eigen::MatrixXd P(n, n); // Estimate error covariance - - // Discrete LTI projectile motion, measuring position only - A << 1, dt, 0, 0, 1, dt, 0, 0, 1; - C << 1, 0, 0; - - // Reasonable covariance matrices - Q << .05, .05, .0, .05, .05, .0, .0, .0, .0; - R << 5; - P << .1, .1, .1, .1, 10000, 10, .1, 10, 100; - - std::cout << "A: \n" << A << std::endl; - std::cout << "C: \n" << C << std::endl; - std::cout << "Q: \n" << Q << std::endl; - std::cout << "R: \n" << R << std::endl; - std::cout << "P: \n" << P << std::endl; - - // Construct the filter - KalmanFilter kf(dt,A, C, Q, R, P); - - // List of noisy position measurements (y) - std::vector measurements = { - 1.04202710058, 1.10726790452, 1.2913511148, 1.48485250951, 1.72825901034, - 1.74216489744, 2.11672039768, 2.14529225112, 2.16029641405, 2.21269371128, - 2.57709350237, 2.6682215744, 2.51641839428, 2.76034056782, 2.88131780617, - 2.88373786518, 2.9448468727, 2.82866600131, 3.0006601946, 3.12920591669, - 2.858361783, 2.83808170354, 2.68975330958, 2.66533185589, 2.81613499531, - 2.81003612051, 2.88321849354, 2.69789264832, 2.4342229249, 2.23464791825, - 2.30278776224, 2.02069770395, 1.94393985809, 1.82498398739, 1.52526230354, - 1.86967808173, 1.18073207847, 1.10729605087, 0.916168349913, 0.678547664519, - 0.562381751596, 0.355468474885, -0.155607486619, -0.287198661013, -0.602973173813 - }; - - // Best guess of initial states - Eigen::VectorXd x0(n); - double t = 0; - x0 << measurements[0], 0, -9.81; - kf.init(t, x0); - - // Feed measurements into filter, output estimated states - - Eigen::VectorXd y(m); - std::cout << "t = " << t << ", " << "x_hat[0]: " << kf.state().transpose() << std::endl; - for(int i = 0; i < measurements.size(); i++) { - t += dt; - y << measurements[i]; - kf.update(y); - std::cout << "t = " << t << ", " << "y[" << i << "] = " << y.transpose() - << ", x_hat[" << i << "] = " << kf.state().transpose() << std::endl; - } - - return 0; -} +/** + * Test for the KalmanFilter class with 1D projectile motion. + * + * @author: Hayk Martirosyan + * @date: 2014.11.15 + */ + +#include +#include +#include + +#include + +int main(int argc, char* argv[]) { + + int n = 3; // Number of states + int m = 1; // Number of measurements + + double dt = 1.0/30; // Time step + + Eigen::MatrixXd A(n, n); // System dynamics matrix + Eigen::MatrixXd C(m, n); // Output matrix + Eigen::MatrixXd Q(n, n); // Process noise covariance + Eigen::MatrixXd R(m, m); // Measurement noise covariance + Eigen::MatrixXd P(n, n); // Estimate error covariance + + // Discrete LTI projectile motion, measuring position only + A << 1, dt, 0, 0, 1, dt, 0, 0, 1; + C << 1, 0, 0; + + // Reasonable covariance matrices + Q << .05, .05, .0, .05, .05, .0, .0, .0, .0; + R << 5; + P << .1, .1, .1, .1, 10000, 10, .1, 10, 100; + + std::cout << "A: \n" << A << std::endl; + std::cout << "C: \n" << C << std::endl; + std::cout << "Q: \n" << Q << std::endl; + std::cout << "R: \n" << R << std::endl; + std::cout << "P: \n" << P << std::endl; + + // Construct the filter + KalmanFilter kf(dt,A, C, Q, R, P); + + // List of noisy position measurements (y) + std::vector measurements = { + 1.04202710058, 1.10726790452, 1.2913511148, 1.48485250951, 1.72825901034, + 1.74216489744, 2.11672039768, 2.14529225112, 2.16029641405, 2.21269371128, + 2.57709350237, 2.6682215744, 2.51641839428, 2.76034056782, 2.88131780617, + 2.88373786518, 2.9448468727, 2.82866600131, 3.0006601946, 3.12920591669, + 2.858361783, 2.83808170354, 2.68975330958, 2.66533185589, 2.81613499531, + 2.81003612051, 2.88321849354, 2.69789264832, 2.4342229249, 2.23464791825, + 2.30278776224, 2.02069770395, 1.94393985809, 1.82498398739, 1.52526230354, + 1.86967808173, 1.18073207847, 1.10729605087, 0.916168349913, 0.678547664519, + 0.562381751596, 0.355468474885, -0.155607486619, -0.287198661013, -0.602973173813 + }; + + // Best guess of initial states + Eigen::VectorXd x0(n); + double t = 0; + x0 << measurements[0], 0, -9.81; + kf.init(t, x0); + + // Feed measurements into filter, output estimated states + + Eigen::VectorXd y(m); + std::cout << "t = " << t << ", " << "x_hat[0]: " << kf.state().transpose() << std::endl; + for(int i = 0; i < measurements.size(); i++) { + t += dt; + y << measurements[i]; + kf.update(y); + std::cout << "t = " << t << ", " << "y[" << i << "] = " << y.transpose() + << ", x_hat[" << i << "] = " << kf.state().transpose() << std::endl; + } + + return 0; +} diff --git a/src/Algorithms/Libraries/kalman/src/kalman.cpp b/src/Algorithms/Libraries/kalman/src/kalman.cpp old mode 100755 new mode 100644 index 5e47d9f..a1b37b6 --- a/src/Algorithms/Libraries/kalman/src/kalman.cpp +++ b/src/Algorithms/Libraries/kalman/src/kalman.cpp @@ -1,96 +1,96 @@ -/** -* Implementation of KalmanFilter class. -* -* @author: Hayk Martirosyan -* @date: 2014.11.15 -*/ - -#include -#include - -#include - -KalmanFilter::KalmanFilter( - double dt, - const Eigen::MatrixXd& A, - const Eigen::MatrixXd& C, - const Eigen::MatrixXd& Q, - const Eigen::MatrixXd& R, - const Eigen::MatrixXd& P) - : A(A), C(C), Q(Q), R(R), P0(P), - m(C.rows()), n(A.rows()), dt(dt), initialized(false), - I(n, n), x_hat(n), x_hat_new(n) -{ - I.setIdentity(); -} - -KalmanFilter::KalmanFilter() - : m(0), - n(0), - t0(0.0), - t(0.0), - dt(0.0), - initialized(false) -{ -} - -void KalmanFilter::init(double t0, const Eigen::VectorXd& x0) { - x_hat = x0; - P = P0; - this->t0 = t0; - t = t0; - initialized = true; -} - -void KalmanFilter::init() { - x_hat.setZero(); - P = P0; - t0 = 0; - t = t0; - initialized = true; -} - -void KalmanFilter::update(const Eigen::VectorXd& y) { - - if(!initialized) - throw std::runtime_error("Filter is not initialized!"); - - if (y.size() != m) - throw std::runtime_error("KalmanFilter::update(): measurement vector has wrong size"); - - if (A.rows() != n || A.cols() != n || C.rows() != m || C.cols() != n || - Q.rows() != n || Q.cols() != n || R.rows() != m || R.cols() != m || - P.rows() != n || P.cols() != n) - throw std::runtime_error("KalmanFilter::update(): matrix dimensions are inconsistent"); - - x_hat_new = A * x_hat; - P = A*P*A.transpose() + Q; - - const Eigen::MatrixXd S = C * P * C.transpose() + R; - Eigen::LDLT ldlt(S); - if (ldlt.info() != Eigen::Success) - throw std::runtime_error("KalmanFilter::update(): failed to decompose innovation covariance"); - - // K = P*C' * inv(S) -> solve(S * X = (P*C')^T) - const Eigen::MatrixXd PCt = P * C.transpose(); - const Eigen::MatrixXd KT = ldlt.solve(PCt.transpose()); - if (ldlt.info() != Eigen::Success) - throw std::runtime_error("KalmanFilter::update(): failed to solve for Kalman gain"); - K = KT.transpose(); - - x_hat_new += K * (y - C*x_hat_new); - - // Joseph form: keeps P symmetric / PSD under numeric errors - const Eigen::MatrixXd IKC = I - K * C; - P = IKC * P * IKC.transpose() + K * R * K.transpose(); - x_hat = x_hat_new; - - t += dt; -} - -void KalmanFilter::update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A) { - - this->A = A; - this->dt = dt; - update(y); -} +/** +* Implementation of KalmanFilter class. +* +* @author: Hayk Martirosyan +* @date: 2014.11.15 +*/ + +#include +#include + +#include + +KalmanFilter::KalmanFilter( + double dt, + const Eigen::MatrixXd& A, + const Eigen::MatrixXd& C, + const Eigen::MatrixXd& Q, + const Eigen::MatrixXd& R, + const Eigen::MatrixXd& P) + : A(A), C(C), Q(Q), R(R), P0(P), + m(C.rows()), n(A.rows()), dt(dt), initialized(false), + I(n, n), x_hat(n), x_hat_new(n) +{ + I.setIdentity(); +} + +KalmanFilter::KalmanFilter() + : m(0), + n(0), + t0(0.0), + t(0.0), + dt(0.0), + initialized(false) +{ +} + +void KalmanFilter::init(double t0, const Eigen::VectorXd& x0) { + x_hat = x0; + P = P0; + this->t0 = t0; + t = t0; + initialized = true; +} + +void KalmanFilter::init() { + x_hat.setZero(); + P = P0; + t0 = 0; + t = t0; + initialized = true; +} + +void KalmanFilter::update(const Eigen::VectorXd& y) { + + if(!initialized) + throw std::runtime_error("Filter is not initialized!"); + + if (y.size() != m) + throw std::runtime_error("KalmanFilter::update(): measurement vector has wrong size"); + + if (A.rows() != n || A.cols() != n || C.rows() != m || C.cols() != n || + Q.rows() != n || Q.cols() != n || R.rows() != m || R.cols() != m || + P.rows() != n || P.cols() != n) + throw std::runtime_error("KalmanFilter::update(): matrix dimensions are inconsistent"); + + x_hat_new = A * x_hat; + P = A*P*A.transpose() + Q; + + const Eigen::MatrixXd S = C * P * C.transpose() + R; + Eigen::LDLT ldlt(S); + if (ldlt.info() != Eigen::Success) + throw std::runtime_error("KalmanFilter::update(): failed to decompose innovation covariance"); + + // K = P*C' * inv(S) -> solve(S * X = (P*C')^T) + const Eigen::MatrixXd PCt = P * C.transpose(); + const Eigen::MatrixXd KT = ldlt.solve(PCt.transpose()); + if (ldlt.info() != Eigen::Success) + throw std::runtime_error("KalmanFilter::update(): failed to solve for Kalman gain"); + K = KT.transpose(); + + x_hat_new += K * (y - C*x_hat_new); + + // Joseph form: keeps P symmetric / PSD under numeric errors + const Eigen::MatrixXd IKC = I - K * C; + P = IKC * P * IKC.transpose() + K * R * K.transpose(); + x_hat = x_hat_new; + + t += dt; +} + +void KalmanFilter::update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A) { + + this->A = A; + this->dt = dt; + update(y); +} diff --git a/src/Algorithms/Libraries/mkt_algorithm/CMakeLists.txt b/src/Algorithms/Libraries/mkt_algorithm/CMakeLists.txt index 1f54a64..cccf466 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/CMakeLists.txt +++ b/src/Algorithms/Libraries/mkt_algorithm/CMakeLists.txt @@ -1,190 +1,190 @@ -cmake_minimum_required(VERSION 3.0.2) -project(mkt_algorithm VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building mkt_algorithm with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building mkt_algorithm with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -# Find dependencies -find_package(Boost REQUIRED COMPONENTS system) -find_package(Eigen3 REQUIRED) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - - set(PACKAGES_DIR - geometry_msgs - score_algorithm - robot_nav_2d_msgs - robot_nav_2d_utils - kalman - angles - nav_grid - robot_costmap_2d - robot_sensor_msgs - robot_std_msgs - robot_cpp - ) - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED COMPONENTS - geometry_msgs - score_algorithm - robot_nav_2d_msgs - robot_nav_2d_utils - kalman - angles - nav_grid - robot_costmap_2d - robot_sensor_msgs - robot_std_msgs - robot_cpp - ) - - catkin_package( - INCLUDE_DIRS include - LIBRARIES ${PROJECT_NAME}_diff - CATKIN_DEPENDS geometry_msgs score_algorithm robot_nav_2d_msgs robot_nav_2d_utils kalman angles nav_grid robot_costmap_2d robot_sensor_msgs robot_std_msgs robot_cpp - DEPENDS Boost Eigen3 - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ${EIGEN3_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ) -endif() - -# ======================================================== -# Libraries -# ======================================================== -add_library(${PROJECT_NAME}_diff SHARED - src/diff/diff_predictive_trajectory.cpp - src/diff/diff_rotate_to_goal.cpp - src/diff/diff_go_straight.cpp -) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME}_diff ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - target_include_directories(${PROJECT_NAME}_diff - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME}_diff - PUBLIC ${catkin_LIBRARIES} - PRIVATE Boost::system Eigen3::Eigen - ) - -else() - - target_include_directories(${PROJECT_NAME}_diff - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME}_diff - PUBLIC - ${PACKAGES_DIR} - PRIVATE - Boost::system Eigen3::Eigen - ) - - set_target_properties(${PROJECT_NAME}_diff PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - -endif() - -# ======================================================== -# Install -# ======================================================== -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME}_diff - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - ## Install plugins.xml if it exists - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) - install(FILES plugins.xml - DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} - ) - endif() - -else() - - install(TARGETS ${PROJECT_NAME}_diff - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - ## Install plugins.xml if it exists - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) - install(FILES plugins.xml - DESTINATION share/${PROJECT_NAME} - ) - endif() - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME}") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Libraries: ${PROJECT_NAME}_diff") - message(STATUS "Dependencies: geometry_msgs, score_algorithm, robot_nav_2d_msgs, robot_nav_2d_utils, kalman, angles, nav_grid, robot_costmap_2d, robot_sensor_msgs, robot_std_msgs, robot_cpp, Boost, Eigen3") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(mkt_algorithm VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building mkt_algorithm with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building mkt_algorithm with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Find dependencies +find_package(Boost REQUIRED COMPONENTS system) +find_package(Eigen3 REQUIRED) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + set(PACKAGES_DIR + geometry_msgs + score_algorithm + robot_nav_2d_msgs + robot_nav_2d_utils + kalman + angles + nav_grid + robot_costmap_2d + robot_sensor_msgs + robot_std_msgs + robot_cpp + ) + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED COMPONENTS + geometry_msgs + score_algorithm + robot_nav_2d_msgs + robot_nav_2d_utils + kalman + angles + nav_grid + robot_costmap_2d + robot_sensor_msgs + robot_std_msgs + robot_cpp + ) + + catkin_package( + INCLUDE_DIRS include + LIBRARIES ${PROJECT_NAME}_diff + CATKIN_DEPENDS geometry_msgs score_algorithm robot_nav_2d_msgs robot_nav_2d_utils kalman angles nav_grid robot_costmap_2d robot_sensor_msgs robot_std_msgs robot_cpp + DEPENDS Boost Eigen3 + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ${EIGEN3_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) +endif() + +# ======================================================== +# Libraries +# ======================================================== +add_library(${PROJECT_NAME}_diff SHARED + src/diff/diff_predictive_trajectory.cpp + src/diff/diff_rotate_to_goal.cpp + src/diff/diff_go_straight.cpp +) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME}_diff ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + target_include_directories(${PROJECT_NAME}_diff + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME}_diff + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::system Eigen3::Eigen + ) + +else() + + target_include_directories(${PROJECT_NAME}_diff + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME}_diff + PUBLIC + ${PACKAGES_DIR} + PRIVATE + Boost::system Eigen3::Eigen + ) + + set_target_properties(${PROJECT_NAME}_diff PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + +endif() + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME}_diff + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + ## Install plugins.xml if it exists + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) + install(FILES plugins.xml + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} + ) + endif() + +else() + + install(TARGETS ${PROJECT_NAME}_diff + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + ## Install plugins.xml if it exists + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) + install(FILES plugins.xml + DESTINATION share/${PROJECT_NAME} + ) + endif() + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME}") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Libraries: ${PROJECT_NAME}_diff") + message(STATUS "Dependencies: geometry_msgs, score_algorithm, robot_nav_2d_msgs, robot_nav_2d_utils, kalman, angles, nav_grid, robot_costmap_2d, robot_sensor_msgs, robot_std_msgs, robot_cpp, Boost, Eigen3") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/bicycle.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/bicycle.h index 260a595..281d87d 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/bicycle.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/bicycle.h @@ -1,108 +1,108 @@ -#ifndef _NAV_ALGORITHM_BICYCLE_H_INCLUDED__ -#define _NAV_ALGORITHM_BICYCLE_H_INCLUDED__ - -#include -#include -#include -#include -#include -#include - -namespace mkt_algorithm -{ - -/** - * @class Bicycle - * @brief Standard Bicycle-like ScoreAlgorithm -*/ -class Bicycle : public score_algorithm::ScoreAlgorithm -{ -public: - - Bicycle() {}; //: line_generator_(nullptr) {}; - - virtual ~Bicycle() {}; - - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) override; - - /** - * @brief Reset all data - */ - virtual void reset() override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - */ - virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; - - -protected: - - unsigned int getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, - const double distance, unsigned int start_index, unsigned int last_valid_index) const; - - double journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const; - - - bool getGoalPose(const robot_geometry_msgs::Pose2D &robot_pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_nav_2d_msgs::Path2D &global_plan, robot_geometry_msgs::Pose2D &sub_goal, - double &target_direction); - - bool findSubGoalIndex(const std::vector &plan, std::vector &index_s); - - robot::NodeHandle nh_priv_, nh_; - std::string frame_id_path_; - robot::Publisher reached_intermediate_goals_pub_, current_goal_pub_, closet_robot_goal_pub_; - - std::vector reached_intermediate_goals_; - robot_geometry_msgs::Pose2D rev_sub_goal_, sub_goal_; - robot_geometry_msgs::Pose2D goal_; - robot_nav_2d_msgs::Path2D global_plan_; - - unsigned int start_index_saved_; - unsigned int sub_goal_index_saved_, sub_start_index_saved_; - std::vector start_index_saved_vt_; - int index_samples_; - - double steering_fix_wheel_distance_x_; - double steering_fix_wheel_distance_y_; - double xy_local_goal_tolerance_; - double xy_goal_tolerance_; - double angle_threshold_; - double acc_lim_theta_; - double decel_lim_theta_; - double x_direction_, y_direction_, theta_direction_; - double k_d_reduce_, distance_rg_, k_ld_, ld_min_, ld_max_; - double controller_frequency_param_name_; - - bool follow_step_path_; - bool is_filter_; - boost::shared_ptr kf_; - robot::Publisher cmd_raw_pub_; - robot::Time last_actuator_update_; -}; // class Bicycle - -} // namespace mkt_algorithm - - +#ifndef _NAV_ALGORITHM_BICYCLE_H_INCLUDED__ +#define _NAV_ALGORITHM_BICYCLE_H_INCLUDED__ + +#include +#include +#include +#include +#include +#include + +namespace mkt_algorithm +{ + +/** + * @class Bicycle + * @brief Standard Bicycle-like ScoreAlgorithm +*/ +class Bicycle : public score_algorithm::ScoreAlgorithm +{ +public: + + Bicycle() {}; //: line_generator_(nullptr) {}; + + virtual ~Bicycle() {}; + + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) override; + + /** + * @brief Reset all data + */ + virtual void reset() override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + */ + virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; + + +protected: + + unsigned int getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, + const double distance, unsigned int start_index, unsigned int last_valid_index) const; + + double journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const; + + + bool getGoalPose(const robot_geometry_msgs::Pose2D &robot_pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_nav_2d_msgs::Path2D &global_plan, robot_geometry_msgs::Pose2D &sub_goal, + double &target_direction); + + bool findSubGoalIndex(const std::vector &plan, std::vector &index_s); + + robot::NodeHandle nh_priv_, nh_; + std::string frame_id_path_; + robot::Publisher reached_intermediate_goals_pub_, current_goal_pub_, closet_robot_goal_pub_; + + std::vector reached_intermediate_goals_; + robot_geometry_msgs::Pose2D rev_sub_goal_, sub_goal_; + robot_geometry_msgs::Pose2D goal_; + robot_nav_2d_msgs::Path2D global_plan_; + + unsigned int start_index_saved_; + unsigned int sub_goal_index_saved_, sub_start_index_saved_; + std::vector start_index_saved_vt_; + int index_samples_; + + double steering_fix_wheel_distance_x_; + double steering_fix_wheel_distance_y_; + double xy_local_goal_tolerance_; + double xy_goal_tolerance_; + double angle_threshold_; + double acc_lim_theta_; + double decel_lim_theta_; + double x_direction_, y_direction_, theta_direction_; + double k_d_reduce_, distance_rg_, k_ld_, ld_min_, ld_max_; + double controller_frequency_param_name_; + + bool follow_step_path_; + bool is_filter_; + boost::shared_ptr kf_; + robot::Publisher cmd_raw_pub_; + robot::Time last_actuator_update_; +}; // class Bicycle + +} // namespace mkt_algorithm + + #endif //_NAV_ALGORITHM_BICYCLE_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/equation_line.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/equation_line.h index e201e10..682b399 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/equation_line.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/equation_line.h @@ -1,74 +1,74 @@ -#ifndef __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__ -#define __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__ -#include -#include -#include - -namespace mkt_algorithm -{ - -/** - * @class NoSolution - */ -class NoSolution : public std::exception { - public: - const char * what () const throw () { - return "Robot cannot calculate error line!"; - } -}; // class NoSolution - -/** - * @class LineGenerator - */ -class LineGenerator -{ - /* data */ - struct LineEquation { - robot_geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊) */ - robot_geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋) */ - float a, b, c ; /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */ - }; - - /* Save data present position */ - struct PresentPosition { - float Gxh, Gyh; /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */ - float Yaw_degree; /* Angle of Robot (degree) */ - float Yaw_rad; /* Angle of Robot (degree) */ - float error_line; /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2) */ - double distance_to_goal; /* The distance from query pose to goal */ - double distance_to_start; /* The distance from query pose to start*/ - double distace_start_goal; - }; -public: - - /** - * @brief To caculated the equation of the line - * @param start_point start point of the line - * @param end_point end point of the line - */ - virtual bool calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point); - - /** - * @brief Calculating error - * @param[in] Lm The distance from the center of the wheel axis to the center line - * @param[in] pose - * @param[in] rev - */ - virtual void calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev = false); - - /** - * @brief Calculating tolerance - * @param query_pose The pose to check - * @param goal_pose The pose to check against - */ - virtual double calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose); - - /* Properties */ - LineEquation Leq_; - PresentPosition present_pose_; - -}; // class LineGenerator - -} // namespace mkt_algorithm - +#ifndef __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__ +#define __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__ +#include +#include +#include + +namespace mkt_algorithm +{ + +/** + * @class NoSolution + */ +class NoSolution : public std::exception { + public: + const char * what () const throw () { + return "Robot cannot calculate error line!"; + } +}; // class NoSolution + +/** + * @class LineGenerator + */ +class LineGenerator +{ + /* data */ + struct LineEquation { + robot_geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊) */ + robot_geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋) */ + float a, b, c ; /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */ + }; + + /* Save data present position */ + struct PresentPosition { + float Gxh, Gyh; /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */ + float Yaw_degree; /* Angle of Robot (degree) */ + float Yaw_rad; /* Angle of Robot (degree) */ + float error_line; /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2) */ + double distance_to_goal; /* The distance from query pose to goal */ + double distance_to_start; /* The distance from query pose to start*/ + double distace_start_goal; + }; +public: + + /** + * @brief To caculated the equation of the line + * @param start_point start point of the line + * @param end_point end point of the line + */ + virtual bool calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point); + + /** + * @brief Calculating error + * @param[in] Lm The distance from the center of the wheel axis to the center line + * @param[in] pose + * @param[in] rev + */ + virtual void calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev = false); + + /** + * @brief Calculating tolerance + * @param query_pose The pose to check + * @param goal_pose The pose to check against + */ + virtual double calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose); + + /* Properties */ + LineEquation Leq_; + PresentPosition present_pose_; + +}; // class LineGenerator + +} // namespace mkt_algorithm + #endif // __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/go_straight.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/go_straight.h index 0faaa06..2890265 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/go_straight.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/go_straight.h @@ -1,70 +1,70 @@ -#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ -#define _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ - -#include -#include -#include -#include - -namespace mkt_algorithm -{ - -/** - * @class GoStraight - * @brief Standard Bicycle-like ScoreAlgorithm -*/ -class GoStraight : public score_algorithm::ScoreAlgorithm -{ -public: - - GoStraight() {}; - - virtual ~GoStraight() {}; - - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) override; - - /** - * @brief Reset all data - */ - virtual void reset() override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - */ - virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; - - -protected: - robot::NodeHandle nh_; - robot::NodeHandle nh_kinematics_; - - double steering_fix_wheel_distance_x_; - double steering_fix_wheel_distance_y_; - robot_geometry_msgs::Pose2D goal_; - robot::Time time_last_cmd_; - -}; // class GoStraight - -} // namespace mkt_algorithm - +#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ +#define _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ + +#include +#include +#include +#include + +namespace mkt_algorithm +{ + +/** + * @class GoStraight + * @brief Standard Bicycle-like ScoreAlgorithm +*/ +class GoStraight : public score_algorithm::ScoreAlgorithm +{ +public: + + GoStraight() {}; + + virtual ~GoStraight() {}; + + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) override; + + /** + * @brief Reset all data + */ + virtual void reset() override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + */ + virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; + + +protected: + robot::NodeHandle nh_; + robot::NodeHandle nh_kinematics_; + + double steering_fix_wheel_distance_x_; + double steering_fix_wheel_distance_y_; + robot_geometry_msgs::Pose2D goal_; + robot::Time time_last_cmd_; + +}; // class GoStraight + +} // namespace mkt_algorithm + #endif \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/goal_checker.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/goal_checker.h index 6c24369..6fde87f 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/goal_checker.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/goal_checker.h @@ -1,45 +1,45 @@ -#ifndef _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__ -#define _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__ - -#include -#include - -namespace mkt_algorithm -{ -class GoalChecker : public score_algorithm::GoalChecker -{ -public: - - /** - * @brief Initialize any parameters from the NodeHandle - * @param nh NodeHandle for grabbing parameters - */ - virtual void initialize(const robot::NodeHandle& nh) override; - - /** - * @brief Reset the state of the goal checker (if any) - */ - virtual void reset() override; - - /** - * @brief Check whether the goal should be considered reached - * @param query_pose The pose to check - * @param goal_pose The pose to check against - * @param velocity The robot's current velocity - * @return True if goal is reached - */ - bool isGoalReached(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose, - const std::vector& path, const robot_nav_2d_msgs::Twist2D& velocity) override; - -protected: - - boost::shared_ptr line_generator_; - double yaw_goal_tolerance_; - double xy_goal_tolerance_; - double old_xy_goal_tolerance_; - bool setup_; -}; - -} // namespace mkt_algorithm - +#ifndef _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__ +#define _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__ + +#include +#include + +namespace mkt_algorithm +{ +class GoalChecker : public score_algorithm::GoalChecker +{ +public: + + /** + * @brief Initialize any parameters from the NodeHandle + * @param nh NodeHandle for grabbing parameters + */ + virtual void initialize(const robot::NodeHandle& nh) override; + + /** + * @brief Reset the state of the goal checker (if any) + */ + virtual void reset() override; + + /** + * @brief Check whether the goal should be considered reached + * @param query_pose The pose to check + * @param goal_pose The pose to check against + * @param velocity The robot's current velocity + * @return True if goal is reached + */ + bool isGoalReached(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose, + const std::vector& path, const robot_nav_2d_msgs::Twist2D& velocity) override; + +protected: + + boost::shared_ptr line_generator_; + double yaw_goal_tolerance_; + double xy_goal_tolerance_; + double old_xy_goal_tolerance_; + bool setup_; +}; + +} // namespace mkt_algorithm + #endif // _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/pta.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/pta.h index 62ade0e..201462d 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/pta.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/pta.h @@ -1,60 +1,60 @@ -#ifndef _NAV_ALGORITHM_PTA_H_INCLUDED__ -#define _NAV_ALGORITHM_PTA_H_INCLUDED__ - -#include -#include - -namespace mkt_algorithm -{ - -/** - * @class PTA - * @brief Standard PTA-like ScoreAlgorithm -*/ -class PTA : public score_algorithm::ScoreAlgorithm -{ -public: - - PTA() : line_generator_(nullptr) {}; - - virtual ~PTA() {}; - -// Standard ScoreAlgorithm Interface - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - */ - virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; - -protected: - - boost::shared_ptr line_generator_; - double pta_amplitude_max_; // (Default: 0.5 - Range: 0.1 -> 1.0) Cai dat bien do (mot phia - m) cho phep robot di chuyen trong do - -}; // class PTA - -} // namespace mkt_algorithm - - +#ifndef _NAV_ALGORITHM_PTA_H_INCLUDED__ +#define _NAV_ALGORITHM_PTA_H_INCLUDED__ + +#include +#include + +namespace mkt_algorithm +{ + +/** + * @class PTA + * @brief Standard PTA-like ScoreAlgorithm +*/ +class PTA : public score_algorithm::ScoreAlgorithm +{ +public: + + PTA() : line_generator_(nullptr) {}; + + virtual ~PTA() {}; + +// Standard ScoreAlgorithm Interface + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + */ + virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; + +protected: + + boost::shared_ptr line_generator_; + double pta_amplitude_max_; // (Default: 0.5 - Range: 0.1 -> 1.0) Cai dat bien do (mot phia - m) cho phep robot di chuyen trong do + +}; // class PTA + +} // namespace mkt_algorithm + + #endif //_NAV_ALGORITHM_PTA_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/rotate_to_goal.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/rotate_to_goal.h index 413eb08..0937070 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/rotate_to_goal.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/bicycle/rotate_to_goal.h @@ -1,74 +1,74 @@ -#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ -#define _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ - -#include -#include -#include -#include - -namespace mkt_algorithm -{ - -/** - * @class GoStraight - * @brief Standard Bicycle-like ScoreAlgorithm -*/ -class RotateToGoal : public score_algorithm::ScoreAlgorithm -{ -public: - - RotateToGoal() {}; - - virtual ~RotateToGoal() {}; - - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) override; - - /** - * @brief Reset all data - */ - virtual void reset() override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - */ - virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; - - -protected: - robot::NodeHandle nh_; - robot::NodeHandle nh_kinematics_; - robot_geometry_msgs::Pose2D sub_goal_; - - double steering_fix_wheel_distance_x_; - double steering_fix_wheel_distance_y_; - double angle_threshold_; - double current_direction_; - double velocity_rotate_min_, velocity_rotate_max_; - robot_geometry_msgs::Pose2D goal_; - robot::Time time_last_cmd_; - -}; // class RotateToGoal - -} // namespace mkt_algorithm - +#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ +#define _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__ + +#include +#include +#include +#include + +namespace mkt_algorithm +{ + +/** + * @class GoStraight + * @brief Standard Bicycle-like ScoreAlgorithm +*/ +class RotateToGoal : public score_algorithm::ScoreAlgorithm +{ +public: + + RotateToGoal() {}; + + virtual ~RotateToGoal() {}; + + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) override; + + /** + * @brief Reset all data + */ + virtual void reset() override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + */ + virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override; + + +protected: + robot::NodeHandle nh_; + robot::NodeHandle nh_kinematics_; + robot_geometry_msgs::Pose2D sub_goal_; + + double steering_fix_wheel_distance_x_; + double steering_fix_wheel_distance_y_; + double angle_threshold_; + double current_direction_; + double velocity_rotate_min_, velocity_rotate_max_; + robot_geometry_msgs::Pose2D goal_; + robot::Time time_last_cmd_; + +}; // class RotateToGoal + +} // namespace mkt_algorithm + #endif \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_go_straight.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_go_straight.h index 88d3dba..6a72419 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_go_straight.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_go_straight.h @@ -1,49 +1,49 @@ -#ifndef _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__ -#define _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__ - -#include - -namespace mkt_algorithm -{ - - namespace diff - { - /** - * @class GoStraight - * @brief Standard Bicycle-like ScoreAlgorithm - */ - class GoStraight : public mkt_algorithm::diff::PredictiveTrajectory - { - public: - GoStraight(); - - virtual ~GoStraight(); - - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize( - robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - * @param traj - */ - virtual mkt_msgs::Trajectory2D calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Create a new GoStraight instance - * @return A pointer to the new GoStraight instance - */ - static score_algorithm::ScoreAlgorithm::Ptr create(); - - }; // class GoStraight - } // namespace diff - -} // namespace mkt_algorithm - +#ifndef _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__ +#define _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__ + +#include + +namespace mkt_algorithm +{ + + namespace diff + { + /** + * @class GoStraight + * @brief Standard Bicycle-like ScoreAlgorithm + */ + class GoStraight : public mkt_algorithm::diff::PredictiveTrajectory + { + public: + GoStraight(); + + virtual ~GoStraight(); + + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize( + robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + * @param traj + */ + virtual mkt_msgs::Trajectory2D calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Create a new GoStraight instance + * @return A pointer to the new GoStraight instance + */ + static score_algorithm::ScoreAlgorithm::Ptr create(); + + }; // class GoStraight + } // namespace diff + +} // namespace mkt_algorithm + #endif // _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_predictive_trajectory.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_predictive_trajectory.h index 76233d8..99cf35f 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_predictive_trajectory.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_predictive_trajectory.h @@ -1,433 +1,433 @@ -#ifndef _NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__ -#define _NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace mkt_algorithm -{ - namespace diff - { - /** - * @class PredictiveTrajectory - * @brief Standard PredictiveTrajectory-like ScoreAlgorithm - */ - class PredictiveTrajectory : public score_algorithm::ScoreAlgorithm - { - public: - /** - * @brief Constructor - */ - PredictiveTrajectory(); - - /** - * @brief Destructor - */ - virtual ~PredictiveTrajectory(); - - // Standard ScoreAlgorithm Interface - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize( - robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, - double &x_direction, double &y_direction, double &theta_direction) override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - * @param traj - */ - virtual mkt_msgs::Trajectory2D calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Reset all data - */ - virtual void reset() override; - - /** - * @brief Stoping move navigation - */ - virtual void stop() override; - - /** - * @brief resume move navigation after stopped - */ - virtual void resume() override; - - /** - * @brief Create a new PredictiveTrajectory instance - * @return A pointer to the new PredictiveTrajectory instance - */ - static score_algorithm::ScoreAlgorithm::Ptr create(); - - protected: - inline double sign(double x) - { - return x < 0.0 ? -1.0 : 1.0; - } - - /** - * @brief Initialize parameters - */ - virtual void getParams(); - - /** - * @brief Dynamically adjust look ahead distance based on the speed - * @param velocity - * @return look ahead distance - */ - double getLookAheadDistance(const robot_nav_2d_msgs::Twist2D &velocity); - - /** - * @brief Get lookahead point on the global plan - * @param lookahead_dist - * @param global_plan - * @return lookahead point - */ - std::vector::iterator - getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan); - - /** - * @brief Prune global plan - * @param tf - * @param pose - * @param global_plan - * @param dist_behind_robot - * @return true if plan is pruned, false otherwise - */ - bool pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose, - robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot); - - /** - * @brief Transforms the global plan of the robot from the planner frame to the local frame (modified). - * - * The method replaces transformGlobalPlan as defined in base_local_planner/goal_functions.h - * such that the index of the current goal pose is returned as well as - * the transformation between the global plan and the planning frame. - * @param tf A reference to a tf buffer - * @param global_plan The plan to be transformed - * @param pose The pose of the robot - * @param costmap A reference to the costmap being used so the window size for transforming can be computed - * @param global_frame The frame to transform the plan to - * @param max_plan_length Specify maximum length (cumulative Euclidean distances) of the transformed plan [if <=0: disabled; the length is also bounded by the local costmap size!] - * @param[out] transformed_plan Populated with the transformed plan - * @return \c true if the global plan is transformed, \c false otherwise - */ - bool transformGlobalPlan( - TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &robot_base_frame, double max_plan_length, - robot_nav_2d_msgs::Path2D &transformed_plan); - - /** - * @brief Calculate max kappa - * @param path - * @param preview_distance - * @return max kappa - */ - double calculateMaxKappa(const robot_nav_2d_msgs::Path2D &path, const double preview_distance = std::numeric_limits::max()); - - /** - * @brief Adjust speed with Hermite trajectory - * @param velocity - * @param trajectory - * @param v_target - * @param sign_x - * @return speed - */ - double adjustSpeedWithHermiteTrajectory( - const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Path2D &trajectory, double v_target, const double &sign_x - ); - - /** - * @brief Generate Hermite trajectory - * @param path - * @param drive_target - * @param velocity - * @param sign_x - * @param drive_cmd - * @return trajectory - */ - robot_nav_2d_msgs::Path2D generateTrajectory( - const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &drive_target, - const robot_nav_2d_msgs::Twist2D &velocity, const double &sign_x, robot_nav_2d_msgs::Twist2D &drive_cmd, const double &dt); - - /** - * @brief Generate trajectory - * @param path - * @param sign_x - * @return trajectory - */ - robot_nav_2d_msgs::Path2D generateParallelPath( - const robot_nav_2d_msgs::Path2D &path, const double &sign_x); - - /** - * @brief Generate Hermite trajectory - * @param path - * @param sign_x - * @return trajectory - */ - robot_nav_2d_msgs::Path2D generateHermiteTrajectory(const robot_nav_2d_msgs::Path2D &path, const double &sign_x); - - /** - * @brief Generate Hermite quadratic trajectory - * @param pose - * @param sign_x - * @return trajectory - */ - robot_nav_2d_msgs::Path2D generateHermiteQuadraticTrajectory(const robot_nav_2d_msgs::Path2D &path, const double &sign_x); - - /** - * @brief Should rotate to path - * @param carrot_pose - * @param velocity - * @param sign_x - * @param angle_to_path - * @return true if should rotate, false otherwise - */ - bool shouldRotateToPath( - const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, robot_nav_2d_msgs::Twist2D velocity, double &angle_to_path, const double &sign_x); - - /** - * @brief Rotate to heading - * @param angle_to_path - * @param velocity The velocity of the robot - * @param cmd_vel The velocity commands to be filled - */ - void rotateToHeading(const double &angle_to_path, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt); - - /** - * @brief Check if robot should align to final heading (near goal position) - * @param trajectory The transformed trajectory in robot frame - * @param goal The goal pose with desired final heading - * @param velocity Current velocity - * @param xy_error Output: distance to goal - * @param heading_error Output: angle difference to goal heading - * @return true if should enter final heading alignment phase - */ - bool shouldAlignToFinalHeading( - const robot_nav_2d_msgs::Path2D &trajectory, - const robot_nav_2d_msgs::Pose2DStamped &goal, - const robot_nav_2d_msgs::Twist2D &velocity, - double &xy_error, - double &heading_error, - const double &sign_x); - - /** - * @brief Arc Motion controller for final heading alignment - * Smoothly reduces linear velocity while adjusting angular velocity to reach final heading - * @param xy_error Distance to goal position - * @param heading_error Angle difference to goal heading - * @param velocity Current velocity - * @param sign_x Direction of motion (forward/backward) - * @param dt Time step - * @param cmd_vel Output velocity command - */ - void alignToFinalHeading( - const double &xy_error, - const double &heading_error, - const robot_nav_2d_msgs::Twist2D &velocity, - const double &sign_x, - const double &dt, - robot_nav_2d_msgs::Twist2D &cmd_vel); - - /** - * @brief PID controller - * @param error - * @param integral - * @param last_error - * @param dt - * @param kp - * @param ki - * @param kd - * @param output - */ - void pid(const double &error, double &integral, double &last_error, const double &dt, const double &kp, const double &ki, const double &kd, double &output); - - /** - * @brief the robot is moving acceleration limits - * @param velocity The velocity of the robot - * @param cmd_vel The velocity commands - * @param cmd_vel_result The velocity commands result - * @param dt The time step - */ - void moveWithAccLimits( - const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Twist2D &cmd_vel, robot_nav_2d_msgs::Twist2D &cmd_vel_result, const double &dt); - - /** - * @brief Stop the robot taking into account acceleration limits - * @param pose The pose of the robot in the global frame - * @param velocity The velocity of the robot - * @param cmd_vel The velocity commands to be filled - * @param dt The time step - * @return True if a valid trajectory was found, false otherwise - */ - bool stopWithAccLimits(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt); - - /** - * @brief Compute pure pursuit - * @param carrot_pose - * @param drive_target - * @param velocity - * @param trajectory - * @param min_approach_linear_velocity - * @param sign_x - * @param dt - * @param drive_cmd - */ - void computePurePursuit( - const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, - const robot_nav_2d_msgs::Twist2D &drive_target, - const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Path2D &trajectory, - const double &min_approach_linear_velocity, - const double &sign_x, - const double &dt, - robot_nav_2d_msgs::Twist2D &drive_cmd); - - /** - * @brief Apply distance-based speed scaling and acceleration limits - * @param plan The plan to be scaled - * @param velocity Current velocity - * @param drive_cmd Input/output velocity command - * @param sign_x Direction of motion - * @param dt Time step - */ - void applyDistanceSpeedScaling( - const robot_nav_2d_msgs::Path2D &plan, - const robot_nav_2d_msgs::Twist2D &velocity, - robot_nav_2d_msgs::Twist2D &drive_cmd, - const double &sign_x, - const double &dt); - - /** - * @brief Interpolate footprint - * @param pose - * @param footprint - * @param resolution - * @return interpolated footprint - */ - std::vector interpolateFootprint( - const robot_geometry_msgs::Pose2D &pose, const std::vector &footprint, const double &resolution); - - /** - * @brief Cost at pose - * @param x - * @param y - * @return cost - */ - double costAtPose(const double &x, const double &y); - - - bool initialized_; - bool nav_stop_; - robot::NodeHandle nh_, nh_priv_; - std::string frame_id_path_; - std::string robot_base_frame_; - - robot_nav_2d_msgs::Pose2DStamped goal_; - robot_nav_2d_msgs::Path2D global_plan_; - robot_nav_2d_msgs::Path2D compute_plan_; - robot_nav_2d_msgs::Path2D transform_plan_; - robot_nav_2d_msgs::Twist2D prevous_drive_cmd_; - - double x_direction_, y_direction_, theta_direction_; - - // Lookahead - bool use_velocity_scaled_lookahead_dist_; - double lookahead_time_; - double lookahead_dist_; - double min_lookahead_dist_; - double max_lookahead_dist_; - double max_lateral_accel_; - - // journey - double min_journey_squared_{1e9}; - double max_journey_squared_{1e9}; - - // Rotate to heading - bool use_rotate_to_heading_; - double rotate_to_heading_min_angle_; - double min_path_distance_, max_path_distance_; - - // Final heading alignment (Arc Motion) - bool use_final_heading_alignment_; - double final_heading_xy_tolerance_; // Distance threshold to trigger alignment - double final_heading_angle_tolerance_; // Angle threshold to consider heading reached - double final_heading_min_velocity_; // Minimum linear velocity during alignment - double final_heading_kp_angular_; // Proportional gain for angular control - double final_heading_ki_angular_; - double final_heading_kd_angular_; - - double near_goal_heading_integral_; - double near_goal_heading_last_error_; - bool near_goal_heading_was_active_; - - double min_approach_linear_velocity_; - - bool use_cost_regulated_linear_velocity_scaling_; - double inflation_cost_scaling_factor_; - double cost_scaling_dist_, cost_scaling_gain_; - - // Control frequency - double control_duration_; - std::vector footprint_spec_; - - robot::Time last_actuator_update_; - boost::shared_ptr kf_; - int m_, n_; - Eigen::MatrixXd A; - Eigen::MatrixXd C; - Eigen::MatrixXd Q; - Eigen::MatrixXd R; - Eigen::MatrixXd P; - - // Kalman filter tuning (for v and w filtering) - double kf_q_v_; - double kf_q_w_; - double kf_r_v_; - double kf_r_w_; - double kf_p0_; - bool kf_filter_angular_; -#ifdef BUILD_WITH_ROS - ros::Publisher lookahead_point_pub_; -#endif - - }; // class PredictiveTrajectory - - } // namespace diff - -} // namespace mkt_algorithm - +#ifndef _NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__ +#define _NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace mkt_algorithm +{ + namespace diff + { + /** + * @class PredictiveTrajectory + * @brief Standard PredictiveTrajectory-like ScoreAlgorithm + */ + class PredictiveTrajectory : public score_algorithm::ScoreAlgorithm + { + public: + /** + * @brief Constructor + */ + PredictiveTrajectory(); + + /** + * @brief Destructor + */ + virtual ~PredictiveTrajectory(); + + // Standard ScoreAlgorithm Interface + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize( + robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, + double &x_direction, double &y_direction, double &theta_direction) override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + * @param traj + */ + virtual mkt_msgs::Trajectory2D calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Reset all data + */ + virtual void reset() override; + + /** + * @brief Stoping move navigation + */ + virtual void stop() override; + + /** + * @brief resume move navigation after stopped + */ + virtual void resume() override; + + /** + * @brief Create a new PredictiveTrajectory instance + * @return A pointer to the new PredictiveTrajectory instance + */ + static score_algorithm::ScoreAlgorithm::Ptr create(); + + protected: + inline double sign(double x) + { + return x < 0.0 ? -1.0 : 1.0; + } + + /** + * @brief Initialize parameters + */ + virtual void getParams(); + + /** + * @brief Dynamically adjust look ahead distance based on the speed + * @param velocity + * @return look ahead distance + */ + double getLookAheadDistance(const robot_nav_2d_msgs::Twist2D &velocity); + + /** + * @brief Get lookahead point on the global plan + * @param lookahead_dist + * @param global_plan + * @return lookahead point + */ + std::vector::iterator + getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan); + + /** + * @brief Prune global plan + * @param tf + * @param pose + * @param global_plan + * @param dist_behind_robot + * @return true if plan is pruned, false otherwise + */ + bool pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose, + robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot); + + /** + * @brief Transforms the global plan of the robot from the planner frame to the local frame (modified). + * + * The method replaces transformGlobalPlan as defined in base_local_planner/goal_functions.h + * such that the index of the current goal pose is returned as well as + * the transformation between the global plan and the planning frame. + * @param tf A reference to a tf buffer + * @param global_plan The plan to be transformed + * @param pose The pose of the robot + * @param costmap A reference to the costmap being used so the window size for transforming can be computed + * @param global_frame The frame to transform the plan to + * @param max_plan_length Specify maximum length (cumulative Euclidean distances) of the transformed plan [if <=0: disabled; the length is also bounded by the local costmap size!] + * @param[out] transformed_plan Populated with the transformed plan + * @return \c true if the global plan is transformed, \c false otherwise + */ + bool transformGlobalPlan( + TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &robot_base_frame, double max_plan_length, + robot_nav_2d_msgs::Path2D &transformed_plan); + + /** + * @brief Calculate max kappa + * @param path + * @param preview_distance + * @return max kappa + */ + double calculateMaxKappa(const robot_nav_2d_msgs::Path2D &path, const double preview_distance = std::numeric_limits::max()); + + /** + * @brief Adjust speed with Hermite trajectory + * @param velocity + * @param trajectory + * @param v_target + * @param sign_x + * @return speed + */ + double adjustSpeedWithHermiteTrajectory( + const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Path2D &trajectory, double v_target, const double &sign_x + ); + + /** + * @brief Generate Hermite trajectory + * @param path + * @param drive_target + * @param velocity + * @param sign_x + * @param drive_cmd + * @return trajectory + */ + robot_nav_2d_msgs::Path2D generateTrajectory( + const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &drive_target, + const robot_nav_2d_msgs::Twist2D &velocity, const double &sign_x, robot_nav_2d_msgs::Twist2D &drive_cmd); + + /** + * @brief Generate trajectory + * @param path + * @param sign_x + * @return trajectory + */ + robot_nav_2d_msgs::Path2D generateParallelPath( + const robot_nav_2d_msgs::Path2D &path, const double &sign_x); + + /** + * @brief Generate Hermite trajectory + * @param path + * @param sign_x + * @return trajectory + */ + robot_nav_2d_msgs::Path2D generateHermiteTrajectory(const robot_nav_2d_msgs::Path2D &path, const double &sign_x); + + /** + * @brief Generate Hermite quadratic trajectory + * @param pose + * @param sign_x + * @return trajectory + */ + robot_nav_2d_msgs::Path2D generateHermiteQuadraticTrajectory(const robot_nav_2d_msgs::Path2D &path, const double &sign_x); + + /** + * @brief Should rotate to path + * @param carrot_pose + * @param velocity + * @param sign_x + * @param angle_to_path + * @return true if should rotate, false otherwise + */ + bool shouldRotateToPath( + const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, robot_nav_2d_msgs::Twist2D velocity, double &angle_to_path, const double &sign_x); + + /** + * @brief Rotate to heading + * @param angle_to_path + * @param velocity The velocity of the robot + * @param cmd_vel The velocity commands to be filled + */ + void rotateToHeading(const double &angle_to_path, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt); + + /** + * @brief Check if robot should align to final heading (near goal position) + * @param trajectory The transformed trajectory in robot frame + * @param goal The goal pose with desired final heading + * @param velocity Current velocity + * @param xy_error Output: distance to goal + * @param heading_error Output: angle difference to goal heading + * @return true if should enter final heading alignment phase + */ + bool shouldAlignToFinalHeading( + const robot_nav_2d_msgs::Path2D &trajectory, + const robot_nav_2d_msgs::Pose2DStamped &goal, + const robot_nav_2d_msgs::Twist2D &velocity, + double &xy_error, + double &heading_error, + const double &sign_x); + + /** + * @brief Arc Motion controller for final heading alignment + * Smoothly reduces linear velocity while adjusting angular velocity to reach final heading + * @param xy_error Distance to goal position + * @param heading_error Angle difference to goal heading + * @param velocity Current velocity + * @param sign_x Direction of motion (forward/backward) + * @param dt Time step + * @param cmd_vel Output velocity command + */ + void alignToFinalHeading( + const double &xy_error, + const double &heading_error, + const robot_nav_2d_msgs::Twist2D &velocity, + const double &sign_x, + const double &dt, + robot_nav_2d_msgs::Twist2D &cmd_vel); + + /** + * @brief PID controller + * @param error + * @param integral + * @param last_error + * @param dt + * @param kp + * @param ki + * @param kd + * @param output + */ + void pid(const double &error, double &integral, double &last_error, const double &dt, const double &kp, const double &ki, const double &kd, double &output); + + /** + * @brief the robot is moving acceleration limits + * @param velocity The velocity of the robot + * @param cmd_vel The velocity commands + * @param cmd_vel_result The velocity commands result + * @param dt The time step + */ + void moveWithAccLimits( + const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Twist2D &cmd_vel, robot_nav_2d_msgs::Twist2D &cmd_vel_result, const double &dt); + + /** + * @brief Stop the robot taking into account acceleration limits + * @param pose The pose of the robot in the global frame + * @param velocity The velocity of the robot + * @param cmd_vel The velocity commands to be filled + * @param dt The time step + * @return True if a valid trajectory was found, false otherwise + */ + bool stopWithAccLimits(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt); + + /** + * @brief Compute pure pursuit + * @param carrot_pose + * @param drive_target + * @param velocity + * @param trajectory + * @param min_approach_linear_velocity + * @param sign_x + * @param dt + * @param drive_cmd + */ + void computePurePursuit( + const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, + const robot_nav_2d_msgs::Twist2D &drive_target, + const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Path2D &trajectory, + const double &min_approach_linear_velocity, + const double &sign_x, + const double &dt, + robot_nav_2d_msgs::Twist2D &drive_cmd); + + /** + * @brief Apply distance-based speed scaling and acceleration limits + * @param plan The plan to be scaled + * @param velocity Current velocity + * @param drive_cmd Input/output velocity command + * @param sign_x Direction of motion + * @param dt Time step + */ + void applyDistanceSpeedScaling( + const robot_nav_2d_msgs::Path2D &plan, + const robot_nav_2d_msgs::Twist2D &velocity, + robot_nav_2d_msgs::Twist2D &drive_cmd, + const double &sign_x, + const double &dt); + + /** + * @brief Interpolate footprint + * @param pose + * @param footprint + * @param resolution + * @return interpolated footprint + */ + std::vector interpolateFootprint( + const robot_geometry_msgs::Pose2D &pose, const std::vector &footprint, const double &resolution); + + /** + * @brief Cost at pose + * @param x + * @param y + * @return cost + */ + double costAtPose(const double &x, const double &y); + + + bool initialized_; + bool nav_stop_; + robot::NodeHandle nh_, nh_priv_; + std::string frame_id_path_; + std::string robot_base_frame_; + + robot_nav_2d_msgs::Pose2DStamped goal_; + robot_nav_2d_msgs::Path2D global_plan_; + robot_nav_2d_msgs::Path2D compute_plan_; + robot_nav_2d_msgs::Path2D transform_plan_; + robot_nav_2d_msgs::Twist2D prevous_drive_cmd_; + + double x_direction_, y_direction_, theta_direction_; + + // Lookahead + bool use_velocity_scaled_lookahead_dist_; + double lookahead_time_; + double lookahead_dist_; + double min_lookahead_dist_; + double max_lookahead_dist_; + double max_lateral_accel_; + + // journey + double min_journey_squared_{1e9}; + double max_journey_squared_{1e9}; + + // Rotate to heading + bool use_rotate_to_heading_; + double rotate_to_heading_min_angle_; + double min_path_distance_, max_path_distance_; + + // Final heading alignment (Arc Motion) + bool use_final_heading_alignment_; + double final_heading_xy_tolerance_; // Distance threshold to trigger alignment + double final_heading_angle_tolerance_; // Angle threshold to consider heading reached + double final_heading_min_velocity_; // Minimum linear velocity during alignment + double final_heading_kp_angular_; // Proportional gain for angular control + double final_heading_ki_angular_; + double final_heading_kd_angular_; + + double near_goal_heading_integral_; + double near_goal_heading_last_error_; + bool near_goal_heading_was_active_; + + double min_approach_linear_velocity_; + + bool use_cost_regulated_linear_velocity_scaling_; + double inflation_cost_scaling_factor_; + double cost_scaling_dist_, cost_scaling_gain_; + + // Control frequency + double control_duration_; + std::vector footprint_spec_; + + robot::Time last_actuator_update_; + boost::shared_ptr kf_; + int m_, n_; + Eigen::MatrixXd A; + Eigen::MatrixXd C; + Eigen::MatrixXd Q; + Eigen::MatrixXd R; + Eigen::MatrixXd P; + + // Kalman filter tuning (for v and w filtering) + double kf_q_v_; + double kf_q_w_; + double kf_r_v_; + double kf_r_w_; + double kf_p0_; + bool kf_filter_angular_; +#ifdef BUILD_WITH_ROS + ros::Publisher lookahead_point_pub_; +#endif + + }; // class PredictiveTrajectory + + } // namespace diff + +} // namespace mkt_algorithm + #endif //_NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_rotate_to_goal.h b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_rotate_to_goal.h index e888cfc..519585f 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_rotate_to_goal.h +++ b/src/Algorithms/Libraries/mkt_algorithm/include/mkt_algorithm/diff/diff_rotate_to_goal.h @@ -1,68 +1,68 @@ -#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__ -#define _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__ - -#include - -namespace mkt_algorithm -{ - namespace diff - { - /** - * @class GoStraight - * @brief Standard Bicycle-like ScoreAlgorithm - */ - class RotateToGoal : public mkt_algorithm::diff::PredictiveTrajectory - { - public: - RotateToGoal(); - - virtual ~RotateToGoal(); - - /** - * @brief Initialize parameters as needed - * @param nh NodeHandle to read parameters from - */ - virtual void initialize( - robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override; - - /** - * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories - * - * Subclasses may overwrite. Return false in case there is any error. - * - * @param pose Current pose (costmap frame) - * @param velocity Current velocity - * @param goal The final goal (costmap frame) - * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points - */ - virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, - double &x_direction, double &y_direction, double &theta_direction) override; - - /** - * @brief Reset all data - */ - virtual void reset() override; - - /** - * @brief Calculating algorithm - * @param pose - * @param velocity - * @param traj - */ - virtual mkt_msgs::Trajectory2D calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Create a new RotateToGoal instance - * @return A pointer to the new RotateToGoal instance - */ - static score_algorithm::ScoreAlgorithm::Ptr create(); - - }; // class RotateToGoalDiff - - } // namespace diff - -} // namespace mkt_algorithm - +#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__ +#define _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__ + +#include + +namespace mkt_algorithm +{ + namespace diff + { + /** + * @class GoStraight + * @brief Standard Bicycle-like ScoreAlgorithm + */ + class RotateToGoal : public mkt_algorithm::diff::PredictiveTrajectory + { + public: + RotateToGoal(); + + virtual ~RotateToGoal(); + + /** + * @brief Initialize parameters as needed + * @param nh NodeHandle to read parameters from + */ + virtual void initialize( + robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override; + + /** + * @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories + * + * Subclasses may overwrite. Return false in case there is any error. + * + * @param pose Current pose (costmap frame) + * @param velocity Current velocity + * @param goal The final goal (costmap frame) + * @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points + */ + virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, + double &x_direction, double &y_direction, double &theta_direction) override; + + /** + * @brief Reset all data + */ + virtual void reset() override; + + /** + * @brief Calculating algorithm + * @param pose + * @param velocity + * @param traj + */ + virtual mkt_msgs::Trajectory2D calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Create a new RotateToGoal instance + * @return A pointer to the new RotateToGoal instance + */ + static score_algorithm::ScoreAlgorithm::Ptr create(); + + }; // class RotateToGoalDiff + + } // namespace diff + +} // namespace mkt_algorithm + #endif // _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/package.xml b/src/Algorithms/Libraries/mkt_algorithm/package.xml index 4a9b2bd..6240a78 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/package.xml +++ b/src/Algorithms/Libraries/mkt_algorithm/package.xml @@ -1,44 +1,44 @@ - - mkt_algorithm - 0.7.10 - - mkt_algorithm is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. mkt_algorithm - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/mkt_algorithm - - catkin - geometry_msgs - score_algorithm - robot_nav_2d_msgs - robot_nav_2d_utils - kalman - angles - nav_grid - robot_costmap_2d - robot_sensor_msgs - robot_std_msgs - robot_cpp - - geometry_msgs - score_algorithm - robot_nav_2d_msgs - robot_nav_2d_utils - kalman - angles - nav_grid - robot_costmap_2d - robot_sensor_msgs - robot_std_msgs - robot_cpp + + mkt_algorithm + 0.7.10 + + mkt_algorithm is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. mkt_algorithm + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/mkt_algorithm + + catkin + geometry_msgs + score_algorithm + robot_nav_2d_msgs + robot_nav_2d_utils + kalman + angles + nav_grid + robot_costmap_2d + robot_sensor_msgs + robot_std_msgs + robot_cpp + + geometry_msgs + score_algorithm + robot_nav_2d_msgs + robot_nav_2d_utils + kalman + angles + nav_grid + robot_costmap_2d + robot_sensor_msgs + robot_std_msgs + robot_cpp \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycel_go_straight.cpp b/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycel_go_straight.cpp index c35abf5..ef8880d 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycel_go_straight.cpp +++ b/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycel_go_straight.cpp @@ -1,68 +1,68 @@ -#include -#include -#include -#include - -namespace mkt_algorithm -{ - -void GoStraight::initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) -{ - nh_ = robot::NodeHandle(nh, name); - name_ = name; - tf_ = tf; - costmap_robot_ = costmap_robot; - - steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_x", 1.1); - steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_y", 0.); -} - -void GoStraight::reset() -{ - time_last_cmd_ = robot::Time::now(); -} - -bool GoStraight::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) -{ - goal_ = goal; - - const double rb_direction_x = goal_.x - pose.x; - const double rb_direction_y = goal_.y - pose.y; - const double rb_angle = atan2(rb_direction_y, rb_direction_x); - double rb_dir = cos(rb_angle- pose.theta); - x_direction = y_direction = theta_direction = rb_dir; - - return true; -} - -robot_nav_2d_msgs::Twist2DStamped GoStraight::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) -{ - robot_nav_2d_msgs::Twist2DStamped result; - result.header.stamp = robot::Time::now(); - - robot_geometry_msgs::Pose2D steer_to_baselink_pose; - - if(!getPose("steer_link", "base_link", steer_to_baselink_pose)) - return result; - double odom_alpha = steer_to_baselink_pose.theta; - if(fabs(odom_alpha) > 0.03) return result; - - double delta_x = goal_.x - pose.x; - double delta_y = goal_.y - pose.y; - - double d_rg = sqrt(pow(delta_x, 2) + pow(delta_y, 2)); - double d_reduce = std::min(std::max(fabs(velocity.x), 0.6), 0.9); - double v_min = 0.03 * velocity.x / (fabs(velocity.x) + 1e-9); - -// Van toc robot - double vr = d_rg > d_reduce? velocity.x : (velocity.x - v_min)*sin((d_rg / d_reduce) * (M_PI/2)) + v_min; - result.velocity.x = fabs(cos(fabs(0.0 - odom_alpha))) * vr / cos(std::min(M_PI/3, fabs(odom_alpha))); - // ROS_INFO("d_rg %f d_reduce %f V = %f %f", d_rg, d_reduce,velocity.x, vr); - return result; -} - -}; // namespace mkt_algorithm - +#include +#include +#include +#include + +namespace mkt_algorithm +{ + +void GoStraight::initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) +{ + nh_ = robot::NodeHandle(nh, name); + name_ = name; + tf_ = tf; + costmap_robot_ = costmap_robot; + + steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_x", 1.1); + steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_y", 0.); +} + +void GoStraight::reset() +{ + time_last_cmd_ = robot::Time::now(); +} + +bool GoStraight::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) +{ + goal_ = goal; + + const double rb_direction_x = goal_.x - pose.x; + const double rb_direction_y = goal_.y - pose.y; + const double rb_angle = atan2(rb_direction_y, rb_direction_x); + double rb_dir = cos(rb_angle- pose.theta); + x_direction = y_direction = theta_direction = rb_dir; + + return true; +} + +robot_nav_2d_msgs::Twist2DStamped GoStraight::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) +{ + robot_nav_2d_msgs::Twist2DStamped result; + result.header.stamp = robot::Time::now(); + + robot_geometry_msgs::Pose2D steer_to_baselink_pose; + + if(!getPose("steer_link", "base_link", steer_to_baselink_pose)) + return result; + double odom_alpha = steer_to_baselink_pose.theta; + if(fabs(odom_alpha) > 0.03) return result; + + double delta_x = goal_.x - pose.x; + double delta_y = goal_.y - pose.y; + + double d_rg = sqrt(pow(delta_x, 2) + pow(delta_y, 2)); + double d_reduce = std::min(std::max(fabs(velocity.x), 0.6), 0.9); + double v_min = 0.03 * velocity.x / (fabs(velocity.x) + 1e-9); + +// Van toc robot + double vr = d_rg > d_reduce? velocity.x : (velocity.x - v_min)*sin((d_rg / d_reduce) * (M_PI/2)) + v_min; + result.velocity.x = fabs(cos(fabs(0.0 - odom_alpha))) * vr / cos(std::min(M_PI/3, fabs(odom_alpha))); + // ROS_INFO("d_rg %f d_reduce %f V = %f %f", d_rg, d_reduce,velocity.x, vr); + return result; +} + +}; // namespace mkt_algorithm + PLUGINLIB_EXPORT_CLASS(mkt_algorithm::GoStraight, score_algorithm::ScoreAlgorithm) \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_pure_pursuit.cpp b/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_pure_pursuit.cpp index 39f63c2..bd8e061 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_pure_pursuit.cpp +++ b/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_pure_pursuit.cpp @@ -1,641 +1,641 @@ -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace mkt_algorithm -{ - -void Bicycle::initialize(const robot::NodeHandle& nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) -{ - nh_priv_ = robot::NodeHandle(nh, name); - nh_ = robot::NodeHandle("~"); - name_ = name; - tf_ = tf; - costmap_robot_ = costmap_robot; - last_actuator_update_ = robot::Time(0); - - nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5); - nh_priv_.param("xy_local_goal_tolerance_offset", xy_local_goal_tolerance_offset_, 0.5); - nh_priv_.param("angle_threshold", angle_threshold_, M_PI/8); - nh_priv_.param("index_samples", index_samples_, 0); - nh_priv_.param("filter", is_filter_, false); - - steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "steering_fix_wheel_distance_x", 1.1); - steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "steering_fix_wheel_distance_y", 0.); - xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "xy_goal_tolerance", 0.1); - acc_lim_theta_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "acc_lim_theta", 0.1); - decel_lim_theta_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "decel_lim_theta", 0.1); - controller_frequency_param_name_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "controller_frequency", 10); - if(controller_frequency_param_name_ <= 0.0) - { - ROS_WARN("controller_frequency is not setting lower 0.0 so will set to 1.0"); - controller_frequency_param_name_ = 1.0; - } - - reached_intermediate_goals_pub_ = nh_.advertise("reached_intermediate_goals", 1); - current_goal_pub_ = nh_.advertise("current_goal", 1); - closet_robot_goal_pub_ = nh_.advertise("closet_robot_goal", 1); - cmd_raw_pub_ = nh_.advertise("cmd_raw", 1); - x_direction_ = y_direction_= theta_direction_ = 0; - -// kalman - int n = 3; // Number of states - int m = 1; // Number of measurements - double dt = 1.0/controller_frequency_param_name_; // Time step - // ROS_INFO("controller_frequency_param_name %f", controller_frequency_param_name); - Eigen::MatrixXd A(n, n); // System dynamics matrix - Eigen::MatrixXd C(m, n); // Output matrix - Eigen::MatrixXd Q(n, n); // Process noise covariance - Eigen::MatrixXd R(m, m); // Measurement noise covariance - Eigen::MatrixXd P(n, n); // Estimate error covariance - - // Discrete LTI projectile motion, measuring position only - A << 1, dt, 0, 0, 1, dt, 0, 0, 1; - C << 1, 0, 0; - - // Reasonable covariance matrices - double q = 0.1; - double r = 0.6; - double p = 0.2; - Q << q, q, 0.0, q, q, 0.0, 0.0, 0.0, 0.0; - R << r; - P << p, p, p, p, 10.0, 1, p, 1, 10.0; - - // Construct the filter - kf_ = boost::make_shared(dt,A, C, Q, R, P); - // Best guess of initial states - Eigen::VectorXd x0(n); - x0 << 0.0, 0.0, 0.0; - kf_->init(robot::Time::now().toSec(), x0); -} - -void Bicycle::reset() -{ - reached_intermediate_goals_.clear(); - start_index_saved_vt_.clear(); - start_index_saved_ = 0; - sub_goal_index_saved_ = 0; - sub_start_index_saved_ = 0; - x_direction_ = y_direction_= theta_direction_ = 0; - follow_step_path_ = false; - last_actuator_update_ = robot::Time(0); -} - -bool Bicycle::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) -{ - nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5); - nh_priv_.param("xy_local_goal_tolerance_offset", xy_local_goal_tolerance_offset_, 0.5); - nh_priv_.param("angle_threshold", angle_threshold_, M_PI/8); - nh_priv_.param("index_samples", index_samples_, 0); - nh_priv_.param("distance_rg", distance_rg_, 0.1); - nh_priv_.param("k_ld", k_ld_, 1.0); - nh_priv_.param("k_d_reduce", k_d_reduce_, 1.0); - nh_priv_.param("ld_min", ld_min_, 0.2); - nh_priv_.param("ld_max", ld_max_, 1.1); - nh_priv_.param("follow_step_path", follow_step_path_, false); - - // ROS_INFO("%f %f %f %d", xy_local_goal_tolerance_, xy_local_goal_tolerance_offset_, angle_threshold_, index_samples_); - frame_id_path_ = global_plan.header.frame_id; - goal_ = goal; - global_plan_ = global_plan; - double rb_direction; - if(!getGoalPose(pose, velocity,global_plan, sub_goal_, rb_direction)) - { - ROS_ERROR("getGoalPose Failed"); - return false; - } - x_direction_= fabs(rb_direction)/rb_direction; - x_direction = x_direction_; - y_direction = y_direction_ = 0; - theta_direction = theta_direction_; - return true; -} - -robot_nav_2d_msgs::Twist2DStamped Bicycle::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) -{ - robot_nav_2d_msgs::Twist2DStamped result; - result.header.stamp = robot::Time::now(); - - robot_geometry_msgs::Pose2D steer_to_baselink_pose; - - if(!getPose("steer_link", "base_link", steer_to_baselink_pose)) - return result; - double actual_phi_steer = steer_to_baselink_pose.theta; - - const double L = sqrt(pow(steering_fix_wheel_distance_x_, 2) + pow(steering_fix_wheel_distance_y_, 2)); - const double delta_x = sub_goal_.x - pose.x; - const double delta_y = sub_goal_.y - pose.y; - const double d_rg = sqrt(pow(delta_x, 2) + pow(delta_y, 2)); - -// Van toc robot - double d_reduce = std::min(std::max(fabs(velocity.x) * k_d_reduce_, 0.6), 3.0); - double v_min = 0.05 * velocity.x / (fabs(velocity.x) + 1e-9); - double vr = d_rg > d_reduce? velocity.x : (velocity.x - v_min)*sin((d_rg / d_reduce) * (M_PI/2)) + v_min; - -// Góc lái của bánh lái là: α(t) - double alpha = atan2(delta_y,delta_x) - pose.theta; - double ld = std::min(std::max(fabs(velocity.x)*k_ld_, ld_min_), ld_max_); - // double ld = std::min(std::max(d_rg*k_ld_, ld_min_), ld_max_); - - double phi_steer = atan2(2 * L * sin(alpha), ld); - if(d_rg <= distance_rg_ && global_plan_.poses.size() > 1) - { - const double d_x = goal_.x - sub_goal_.x; - const double d_y = goal_.y - sub_goal_.y; - const double dd = sqrt(d_x * d_x + d_y * d_y); - const double d_theta = goal_.theta - sub_goal_.theta; - if(dd < 1e-5) - { - robot_geometry_msgs::Pose2D p = global_plan_.poses[global_plan_.poses.size() - 2]; - alpha = velocity.x / (fabs(velocity.x) + 1e-9)*(p.theta - pose.theta); - phi_steer = atan2(2 * L * sin(alpha), 1.0); - } - } - - double alpha_reduce = std::min(std::max(fabs(vr), 0.6), 1.0); - double cos_actual_phi_steer = cos( std::min(M_PI/2.3, fabs(actual_phi_steer))); - - // limit W - double result_W_max = 0.25; - // double result_W_min = 0.13; - double result_W = vr * fabs(cos(alpha)) * tan(actual_phi_steer) / L; - double V_s = std::max(alpha_reduce, fabs(cos(alpha))) * vr / cos_actual_phi_steer; - std::stringstream ss; - if(fabs(result_W) > 0.02) - { - double d_w = fabs(result_W) - fabs(velocity.theta); - double a = fabs(velocity.theta) > fabs(result_W) ? fabs(acc_lim_theta_/controller_frequency_param_name_) : fabs(decel_lim_theta_/controller_frequency_param_name_); - // ss << d_w << " " << a << " "; - double result; - if(fabs(d_w) >= a) - result = fabs(velocity.theta) + d_w / fabs(d_w + 1e-9) * a; - else if (fabs(d_w) < fabs(a)) - result = fabs(velocity.theta); - // ss << result_W << " " << velocity.theta << " "; - result_W = result_W / (fabs(result_W) + 1e-9) * result; - // ss << result_W << " "; - // ROS_INFO_STREAM(ss.str()); - - double d_v = fabs(result_W * L / tan(actual_phi_steer)) - fabs(vr); - if(fabs(d_v) >= a) - result = velocity.x / (fabs(velocity.x) + 1e-9)* (fabs(vr) + d_v / fabs(d_v + 1e-9) * a); - else if (fabs(d_v) < fabs(a)) - result = velocity.x / (fabs(velocity.x) + 1e-9) * fabs(vr); - - V_s = std::max(alpha_reduce, fabs(cos(alpha)))*result/ cos_actual_phi_steer; - } - - if(fabs(result_W) > result_W_max) - V_s = ( result_W / (fabs(result_W) + 1e-9) * result_W_max * L / tan(actual_phi_steer)) / cos_actual_phi_steer; - - if(is_filter_) - { - robot_geometry_msgs::Twist msg; - msg.linear.x = result.velocity.x; - msg.angular.z = phi_steer; - cmd_raw_pub_.publish(msg); - - Eigen::VectorXd y(1); - y << phi_steer; - robot::Time current_time = robot::Time::now(); - double dt = robot::Duration(current_time - last_actuator_update_).toSec(); - last_actuator_update_ = current_time; - Eigen::MatrixXd A(3, 3); // System dynamics matrix - A << 1, dt, 0, 0, 1, dt, 0, 0, 1; - kf_->update(y, dt, A); - phi_steer = kf_->state().transpose()[0]; - } - theta_direction_ = phi_steer !=0 ? phi_steer/(fabs(phi_steer) + 1e-9) * velocity.x/((fabs(velocity.x) + 1e-9)) : 0; - - result.velocity.theta = phi_steer; - result.velocity.x = fabs(cos(phi_steer - actual_phi_steer)) * V_s; - return result; -} - -unsigned int Bicycle::getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, - const double distance, unsigned int start_index, unsigned int last_valid_index) const -{ - if (start_index >= last_valid_index) - return last_valid_index; - - unsigned int goal_index = start_index; - const double start_direction_x = plan[start_index + 1].x - plan[start_index].x; - const double start_direction_y = plan[start_index + 1].y - plan[start_index].y; - if (fabs(start_direction_x) > 1e-9 || fabs(start_direction_y) > 1e-9) { // make sure that atan2 is defined - double start_angle = atan2(start_direction_y, start_direction_x); - double S = sqrt(pow(start_direction_x, 2) + pow(start_direction_y, 2)); - // double angle_threshold = 0.0; - for (unsigned int i = start_index + 1; i <= last_valid_index; ++i) - { - const double current_direction_x = plan[i].x - plan[i - 1].x; - const double current_direction_y = plan[i].y - plan[i - 1].y; - const double dd = sqrt(pow(current_direction_x, 2) + pow(current_direction_y, 2)); - S += dd; - if (fabs(current_direction_x) > 1e-9 || fabs(current_direction_y) > 1e-9) - { - double current_angle = atan2(current_direction_y, current_direction_x); - if(fabs(remainder(start_angle - current_angle, 2 * M_PI)) >= angle_threshold_ || S >= distance) - { - break; - } - goal_index = i; - } - } - } - return goal_index; -} - -bool Bicycle::getGoalPose(const robot_geometry_msgs::Pose2D &robot_pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_nav_2d_msgs::Path2D &global_plan, robot_geometry_msgs::Pose2D &sub_goal, - double &target_direction) -{ - const robot_nav_core2::Costmap &costmap = *costmap_; - const nav_grid::NavGridInfo &info = costmap.getInfo(); - - if (global_plan.poses.empty()) - { - ROS_ERROR_NAMED("PathProgressCritic", "The global plan was empty."); - return false; - } - // Chuyển đổi dữ liệu kế hoạch đường đi 'robot_nav_2d_msgs::Path2D' sang 'std::vector' - std::vector plan = global_plan.poses; - - std::vector index_s; - if(!findSubGoalIndex(plan, index_s)) - { - ROS_ERROR_NAMED("PathProgressCritic", "Can not find SubGoal Index"); - return false; - } - // else - // { - // std::stringstream ss; - // for(auto i : index_s) ss << i << " "; - // ROS_INFO_STREAM(ss.str()); - // } - - unsigned int sub_goal_index = sub_goal_index_saved_; - unsigned int sub_start_index = sub_start_index_saved_; - if(index_s.empty() || index_s.size() < 1) - { - sub_goal_index = (unsigned int)plan.size(); - sub_goal_index_saved_ = sub_goal_index; - } - else - { - if(index_s.front() > sub_goal_index_saved_) - { - sub_goal_index = (unsigned int)(index_s.front()) + 1; - sub_goal_index_saved_ = sub_goal_index; - } - if(index_s.size() > 1) - { - for(int i = 1; i < index_s.size(); ++i) - { - // double tolerance = line_generator->calculateTolerance(robot_pose, plan[index_s[i-1]]); - double distance = fabs(robot_nav_2d_utils::poseDistance(robot_pose, plan[index_s[i-1]])); - // double dx = plan[index_s[i-1]].x - robot_pose.x; - // double dy = plan[index_s[i-1]].y - robot_pose.y; - // if(std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_goal_tolerance_ + 0.15) - if (distance < xy_local_goal_tolerance_offset_) - { - if(index_s[i] > sub_goal_index_saved_) - { - if(i < index_s.size()-1) - { - sub_goal_index = index_s[i] + 1; - } - else - { - sub_goal_index = (unsigned int)plan.size(); - } - if(follow_step_path_) - { - sub_start_index = index_s[i-1]; - sub_start_index_saved_ = sub_start_index; - } - ROS_INFO("Tang nac path tu %d den %d boi khoang cach", sub_goal_index_saved_, sub_goal_index); - // ROS_WARN("i %d follow_step_path_ = %x start = %d sub_goal = %d size = %d", i, follow_step_path_, sub_start_index, sub_goal_index, (unsigned int)plan.size()); - sub_goal_index_saved_ = sub_goal_index; - break; - } - } - } - } - else - { - double distance = fabs(robot_nav_2d_utils::poseDistance(plan[sub_goal_index], robot_pose)); - if(distance <= xy_local_goal_tolerance_ ) - { - sub_goal_index = (unsigned int)plan.size(); - sub_goal_index_saved_ = sub_goal_index; - } - } - - } - - // find the "start pose", i.e. the pose on the plan closest to the robot that is also on the local map - // Tìm điểm pose bắt đầu trên kế hoạch đường đi gần nhất với robot đồng thời có tồn tại trong local map - unsigned int start_index = 0; // số vị trí pose trong kế hoạch đường đi - double distance_to_start = std::numeric_limits::infinity(); // Xét giá trị là vô cùng oo - bool started_path = false; - // for (unsigned int i = 0; i < plan.size(); i++) - // ROS_INFO_THROTTLE(1.0, "follow_step_path_ = %x start = %d sub_goal = %d size = %d", follow_step_path_, sub_start_index, sub_goal_index, (unsigned int)plan.size()); - for (unsigned int i = sub_start_index; i < sub_goal_index; i++) - { - - // double g_x = plan[i].x; - // double g_y = plan[i].y; - // unsigned int map_x, map_y; - // if (worldToGridBounded(info, g_x, g_y, map_x, map_y) // chuyển tọa độ từ đơn vị mét sang pixel - // && costmap(map_x, map_y) != robot_nav_core2::Costmap::NO_INFORMATION) - // { - // Still on the costmap. Continue. - double distance = fabs(robot_nav_2d_utils::poseDistance(plan[i], robot_pose)); // Tính khoảng cách từ vị trí của robot đến pose đang xét - if (distance_to_start > distance) - { - start_index = i; - distance_to_start = distance; - started_path = true; - } - // else - // { - // break; - // } - // else if (started_path) - // { - // // Plan is going away from the robot again. It's possible that it comes back and we would find a pose that's - // // even closer to the robot, but then we would skip over parts of the plan. - // break; - // } - // else, we have not yet found a point on the costmap, so we just continue - } - // Nếu khồng tìm được điểm gần với robot nhất thì trả về false - if (!started_path) - { - ROS_ERROR_NAMED("PathProgressCritic", "None of the points of the global plan were in the local costmap."); - return false; - } - - // find the "last valid pose", i.e. the last pose on the plan after the start pose that is still on the local map - // Tìm điểm pose cuôi cùng sau điểm pose bắt đầu và có tồn tại trong local map - if(start_index < 1) start_index == 1; - // unsigned int last_valid_index = plan.size() - 1; - unsigned int last_valid_index = sub_goal_index - 1; - // for (unsigned int i = start_index + 1; i < sub_goal_index; i++) - // { - // double g_x = plan[i].x; - // double g_y = plan[i].y; - // unsigned int map_x, map_y; - // if (worldToGridBounded(info, g_x, g_y, map_x, map_y) && costmap(map_x, map_y) != robot_nav_core2::Costmap::NO_INFORMATION) - // { - // // Still on the costmap. Continue. - // last_valid_index = i; - // } - // else - // { - // // Off the costmap after being on the costmap. - // break; - // } - // } - - // find the "goal pose" by walking along the plan as long as each step leads far enough away from the starting point, - // i.e. is within angle_threshold_ of the starting direction. - // Tìm điểm mục tiêu chạy từ điểm start pose đến last valid pose dọc thep plan - - unsigned int goal_index = start_index; - robot::Rate r(30); - while (goal_index < last_valid_index && robot::ok()) - { - // Tìm kiếm vị trí điểm mục tiêu phù hợp - double S; - if(velocity.x > 0) S = std::min(4.0, std::max(0.9, fabs(velocity.x)*k_d_reduce_)); - // else if(velocity.x < 0) S = 0.5; - else if(velocity.x < 0) S = std::min(0.7, std::max(0.5, fabs(velocity.x)*k_d_reduce_)); - else S = 0.5; - goal_index = getGoalIndex(robot_pose, plan, S, start_index, last_valid_index); - - // check if goal already reached - bool goal_already_reached = false; - - robot_geometry_msgs::PoseArray poseArrayMsg; - poseArrayMsg.header.stamp = robot::Time::now(); - poseArrayMsg.header.frame_id = frame_id_path_; - // std::stringstream ss; - for (auto &reached_intermediate_goal : reached_intermediate_goals_) - { - double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[goal_index])); - // ss << distance << " "; - robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPose(reached_intermediate_goal); - poseArrayMsg.poses.push_back(pose); - } - reached_intermediate_goals_pub_.publish(poseArrayMsg); - // if(!reached_intermediate_goals_.empty()) - // { - // ROS_INFO_STREAM(ss.str()); - // } - - for (auto &reached_intermediate_goal : reached_intermediate_goals_) - { - double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[goal_index])); - if (distance < xy_local_goal_tolerance_) - { - goal_already_reached = true; - // choose a new start_index by walking along the plan until we're outside xy_local_goal_tolerance_ and try again - // (start_index is now > goal_index) - for (start_index = goal_index; start_index <= last_valid_index; ++start_index) - { - distance = robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[start_index]); - if ( distance >= xy_local_goal_tolerance_offset_) - { - break; - } - } - // start_index_saved_ = start_index; - break; - } - } - - //try hiep - unsigned num = 0; - start_index_saved_vt_.insert(start_index_saved_vt_.begin(),start_index); - if(start_index_saved_vt_.size() > index_samples_) start_index_saved_vt_.pop_back(); - std::stringstream ss; - for(int i = 0; i < start_index_saved_vt_.size() - 1; i++) - { - double edge = 0; - if(start_index_saved_vt_[i] != start_index_saved_vt_[i+1]) - edge = journey(plan, start_index_saved_vt_[i], start_index_saved_vt_[i+1]); - if(edge < xy_local_goal_tolerance_) num++; - ss << start_index_saved_vt_[i] << " "; - } - // ss << start_index << " "; - - if(num < index_samples_ - 1 && !start_index_saved_vt_.empty()) - { - auto max_iter = *(std::max_element(start_index_saved_vt_.begin(), start_index_saved_vt_.end())); - start_index_saved_ = start_index_saved_ >= max_iter? start_index_saved_ : max_iter; - double S1 = journey(plan, start_index, plan.size()-1 ); - double S2 = journey(plan, start_index_saved_, plan.size()-1 ); - - // ROS_INFO_STREAM(ss.str()); - if(S2 - S1 < -fabs(xy_local_goal_tolerance_)) - { - start_index = start_index_saved_; - } - else start_index_saved_ = start_index; - // ROS_INFO(" %d %d %f %d %f %f", max_iter, start_index, S1, start_index_saved_, S2, S2 - S1); - } - else start_index_saved_ = start_index; - - if(start_index >= goal_index) goal_index = getGoalIndex(robot_pose, plan, S,start_index, last_valid_index); - - if (!goal_already_reached) - { - // new goal not in reached_intermediate_goals_ - double distance = fabs(robot_nav_2d_utils::poseDistance(plan[goal_index], plan[start_index])); - if (distance < xy_local_goal_tolerance_) - { - // ROS_INFO("goal_index %d distance %f", goal_index, distance); - // the robot has currently reached the goal - reached_intermediate_goals_.push_back(plan[goal_index]); - ROS_DEBUG_NAMED("PathProgressCritic", "Number of reached_intermediate goals: %zu", reached_intermediate_goals_.size()); - } - else - { - // we've found a new goal! - break; - } - } - - r.sleep(); - robot::spinOnce(); - } - - if (start_index > goal_index) - start_index = goal_index; - ROS_ASSERT(goal_index <= last_valid_index); - if((unsigned int)plan.size() == 2 && !plan.empty()) - { - start_index = 0; - goal_index = 1; - } - - // Tham chiếu lại đối số đầu vao - sub_goal = plan[goal_index]; - if(goal_index > 0) rev_sub_goal_ = plan[goal_index - 1]; - else rev_sub_goal_ = plan[start_index]; - - target_direction = x_direction_; - if(goal_index > 0 && (unsigned int)plan.size() > 1) - { - if(goal_index < (unsigned int)(plan.size() -1)) - { - const robot_geometry_msgs::Pose2D p1 = plan[start_index]; - int index; - for(index = start_index+1; index < goal_index; index++) - { - robot_geometry_msgs::Pose2D pose = plan[index]; - if(robot_nav_2d_utils::poseDistance(p1, pose) > xy_goal_tolerance_) break; - } - const robot_geometry_msgs::Pose2D p2 = plan[index]; - if(fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) - { - const double path_angle = atan2(p2.y - p1.y, p2.x - p1.x); - const double dir_path = cos(fabs(path_angle - p2.theta)); - if(fabs(dir_path) > 1e-9) - target_direction = dir_path; - // ROS_INFO("%f %f %f %f", p1.x ,p1.y, p2.x ,p2.y); - // ROS_INFO("%d %0.2f %0.2f %0.2f", goal_index, path_angle, p2.theta, target_direction); - } - } - else - { - const double rb_direction_x = sub_goal.x - robot_pose.x; - const double rb_direction_y = sub_goal.y - robot_pose.y; - const double rb_angle = atan2(rb_direction_y, rb_direction_x); - double dir_rg = cos(rb_angle - robot_pose.theta); - const double angle_threshold = 0.6; - if(fabs(dir_rg) > angle_threshold) - target_direction = dir_rg; - } - } - - // Publish start_index - robot_geometry_msgs::PoseStamped pose_st = robot_nav_2d_utils::pose2DToPoseStamped(plan[start_index], global_plan.header.frame_id, robot::Time::now()); - closet_robot_goal_pub_.publish(pose_st); - - // Publish goal_index - robot_geometry_msgs::PoseStamped pose_g = robot_nav_2d_utils::pose2DToPoseStamped(plan[goal_index], global_plan.header.frame_id, robot::Time::now()); - current_goal_pub_.publish(pose_g); - - return true; -} - -bool Bicycle::findSubGoalIndex(const std::vector &plan, std::vector &index_s) -{ - if (plan.empty()) - { - return false; - } - double x_direction_saved = 0.0; - robot_geometry_msgs::PoseArray poseArrayMsg; - poseArrayMsg.header.stamp = robot::Time::now(); - poseArrayMsg.header.frame_id = frame_id_path_; - - for (unsigned int i = 1; i < (unsigned int)plan.size(); i++) - { - robot_geometry_msgs::Pose2D p1 = plan[i]; - robot_geometry_msgs::Pose2D p2 = plan[i+1]; - // robot_geometry_msgs::Pose2D p3 = plan[i+2]; - double angle1; - if(fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) - angle1 = atan2(p2.y - p1.y, p2.x - p1.x); - else continue; - // const double angle2 = atan2(p3.y - p2.y, p3.x - p2.x); - const double target_direction = cos(fabs(angle1 - p2.theta)); - - if(target_direction * x_direction_saved < 0.0) - { - index_s.push_back(i); - robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPose(plan[i]); - poseArrayMsg.poses.push_back(pose); - } - x_direction_saved = target_direction; - } - - if(index_s.empty()) - index_s.push_back((unsigned int)plan.size() - 1); - else - { - if(index_s.back() < (unsigned int)plan.size() - 1) - index_s.push_back((unsigned int)plan.size() - 1); - } - reached_intermediate_goals_pub_.publish(poseArrayMsg); - return true; -} - -double Bicycle::journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const -{ - double S = 0; - if(last_valid_index - start_index > 1) - { - for(int i= start_index; i < last_valid_index; i++) - { - S += robot_nav_2d_utils::poseDistance(plan[i], plan[i+1]); - } - } - return S; -} - - -} // namespace mkt_algorithm - -PLUGINLIB_EXPORT_CLASS(mkt_algorithm::Bicycle, score_algorithm::ScoreAlgorithm) +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace mkt_algorithm +{ + +void Bicycle::initialize(const robot::NodeHandle& nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) +{ + nh_priv_ = robot::NodeHandle(nh, name); + nh_ = robot::NodeHandle("~"); + name_ = name; + tf_ = tf; + costmap_robot_ = costmap_robot; + last_actuator_update_ = robot::Time(0); + + nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5); + nh_priv_.param("xy_local_goal_tolerance_offset", xy_local_goal_tolerance_offset_, 0.5); + nh_priv_.param("angle_threshold", angle_threshold_, M_PI/8); + nh_priv_.param("index_samples", index_samples_, 0); + nh_priv_.param("filter", is_filter_, false); + + steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "steering_fix_wheel_distance_x", 1.1); + steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "steering_fix_wheel_distance_y", 0.); + xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "xy_goal_tolerance", 0.1); + acc_lim_theta_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "acc_lim_theta", 0.1); + decel_lim_theta_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "decel_lim_theta", 0.1); + controller_frequency_param_name_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "controller_frequency", 10); + if(controller_frequency_param_name_ <= 0.0) + { + ROS_WARN("controller_frequency is not setting lower 0.0 so will set to 1.0"); + controller_frequency_param_name_ = 1.0; + } + + reached_intermediate_goals_pub_ = nh_.advertise("reached_intermediate_goals", 1); + current_goal_pub_ = nh_.advertise("current_goal", 1); + closet_robot_goal_pub_ = nh_.advertise("closet_robot_goal", 1); + cmd_raw_pub_ = nh_.advertise("cmd_raw", 1); + x_direction_ = y_direction_= theta_direction_ = 0; + +// kalman + int n = 3; // Number of states + int m = 1; // Number of measurements + double dt = 1.0/controller_frequency_param_name_; // Time step + // ROS_INFO("controller_frequency_param_name %f", controller_frequency_param_name); + Eigen::MatrixXd A(n, n); // System dynamics matrix + Eigen::MatrixXd C(m, n); // Output matrix + Eigen::MatrixXd Q(n, n); // Process noise covariance + Eigen::MatrixXd R(m, m); // Measurement noise covariance + Eigen::MatrixXd P(n, n); // Estimate error covariance + + // Discrete LTI projectile motion, measuring position only + A << 1, dt, 0, 0, 1, dt, 0, 0, 1; + C << 1, 0, 0; + + // Reasonable covariance matrices + double q = 0.1; + double r = 0.6; + double p = 0.2; + Q << q, q, 0.0, q, q, 0.0, 0.0, 0.0, 0.0; + R << r; + P << p, p, p, p, 10.0, 1, p, 1, 10.0; + + // Construct the filter + kf_ = boost::make_shared(dt,A, C, Q, R, P); + // Best guess of initial states + Eigen::VectorXd x0(n); + x0 << 0.0, 0.0, 0.0; + kf_->init(robot::Time::now().toSec(), x0); +} + +void Bicycle::reset() +{ + reached_intermediate_goals_.clear(); + start_index_saved_vt_.clear(); + start_index_saved_ = 0; + sub_goal_index_saved_ = 0; + sub_start_index_saved_ = 0; + x_direction_ = y_direction_= theta_direction_ = 0; + follow_step_path_ = false; + last_actuator_update_ = robot::Time(0); +} + +bool Bicycle::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) +{ + nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5); + nh_priv_.param("xy_local_goal_tolerance_offset", xy_local_goal_tolerance_offset_, 0.5); + nh_priv_.param("angle_threshold", angle_threshold_, M_PI/8); + nh_priv_.param("index_samples", index_samples_, 0); + nh_priv_.param("distance_rg", distance_rg_, 0.1); + nh_priv_.param("k_ld", k_ld_, 1.0); + nh_priv_.param("k_d_reduce", k_d_reduce_, 1.0); + nh_priv_.param("ld_min", ld_min_, 0.2); + nh_priv_.param("ld_max", ld_max_, 1.1); + nh_priv_.param("follow_step_path", follow_step_path_, false); + + // ROS_INFO("%f %f %f %d", xy_local_goal_tolerance_, xy_local_goal_tolerance_offset_, angle_threshold_, index_samples_); + frame_id_path_ = global_plan.header.frame_id; + goal_ = goal; + global_plan_ = global_plan; + double rb_direction; + if(!getGoalPose(pose, velocity,global_plan, sub_goal_, rb_direction)) + { + ROS_ERROR("getGoalPose Failed"); + return false; + } + x_direction_= fabs(rb_direction)/rb_direction; + x_direction = x_direction_; + y_direction = y_direction_ = 0; + theta_direction = theta_direction_; + return true; +} + +robot_nav_2d_msgs::Twist2DStamped Bicycle::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) +{ + robot_nav_2d_msgs::Twist2DStamped result; + result.header.stamp = robot::Time::now(); + + robot_geometry_msgs::Pose2D steer_to_baselink_pose; + + if(!getPose("steer_link", "base_link", steer_to_baselink_pose)) + return result; + double actual_phi_steer = steer_to_baselink_pose.theta; + + const double L = sqrt(pow(steering_fix_wheel_distance_x_, 2) + pow(steering_fix_wheel_distance_y_, 2)); + const double delta_x = sub_goal_.x - pose.x; + const double delta_y = sub_goal_.y - pose.y; + const double d_rg = sqrt(pow(delta_x, 2) + pow(delta_y, 2)); + +// Van toc robot + double d_reduce = std::min(std::max(fabs(velocity.x) * k_d_reduce_, 0.6), 3.0); + double v_min = 0.05 * velocity.x / (fabs(velocity.x) + 1e-9); + double vr = d_rg > d_reduce? velocity.x : (velocity.x - v_min)*sin((d_rg / d_reduce) * (M_PI/2)) + v_min; + +// Góc lái của bánh lái là: α(t) + double alpha = atan2(delta_y,delta_x) - pose.theta; + double ld = std::min(std::max(fabs(velocity.x)*k_ld_, ld_min_), ld_max_); + // double ld = std::min(std::max(d_rg*k_ld_, ld_min_), ld_max_); + + double phi_steer = atan2(2 * L * sin(alpha), ld); + if(d_rg <= distance_rg_ && global_plan_.poses.size() > 1) + { + const double d_x = goal_.x - sub_goal_.x; + const double d_y = goal_.y - sub_goal_.y; + const double dd = sqrt(d_x * d_x + d_y * d_y); + const double d_theta = goal_.theta - sub_goal_.theta; + if(dd < 1e-5) + { + robot_geometry_msgs::Pose2D p = global_plan_.poses[global_plan_.poses.size() - 2]; + alpha = velocity.x / (fabs(velocity.x) + 1e-9)*(p.theta - pose.theta); + phi_steer = atan2(2 * L * sin(alpha), 1.0); + } + } + + double alpha_reduce = std::min(std::max(fabs(vr), 0.6), 1.0); + double cos_actual_phi_steer = cos( std::min(M_PI/2.3, fabs(actual_phi_steer))); + + // limit W + double result_W_max = 0.25; + // double result_W_min = 0.13; + double result_W = vr * fabs(cos(alpha)) * tan(actual_phi_steer) / L; + double V_s = std::max(alpha_reduce, fabs(cos(alpha))) * vr / cos_actual_phi_steer; + std::stringstream ss; + if(fabs(result_W) > 0.02) + { + double d_w = fabs(result_W) - fabs(velocity.theta); + double a = fabs(velocity.theta) > fabs(result_W) ? fabs(acc_lim_theta_/controller_frequency_param_name_) : fabs(decel_lim_theta_/controller_frequency_param_name_); + // ss << d_w << " " << a << " "; + double result; + if(fabs(d_w) >= a) + result = fabs(velocity.theta) + d_w / fabs(d_w + 1e-9) * a; + else if (fabs(d_w) < fabs(a)) + result = fabs(velocity.theta); + // ss << result_W << " " << velocity.theta << " "; + result_W = result_W / (fabs(result_W) + 1e-9) * result; + // ss << result_W << " "; + // ROS_INFO_STREAM(ss.str()); + + double d_v = fabs(result_W * L / tan(actual_phi_steer)) - fabs(vr); + if(fabs(d_v) >= a) + result = velocity.x / (fabs(velocity.x) + 1e-9)* (fabs(vr) + d_v / fabs(d_v + 1e-9) * a); + else if (fabs(d_v) < fabs(a)) + result = velocity.x / (fabs(velocity.x) + 1e-9) * fabs(vr); + + V_s = std::max(alpha_reduce, fabs(cos(alpha)))*result/ cos_actual_phi_steer; + } + + if(fabs(result_W) > result_W_max) + V_s = ( result_W / (fabs(result_W) + 1e-9) * result_W_max * L / tan(actual_phi_steer)) / cos_actual_phi_steer; + + if(is_filter_) + { + robot_geometry_msgs::Twist msg; + msg.linear.x = result.velocity.x; + msg.angular.z = phi_steer; + cmd_raw_pub_.publish(msg); + + Eigen::VectorXd y(1); + y << phi_steer; + robot::Time current_time = robot::Time::now(); + double dt = robot::Duration(current_time - last_actuator_update_).toSec(); + last_actuator_update_ = current_time; + Eigen::MatrixXd A(3, 3); // System dynamics matrix + A << 1, dt, 0, 0, 1, dt, 0, 0, 1; + kf_->update(y, dt, A); + phi_steer = kf_->state().transpose()[0]; + } + theta_direction_ = phi_steer !=0 ? phi_steer/(fabs(phi_steer) + 1e-9) * velocity.x/((fabs(velocity.x) + 1e-9)) : 0; + + result.velocity.theta = phi_steer; + result.velocity.x = fabs(cos(phi_steer - actual_phi_steer)) * V_s; + return result; +} + +unsigned int Bicycle::getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector &plan, + const double distance, unsigned int start_index, unsigned int last_valid_index) const +{ + if (start_index >= last_valid_index) + return last_valid_index; + + unsigned int goal_index = start_index; + const double start_direction_x = plan[start_index + 1].x - plan[start_index].x; + const double start_direction_y = plan[start_index + 1].y - plan[start_index].y; + if (fabs(start_direction_x) > 1e-9 || fabs(start_direction_y) > 1e-9) { // make sure that atan2 is defined + double start_angle = atan2(start_direction_y, start_direction_x); + double S = sqrt(pow(start_direction_x, 2) + pow(start_direction_y, 2)); + // double angle_threshold = 0.0; + for (unsigned int i = start_index + 1; i <= last_valid_index; ++i) + { + const double current_direction_x = plan[i].x - plan[i - 1].x; + const double current_direction_y = plan[i].y - plan[i - 1].y; + const double dd = sqrt(pow(current_direction_x, 2) + pow(current_direction_y, 2)); + S += dd; + if (fabs(current_direction_x) > 1e-9 || fabs(current_direction_y) > 1e-9) + { + double current_angle = atan2(current_direction_y, current_direction_x); + if(fabs(remainder(start_angle - current_angle, 2 * M_PI)) >= angle_threshold_ || S >= distance) + { + break; + } + goal_index = i; + } + } + } + return goal_index; +} + +bool Bicycle::getGoalPose(const robot_geometry_msgs::Pose2D &robot_pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_nav_2d_msgs::Path2D &global_plan, robot_geometry_msgs::Pose2D &sub_goal, + double &target_direction) +{ + const robot_nav_core2::Costmap &costmap = *costmap_; + const nav_grid::NavGridInfo &info = costmap.getInfo(); + + if (global_plan.poses.empty()) + { + ROS_ERROR_NAMED("PathProgressCritic", "The global plan was empty."); + return false; + } + // Chuyển đổi dữ liệu kế hoạch đường đi 'robot_nav_2d_msgs::Path2D' sang 'std::vector' + std::vector plan = global_plan.poses; + + std::vector index_s; + if(!findSubGoalIndex(plan, index_s)) + { + ROS_ERROR_NAMED("PathProgressCritic", "Can not find SubGoal Index"); + return false; + } + // else + // { + // std::stringstream ss; + // for(auto i : index_s) ss << i << " "; + // ROS_INFO_STREAM(ss.str()); + // } + + unsigned int sub_goal_index = sub_goal_index_saved_; + unsigned int sub_start_index = sub_start_index_saved_; + if(index_s.empty() || index_s.size() < 1) + { + sub_goal_index = (unsigned int)plan.size(); + sub_goal_index_saved_ = sub_goal_index; + } + else + { + if(index_s.front() > sub_goal_index_saved_) + { + sub_goal_index = (unsigned int)(index_s.front()) + 1; + sub_goal_index_saved_ = sub_goal_index; + } + if(index_s.size() > 1) + { + for(int i = 1; i < index_s.size(); ++i) + { + // double tolerance = line_generator->calculateTolerance(robot_pose, plan[index_s[i-1]]); + double distance = fabs(robot_nav_2d_utils::poseDistance(robot_pose, plan[index_s[i-1]])); + // double dx = plan[index_s[i-1]].x - robot_pose.x; + // double dy = plan[index_s[i-1]].y - robot_pose.y; + // if(std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_goal_tolerance_ + 0.15) + if (distance < xy_local_goal_tolerance_offset_) + { + if(index_s[i] > sub_goal_index_saved_) + { + if(i < index_s.size()-1) + { + sub_goal_index = index_s[i] + 1; + } + else + { + sub_goal_index = (unsigned int)plan.size(); + } + if(follow_step_path_) + { + sub_start_index = index_s[i-1]; + sub_start_index_saved_ = sub_start_index; + } + ROS_INFO("Tang nac path tu %d den %d boi khoang cach", sub_goal_index_saved_, sub_goal_index); + // ROS_WARN("i %d follow_step_path_ = %x start = %d sub_goal = %d size = %d", i, follow_step_path_, sub_start_index, sub_goal_index, (unsigned int)plan.size()); + sub_goal_index_saved_ = sub_goal_index; + break; + } + } + } + } + else + { + double distance = fabs(robot_nav_2d_utils::poseDistance(plan[sub_goal_index], robot_pose)); + if(distance <= xy_local_goal_tolerance_ ) + { + sub_goal_index = (unsigned int)plan.size(); + sub_goal_index_saved_ = sub_goal_index; + } + } + + } + + // find the "start pose", i.e. the pose on the plan closest to the robot that is also on the local map + // Tìm điểm pose bắt đầu trên kế hoạch đường đi gần nhất với robot đồng thời có tồn tại trong local map + unsigned int start_index = 0; // số vị trí pose trong kế hoạch đường đi + double distance_to_start = std::numeric_limits::infinity(); // Xét giá trị là vô cùng oo + bool started_path = false; + // for (unsigned int i = 0; i < plan.size(); i++) + // ROS_INFO_THROTTLE(1.0, "follow_step_path_ = %x start = %d sub_goal = %d size = %d", follow_step_path_, sub_start_index, sub_goal_index, (unsigned int)plan.size()); + for (unsigned int i = sub_start_index; i < sub_goal_index; i++) + { + + // double g_x = plan[i].x; + // double g_y = plan[i].y; + // unsigned int map_x, map_y; + // if (worldToGridBounded(info, g_x, g_y, map_x, map_y) // chuyển tọa độ từ đơn vị mét sang pixel + // && costmap(map_x, map_y) != robot_nav_core2::Costmap::NO_INFORMATION) + // { + // Still on the costmap. Continue. + double distance = fabs(robot_nav_2d_utils::poseDistance(plan[i], robot_pose)); // Tính khoảng cách từ vị trí của robot đến pose đang xét + if (distance_to_start > distance) + { + start_index = i; + distance_to_start = distance; + started_path = true; + } + // else + // { + // break; + // } + // else if (started_path) + // { + // // Plan is going away from the robot again. It's possible that it comes back and we would find a pose that's + // // even closer to the robot, but then we would skip over parts of the plan. + // break; + // } + // else, we have not yet found a point on the costmap, so we just continue + } + // Nếu khồng tìm được điểm gần với robot nhất thì trả về false + if (!started_path) + { + ROS_ERROR_NAMED("PathProgressCritic", "None of the points of the global plan were in the local costmap."); + return false; + } + + // find the "last valid pose", i.e. the last pose on the plan after the start pose that is still on the local map + // Tìm điểm pose cuôi cùng sau điểm pose bắt đầu và có tồn tại trong local map + if(start_index < 1) start_index == 1; + // unsigned int last_valid_index = plan.size() - 1; + unsigned int last_valid_index = sub_goal_index - 1; + // for (unsigned int i = start_index + 1; i < sub_goal_index; i++) + // { + // double g_x = plan[i].x; + // double g_y = plan[i].y; + // unsigned int map_x, map_y; + // if (worldToGridBounded(info, g_x, g_y, map_x, map_y) && costmap(map_x, map_y) != robot_nav_core2::Costmap::NO_INFORMATION) + // { + // // Still on the costmap. Continue. + // last_valid_index = i; + // } + // else + // { + // // Off the costmap after being on the costmap. + // break; + // } + // } + + // find the "goal pose" by walking along the plan as long as each step leads far enough away from the starting point, + // i.e. is within angle_threshold_ of the starting direction. + // Tìm điểm mục tiêu chạy từ điểm start pose đến last valid pose dọc thep plan + + unsigned int goal_index = start_index; + robot::Rate r(30); + while (goal_index < last_valid_index && robot::ok()) + { + // Tìm kiếm vị trí điểm mục tiêu phù hợp + double S; + if(velocity.x > 0) S = std::min(4.0, std::max(0.9, fabs(velocity.x)*k_d_reduce_)); + // else if(velocity.x < 0) S = 0.5; + else if(velocity.x < 0) S = std::min(0.7, std::max(0.5, fabs(velocity.x)*k_d_reduce_)); + else S = 0.5; + goal_index = getGoalIndex(robot_pose, plan, S, start_index, last_valid_index); + + // check if goal already reached + bool goal_already_reached = false; + + robot_geometry_msgs::PoseArray poseArrayMsg; + poseArrayMsg.header.stamp = robot::Time::now(); + poseArrayMsg.header.frame_id = frame_id_path_; + // std::stringstream ss; + for (auto &reached_intermediate_goal : reached_intermediate_goals_) + { + double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[goal_index])); + // ss << distance << " "; + robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPose(reached_intermediate_goal); + poseArrayMsg.poses.push_back(pose); + } + reached_intermediate_goals_pub_.publish(poseArrayMsg); + // if(!reached_intermediate_goals_.empty()) + // { + // ROS_INFO_STREAM(ss.str()); + // } + + for (auto &reached_intermediate_goal : reached_intermediate_goals_) + { + double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[goal_index])); + if (distance < xy_local_goal_tolerance_) + { + goal_already_reached = true; + // choose a new start_index by walking along the plan until we're outside xy_local_goal_tolerance_ and try again + // (start_index is now > goal_index) + for (start_index = goal_index; start_index <= last_valid_index; ++start_index) + { + distance = robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[start_index]); + if ( distance >= xy_local_goal_tolerance_offset_) + { + break; + } + } + // start_index_saved_ = start_index; + break; + } + } + + //try hiep + unsigned num = 0; + start_index_saved_vt_.insert(start_index_saved_vt_.begin(),start_index); + if(start_index_saved_vt_.size() > index_samples_) start_index_saved_vt_.pop_back(); + std::stringstream ss; + for(int i = 0; i < start_index_saved_vt_.size() - 1; i++) + { + double edge = 0; + if(start_index_saved_vt_[i] != start_index_saved_vt_[i+1]) + edge = journey(plan, start_index_saved_vt_[i], start_index_saved_vt_[i+1]); + if(edge < xy_local_goal_tolerance_) num++; + ss << start_index_saved_vt_[i] << " "; + } + // ss << start_index << " "; + + if(num < index_samples_ - 1 && !start_index_saved_vt_.empty()) + { + auto max_iter = *(std::max_element(start_index_saved_vt_.begin(), start_index_saved_vt_.end())); + start_index_saved_ = start_index_saved_ >= max_iter? start_index_saved_ : max_iter; + double S1 = journey(plan, start_index, plan.size()-1 ); + double S2 = journey(plan, start_index_saved_, plan.size()-1 ); + + // ROS_INFO_STREAM(ss.str()); + if(S2 - S1 < -fabs(xy_local_goal_tolerance_)) + { + start_index = start_index_saved_; + } + else start_index_saved_ = start_index; + // ROS_INFO(" %d %d %f %d %f %f", max_iter, start_index, S1, start_index_saved_, S2, S2 - S1); + } + else start_index_saved_ = start_index; + + if(start_index >= goal_index) goal_index = getGoalIndex(robot_pose, plan, S,start_index, last_valid_index); + + if (!goal_already_reached) + { + // new goal not in reached_intermediate_goals_ + double distance = fabs(robot_nav_2d_utils::poseDistance(plan[goal_index], plan[start_index])); + if (distance < xy_local_goal_tolerance_) + { + // ROS_INFO("goal_index %d distance %f", goal_index, distance); + // the robot has currently reached the goal + reached_intermediate_goals_.push_back(plan[goal_index]); + ROS_DEBUG_NAMED("PathProgressCritic", "Number of reached_intermediate goals: %zu", reached_intermediate_goals_.size()); + } + else + { + // we've found a new goal! + break; + } + } + + r.sleep(); + robot::spinOnce(); + } + + if (start_index > goal_index) + start_index = goal_index; + ROS_ASSERT(goal_index <= last_valid_index); + if((unsigned int)plan.size() == 2 && !plan.empty()) + { + start_index = 0; + goal_index = 1; + } + + // Tham chiếu lại đối số đầu vao + sub_goal = plan[goal_index]; + if(goal_index > 0) rev_sub_goal_ = plan[goal_index - 1]; + else rev_sub_goal_ = plan[start_index]; + + target_direction = x_direction_; + if(goal_index > 0 && (unsigned int)plan.size() > 1) + { + if(goal_index < (unsigned int)(plan.size() -1)) + { + const robot_geometry_msgs::Pose2D p1 = plan[start_index]; + int index; + for(index = start_index+1; index < goal_index; index++) + { + robot_geometry_msgs::Pose2D pose = plan[index]; + if(robot_nav_2d_utils::poseDistance(p1, pose) > xy_goal_tolerance_) break; + } + const robot_geometry_msgs::Pose2D p2 = plan[index]; + if(fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) + { + const double path_angle = atan2(p2.y - p1.y, p2.x - p1.x); + const double dir_path = cos(fabs(path_angle - p2.theta)); + if(fabs(dir_path) > 1e-9) + target_direction = dir_path; + // ROS_INFO("%f %f %f %f", p1.x ,p1.y, p2.x ,p2.y); + // ROS_INFO("%d %0.2f %0.2f %0.2f", goal_index, path_angle, p2.theta, target_direction); + } + } + else + { + const double rb_direction_x = sub_goal.x - robot_pose.x; + const double rb_direction_y = sub_goal.y - robot_pose.y; + const double rb_angle = atan2(rb_direction_y, rb_direction_x); + double dir_rg = cos(rb_angle - robot_pose.theta); + const double angle_threshold = 0.6; + if(fabs(dir_rg) > angle_threshold) + target_direction = dir_rg; + } + } + + // Publish start_index + robot_geometry_msgs::PoseStamped pose_st = robot_nav_2d_utils::pose2DToPoseStamped(plan[start_index], global_plan.header.frame_id, robot::Time::now()); + closet_robot_goal_pub_.publish(pose_st); + + // Publish goal_index + robot_geometry_msgs::PoseStamped pose_g = robot_nav_2d_utils::pose2DToPoseStamped(plan[goal_index], global_plan.header.frame_id, robot::Time::now()); + current_goal_pub_.publish(pose_g); + + return true; +} + +bool Bicycle::findSubGoalIndex(const std::vector &plan, std::vector &index_s) +{ + if (plan.empty()) + { + return false; + } + double x_direction_saved = 0.0; + robot_geometry_msgs::PoseArray poseArrayMsg; + poseArrayMsg.header.stamp = robot::Time::now(); + poseArrayMsg.header.frame_id = frame_id_path_; + + for (unsigned int i = 1; i < (unsigned int)plan.size(); i++) + { + robot_geometry_msgs::Pose2D p1 = plan[i]; + robot_geometry_msgs::Pose2D p2 = plan[i+1]; + // robot_geometry_msgs::Pose2D p3 = plan[i+2]; + double angle1; + if(fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) + angle1 = atan2(p2.y - p1.y, p2.x - p1.x); + else continue; + // const double angle2 = atan2(p3.y - p2.y, p3.x - p2.x); + const double target_direction = cos(fabs(angle1 - p2.theta)); + + if(target_direction * x_direction_saved < 0.0) + { + index_s.push_back(i); + robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPose(plan[i]); + poseArrayMsg.poses.push_back(pose); + } + x_direction_saved = target_direction; + } + + if(index_s.empty()) + index_s.push_back((unsigned int)plan.size() - 1); + else + { + if(index_s.back() < (unsigned int)plan.size() - 1) + index_s.push_back((unsigned int)plan.size() - 1); + } + reached_intermediate_goals_pub_.publish(poseArrayMsg); + return true; +} + +double Bicycle::journey(const std::vector &plan, const unsigned int start_index, const unsigned int last_valid_index) const +{ + double S = 0; + if(last_valid_index - start_index > 1) + { + for(int i= start_index; i < last_valid_index; i++) + { + S += robot_nav_2d_utils::poseDistance(plan[i], plan[i+1]); + } + } + return S; +} + + +} // namespace mkt_algorithm + +PLUGINLIB_EXPORT_CLASS(mkt_algorithm::Bicycle, score_algorithm::ScoreAlgorithm) diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_rotate_to_goal.cpp b/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_rotate_to_goal.cpp index e9a7980..113ffc6 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_rotate_to_goal.cpp +++ b/src/Algorithms/Libraries/mkt_algorithm/src/bicycle/bicycle_rotate_to_goal.cpp @@ -1,78 +1,78 @@ -#include -#include -#include -#include - -namespace mkt_algorithm -{ - -void RotateToGoal::initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) -{ - nh_ = robot::NodeHandle(nh, name); - name_ = name; - tf_ = tf; - costmap_robot_ = costmap_robot; - - steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_x", 1.1); - steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_y", 0.); - nh_.param("velocity_rotate_min", velocity_rotate_min_, 0.1); - nh_.param("velocity_rotate_max", velocity_rotate_max_, 0.6); - nh_.param("angle_pass_rotate", angle_threshold_, 0.02); -} - -void RotateToGoal::reset() -{ - time_last_cmd_ = robot::Time::now(); -} - -bool RotateToGoal::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, - const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, - double& x_direction, double& y_direction, double& theta_direction) -{ - goal_ = goal; - double angle = angles::shortest_angular_distance(pose.theta, goal_.theta); - - if(angle > 0) current_direction_ = 1; - else if(angle < 0) current_direction_ = -1; - x_direction = y_direction = theta_direction = current_direction_; - return true; -} - -robot_nav_2d_msgs::Twist2DStamped RotateToGoal::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) -{ - robot_nav_2d_msgs::Twist2DStamped result; - result.header.stamp = robot::Time::now(); - - robot_geometry_msgs::Pose2D steer_to_baselink_pose; - - if(!getPose("steer_link", "base_link", steer_to_baselink_pose)) - return result; - double actual_phi_steer = steer_to_baselink_pose.theta; - - double L = sqrt(pow(steering_fix_wheel_distance_x_, 2) + pow(steering_fix_wheel_distance_y_, 2)); - - // robot::Time t = robot::Time::now(); - // double dt = time_last_cmd_.isZero() ? 0.0 : (t - time_last_cmd_).toSec(); - // time_last_cmd_ = robot::Time::now(); - - double angle_rg = angles::shortest_angular_distance(pose.theta, goal_.theta); - double angle_reduce = std::min(std::max(fabs(velocity.theta), 0.15), velocity_rotate_max_); - double w_min = velocity.theta / (fabs(velocity.theta) + 1e-9) * velocity_rotate_min_; - double w_r = fabs(angle_rg) > angle_reduce? velocity.theta : (velocity.theta - w_min)*sin((fabs(angle_rg) / angle_reduce) * (M_PI/2)) + w_min; - - int direct_rotate = (angle_rg/fabs(angle_rg)); - double target_phi_steer = direct_rotate * M_PI/2; - if( fabs(target_phi_steer - actual_phi_steer) <= angle_threshold_) - { - double target_v = fabs(w_r * L); - result.velocity.x = std::min(velocity_rotate_max_ * L, fabs(target_v)); - } - else result.velocity.x = 0.0; - - result.velocity.theta = target_phi_steer; - return result; -} - -}; // namespace mkt_algorithm - +#include +#include +#include +#include + +namespace mkt_algorithm +{ + +void RotateToGoal::initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) +{ + nh_ = robot::NodeHandle(nh, name); + name_ = name; + tf_ = tf; + costmap_robot_ = costmap_robot; + + steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_x", 1.1); + steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_y", 0.); + nh_.param("velocity_rotate_min", velocity_rotate_min_, 0.1); + nh_.param("velocity_rotate_max", velocity_rotate_max_, 0.6); + nh_.param("angle_pass_rotate", angle_threshold_, 0.02); +} + +void RotateToGoal::reset() +{ + time_last_cmd_ = robot::Time::now(); +} + +bool RotateToGoal::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity, + const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan, + double& x_direction, double& y_direction, double& theta_direction) +{ + goal_ = goal; + double angle = angles::shortest_angular_distance(pose.theta, goal_.theta); + + if(angle > 0) current_direction_ = 1; + else if(angle < 0) current_direction_ = -1; + x_direction = y_direction = theta_direction = current_direction_; + return true; +} + +robot_nav_2d_msgs::Twist2DStamped RotateToGoal::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) +{ + robot_nav_2d_msgs::Twist2DStamped result; + result.header.stamp = robot::Time::now(); + + robot_geometry_msgs::Pose2D steer_to_baselink_pose; + + if(!getPose("steer_link", "base_link", steer_to_baselink_pose)) + return result; + double actual_phi_steer = steer_to_baselink_pose.theta; + + double L = sqrt(pow(steering_fix_wheel_distance_x_, 2) + pow(steering_fix_wheel_distance_y_, 2)); + + // robot::Time t = robot::Time::now(); + // double dt = time_last_cmd_.isZero() ? 0.0 : (t - time_last_cmd_).toSec(); + // time_last_cmd_ = robot::Time::now(); + + double angle_rg = angles::shortest_angular_distance(pose.theta, goal_.theta); + double angle_reduce = std::min(std::max(fabs(velocity.theta), 0.15), velocity_rotate_max_); + double w_min = velocity.theta / (fabs(velocity.theta) + 1e-9) * velocity_rotate_min_; + double w_r = fabs(angle_rg) > angle_reduce? velocity.theta : (velocity.theta - w_min)*sin((fabs(angle_rg) / angle_reduce) * (M_PI/2)) + w_min; + + int direct_rotate = (angle_rg/fabs(angle_rg)); + double target_phi_steer = direct_rotate * M_PI/2; + if( fabs(target_phi_steer - actual_phi_steer) <= angle_threshold_) + { + double target_v = fabs(w_r * L); + result.velocity.x = std::min(velocity_rotate_max_ * L, fabs(target_v)); + } + else result.velocity.x = 0.0; + + result.velocity.theta = target_phi_steer; + return result; +} + +}; // namespace mkt_algorithm + PLUGINLIB_EXPORT_CLASS(mkt_algorithm::RotateToGoal, score_algorithm::ScoreAlgorithm) \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.md b/src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.md index 9d58754..04e6095 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.md +++ b/src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.md @@ -1,126 +1,126 @@ -## Hermite (quỹ đạo 2D) từ robot đến look-ahead pose - -![Hermite trajectory](hermite_trajectory.svg) - -### Bài toán -Cho pose đích trong hệ tọa độ robot: `goal = (x, y, theta)`, với robot ở gốc -`(0, 0, 0)` (hướng theo trục +x). Cần sinh quỹ đạo từ robot đến pose đích. - -### Ý tưởng -Dùng đường cong Hermite bậc 3 để đảm bảo: -- Đi qua đúng điểm đầu và cuối. -- Đúng hướng đầu và cuối. - -Đường cong tham số `t` từ `0` đến `1`: - -``` -p(t) = (x(t), y(t)) -``` - -Ràng buộc: -- p(0) = (0, 0), hướng 0 rad. -- p(1) = (x, y), hướng theta rad. - -### Hệ số Hermite -``` -h00 = 2t^3 - 3t^2 + 1 -h10 = t^3 - 2t^2 + t -h01 = -2t^3 + 3t^2 -h11 = t^3 - t^2 -``` - -### Đạo hàm đầu/cuối -Chọn độ dài đặc trưng `L` (thường L = sqrt(x^2 + y^2)) và hướng `dir`: -``` -dir = +1 (đi xuôi) -dir = -1 (đi ngược 180° ở cả đầu và cuối) -``` -Khi đó: -``` -p'(0) = (dir * L, 0) -p'(1) = (dir * L*cos(theta), dir * L*sin(theta)) -``` - -### Công thức quỹ đạo -``` -x(t) = h10*(dir*L) + h01*x + h11*(dir*L*cos(theta)) -y(t) = h01*y + h11*(dir*L*sin(theta)) -``` - -### Hướng (heading) trên đường cong -Đạo hàm: -``` -h00' = 6t^2 - 6t -h10' = 3t^2 - 4t + 1 -h01' = -6t^2 + 6t -h11' = 3t^2 - 2t - -dx = h10'*(dir*L) + h01'*x + h11'*(dir*L*cos(theta)) -dy = h01'*y + h11'*(dir*L*sin(theta)) -``` -Hướng: -``` -heading(t) = atan2(dy, dx) -``` - -### Cách sử dụng -Lấy mẫu `t` đều (ví dụ 50-200 điểm) để tạo danh sách điểm quỹ đạo. -Nếu cần độ cong, có thể tính thêm từ đạo hàm bậc 2. - -### Ví dụ code C++ -``` -#include -#include - -struct Pose2D { - double x; - double y; - double theta; -}; - -std::vector generateHermiteTrajectory( - double x, double y, double theta, - int samples = 100) -{ - std::vector path; - path.reserve(samples + 1); - - double L = std::sqrt(x * x + y * y); - if (L < 1e-6) { - path.push_back({0.0, 0.0, 0.0}); - return path; - } - - for (int i = 0; i <= samples; ++i) { - double t = static_cast(i) / samples; - double t2 = t * t; - double t3 = t2 * t; - - double h00 = 2 * t3 - 3 * t2 + 1; - double h10 = t3 - 2 * t2 + t; - double h01 = -2 * t3 + 3 * t2; - double h11 = t3 - t2; - - double px = h10 * L + h01 * x + h11 * (L * std::cos(theta)); - double py = h01 * y + h11 * (L * std::sin(theta)); - - double dh00 = 6 * t2 - 6 * t; - double dh10 = 3 * t2 - 4 * t + 1; - double dh01 = -6 * t2 + 6 * t; - double dh11 = 3 * t2 - 2 * t; - - double dx = dh10 * L + dh01 * x + dh11 * (L * std::cos(theta)); - double dy = dh01 * y + dh11 * (L * std::sin(theta)); - - double heading = std::atan2(dy, dx); - - path.push_back({px, py, heading}); - } - - return path; -} -``` - -### Ghi chú -- Nếu (x, y) rất gần 0 thì quỹ đạo suy biến, chỉ trả về điểm gốc. +## Hermite (quỹ đạo 2D) từ robot đến look-ahead pose + +![Hermite trajectory](hermite_trajectory.svg) + +### Bài toán +Cho pose đích trong hệ tọa độ robot: `goal = (x, y, theta)`, với robot ở gốc +`(0, 0, 0)` (hướng theo trục +x). Cần sinh quỹ đạo từ robot đến pose đích. + +### Ý tưởng +Dùng đường cong Hermite bậc 3 để đảm bảo: +- Đi qua đúng điểm đầu và cuối. +- Đúng hướng đầu và cuối. + +Đường cong tham số `t` từ `0` đến `1`: + +``` +p(t) = (x(t), y(t)) +``` + +Ràng buộc: +- p(0) = (0, 0), hướng 0 rad. +- p(1) = (x, y), hướng theta rad. + +### Hệ số Hermite +``` +h00 = 2t^3 - 3t^2 + 1 +h10 = t^3 - 2t^2 + t +h01 = -2t^3 + 3t^2 +h11 = t^3 - t^2 +``` + +### Đạo hàm đầu/cuối +Chọn độ dài đặc trưng `L` (thường L = sqrt(x^2 + y^2)) và hướng `dir`: +``` +dir = +1 (đi xuôi) +dir = -1 (đi ngược 180° ở cả đầu và cuối) +``` +Khi đó: +``` +p'(0) = (dir * L, 0) +p'(1) = (dir * L*cos(theta), dir * L*sin(theta)) +``` + +### Công thức quỹ đạo +``` +x(t) = h10*(dir*L) + h01*x + h11*(dir*L*cos(theta)) +y(t) = h01*y + h11*(dir*L*sin(theta)) +``` + +### Hướng (heading) trên đường cong +Đạo hàm: +``` +h00' = 6t^2 - 6t +h10' = 3t^2 - 4t + 1 +h01' = -6t^2 + 6t +h11' = 3t^2 - 2t + +dx = h10'*(dir*L) + h01'*x + h11'*(dir*L*cos(theta)) +dy = h01'*y + h11'*(dir*L*sin(theta)) +``` +Hướng: +``` +heading(t) = atan2(dy, dx) +``` + +### Cách sử dụng +Lấy mẫu `t` đều (ví dụ 50-200 điểm) để tạo danh sách điểm quỹ đạo. +Nếu cần độ cong, có thể tính thêm từ đạo hàm bậc 2. + +### Ví dụ code C++ +``` +#include +#include + +struct Pose2D { + double x; + double y; + double theta; +}; + +std::vector generateHermiteTrajectory( + double x, double y, double theta, + int samples = 100) +{ + std::vector path; + path.reserve(samples + 1); + + double L = std::sqrt(x * x + y * y); + if (L < 1e-6) { + path.push_back({0.0, 0.0, 0.0}); + return path; + } + + for (int i = 0; i <= samples; ++i) { + double t = static_cast(i) / samples; + double t2 = t * t; + double t3 = t2 * t; + + double h00 = 2 * t3 - 3 * t2 + 1; + double h10 = t3 - 2 * t2 + t; + double h01 = -2 * t3 + 3 * t2; + double h11 = t3 - t2; + + double px = h10 * L + h01 * x + h11 * (L * std::cos(theta)); + double py = h01 * y + h11 * (L * std::sin(theta)); + + double dh00 = 6 * t2 - 6 * t; + double dh10 = 3 * t2 - 4 * t + 1; + double dh01 = -6 * t2 + 6 * t; + double dh11 = 3 * t2 - 2 * t; + + double dx = dh10 * L + dh01 * x + dh11 * (L * std::cos(theta)); + double dy = dh01 * y + dh11 * (L * std::sin(theta)); + + double heading = std::atan2(dy, dx); + + path.push_back({px, py, heading}); + } + + return path; +} +``` + +### Ghi chú +- Nếu (x, y) rất gần 0 thì quỹ đạo suy biến, chỉ trả về điểm gốc. - L có thể điều chỉnh lớn hơn để quỹ đạo mềm hơn. \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_go_straight.cpp b/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_go_straight.cpp index eaf041d..68a311f 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_go_straight.cpp +++ b/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_go_straight.cpp @@ -1,224 +1,224 @@ -#include -#include -#include - -mkt_algorithm::diff::GoStraight::GoStraight() - : PredictiveTrajectory() -{ -} - -mkt_algorithm::diff::GoStraight::~GoStraight() {} - -void mkt_algorithm::diff::GoStraight::initialize( - robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) -{ - if (!initialized_) - { - nh_ = nh; - nh_priv_ = robot::NodeHandle(nh, name); - name_ = name; - tf_ = tf; - traj_ = traj; - costmap_robot_ = costmap_robot; - nh_.param("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); - this->getParams(); - - std::vector footprint = costmap_robot_? costmap_robot_->getRobotFootprint() : std::vector(); - if (footprint.size() > 1) - { - double min_length = 1e10; - double max_length = 0.0; - for (size_t i = 0; i < footprint.size(); ++i) - { - const robot_geometry_msgs::Point &p1 = footprint[i]; - const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point - double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0; - if (len > max_length) - { - max_length = len; - } - if (len < min_length) - { - min_length = len; - } - } - this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; - this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; - } - - // kalman - last_actuator_update_ = robot::Time::now(); - n_ = 6; // [x, vx, ax, y, vy, ay, theta, vtheta, atheta] - m_ = 2; // measurements: x, y, theta - double dt = control_duration_; - - // Khởi tạo ma trận - A = Eigen::MatrixXd::Identity(n_, n_); - C = Eigen::MatrixXd::Zero(m_, n_); - Q = Eigen::MatrixXd::Zero(n_, n_); - R = Eigen::MatrixXd::Identity(m_, m_); - P = Eigen::MatrixXd::Identity(n_, n_); - - for (int i = 0; i < n_; i += 3) - { - A(i, i + 1) = dt; - A(i, i + 2) = 0.5 * dt * dt; - A(i + 1, i + 2) = dt; - } - - C(0, 0) = 1; - C(1, 3) = 1; - Q(2, 2) = 0.1; - Q(5, 5) = 0.6; - - R(0, 0) = 0.1; - R(1, 1) = 0.2; - - P(3, 3) = 0.4; - P(4, 4) = 0.4; - P(5, 5) = 0.4; - - kf_ = boost::make_shared(dt, A, C, Q, R, P); - Eigen::VectorXd x0(n_); - x0 << 0, 0, 0, 0, 0, 0; - kf_->init(robot::Time::now().toSec(), x0); - - x_direction_ = y_direction_ = theta_direction_ = 0; - initialized_ = true; - robot::log_info("GoStraight Initialized successfully"); - } -} - -mkt_msgs::Trajectory2D mkt_algorithm::diff::GoStraight::calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - // robot::log_info("x %f y %f theta %f", pose.pose.x, pose.pose.y, pose.pose.theta); - mkt_msgs::Trajectory2D result; - result.velocity.x = result.velocity.y = result.velocity.theta = 0.0; - if (!traj_) - return result; - if (compute_plan_.poses.size() < 2) - { - robot::log_warning("Local compute plan is available"); - return result; - } - - robot::Time current_time = robot::Time::now(); - const double dt = (current_time - last_actuator_update_).toSec(); - last_actuator_update_ = current_time; - - robot_nav_2d_msgs::Twist2D drive_cmd; - double sign_x = x_direction_; - - robot_nav_2d_msgs::Twist2D twist; - traj_->startNewIteration(velocity); // Nhận tốc độ hiện tại từ odom - while (robot::ok() && traj_->hasMoreTwists()) - { - twist = traj_->nextTwist(); - } - double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; - drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max)); - robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_; - if (transformed_plan.poses.empty()) - { - robot::log_warning("[%s:%d]\n Transformed plan is empty. Cannot determine a localglobal_plan.", __FILE__, __LINE__); - stopWithAccLimits(pose, velocity, drive_cmd, dt); - result.velocity = drive_cmd; - prevous_drive_cmd_ = drive_cmd; - return result; - } - double lookahead_dist = getLookAheadDistance(velocity); - auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); - robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose); - -// // === Final Heading Alignment Check === -// double xy_error = 0.0, heading_error = 0.0; -// if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x)) -// { -// // Use Arc Motion controller for final heading alignment -// alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd); -// #ifdef BUILD_WITH_ROS -// ROS_INFO("xy_err=%.3f, heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f", -// xy_error, heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta); -// #endif -// } -// else -// { - // robot::log_info_at(__FILE__, __LINE__, "journey : %f lookahead_dist : %f", - // journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1), lookahead_dist); - if(fabs(carrot_pose.pose.y) > 0.2) - { - lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist); - } - robot_nav_2d_msgs::Twist2D drive_target; - transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target, dt); - carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); - - // Normal Pure Pursuit - this->computePurePursuit( - carrot_pose, - drive_target, - velocity, - transformed_plan, - min_approach_linear_velocity_, - sign_x, - dt, - drive_cmd); - // } - applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt); - - if (this->nav_stop_) - { - if (!stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_)) - { - if (!stopWithAccLimits(pose, velocity, drive_cmd, dt)) - return result; - } - else - drive_cmd = {}; - result.velocity = drive_cmd; - return result; - } - - Eigen::VectorXd y(2); - y << drive_cmd.x, drive_cmd.theta; - - // Cập nhật lại A nếu dt thay đổi - for (int i = 0; i < n_; ++i) - for (int j = 0; j < n_; ++j) - A(i, j) = (i == j ? 1.0 : 0.0); - for (int i = 0; i < n_; i += 3) - { - A(i, i + 1) = dt; - A(i, i + 2) = 0.5 * dt * dt; - A(i + 1, i + 2) = dt; - } - kf_->update(y, dt, A); - double v_min = min_approach_linear_velocity_; - drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_max), fabs(v_max)); - drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x); - drive_cmd.theta = std::clamp(kf_->state()[3], -max_vel_theta_, max_vel_theta_); - - - result.poses.clear(); - result.poses.reserve(transformed_plan.poses.size()); - for (const auto &pose_stamped : transformed_plan.poses) - { - result.poses.push_back(pose_stamped.pose); - if(fabs(pose_stamped.pose.x - carrot_pose.pose.x) < 1e-6 && - fabs(pose_stamped.pose.y - carrot_pose.pose.y) < 1e-6 && - fabs(pose_stamped.pose.theta - carrot_pose.pose.theta) < 1e-6) - break; - } - drive_cmd.theta = std::clamp(drive_cmd.theta, -fabs(0.02), fabs(0.02)); - result.velocity = drive_cmd; - prevous_drive_cmd_ = drive_cmd; - return result; -} - -score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::GoStraight::create() -{ - return std::make_shared(); -} - +#include +#include +#include + +mkt_algorithm::diff::GoStraight::GoStraight() + : PredictiveTrajectory() +{ +} + +mkt_algorithm::diff::GoStraight::~GoStraight() {} + +void mkt_algorithm::diff::GoStraight::initialize( + robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) +{ + if (!initialized_) + { + nh_ = nh; + nh_priv_ = robot::NodeHandle(nh, name); + name_ = name; + tf_ = tf; + traj_ = traj; + costmap_robot_ = costmap_robot; + nh_.param("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); + this->getParams(); + + std::vector footprint = costmap_robot_? costmap_robot_->getRobotFootprint() : std::vector(); + if (footprint.size() > 1) + { + double min_length = 1e10; + double max_length = 0.0; + for (size_t i = 0; i < footprint.size(); ++i) + { + const robot_geometry_msgs::Point &p1 = footprint[i]; + const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point + double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0; + if (len > max_length) + { + max_length = len; + } + if (len < min_length) + { + min_length = len; + } + } + this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; + this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; + } + + // kalman + last_actuator_update_ = robot::Time::now(); + n_ = 6; // [x, vx, ax, y, vy, ay, theta, vtheta, atheta] + m_ = 2; // measurements: x, y, theta + double dt = control_duration_; + + // Khởi tạo ma trận + A = Eigen::MatrixXd::Identity(n_, n_); + C = Eigen::MatrixXd::Zero(m_, n_); + Q = Eigen::MatrixXd::Zero(n_, n_); + R = Eigen::MatrixXd::Identity(m_, m_); + P = Eigen::MatrixXd::Identity(n_, n_); + + for (int i = 0; i < n_; i += 3) + { + A(i, i + 1) = dt; + A(i, i + 2) = 0.5 * dt * dt; + A(i + 1, i + 2) = dt; + } + + C(0, 0) = 1; + C(1, 3) = 1; + Q(2, 2) = 0.1; + Q(5, 5) = 0.6; + + R(0, 0) = 0.1; + R(1, 1) = 0.2; + + P(3, 3) = 0.4; + P(4, 4) = 0.4; + P(5, 5) = 0.4; + + kf_ = boost::make_shared(dt, A, C, Q, R, P); + Eigen::VectorXd x0(n_); + x0 << 0, 0, 0, 0, 0, 0; + kf_->init(robot::Time::now().toSec(), x0); + + x_direction_ = y_direction_ = theta_direction_ = 0; + initialized_ = true; + robot::log_info("GoStraight Initialized successfully"); + } +} + +mkt_msgs::Trajectory2D mkt_algorithm::diff::GoStraight::calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + // robot::log_info("x %f y %f theta %f", pose.pose.x, pose.pose.y, pose.pose.theta); + mkt_msgs::Trajectory2D result; + result.velocity.x = result.velocity.y = result.velocity.theta = 0.0; + if (!traj_) + return result; + if (compute_plan_.poses.size() < 2) + { + robot::log_warning("Local compute plan is available"); + return result; + } + + robot::Time current_time = robot::Time::now(); + const double dt = (current_time - last_actuator_update_).toSec(); + last_actuator_update_ = current_time; + + robot_nav_2d_msgs::Twist2D drive_cmd; + double sign_x = x_direction_; + + robot_nav_2d_msgs::Twist2D twist; + traj_->startNewIteration(velocity); // Nhận tốc độ hiện tại từ odom + while (robot::ok() && traj_->hasMoreTwists()) + { + twist = traj_->nextTwist(); + } + double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; + drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max)); + robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_; + if (transformed_plan.poses.empty()) + { + robot::log_warning("[%s:%d]\n Transformed plan is empty. Cannot determine a localglobal_plan.", __FILE__, __LINE__); + stopWithAccLimits(pose, velocity, drive_cmd, dt); + result.velocity = drive_cmd; + prevous_drive_cmd_ = drive_cmd; + return result; + } + double lookahead_dist = getLookAheadDistance(velocity); + auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); + robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose); + + // === Final Heading Alignment Check === + double xy_error = 0.0, heading_error = 0.0; + if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x)) + { + // Use Arc Motion controller for final heading alignment + alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd); +#ifdef BUILD_WITH_ROS + ROS_INFO("xy_err=%.3f, heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f", + xy_error, heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta); +#endif + } + else + { + // robot::log_info_at(__FILE__, __LINE__, "journey : %f lookahead_dist : %f", + // journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1), lookahead_dist); + if(fabs(carrot_pose.pose.y) > 0.2) + { + lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist); + } + robot_nav_2d_msgs::Twist2D drive_target; + transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target); + carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); + + // Normal Pure Pursuit + this->computePurePursuit( + carrot_pose, + drive_target, + velocity, + transformed_plan, + min_approach_linear_velocity_, + sign_x, + dt, + drive_cmd); + } + applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt); + + if (this->nav_stop_) + { + if (!stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_)) + { + if (!stopWithAccLimits(pose, velocity, drive_cmd, dt)) + return result; + } + else + drive_cmd = {}; + result.velocity = drive_cmd; + return result; + } + + Eigen::VectorXd y(2); + y << drive_cmd.x, drive_cmd.theta; + + // Cập nhật lại A nếu dt thay đổi + for (int i = 0; i < n_; ++i) + for (int j = 0; j < n_; ++j) + A(i, j) = (i == j ? 1.0 : 0.0); + for (int i = 0; i < n_; i += 3) + { + A(i, i + 1) = dt; + A(i, i + 2) = 0.5 * dt * dt; + A(i + 1, i + 2) = dt; + } + kf_->update(y, dt, A); + double v_min = min_approach_linear_velocity_; + drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_max), fabs(v_max)); + drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x); + drive_cmd.theta = std::clamp(kf_->state()[3], -max_vel_theta_, max_vel_theta_); + + + result.poses.clear(); + result.poses.reserve(transformed_plan.poses.size()); + for (const auto &pose_stamped : transformed_plan.poses) + { + result.poses.push_back(pose_stamped.pose); + if(fabs(pose_stamped.pose.x - carrot_pose.pose.x) < 1e-6 && + fabs(pose_stamped.pose.y - carrot_pose.pose.y) < 1e-6 && + fabs(pose_stamped.pose.theta - carrot_pose.pose.theta) < 1e-6) + break; + } + drive_cmd.theta = std::clamp(drive_cmd.theta, -fabs(0.02), fabs(0.02)); + result.velocity = drive_cmd; + prevous_drive_cmd_ = drive_cmd; + return result; +} + +score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::GoStraight::create() +{ + return std::make_shared(); +} + BOOST_DLL_ALIAS(mkt_algorithm::diff::GoStraight::create, MKTAlgorithmDiffGoStraight) \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_predictive_trajectory.cpp b/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_predictive_trajectory.cpp index 95d4ba5..b410572 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_predictive_trajectory.cpp +++ b/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_predictive_trajectory.cpp @@ -1,1705 +1,1705 @@ -#include -#include - - -mkt_algorithm::diff::PredictiveTrajectory::PredictiveTrajectory() - : initialized_(false), - nav_stop_(false), - x_direction_(0.0), - y_direction_(0.0), - theta_direction_(0.0), - use_velocity_scaled_lookahead_dist_(false), - lookahead_time_(0.0), - lookahead_dist_(0.0), - min_lookahead_dist_(0.0), - max_lookahead_dist_(0.0), - max_lateral_accel_(0.0), - use_rotate_to_heading_(false), - rotate_to_heading_min_angle_(0.0), - min_path_distance_(0.0), - max_path_distance_(0.0), - use_final_heading_alignment_(false), - final_heading_xy_tolerance_(0.0), - final_heading_angle_tolerance_(0.0), - final_heading_min_velocity_(0.0), - final_heading_kp_angular_(0.0), - final_heading_ki_angular_(0.0), - final_heading_kd_angular_(0.0), - near_goal_heading_integral_(0.0), - near_goal_heading_last_error_(0.0), - near_goal_heading_was_active_(false), - min_approach_linear_velocity_(0.0), - use_cost_regulated_linear_velocity_scaling_(false), - inflation_cost_scaling_factor_(0.0), - cost_scaling_dist_(0.0), - cost_scaling_gain_(0.0), - control_duration_(0.0), - kf_(nullptr), - kf_q_v_(0.25), - kf_q_w_(0.8), - kf_r_v_(0.05), - kf_r_w_(0.08), - kf_p0_(0.5), - kf_filter_angular_(false), - m_(0), - n_(0) -{ -} - -mkt_algorithm::diff::PredictiveTrajectory::~PredictiveTrajectory() {} - -void mkt_algorithm::diff::PredictiveTrajectory::initialize( - robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) -{ - if (!initialized_) - { - nh_ = nh; - nh_priv_ = robot::NodeHandle(nh, name); - robot::log_info_at(__FILE__, __LINE__, "nh_ : %s", nh_.getNamespace().c_str()); - robot::log_info_at(__FILE__, __LINE__, "nh_priv_ : %s", nh_priv_.getNamespace().c_str()); - name_ = name; - tf_ = tf; - traj_ = traj; - costmap_robot_ = costmap_robot; - nh_.param("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); - this->getParams(); - - std::vector footprint = costmap_robot_ ? costmap_robot_->getRobotFootprint() : std::vector(); - if (footprint.size() > 1) - { - double min_length = 1e10; - double max_length = 0.0; - for (size_t i = 0; i < footprint.size(); ++i) - { - const robot_geometry_msgs::Point &p1 = footprint[i]; - const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point - double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0; - if (len > max_length) - { - max_length = len; - } - if (len < min_length) - { - min_length = len; - } - } - this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; - this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; - } - - // kalman - last_actuator_update_ = robot::Time::now(); - // State: [v, a, j, w, alpha, jw] where: - // - v: linear velocity, a: linear accel, j: linear jerk - // - w: angular velocity, alpha: angular accel, jw: angular jerk - // Measurement: [v, w] - n_ = 6; - m_ = 2; - double dt = control_duration_; - - // Khởi tạo ma trận - A = Eigen::MatrixXd::Identity(n_, n_); - C = Eigen::MatrixXd::Zero(m_, n_); - Q = Eigen::MatrixXd::Zero(n_, n_); - R = Eigen::MatrixXd::Zero(m_, m_); - P = Eigen::MatrixXd::Identity(n_, n_) * std::max(1e-9, kf_p0_); - - for (int i = 0; i < n_; i += 3) - { - A(i, i + 1) = dt; - A(i, i + 2) = 0.5 * dt * dt; - A(i + 1, i + 2) = dt; - } - - C(0, 0) = 1; - C(1, 3) = 1; - Q(2, 2) = std::max(1e-12, kf_q_v_); - Q(5, 5) = std::max(1e-12, kf_q_w_); - - R(0, 0) = std::max(1e-12, kf_r_v_); - R(1, 1) = std::max(1e-12, kf_r_w_); - - kf_ = boost::make_shared(dt, A, C, Q, R, P); - Eigen::VectorXd x0(n_); - x0 << 0, 0, 0, 0, 0, 0; - kf_->init(robot::Time::now().toSec(), x0); - -#ifdef BUILD_WITH_ROS - ros::NodeHandle nh_ros; - current_goal_pub_ = nh_ros.advertise("current_goal", 10); - closet_robot_goal_pub_ = nh_ros.advertise("closet_robot_goal", 10); - lookahead_point_pub_ = nh_ros.advertise("lookahead_point", 10); -#endif - - x_direction_ = y_direction_ = theta_direction_ = 0; - this->initialized_ = true; - robot::log_info("[%s:%d]\n PredictiveTrajectory Initialized successfully", __FILE__, __LINE__); - } -} - -void mkt_algorithm::diff::PredictiveTrajectory::getParams() -{ - robot_base_frame_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "robot_base_frame", std::string("base_link")); - nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5); - nh_priv_.param("angle_threshold", angle_threshold_, M_PI / 8); - nh_priv_.param("index_samples", index_samples_, 0); - nh_priv_.param("follow_step_path", follow_step_path_, false); - - nh_priv_.param("use_velocity_scaled_lookahead_dist", use_velocity_scaled_lookahead_dist_, false); - nh_priv_.param("lookahead_dist", lookahead_dist_, 0.25); - nh_priv_.param("min_lookahead_dist", min_lookahead_dist_, 0.3); - nh_priv_.param("max_lookahead_dist", max_lookahead_dist_, 0.9); - nh_priv_.param("lookahead_time", lookahead_time_, 1.5); - nh_priv_.param("min_journey_squared", min_journey_squared_, std::numeric_limits::infinity()); - nh_priv_.param("max_journey_squared", max_journey_squared_, std::numeric_limits::infinity()); - - nh_priv_.param("use_rotate_to_heading", use_rotate_to_heading_, false); - nh_priv_.param("rotate_to_heading_min_angle", rotate_to_heading_min_angle_, 0.785); - - // Final heading alignment (Arc Motion) - nh_priv_.param("use_final_heading_alignment", use_final_heading_alignment_, true); - nh_priv_.param("final_heading_xy_tolerance", final_heading_xy_tolerance_, 0.15); - nh_priv_.param("final_heading_angle_tolerance", final_heading_angle_tolerance_, 0.05); - nh_priv_.param("final_heading_min_velocity", final_heading_min_velocity_, 0.05); - nh_priv_.param("final_heading_kp_angular", final_heading_kp_angular_, 1.5); - nh_priv_.param("final_heading_ki_angular", final_heading_ki_angular_, 0.0); - nh_priv_.param("final_heading_kd_angular", final_heading_kd_angular_, 0.0); - - nh_priv_.param("rot_stopped_velocity", rot_stopped_velocity_, 0.01); - nh_priv_.param("trans_stopped_velocity", trans_stopped_velocity_, 0.01); - if (trans_stopped_velocity_ < 0.02) - trans_stopped_velocity_ = 0.5 * min_approach_linear_velocity_; - if (trans_stopped_velocity_ > min_approach_linear_velocity_) - trans_stopped_velocity_ = min_approach_linear_velocity_ + 0.01; - - // Inflation cost scaling (Limit velocity by proximity to obstacles) - nh_priv_.param("use_cost_regulated_linear_velocity_scaling", use_cost_regulated_linear_velocity_scaling_, true); - nh_priv_.param("inflation_cost_scaling_factor", inflation_cost_scaling_factor_, 3.0); - nh_priv_.param("cost_scaling_dist", cost_scaling_dist_, 0.6); - nh_priv_.param("cost_scaling_gain", cost_scaling_gain_, 1.0); - nh_priv_.param("max_lateral_accel", max_lateral_accel_, 1.0); - if (inflation_cost_scaling_factor_ <= 0.0) - { - robot::log_warning("[%s:%d]\n The value inflation_cost_scaling_factor is incorrectly set, it should be >0. Disabling cost regulated linear velocity scaling.", __FILE__, __LINE__); - use_cost_regulated_linear_velocity_scaling_ = false; - } - - // Kalman filter tuning (filtering v and w commands) - nh_priv_.param("kf_q_v", kf_q_v_, kf_q_v_); - nh_priv_.param("kf_q_w", kf_q_w_, kf_q_w_); - nh_priv_.param("kf_r_v", kf_r_v_, kf_r_v_); - nh_priv_.param("kf_r_w", kf_r_w_, kf_r_w_); - nh_priv_.param("kf_p0", kf_p0_, kf_p0_); - nh_priv_.param("kf_filter_angular", kf_filter_angular_, kf_filter_angular_); - - double control_frequency = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "controller_frequency", 10); - control_duration_ = 1.0 / control_frequency; - - if (traj_) - { - traj_.get()->getNodeHandle().param("max_vel_x", max_vel_x_, 0.0); - traj_.get()->getNodeHandle().param("min_vel_x", min_vel_x_, 0.0); - traj_.get()->getNodeHandle().param("acc_lim_x", acc_lim_x_, 0.0); - traj_.get()->getNodeHandle().param("decel_lim_x", decel_lim_x_, 0.0); - - traj_.get()->getNodeHandle().param("max_vel_y", max_vel_y_, 0.0); - traj_.get()->getNodeHandle().param("min_vel_y", min_vel_y_, 0.0); - traj_.get()->getNodeHandle().param("acc_lim_y", acc_lim_y_, 0.0); - traj_.get()->getNodeHandle().param("decel_lim_y", decel_lim_y_, 0.0); - - traj_.get()->getNodeHandle().param("max_vel_theta", max_vel_theta_, 0.0); - traj_.get()->getNodeHandle().param("min_vel_theta", min_vel_theta_, 0.0); - traj_.get()->getNodeHandle().param("acc_lim_theta", acc_lim_theta_, 0.0); - traj_.get()->getNodeHandle().param("decel_lim_theta", decel_lim_theta_, 0.0); - traj_.get()->getNodeHandle().param("min_speed_xy", min_speed_xy_, 0.0); - if(fabs(min_speed_xy_) > sqrt(max_vel_x_ * max_vel_x_ + max_vel_y_ * max_vel_y_)) - { - min_speed_xy_ = sqrt(max_vel_x_ * max_vel_x_ + max_vel_y_ * max_vel_y_); - } - if(fabs(min_speed_xy_) > sqrt(min_vel_x_ * min_vel_x_ + min_vel_y_ * min_vel_y_)) - { - min_speed_xy_ = sqrt(max_vel_x_ * max_vel_x_ + max_vel_y_ * max_vel_y_); - } - - traj_.get()->getNodeHandle().param("max_speed_xy", max_speed_xy_, 0.0); - } -} - -void mkt_algorithm::diff::PredictiveTrajectory::reset() -{ - if (this->initialized_) - { - robot::log_info("[%s:%d]\n PredictiveTrajectory is reset", __FILE__, __LINE__); - reached_intermediate_goals_.clear(); - start_index_saved_vt_.clear(); - this->clear(); - x_direction_ = y_direction_ = theta_direction_ = 0; - this->follow_step_path_ = false; - this->nav_stop_ = false; - last_actuator_update_ = robot::Time::now(); - prevous_drive_cmd_ = robot_nav_2d_msgs::Twist2D(); - near_goal_heading_integral_ = 0.0; - near_goal_heading_last_error_ = 0.0; - near_goal_heading_was_active_ = false; - - if (kf_) - { - Eigen::VectorXd x0(n_); - x0 << 0, 0, 0, 0, 0, 0; - kf_->init(robot::Time::now().toSec(), x0); - } - } -} - -void mkt_algorithm::diff::PredictiveTrajectory::stop() -{ - this->nav_stop_ = true; -} - -void mkt_algorithm::diff::PredictiveTrajectory::resume() -{ - if (this->initialized_) - { - if(!this->nav_stop_) - return; - prevous_drive_cmd_ = robot_nav_2d_msgs::Twist2D(); - last_actuator_update_ = robot::Time::now(); - - if (kf_) - { - Eigen::VectorXd x0(n_); - x0 << 0, 0, 0, 0, 0, 0; - kf_->init(robot::Time::now().toSec(), x0); - } - this->nav_stop_ = false; - } -} - -bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, - double &x_direction, double &y_direction, double &theta_direction) -{ - if (!initialized_) - { - robot::log_error("[%s:%d]\n This planner has not been initialized, please call initialize() before using this planner", __FILE__, __LINE__); - return false; - } - if(robot::Time::now() - last_actuator_update_ > robot::Duration(0.5)) - { - last_actuator_update_ = robot::Time::now(); - } - - std::vector footprint = costmap_robot_ ? costmap_robot_->getRobotFootprint() : std::vector(); - if (footprint.size() > 1) - { - double min_length = 1e10; - double max_length = 0.0; - for (size_t i = 0; i < footprint.size(); ++i) - { - const robot_geometry_msgs::Point &p1 = footprint[i]; - const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point - double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0; - if (len > max_length) - { - max_length = len; - } - if (len < min_length) - { - min_length = len; - } - } - this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; - this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; - } - - if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2) - { - robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size()); - return false; - } - this->getParams(); - - frame_id_path_ = global_plan.header.frame_id; - goal_ = goal; - global_plan_ = global_plan; - - // prune global plan to cut off parts of the past (spatially before the robot) - if (!this->pruneGlobalPlan(tf_, pose, global_plan_, 1.0)) - { - robot::log_error("[%s:%d]\n pruneGlobalPlan Failed", __FILE__, __LINE__); - return false; - } - - double S = std::numeric_limits::infinity(); - S = std::max(costmap_robot_->getCostmap()->getSizeInCellsX() * costmap_robot_->getCostmap()->getResolution() / 2.0, - costmap_robot_->getCostmap()->getSizeInCellsY() * costmap_robot_->getCostmap()->getResolution() / 2.0); - const double min_S = min_lookahead_dist_ * 1.5 + max_path_distance_, max_S = max_lookahead_dist_ * 1.5 + max_path_distance_; - S = std::clamp(S * fabs(velocity.x) * lookahead_time_, min_S, max_S); - compute_plan_.poses.clear(); - - if ((unsigned int)global_plan_.poses.size() == 2) - { - double dx = global_plan_.poses.back().pose.x - global_plan_.poses.front().pose.x; - double dy = global_plan_.poses.back().pose.y - global_plan_.poses.front().pose.y; - if (hypot(dx, dy) <= 2.0 * costmap_robot_->getCostmap()->getResolution()) - { - compute_plan_ = global_plan_; - } - else - { - robot::log_error("[%s:%d]\n The Local Plan has 2 points and hypot between more than is %.3f m", __FILE__, __LINE__, costmap_robot_->getCostmap()->getResolution()); - return false; - } - } - else - { - unsigned int start_index, goal_index; - if (!this->computePlanCommand(pose, velocity, S, global_plan_, start_index, goal_index, compute_plan_)) - { - robot::log_error("[%s:%d]\n computePlanCommand is Failed", __FILE__, __LINE__); - return false; - } - } - - double lookahead_dist = this->getLookAheadDistance(velocity); - transform_plan_.poses.clear(); - if (!this->transformGlobalPlan(tf_, compute_plan_, pose, costmap_robot_, robot_base_frame_, lookahead_dist, transform_plan_)) - { - robot::log_warning("[%s:%d]\n Could not transform the global plan to the frame of the controller", __FILE__, __LINE__); - return false; - } - - const auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transform_plan_); - if(fabs(carrot_pose.pose.y) > 0.2) - { - lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist); - if (!this->transformGlobalPlan(tf_, compute_plan_, pose, costmap_robot_, robot_base_frame_, lookahead_dist, transform_plan_)) - { - robot::log_warning("[%s:%d]\n Could not transform the global plan to the frame of the controller", __FILE__, __LINE__); - return false; - } - } - - x_direction = x_direction_; - y_direction = y_direction_ = 0; - theta_direction = theta_direction_; - - if ((unsigned int)(compute_plan_.poses.size() > 1) && - journey(compute_plan_.poses, 0, compute_plan_.poses.size() - 1) >= costmap_robot_->getCostmap()->getResolution()) - { - const robot_geometry_msgs::Pose2D p2 = compute_plan_.poses.back().pose; - int index; - for (index = (unsigned int)(compute_plan_.poses.size() - 1); index > 0; index--) - { - robot_geometry_msgs::Pose2D pose = compute_plan_.poses[index].pose; - if (robot_nav_2d_utils::poseDistance(p2, pose) > xy_local_goal_tolerance_) - break; - } - const robot_geometry_msgs::Pose2D p1 = compute_plan_.poses[index].pose; - if (fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) - { - const double path_angle = atan2(p2.y - p1.y, p2.x - p1.x); - const double dir_path = cos(fabs(path_angle - p2.theta)); - if (fabs(dir_path) > M_PI / 6 || x_direction < 1e-9) - x_direction = dir_path > 0 ? FORWARD : BACKWARD; - } - - } - else if(compute_plan_.poses.size() == 1) - { - try - { - // auto carrot_pose_it = getLookAheadPoint(velocity, lookahead_dist, transform_plan_); - // auto prev_carrot_pose_it = transform_plan_.poses.begin(); - // double distance_it = 0; - // for (auto it = carrot_pose_it - 1; it != transform_plan_.poses.begin(); --it) - // { - // double dx = it->pose.x - carrot_pose_it->pose.x; - // double dy = it->pose.y - carrot_pose_it->pose.y; - // distance_it += std::hypot(dx, dy); - // if (distance_it > costmap_robot_->getCostmap()->getResolution()) - // { - // prev_carrot_pose_it = it; - // break; - // } - // } - - // robot_geometry_msgs::Pose front = journey(transform_plan_.poses, 0, transform_plan_.poses.size() - 1) > 5.0 * costmap_robot_->getCostmap()->getResolution() - // ? robot_nav_2d_utils::pose2DToPose((*(prev_carrot_pose_it)).pose) - // : robot_nav_2d_utils::pose2DToPose(robot_geometry_msgs::Pose2D()); - - // robot_geometry_msgs::Pose back = robot_nav_2d_utils::pose2DToPose((*(carrot_pose_it)).pose); - - // teb_local_planner::PoseSE2 start_pose(front); - // teb_local_planner::PoseSE2 goal_pose(back); - // const double dir_path = (goal_pose.position() - start_pose.position()).dot(start_pose.orientationUnitVec()); - - - auto goal_pose = compute_plan_.poses.front().pose; - auto start_pose = pose.pose; - double angle_path = atan2(goal_pose.y - start_pose.y, goal_pose.x - start_pose.x); - double dir_path = cos(fabs(angle_path - goal_pose.theta)); - if (fabs(dir_path) > M_PI / 6 || x_direction < 1e-9) - x_direction = dir_path > 0 ? FORWARD : BACKWARD; - } - catch (std::exception &e) - { - robot::log_warning_throttle(0.2, "[%s:%d]\n getLookAheadPoint throw an exception: %s", __FILE__, __LINE__, e.what()); - x_direction = x_direction_; - } - } - - x_direction_ = x_direction; - y_direction_ = y_direction; - theta_direction_ = theta_direction; - return true; -} - -mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - mkt_msgs::Trajectory2D result; - result.velocity.x = result.velocity.y = result.velocity.theta = 0.0; - if (!traj_) - return result; - if (compute_plan_.poses.size() < 2) - { - robot::log_warning("[%s:%d]\n Local compute plan is available", __FILE__, __LINE__); - return result; - } - - robot::Time current_time = robot::Time::now(); - const double dt = (current_time - last_actuator_update_).toSec(); - last_actuator_update_ = current_time; - - robot_nav_2d_msgs::Twist2D drive_cmd; - double sign_x = sign(x_direction_); - - robot_nav_2d_msgs::Twist2D twist; - traj_->startNewIteration(velocity); - while (robot::ok() && traj_->hasMoreTwists()) - { - twist = traj_->nextTwist(); - } - double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; - drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max)); - // drive_cmd.x = sqrt(twist.x * twist.x); - - robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_; - if (transformed_plan.poses.empty()) - { - robot::log_warning("[%s:%d]\n Transformed plan is empty. Cannot determine a localglobal_plan.", __FILE__, __LINE__); - stopWithAccLimits(pose, velocity, drive_cmd, dt); - result.velocity = drive_cmd; - prevous_drive_cmd_ = drive_cmd; - return result; - } - double lookahead_dist = getLookAheadDistance(velocity); - auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); - robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose); - -#ifdef BUILD_WITH_ROS - { - geometry_msgs::PoseStamped lookahead_point; - lookahead_point.header.stamp = ros::Time::now(); - lookahead_point.header.frame_id = carrot_pose_stamped.header.frame_id; - lookahead_point.pose.position.x = carrot_pose_stamped.pose.position.x; - lookahead_point.pose.position.y = carrot_pose_stamped.pose.position.y; - lookahead_point.pose.position.z = carrot_pose_stamped.pose.position.z; - lookahead_point.pose.orientation.x = carrot_pose_stamped.pose.orientation.x; - lookahead_point.pose.orientation.y = carrot_pose_stamped.pose.orientation.y; - lookahead_point.pose.orientation.z = carrot_pose_stamped.pose.orientation.z; - lookahead_point.pose.orientation.w = carrot_pose_stamped.pose.orientation.w; - lookahead_point_pub_.publish(lookahead_point); - } -#endif - - bool allow_rotate = false; - nh_priv_.param("allow_rotate", allow_rotate, false); - - const double distance_allow_rotate = min_journey_squared_; - const double path_distance_to_rotate = journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1); - allow_rotate |= path_distance_to_rotate >= distance_allow_rotate; - // robot_geometry_msgs::Pose2D back_pose = transformed_plan.poses.back().pose; - // allow_rotate |= fabs(atan2(back_pose.y, back_pose.x) - back_pose.theta) > M_PI / 3.0; - - allow_rotate &= (fabs(transformed_plan.poses.front().pose.y) <= 0.5); - - double angle_to_heading; - if (allow_rotate && shouldRotateToPath(transformed_plan, carrot_pose, velocity, angle_to_heading, sign_x)) - { - if (!stopped(velocity, max_vel_theta_ + rot_stopped_velocity_, trans_stopped_velocity_)) - { - if (!stopWithAccLimits(pose, velocity, drive_cmd, dt)) - return result; - } - else - { - rotateToHeading(angle_to_heading, velocity, drive_cmd, dt); - } - } - else - { -// // === Final Heading Alignment Check === -// double xy_error = 0.0, heading_error = 0.0; -// if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x)) -// { -// // Use Arc Motion controller for final heading alignment -// alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd); -// #ifdef BUILD_WITH_ROS -// ROS_INFO("heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f", -// heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta); -// #endif -// } -// else -// { - robot_nav_2d_msgs::Twist2D drive_target = drive_cmd; - transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target, dt); - carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); - - // Normal Pure Pursuit - this->computePurePursuit( - carrot_pose, - drive_target, - velocity, - transformed_plan, - min_approach_linear_velocity_, - sign_x, - dt, - drive_cmd); - // } - applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt); - if (this->nav_stop_) - { - if (!stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_)) - { - if (!stopWithAccLimits(pose, velocity, drive_cmd, dt)) - return result; - } - else - drive_cmd = {}; - result.velocity = drive_cmd; - return result; - } - - } - result.poses.clear(); - result.poses.reserve(transformed_plan.poses.size()); - for (const auto &pose_stamped : transformed_plan.poses) - { - result.poses.push_back(pose_stamped.pose); - if(fabs(pose_stamped.pose.x - carrot_pose.pose.x) < 1e-6 && - fabs(pose_stamped.pose.y - carrot_pose.pose.y) < 1e-6 && - fabs(pose_stamped.pose.theta - carrot_pose.pose.theta) < 1e-6) - break; - } - - if(fabs(v_max == 0.0)) - { - drive_cmd.x = 0.0; - robot::log_warning_throttle(0.2, "[%s:%d]\n v_max is 0.0", __FILE__, __LINE__); - return result; - } - result.velocity = drive_cmd; - prevous_drive_cmd_ = drive_cmd; - return result; -} - -void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit( - const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, - const robot_nav_2d_msgs::Twist2D &drive_target, - const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Path2D &trajectory, - const double &min_approach_linear_velocity, - const double &sign_x, - const double &dt, - robot_nav_2d_msgs::Twist2D &drive_cmd) -{ - // 1) Curvature from pure pursuit - const double L2 = carrot_pose.pose.x * carrot_pose.pose.x + carrot_pose.pose.y * carrot_pose.pose.y; - const double L2_min = 0.01; // m^2, chỉnh theo nhu cầu (0.02–0.1) - const double L2_safe = std::max(L2, L2_min); - const double L = std::sqrt(L2_safe); - - const double kappa = 2.0 * carrot_pose.pose.y / L2_safe; - - // 3) Adjust speed using Hermite trajectory curvature + remaining distance - double v_target = adjustSpeedWithHermiteTrajectory(velocity, trajectory, drive_target.x, sign_x); - // const double L_min = 0.1; // m, chỉnh theo nhu cầu - // double scale_close = std::clamp(L / L_min, 0.0, 1.0); - // v_target *= scale_close; - const double y_abs = std::fabs(carrot_pose.pose.y); - const double y_soft = 0.1; - if (y_abs > y_soft) - { - double scale = y_soft / y_abs; // y càng lớn => scale càng nhỏ - scale = std::clamp(scale, 0.6, 1.0); // không giảm quá sâu - v_target *= scale; - robot_nav_2d_msgs::Twist2D cmd, result; - cmd.x = v_target; - this->moveWithAccLimits(velocity, cmd, result, dt); - v_target = result.x; - } - - // 4) Maintain minimum approach speed - if (std::fabs(v_target) < min_approach_linear_velocity) - v_target = std::copysign(min_approach_linear_velocity, sign_x); - // 5) Angular speed from curvature - double w_target = v_target * kappa; - if(journey(trajectory.poses, 0, trajectory.poses.size() - 1) <= min_journey_squared_) - { - if (trajectory.poses.size() >= 2) { - const auto& p1 = trajectory.poses[trajectory.poses.size() - 1].pose; - double heading_ref = 0.0; - for(int i = trajectory.poses.size() - 2; i >= 0; i--) - { - const auto& p = trajectory.poses[i].pose; - const auto& dx = p1.x - p.x ; - const auto& dy = p1.y - p.y ; - if(std::hypot(dx, dy) >= costmap_robot_->getCostmap()->getResolution()) - { - if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) - continue; - heading_ref = std::atan2(dy, dx); - if(sign_x < 0.0) - heading_ref += std::copysign(M_PI, heading_ref) * (-1.0); - break; - } - } - - const double error = heading_ref; - double w_heading = 0.0; - pid(error, - near_goal_heading_integral_, - near_goal_heading_last_error_, - dt, - final_heading_kp_angular_, - final_heading_ki_angular_, - final_heading_kd_angular_, - w_heading); - // Apply acceleration limits - double dw_heading = std::clamp(w_heading - velocity.theta, -acc_lim_theta_ * dt, acc_lim_theta_ * dt); - w_target = velocity.theta + dw_heading; - w_target = std::clamp(w_target, -fabs(drive_target.theta), fabs(drive_target.theta)); - } - else - { - w_target = std::clamp(w_target, -0.001, 0.001); - near_goal_heading_was_active_ = false; - } - } - else - { - near_goal_heading_was_active_ = false; - } - w_target = std::clamp(w_target, -fabs(drive_target.theta), fabs(drive_target.theta)); - - // 6) Apply acceleration limits (linear + angular) - const double dv = std::clamp(v_target - velocity.x, -acc_lim_x_ * dt, acc_lim_x_ * dt); - const double dw = std::clamp(w_target - velocity.theta, -acc_lim_theta_ * dt, acc_lim_theta_ * dt); - - drive_cmd.x = velocity.x + dv; - drive_cmd.theta = velocity.theta + dw; - - Eigen::VectorXd y(2); - y << drive_cmd.x, drive_cmd.theta; - - // Cập nhật lại A nếu dt thay đổi - for (int i = 0; i < n_; ++i) - for (int j = 0; j < n_; ++j) - A(i, j) = (i == j ? 1.0 : 0.0); - for (int i = 0; i < n_; i += 3) - { - A(i, i + 1) = dt; - A(i, i + 2) = 0.5 * dt * dt; - A(i + 1, i + 2) = dt; - } - kf_->update(y, dt, A); - double v_min = min_approach_linear_velocity_; - drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_target), fabs(v_target)); - drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x); - if (kf_filter_angular_) - drive_cmd.theta = std::clamp(kf_->state()[3], -fabs(drive_target.theta), fabs(drive_target.theta)); - // robot::log_info("drive_cmd.theta: %f, drive_target.theta: %f", drive_cmd.theta, drive_target.theta); -} - -void mkt_algorithm::diff::PredictiveTrajectory::applyDistanceSpeedScaling( - const robot_nav_2d_msgs::Path2D &plan, - const robot_nav_2d_msgs::Twist2D &velocity, - robot_nav_2d_msgs::Twist2D &drive_cmd, - const double &sign_x, - const double &dt) -{ - double s = plan.poses.empty() - ? min_journey_squared_ - : journey(plan.poses, 0, plan.poses.size() - 1); - double S_th = 0.1 + max_path_distance_ + fabs(velocity.x) * lookahead_time_; - double S_final = std::min(S_th * 0.2, 0.1 + max_path_distance_); - - double max_speed = fabs(drive_cmd.x); - double target_speed = max_speed; - if (s < S_th) - { - double r = std::clamp(s / S_th, 0.0, 1.0); - double cosine_factor = 0.5 * (1.0 + std::cos(M_PI * (1.0 - r))); - target_speed = max_speed * cosine_factor; - } - const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; - const double v_min = std::min(fabs(v_limited), min_speed_xy_); - double reduce_speed = std::min(max_speed, v_min); - if (s < S_final) - { - double r = std::clamp(s / S_final, 0.0, 1.0); - double cosine_factor = 0.5 * (1.0 + std::cos(M_PI * (1.0 - r))); - reduce_speed = (reduce_speed - min_approach_linear_velocity_) * cosine_factor + min_approach_linear_velocity_; - reduce_speed = std::max(reduce_speed, min_approach_linear_velocity_); - } - target_speed = std::max(target_speed, reduce_speed); - - double v_desired = std::copysign(target_speed, sign_x); - double max_acc_vel = velocity.x + fabs(acc_lim_x_) * dt; - double min_acc_vel = velocity.x - fabs(acc_lim_x_) * dt; - double v_samp = std::clamp(v_desired, min_acc_vel, max_acc_vel); - - double max_speed_to_stop = std::sqrt(2.0 * fabs(decel_lim_x_) * std::max(0.0, s)); - v_samp = std::copysign(std::min(max_speed_to_stop, fabs(v_samp)), sign_x); - if (sign_x > 0.0) - drive_cmd.x = std::clamp(v_samp, min_approach_linear_velocity_, max_speed); - else - drive_cmd.x = std::clamp(v_samp, -max_speed, -min_approach_linear_velocity_); -} - -bool mkt_algorithm::diff::PredictiveTrajectory::shouldRotateToPath( - const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, - robot_nav_2d_msgs::Twist2D velocity, double &angle_to_path, const double &sign_x) -{ - - const bool is_stopped = stopped(velocity, max_vel_theta_ + rot_stopped_velocity_ + 0.01, trans_stopped_velocity_ + 0.01); - // const double straight_threshold = std::max(0.05, 2.0 * (costmap_robot_ ? costmap_robot_->getCostmap()->getResolution() : 0.05)); - // const double max_kappa = calculateMaxKappa(global_plan); - // const bool curvature = max_kappa > straight_threshold; - double path_angle = std::atan2(carrot_pose.pose.y, carrot_pose.pose.x); - if(is_stopped && global_plan.poses.size() >= 4 && - journey(global_plan.poses, 0, global_plan.poses.size() - 1) >= 0.7 * min_lookahead_dist_) - { - const auto& p1 = global_plan.poses[2]; - for(int i = 3; i < global_plan.poses.size(); i++) - { - const auto& p = global_plan.poses[i]; - const auto& dx = p.pose.x - p1.pose.x; - const auto& dy = p.pose.y - p1.pose.y; - if(std::hypot(dx, dy) > costmap_robot_->getCostmap()->getResolution()) - { - if(fabs(dx) < 1e-9 && fabs(dy) < 1e-9) - continue; - path_angle = std::atan2(dy, dx); - break; - } - } - } - - // Whether we should rotate robot to rough path heading - // if(sign_x < 0.0) - // path_angle += std::copysign(M_PI, path_angle) * (-1.0); - // angle_to_path = path_angle; - angle_to_path = sign_x < 0.0 ? angles::normalize_angle(M_PI + path_angle) : path_angle; - double heading_linear = sqrt(velocity.x * velocity.x + velocity.y * velocity.y); - // The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785) - double heading_rotate = rotate_to_heading_min_angle_; - - heading_rotate = is_stopped - ? rotate_to_heading_min_angle_ + heading_linear - : std::clamp(heading_rotate + heading_linear, angle_threshold_ + rotate_to_heading_min_angle_, M_PI_2); - - // bool result = use_rotate_to_heading_ && - // (is_stopped || sign(angle_to_path) * sign_x < 0 ) && fabs(angle_to_path) > heading_rotate; - - bool result = use_rotate_to_heading_ && fabs(angle_to_path) > heading_rotate; -#ifdef BUILD_WITH_ROS - if (result) - ROS_WARN_THROTTLE(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x); -#else - if (result) - robot::log_info_throttle(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x); -#endif - return result; -} - -void mkt_algorithm::diff::PredictiveTrajectory::rotateToHeading( - const double &angle_to_path, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt) -{ - const double theta_direction = angle_to_path > 0.0 ? 1.0 : -1.0; - double ang_diff = angle_to_path; - double max_vel_theta = traj_ ? fabs(traj_->getTwistAngular(true).z) : 0.3; - double min_vel_theta = min_vel_theta_; - - double angular_decel_zone = 0.3; // rad - khoảng cách bắt đầu giảm tốc - nh_priv_.param("angular_decel_zone", angular_decel_zone, 0.5); - angular_decel_zone += std::clamp( - fabs(max_vel_theta) + (M_PI_2 - fabs(atan2(min_path_distance_, max_path_distance_))), 0.4, M_PI_2); - double zone_begin = std::max(angular_decel_zone * 0.2, 0.2); - double cosine_begin_factor = 0.5 * (1.0 + cos(M_PI * (1.0 - fabs(ang_diff) / zone_begin))); - - double reduce_vel_theta = std::min(max_vel_theta, 0.25 + min_vel_theta); - reduce_vel_theta = fabs(ang_diff) > zone_begin ? reduce_vel_theta : (reduce_vel_theta - min_vel_theta) * cosine_begin_factor + min_vel_theta_; - - // === ANGULAR DECELERATION ZONE === - double target_angular_speed = max_vel_theta; - if (fabs(ang_diff) < angular_decel_zone) - { - double cosine_factor = 0.5 * (1.0 + cos(M_PI * (1.0 - fabs(ang_diff) / angular_decel_zone))); - double cosine_speed = max_vel_theta * cosine_factor; - - // Choose deceleration profile - target_angular_speed = cosine_speed; // Smoothest option - - // Ensure minimum speed to avoid stalling - target_angular_speed = std::max(target_angular_speed, reduce_vel_theta); - } - // Apply direction - double v_theta_desired = std::copysign(target_angular_speed, ang_diff); - - // === STOPPING CONSTRAINT === - double max_speed_to_stop = sqrt(2.0 * fabs(decel_lim_theta_) * fabs(ang_diff)); - - double v_theta_samp = std::copysign( - std::min(max_speed_to_stop, fabs(v_theta_desired)), ang_diff); - - // === ACCELERATION LIMITS === - double max_acc_vel = fabs(acc_lim_theta_) * dt; - double domega = std::clamp(v_theta_samp - velocity.theta, -max_acc_vel, max_acc_vel); - - // === FINAL LIMITS === - cmd_vel.x = 0.0; - cmd_vel.y = 0.0; - cmd_vel.theta = velocity.theta + domega; - // robot::log_info("cmd_vel.theta: %f, velocity.theta: %f, domega: %f, max_acc_vel: %f, v_theta_samp: %f", cmd_vel.theta, velocity.theta, domega, max_acc_vel, v_theta_samp); -} - -bool mkt_algorithm::diff::PredictiveTrajectory::shouldAlignToFinalHeading( - const robot_nav_2d_msgs::Path2D &trajectory, - const robot_nav_2d_msgs::Pose2DStamped &goal, - const robot_nav_2d_msgs::Twist2D &velocity, - double &xy_error, - double &heading_error, - const double &sign_x) -{ - if (!use_final_heading_alignment_) - return false; - - if (trajectory.poses.empty()) - return false; - - // Calculate distance to goal (last point in trajectory is closest to goal in robot frame) - const auto &last_pose = trajectory.poses.back().pose; - xy_error = std::hypot(last_pose.x, last_pose.y); - - // Transform goal heading to robot frame - // In robot frame, robot heading is 0, so heading_error = goal_heading_in_robot_frame - heading_error = 0.0; - if(trajectory.poses.size() >= 2) - { - const auto& p1 = trajectory.poses[trajectory.poses.size() - 1].pose; - for(int i = trajectory.poses.size() - 2; i >= 0; i--) - { - const auto& p = trajectory.poses[i].pose; - const auto& dx = sign_x < 0.0 ? p1.x - p.x : p.x - p1.x; - const auto& dy = sign_x < 0.0 ? p1.y - p.y : p.y - p1.y; - if(std::hypot(dx, dy) >= costmap_robot_->getCostmap()->getResolution()) - { - heading_error = angles::normalize_angle(std::atan2(dy, dx)); - break; - } - } - } - - // Check if we're close enough to goal position to start final heading alignment - double distance_threshold = final_heading_xy_tolerance_; - - // Dynamic threshold: increase when moving fast to allow smooth transition - double velocity_factor = std::max(0.0, std::fabs(velocity.x) * 0.5); - distance_threshold += velocity_factor; - - bool near_goal = xy_error < distance_threshold; - bool heading_not_reached = std::fabs(heading_error) > final_heading_angle_tolerance_; - - return near_goal && heading_not_reached; -} - -void mkt_algorithm::diff::PredictiveTrajectory::alignToFinalHeading( - const double &xy_error, - const double &heading_error, - const robot_nav_2d_msgs::Twist2D &velocity, - const double &sign_x, - const double &dt, - robot_nav_2d_msgs::Twist2D &cmd_vel) -{ - // ============================================================ - // Arc Motion Controller for Final Heading Alignment - // ============================================================ - // - // Strategy: - // 1. Linear velocity: proportional to xy_error, decreasing as we approach goal - // 2. Angular velocity: proportional to heading_error with feedforward - // 3. Coordinate both to arrive at goal with correct heading - // - // Key insight: For arc motion, the relationship is: - // arc_length = radius * angle - // v = omega * radius - // - // We want to cover xy_error distance while rotating heading_error angle - // So ideal radius = xy_error / |heading_error| (when heading_error != 0) - // ============================================================ - - const double abs_heading_error = std::fabs(heading_error); - const double heading_sign = (heading_error > 0) ? 1.0 : -1.0; - - // --- Linear velocity calculation --- - // Base velocity proportional to distance, with minimum for smooth motion - double v_base = std::sqrt(2.0 * std::fabs(decel_lim_x_) * xy_error); - const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; - const double v_min = std::min(fabs(v_limited), min_speed_xy_); - v_base = std::max(v_base, final_heading_min_velocity_); - v_base = std::min(v_base, v_min); - - // Scale down when heading error is large (prioritize rotation) - double heading_scale = 1.0; - if (abs_heading_error > 0.1) // ~5.7 degrees - { - // Reduce linear velocity when heading error is significant - heading_scale = std::clamp(0.3 / abs_heading_error, 0.3, 1.0); - } - - double v_target = v_base * heading_scale * sign_x; - - // --- Angular velocity calculation --- - double omega_target = 0.0; - - if (abs_heading_error > final_heading_angle_tolerance_) - { - // Method 1: Proportional control - double omega_p = 0.0; - pid(heading_error, - near_goal_heading_integral_, - near_goal_heading_last_error_, - dt, - final_heading_kp_angular_, - final_heading_ki_angular_, - final_heading_kd_angular_, - omega_p); - - // Method 2: Arc-based feedforward (coordinate linear and angular motion) - double omega_arc = 0.0; - if (xy_error > 0.01 && abs_heading_error > 0.01) - { - // Ideal omega to complete rotation while traveling remaining distance - // omega = v * heading_error / xy_error - omega_arc = std::fabs(v_target - velocity.x) * heading_error / xy_error; - } - - // Blend proportional and arc-based control - // Use more arc-based when far, more proportional when close - double blend_factor = std::clamp(xy_error / final_heading_xy_tolerance_, 0.0, 1.0); - omega_target = blend_factor * omega_arc + (1.0 - blend_factor) * omega_p; - - // Reduce angular speed as heading error approaches zero - double heading_scale = std::clamp( - abs_heading_error / std::max(final_heading_angle_tolerance_, 1e-3), - 0.0, 1.0); - heading_scale = heading_scale * heading_scale; // smoother near zero - omega_target *= heading_scale; - - // Ensure minimum angular velocity for responsiveness - double omega_min = min_vel_theta_; - if (std::fabs(omega_target) < omega_min && - abs_heading_error > final_heading_angle_tolerance_ * 3.0) - { - omega_target = heading_sign * omega_min; - } - } - - // --- Apply acceleration limits --- - // Linear - double v_current = velocity.x; - double dv_max = acc_lim_x_ * dt; - double dv = std::clamp(v_target - v_current, -dv_max, dv_max); - cmd_vel.x = v_current + dv; - - // Angular - double omega_current = velocity.theta; - double domega_max = acc_lim_theta_ * dt; - double domega = std::clamp(omega_target - omega_current, -domega_max, domega_max); - cmd_vel.theta = omega_current + domega; - - // --- Apply velocity limits --- - cmd_vel.x = std::clamp(cmd_vel.x, -v_min, v_min); - cmd_vel.theta = std::clamp(cmd_vel.theta, -max_vel_theta_, max_vel_theta_); - - // --- Safety: ensure we can stop --- - double max_v_to_stop = std::sqrt(2.0 * std::fabs(decel_lim_x_) * xy_error); - if (std::fabs(cmd_vel.x) > max_v_to_stop) - { - cmd_vel.x = std::copysign(max_v_to_stop, cmd_vel.x); - } - - cmd_vel.y = 0.0; - -#ifdef BUILD_WITH_ROS - ROS_DEBUG_THROTTLE(0.2, "[FinalHeading] xy=%.3f, heading=%.3f, v=%.3f, omega=%.3f", - xy_error, heading_error, cmd_vel.x, cmd_vel.theta); -#endif -} - -void mkt_algorithm::diff::PredictiveTrajectory::pid( - const double &error, double &integral, double &last_error, const double &dt, const double &kp, const double &ki, const double &kd, double &output) -{ - if (!near_goal_heading_was_active_) - { - integral = 0.0; - last_error = error; - near_goal_heading_was_active_ = true; - } - const double dt_safe = std::max(dt, 1e-6); - double w_p = kp * error; - integral += error * dt_safe; - const double integral_cap = (std::fabs(ki) > 1e-9)? (2.0 / ki) : 1e6; - integral = std::clamp(integral, -integral_cap, integral_cap); - double w_i = ki * integral; - double w_d = kd * (error - last_error) / dt_safe; - last_error = error; - output = w_p + w_i + w_d; -} - -double mkt_algorithm::diff::PredictiveTrajectory::getLookAheadDistance(const robot_nav_2d_msgs::Twist2D &velocity) -{ - // If using velocity-scaled look ahead distances, find and clamp the dist - // Else, use the static look ahead distance - double lookahead_dist = lookahead_dist_; - if (use_velocity_scaled_lookahead_dist_) - { - lookahead_dist = fabs(velocity.x) * lookahead_time_; - lookahead_dist = std::clamp(lookahead_dist, min_lookahead_dist_, max_lookahead_dist_); - } - return lookahead_dist; -} - -std::vector::iterator -mkt_algorithm::diff::PredictiveTrajectory::getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan) -{ - if (global_plan.poses.empty()) - throw robot_nav_core2::PlannerTFException("The global plan passed to the local planner is empty."); - - if (global_plan.poses.size() < 2) - return std::prev(global_plan.poses.end()); - - unsigned int goal_index = (unsigned)global_plan.poses.size() - 1; - - // Góc đầu và ngưỡng gãy (fixed) - const auto &p0 = global_plan.poses[0].pose; - const auto &p1 = global_plan.poses[1].pose; - double start_angle = atan2(p1.y - p0.y, p1.x - p0.x); - double turn_threshold = M_PI_2 * 0.6; // ~54deg, chỉnh theo nhu cầu - - // Dừng nếu gãy góc - for (unsigned int i = 1; i < global_plan.poses.size(); ++i) - { - const auto &a = global_plan.poses[i - 1].pose; - const auto &b = global_plan.poses[i].pose; - double current_angle = atan2(b.y - a.y, b.x - a.x); - double delta = angles::normalize_angle(current_angle - start_angle); - goal_index = i; - if (fabs(delta) >= turn_threshold) - break; - } - // Chọn điểm lookahead theo khoảng cách - auto goal_pose_it = std::find_if( - global_plan.poses.begin(), global_plan.poses.begin() + goal_index, - [&](const auto &ps) { - return std::hypot(ps.pose.x, ps.pose.y) >= lookahead_dist; - }); - - if (goal_pose_it == global_plan.poses.end()) - goal_pose_it = std::prev(global_plan.poses.end()); - - return goal_pose_it; -} - -bool mkt_algorithm::diff::PredictiveTrajectory::pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose, robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot) -{ - if (global_plan.poses.empty()) - return false; - if (tf == nullptr) - return false; - try - { - // let's get the pose of the robot in the frame of the plan - robot_nav_2d_msgs::Pose2DStamped robot; - if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot)) - { - throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into global plan's frame"); - } - - double dist_thresh_sq = dist_behind_robot * dist_behind_robot; - - // iterate plan until a pose close the robot is found - std::vector::iterator it = global_plan.poses.begin(); - std::vector::iterator erase_end = it; - while (it != global_plan.poses.end()) - { - double dx = robot.pose.x - it->pose.x; - double dy = robot.pose.y - it->pose.y; - double dist_sq = dx * dx + dy * dy; - if (dist_sq < dist_thresh_sq) - { - erase_end = it; - break; - } - ++it; - } - if (erase_end == global_plan.poses.end()) - return false; - - if (erase_end != global_plan.poses.begin()) - global_plan.poses.erase(global_plan.poses.begin(), erase_end); - } - catch (const tf3::TransformException &ex) - { - robot::log_debug("[%s:%d]\n Cannot prune path since no transform is available: %s\n", __FILE__, __LINE__, ex.what()); - return false; - } - return true; -} - -double mkt_algorithm::diff::PredictiveTrajectory::calculateMaxKappa(const robot_nav_2d_msgs::Path2D &path, const double preview_distance) -{ - double traveled = 0.0; - double max_kappa = 0.0; - for (size_t i = 1; i + 1 < path.poses.size(); ++i) - { - const auto &p0 = path.poses[i - 1].pose; - const auto &p1 = path.poses[i].pose; - const auto &p2 = path.poses[i + 1].pose; - - const double a = std::hypot(p1.x - p0.x, p1.y - p0.y); - const double b = std::hypot(p2.x - p1.x, p2.y - p1.y); - const double c = std::hypot(p2.x - p0.x, p2.y - p0.y); - traveled += a; - - if (a > 1e-6 && b > 1e-6 && c > 1e-6) - { - const double cross = (p1.x - p0.x) * (p2.y - p0.y) - (p1.y - p0.y) * (p2.x - p0.x); - const double area2 = std::fabs(cross); // 2 * area - const double kappa = 2.0 * area2 / (a * b * c); - max_kappa = std::max(max_kappa, std::fabs(kappa)); - } - - if (traveled >= preview_distance) - break; - } - return max_kappa; -} - -double mkt_algorithm::diff::PredictiveTrajectory::adjustSpeedWithHermiteTrajectory( - const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Path2D &trajectory, - double v_target, - const double &sign_x) -{ - if(trajectory.poses.size() < 2) - return min_approach_linear_velocity_ * sign_x; - - double preview_distance = std::clamp(std::fabs(velocity.x) * lookahead_time_, min_lookahead_dist_, max_lookahead_dist_); - - double max_kappa = calculateMaxKappa(trajectory, preview_distance); - double v_limit = std::fabs(v_target); - double journey_distance = journey(trajectory.poses, 0, trajectory.poses.size() - 1); - - const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; - const double v_min = std::min(fabs(v_limited), min_speed_xy_); - if (journey_distance < min_journey_squared_) - { - v_limit = std::clamp(sqrt(2.0 * fabs(decel_lim_x_) * journey_distance), min_approach_linear_velocity_, v_min) * sign_x; - } - - if (max_kappa > 1e-6 && max_lateral_accel_ > 1e-6) - { - const double v_curve = std::sqrt(max_lateral_accel_ / max_kappa); - v_limit = std::min(v_limit, v_curve); - } - - if(trajectory.poses.size() > 2 && fabs(trajectory.poses.front().pose.theta) >= angle_threshold_) - v_limit = v_min * sign_x; - - if (fabs(decel_lim_x_) > 1e-6) - { - const double remaining = journey(trajectory.poses, 0, trajectory.poses.size() - 1); - const double v_stop = std::sqrt(2.0 * fabs(decel_lim_x_) * std::max(0.0, remaining)); - v_limit = std::min(v_limit, v_stop); - } - v_limit = std::min(v_limit, fabs(v_target)); - - return std::copysign(v_limit, sign_x); -} - -robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateTrajectory( - const robot_nav_2d_msgs::Path2D &path, - const robot_nav_2d_msgs::Twist2D &drive_target, - const robot_nav_2d_msgs::Twist2D &velocity, - const double &sign_x, - robot_nav_2d_msgs::Twist2D &drive_cmd, - const double &dt) -{ - if (path.poses.empty()) - { - drive_cmd.x = 0.0; - drive_cmd.theta = 0.0; - return robot_nav_2d_msgs::Path2D(); - } - - drive_cmd.x = drive_target.x; - drive_cmd.theta = max_vel_theta_; - double max_kappa = calculateMaxKappa(path); - const double straight_threshold = std::max(0.05, 2.0 * (costmap_robot_ ? costmap_robot_->getCostmap()->getResolution() : 0.05)); - // nếu đường thẳng - if (max_kappa <= straight_threshold) - { - if(fabs(path.poses.back().pose.x) < min_lookahead_dist_ * 0.8) - { - if(fabs(path.poses.back().pose.x) < min_journey_squared_) - drive_cmd.theta = 0.01; - return generateParallelPath(path, sign_x); - } - return generateHermiteTrajectory(path, sign_x); - } - else // nếu đường cong - { - const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; - const double v_min = std::min(fabs(v_limited), min_speed_xy_); - if(fabs(drive_cmd.x) < v_min) - { - drive_cmd.x = std::copysign(v_min, sign_x); - } - return generateHermiteQuadraticTrajectory(path, sign_x); - } -} - -robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateParallelPath( - const robot_nav_2d_msgs::Path2D &path, const double &sign_x) -{ - robot_nav_2d_msgs::Path2D parallel_path; - parallel_path.header = path.header; - int N = path.poses.size(); - if (N < 2) return parallel_path; - - double offset_y = path.poses.front().pose.y; - - parallel_path.poses.resize(N); - for (int i = 0; i < N; ++i) - { - const auto& p = path.poses[i].pose; - - double dx, dy; - if (i == 0) { - dx = path.poses[i+1].pose.x - p.x; - dy = path.poses[i+1].pose.y - p.y; - } else if (i == N-1) { - dx = p.x - path.poses[i-1].pose.x; - dy = p.y - path.poses[i-1].pose.y; - } else { - dx = path.poses[i+1].pose.x - path.poses[i-1].pose.x; - dy = path.poses[i+1].pose.y - path.poses[i-1].pose.y; - } - if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) - continue; - double theta = atan2(dy, dx); - double x_off = p.x - offset_y * sin(theta)*sign_x; - double y_off = p.y - offset_y * cos(theta)*sign_x; - - parallel_path.poses[i].header = path.poses[i].header; - parallel_path.poses[i].pose.x = x_off; - parallel_path.poses[i].pose.y = y_off; - parallel_path.poses[i].pose.theta = sign_x < 0 ? angles::normalize_angle(theta + M_PI) : theta; - } - return parallel_path; -} - -robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateHermiteTrajectory( - const robot_nav_2d_msgs::Path2D &path, const double &sign_x) -{ - robot_nav_2d_msgs::Path2D hermite_trajectory; - hermite_trajectory.poses.clear(); - hermite_trajectory.header = path.header; - - if (path.poses.empty()) - return hermite_trajectory; - - const auto &goal = path.poses.back(); - if (hermite_trajectory.header.frame_id.empty()) - hermite_trajectory.header.frame_id = goal.header.frame_id; - if (hermite_trajectory.header.stamp.isZero()) - hermite_trajectory.header.stamp = goal.header.stamp; - - const double x = goal.pose.x; - const double y = goal.pose.y; - double theta = goal.pose.theta; - const double L = std::hypot(x, y); - if (L < 1e-6) { - robot_nav_2d_msgs::Pose2DStamped pose_stamped; - pose_stamped.pose.x = x; - pose_stamped.pose.y = y; - pose_stamped.pose.theta = theta; - pose_stamped.header.stamp = hermite_trajectory.header.stamp; - pose_stamped.header.frame_id = hermite_trajectory.header.frame_id; - hermite_trajectory.poses.push_back(pose_stamped); - return hermite_trajectory; - } - - int samples = L/costmap_robot_->getCostmap()->getResolution(); - if (samples < 1) { - samples = 1; - } - hermite_trajectory.poses.reserve(samples + 1); - const double Lnegative = sign_x < 0 ? -L : L; - for (int i = 0; i <= samples; ++i) { - double t = static_cast(i) / samples; - double t2 = t * t; - double t3 = t2 * t; - - double h00 = 2 * t3 - 3 * t2 + 1; - double h10 = t3 - 2 * t2 + t; - double h01 = -2 * t3 + 3 * t2; - double h11 = t3 - t2; - - // Hermite interpolation - double px = h10 * Lnegative + h01 * x + h11 * Lnegative * std::cos(theta); - double py = h01 * y + h11 * Lnegative * std::sin(theta); - - // First derivatives for heading - double dh00 = 6 * t2 - 6 * t; - double dh10 = 3 * t2 - 4 * t + 1; - double dh01 = -6 * t2 + 6 * t; - double dh11 = 3 * t2 - 2 * t; - - double dx = dh10 * Lnegative + dh01 * x + dh11 * Lnegative * std::cos(theta); - double dy = dh01 * y + dh11 * Lnegative * std::sin(theta); - - if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) - continue; - double heading = std::atan2(dy, dx); - - robot_nav_2d_msgs::Pose2DStamped pose_out; - pose_out.pose.x = px; - pose_out.pose.y = py; - pose_out.pose.theta = sign_x < 0 ? angles::normalize_angle(heading + M_PI) : heading; - pose_out.header.stamp = hermite_trajectory.header.stamp; - pose_out.header.frame_id = hermite_trajectory.header.frame_id; - hermite_trajectory.poses.push_back(pose_out); - } - return hermite_trajectory; -} - -robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateHermiteQuadraticTrajectory( - const robot_nav_2d_msgs::Path2D &path, const double &sign_x) -{ - robot_nav_2d_msgs::Path2D trajectory; - trajectory.poses.clear(); - trajectory.header = path.header; - if (path.poses.empty()) - return trajectory; - - const auto &goal = path.poses.back(); - if (trajectory.header.frame_id.empty()) - trajectory.header.frame_id = goal.header.frame_id; - if (trajectory.header.stamp.isZero()) - trajectory.header.stamp = goal.header.stamp; - - const double x = goal.pose.x; - const double y = goal.pose.y; - const double theta = sign_x < 0 ? angles::normalize_angle(goal.pose.theta + M_PI) : goal.pose.theta; - const double L = std::hypot(x, y); - if (L < 1e-6) - { - robot_nav_2d_msgs::Pose2DStamped pose_stamped; - pose_stamped.pose.x = 0.0; - pose_stamped.pose.y = 0.0; - pose_stamped.pose.theta = 0.0; - pose_stamped.header.stamp = trajectory.header.stamp; - pose_stamped.header.frame_id = trajectory.header.frame_id; - trajectory.poses.push_back(pose_stamped); - return trajectory; - } - - int samples = L/costmap_robot_->getCostmap()->getResolution(); - if (samples < 1) { - samples = 1; - } - trajectory.poses.reserve(samples + 1); - - // Quadratic Hermite with end tangent aligned to carrot_pose heading: - // p(0) = 0, p(1) = goal, p'(1) = v1 - const double v1x = L * std::cos(theta); - const double v1y = L * std::sin(theta); - const double ax = v1x - x; - const double ay = v1y - y; - const double bx = 2.0 * x - v1x; - const double by = 2.0 * y - v1y; - - trajectory.poses.reserve(samples + 1); - for (int i = 0; i <= samples; ++i) - { - double t = static_cast(i) / samples; - double t2 = t * t; - - double px = ax * t2 + bx * t; - double py = ay * t2 + by * t; - - double dx = 2.0 * ax * t + bx; - double dy = 2.0 * ay * t + by; - if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) - continue; - double heading = std::atan2(dy, dx); - - robot_nav_2d_msgs::Pose2DStamped pose_out; - pose_out.pose.x = px; - pose_out.pose.y = py; - pose_out.pose.theta = sign_x < 0 ? angles::normalize_angle(heading + M_PI) : heading; - pose_out.header.stamp = trajectory.header.stamp; - pose_out.header.frame_id = trajectory.header.frame_id; - trajectory.poses.push_back(pose_out); - } - - return trajectory; -} - -bool mkt_algorithm::diff::PredictiveTrajectory::transformGlobalPlan( - TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &robot_base_frame, double max_plan_length, - robot_nav_2d_msgs::Path2D &transformed_plan) -{ - // this method is a slightly modified version of base_local_planner/goal_functions.h - transformed_plan.poses.clear(); - transformed_plan.header.stamp = pose.header.stamp; - transformed_plan.header.frame_id = robot_base_frame; - - if (global_plan.poses.empty()) - return false; - - if (tf == nullptr) - return false; - - if (costmap == nullptr || costmap->getCostmap() == nullptr) - return false; - - try - { - if (global_plan.poses.empty()) - { - robot::log_error("[%s:%d]\n Received plan with zero length", __FILE__, __LINE__); - return false; - } - - // let's get the pose of the robot in the frame of the plan - robot_nav_2d_msgs::Pose2DStamped robot_pose; - if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot_pose)) - { - throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into global plan's frame"); - } - - // we'll discard points on the plan that are outside the local costmap - double dist_threshold = std::max(costmap->getCostmap()->getSizeInCellsX() * costmap->getCostmap()->getResolution() / 2.0, - costmap->getCostmap()->getSizeInCellsY() * costmap->getCostmap()->getResolution() / 2.0); - - dist_threshold *= 0.85; // just consider 85% of the costmap size to better incorporate point obstacle that are - double sq_dist_threshold = dist_threshold * dist_threshold; - // located on the border of the local costmap - - int i = 0; - double sq_dist = std::numeric_limits::infinity(); - - // we need to loop to a point on the plan that is within a certain distance of the robot - bool robot_reached = false; - for (int j = 0; j < (int)global_plan.poses.size(); ++j) - { - double x_diff = robot_pose.pose.x - global_plan.poses[j].pose.x; - double y_diff = robot_pose.pose.y - global_plan.poses[j].pose.y; - double new_sq_dist = x_diff * x_diff + y_diff * y_diff; - if (robot_reached && new_sq_dist > sq_dist_threshold) - { - break; - } // force stop if we have reached the costmap border - - if (new_sq_dist < sq_dist) // find closest distance - { - sq_dist = new_sq_dist; - i = j; - if (sq_dist < costmap->getCostmap()->getResolution()) // 5 cm to the robot; take the immediate local minima; if it's not the global - robot_reached = true; // minima, probably means that there's a loop in the path, and so we prefer this - } - } - - double plan_length = 0; // check cumulative Euclidean distance along the plan - double x_direction_saved = 0.0; - // now we'll transform until points are outside of our distance threshold - while (i < (int)global_plan.poses.size() && sq_dist <= sq_dist_threshold && - (max_plan_length <= 0 || plan_length <= max_plan_length)) - { - robot_nav_2d_msgs::Pose2DStamped stamped_pose; - stamped_pose.pose = global_plan.poses[i].pose; - stamped_pose.header.frame_id = global_plan.header.frame_id; - - robot_nav_2d_msgs::Pose2DStamped newer_pose; - if (!robot_nav_2d_utils::transformPose(tf, robot_base_frame, stamped_pose, newer_pose)) - { - ++i; - continue; - } - transformed_plan.poses.push_back(newer_pose); - - double x_diff = robot_pose.pose.x - global_plan.poses[i].pose.x; - double y_diff = robot_pose.pose.y - global_plan.poses[i].pose.y; - sq_dist = x_diff * x_diff + y_diff * y_diff; - - // Calculate distance to previous pose - if (i > 0 && max_plan_length > 0) - { - robot_geometry_msgs::Pose2D p1 = global_plan.poses[i].pose; - robot_geometry_msgs::Pose2D p2 = global_plan.poses[i - 1].pose; - plan_length += std::sqrt(std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2)); - if (fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) - { - const double egde_angle = atan2(p1.y - p2.y, p1.x - p2.x); - const double target_direction = cos(fabs(egde_angle - p1.theta)); - if (target_direction * x_direction_saved < 0.0) - { - plan_length = 0; - } - x_direction_saved = target_direction; - } - } - ++i; - } - } - catch (tf3::LookupException &ex) - { - robot::log_error("[%s:%d]\n No Transform available Error: %s\n", __FILE__, __LINE__, ex.what()); - return false; - } - catch (tf3::ConnectivityException &ex) - { - robot::log_error("[%s:%d]\n Connectivity Error: %s\n", __FILE__, __LINE__, ex.what()); - return false; - } - catch (tf3::ExtrapolationException &ex) - { - robot::log_error("[%s:%d]\n Extrapolation Error: %s\n", __FILE__, __LINE__, ex.what()); - if (global_plan.poses.size() > 0) - robot::log_error("[%s:%d]\n Robot Frame: %s Plan Frame size %d: %s\n", __FILE__, __LINE__, robot_base_frame.c_str(), (unsigned int)global_plan.poses.size(), global_plan.header.frame_id.c_str()); - - return false; - } - return true; -} - -void mkt_algorithm::diff::PredictiveTrajectory::moveWithAccLimits( - const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Twist2D &cmd_vel, robot_nav_2d_msgs::Twist2D &cmd_vel_result, const double &dt) -{ - // --- X axis --- - double min_vel_x = traj_ ? min_vel_x_ : fabs(traj_->getTwistLinear(false).x); - double max_vel_x = traj_ ? max_vel_x_ : fabs(traj_->getTwistLinear(true).x); - - double vx = cmd_vel.x > 0.0 ? std::min(max_vel_x, std::max(min_vel_x, cmd_vel.x)) : std::max(-max_vel_x, std::min(-min_vel_x, cmd_vel.x)); - - double max_acc_vx = velocity.x + fabs(acc_lim_x_) * dt; - double min_acc_vx = velocity.x - fabs(decel_lim_x_) * dt; - vx = std::clamp(vx, min_acc_vx, max_acc_vx); - - // --- Y axis --- - double min_vel_y = traj_ ? min_vel_y_ : fabs(traj_->getTwistLinear(false).y); - double max_vel_y = traj_ ? max_vel_y_ : fabs(traj_->getTwistLinear(true).y); - double vy = cmd_vel.y > 0.0 ? std::min(max_vel_y, std::max(min_vel_y, cmd_vel.y)) : std::max(-max_vel_y, std::min(-min_vel_y, cmd_vel.y)); - - double max_acc_vy = velocity.y + fabs(acc_lim_y_) * dt; - double min_acc_vy = velocity.y - fabs(decel_lim_y_) * dt; - vy = std::clamp(vy, min_acc_vy, max_acc_vy); - // --- Assign result --- - cmd_vel_result.x = vx; - cmd_vel_result.y = vy; - // cmd_vel_result.theta = vth; -} - -bool mkt_algorithm::diff::PredictiveTrajectory::stopWithAccLimits(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt) -{ - // slow down with the maximum possible acceleration... we should really use the frequency that we're running at to determine what is feasible - // but we'll use a tenth of a second to be consistent with the implementation of the local planner. - double vx = sign(velocity.x) * std::max(0.0, (fabs(velocity.x) - fabs(decel_lim_x_) * dt)); - double vy = sign(velocity.y) * std::max(0.0, (fabs(velocity.y) - fabs(decel_lim_y_) * dt)); - - double vel_yaw = velocity.theta; - double vth = sign(vel_yaw) * std::max(0.0, (fabs(vel_yaw) - fabs(decel_lim_theta_) * dt)); - - cmd_vel.x = vx; - cmd_vel.y = vy; - cmd_vel.theta = vth; - return true; -} - -std::vector -mkt_algorithm::diff::PredictiveTrajectory::interpolateFootprint(const robot_geometry_msgs::Pose2D &pose, const std::vector &footprint, const double &resolution) -{ - - // Dịch sang tọa độ tuyệt đối - std::vector abs_footprint; - double cos_th = std::cos(pose.theta); - double sin_th = std::sin(pose.theta); - for (auto pt : footprint) - { - pt.x *= 1.2; - pt.y *= 1.2; - robot_geometry_msgs::Point abs_pt; - abs_pt.x = pose.x + pt.x * cos_th - pt.y * sin_th; - abs_pt.y = pose.y + pt.x * sin_th + pt.y * cos_th; - abs_footprint.push_back(abs_pt); - } - - std::vector points; - for (size_t i = 0; i < abs_footprint.size(); ++i) - { - const robot_geometry_msgs::Point &start = abs_footprint[i]; - const robot_geometry_msgs::Point &end = abs_footprint[(i + 1) % abs_footprint.size()]; - - double dx = end.x - start.x; - double dy = end.y - start.y; - double distance = std::hypot(dx, dy); - int steps = std::max(1, static_cast(std::floor(distance / resolution))); - - for (int j = 0; j <= steps; ++j) - { - if (j == steps && i != abs_footprint.size() - 1) - continue; // tránh lặp - double t = static_cast(j) / steps; - robot_geometry_msgs::Point pt; - pt.x = start.x + t * dx; - pt.y = start.y + t * dy; - points.push_back(pt); - } - } - return points; -} - -double mkt_algorithm::diff::PredictiveTrajectory::costAtPose(const double &x, const double &y) -{ - unsigned int mx, my; - unsigned char cost; - if (costmap_robot_->getCostmap()->worldToMap(x, y, mx, my)) - { - cost = costmap_robot_->getCostmap()->getCost(mx, my); - } - return static_cast(cost); -} - -score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::PredictiveTrajectory::create() -{ - return std::make_shared(); -} - +#include +#include + + +mkt_algorithm::diff::PredictiveTrajectory::PredictiveTrajectory() + : initialized_(false), + nav_stop_(false), + x_direction_(0.0), + y_direction_(0.0), + theta_direction_(0.0), + use_velocity_scaled_lookahead_dist_(false), + lookahead_time_(0.0), + lookahead_dist_(0.0), + min_lookahead_dist_(0.0), + max_lookahead_dist_(0.0), + max_lateral_accel_(0.0), + use_rotate_to_heading_(false), + rotate_to_heading_min_angle_(0.0), + min_path_distance_(0.0), + max_path_distance_(0.0), + use_final_heading_alignment_(false), + final_heading_xy_tolerance_(0.0), + final_heading_angle_tolerance_(0.0), + final_heading_min_velocity_(0.0), + final_heading_kp_angular_(0.0), + final_heading_ki_angular_(0.0), + final_heading_kd_angular_(0.0), + near_goal_heading_integral_(0.0), + near_goal_heading_last_error_(0.0), + near_goal_heading_was_active_(false), + min_approach_linear_velocity_(0.0), + use_cost_regulated_linear_velocity_scaling_(false), + inflation_cost_scaling_factor_(0.0), + cost_scaling_dist_(0.0), + cost_scaling_gain_(0.0), + control_duration_(0.0), + kf_(nullptr), + kf_q_v_(0.25), + kf_q_w_(0.8), + kf_r_v_(0.05), + kf_r_w_(0.08), + kf_p0_(0.5), + kf_filter_angular_(false), + m_(0), + n_(0) +{ +} + +mkt_algorithm::diff::PredictiveTrajectory::~PredictiveTrajectory() {} + +void mkt_algorithm::diff::PredictiveTrajectory::initialize( + robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) +{ + if (!initialized_) + { + nh_ = nh; + nh_priv_ = robot::NodeHandle(nh, name); + robot::log_info_at(__FILE__, __LINE__, "nh_ : %s", nh_.getNamespace().c_str()); + robot::log_info_at(__FILE__, __LINE__, "nh_priv_ : %s", nh_priv_.getNamespace().c_str()); + name_ = name; + tf_ = tf; + traj_ = traj; + costmap_robot_ = costmap_robot; + nh_.param("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); + this->getParams(); + + std::vector footprint = costmap_robot_ ? costmap_robot_->getRobotFootprint() : std::vector(); + if (footprint.size() > 1) + { + double min_length = 1e10; + double max_length = 0.0; + for (size_t i = 0; i < footprint.size(); ++i) + { + const robot_geometry_msgs::Point &p1 = footprint[i]; + const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point + double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0; + if (len > max_length) + { + max_length = len; + } + if (len < min_length) + { + min_length = len; + } + } + this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; + this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; + } + + // kalman + last_actuator_update_ = robot::Time::now(); + // State: [v, a, j, w, alpha, jw] where: + // - v: linear velocity, a: linear accel, j: linear jerk + // - w: angular velocity, alpha: angular accel, jw: angular jerk + // Measurement: [v, w] + n_ = 6; + m_ = 2; + double dt = control_duration_; + + // Khởi tạo ma trận + A = Eigen::MatrixXd::Identity(n_, n_); + C = Eigen::MatrixXd::Zero(m_, n_); + Q = Eigen::MatrixXd::Zero(n_, n_); + R = Eigen::MatrixXd::Zero(m_, m_); + P = Eigen::MatrixXd::Identity(n_, n_) * std::max(1e-9, kf_p0_); + + for (int i = 0; i < n_; i += 3) + { + A(i, i + 1) = dt; + A(i, i + 2) = 0.5 * dt * dt; + A(i + 1, i + 2) = dt; + } + + C(0, 0) = 1; + C(1, 3) = 1; + Q(2, 2) = std::max(1e-12, kf_q_v_); + Q(5, 5) = std::max(1e-12, kf_q_w_); + + R(0, 0) = std::max(1e-12, kf_r_v_); + R(1, 1) = std::max(1e-12, kf_r_w_); + + kf_ = boost::make_shared(dt, A, C, Q, R, P); + Eigen::VectorXd x0(n_); + x0 << 0, 0, 0, 0, 0, 0; + kf_->init(robot::Time::now().toSec(), x0); + +#ifdef BUILD_WITH_ROS + ros::NodeHandle nh_ros; + current_goal_pub_ = nh_ros.advertise("current_goal", 10); + closet_robot_goal_pub_ = nh_ros.advertise("closet_robot_goal", 10); + lookahead_point_pub_ = nh_ros.advertise("lookahead_point", 10); +#endif + + x_direction_ = y_direction_ = theta_direction_ = 0; + this->initialized_ = true; + robot::log_info("[%s:%d]\n PredictiveTrajectory Initialized successfully", __FILE__, __LINE__); + } +} + +void mkt_algorithm::diff::PredictiveTrajectory::getParams() +{ + robot_base_frame_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "robot_base_frame", std::string("base_link")); + nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5); + nh_priv_.param("angle_threshold", angle_threshold_, M_PI / 8); + nh_priv_.param("index_samples", index_samples_, 0); + nh_priv_.param("follow_step_path", follow_step_path_, false); + + nh_priv_.param("use_velocity_scaled_lookahead_dist", use_velocity_scaled_lookahead_dist_, false); + nh_priv_.param("lookahead_dist", lookahead_dist_, 0.25); + nh_priv_.param("min_lookahead_dist", min_lookahead_dist_, 0.3); + nh_priv_.param("max_lookahead_dist", max_lookahead_dist_, 0.9); + nh_priv_.param("lookahead_time", lookahead_time_, 1.5); + nh_priv_.param("min_journey_squared", min_journey_squared_, std::numeric_limits::infinity()); + nh_priv_.param("max_journey_squared", max_journey_squared_, std::numeric_limits::infinity()); + + nh_priv_.param("use_rotate_to_heading", use_rotate_to_heading_, false); + nh_priv_.param("rotate_to_heading_min_angle", rotate_to_heading_min_angle_, 0.785); + + // Final heading alignment (Arc Motion) + nh_priv_.param("use_final_heading_alignment", use_final_heading_alignment_, true); + nh_priv_.param("final_heading_xy_tolerance", final_heading_xy_tolerance_, 0.15); + nh_priv_.param("final_heading_angle_tolerance", final_heading_angle_tolerance_, 0.05); + nh_priv_.param("final_heading_min_velocity", final_heading_min_velocity_, 0.05); + nh_priv_.param("final_heading_kp_angular", final_heading_kp_angular_, 1.5); + nh_priv_.param("final_heading_ki_angular", final_heading_ki_angular_, 0.0); + nh_priv_.param("final_heading_kd_angular", final_heading_kd_angular_, 0.0); + + nh_priv_.param("rot_stopped_velocity", rot_stopped_velocity_, 0.01); + nh_priv_.param("trans_stopped_velocity", trans_stopped_velocity_, 0.01); + if (trans_stopped_velocity_ < 0.02) + trans_stopped_velocity_ = 0.5 * min_approach_linear_velocity_; + if (trans_stopped_velocity_ > min_approach_linear_velocity_) + trans_stopped_velocity_ = min_approach_linear_velocity_ + 0.01; + + // Inflation cost scaling (Limit velocity by proximity to obstacles) + nh_priv_.param("use_cost_regulated_linear_velocity_scaling", use_cost_regulated_linear_velocity_scaling_, true); + nh_priv_.param("inflation_cost_scaling_factor", inflation_cost_scaling_factor_, 3.0); + nh_priv_.param("cost_scaling_dist", cost_scaling_dist_, 0.6); + nh_priv_.param("cost_scaling_gain", cost_scaling_gain_, 1.0); + nh_priv_.param("max_lateral_accel", max_lateral_accel_, 1.0); + if (inflation_cost_scaling_factor_ <= 0.0) + { + robot::log_warning("[%s:%d]\n The value inflation_cost_scaling_factor is incorrectly set, it should be >0. Disabling cost regulated linear velocity scaling.", __FILE__, __LINE__); + use_cost_regulated_linear_velocity_scaling_ = false; + } + + // Kalman filter tuning (filtering v and w commands) + nh_priv_.param("kf_q_v", kf_q_v_, kf_q_v_); + nh_priv_.param("kf_q_w", kf_q_w_, kf_q_w_); + nh_priv_.param("kf_r_v", kf_r_v_, kf_r_v_); + nh_priv_.param("kf_r_w", kf_r_w_, kf_r_w_); + nh_priv_.param("kf_p0", kf_p0_, kf_p0_); + nh_priv_.param("kf_filter_angular", kf_filter_angular_, kf_filter_angular_); + + double control_frequency = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "controller_frequency", 10); + control_duration_ = 1.0 / control_frequency; + + if (traj_) + { + traj_.get()->getNodeHandle().param("max_vel_x", max_vel_x_, 0.0); + traj_.get()->getNodeHandle().param("min_vel_x", min_vel_x_, 0.0); + traj_.get()->getNodeHandle().param("acc_lim_x", acc_lim_x_, 0.0); + traj_.get()->getNodeHandle().param("decel_lim_x", decel_lim_x_, 0.0); + + traj_.get()->getNodeHandle().param("max_vel_y", max_vel_y_, 0.0); + traj_.get()->getNodeHandle().param("min_vel_y", min_vel_y_, 0.0); + traj_.get()->getNodeHandle().param("acc_lim_y", acc_lim_y_, 0.0); + traj_.get()->getNodeHandle().param("decel_lim_y", decel_lim_y_, 0.0); + + traj_.get()->getNodeHandle().param("max_vel_theta", max_vel_theta_, 0.0); + traj_.get()->getNodeHandle().param("min_vel_theta", min_vel_theta_, 0.0); + traj_.get()->getNodeHandle().param("acc_lim_theta", acc_lim_theta_, 0.0); + traj_.get()->getNodeHandle().param("decel_lim_theta", decel_lim_theta_, 0.0); + traj_.get()->getNodeHandle().param("min_speed_xy", min_speed_xy_, 0.0); + if(fabs(min_speed_xy_) > sqrt(max_vel_x_ * max_vel_x_ + max_vel_y_ * max_vel_y_)) + { + min_speed_xy_ = sqrt(max_vel_x_ * max_vel_x_ + max_vel_y_ * max_vel_y_); + } + if(fabs(min_speed_xy_) > sqrt(min_vel_x_ * min_vel_x_ + min_vel_y_ * min_vel_y_)) + { + min_speed_xy_ = sqrt(max_vel_x_ * max_vel_x_ + max_vel_y_ * max_vel_y_); + } + + traj_.get()->getNodeHandle().param("max_speed_xy", max_speed_xy_, 0.0); + } +} + +void mkt_algorithm::diff::PredictiveTrajectory::reset() +{ + if (this->initialized_) + { + robot::log_info("[%s:%d]\n PredictiveTrajectory is reset", __FILE__, __LINE__); + reached_intermediate_goals_.clear(); + start_index_saved_vt_.clear(); + this->clear(); + x_direction_ = y_direction_ = theta_direction_ = 0; + this->follow_step_path_ = false; + this->nav_stop_ = false; + last_actuator_update_ = robot::Time::now(); + prevous_drive_cmd_ = robot_nav_2d_msgs::Twist2D(); + near_goal_heading_integral_ = 0.0; + near_goal_heading_last_error_ = 0.0; + near_goal_heading_was_active_ = false; + + if (kf_) + { + Eigen::VectorXd x0(n_); + x0 << 0, 0, 0, 0, 0, 0; + kf_->init(robot::Time::now().toSec(), x0); + } + } +} + +void mkt_algorithm::diff::PredictiveTrajectory::stop() +{ + this->nav_stop_ = true; +} + +void mkt_algorithm::diff::PredictiveTrajectory::resume() +{ + if (this->initialized_) + { + if(!this->nav_stop_) + return; + prevous_drive_cmd_ = robot_nav_2d_msgs::Twist2D(); + last_actuator_update_ = robot::Time::now(); + + if (kf_) + { + Eigen::VectorXd x0(n_); + x0 << 0, 0, 0, 0, 0, 0; + kf_->init(robot::Time::now().toSec(), x0); + } + this->nav_stop_ = false; + } +} + +bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, + double &x_direction, double &y_direction, double &theta_direction) +{ + if (!initialized_) + { + robot::log_error("[%s:%d]\n This planner has not been initialized, please call initialize() before using this planner", __FILE__, __LINE__); + return false; + } + if(robot::Time::now() - last_actuator_update_ > robot::Duration(0.5)) + { + last_actuator_update_ = robot::Time::now(); + } + + std::vector footprint = costmap_robot_ ? costmap_robot_->getRobotFootprint() : std::vector(); + if (footprint.size() > 1) + { + double min_length = 1e10; + double max_length = 0.0; + for (size_t i = 0; i < footprint.size(); ++i) + { + const robot_geometry_msgs::Point &p1 = footprint[i]; + const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point + double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0; + if (len > max_length) + { + max_length = len; + } + if (len < min_length) + { + min_length = len; + } + } + this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; + this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; + } + + if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2) + { + robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size()); + return false; + } + this->getParams(); + + frame_id_path_ = global_plan.header.frame_id; + goal_ = goal; + global_plan_ = global_plan; + + // prune global plan to cut off parts of the past (spatially before the robot) + if (!this->pruneGlobalPlan(tf_, pose, global_plan_, 1.0)) + { + robot::log_error("[%s:%d]\n pruneGlobalPlan Failed", __FILE__, __LINE__); + return false; + } + + double S = std::numeric_limits::infinity(); + S = std::max(costmap_robot_->getCostmap()->getSizeInCellsX() * costmap_robot_->getCostmap()->getResolution() / 2.0, + costmap_robot_->getCostmap()->getSizeInCellsY() * costmap_robot_->getCostmap()->getResolution() / 2.0); + const double min_S = min_lookahead_dist_ * 1.5 + max_path_distance_, max_S = max_lookahead_dist_ * 1.5 + max_path_distance_; + S = std::clamp(S * fabs(velocity.x) * lookahead_time_, min_S, max_S); + compute_plan_.poses.clear(); + + if ((unsigned int)global_plan_.poses.size() == 2) + { + double dx = global_plan_.poses.back().pose.x - global_plan_.poses.front().pose.x; + double dy = global_plan_.poses.back().pose.y - global_plan_.poses.front().pose.y; + if (hypot(dx, dy) <= 2.0 * costmap_robot_->getCostmap()->getResolution()) + { + compute_plan_ = global_plan_; + } + else + { + robot::log_error("[%s:%d]\n The Local Plan has 2 points and hypot between more than is %.3f m", __FILE__, __LINE__, costmap_robot_->getCostmap()->getResolution()); + return false; + } + } + else + { + unsigned int start_index, goal_index; + if (!this->computePlanCommand(pose, velocity, S, global_plan_, start_index, goal_index, compute_plan_)) + { + robot::log_error("[%s:%d]\n computePlanCommand is Failed", __FILE__, __LINE__); + return false; + } + } + + double lookahead_dist = this->getLookAheadDistance(velocity); + transform_plan_.poses.clear(); + if (!this->transformGlobalPlan(tf_, compute_plan_, pose, costmap_robot_, robot_base_frame_, lookahead_dist, transform_plan_)) + { + robot::log_warning("[%s:%d]\n Could not transform the global plan to the frame of the controller", __FILE__, __LINE__); + return false; + } + const auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transform_plan_); + if(fabs(carrot_pose.pose.y) > 0.2) + { + lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist); + if (!this->transformGlobalPlan(tf_, compute_plan_, pose, costmap_robot_, robot_base_frame_, lookahead_dist, transform_plan_)) + { + robot::log_warning("[%s:%d]\n Could not transform the global plan to the frame of the controller", __FILE__, __LINE__); + return false; + } + } + + x_direction = x_direction_; + y_direction = y_direction_ = 0; + theta_direction = theta_direction_; + + if ((unsigned int)(compute_plan_.poses.size() > 1) && + journey(compute_plan_.poses, 0, compute_plan_.poses.size() - 1) >= costmap_robot_->getCostmap()->getResolution()) + { + const robot_geometry_msgs::Pose2D p2 = compute_plan_.poses.back().pose; + int index; + for (index = (unsigned int)(compute_plan_.poses.size() - 1); index > 0; index--) + { + robot_geometry_msgs::Pose2D pose = compute_plan_.poses[index].pose; + if (robot_nav_2d_utils::poseDistance(p2, pose) > xy_local_goal_tolerance_) + break; + } + const robot_geometry_msgs::Pose2D p1 = compute_plan_.poses[index].pose; + if (fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) + { + const double path_angle = atan2(p2.y - p1.y, p2.x - p1.x); + const double dir_path = cos(fabs(path_angle - p2.theta)); + if (fabs(dir_path) > M_PI / 6 || x_direction < 1e-9) + x_direction = dir_path > 0 ? FORWARD : BACKWARD; + } + + } + else if(compute_plan_.poses.size() == 1) + { + try + { + // auto carrot_pose_it = getLookAheadPoint(velocity, lookahead_dist, transform_plan_); + // auto prev_carrot_pose_it = transform_plan_.poses.begin(); + // double distance_it = 0; + // for (auto it = carrot_pose_it - 1; it != transform_plan_.poses.begin(); --it) + // { + // double dx = it->pose.x - carrot_pose_it->pose.x; + // double dy = it->pose.y - carrot_pose_it->pose.y; + // distance_it += std::hypot(dx, dy); + // if (distance_it > costmap_robot_->getCostmap()->getResolution()) + // { + // prev_carrot_pose_it = it; + // break; + // } + // } + + // robot_geometry_msgs::Pose front = journey(transform_plan_.poses, 0, transform_plan_.poses.size() - 1) > 5.0 * costmap_robot_->getCostmap()->getResolution() + // ? robot_nav_2d_utils::pose2DToPose((*(prev_carrot_pose_it)).pose) + // : robot_nav_2d_utils::pose2DToPose(robot_geometry_msgs::Pose2D()); + + // robot_geometry_msgs::Pose back = robot_nav_2d_utils::pose2DToPose((*(carrot_pose_it)).pose); + + // teb_local_planner::PoseSE2 start_pose(front); + // teb_local_planner::PoseSE2 goal_pose(back); + // const double dir_path = (goal_pose.position() - start_pose.position()).dot(start_pose.orientationUnitVec()); + + + auto goal_pose = compute_plan_.poses.front().pose; + auto start_pose = pose.pose; + double angle_path = atan2(goal_pose.y - start_pose.y, goal_pose.x - start_pose.x); + double dir_path = cos(fabs(angle_path - goal_pose.theta)); + if (fabs(dir_path) > M_PI / 6 || x_direction < 1e-9) + x_direction = dir_path > 0 ? FORWARD : BACKWARD; + } + catch (std::exception &e) + { + robot::log_error("[%s:%d]\n getLookAheadPoint throw an exception: %s", __FILE__, __LINE__, e.what()); + return false; + } + } + + x_direction_ = x_direction; + y_direction_ = y_direction; + theta_direction_ = theta_direction; + return true; +} + +mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + mkt_msgs::Trajectory2D result; + result.velocity.x = result.velocity.y = result.velocity.theta = 0.0; + if (!traj_) + return result; + if (compute_plan_.poses.size() < 2) + { + robot::log_warning("[%s:%d]\n Local compute plan is available", __FILE__, __LINE__); + return result; + } + + robot::Time current_time = robot::Time::now(); + const double dt = (current_time - last_actuator_update_).toSec(); + last_actuator_update_ = current_time; + + robot_nav_2d_msgs::Twist2D drive_cmd; + double sign_x = sign(x_direction_); + + robot_nav_2d_msgs::Twist2D twist; + traj_->startNewIteration(velocity); + while (robot::ok() && traj_->hasMoreTwists()) + { + twist = traj_->nextTwist(); + } + double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; + drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max)); + // drive_cmd.x = sqrt(twist.x * twist.x); + + robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_; + if (transformed_plan.poses.empty()) + { + robot::log_warning("[%s:%d]\n Transformed plan is empty. Cannot determine a localglobal_plan.", __FILE__, __LINE__); + stopWithAccLimits(pose, velocity, drive_cmd, dt); + result.velocity = drive_cmd; + prevous_drive_cmd_ = drive_cmd; + return result; + } + double lookahead_dist = getLookAheadDistance(velocity); + auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); + robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose); + +#ifdef BUILD_WITH_ROS + { + geometry_msgs::PoseStamped lookahead_point; + lookahead_point.header.stamp = ros::Time::now(); + lookahead_point.header.frame_id = carrot_pose_stamped.header.frame_id; + lookahead_point.pose.position.x = carrot_pose_stamped.pose.position.x; + lookahead_point.pose.position.y = carrot_pose_stamped.pose.position.y; + lookahead_point.pose.position.z = carrot_pose_stamped.pose.position.z; + lookahead_point.pose.orientation.x = carrot_pose_stamped.pose.orientation.x; + lookahead_point.pose.orientation.y = carrot_pose_stamped.pose.orientation.y; + lookahead_point.pose.orientation.z = carrot_pose_stamped.pose.orientation.z; + lookahead_point.pose.orientation.w = carrot_pose_stamped.pose.orientation.w; + lookahead_point_pub_.publish(lookahead_point); + } +#endif + + bool allow_rotate = false; + nh_priv_.param("allow_rotate", allow_rotate, false); + + const double distance_allow_rotate = min_journey_squared_; + const double path_distance_to_rotate = journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1); + allow_rotate |= path_distance_to_rotate >= distance_allow_rotate; + allow_rotate &= std::hypot(compute_plan_.poses.front().pose.x - pose.pose.x, compute_plan_.poses.front().pose.y - pose.pose.y) <= 0.1; + double angle_to_heading; + if (allow_rotate && shouldRotateToPath(transformed_plan, carrot_pose, velocity, angle_to_heading, sign_x)) + { + if (!stopped(velocity, max_vel_theta_ + rot_stopped_velocity_, trans_stopped_velocity_)) + { + if (!stopWithAccLimits(pose, velocity, drive_cmd, dt)) + return result; + } + else + { + rotateToHeading(angle_to_heading, velocity, drive_cmd, dt); + } + } + else + { +// // === Final Heading Alignment Check === +// double xy_error = 0.0, heading_error = 0.0; +// if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x)) +// { +// // Use Arc Motion controller for final heading alignment +// alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd); +// #ifdef BUILD_WITH_ROS +// ROS_INFO("heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f", +// heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta); +// #endif +// } +// else +// { + robot_nav_2d_msgs::Twist2D drive_target = drive_cmd; + transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target); + carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); + + // Normal Pure Pursuit + this->computePurePursuit( + carrot_pose, + drive_target, + velocity, + transformed_plan, + min_approach_linear_velocity_, + sign_x, + dt, + drive_cmd); + // } + applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt); + if (this->nav_stop_) + { + if (!stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_)) + { + if (!stopWithAccLimits(pose, velocity, drive_cmd, dt)) + return result; + } + else + drive_cmd = {}; + result.velocity = drive_cmd; + return result; + } + } + result.poses.clear(); + result.poses.reserve(transformed_plan.poses.size()); + for (const auto &pose_stamped : transformed_plan.poses) + { + result.poses.push_back(pose_stamped.pose); + if(fabs(pose_stamped.pose.x - carrot_pose.pose.x) < 1e-6 && + fabs(pose_stamped.pose.y - carrot_pose.pose.y) < 1e-6 && + fabs(pose_stamped.pose.theta - carrot_pose.pose.theta) < 1e-6) + break; + } + + robot::log_info("vmax %f %f %f", sign_x, fabs(v_max), drive_cmd.x); + if(fabs(v_max) < 0.01) + { + drive_cmd.x = 0.0; + drive_cmd.y = 0.0; + drive_cmd.theta = 0.0; + robot::log_info("vmax %f", drive_cmd.x); + } + result.velocity = drive_cmd; + prevous_drive_cmd_ = drive_cmd; + return result; +} + +void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit( + const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, + const robot_nav_2d_msgs::Twist2D &drive_target, + const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Path2D &trajectory, + const double &min_approach_linear_velocity, + const double &sign_x, + const double &dt, + robot_nav_2d_msgs::Twist2D &drive_cmd) +{ + // 1) Curvature from pure pursuit + const double L2 = carrot_pose.pose.x * carrot_pose.pose.x + carrot_pose.pose.y * carrot_pose.pose.y; + const double L2_min = 0.01; // m^2, chỉnh theo nhu cầu (0.02–0.1) + const double L2_safe = std::max(L2, L2_min); + const double L = std::sqrt(L2_safe); + + const double kappa = 2.0 * carrot_pose.pose.y / L2_safe; + + // 3) Adjust speed using Hermite trajectory curvature + remaining distance + double v_target = adjustSpeedWithHermiteTrajectory(velocity, trajectory, drive_target.x, sign_x); + const double L_min = 0.1; // m, chỉnh theo nhu cầu + double scale_close = std::clamp(L / L_min, 0.0, 1.0); + v_target *= scale_close; + const double y_abs = std::fabs(carrot_pose.pose.y); + const double y_soft = 0.1; + if (y_abs > y_soft) + { + double scale = y_soft / y_abs; // y càng lớn => scale càng nhỏ + scale = std::clamp(scale, 0.2, 1.0); // không giảm quá sâu + v_target *= scale; + robot_nav_2d_msgs::Twist2D cmd, result; + cmd.x = v_target; + this->moveWithAccLimits(velocity, cmd, result, dt); + v_target = result.x; + } + + // 4) Maintain minimum approach speed + if (std::fabs(v_target) < min_approach_linear_velocity) + v_target = std::copysign(min_approach_linear_velocity, sign_x); + + std::stringstream ss; + + // 5) Angular speed from curvature + double w_target = v_target * kappa; + if(journey(trajectory.poses, 0, trajectory.poses.size() - 1) <= min_journey_squared_) + { + if (trajectory.poses.size() >= 2) { + const auto& p1 = trajectory.poses[trajectory.poses.size() - 1].pose; + double heading_ref = 0.0; + for(int i = trajectory.poses.size() - 2; i >= 0; i--) + { + const auto& p = trajectory.poses[i].pose; + const auto& dx = p1.x - p.x ; + const auto& dy = p1.y - p.y ; + if(std::hypot(dx, dy) >= costmap_robot_->getCostmap()->getResolution()) + { + if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) + continue; + heading_ref = std::atan2(dy, dx); + ss << "error " << heading_ref << " "; + if(sign_x < 0.0) + heading_ref += std::copysign(M_PI, heading_ref) * (-1.0); + break; + } + } + + const double error = heading_ref; + ss << error << " "; + double w_heading = 0.0; + pid(error, + near_goal_heading_integral_, + near_goal_heading_last_error_, + dt, + final_heading_kp_angular_, + final_heading_ki_angular_, + final_heading_kd_angular_, + w_heading); + // Apply acceleration limits + double dw_heading = std::clamp(w_heading - velocity.theta, -acc_lim_theta_ * dt, acc_lim_theta_ * dt); + ss << "dw_heading " << dw_heading << " "; + w_target = velocity.theta + dw_heading; + // w_target = std::clamp(w_target, -0.03, 0.03); + } + else + { + w_target = std::clamp(w_target, -0.001, 0.001); + near_goal_heading_was_active_ = false; + } + } + else + { + near_goal_heading_was_active_ = false; + } + + w_target = std::clamp(w_target, -fabs(drive_target.theta), fabs(drive_target.theta)); + + // 6) Apply acceleration limits (linear + angular) + const double dv = std::clamp(v_target - velocity.x, -acc_lim_x_ * dt, acc_lim_x_ * dt); + const double dw = std::clamp(w_target - velocity.theta, -acc_lim_theta_ * dt, acc_lim_theta_ * dt); + + drive_cmd.x = velocity.x + dv; + drive_cmd.theta = velocity.theta + dw; + + Eigen::VectorXd y(2); + y << drive_cmd.x, drive_cmd.theta; + + // Cập nhật lại A nếu dt thay đổi + for (int i = 0; i < n_; ++i) + for (int j = 0; j < n_; ++j) + A(i, j) = (i == j ? 1.0 : 0.0); + for (int i = 0; i < n_; i += 3) + { + A(i, i + 1) = dt; + A(i, i + 2) = 0.5 * dt * dt; + A(i + 1, i + 2) = dt; + } + kf_->update(y, dt, A); + double v_min = min_approach_linear_velocity_; + drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_target), fabs(v_target)); + drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x); + if (kf_filter_angular_) + drive_cmd.theta = std::clamp(kf_->state()[3], -max_vel_theta_, max_vel_theta_); + // robot::log_info("%s", ss.str().c_str()); +} + +void mkt_algorithm::diff::PredictiveTrajectory::applyDistanceSpeedScaling( + const robot_nav_2d_msgs::Path2D &plan, + const robot_nav_2d_msgs::Twist2D &velocity, + robot_nav_2d_msgs::Twist2D &drive_cmd, + const double &sign_x, + const double &dt) +{ + double s = plan.poses.empty() + ? min_journey_squared_ + : journey(plan.poses, 0, plan.poses.size() - 1); + double S_th = 0.1 + max_path_distance_ + fabs(velocity.x) * lookahead_time_; + double S_final = std::min(S_th * 0.2, 0.1 + max_path_distance_); + + double max_speed = fabs(drive_cmd.x); + double target_speed = max_speed; + if (s < S_th) + { + double r = std::clamp(s / S_th, 0.0, 1.0); + double cosine_factor = 0.5 * (1.0 + std::cos(M_PI * (1.0 - r))); + target_speed = max_speed * cosine_factor; + } + double v_limted = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; + double v_min = std::min(v_limted, min_speed_xy_); + double reduce_speed = std::min(max_speed, v_min); + if (s < S_final) + { + double r = std::clamp(s / S_final, 0.0, 1.0); + double cosine_factor = 0.5 * (1.0 + std::cos(M_PI * (1.0 - r))); + reduce_speed = (reduce_speed - min_approach_linear_velocity_) * cosine_factor + min_approach_linear_velocity_; + reduce_speed = std::max(reduce_speed, min_approach_linear_velocity_); + } + target_speed = std::max(target_speed, reduce_speed); + + double v_desired = std::copysign(target_speed, sign_x); + double max_acc_vel = velocity.x + fabs(acc_lim_x_) * dt; + double min_acc_vel = velocity.x - fabs(acc_lim_x_) * dt; + double v_samp = std::clamp(v_desired, min_acc_vel, max_acc_vel); + + double max_speed_to_stop = std::sqrt(2.0 * fabs(decel_lim_x_) * std::max(0.0, s)); + v_samp = std::copysign(std::min(max_speed_to_stop, fabs(v_samp)), sign_x); + if (sign_x > 0.0) + drive_cmd.x = std::clamp(v_samp, min_approach_linear_velocity_, max_speed); + else + drive_cmd.x = std::clamp(v_samp, -max_speed, -min_approach_linear_velocity_); +} + +bool mkt_algorithm::diff::PredictiveTrajectory::shouldRotateToPath( + const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, + robot_nav_2d_msgs::Twist2D velocity, double &angle_to_path, const double &sign_x) +{ + + const bool is_stopped = stopped(velocity, max_vel_theta_ + rot_stopped_velocity_ + 0.01, trans_stopped_velocity_ + 0.01); + // const double straight_threshold = std::max(0.05, 2.0 * (costmap_robot_ ? costmap_robot_->getCostmap()->getResolution() : 0.05)); + // const double max_kappa = calculateMaxKappa(global_plan); + // const bool curvature = max_kappa > straight_threshold; + double path_angle = std::atan2(carrot_pose.pose.y, carrot_pose.pose.x); + if(is_stopped && global_plan.poses.size() >= 4 && + journey(global_plan.poses, 0, global_plan.poses.size() - 1) >= 0.7 * min_lookahead_dist_) + { + const auto& p1 = global_plan.poses[2]; + for(int i = 3; i < global_plan.poses.size(); i++) + { + const auto& p = global_plan.poses[i]; + const auto& dx = p.pose.x - p1.pose.x; + const auto& dy = p.pose.y - p1.pose.y; + if(std::hypot(dx, dy) > costmap_robot_->getCostmap()->getResolution()) + { + if(fabs(dx) < 1e-9 && fabs(dy) < 1e-9) + continue; + path_angle = std::atan2(dy, dx); + break; + } + } + } + + // Whether we should rotate robot to rough path heading + // if(sign_x < 0.0) + // path_angle += std::copysign(M_PI, path_angle) * (-1.0); + // angle_to_path = path_angle; + angle_to_path = sign_x < 0.0 ? angles::normalize_angle(M_PI + path_angle) : path_angle; + double heading_linear = sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + // The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785) + double heading_rotate = rotate_to_heading_min_angle_; + + heading_rotate = is_stopped + ? rotate_to_heading_min_angle_ + heading_linear + : std::clamp(heading_rotate + heading_linear, angle_threshold_ + rotate_to_heading_min_angle_, M_PI_2); + + // bool result = use_rotate_to_heading_ && + // (is_stopped || sign(angle_to_path) * sign_x < 0 ) && fabs(angle_to_path) > heading_rotate; + + bool result = use_rotate_to_heading_ && fabs(angle_to_path) > heading_rotate; +#ifdef BUILD_WITH_ROS + if (result) + ROS_WARN_THROTTLE(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x); +#else + if (result) + robot::log_info_throttle(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x); +#endif + return result; +} + +void mkt_algorithm::diff::PredictiveTrajectory::rotateToHeading( + const double &angle_to_path, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt) +{ + const double theta_direction = angle_to_path > 0.0 ? 1.0 : -1.0; + double ang_diff = angle_to_path; + double max_vel_theta = traj_ ? fabs(traj_->getTwistAngular(true).z) : 0.3; + double min_vel_theta = min_vel_theta_; + + double angular_decel_zone = 0.3; // rad - khoảng cách bắt đầu giảm tốc + nh_priv_.param("angular_decel_zone", angular_decel_zone, 0.5); + angular_decel_zone += std::clamp( + fabs(max_vel_theta) + (M_PI_2 - fabs(atan2(min_path_distance_, max_path_distance_))), 0.4, M_PI_2); + double zone_begin = std::max(angular_decel_zone * 0.2, 0.2); + double cosine_begin_factor = 0.5 * (1.0 + cos(M_PI * (1.0 - fabs(ang_diff) / zone_begin))); + + double reduce_vel_theta = std::min(max_vel_theta, 0.25 + min_vel_theta); + reduce_vel_theta = fabs(ang_diff) > zone_begin ? reduce_vel_theta : (reduce_vel_theta - min_vel_theta) * cosine_begin_factor + min_vel_theta_; + + // === ANGULAR DECELERATION ZONE === + double target_angular_speed = max_vel_theta; + if (fabs(ang_diff) < angular_decel_zone) + { + double cosine_factor = 0.5 * (1.0 + cos(M_PI * (1.0 - fabs(ang_diff) / angular_decel_zone))); + double cosine_speed = max_vel_theta * cosine_factor; + + // Choose deceleration profile + target_angular_speed = cosine_speed; // Smoothest option + + // Ensure minimum speed to avoid stalling + target_angular_speed = std::max(target_angular_speed, reduce_vel_theta); + } + // Apply direction + double v_theta_desired = std::copysign(target_angular_speed, ang_diff); + + // === STOPPING CONSTRAINT === + double max_speed_to_stop = sqrt(2.0 * fabs(decel_lim_theta_) * fabs(ang_diff)); + + double v_theta_samp = std::copysign( + std::min(max_speed_to_stop, fabs(v_theta_desired)), ang_diff); + + // === ACCELERATION LIMITS === + double max_acc_vel = fabs(acc_lim_theta_) * dt; + double domega = std::clamp(v_theta_samp - velocity.theta, -max_acc_vel, max_acc_vel); + + // === FINAL LIMITS === + cmd_vel.x = 0.0; + cmd_vel.y = 0.0; + cmd_vel.theta = velocity.theta + domega; + // robot::log_info("cmd_vel.theta: %f, velocity.theta: %f, domega: %f, max_acc_vel: %f, v_theta_samp: %f", cmd_vel.theta, velocity.theta, domega, max_acc_vel, v_theta_samp); +} + +bool mkt_algorithm::diff::PredictiveTrajectory::shouldAlignToFinalHeading( + const robot_nav_2d_msgs::Path2D &trajectory, + const robot_nav_2d_msgs::Pose2DStamped &goal, + const robot_nav_2d_msgs::Twist2D &velocity, + double &xy_error, + double &heading_error, + const double &sign_x) +{ + if (!use_final_heading_alignment_) + return false; + + if (trajectory.poses.empty()) + return false; + + // Calculate distance to goal (last point in trajectory is closest to goal in robot frame) + const auto &last_pose = trajectory.poses.back().pose; + xy_error = std::hypot(last_pose.x, last_pose.y); + + // Transform goal heading to robot frame + // In robot frame, robot heading is 0, so heading_error = goal_heading_in_robot_frame + heading_error = 0.0; + if(trajectory.poses.size() >= 2) + { + const auto& p1 = trajectory.poses[trajectory.poses.size() - 1].pose; + for(int i = trajectory.poses.size() - 2; i >= 0; i--) + { + const auto& p = trajectory.poses[i].pose; + const auto& dx = sign_x < 0.0 ? p1.x - p.x : p.x - p1.x; + const auto& dy = sign_x < 0.0 ? p1.y - p.y : p.y - p1.y; + if(std::hypot(dx, dy) >= costmap_robot_->getCostmap()->getResolution()) + { + heading_error = angles::normalize_angle(std::atan2(dy, dx)); + break; + } + } + } + + // Check if we're close enough to goal position to start final heading alignment + double distance_threshold = final_heading_xy_tolerance_; + + // Dynamic threshold: increase when moving fast to allow smooth transition + double velocity_factor = std::max(0.0, std::fabs(velocity.x) * 0.5); + distance_threshold += velocity_factor; + + bool near_goal = xy_error < distance_threshold; + bool heading_not_reached = std::fabs(heading_error) > final_heading_angle_tolerance_; + + return near_goal && heading_not_reached; +} + +void mkt_algorithm::diff::PredictiveTrajectory::alignToFinalHeading( + const double &xy_error, + const double &heading_error, + const robot_nav_2d_msgs::Twist2D &velocity, + const double &sign_x, + const double &dt, + robot_nav_2d_msgs::Twist2D &cmd_vel) +{ + // ============================================================ + // Arc Motion Controller for Final Heading Alignment + // ============================================================ + // + // Strategy: + // 1. Linear velocity: proportional to xy_error, decreasing as we approach goal + // 2. Angular velocity: proportional to heading_error with feedforward + // 3. Coordinate both to arrive at goal with correct heading + // + // Key insight: For arc motion, the relationship is: + // arc_length = radius * angle + // v = omega * radius + // + // We want to cover xy_error distance while rotating heading_error angle + // So ideal radius = xy_error / |heading_error| (when heading_error != 0) + // ============================================================ + + const double abs_heading_error = std::fabs(heading_error); + const double heading_sign = (heading_error > 0) ? 1.0 : -1.0; + + // --- Linear velocity calculation --- + // Base velocity proportional to distance, with minimum for smooth motion + double v_base = std::sqrt(2.0 * std::fabs(decel_lim_x_) * xy_error); + double v_limted = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; + double v_min = std::min(v_limted, min_speed_xy_); + v_base = std::max(v_base, final_heading_min_velocity_); + v_base = std::min(v_base, v_min); + + // Scale down when heading error is large (prioritize rotation) + double heading_scale = 1.0; + if (abs_heading_error > 0.1) // ~5.7 degrees + { + // Reduce linear velocity when heading error is significant + heading_scale = std::clamp(0.3 / abs_heading_error, 0.3, 1.0); + } + + double v_target = v_base * heading_scale * sign_x; + + // --- Angular velocity calculation --- + double omega_target = 0.0; + + if (abs_heading_error > final_heading_angle_tolerance_) + { + // Method 1: Proportional control + double omega_p = 0.0; + pid(heading_error, + near_goal_heading_integral_, + near_goal_heading_last_error_, + dt, + final_heading_kp_angular_, + final_heading_ki_angular_, + final_heading_kd_angular_, + omega_p); + + // Method 2: Arc-based feedforward (coordinate linear and angular motion) + double omega_arc = 0.0; + if (xy_error > 0.01 && abs_heading_error > 0.01) + { + // Ideal omega to complete rotation while traveling remaining distance + // omega = v * heading_error / xy_error + omega_arc = std::fabs(v_target - velocity.x) * heading_error / xy_error; + } + + // Blend proportional and arc-based control + // Use more arc-based when far, more proportional when close + double blend_factor = std::clamp(xy_error / final_heading_xy_tolerance_, 0.0, 1.0); + omega_target = blend_factor * omega_arc + (1.0 - blend_factor) * omega_p; + + // Reduce angular speed as heading error approaches zero + double heading_scale = std::clamp( + abs_heading_error / std::max(final_heading_angle_tolerance_, 1e-3), + 0.0, 1.0); + heading_scale = heading_scale * heading_scale; // smoother near zero + omega_target *= heading_scale; + + // Ensure minimum angular velocity for responsiveness + double omega_min = min_vel_theta_; + if (std::fabs(omega_target) < omega_min && + abs_heading_error > final_heading_angle_tolerance_ * 3.0) + { + omega_target = heading_sign * omega_min; + } + } + + // --- Apply acceleration limits --- + // Linear + double v_current = velocity.x; + double dv_max = acc_lim_x_ * dt; + double dv = std::clamp(v_target - v_current, -dv_max, dv_max); + cmd_vel.x = v_current + dv; + + // Angular + double omega_current = velocity.theta; + double domega_max = acc_lim_theta_ * dt; + double domega = std::clamp(omega_target - omega_current, -domega_max, domega_max); + cmd_vel.theta = omega_current + domega; + + // --- Apply velocity limits --- + cmd_vel.x = std::clamp(cmd_vel.x, -v_min, v_min); + cmd_vel.theta = std::clamp(cmd_vel.theta, -max_vel_theta_, max_vel_theta_); + + // --- Safety: ensure we can stop --- + double max_v_to_stop = std::sqrt(2.0 * std::fabs(decel_lim_x_) * xy_error); + if (std::fabs(cmd_vel.x) > max_v_to_stop) + { + cmd_vel.x = std::copysign(max_v_to_stop, cmd_vel.x); + } + + cmd_vel.y = 0.0; + +#ifdef BUILD_WITH_ROS + ROS_DEBUG_THROTTLE(0.2, "[FinalHeading] xy=%.3f, heading=%.3f, v=%.3f, omega=%.3f", + xy_error, heading_error, cmd_vel.x, cmd_vel.theta); +#endif +} + +void mkt_algorithm::diff::PredictiveTrajectory::pid( + const double &error, double &integral, double &last_error, const double &dt, const double &kp, const double &ki, const double &kd, double &output) +{ + if (!near_goal_heading_was_active_) + { + integral = 0.0; + last_error = error; + near_goal_heading_was_active_ = true; + } + const double dt_safe = std::max(dt, 1e-6); + double w_p = kp * error; + integral += error * dt_safe; + const double integral_cap = (std::fabs(ki) > 1e-9)? (2.0 / ki) : 1e6; + integral = std::clamp(integral, -integral_cap, integral_cap); + double w_i = ki * integral; + double w_d = kd * (error - last_error) / dt_safe; + last_error = error; + output = w_p + w_i + w_d; +} + +double mkt_algorithm::diff::PredictiveTrajectory::getLookAheadDistance(const robot_nav_2d_msgs::Twist2D &velocity) +{ + // If using velocity-scaled look ahead distances, find and clamp the dist + // Else, use the static look ahead distance + double lookahead_dist = lookahead_dist_; + if (use_velocity_scaled_lookahead_dist_) + { + lookahead_dist = fabs(velocity.x) * lookahead_time_; + lookahead_dist = std::clamp(lookahead_dist, min_lookahead_dist_, max_lookahead_dist_); + } + return lookahead_dist; +} + +std::vector::iterator +mkt_algorithm::diff::PredictiveTrajectory::getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan) +{ + if (global_plan.poses.empty()) + throw robot_nav_core2::PlannerTFException("The global plan passed to the local planner is empty."); + + if (global_plan.poses.size() < 2) + return std::prev(global_plan.poses.end()); + + unsigned int goal_index = (unsigned)global_plan.poses.size() - 1; + + // Góc đầu và ngưỡng gãy (fixed) + const auto &p0 = global_plan.poses[0].pose; + const auto &p1 = global_plan.poses[1].pose; + double start_angle = atan2(p1.y - p0.y, p1.x - p0.x); + double turn_threshold = M_PI_2 * 0.6; // ~54deg, chỉnh theo nhu cầu + + // Dừng nếu gãy góc + for (unsigned int i = 1; i < global_plan.poses.size(); ++i) + { + const auto &a = global_plan.poses[i - 1].pose; + const auto &b = global_plan.poses[i].pose; + double current_angle = atan2(b.y - a.y, b.x - a.x); + double delta = angles::normalize_angle(current_angle - start_angle); + goal_index = i; + if (fabs(delta) >= turn_threshold) + break; + } + // Chọn điểm lookahead theo khoảng cách + auto goal_pose_it = std::find_if( + global_plan.poses.begin(), global_plan.poses.begin() + goal_index, + [&](const auto &ps) { + return std::hypot(ps.pose.x, ps.pose.y) >= lookahead_dist; + }); + + if (goal_pose_it == global_plan.poses.end()) + goal_pose_it = std::prev(global_plan.poses.end()); + + return goal_pose_it; +} + +bool mkt_algorithm::diff::PredictiveTrajectory::pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose, robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot) +{ + if (global_plan.poses.empty()) + return false; + if (tf == nullptr) + return false; + try + { + // let's get the pose of the robot in the frame of the plan + robot_nav_2d_msgs::Pose2DStamped robot; + if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot)) + { + throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into global plan's frame"); + } + + double dist_thresh_sq = dist_behind_robot * dist_behind_robot; + + // iterate plan until a pose close the robot is found + std::vector::iterator it = global_plan.poses.begin(); + std::vector::iterator erase_end = it; + while (it != global_plan.poses.end()) + { + double dx = robot.pose.x - it->pose.x; + double dy = robot.pose.y - it->pose.y; + double dist_sq = dx * dx + dy * dy; + if (dist_sq < dist_thresh_sq) + { + erase_end = it; + break; + } + ++it; + } + if (erase_end == global_plan.poses.end()) + return false; + + if (erase_end != global_plan.poses.begin()) + global_plan.poses.erase(global_plan.poses.begin(), erase_end); + } + catch (const tf3::TransformException &ex) + { + robot::log_debug("[%s:%d]\n Cannot prune path since no transform is available: %s\n", __FILE__, __LINE__, ex.what()); + return false; + } + return true; +} + +double mkt_algorithm::diff::PredictiveTrajectory::calculateMaxKappa(const robot_nav_2d_msgs::Path2D &path, const double preview_distance) +{ + double traveled = 0.0; + double max_kappa = 0.0; + for (size_t i = 1; i + 1 < path.poses.size(); ++i) + { + const auto &p0 = path.poses[i - 1].pose; + const auto &p1 = path.poses[i].pose; + const auto &p2 = path.poses[i + 1].pose; + + const double a = std::hypot(p1.x - p0.x, p1.y - p0.y); + const double b = std::hypot(p2.x - p1.x, p2.y - p1.y); + const double c = std::hypot(p2.x - p0.x, p2.y - p0.y); + traveled += a; + + if (a > 1e-6 && b > 1e-6 && c > 1e-6) + { + const double cross = (p1.x - p0.x) * (p2.y - p0.y) - (p1.y - p0.y) * (p2.x - p0.x); + const double area2 = std::fabs(cross); // 2 * area + const double kappa = 2.0 * area2 / (a * b * c); + max_kappa = std::max(max_kappa, std::fabs(kappa)); + } + + if (traveled >= preview_distance) + break; + } + return max_kappa; +} + +double mkt_algorithm::diff::PredictiveTrajectory::adjustSpeedWithHermiteTrajectory( + const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Path2D &trajectory, + double v_target, + const double &sign_x) +{ + if(trajectory.poses.size() < 2) + return min_approach_linear_velocity_ * sign_x; + + double preview_distance = std::clamp(std::fabs(velocity.x) * lookahead_time_, min_lookahead_dist_, max_lookahead_dist_); + + double max_kappa = calculateMaxKappa(trajectory, preview_distance); + double v_limit = fabs(v_target); + double v_min = std::min(fabs(v_target), min_speed_xy_); + double journey_distance = journey(trajectory.poses, 0, trajectory.poses.size() - 1); + + if (journey_distance < min_journey_squared_) + { + v_limit = std::clamp(sqrt(2.0 * fabs(decel_lim_x_) * journey_distance), min_approach_linear_velocity_, v_min) * sign_x; + } + + if (max_kappa > 1e-6 && max_lateral_accel_ > 1e-6) + { + const double v_curve = std::sqrt(max_lateral_accel_ / max_kappa); + v_limit = std::min(v_limit, v_curve); + } + + if(trajectory.poses.size() > 2 && fabs(trajectory.poses.front().pose.theta) >= angle_threshold_) + v_limit = v_min * sign_x; + + + if (fabs(decel_lim_x_) > 1e-6) + { + const double remaining = journey(trajectory.poses, 0, trajectory.poses.size() - 1); + const double v_stop = std::sqrt(2.0 * fabs(decel_lim_x_) * std::max(0.0, remaining)); + v_limit = std::min(v_limit, v_stop); + } + v_limit = std::min(v_limit, fabs(v_target)); + + return std::copysign(v_limit, sign_x); +} + +robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateTrajectory( + const robot_nav_2d_msgs::Path2D &path, + const robot_nav_2d_msgs::Twist2D &drive_target, + const robot_nav_2d_msgs::Twist2D &velocity, + const double &sign_x, + robot_nav_2d_msgs::Twist2D &drive_cmd) +{ + if (path.poses.empty()) + { + drive_cmd.x = 0.0; + drive_cmd.theta = 0.0; + return robot_nav_2d_msgs::Path2D(); + } + + double max_kappa = calculateMaxKappa(path); + const double straight_threshold = std::max(0.05, 2.0 * (costmap_robot_ ? costmap_robot_->getCostmap()->getResolution() : 0.05)); + drive_cmd.x = this->adjustSpeedWithHermiteTrajectory(velocity, path, drive_target.x, sign_x); + drive_cmd.theta = max_vel_theta_; + + if (max_kappa <= straight_threshold && fabs(path.poses.back().pose.x) < min_lookahead_dist_) // nếu đường thẳng + { + if(fabs(path.poses.front().pose.y) <= 0.03 && fabs(path.poses.back().pose.x) < min_lookahead_dist_ ) + { + return generateParallelPath(path, sign_x); + } + return generateHermiteTrajectory(path, sign_x); + } + else // nếu đường cong + { + double v_limted = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; + double v_min = std::min(v_limted, v_min); + if(fabs(drive_cmd.x) < v_min) + drive_cmd.x = std::copysign(v_min, sign_x); + return generateHermiteQuadraticTrajectory(path, sign_x); + } +} + +robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateParallelPath( + const robot_nav_2d_msgs::Path2D &path, const double &sign_x) +{ + robot_nav_2d_msgs::Path2D parallel_path; + parallel_path.header = path.header; + int N = path.poses.size(); + if (N < 2) return parallel_path; + + double offset_y = path.poses.front().pose.y; + + parallel_path.poses.resize(N); + for (int i = 0; i < N; ++i) + { + const auto& p = path.poses[i].pose; + + double dx, dy; + if (i == 0) { + dx = path.poses[i+1].pose.x - p.x; + dy = path.poses[i+1].pose.y - p.y; + } else if (i == N-1) { + dx = p.x - path.poses[i-1].pose.x; + dy = p.y - path.poses[i-1].pose.y; + } else { + dx = path.poses[i+1].pose.x - path.poses[i-1].pose.x; + dy = path.poses[i+1].pose.y - path.poses[i-1].pose.y; + } + if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) + continue; + double theta = atan2(dy, dx); + double x_off = p.x - offset_y * sin(theta)*sign_x; + double y_off = p.y - offset_y * cos(theta)*sign_x; + + parallel_path.poses[i].header = path.poses[i].header; + parallel_path.poses[i].pose.x = x_off; + parallel_path.poses[i].pose.y = y_off; + parallel_path.poses[i].pose.theta = sign_x < 0 ? angles::normalize_angle(theta + M_PI) : theta; + } + return parallel_path; +} + + + +robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateHermiteTrajectory( + const robot_nav_2d_msgs::Path2D &path, const double &sign_x) +{ + robot_nav_2d_msgs::Path2D hermite_trajectory; + hermite_trajectory.poses.clear(); + hermite_trajectory.header = path.header; + + if (path.poses.empty()) + return hermite_trajectory; + + const auto &goal = path.poses.back(); + if (hermite_trajectory.header.frame_id.empty()) + hermite_trajectory.header.frame_id = goal.header.frame_id; + if (hermite_trajectory.header.stamp.isZero()) + hermite_trajectory.header.stamp = goal.header.stamp; + + const double x = goal.pose.x; + const double y = goal.pose.y; + double theta = goal.pose.theta; + const double L = std::hypot(x, y); + if (L < 1e-6) { + robot_nav_2d_msgs::Pose2DStamped pose_stamped; + pose_stamped.pose.x = x; + pose_stamped.pose.y = y; + pose_stamped.pose.theta = theta; + pose_stamped.header.stamp = hermite_trajectory.header.stamp; + pose_stamped.header.frame_id = hermite_trajectory.header.frame_id; + hermite_trajectory.poses.push_back(pose_stamped); + return hermite_trajectory; + } + + int samples = L/costmap_robot_->getCostmap()->getResolution(); + if (samples < 1) { + samples = 1; + } + hermite_trajectory.poses.reserve(samples + 1); + const double Lnegative = sign_x < 0 ? -L : L; + for (int i = 0; i <= samples; ++i) { + double t = static_cast(i) / samples; + double t2 = t * t; + double t3 = t2 * t; + + double h00 = 2 * t3 - 3 * t2 + 1; + double h10 = t3 - 2 * t2 + t; + double h01 = -2 * t3 + 3 * t2; + double h11 = t3 - t2; + + // Hermite interpolation + double px = h10 * Lnegative + h01 * x + h11 * Lnegative * std::cos(theta); + double py = h01 * y + h11 * Lnegative * std::sin(theta); + + // First derivatives for heading + double dh00 = 6 * t2 - 6 * t; + double dh10 = 3 * t2 - 4 * t + 1; + double dh01 = -6 * t2 + 6 * t; + double dh11 = 3 * t2 - 2 * t; + + double dx = dh10 * Lnegative + dh01 * x + dh11 * Lnegative * std::cos(theta); + double dy = dh01 * y + dh11 * Lnegative * std::sin(theta); + + if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) + continue; + double heading = std::atan2(dy, dx); + + robot_nav_2d_msgs::Pose2DStamped pose_out; + pose_out.pose.x = px; + pose_out.pose.y = py; + pose_out.pose.theta = sign_x < 0 ? angles::normalize_angle(heading + M_PI) : heading; + pose_out.header.stamp = hermite_trajectory.header.stamp; + pose_out.header.frame_id = hermite_trajectory.header.frame_id; + hermite_trajectory.poses.push_back(pose_out); + } + return hermite_trajectory; +} + +robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateHermiteQuadraticTrajectory( + const robot_nav_2d_msgs::Path2D &path, const double &sign_x) +{ + robot_nav_2d_msgs::Path2D trajectory; + trajectory.poses.clear(); + trajectory.header = path.header; + if (path.poses.empty()) + return trajectory; + + const auto &goal = path.poses.back(); + if (trajectory.header.frame_id.empty()) + trajectory.header.frame_id = goal.header.frame_id; + if (trajectory.header.stamp.isZero()) + trajectory.header.stamp = goal.header.stamp; + + const double x = goal.pose.x; + const double y = goal.pose.y; + const double theta = sign_x < 0 ? angles::normalize_angle(goal.pose.theta + M_PI) : goal.pose.theta; + const double L = std::hypot(x, y); + if (L < 1e-6) + { + robot_nav_2d_msgs::Pose2DStamped pose_stamped; + pose_stamped.pose.x = 0.0; + pose_stamped.pose.y = 0.0; + pose_stamped.pose.theta = 0.0; + pose_stamped.header.stamp = trajectory.header.stamp; + pose_stamped.header.frame_id = trajectory.header.frame_id; + trajectory.poses.push_back(pose_stamped); + return trajectory; + } + + int samples = L/costmap_robot_->getCostmap()->getResolution(); + if (samples < 1) { + samples = 1; + } + trajectory.poses.reserve(samples + 1); + + // Quadratic Hermite with end tangent aligned to carrot_pose heading: + // p(0) = 0, p(1) = goal, p'(1) = v1 + const double v1x = L * std::cos(theta); + const double v1y = L * std::sin(theta); + const double ax = v1x - x; + const double ay = v1y - y; + const double bx = 2.0 * x - v1x; + const double by = 2.0 * y - v1y; + + trajectory.poses.reserve(samples + 1); + for (int i = 0; i <= samples; ++i) + { + double t = static_cast(i) / samples; + double t2 = t * t; + + double px = ax * t2 + bx * t; + double py = ay * t2 + by * t; + + double dx = 2.0 * ax * t + bx; + double dy = 2.0 * ay * t + by; + if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) + continue; + double heading = std::atan2(dy, dx); + + robot_nav_2d_msgs::Pose2DStamped pose_out; + pose_out.pose.x = px; + pose_out.pose.y = py; + pose_out.pose.theta = sign_x < 0 ? angles::normalize_angle(heading + M_PI) : heading; + pose_out.header.stamp = trajectory.header.stamp; + pose_out.header.frame_id = trajectory.header.frame_id; + trajectory.poses.push_back(pose_out); + } + + return trajectory; +} + +bool mkt_algorithm::diff::PredictiveTrajectory::transformGlobalPlan( + TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &robot_base_frame, double max_plan_length, + robot_nav_2d_msgs::Path2D &transformed_plan) +{ + // this method is a slightly modified version of base_local_planner/goal_functions.h + transformed_plan.poses.clear(); + transformed_plan.header.stamp = pose.header.stamp; + transformed_plan.header.frame_id = robot_base_frame; + + if (global_plan.poses.empty()) + return false; + + if (tf == nullptr) + return false; + + if (costmap == nullptr || costmap->getCostmap() == nullptr) + return false; + + try + { + if (global_plan.poses.empty()) + { + robot::log_error("[%s:%d]\n Received plan with zero length", __FILE__, __LINE__); + return false; + } + + // let's get the pose of the robot in the frame of the plan + robot_nav_2d_msgs::Pose2DStamped robot_pose; + if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot_pose)) + { + throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into global plan's frame"); + } + + // we'll discard points on the plan that are outside the local costmap + double dist_threshold = std::max(costmap->getCostmap()->getSizeInCellsX() * costmap->getCostmap()->getResolution() / 2.0, + costmap->getCostmap()->getSizeInCellsY() * costmap->getCostmap()->getResolution() / 2.0); + + dist_threshold *= 0.85; // just consider 85% of the costmap size to better incorporate point obstacle that are + double sq_dist_threshold = dist_threshold * dist_threshold; + // located on the border of the local costmap + + int i = 0; + double sq_dist = std::numeric_limits::infinity(); + + // we need to loop to a point on the plan that is within a certain distance of the robot + bool robot_reached = false; + for (int j = 0; j < (int)global_plan.poses.size(); ++j) + { + double x_diff = robot_pose.pose.x - global_plan.poses[j].pose.x; + double y_diff = robot_pose.pose.y - global_plan.poses[j].pose.y; + double new_sq_dist = x_diff * x_diff + y_diff * y_diff; + if (robot_reached && new_sq_dist > sq_dist_threshold) + { + break; + } // force stop if we have reached the costmap border + + if (new_sq_dist < sq_dist) // find closest distance + { + sq_dist = new_sq_dist; + i = j; + if (sq_dist < costmap->getCostmap()->getResolution()) // 5 cm to the robot; take the immediate local minima; if it's not the global + robot_reached = true; // minima, probably means that there's a loop in the path, and so we prefer this + } + } + + double plan_length = 0; // check cumulative Euclidean distance along the plan + double x_direction_saved = 0.0; + // now we'll transform until points are outside of our distance threshold + while (i < (int)global_plan.poses.size() && sq_dist <= sq_dist_threshold && + (max_plan_length <= 0 || plan_length <= max_plan_length)) + { + robot_nav_2d_msgs::Pose2DStamped stamped_pose; + stamped_pose.pose = global_plan.poses[i].pose; + stamped_pose.header.frame_id = global_plan.header.frame_id; + + robot_nav_2d_msgs::Pose2DStamped newer_pose; + if (!robot_nav_2d_utils::transformPose(tf, robot_base_frame, stamped_pose, newer_pose)) + { + ++i; + continue; + } + transformed_plan.poses.push_back(newer_pose); + + double x_diff = robot_pose.pose.x - global_plan.poses[i].pose.x; + double y_diff = robot_pose.pose.y - global_plan.poses[i].pose.y; + sq_dist = x_diff * x_diff + y_diff * y_diff; + + // Calculate distance to previous pose + if (i > 0 && max_plan_length > 0) + { + robot_geometry_msgs::Pose2D p1 = global_plan.poses[i].pose; + robot_geometry_msgs::Pose2D p2 = global_plan.poses[i - 1].pose; + plan_length += std::sqrt(std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2)); + if (fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9) + { + const double egde_angle = atan2(p1.y - p2.y, p1.x - p2.x); + const double target_direction = cos(fabs(egde_angle - p1.theta)); + if (target_direction * x_direction_saved < 0.0) + { + plan_length = 0; + } + x_direction_saved = target_direction; + } + } + ++i; + } + } + catch (tf3::LookupException &ex) + { + robot::log_error("[%s:%d]\n No Transform available Error: %s\n", __FILE__, __LINE__, ex.what()); + return false; + } + catch (tf3::ConnectivityException &ex) + { + robot::log_error("[%s:%d]\n Connectivity Error: %s\n", __FILE__, __LINE__, ex.what()); + return false; + } + catch (tf3::ExtrapolationException &ex) + { + robot::log_error("[%s:%d]\n Extrapolation Error: %s\n", __FILE__, __LINE__, ex.what()); + if (global_plan.poses.size() > 0) + robot::log_error("[%s:%d]\n Robot Frame: %s Plan Frame size %d: %s\n", __FILE__, __LINE__, robot_base_frame.c_str(), (unsigned int)global_plan.poses.size(), global_plan.header.frame_id.c_str()); + + return false; + } + return true; +} + +void mkt_algorithm::diff::PredictiveTrajectory::moveWithAccLimits( + const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Twist2D &cmd_vel, robot_nav_2d_msgs::Twist2D &cmd_vel_result, const double &dt) +{ + // --- X axis --- + double min_vel_x = traj_ ? min_vel_x_ : fabs(traj_->getTwistLinear(false).x); + double max_vel_x = traj_ ? max_vel_x_ : fabs(traj_->getTwistLinear(true).x); + + double vx = cmd_vel.x > 0.0 ? std::min(max_vel_x, std::max(min_vel_x, cmd_vel.x)) : std::max(-max_vel_x, std::min(-min_vel_x, cmd_vel.x)); + + double max_acc_vx = velocity.x + fabs(acc_lim_x_) * dt; + double min_acc_vx = velocity.x - fabs(decel_lim_x_) * dt; + vx = std::clamp(vx, min_acc_vx, max_acc_vx); + + // --- Y axis --- + double min_vel_y = traj_ ? min_vel_y_ : fabs(traj_->getTwistLinear(false).y); + double max_vel_y = traj_ ? max_vel_y_ : fabs(traj_->getTwistLinear(true).y); + double vy = cmd_vel.y > 0.0 ? std::min(max_vel_y, std::max(min_vel_y, cmd_vel.y)) : std::max(-max_vel_y, std::min(-min_vel_y, cmd_vel.y)); + + double max_acc_vy = velocity.y + fabs(acc_lim_y_) * dt; + double min_acc_vy = velocity.y - fabs(decel_lim_y_) * dt; + vy = std::clamp(vy, min_acc_vy, max_acc_vy); + // --- Assign result --- + cmd_vel_result.x = vx; + cmd_vel_result.y = vy; + // cmd_vel_result.theta = vth; +} + +bool mkt_algorithm::diff::PredictiveTrajectory::stopWithAccLimits(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt) +{ + // slow down with the maximum possible acceleration... we should really use the frequency that we're running at to determine what is feasible + // but we'll use a tenth of a second to be consistent with the implementation of the local planner. + double vx = sign(velocity.x) * std::max(0.0, (fabs(velocity.x) - fabs(decel_lim_x_) * dt)); + double vy = sign(velocity.y) * std::max(0.0, (fabs(velocity.y) - fabs(decel_lim_y_) * dt)); + + double vel_yaw = velocity.theta; + double vth = sign(vel_yaw) * std::max(0.0, (fabs(vel_yaw) - fabs(decel_lim_theta_) * dt)); + + cmd_vel.x = vx; + cmd_vel.y = vy; + cmd_vel.theta = vth; + return true; +} + +std::vector +mkt_algorithm::diff::PredictiveTrajectory::interpolateFootprint(const robot_geometry_msgs::Pose2D &pose, const std::vector &footprint, const double &resolution) +{ + + // Dịch sang tọa độ tuyệt đối + std::vector abs_footprint; + double cos_th = std::cos(pose.theta); + double sin_th = std::sin(pose.theta); + for (auto pt : footprint) + { + pt.x *= 1.2; + pt.y *= 1.2; + robot_geometry_msgs::Point abs_pt; + abs_pt.x = pose.x + pt.x * cos_th - pt.y * sin_th; + abs_pt.y = pose.y + pt.x * sin_th + pt.y * cos_th; + abs_footprint.push_back(abs_pt); + } + + std::vector points; + for (size_t i = 0; i < abs_footprint.size(); ++i) + { + const robot_geometry_msgs::Point &start = abs_footprint[i]; + const robot_geometry_msgs::Point &end = abs_footprint[(i + 1) % abs_footprint.size()]; + + double dx = end.x - start.x; + double dy = end.y - start.y; + double distance = std::hypot(dx, dy); + int steps = std::max(1, static_cast(std::floor(distance / resolution))); + + for (int j = 0; j <= steps; ++j) + { + if (j == steps && i != abs_footprint.size() - 1) + continue; // tránh lặp + double t = static_cast(j) / steps; + robot_geometry_msgs::Point pt; + pt.x = start.x + t * dx; + pt.y = start.y + t * dy; + points.push_back(pt); + } + } + return points; +} + +double mkt_algorithm::diff::PredictiveTrajectory::costAtPose(const double &x, const double &y) +{ + unsigned int mx, my; + unsigned char cost; + if (costmap_robot_->getCostmap()->worldToMap(x, y, mx, my)) + { + cost = costmap_robot_->getCostmap()->getCost(mx, my); + } + return static_cast(cost); +} + +score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::PredictiveTrajectory::create() +{ + return std::make_shared(); +} + BOOST_DLL_ALIAS(mkt_algorithm::diff::PredictiveTrajectory::create, MKTAlgorithmDiffPredictiveTrajectory) \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_rotate_to_goal.cpp b/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_rotate_to_goal.cpp index 51670e9..b8a8f59 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_rotate_to_goal.cpp +++ b/src/Algorithms/Libraries/mkt_algorithm/src/diff/diff_rotate_to_goal.cpp @@ -1,101 +1,101 @@ -#include -#include -#include -#include -#include - - -mkt_algorithm::diff::RotateToGoal::RotateToGoal() - : PredictiveTrajectory() -{ -} - -mkt_algorithm::diff::RotateToGoal::~RotateToGoal() {} - -void mkt_algorithm::diff::RotateToGoal::initialize( - robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) -{ - if (!initialized_) - { - nh_ = robot::NodeHandle(nh, name); - name_ = name; - tf_ = tf; - traj_ = traj; - costmap_robot_ = costmap_robot; - nh_.param("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); - this->getParams(); - - last_actuator_update_ = robot::Time::now(); - x_direction_ = y_direction_ = theta_direction_ = 0; - this->initialized_ = true; - robot::log_info("[%s:%d]\n RotateToGoal Initialized successfully", __FILE__, __LINE__); - } -} - -void mkt_algorithm::diff::RotateToGoal::reset() -{ - robot::log_info("[%s:%d]\n RotateToGoal is reset", __FILE__, __LINE__); - if (initialized_) - { - this->clear(); - x_direction_ = y_direction_ = theta_direction_ = 0; - last_actuator_update_ = robot::Time::now(); - } -} - -bool mkt_algorithm::diff::RotateToGoal::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, - const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, - double &x_direction, double &y_direction, double &theta_direction) -{ - - if (!initialized_) - { - robot::log_error("This planner has not been initialized, please call initialize() before using this planner"); - return false; - } - if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2) - { - robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size()); - return false; - } - if(robot::Time::now() - last_actuator_update_ > robot::Duration(0.5)) - { - last_actuator_update_ = robot::Time::now(); - } - this->getParams(); - frame_id_path_ = global_plan.header.frame_id; - goal_ = goal; - - double angle = angles::shortest_angular_distance(pose.pose.theta, goal_.pose.theta); - x_direction = y_direction = theta_direction = sign(angle); - return true; -} - -mkt_msgs::Trajectory2D mkt_algorithm::diff::RotateToGoal::calculator( - const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - mkt_msgs::Trajectory2D result; - robot_nav_2d_msgs::Twist2D drive_cmd; - result.velocity.x = result.velocity.y = result.velocity.theta = 0.0; - if (!traj_) - return result; - - robot::Time current_time = robot::Time::now(); - const double dt = (current_time - last_actuator_update_).toSec(); - last_actuator_update_ = current_time; - double vel_yaw = velocity.theta; - double ang_diff = angles::shortest_angular_distance(pose.pose.theta, goal_.pose.theta); - rotateToHeading(ang_diff, velocity, drive_cmd, dt); - - drive_cmd.x = 0.0; - drive_cmd.y = 0.0; - result.velocity = drive_cmd; - return result; -} - -score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::RotateToGoal::create() -{ - return std::make_shared(); -} - +#include +#include +#include +#include +#include + + +mkt_algorithm::diff::RotateToGoal::RotateToGoal() + : PredictiveTrajectory() +{ +} + +mkt_algorithm::diff::RotateToGoal::~RotateToGoal() {} + +void mkt_algorithm::diff::RotateToGoal::initialize( + robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) +{ + if (!initialized_) + { + nh_ = robot::NodeHandle(nh, name); + name_ = name; + tf_ = tf; + traj_ = traj; + costmap_robot_ = costmap_robot; + nh_.param("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); + this->getParams(); + + last_actuator_update_ = robot::Time::now(); + x_direction_ = y_direction_ = theta_direction_ = 0; + this->initialized_ = true; + robot::log_info("[%s:%d]\n RotateToGoal Initialized successfully", __FILE__, __LINE__); + } +} + +void mkt_algorithm::diff::RotateToGoal::reset() +{ + robot::log_info("[%s:%d]\n RotateToGoal is reset", __FILE__, __LINE__); + if (initialized_) + { + this->clear(); + x_direction_ = y_direction_ = theta_direction_ = 0; + last_actuator_update_ = robot::Time::now(); + } +} + +bool mkt_algorithm::diff::RotateToGoal::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, + const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, + double &x_direction, double &y_direction, double &theta_direction) +{ + + if (!initialized_) + { + robot::log_error("This planner has not been initialized, please call initialize() before using this planner"); + return false; + } + if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2) + { + robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size()); + return false; + } + if(robot::Time::now() - last_actuator_update_ > robot::Duration(0.5)) + { + last_actuator_update_ = robot::Time::now(); + } + this->getParams(); + frame_id_path_ = global_plan.header.frame_id; + goal_ = goal; + + double angle = angles::shortest_angular_distance(pose.pose.theta, goal_.pose.theta); + x_direction = y_direction = theta_direction = sign(angle); + return true; +} + +mkt_msgs::Trajectory2D mkt_algorithm::diff::RotateToGoal::calculator( + const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + mkt_msgs::Trajectory2D result; + robot_nav_2d_msgs::Twist2D drive_cmd; + result.velocity.x = result.velocity.y = result.velocity.theta = 0.0; + if (!traj_) + return result; + + robot::Time current_time = robot::Time::now(); + const double dt = (current_time - last_actuator_update_).toSec(); + last_actuator_update_ = current_time; + double vel_yaw = velocity.theta; + double ang_diff = angles::shortest_angular_distance(pose.pose.theta, goal_.pose.theta); + rotateToHeading(ang_diff, velocity, drive_cmd, dt); + + drive_cmd.x = 0.0; + drive_cmd.y = 0.0; + result.velocity = drive_cmd; + return result; +} + +score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::RotateToGoal::create() +{ + return std::make_shared(); +} + BOOST_DLL_ALIAS(mkt_algorithm::diff::RotateToGoal::create, MKTAlgorithmDiffRotateToGoal) \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_algorithm/src/diff/hermite_trajectory.svg b/src/Algorithms/Libraries/mkt_algorithm/src/diff/hermite_trajectory.svg index fe475ae..42de1a2 100644 --- a/src/Algorithms/Libraries/mkt_algorithm/src/diff/hermite_trajectory.svg +++ b/src/Algorithms/Libraries/mkt_algorithm/src/diff/hermite_trajectory.svg @@ -1,40 +1,40 @@ - - - - - - - - - - - x - y - O(0,0) - - - - - - - - - - - - - - - - - - - - - - - heading 0 - goal (x,y,theta) - Hermite trajectory - - + + + + + + + + + + + x + y + O(0,0) + + + + + + + + + + + + + + + + + + + + + + + heading 0 + goal (x,y,theta) + Hermite trajectory + + diff --git a/src/Algorithms/Libraries/mkt_msgs/CMakeLists.txt b/src/Algorithms/Libraries/mkt_msgs/CMakeLists.txt index a837f12..fe0dc70 100644 --- a/src/Algorithms/Libraries/mkt_msgs/CMakeLists.txt +++ b/src/Algorithms/Libraries/mkt_msgs/CMakeLists.txt @@ -1,144 +1,144 @@ -cmake_minimum_required(VERSION 3.0.2) -project(mkt_msgs VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building mkt_msgs with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building mkt_msgs with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - - set(PACKAGES_DIR - robot_nav_2d_msgs - geometry_msgs - ) - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED COMPONENTS - robot_nav_2d_msgs - geometry_msgs - ) - - catkin_package( - INCLUDE_DIRS include - # LIBRARIES không cần vì đây là header-only library - CATKIN_DEPENDS robot_nav_2d_msgs geometry_msgs - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ) -endif() - -# Tìm tất cả header files -file(GLOB_RECURSE HEADERS "include/mkt_msgs/*.h") - -# Tạo INTERFACE library (header-only) -add_library(${PROJECT_NAME} INTERFACE) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - # Set include directories - target_include_directories(${PROJECT_NAME} - INTERFACE - $ - $ - ) - - # Link dependencies (header-only, chỉ cần include paths) - target_link_libraries(${PROJECT_NAME} - INTERFACE - ${catkin_LIBRARIES} - ) - -else() - - # Set include directories - target_include_directories(${PROJECT_NAME} - INTERFACE - $ - $ - ) - - # Link dependencies (header-only, chỉ cần include paths) - target_link_libraries(${PROJECT_NAME} - INTERFACE - ${PACKAGES_DIR} - ) - -endif() - -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME} - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - -else() - - install(TARGETS ${PROJECT_NAME} - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME} (Header-Only)") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Headers found:") - foreach(hdr ${HEADERS}) - message(STATUS " - ${hdr}") - endforeach() - message(STATUS "Dependencies: robot_nav_2d_msgs, geometry_msgs") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(mkt_msgs VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building mkt_msgs with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building mkt_msgs with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + set(PACKAGES_DIR + robot_nav_2d_msgs + geometry_msgs + ) + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED COMPONENTS + robot_nav_2d_msgs + geometry_msgs + ) + + catkin_package( + INCLUDE_DIRS include + # LIBRARIES không cần vì đây là header-only library + CATKIN_DEPENDS robot_nav_2d_msgs geometry_msgs + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ) +endif() + +# Tìm tất cả header files +file(GLOB_RECURSE HEADERS "include/mkt_msgs/*.h") + +# Tạo INTERFACE library (header-only) +add_library(${PROJECT_NAME} INTERFACE) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + # Set include directories + target_include_directories(${PROJECT_NAME} + INTERFACE + $ + $ + ) + + # Link dependencies (header-only, chỉ cần include paths) + target_link_libraries(${PROJECT_NAME} + INTERFACE + ${catkin_LIBRARIES} + ) + +else() + + # Set include directories + target_include_directories(${PROJECT_NAME} + INTERFACE + $ + $ + ) + + # Link dependencies (header-only, chỉ cần include paths) + target_link_libraries(${PROJECT_NAME} + INTERFACE + ${PACKAGES_DIR} + ) + +endif() + +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME} + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + +else() + + install(TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME} (Header-Only)") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Headers found:") + foreach(hdr ${HEADERS}) + message(STATUS " - ${hdr}") + endforeach() + message(STATUS "Dependencies: robot_nav_2d_msgs, geometry_msgs") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Libraries/mkt_msgs/include/mkt_msgs/Trajectory2D.h b/src/Algorithms/Libraries/mkt_msgs/include/mkt_msgs/Trajectory2D.h index 84ab6e5..dcd9b07 100644 --- a/src/Algorithms/Libraries/mkt_msgs/include/mkt_msgs/Trajectory2D.h +++ b/src/Algorithms/Libraries/mkt_msgs/include/mkt_msgs/Trajectory2D.h @@ -1,66 +1,66 @@ -// Generated by gencpp from file mkt_msgs/Trajectory2D.msg -// DO NOT EDIT! - -#ifndef MKT_MSGS_MESSAGE_TRAJECTORY2D_H -#define MKT_MSGS_MESSAGE_TRAJECTORY2D_H - -#include -#include -#include -#include -#include -#include - -namespace mkt_msgs -{ - template - struct Trajectory2D_ - { - typedef Trajectory2D_ Type; - - Trajectory2D_() - : velocity(), poses(), time_offsets() - { - } - Trajectory2D_(const ContainerAllocator &_alloc) - : velocity(_alloc), poses(_alloc), time_offsets(_alloc) - { - (void)_alloc; - } - - typedef ::robot_nav_2d_msgs::Twist2D_ _velocity_type; - _velocity_type velocity; - - typedef std::vector::template rebind_alloc> _poses_type; - _poses_type poses; - - typedef std::vector::template rebind_alloc> _time_offsets_type; - _time_offsets_type time_offsets; - - typedef boost::shared_ptr<::mkt_msgs::Trajectory2D_> Ptr; - typedef boost::shared_ptr<::mkt_msgs::Trajectory2D_ const> ConstPtr; - - }; // struct Trajectory2D_ - - typedef ::mkt_msgs::Trajectory2D_> Trajectory2D; - - typedef boost::shared_ptr<::mkt_msgs::Trajectory2D> Trajectory2DPtr; - typedef boost::shared_ptr<::mkt_msgs::Trajectory2D const> Trajectory2DConstPtr; - - template - bool operator==(const ::mkt_msgs::Trajectory2D_ &lhs, const ::mkt_msgs::Trajectory2D_ &rhs) - { - return lhs.velocity == rhs.velocity && - lhs.poses == rhs.poses && - lhs.time_offsets == rhs.time_offsets; - } - - template - bool operator!=(const ::mkt_msgs::Trajectory2D_ &lhs, const ::mkt_msgs::Trajectory2D_ &rhs) - { - return !(lhs == rhs); - } - -} // namespace mkt_msgs - -#endif // MKT_MSGS_MESSAGE_TRAJECTORY2D_H +// Generated by gencpp from file mkt_msgs/Trajectory2D.msg +// DO NOT EDIT! + +#ifndef MKT_MSGS_MESSAGE_TRAJECTORY2D_H +#define MKT_MSGS_MESSAGE_TRAJECTORY2D_H + +#include +#include +#include +#include +#include +#include + +namespace mkt_msgs +{ + template + struct Trajectory2D_ + { + typedef Trajectory2D_ Type; + + Trajectory2D_() + : velocity(), poses(), time_offsets() + { + } + Trajectory2D_(const ContainerAllocator &_alloc) + : velocity(_alloc), poses(_alloc), time_offsets(_alloc) + { + (void)_alloc; + } + + typedef ::robot_nav_2d_msgs::Twist2D_ _velocity_type; + _velocity_type velocity; + + typedef std::vector::template rebind_alloc> _poses_type; + _poses_type poses; + + typedef std::vector::template rebind_alloc> _time_offsets_type; + _time_offsets_type time_offsets; + + typedef boost::shared_ptr<::mkt_msgs::Trajectory2D_> Ptr; + typedef boost::shared_ptr<::mkt_msgs::Trajectory2D_ const> ConstPtr; + + }; // struct Trajectory2D_ + + typedef ::mkt_msgs::Trajectory2D_> Trajectory2D; + + typedef boost::shared_ptr<::mkt_msgs::Trajectory2D> Trajectory2DPtr; + typedef boost::shared_ptr<::mkt_msgs::Trajectory2D const> Trajectory2DConstPtr; + + template + bool operator==(const ::mkt_msgs::Trajectory2D_ &lhs, const ::mkt_msgs::Trajectory2D_ &rhs) + { + return lhs.velocity == rhs.velocity && + lhs.poses == rhs.poses && + lhs.time_offsets == rhs.time_offsets; + } + + template + bool operator!=(const ::mkt_msgs::Trajectory2D_ &lhs, const ::mkt_msgs::Trajectory2D_ &rhs) + { + return !(lhs == rhs); + } + +} // namespace mkt_msgs + +#endif // MKT_MSGS_MESSAGE_TRAJECTORY2D_H diff --git a/src/Algorithms/Libraries/mkt_msgs/package.xml b/src/Algorithms/Libraries/mkt_msgs/package.xml index c1573bf..b168068 100644 --- a/src/Algorithms/Libraries/mkt_msgs/package.xml +++ b/src/Algorithms/Libraries/mkt_msgs/package.xml @@ -1,27 +1,27 @@ - - mkt_msgs - 0.7.10 - - mkt_msgs is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. mkt_msgs - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/mkt_msgs - - catkin - - robot_nav_2d_msgs - geometry_msgs - - robot_nav_2d_msgs - geometry_msgs + + mkt_msgs + 0.7.10 + + mkt_msgs is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. mkt_msgs + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/mkt_msgs + + catkin + + robot_nav_2d_msgs + geometry_msgs + + robot_nav_2d_msgs + geometry_msgs \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_plugins/CMakeLists.txt b/src/Algorithms/Libraries/mkt_plugins/CMakeLists.txt index 8217e36..69dbde6 100644 --- a/src/Algorithms/Libraries/mkt_plugins/CMakeLists.txt +++ b/src/Algorithms/Libraries/mkt_plugins/CMakeLists.txt @@ -1,208 +1,208 @@ -cmake_minimum_required(VERSION 3.0.2) -project(mkt_plugins VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building mkt_plugins with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building mkt_plugins with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -# Find dependencies -find_package(Boost REQUIRED COMPONENTS system) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - - set(PACKAGES_DIR - score_algorithm - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core2 - geometry_msgs - robot_nav_msgs - robot_std_msgs - robot_sensor_msgs - angles - ) - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED COMPONENTS - score_algorithm - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core2 - geometry_msgs - robot_nav_msgs - robot_std_msgs - robot_sensor_msgs - angles - ) - - catkin_package( - INCLUDE_DIRS include - LIBRARIES ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator - CATKIN_DEPENDS score_algorithm robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core2 geometry_msgs robot_nav_msgs robot_std_msgs robot_sensor_msgs angles - DEPENDS Boost - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ) -endif() - -# ======================================================== -# Libraries -# ======================================================== -add_library(${PROJECT_NAME}_goal_checker SHARED - src/goal_checker.cpp - src/simple_goal_checker.cpp - src/equation_line.cpp -) - -add_library(${PROJECT_NAME}_standard_traj_generator SHARED - src/kinematic_parameters.cpp - src/xy_theta_iterator.cpp - src/standard_traj_generator.cpp - src/limited_accel_generator.cpp -) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME}_goal_checker ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - add_dependencies(${PROJECT_NAME}_standard_traj_generator ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - target_include_directories(${PROJECT_NAME}_goal_checker - PUBLIC - $ - $ - ) - - target_include_directories(${PROJECT_NAME}_standard_traj_generator - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME}_goal_checker - PUBLIC ${catkin_LIBRARIES} - PRIVATE Boost::system - ) - - target_link_libraries(${PROJECT_NAME}_standard_traj_generator - PUBLIC ${catkin_LIBRARIES} - PRIVATE Boost::system - ) - -else() - - target_include_directories(${PROJECT_NAME}_goal_checker - PUBLIC - $ - $ - ) - - target_include_directories(${PROJECT_NAME}_standard_traj_generator - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME}_goal_checker - PUBLIC - ${PACKAGES_DIR} - PRIVATE - Boost::system - ) - - target_link_libraries(${PROJECT_NAME}_standard_traj_generator - PUBLIC - ${PACKAGES_DIR} - PRIVATE - Boost::system - ) - - set_target_properties(${PROJECT_NAME}_goal_checker PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - - set_target_properties(${PROJECT_NAME}_standard_traj_generator PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - -endif() - -# ======================================================== -# Install -# ======================================================== -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - -else() - - install(TARGETS ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME}") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Libraries: ${PROJECT_NAME}_goal_checker, ${PROJECT_NAME}_standard_traj_generator") - message(STATUS "Dependencies: score_algorithm, robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core2, geometry_msgs, robot_nav_msgs, robot_std_msgs, robot_sensor_msgs, angles, Boost") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(mkt_plugins VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building mkt_plugins with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building mkt_plugins with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Find dependencies +find_package(Boost REQUIRED COMPONENTS system) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + set(PACKAGES_DIR + score_algorithm + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core2 + geometry_msgs + robot_nav_msgs + robot_std_msgs + robot_sensor_msgs + angles + ) + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED COMPONENTS + score_algorithm + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core2 + geometry_msgs + robot_nav_msgs + robot_std_msgs + robot_sensor_msgs + angles + ) + + catkin_package( + INCLUDE_DIRS include + LIBRARIES ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator + CATKIN_DEPENDS score_algorithm robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core2 geometry_msgs robot_nav_msgs robot_std_msgs robot_sensor_msgs angles + DEPENDS Boost + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) +endif() + +# ======================================================== +# Libraries +# ======================================================== +add_library(${PROJECT_NAME}_goal_checker SHARED + src/goal_checker.cpp + src/simple_goal_checker.cpp + src/equation_line.cpp +) + +add_library(${PROJECT_NAME}_standard_traj_generator SHARED + src/kinematic_parameters.cpp + src/xy_theta_iterator.cpp + src/standard_traj_generator.cpp + src/limited_accel_generator.cpp +) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME}_goal_checker ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + add_dependencies(${PROJECT_NAME}_standard_traj_generator ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + target_include_directories(${PROJECT_NAME}_goal_checker + PUBLIC + $ + $ + ) + + target_include_directories(${PROJECT_NAME}_standard_traj_generator + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME}_goal_checker + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::system + ) + + target_link_libraries(${PROJECT_NAME}_standard_traj_generator + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::system + ) + +else() + + target_include_directories(${PROJECT_NAME}_goal_checker + PUBLIC + $ + $ + ) + + target_include_directories(${PROJECT_NAME}_standard_traj_generator + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME}_goal_checker + PUBLIC + ${PACKAGES_DIR} + PRIVATE + Boost::system + ) + + target_link_libraries(${PROJECT_NAME}_standard_traj_generator + PUBLIC + ${PACKAGES_DIR} + PRIVATE + Boost::system + ) + + set_target_properties(${PROJECT_NAME}_goal_checker PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + + set_target_properties(${PROJECT_NAME}_standard_traj_generator PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + +endif() + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + +else() + + install(TARGETS ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME}") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Libraries: ${PROJECT_NAME}_goal_checker, ${PROJECT_NAME}_standard_traj_generator") + message(STATUS "Dependencies: score_algorithm, robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core2, geometry_msgs, robot_nav_msgs, robot_std_msgs, robot_sensor_msgs, angles, Boost") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/equation_line.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/equation_line.h index 31bbeaa..b6976ac 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/equation_line.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/equation_line.h @@ -1,74 +1,74 @@ -#ifndef __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__ -#define __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__ -#include -#include -#include - -namespace mkt_plugins -{ - -/** - * @class NoSolution - */ -class NoSolution : public std::exception { - public: - const char * what () const throw () { - return "Robot cannot calculate error line!"; - } -}; // class NoSolution - -/** - * @class LineGenerator - */ -class LineGenerator -{ - /* data */ - struct LineEquation { - robot_geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊) */ - robot_geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋) */ - float a, b, c ; /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */ - }; - - /* Save data present position */ - struct PresentPosition { - float Gxh, Gyh; /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */ - float Yaw_degree; /* Angle of Robot (degree) */ - float Yaw_rad; /* Angle of Robot (degree) */ - float error_line; /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2) */ - double distance_to_goal; /* The distance from query pose to goal */ - double distance_to_start; /* The distance from query pose to start*/ - double distace_start_goal; - }; -public: - - /** - * @brief To caculated the equation of the line - * @param start_point start point of the line - * @param end_point end point of the line - */ - virtual bool calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point); - - /** - * @brief Calculating error - * @param[in] Lm The distance from the center of the wheel axis to the center line - * @param[in] pose - * @param[in] rev - */ - virtual void calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev = false); - - /** - * @brief Calculating tolerance - * @param query_pose The pose to check - * @param goal_pose The pose to check against - */ - virtual double calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose); - - /* Properties */ - LineEquation Leq_; - PresentPosition present_pose_; - -}; // class LineGenerator - -} // namespace mkt_plugins - -#endif // __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__ +#ifndef __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__ +#define __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__ +#include +#include +#include + +namespace mkt_plugins +{ + +/** + * @class NoSolution + */ +class NoSolution : public std::exception { + public: + const char * what () const throw () { + return "Robot cannot calculate error line!"; + } +}; // class NoSolution + +/** + * @class LineGenerator + */ +class LineGenerator +{ + /* data */ + struct LineEquation { + robot_geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊) */ + robot_geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋) */ + float a, b, c ; /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */ + }; + + /* Save data present position */ + struct PresentPosition { + float Gxh, Gyh; /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */ + float Yaw_degree; /* Angle of Robot (degree) */ + float Yaw_rad; /* Angle of Robot (degree) */ + float error_line; /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2) */ + double distance_to_goal; /* The distance from query pose to goal */ + double distance_to_start; /* The distance from query pose to start*/ + double distace_start_goal; + }; +public: + + /** + * @brief To caculated the equation of the line + * @param start_point start point of the line + * @param end_point end point of the line + */ + virtual bool calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point); + + /** + * @brief Calculating error + * @param[in] Lm The distance from the center of the wheel axis to the center line + * @param[in] pose + * @param[in] rev + */ + virtual void calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev = false); + + /** + * @brief Calculating tolerance + * @param query_pose The pose to check + * @param goal_pose The pose to check against + */ + virtual double calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose); + + /* Properties */ + LineEquation Leq_; + PresentPosition present_pose_; + +}; // class LineGenerator + +} // namespace mkt_plugins + +#endif // __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__ diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/goal_checker.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/goal_checker.h index 76bccae..6a747b8 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/goal_checker.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/goal_checker.h @@ -1,57 +1,57 @@ -#ifndef _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__ -#define _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__ - -#include -#include - -namespace mkt_plugins -{ - class GoalChecker : public score_algorithm::GoalChecker - { - public: - GoalChecker(); - /** - * @brief Initialize any parameters from the NodeHandle - * @param nh NodeHandle for grabbing parameters - */ - virtual void initialize(const robot::NodeHandle &nh) override; - - /** - * @brief Reset the state of the goal checker (if any) - */ - virtual void reset() override; - - /** - * @brief Check whether the goal should be considered reached - * @param query_pose The pose to check - * @param goal_pose The pose to check against - * @param velocity The robot's current velocity - * @return True if goal is reached - */ - bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose, - const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Factory function to create a GoalChecker instance - * @return Shared pointer to a new GoalChecker instance - */ - static score_algorithm::GoalChecker::Ptr create(); - protected: - /** - * @brief Internal method to initialize parameters from NodeHandle - * @param nh NodeHandle to load parameters from - * - * Loads xy_goal_tolerance and yaw_goal_tolerance parameters - */ - void intParam(const robot::NodeHandle &nh); - - robot::NodeHandle nh_; - std::shared_ptr line_generator_; - double yaw_goal_tolerance_; - double xy_goal_tolerance_; - double old_xy_goal_tolerance_; - }; - -} // namespace mkt_plugins - -#endif // _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__ +#ifndef _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__ +#define _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__ + +#include +#include + +namespace mkt_plugins +{ + class GoalChecker : public score_algorithm::GoalChecker + { + public: + GoalChecker(); + /** + * @brief Initialize any parameters from the NodeHandle + * @param nh NodeHandle for grabbing parameters + */ + virtual void initialize(const robot::NodeHandle &nh) override; + + /** + * @brief Reset the state of the goal checker (if any) + */ + virtual void reset() override; + + /** + * @brief Check whether the goal should be considered reached + * @param query_pose The pose to check + * @param goal_pose The pose to check against + * @param velocity The robot's current velocity + * @return True if goal is reached + */ + bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose, + const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Factory function to create a GoalChecker instance + * @return Shared pointer to a new GoalChecker instance + */ + static score_algorithm::GoalChecker::Ptr create(); + protected: + /** + * @brief Internal method to initialize parameters from NodeHandle + * @param nh NodeHandle to load parameters from + * + * Loads xy_goal_tolerance and yaw_goal_tolerance parameters + */ + void intParam(const robot::NodeHandle &nh); + + robot::NodeHandle nh_; + std::shared_ptr line_generator_; + double yaw_goal_tolerance_; + double xy_goal_tolerance_; + double old_xy_goal_tolerance_; + }; + +} // namespace mkt_plugins + +#endif // _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__ diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/kinematic_parameters.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/kinematic_parameters.h index 56aac68..edc1bfa 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/kinematic_parameters.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/kinematic_parameters.h @@ -1,318 +1,318 @@ -#ifndef MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_ -#define MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_ - -#include -#include - -namespace mkt_plugins -{ - - /** - * @class KinematicParameters - * @brief A dynamically reconfigurable class containing one representation of the robot's kinematics - */ - class KinematicParameters - { - public: - KinematicParameters(); - virtual ~KinematicParameters(); - void initialize(const robot::NodeHandle &nh); - - /** - * @brief Get the direction array for X, Y, and theta movement - * @return Pointer to an array of integers representing the direction of movement for X, Y, and theta (e.g., 1 for forward/right/clockwise, -1 for backward/left/counterclockwise, 0 for stop) - * - * This array controls the intended direction of the robot. Sudden changes in the theta component can cause discontinuities in odometry data, potentially leading to localization jumps in AMCL when rotating in place. - */ - int *getDirect(); - - /** - * @brief Get the minimum linear velocity along the X-axis - * @return Minimum linear velocity (m/s) for forward/backward motion - * - * Used to ensure the robot does not move too slowly along X, which could lead to odometry drift. Less relevant for in-place rotation issues. - */ - double getMinX(); - - /** - * @brief Get the maximum linear velocity along the X-axis - * @return Maximum linear velocity (m/s) for forward/backward motion - * - * Ensures the robot does not exceed safe speeds along X. Not directly related to rotation-induced localization jumps. - */ - double getMaxX(); - - /** - * @brief Get the maximum linear acceleration along the X-axis - * @return Maximum linear acceleration (m/s²) for forward/backward motion - * - * High acceleration can cause odometry errors if the robot's hardware cannot keep up. Less relevant for in-place rotation. - */ - double getAccX(); - - /** - * @brief Get the maximum linear deceleration along the X-axis - * @return Maximum linear deceleration (m/s²) for forward/backward motion - * - * Improper deceleration may cause jerky stops, leading to minor odometry errors. Not a primary cause of rotation-induced localization jumps. - */ - double getDecelX(); - - /** - * @brief Get the minimum linear velocity along the Y-axis - * @return Minimum linear velocity (m/s) for lateral motion (if applicable) - * - * Typically zero for differential drive robots. Not relevant for in-place rotation. - */ - double getMinY(); - - /** - * @brief Get the maximum linear velocity along the Y-axis - * @return Maximum linear velocity (m/s) for lateral motion - * - * Typically zero for differential drive robots. Not relevant for in-place rotation. - */ - double getMaxY(); - - /** - * @brief Get the maximum linear acceleration along the Y-axis - * @return Maximum linear acceleration (m/s²) for lateral motion - * - * Not relevant for in-place rotation in differential drive robots. - */ - double getAccY(); - - /** - * @brief Get the maximum linear deceleration along the Y-axis - * @return Maximum linear deceleration (m/s²) for lateral motion - * - * Not relevant for in-place rotation in differential drive robots. - */ - double getDecelY(); - - /** - * @brief Get the minimum combined linear velocity in the XY plane - * @return Minimum combined velocity (m/s) for motion in the XY plane - * - * Ensures the robot moves at a meaningful speed in the XY plane. Not directly related to in-place rotation issues. - */ - double getMinSpeedXY(); - - /** - * @brief Get the minimum angular velocity for rotation - * @return Minimum angular velocity (rad/s) for rotation around the Z-axis - * - * A very low value may cause the robot to struggle with stable rotation, leading to odometry errors and potential localization jumps in AMCL. - */ - double getMinTheta(); - - /** - * @brief Get the maximum angular velocity for rotation - * @return Maximum angular velocity (rad/s) for rotation around the Z-axis - * - * A high value (e.g., >2.0 rad/s) can cause wheel slip or odometry errors during fast rotation, leading to localization jumps in AMCL. - */ - double getMaxTheta(); - - /** - * @brief Get the maximum angular acceleration for rotation - * @return Maximum angular acceleration (rad/s²) for rotation around the Z-axis - * - * High angular acceleration can cause jerky rotation, leading to odometry errors and potential localization jumps in AMCL. - */ - double getAccTheta(); - - /** - * @brief Get the maximum angular deceleration for rotation - * @return Maximum angular deceleration (rad/s²) for rotation around the Z-axis - * - * Improper deceleration can cause jerky stops during rotation, leading to odometry errors and localization jumps in AMCL. - */ - double getDecelTheta(); - - /** - * @brief Get the minimum angular speed for rotation - * @return Minimum angular speed (rad/s) for rotation around the Z-axis - * - * Similar to getMinTheta(), a very low value may cause unstable rotation, contributing to odometry errors and AMCL localization issues. - */ - double getMinSpeedTheta(); - - /** - * @brief Set the direction array for X, Y, and theta movement - * @param xytheta_direct Pointer to an array of integers specifying the direction for X, Y, and theta - * - * Sets the intended direction of motion. Sudden changes in the theta component can cause discontinuities in odometry, leading to localization jumps in AMCL during in-place rotation. - */ - void setDirect(int *xytheta_direct); - - /** - * @brief Set the minimum linear velocity along the X-axis - * @param value Minimum linear velocity (m/s) for forward/backward motion - * - * Ensures the robot does not move too slowly along X. Not directly related to in-place rotation issues. - */ - void setMinX(double value); - - /** - * @brief Set the maximum linear velocity along the X-axis - * @param value Maximum linear velocity (m/s) for forward/backward motion - * - * Limits the robot's speed along X. Not directly related to in-place rotation issues. - */ - void setMaxX(double value); - - /** - * @brief Set the maximum linear acceleration along the X-axis - * @param value Maximum linear acceleration (m/s²) for forward/backward motion - * - * High acceleration can cause odometry errors if not supported by hardware. Less relevant for in-place rotation. - */ - void setAccX(double value); - - /** - * @brief Set the maximum linear deceleration along the X-axis - * @param value Maximum linear deceleration (m/s²) for forward/backward motion - * - * Improper deceleration may cause minor odometry errors. Not a primary cause of rotation-induced localization jumps. - */ - void setDecelX(double value); - - /** - * @brief Set the minimum linear velocity along the Y-axis - * @param value Minimum linear velocity (m/s) for lateral motion - * - * Typically zero for differential drive robots. Not relevant for in-place rotation. - */ - void setMinY(double value); - - /** - * @brief Set the maximum linear velocity along the Y-axis - * @param value Maximum linear velocity (m/s) for lateral motion - * - * Typically zero for differential drive robots. Not relevant for in-place rotation. - */ - void setMaxY(double value); - - /** - * @brief Set the maximum linear acceleration along the Y-axis - * @param value Maximum linear acceleration (m/s²) for lateral motion - * - * Not relevant for in-place rotation in differential drive robots. - */ - void setAccY(double value); - - /** - * @brief Set the maximum linear deceleration along the Y-axis - * @param value Maximum linear deceleration (m/s²) for lateral motion - * - * Not relevant for in-place rotation in differential drive robots. - */ - void setDecelY(double value); - - /** - * @brief Set the minimum combined linear velocity in the XY plane - * @param value Minimum combined velocity (m/s) for motion in the XY plane - * - * Ensures meaningful motion in the XY plane. Not directly related to in-place rotation issues. - */ - void setMinSpeedXY(double value); - - /** - * @brief Set the maximum angular velocity for rotation - * @param value Maximum angular velocity (rad/s) for rotation around the Z-axis - * - * A high value can cause fast rotation, leading to wheel slip or odometry errors, which may cause AMCL to jump during in-place rotation. - */ - void setMaxTheta(double value); - - /** - * @brief Set the maximum angular acceleration for rotation - * @param value Maximum angular acceleration (rad/s²) for rotation around the Z-axis - * - * High acceleration can cause jerky rotation, leading to odometry errors and AMCL localization jumps. - */ - void setAccTheta(double value); - - /** - * @brief Set the maximum angular deceleration for rotation - * @param value Maximum angular deceleration (rad/s²) for rotation around the Z-axis - * - * Improper deceleration can cause jerky stops, leading to odometry errors and AMCL localization jumps. - */ - void setDecelTheta(double value); - - /** - * @brief Set the minimum angular speed for rotation - * @param value Minimum angular speed (rad/s) for rotation around the Z-axis - * - * A very low value may cause unstable rotation, contributing to odometry errors and AMCL localization issues. - */ - void setMinSpeedTheta(double value); - - /** - * @brief Check to see whether the combined x/y/theta velocities are valid - * @return True if the magnitude hypot(x,y) and theta are within the robot's absolute limits - * - * This is based on three parameters: min_speed_xy, max_speed_xy and min_speed_theta. - * The speed is valid if - * 1) The combined magnitude hypot(x,y) is less than max_speed_xy (or max_speed_xy is negative) - * AND - * 2) min_speed_xy is negative or min_speed_theta is negative or - * hypot(x,y) is greater than min_speed_xy or fabs(theta) is greater than min_speed_theta. - * - * In English, it makes sure the diagonal motion is not too fast, - * and that the velocity is moving in some meaningful direction. - * - * In Latin, quod si motus sit signum quaerit et movere ieiunium et significantissime comprehendite. - */ - bool isValidSpeed(double x, double y, double theta); - - using Ptr = std::shared_ptr; - - protected: - - /** - * @brief Configure the kinematic parameters - * @param nh NodeHandle - * - * Configures the kinematic parameters from the given NodeHandle. - */ - void configure(const robot::NodeHandle &nh); - - /** - * @brief Reconfigure the kinematic parameters - * @param nh NodeHandle - * - * Reconfigures the kinematic parameters from the given NodeHandle. - */ - void reconfigure(const robot::NodeHandle &nh); - - // For parameter descriptions, see cfg/KinematicParams.cfg - int xytheta_direct_[3]; - double min_vel_x_, min_vel_y_; - double max_vel_x_, max_vel_y_, max_vel_theta_; - - double min_speed_xy_, max_speed_xy_; - double min_speed_theta_; - - double acc_lim_x_, acc_lim_y_, acc_lim_theta_; - double decel_lim_x_, decel_lim_y_, decel_lim_theta_; - - // Cached square values of min_speed_xy and max_speed_xy - double min_speed_xy_sq_, max_speed_xy_sq_; - - private: - double original_min_vel_x_, original_min_vel_y_; - double original_max_vel_x_, original_max_vel_y_, original_max_vel_theta_; - - double original_min_speed_xy_, original_max_speed_xy_; - double original_min_speed_theta_; - - double original_acc_lim_x_, original_acc_lim_y_, original_acc_lim_theta_; - double original_decel_lim_x_, original_decel_lim_y_, original_decel_lim_theta_; - }; - -} // namespace mkt_plugins - -#endif // MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_ +#ifndef MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_ +#define MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_ + +#include +#include + +namespace mkt_plugins +{ + + /** + * @class KinematicParameters + * @brief A dynamically reconfigurable class containing one representation of the robot's kinematics + */ + class KinematicParameters + { + public: + KinematicParameters(); + virtual ~KinematicParameters(); + void initialize(const robot::NodeHandle &nh); + + /** + * @brief Get the direction array for X, Y, and theta movement + * @return Pointer to an array of integers representing the direction of movement for X, Y, and theta (e.g., 1 for forward/right/clockwise, -1 for backward/left/counterclockwise, 0 for stop) + * + * This array controls the intended direction of the robot. Sudden changes in the theta component can cause discontinuities in odometry data, potentially leading to localization jumps in AMCL when rotating in place. + */ + int *getDirect(); + + /** + * @brief Get the minimum linear velocity along the X-axis + * @return Minimum linear velocity (m/s) for forward/backward motion + * + * Used to ensure the robot does not move too slowly along X, which could lead to odometry drift. Less relevant for in-place rotation issues. + */ + double getMinX(); + + /** + * @brief Get the maximum linear velocity along the X-axis + * @return Maximum linear velocity (m/s) for forward/backward motion + * + * Ensures the robot does not exceed safe speeds along X. Not directly related to rotation-induced localization jumps. + */ + double getMaxX(); + + /** + * @brief Get the maximum linear acceleration along the X-axis + * @return Maximum linear acceleration (m/s²) for forward/backward motion + * + * High acceleration can cause odometry errors if the robot's hardware cannot keep up. Less relevant for in-place rotation. + */ + double getAccX(); + + /** + * @brief Get the maximum linear deceleration along the X-axis + * @return Maximum linear deceleration (m/s²) for forward/backward motion + * + * Improper deceleration may cause jerky stops, leading to minor odometry errors. Not a primary cause of rotation-induced localization jumps. + */ + double getDecelX(); + + /** + * @brief Get the minimum linear velocity along the Y-axis + * @return Minimum linear velocity (m/s) for lateral motion (if applicable) + * + * Typically zero for differential drive robots. Not relevant for in-place rotation. + */ + double getMinY(); + + /** + * @brief Get the maximum linear velocity along the Y-axis + * @return Maximum linear velocity (m/s) for lateral motion + * + * Typically zero for differential drive robots. Not relevant for in-place rotation. + */ + double getMaxY(); + + /** + * @brief Get the maximum linear acceleration along the Y-axis + * @return Maximum linear acceleration (m/s²) for lateral motion + * + * Not relevant for in-place rotation in differential drive robots. + */ + double getAccY(); + + /** + * @brief Get the maximum linear deceleration along the Y-axis + * @return Maximum linear deceleration (m/s²) for lateral motion + * + * Not relevant for in-place rotation in differential drive robots. + */ + double getDecelY(); + + /** + * @brief Get the minimum combined linear velocity in the XY plane + * @return Minimum combined velocity (m/s) for motion in the XY plane + * + * Ensures the robot moves at a meaningful speed in the XY plane. Not directly related to in-place rotation issues. + */ + double getMinSpeedXY(); + + /** + * @brief Get the minimum angular velocity for rotation + * @return Minimum angular velocity (rad/s) for rotation around the Z-axis + * + * A very low value may cause the robot to struggle with stable rotation, leading to odometry errors and potential localization jumps in AMCL. + */ + double getMinTheta(); + + /** + * @brief Get the maximum angular velocity for rotation + * @return Maximum angular velocity (rad/s) for rotation around the Z-axis + * + * A high value (e.g., >2.0 rad/s) can cause wheel slip or odometry errors during fast rotation, leading to localization jumps in AMCL. + */ + double getMaxTheta(); + + /** + * @brief Get the maximum angular acceleration for rotation + * @return Maximum angular acceleration (rad/s²) for rotation around the Z-axis + * + * High angular acceleration can cause jerky rotation, leading to odometry errors and potential localization jumps in AMCL. + */ + double getAccTheta(); + + /** + * @brief Get the maximum angular deceleration for rotation + * @return Maximum angular deceleration (rad/s²) for rotation around the Z-axis + * + * Improper deceleration can cause jerky stops during rotation, leading to odometry errors and localization jumps in AMCL. + */ + double getDecelTheta(); + + /** + * @brief Get the minimum angular speed for rotation + * @return Minimum angular speed (rad/s) for rotation around the Z-axis + * + * Similar to getMinTheta(), a very low value may cause unstable rotation, contributing to odometry errors and AMCL localization issues. + */ + double getMinSpeedTheta(); + + /** + * @brief Set the direction array for X, Y, and theta movement + * @param xytheta_direct Pointer to an array of integers specifying the direction for X, Y, and theta + * + * Sets the intended direction of motion. Sudden changes in the theta component can cause discontinuities in odometry, leading to localization jumps in AMCL during in-place rotation. + */ + void setDirect(int *xytheta_direct); + + /** + * @brief Set the minimum linear velocity along the X-axis + * @param value Minimum linear velocity (m/s) for forward/backward motion + * + * Ensures the robot does not move too slowly along X. Not directly related to in-place rotation issues. + */ + void setMinX(double value); + + /** + * @brief Set the maximum linear velocity along the X-axis + * @param value Maximum linear velocity (m/s) for forward/backward motion + * + * Limits the robot's speed along X. Not directly related to in-place rotation issues. + */ + void setMaxX(double value); + + /** + * @brief Set the maximum linear acceleration along the X-axis + * @param value Maximum linear acceleration (m/s²) for forward/backward motion + * + * High acceleration can cause odometry errors if not supported by hardware. Less relevant for in-place rotation. + */ + void setAccX(double value); + + /** + * @brief Set the maximum linear deceleration along the X-axis + * @param value Maximum linear deceleration (m/s²) for forward/backward motion + * + * Improper deceleration may cause minor odometry errors. Not a primary cause of rotation-induced localization jumps. + */ + void setDecelX(double value); + + /** + * @brief Set the minimum linear velocity along the Y-axis + * @param value Minimum linear velocity (m/s) for lateral motion + * + * Typically zero for differential drive robots. Not relevant for in-place rotation. + */ + void setMinY(double value); + + /** + * @brief Set the maximum linear velocity along the Y-axis + * @param value Maximum linear velocity (m/s) for lateral motion + * + * Typically zero for differential drive robots. Not relevant for in-place rotation. + */ + void setMaxY(double value); + + /** + * @brief Set the maximum linear acceleration along the Y-axis + * @param value Maximum linear acceleration (m/s²) for lateral motion + * + * Not relevant for in-place rotation in differential drive robots. + */ + void setAccY(double value); + + /** + * @brief Set the maximum linear deceleration along the Y-axis + * @param value Maximum linear deceleration (m/s²) for lateral motion + * + * Not relevant for in-place rotation in differential drive robots. + */ + void setDecelY(double value); + + /** + * @brief Set the minimum combined linear velocity in the XY plane + * @param value Minimum combined velocity (m/s) for motion in the XY plane + * + * Ensures meaningful motion in the XY plane. Not directly related to in-place rotation issues. + */ + void setMinSpeedXY(double value); + + /** + * @brief Set the maximum angular velocity for rotation + * @param value Maximum angular velocity (rad/s) for rotation around the Z-axis + * + * A high value can cause fast rotation, leading to wheel slip or odometry errors, which may cause AMCL to jump during in-place rotation. + */ + void setMaxTheta(double value); + + /** + * @brief Set the maximum angular acceleration for rotation + * @param value Maximum angular acceleration (rad/s²) for rotation around the Z-axis + * + * High acceleration can cause jerky rotation, leading to odometry errors and AMCL localization jumps. + */ + void setAccTheta(double value); + + /** + * @brief Set the maximum angular deceleration for rotation + * @param value Maximum angular deceleration (rad/s²) for rotation around the Z-axis + * + * Improper deceleration can cause jerky stops, leading to odometry errors and AMCL localization jumps. + */ + void setDecelTheta(double value); + + /** + * @brief Set the minimum angular speed for rotation + * @param value Minimum angular speed (rad/s) for rotation around the Z-axis + * + * A very low value may cause unstable rotation, contributing to odometry errors and AMCL localization issues. + */ + void setMinSpeedTheta(double value); + + /** + * @brief Check to see whether the combined x/y/theta velocities are valid + * @return True if the magnitude hypot(x,y) and theta are within the robot's absolute limits + * + * This is based on three parameters: min_speed_xy, max_speed_xy and min_speed_theta. + * The speed is valid if + * 1) The combined magnitude hypot(x,y) is less than max_speed_xy (or max_speed_xy is negative) + * AND + * 2) min_speed_xy is negative or min_speed_theta is negative or + * hypot(x,y) is greater than min_speed_xy or fabs(theta) is greater than min_speed_theta. + * + * In English, it makes sure the diagonal motion is not too fast, + * and that the velocity is moving in some meaningful direction. + * + * In Latin, quod si motus sit signum quaerit et movere ieiunium et significantissime comprehendite. + */ + bool isValidSpeed(double x, double y, double theta); + + using Ptr = std::shared_ptr; + + protected: + + /** + * @brief Configure the kinematic parameters + * @param nh NodeHandle + * + * Configures the kinematic parameters from the given NodeHandle. + */ + void configure(const robot::NodeHandle &nh); + + /** + * @brief Reconfigure the kinematic parameters + * @param nh NodeHandle + * + * Reconfigures the kinematic parameters from the given NodeHandle. + */ + void reconfigure(const robot::NodeHandle &nh); + + // For parameter descriptions, see cfg/KinematicParams.cfg + int xytheta_direct_[3]; + double min_vel_x_, min_vel_y_; + double max_vel_x_, max_vel_y_, max_vel_theta_; + + double min_speed_xy_, max_speed_xy_; + double min_speed_theta_; + + double acc_lim_x_, acc_lim_y_, acc_lim_theta_; + double decel_lim_x_, decel_lim_y_, decel_lim_theta_; + + // Cached square values of min_speed_xy and max_speed_xy + double min_speed_xy_sq_, max_speed_xy_sq_; + + private: + double original_min_vel_x_, original_min_vel_y_; + double original_max_vel_x_, original_max_vel_y_, original_max_vel_theta_; + + double original_min_speed_xy_, original_max_speed_xy_; + double original_min_speed_theta_; + + double original_acc_lim_x_, original_acc_lim_y_, original_acc_lim_theta_; + double original_decel_lim_x_, original_decel_lim_y_, original_decel_lim_theta_; + }; + +} // namespace mkt_plugins + +#endif // MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_ diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/limited_accel_generator.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/limited_accel_generator.h index 5c0d783..978fa18 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/limited_accel_generator.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/limited_accel_generator.h @@ -1,51 +1,51 @@ -#ifndef MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_ -#define MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_ - -#include - -namespace mkt_plugins -{ -/** - * @class LimitedAccelGenerator - * @brief Limits the acceleration in the generated trajectories to a fraction of the simulated time. - */ -class LimitedAccelGenerator : public StandardTrajectoryGenerator -{ -public: - /** - * @brief Constructor - */ - LimitedAccelGenerator(); - /** - * @brief Destructor - */ - virtual ~LimitedAccelGenerator(); - - /** - * @brief Initialize the generator with parameters from NodeHandle - * @param nh NodeHandle for loading acceleration_time parameter - * - * Loads the acceleration_time parameter which limits acceleration to a fraction - * of the simulated time. - */ - void initialize(const robot::NodeHandle& nh) override; - - /** - * @brief Start a new iteration with current velocity - * @param current_velocity Current velocity of the robot - * - * Overrides the base class to apply acceleration limits based on acceleration_time. - */ - void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity) override; - - /** - * @brief Factory function to create a LimitedAccelGenerator instance - * @return Shared pointer to a new LimitedAccelGenerator instance - */ - static score_algorithm::TrajectoryGenerator::Ptr create(); -protected: - double acceleration_time_; -}; -} // namespace mkt_plugins - -#endif // MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_ +#ifndef MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_ +#define MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_ + +#include + +namespace mkt_plugins +{ +/** + * @class LimitedAccelGenerator + * @brief Limits the acceleration in the generated trajectories to a fraction of the simulated time. + */ +class LimitedAccelGenerator : public StandardTrajectoryGenerator +{ +public: + /** + * @brief Constructor + */ + LimitedAccelGenerator(); + /** + * @brief Destructor + */ + virtual ~LimitedAccelGenerator(); + + /** + * @brief Initialize the generator with parameters from NodeHandle + * @param nh NodeHandle for loading acceleration_time parameter + * + * Loads the acceleration_time parameter which limits acceleration to a fraction + * of the simulated time. + */ + void initialize(const robot::NodeHandle& nh) override; + + /** + * @brief Start a new iteration with current velocity + * @param current_velocity Current velocity of the robot + * + * Overrides the base class to apply acceleration limits based on acceleration_time. + */ + void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity) override; + + /** + * @brief Factory function to create a LimitedAccelGenerator instance + * @return Shared pointer to a new LimitedAccelGenerator instance + */ + static score_algorithm::TrajectoryGenerator::Ptr create(); +protected: + double acceleration_time_; +}; +} // namespace mkt_plugins + +#endif // MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_ diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/one_d_velocity_iterator.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/one_d_velocity_iterator.h index e9ecf68..2825877 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/one_d_velocity_iterator.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/one_d_velocity_iterator.h @@ -1,220 +1,220 @@ -#ifndef MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED_ -#define MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED_ - -#include -#include -#include - -namespace mkt_plugins -{ - - const double EPSILON = 5E-2; - - inline double exponentialFactor(double x, double k = 2.5) - { - x = std::clamp(x, 0.0, 1.0); - return 1.0 - std::exp(-k * x); // tương đương (1 - e^{-kx}) - } - - /** - * @brief Given initial conditions and a time, figure out the end velocity - * - * @param v0 Initial velocity - * @param accel The acceleration rate - * @param decel The decceleration rate - * @param dt Delta time - amount of time to project into the future - * @param target target velocity - * @return The velocity dt seconds after v0. - */ - inline double projectVelocity(double v0, double accel, double decel, double dt, double target) - { - double magnitude; - if (fabs(v0) < EPSILON) - { - // Starting from standstill, always accelerate - if (target >= 0.0) - { - magnitude = fabs(accel); - } - else - { - magnitude = -fabs(accel); - } - } - else if (v0 > 0.0) - { - if (v0 < target) - { - // Acceleration (speed magnitude increases) - magnitude = fabs(accel); - } - else - { - // Deceleration (speed magnitude decreases) - magnitude = -fabs(decel); - } - } - else - { - if (v0 < target) - { - // Deceleration (speed magnitude decreases) - magnitude = fabs(decel); - } - else - { - // Acceleration (speed magnitude increases) - magnitude = -fabs(accel); - } - } - - double delta_v = fabs(target - v0); - double max_v = std::max(fabs(target), 1e-3); - magnitude *= exponentialFactor(delta_v / max_v, 3.0); - double v1 = v0 + magnitude * dt; - - if (magnitude > 0.0) - { - return std::min(target, v1); - } - else - { - return std::max(target, v1); - } - } - - /** - * @class OneDVelocityIterator - * @brief An iterator for generating a number of samples in a range - * - * In its simplest usage, this gives us N (num_samples) different velocities that are reachable - * given our current velocity. However, there is some fancy logic around zero velocities and - * the min/max velocities - * - * If the current velocity is 2 m/s, and the acceleration limit is 1 m/ss and the acc_time is 1 s, - * this class would provide velocities between 1 m/s and 3 m/s. - * - * - * - */ - class OneDVelocityIterator - { - public: - std::string name_; - /** - * @brief Constructor for the velocity iterator - * @param current Current velocity of the robot - * @param direct Direction multiplier (1 for forward, -1 for backward, 0 for stop) - * @param min Minimum velocity allowable - * @param max Maximum velocity allowable - * @param acc_limit Maximum acceleration limit - * @param decel_limit Maximum deceleration limit - * @param acc_time Time delta for velocity projection - * @param num_samples Number of velocity samples to generate - * - * Creates an iterator that generates num_samples velocities reachable from - * current velocity within acc_time seconds, respecting acceleration/deceleration limits. - * The velocities range from min_vel_ to max_vel_ (projected from current velocity). - */ - OneDVelocityIterator( - std::string name, double current, int direct, double min, double max, double acc_limit, double decel_limit, double acc_time, int num_samples) - : name_(name) - { - // if (current < min) - // { - // current = min; - // } - // else if (current > max) - // { - // current = max; - // } - max_vel_ = projectVelocity(current, acc_limit, decel_limit, acc_time, max); - min_vel_ = projectVelocity(current, acc_limit, decel_limit, acc_time, min); - direct_ = direct; - current_ = direct_ > 0 ? max_vel_ : min_vel_; - reset(); - - if (min_vel_ - max_vel_ < EPSILON) - { - increment_ = 1.0; - return; - } - num_samples = std::max(2, num_samples); - - // e.g. for 4 samples, split distance in 3 even parts - increment_ = (max_vel_ - min_vel_) / std::max(1, (num_samples - 1)); - } - - /** - * @brief Get the current velocity value - * @return Current velocity value, or 0.0 if return_zero_now_ is true - * - * Returns the velocity at the current iterator position. - * If the iterator is set to return zero (when crossing zero velocity), - * returns 0.0 instead of the current value. - */ - double getVelocity() const - { - if (return_zero_now_) - return 0.0; - return current_; - } - - /** - * @brief Increment the iterator to the next velocity sample - * @return Reference to this iterator - * - * Moves to the next velocity sample. If the iterator crosses zero velocity - * (from negative to positive), it will return zero velocity on the next call - * to getVelocity() before continuing with positive velocities. - */ - OneDVelocityIterator &operator++() - { - if (return_zero_ && current_ < 0.0 && current_ + increment_ > 0.0 && current_ + increment_ <= max_vel_ + EPSILON) - { - return_zero_now_ = true; - return_zero_ = false; - } - else - { - current_ += increment_; - return_zero_now_ = false; - } - return *this; - } - - /** - * @brief Reset the iterator back to the first velocity - * - * Resets the iterator to the starting velocity (max_vel_ if direct > 0, - * min_vel_ if direct <= 0) and enables zero-velocity return if applicable. - */ - void reset() - { - return_zero_ = true; - return_zero_now_ = false; - } - - /** - * @brief Check if all velocities for this iteration have been returned - * @return True if the iterator has passed beyond the limit velocity - * - * Returns true when the current velocity has exceeded the maximum - * (if direct > 0) or minimum (if direct <= 0) velocity limit. - */ - bool isFinished() const - { - double limit_vel = direct_ > 0? max_vel_ : min_vel_; - return fabs(current_) > fabs(limit_vel) + EPSILON; - } - - private: - bool return_zero_, return_zero_now_; - double min_vel_, max_vel_; - double current_; - double direct_; - double increment_; - }; -} // namespace mkt_plugins - -#endif // MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED +#ifndef MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED_ +#define MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED_ + +#include +#include +#include + +namespace mkt_plugins +{ + + const double EPSILON = 5E-2; + + inline double exponentialFactor(double x, double k = 2.5) + { + x = std::clamp(x, 0.0, 1.0); + return 1.0 - std::exp(-k * x); // tương đương (1 - e^{-kx}) + } + + /** + * @brief Given initial conditions and a time, figure out the end velocity + * + * @param v0 Initial velocity + * @param accel The acceleration rate + * @param decel The decceleration rate + * @param dt Delta time - amount of time to project into the future + * @param target target velocity + * @return The velocity dt seconds after v0. + */ + inline double projectVelocity(double v0, double accel, double decel, double dt, double target) + { + double magnitude; + if (fabs(v0) < EPSILON) + { + // Starting from standstill, always accelerate + if (target >= 0.0) + { + magnitude = fabs(accel); + } + else + { + magnitude = -fabs(accel); + } + } + else if (v0 > 0.0) + { + if (v0 < target) + { + // Acceleration (speed magnitude increases) + magnitude = fabs(accel); + } + else + { + // Deceleration (speed magnitude decreases) + magnitude = -fabs(decel); + } + } + else + { + if (v0 < target) + { + // Deceleration (speed magnitude decreases) + magnitude = fabs(decel); + } + else + { + // Acceleration (speed magnitude increases) + magnitude = -fabs(accel); + } + } + + double delta_v = fabs(target - v0); + double max_v = std::max(fabs(target), 1e-3); + magnitude *= exponentialFactor(delta_v / max_v, 3.0); + double v1 = v0 + magnitude * dt; + + if (magnitude > 0.0) + { + return std::min(target, v1); + } + else + { + return std::max(target, v1); + } + } + + /** + * @class OneDVelocityIterator + * @brief An iterator for generating a number of samples in a range + * + * In its simplest usage, this gives us N (num_samples) different velocities that are reachable + * given our current velocity. However, there is some fancy logic around zero velocities and + * the min/max velocities + * + * If the current velocity is 2 m/s, and the acceleration limit is 1 m/ss and the acc_time is 1 s, + * this class would provide velocities between 1 m/s and 3 m/s. + * + * + * + */ + class OneDVelocityIterator + { + public: + std::string name_; + /** + * @brief Constructor for the velocity iterator + * @param current Current velocity of the robot + * @param direct Direction multiplier (1 for forward, -1 for backward, 0 for stop) + * @param min Minimum velocity allowable + * @param max Maximum velocity allowable + * @param acc_limit Maximum acceleration limit + * @param decel_limit Maximum deceleration limit + * @param acc_time Time delta for velocity projection + * @param num_samples Number of velocity samples to generate + * + * Creates an iterator that generates num_samples velocities reachable from + * current velocity within acc_time seconds, respecting acceleration/deceleration limits. + * The velocities range from min_vel_ to max_vel_ (projected from current velocity). + */ + OneDVelocityIterator( + std::string name, double current, int direct, double min, double max, double acc_limit, double decel_limit, double acc_time, int num_samples) + : name_(name) + { + // if (current < min) + // { + // current = min; + // } + // else if (current > max) + // { + // current = max; + // } + max_vel_ = projectVelocity(current, acc_limit, decel_limit, acc_time, max); + min_vel_ = projectVelocity(current, acc_limit, decel_limit, acc_time, min); + direct_ = direct; + current_ = direct_ > 0 ? max_vel_ : min_vel_; + reset(); + + if (min_vel_ - max_vel_ < EPSILON) + { + increment_ = 1.0; + return; + } + num_samples = std::max(2, num_samples); + + // e.g. for 4 samples, split distance in 3 even parts + increment_ = (max_vel_ - min_vel_) / std::max(1, (num_samples - 1)); + } + + /** + * @brief Get the current velocity value + * @return Current velocity value, or 0.0 if return_zero_now_ is true + * + * Returns the velocity at the current iterator position. + * If the iterator is set to return zero (when crossing zero velocity), + * returns 0.0 instead of the current value. + */ + double getVelocity() const + { + if (return_zero_now_) + return 0.0; + return current_; + } + + /** + * @brief Increment the iterator to the next velocity sample + * @return Reference to this iterator + * + * Moves to the next velocity sample. If the iterator crosses zero velocity + * (from negative to positive), it will return zero velocity on the next call + * to getVelocity() before continuing with positive velocities. + */ + OneDVelocityIterator &operator++() + { + if (return_zero_ && current_ < 0.0 && current_ + increment_ > 0.0 && current_ + increment_ <= max_vel_ + EPSILON) + { + return_zero_now_ = true; + return_zero_ = false; + } + else + { + current_ += increment_; + return_zero_now_ = false; + } + return *this; + } + + /** + * @brief Reset the iterator back to the first velocity + * + * Resets the iterator to the starting velocity (max_vel_ if direct > 0, + * min_vel_ if direct <= 0) and enables zero-velocity return if applicable. + */ + void reset() + { + return_zero_ = true; + return_zero_now_ = false; + } + + /** + * @brief Check if all velocities for this iteration have been returned + * @return True if the iterator has passed beyond the limit velocity + * + * Returns true when the current velocity has exceeded the maximum + * (if direct > 0) or minimum (if direct <= 0) velocity limit. + */ + bool isFinished() const + { + double limit_vel = direct_ > 0? max_vel_ : min_vel_; + return fabs(current_) > fabs(limit_vel) + EPSILON; + } + + private: + bool return_zero_, return_zero_now_; + double min_vel_, max_vel_; + double current_; + double direct_; + double increment_; + }; +} // namespace mkt_plugins + +#endif // MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/simple_goal_checker.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/simple_goal_checker.h index 4acd429..333a30a 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/simple_goal_checker.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/simple_goal_checker.h @@ -1,77 +1,77 @@ -#ifndef _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__ -#define _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__ - -#include -#include - -namespace mkt_plugins -{ - - /** - * @class SimpleGoalChecker - * @brief Goal Checker plugin that only checks the position difference - * - * This class can be stateful if the stateful parameter is set to true (which it is by default). - * This means that the goal checker will not check if the xy position matches again once it is found to be true. - */ - class SimpleGoalChecker : public score_algorithm::GoalChecker - { - public: - /** - * @brief Default constructor - * Initializes default values for goal tolerances and stateful behavior - */ - SimpleGoalChecker(); - - /** - * @brief Initialize the goal checker with parameters from NodeHandle - * @param nh NodeHandle for loading parameters (xy_goal_tolerance, yaw_goal_tolerance, stateful, check_xy) - */ - void initialize(const robot::NodeHandle &nh) override; - - /** - * @brief Reset the state of the goal checker - * Clears any cached state to allow re-checking of goal conditions - */ - void reset() override; - - /** - * @brief Check if the goal has been reached - * @param query_pose Current pose of the robot - * @param goal_pose Target pose to reach - * @param path Path to follow (not used in simple checker) - * @param velocity Current velocity of the robot (not used in simple checker) - * @return True if the robot is within xy_goal_tolerance and yaw_goal_tolerance of the goal - * - * If stateful is true, once xy position matches, it will not check xy again. - * This prevents oscillation when the robot is close to the goal. - */ - bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose, - const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Factory function to create a SimpleGoalChecker instance - * @return Shared pointer to a new SimpleGoalChecker instance - */ - static score_algorithm::GoalChecker::Ptr create(); - - protected: - /** - * @brief Internal method to initialize parameters from NodeHandle - * @param nh NodeHandle to load parameters from - * - * Loads xy_goal_tolerance, yaw_goal_tolerance, stateful, and check_xy parameters - */ - void intParam(const robot::NodeHandle& nh); - - robot::NodeHandle nh_; - double xy_goal_tolerance_, yaw_goal_tolerance_; - bool stateful_, check_xy_; - - // Cached squared xy_goal_tolerance_ - double xy_goal_tolerance_sq_; - }; - -} // namespace mkt_plugins - +#ifndef _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__ +#define _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__ + +#include +#include + +namespace mkt_plugins +{ + + /** + * @class SimpleGoalChecker + * @brief Goal Checker plugin that only checks the position difference + * + * This class can be stateful if the stateful parameter is set to true (which it is by default). + * This means that the goal checker will not check if the xy position matches again once it is found to be true. + */ + class SimpleGoalChecker : public score_algorithm::GoalChecker + { + public: + /** + * @brief Default constructor + * Initializes default values for goal tolerances and stateful behavior + */ + SimpleGoalChecker(); + + /** + * @brief Initialize the goal checker with parameters from NodeHandle + * @param nh NodeHandle for loading parameters (xy_goal_tolerance, yaw_goal_tolerance, stateful, check_xy) + */ + void initialize(const robot::NodeHandle &nh) override; + + /** + * @brief Reset the state of the goal checker + * Clears any cached state to allow re-checking of goal conditions + */ + void reset() override; + + /** + * @brief Check if the goal has been reached + * @param query_pose Current pose of the robot + * @param goal_pose Target pose to reach + * @param path Path to follow (not used in simple checker) + * @param velocity Current velocity of the robot (not used in simple checker) + * @return True if the robot is within xy_goal_tolerance and yaw_goal_tolerance of the goal + * + * If stateful is true, once xy position matches, it will not check xy again. + * This prevents oscillation when the robot is close to the goal. + */ + bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose, + const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Factory function to create a SimpleGoalChecker instance + * @return Shared pointer to a new SimpleGoalChecker instance + */ + static score_algorithm::GoalChecker::Ptr create(); + + protected: + /** + * @brief Internal method to initialize parameters from NodeHandle + * @param nh NodeHandle to load parameters from + * + * Loads xy_goal_tolerance, yaw_goal_tolerance, stateful, and check_xy parameters + */ + void intParam(const robot::NodeHandle& nh); + + robot::NodeHandle nh_; + double xy_goal_tolerance_, yaw_goal_tolerance_; + bool stateful_, check_xy_; + + // Cached squared xy_goal_tolerance_ + double xy_goal_tolerance_sq_; + }; + +} // namespace mkt_plugins + #endif // _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/standard_traj_generator.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/standard_traj_generator.h index b7480d0..12847e0 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/standard_traj_generator.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/standard_traj_generator.h @@ -1,205 +1,205 @@ -#ifndef MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_ -#define MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_ - -#include -#include -#include -#include -#include -#include - -namespace mkt_plugins -{ - /** - * @class StandardTrajectoryGenerator - * @brief Standard MKT-like trajectory generator. - */ - class StandardTrajectoryGenerator : public score_algorithm::TrajectoryGenerator - { - public: - - /** - * @brief Constructor - */ - StandardTrajectoryGenerator(); - - /** - * @brief Destructor - */ - virtual ~StandardTrajectoryGenerator(); - /** - * @brief Initialize the trajectory generator with parameters from NodeHandle - * @param nh NodeHandle for loading configuration parameters - * - * Loads parameters such as sim_time, discretize_by_time, time_granularity, - * linear_granularity, angular_granularity, and include_last_point. - */ - void initialize(const robot::NodeHandle &nh) override; - - /** - * @brief Set the direction array for X, Y, and Theta movement - * @param xytheta_direct Pointer to array of 3 integers representing direction - * (1 for forward/right/clockwise, -1 for backward/left/counterclockwise) - */ - void setDirect(int *xytheta_direct) override; - - /** - * @brief set velocity for x, y asix of the robot - * @param linear the velocity command - * @return True if set is done, false otherwise - */ - bool setTwistLinear(robot_geometry_msgs::Vector3 linear) override; - - /** - * @brief get velocity for x, y asix of the robot - * @param linear The velocity command - * @return True if set is done, false otherwise - */ - virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) override; - - /** - * @brief Set velocity theta for z asix of the robot - * @param angular the command velocity - * @return True if set is done, false otherwise - */ - virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) override; - - /** - * @brief Get velocity theta for z asix of the robot - * @param direct The velocity command - * @return True if set is done, false otherwise - */ - virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) override; - - /** - * @brief Start a new iteration with current velocity - * @param current_velocity Current velocity of the robot - * - * Resets the velocity iterator and prepares it to generate velocities - * reachable from the current velocity. - */ - void startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) override; - - /** - * @brief Check if there are more velocity samples available - * @return True if there are more valid velocity combinations to iterate - */ - bool hasMoreTwists() override; - - /** - * @brief Get the next velocity sample - * @return Next valid velocity combination - */ - robot_nav_2d_msgs::Twist2D nextTwist() override; - - /** - * @brief Get the current velocity - * @return The current velocity - */ - robot_nav_2d_msgs::Twist2D getTwist() override; - - /** - * @brief Generate a trajectory from start pose to goal - * @param start_pose Starting pose of the robot - * @param transformed_plan Transformed global plan (path to follow) - * @param start_vel Starting velocity of the robot - * @param cmd_vel Command velocity to achieve - * @return Generated trajectory containing poses and velocities over time - * - * Generates a trajectory by: - * 1. Computing velocity steps based on acceleration limits - * 2. Projecting poses forward using kinematic model - * 3. Sampling velocities using the velocity iterator - */ - mkt_msgs::Trajectory2D generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose, - const robot_nav_2d_msgs::Path2D &transformed_plan, - const robot_nav_2d_msgs::Twist2D &start_vel, - const robot_nav_2d_msgs::Twist2D &cmd_vel) override; - - /** - * @brief Get the NodeHandle used for kinematics configuration - * @return NodeHandle scoped to kinematics namespace - */ - virtual robot::NodeHandle getNodeHandle() override; - - /** - * @brief Factory function to create a StandardTrajectoryGenerator instance - * @return Shared pointer to a new StandardTrajectoryGenerator instance - */ - static score_algorithm::TrajectoryGenerator::Ptr create(); - - protected: - /** - * @brief Initialize the VelocityIterator pointer. Put in its own function for easy overriding - */ - virtual void initializeIterator(const robot::NodeHandle &nh); - - /** - * @brief Calculate the velocity after a set period of time, given the desired velocity and acceleration limits - * - * @param cmd_vel Desired velocity - * @param start_vel starting velocity - * @param dt amount of time in seconds - * @return new velocity after dt seconds - */ - virtual robot_nav_2d_msgs::Twist2D computeNewVelocity(const robot_nav_2d_msgs::Twist2D &cmd_vel, - const robot_nav_2d_msgs::Twist2D &start_vel, - const double dt); - - /** - * @brief Use the robot's kinematic model to predict new positions for the robot - * - * @param start_pose Starting pose - * @param vel Actual robot velocity (assumed to be within acceleration limits) - * @param dt amount of time in seconds - * @return New pose after dt seconds - */ - virtual robot_geometry_msgs::Pose2D computeNewPosition(const robot_geometry_msgs::Pose2D start_pose, - const robot_nav_2d_msgs::Twist2D &vel, - const double dt); - - /** - * @brief Compute an array of time deltas between the points in the generated trajectory. - * - * @param cmd_vel The desired command velocity - * @return vector of the difference between each time step in the generated trajectory - * - * If we are discretizing by time, the returned vector will be the same constant time_granularity - * for all cmd_vels. Otherwise, you will get times based on the linear/angular granularity. - * - * Right now the vector contains a single value repeated many times, but this method could be overridden - * to allow for dynamic spacing - */ - virtual std::vector getTimeSteps(const robot_nav_2d_msgs::Twist2D &cmd_vel); - - robot::NodeHandle nh_kinematics_; - KinematicParameters::Ptr kinematics_; - std::shared_ptr velocity_iterator_; - - double sim_time_; - - // Sampling Parameters - bool discretize_by_time_; - double time_granularity_; ///< If discretizing by time, the amount of time between each point in the traj - double linear_granularity_; ///< If not discretizing by time, the amount of linear space between points - double angular_granularity_; ///< If not discretizing by time, the amount of angular space between points - - /* Backwards Compatibility Parameter: include_last_point - * - * dwa had an off-by-one error built into it. - * It generated N trajectory points, where N = ceil(sim_time / time_delta). - * If for example, sim_time=3.0 and time_delta=1.5, it would generate trajectories with 2 points, which - * indeed were time_delta seconds apart. However, the points would be at t=0 and t=1.5, and thus the - * actual sim_time was much less than advertised. - * - * This is remedied by adding one final point at t=sim_time, but only if include_last_point_ is true. - * - * Nothing I could find actually used the time_delta variable or seemed to care that the trajectories - * were not projected out as far as they intended. - */ - bool include_last_point_; - }; // class StandardTrajectoryGenerator - -} // namespace dwb_plugins - +#ifndef MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_ +#define MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_ + +#include +#include +#include +#include +#include +#include + +namespace mkt_plugins +{ + /** + * @class StandardTrajectoryGenerator + * @brief Standard MKT-like trajectory generator. + */ + class StandardTrajectoryGenerator : public score_algorithm::TrajectoryGenerator + { + public: + + /** + * @brief Constructor + */ + StandardTrajectoryGenerator(); + + /** + * @brief Destructor + */ + virtual ~StandardTrajectoryGenerator(); + /** + * @brief Initialize the trajectory generator with parameters from NodeHandle + * @param nh NodeHandle for loading configuration parameters + * + * Loads parameters such as sim_time, discretize_by_time, time_granularity, + * linear_granularity, angular_granularity, and include_last_point. + */ + void initialize(const robot::NodeHandle &nh) override; + + /** + * @brief Set the direction array for X, Y, and Theta movement + * @param xytheta_direct Pointer to array of 3 integers representing direction + * (1 for forward/right/clockwise, -1 for backward/left/counterclockwise) + */ + void setDirect(int *xytheta_direct) override; + + /** + * @brief set velocity for x, y asix of the robot + * @param linear the velocity command + * @return True if set is done, false otherwise + */ + bool setTwistLinear(robot_geometry_msgs::Vector3 linear) override; + + /** + * @brief get velocity for x, y asix of the robot + * @param linear The velocity command + * @return True if set is done, false otherwise + */ + virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) override; + + /** + * @brief Set velocity theta for z asix of the robot + * @param angular the command velocity + * @return True if set is done, false otherwise + */ + virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) override; + + /** + * @brief Get velocity theta for z asix of the robot + * @param direct The velocity command + * @return True if set is done, false otherwise + */ + virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) override; + + /** + * @brief Start a new iteration with current velocity + * @param current_velocity Current velocity of the robot + * + * Resets the velocity iterator and prepares it to generate velocities + * reachable from the current velocity. + */ + void startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) override; + + /** + * @brief Check if there are more velocity samples available + * @return True if there are more valid velocity combinations to iterate + */ + bool hasMoreTwists() override; + + /** + * @brief Get the next velocity sample + * @return Next valid velocity combination + */ + robot_nav_2d_msgs::Twist2D nextTwist() override; + + /** + * @brief Get the current velocity + * @return The current velocity + */ + robot_nav_2d_msgs::Twist2D getTwist() override; + + /** + * @brief Generate a trajectory from start pose to goal + * @param start_pose Starting pose of the robot + * @param transformed_plan Transformed global plan (path to follow) + * @param start_vel Starting velocity of the robot + * @param cmd_vel Command velocity to achieve + * @return Generated trajectory containing poses and velocities over time + * + * Generates a trajectory by: + * 1. Computing velocity steps based on acceleration limits + * 2. Projecting poses forward using kinematic model + * 3. Sampling velocities using the velocity iterator + */ + mkt_msgs::Trajectory2D generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose, + const robot_nav_2d_msgs::Path2D &transformed_plan, + const robot_nav_2d_msgs::Twist2D &start_vel, + const robot_nav_2d_msgs::Twist2D &cmd_vel) override; + + /** + * @brief Get the NodeHandle used for kinematics configuration + * @return NodeHandle scoped to kinematics namespace + */ + virtual robot::NodeHandle getNodeHandle() override; + + /** + * @brief Factory function to create a StandardTrajectoryGenerator instance + * @return Shared pointer to a new StandardTrajectoryGenerator instance + */ + static score_algorithm::TrajectoryGenerator::Ptr create(); + + protected: + /** + * @brief Initialize the VelocityIterator pointer. Put in its own function for easy overriding + */ + virtual void initializeIterator(const robot::NodeHandle &nh); + + /** + * @brief Calculate the velocity after a set period of time, given the desired velocity and acceleration limits + * + * @param cmd_vel Desired velocity + * @param start_vel starting velocity + * @param dt amount of time in seconds + * @return new velocity after dt seconds + */ + virtual robot_nav_2d_msgs::Twist2D computeNewVelocity(const robot_nav_2d_msgs::Twist2D &cmd_vel, + const robot_nav_2d_msgs::Twist2D &start_vel, + const double dt); + + /** + * @brief Use the robot's kinematic model to predict new positions for the robot + * + * @param start_pose Starting pose + * @param vel Actual robot velocity (assumed to be within acceleration limits) + * @param dt amount of time in seconds + * @return New pose after dt seconds + */ + virtual robot_geometry_msgs::Pose2D computeNewPosition(const robot_geometry_msgs::Pose2D start_pose, + const robot_nav_2d_msgs::Twist2D &vel, + const double dt); + + /** + * @brief Compute an array of time deltas between the points in the generated trajectory. + * + * @param cmd_vel The desired command velocity + * @return vector of the difference between each time step in the generated trajectory + * + * If we are discretizing by time, the returned vector will be the same constant time_granularity + * for all cmd_vels. Otherwise, you will get times based on the linear/angular granularity. + * + * Right now the vector contains a single value repeated many times, but this method could be overridden + * to allow for dynamic spacing + */ + virtual std::vector getTimeSteps(const robot_nav_2d_msgs::Twist2D &cmd_vel); + + robot::NodeHandle nh_kinematics_; + KinematicParameters::Ptr kinematics_; + std::shared_ptr velocity_iterator_; + + double sim_time_; + + // Sampling Parameters + bool discretize_by_time_; + double time_granularity_; ///< If discretizing by time, the amount of time between each point in the traj + double linear_granularity_; ///< If not discretizing by time, the amount of linear space between points + double angular_granularity_; ///< If not discretizing by time, the amount of angular space between points + + /* Backwards Compatibility Parameter: include_last_point + * + * dwa had an off-by-one error built into it. + * It generated N trajectory points, where N = ceil(sim_time / time_delta). + * If for example, sim_time=3.0 and time_delta=1.5, it would generate trajectories with 2 points, which + * indeed were time_delta seconds apart. However, the points would be at t=0 and t=1.5, and thus the + * actual sim_time was much less than advertised. + * + * This is remedied by adding one final point at t=sim_time, but only if include_last_point_ is true. + * + * Nothing I could find actually used the time_delta variable or seemed to care that the trajectories + * were not projected out as far as they intended. + */ + bool include_last_point_; + }; // class StandardTrajectoryGenerator + +} // namespace dwb_plugins + #endif // MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_ \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/velocity_iterator.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/velocity_iterator.h index 2d1dbc8..fa6c369 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/velocity_iterator.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/velocity_iterator.h @@ -1,67 +1,67 @@ -#ifndef MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_ -#define MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_ - -#include -#include -#include - -namespace mkt_plugins -{ -/** - * @class VelocityIterator - * @brief Abstract base class for iterating over valid velocity samples - * - * This interface provides a way to generate and iterate through velocity samples - * that satisfy kinematic constraints. Implementations should generate velocities - * reachable from the current velocity within acceleration limits. - */ -class VelocityIterator -{ -public: - /** - * @brief Virtual destructor - */ - virtual ~VelocityIterator() {} - - /** - * @brief Initialize the iterator with parameters and kinematics - * @param nh NodeHandle for loading configuration parameters - * @param kinematics Shared pointer to kinematic parameters for validation - */ - virtual void initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) = 0; - - /** - * @brief Start a new iteration with current velocity and time delta - * @param current_velocity Current velocity of the robot - * @param dt Time delta for velocity projection - * - * Resets the iterator and prepares it to generate velocities reachable - * from the current velocity within dt seconds. - */ - virtual void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) = 0; - - /** - * @brief Check if there are more velocity samples available - * @return True if there are more valid velocity combinations to iterate - */ - virtual bool hasMoreTwists() = 0; - - /** - * @brief Get the next velocity sample - * @return Next valid velocity combination - * - * Returns the next velocity sample that satisfies kinematic constraints. - * Should only be called when hasMoreTwists() returns true. - */ - virtual robot_nav_2d_msgs::Twist2D nextTwist() = 0; - - /** - * @brief Get the current velocity - * @return The current velocity - */ - virtual robot_nav_2d_msgs::Twist2D getTwist() = 0; -}; // class VelocityIterator - -} // namespace mkt_plugins - -#endif // MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_ +#ifndef MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_ +#define MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_ + +#include +#include +#include + +namespace mkt_plugins +{ +/** + * @class VelocityIterator + * @brief Abstract base class for iterating over valid velocity samples + * + * This interface provides a way to generate and iterate through velocity samples + * that satisfy kinematic constraints. Implementations should generate velocities + * reachable from the current velocity within acceleration limits. + */ +class VelocityIterator +{ +public: + /** + * @brief Virtual destructor + */ + virtual ~VelocityIterator() {} + + /** + * @brief Initialize the iterator with parameters and kinematics + * @param nh NodeHandle for loading configuration parameters + * @param kinematics Shared pointer to kinematic parameters for validation + */ + virtual void initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) = 0; + + /** + * @brief Start a new iteration with current velocity and time delta + * @param current_velocity Current velocity of the robot + * @param dt Time delta for velocity projection + * + * Resets the iterator and prepares it to generate velocities reachable + * from the current velocity within dt seconds. + */ + virtual void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) = 0; + + /** + * @brief Check if there are more velocity samples available + * @return True if there are more valid velocity combinations to iterate + */ + virtual bool hasMoreTwists() = 0; + + /** + * @brief Get the next velocity sample + * @return Next valid velocity combination + * + * Returns the next velocity sample that satisfies kinematic constraints. + * Should only be called when hasMoreTwists() returns true. + */ + virtual robot_nav_2d_msgs::Twist2D nextTwist() = 0; + + /** + * @brief Get the current velocity + * @return The current velocity + */ + virtual robot_nav_2d_msgs::Twist2D getTwist() = 0; +}; // class VelocityIterator + +} // namespace mkt_plugins + +#endif // MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_ diff --git a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/xy_theta_iterator.h b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/xy_theta_iterator.h index 37ecab8..db630b3 100644 --- a/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/xy_theta_iterator.h +++ b/src/Algorithms/Libraries/mkt_plugins/include/mkt_plugins/xy_theta_iterator.h @@ -1,90 +1,90 @@ -#ifndef MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_ -#define MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_ - -#include -#include -#include - -namespace mkt_plugins -{ - /** - * @class XYThetaIterator - * @brief Iterator that generates velocity samples for X, Y, and Theta dimensions - * - * This iterator combines three OneDVelocityIterator instances (one for each dimension) - * to generate valid velocity combinations that satisfy kinematic constraints. - */ - class XYThetaIterator : public VelocityIterator - { - public: - /** - * @brief Default constructor - * Initializes all iterators to nullptr - */ - XYThetaIterator(); - - /** - * @brief Destructor - */ - virtual ~XYThetaIterator(); - - /** - * @brief Initialize the iterator with parameters and kinematics - * @param nh NodeHandle for loading sampling parameters (vx_samples, vy_samples, vtheta_samples) - * @param kinematics Shared pointer to kinematic parameters for validation - */ - void initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) override; - - /** - * @brief Start a new iteration with current velocity and time delta - * @param current_velocity Current velocity of the robot - * @param dt Time delta for velocity projection - * - * Creates new OneDVelocityIterator instances for X, Y, and Theta dimensions - * based on the current velocity and kinematic constraints. - */ - void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) override; - - /** - * @brief Check if there are more velocity samples to iterate - * @return True if there are more valid velocity combinations available - */ - bool hasMoreTwists() override; - - /** - * @brief Get the next velocity sample - * @return Next valid velocity combination (x, y, theta) - * - * Returns the next valid velocity that satisfies kinematic constraints. - * Automatically iterates to the next valid velocity if current is invalid. - */ - robot_nav_2d_msgs::Twist2D nextTwist() override; - - /** - * @brief Get the current velocity - * @return The current velocity (x, y, theta) - */ - robot_nav_2d_msgs::Twist2D getTwist() override; - - protected: - /** - * @brief Check if the current velocity combination is valid - * @return True if the current velocity (x_it_, y_it_, th_it_) satisfies kinematic constraints - */ - virtual bool isValidVelocity(); - - /** - * @brief Iterate through velocity samples until a valid combination is found - * - * Increments the iterators (theta first, then y, then x) until a valid - * velocity combination is found or all combinations are exhausted. - */ - void iterateToValidVelocity(); - - int vx_samples_, vy_samples_, vtheta_samples_; - KinematicParameters::Ptr kinematics_; - std::shared_ptr x_it_, y_it_, th_it_; - }; -} // namespace mkt_plugins - -#endif // MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_ +#ifndef MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_ +#define MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_ + +#include +#include +#include + +namespace mkt_plugins +{ + /** + * @class XYThetaIterator + * @brief Iterator that generates velocity samples for X, Y, and Theta dimensions + * + * This iterator combines three OneDVelocityIterator instances (one for each dimension) + * to generate valid velocity combinations that satisfy kinematic constraints. + */ + class XYThetaIterator : public VelocityIterator + { + public: + /** + * @brief Default constructor + * Initializes all iterators to nullptr + */ + XYThetaIterator(); + + /** + * @brief Destructor + */ + virtual ~XYThetaIterator(); + + /** + * @brief Initialize the iterator with parameters and kinematics + * @param nh NodeHandle for loading sampling parameters (vx_samples, vy_samples, vtheta_samples) + * @param kinematics Shared pointer to kinematic parameters for validation + */ + void initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) override; + + /** + * @brief Start a new iteration with current velocity and time delta + * @param current_velocity Current velocity of the robot + * @param dt Time delta for velocity projection + * + * Creates new OneDVelocityIterator instances for X, Y, and Theta dimensions + * based on the current velocity and kinematic constraints. + */ + void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) override; + + /** + * @brief Check if there are more velocity samples to iterate + * @return True if there are more valid velocity combinations available + */ + bool hasMoreTwists() override; + + /** + * @brief Get the next velocity sample + * @return Next valid velocity combination (x, y, theta) + * + * Returns the next valid velocity that satisfies kinematic constraints. + * Automatically iterates to the next valid velocity if current is invalid. + */ + robot_nav_2d_msgs::Twist2D nextTwist() override; + + /** + * @brief Get the current velocity + * @return The current velocity (x, y, theta) + */ + robot_nav_2d_msgs::Twist2D getTwist() override; + + protected: + /** + * @brief Check if the current velocity combination is valid + * @return True if the current velocity (x_it_, y_it_, th_it_) satisfies kinematic constraints + */ + virtual bool isValidVelocity(); + + /** + * @brief Iterate through velocity samples until a valid combination is found + * + * Increments the iterators (theta first, then y, then x) until a valid + * velocity combination is found or all combinations are exhausted. + */ + void iterateToValidVelocity(); + + int vx_samples_, vy_samples_, vtheta_samples_; + KinematicParameters::Ptr kinematics_; + std::shared_ptr x_it_, y_it_, th_it_; + }; +} // namespace mkt_plugins + +#endif // MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_ diff --git a/src/Algorithms/Libraries/mkt_plugins/package.xml b/src/Algorithms/Libraries/mkt_plugins/package.xml index a82e9a3..8c3fb7f 100644 --- a/src/Algorithms/Libraries/mkt_plugins/package.xml +++ b/src/Algorithms/Libraries/mkt_plugins/package.xml @@ -1,49 +1,49 @@ - - mkt_plugins - 0.7.10 - - mkt_plugins is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. mkt_plugins - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/mkt_plugins - - catkin - - score_algorithm - score_algorithm - - robot_nav_2d_msgs - robot_nav_2d_msgs - - robot_nav_2d_utils - robot_nav_2d_utils - - robot_nav_core2 - robot_nav_core2 - - geometry_msgs - geometry_msgs - - robot_nav_msgs - robot_nav_msgs - - robot_std_msgs - robot_std_msgs - - robot_sensor_msgs - robot_sensor_msgs - - angles - angles - + + mkt_plugins + 0.7.10 + + mkt_plugins is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. mkt_plugins + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/mkt_plugins + + catkin + + score_algorithm + score_algorithm + + robot_nav_2d_msgs + robot_nav_2d_msgs + + robot_nav_2d_utils + robot_nav_2d_utils + + robot_nav_core2 + robot_nav_core2 + + geometry_msgs + geometry_msgs + + robot_nav_msgs + robot_nav_msgs + + robot_std_msgs + robot_std_msgs + + robot_sensor_msgs + robot_sensor_msgs + + angles + angles + \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_plugins/src/equation_line.cpp b/src/Algorithms/Libraries/mkt_plugins/src/equation_line.cpp index 2b142b8..615e90e 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/equation_line.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/equation_line.cpp @@ -1,118 +1,118 @@ -#include "mkt_plugins/equation_line.h" -#include -#include - -namespace mkt_plugins -{ - -bool LineGenerator::calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point) -{ - /** - * Phương trình đường thẳng có dạng: - * (y - yi)/(yj - yi) = (x - xi)/(xj - xi) - */ - Leq_.Gi = start_point; Leq_.Gj = end_point; - Leq_.a = (Leq_.Gj.y - Leq_.Gi.y); - Leq_.b = (Leq_.Gi.x - Leq_.Gj.x); - Leq_.c = (Leq_.Gj.x * Leq_.Gi.y - Leq_.Gi.x * Leq_.Gj.y); - - return Leq_.a != 0 || Leq_.b !=0; -} - -void LineGenerator::calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev) -{ - float pha = rev? M_PI : 0; - float Yaw_rad = pose.theta - pha; - -/* - * Tính tọa độ điểm R -*/ - float G_xr = float(pose.x); - float G_yr = float(pose.y); - -/* - * Tính tọa độ điểm H -*/ - present_pose_.Gxh = G_xr + Lm * cos(Yaw_rad); - present_pose_.Gyh = G_yr + Lm * sin(Yaw_rad); - -/** - * Phương trình đường thẳng (rh) có dạng: - * (y - yr)/(yh - yr) = (x - xr)/(xh - xr) -*/ - float A_rh = (present_pose_.Gyh - G_yr); - float B_rh = (G_xr - present_pose_.Gxh); - float C_rh = (present_pose_.Gxh * G_yr - G_xr * present_pose_.Gyh); -/* - * Phương trình đường thẳng vuông góc (y - yr)/(yh - yr) = (x - xr)/(xh - xr) - * và đi qua Gh có dạng: - * -B_rh*(x - Gxh) + Arh*(y - Gyh) = 0 -*/ - float A_he = -B_rh; - float B_he = A_rh; - float C_he = (-B_rh) * (-present_pose_.Gxh) + A_rh * (-present_pose_.Gyh); -/* - * Đường thẳng (he) giao với đường thẳng (ij) tại e - * vậy G_xe và G_ye là nghiệm của hệ phương trình 2 ẩn của 2 đường thẳng trên: -*/ - float D = A_he * Leq_.b - Leq_.a * B_he; - float Dx = (-C_he) * Leq_.b - (-Leq_.c) * B_he; - float Dy = A_he * (-Leq_.c) - Leq_.a * (-C_he); -/* - * Tính tọa độ điểm E -*/ - if(D == 0) { - if(Dx + Dy == 0) - { -/* - * Vì hai đường thẳng trùng nhau nên sai số giữa robot và đường đi là bằng 0 -*/ - present_pose_.error_line = 0; - } - else throw NoSolution(); - } - else - { - float G_xe = Dx/D; - float G_ye = Dy/D; -/* - * Tính khoảng cách từ điểm E đến đường thẳng (RH) -*/ - present_pose_.error_line = -(A_rh * G_xe + B_rh * G_ye + C_rh) / (sqrt(pow(A_rh, 2) + pow(B_rh, 2))); - } - // present_pose_.error_line = (Leq.a * present_pose_.Gxh + Leq.b * present_pose_.Gyh + Leq.c) / (sqrt(pow(Leq.a, 2) + pow(Leq.b, 2))); - present_pose_.distance_to_goal = sqrt(pow((Leq_.Gj.x - G_xr),2) + pow((Leq_.Gj.y - G_yr),2)); - present_pose_.distance_to_start = sqrt(pow((Leq_.Gi.x - G_xr),2) + pow((Leq_.Gi.y - G_yr),2)); - - -} - -double LineGenerator::calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose) -{ - /** - * Phương trình đường thẳng có dạng: - * (y - yi)/(yj - yi) = (x - xi)/(xj - xi) - */ - // LineEquation Leq; - // Leq.Gi = query_pose; Leq.Gj = goal_pose; - // Leq.a = (Leq.Gj.y - Leq.Gi.y); - // Leq.b = (Leq.Gi.x - Leq.Gj.x); - // Leq.c = (Leq.Gj.x * Leq.Gi.y - Leq.Gi.x * Leq.Gj.y); - - /** - * Phương trình đường thẳng vuông góc - */ - LineEquation Leq_l; - Leq_l.a = -Leq_.b; - Leq_l.b = Leq_.a; - Leq_l.c = Leq_.b * goal_pose.x - Leq_.a * goal_pose.y; - - present_pose_.distance_to_goal = sqrt(pow((Leq_.Gj.x - query_pose.x),2) + pow((Leq_.Gj.y - query_pose.y),2)); - present_pose_.distance_to_start = sqrt(pow((Leq_.Gi.x - query_pose.x),2) + pow((Leq_.Gi.y - query_pose.y),2)); - present_pose_.distace_start_goal = sqrt(pow((Leq_.Gj.x - Leq_.Gi.x),2) + pow((Leq_.Gj.y - Leq_.Gi.y),2)); - // ROS_INFO_THROTTLE(0.2, "Goal checker %f %f %f %f %f", Leq_.Gj.x, Leq_.Gj.y, Leq_.Gj.theta, query_pose.x, query_pose.y); - - return (Leq_l.a * query_pose.x + Leq_l.b * query_pose.y + Leq_l.c ) / (sqrt(pow(Leq_l.a, 2) + pow(Leq_l.b, 2))); -} - -} // namespace mkt_plugins +#include "mkt_plugins/equation_line.h" +#include +#include + +namespace mkt_plugins +{ + +bool LineGenerator::calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point) +{ + /** + * Phương trình đường thẳng có dạng: + * (y - yi)/(yj - yi) = (x - xi)/(xj - xi) + */ + Leq_.Gi = start_point; Leq_.Gj = end_point; + Leq_.a = (Leq_.Gj.y - Leq_.Gi.y); + Leq_.b = (Leq_.Gi.x - Leq_.Gj.x); + Leq_.c = (Leq_.Gj.x * Leq_.Gi.y - Leq_.Gi.x * Leq_.Gj.y); + + return Leq_.a != 0 || Leq_.b !=0; +} + +void LineGenerator::calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev) +{ + float pha = rev? M_PI : 0; + float Yaw_rad = pose.theta - pha; + +/* + * Tính tọa độ điểm R +*/ + float G_xr = float(pose.x); + float G_yr = float(pose.y); + +/* + * Tính tọa độ điểm H +*/ + present_pose_.Gxh = G_xr + Lm * cos(Yaw_rad); + present_pose_.Gyh = G_yr + Lm * sin(Yaw_rad); + +/** + * Phương trình đường thẳng (rh) có dạng: + * (y - yr)/(yh - yr) = (x - xr)/(xh - xr) +*/ + float A_rh = (present_pose_.Gyh - G_yr); + float B_rh = (G_xr - present_pose_.Gxh); + float C_rh = (present_pose_.Gxh * G_yr - G_xr * present_pose_.Gyh); +/* + * Phương trình đường thẳng vuông góc (y - yr)/(yh - yr) = (x - xr)/(xh - xr) + * và đi qua Gh có dạng: + * -B_rh*(x - Gxh) + Arh*(y - Gyh) = 0 +*/ + float A_he = -B_rh; + float B_he = A_rh; + float C_he = (-B_rh) * (-present_pose_.Gxh) + A_rh * (-present_pose_.Gyh); +/* + * Đường thẳng (he) giao với đường thẳng (ij) tại e + * vậy G_xe và G_ye là nghiệm của hệ phương trình 2 ẩn của 2 đường thẳng trên: +*/ + float D = A_he * Leq_.b - Leq_.a * B_he; + float Dx = (-C_he) * Leq_.b - (-Leq_.c) * B_he; + float Dy = A_he * (-Leq_.c) - Leq_.a * (-C_he); +/* + * Tính tọa độ điểm E +*/ + if(D == 0) { + if(Dx + Dy == 0) + { +/* + * Vì hai đường thẳng trùng nhau nên sai số giữa robot và đường đi là bằng 0 +*/ + present_pose_.error_line = 0; + } + else throw NoSolution(); + } + else + { + float G_xe = Dx/D; + float G_ye = Dy/D; +/* + * Tính khoảng cách từ điểm E đến đường thẳng (RH) +*/ + present_pose_.error_line = -(A_rh * G_xe + B_rh * G_ye + C_rh) / (sqrt(pow(A_rh, 2) + pow(B_rh, 2))); + } + // present_pose_.error_line = (Leq.a * present_pose_.Gxh + Leq.b * present_pose_.Gyh + Leq.c) / (sqrt(pow(Leq.a, 2) + pow(Leq.b, 2))); + present_pose_.distance_to_goal = sqrt(pow((Leq_.Gj.x - G_xr),2) + pow((Leq_.Gj.y - G_yr),2)); + present_pose_.distance_to_start = sqrt(pow((Leq_.Gi.x - G_xr),2) + pow((Leq_.Gi.y - G_yr),2)); + + +} + +double LineGenerator::calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose) +{ + /** + * Phương trình đường thẳng có dạng: + * (y - yi)/(yj - yi) = (x - xi)/(xj - xi) + */ + // LineEquation Leq; + // Leq.Gi = query_pose; Leq.Gj = goal_pose; + // Leq.a = (Leq.Gj.y - Leq.Gi.y); + // Leq.b = (Leq.Gi.x - Leq.Gj.x); + // Leq.c = (Leq.Gj.x * Leq.Gi.y - Leq.Gi.x * Leq.Gj.y); + + /** + * Phương trình đường thẳng vuông góc + */ + LineEquation Leq_l; + Leq_l.a = -Leq_.b; + Leq_l.b = Leq_.a; + Leq_l.c = Leq_.b * goal_pose.x - Leq_.a * goal_pose.y; + + present_pose_.distance_to_goal = sqrt(pow((Leq_.Gj.x - query_pose.x),2) + pow((Leq_.Gj.y - query_pose.y),2)); + present_pose_.distance_to_start = sqrt(pow((Leq_.Gi.x - query_pose.x),2) + pow((Leq_.Gi.y - query_pose.y),2)); + present_pose_.distace_start_goal = sqrt(pow((Leq_.Gj.x - Leq_.Gi.x),2) + pow((Leq_.Gj.y - Leq_.Gi.y),2)); + // ROS_INFO_THROTTLE(0.2, "Goal checker %f %f %f %f %f", Leq_.Gj.x, Leq_.Gj.y, Leq_.Gj.theta, query_pose.x, query_pose.y); + + return (Leq_l.a * query_pose.x + Leq_l.b * query_pose.y + Leq_l.c ) / (sqrt(pow(Leq_l.a, 2) + pow(Leq_l.b, 2))); +} + +} // namespace mkt_plugins diff --git a/src/Algorithms/Libraries/mkt_plugins/src/goal_checker.cpp b/src/Algorithms/Libraries/mkt_plugins/src/goal_checker.cpp index 2548090..a23f3de 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/goal_checker.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/goal_checker.cpp @@ -1,115 +1,115 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -mkt_plugins::GoalChecker::GoalChecker() - : nh_(), - line_generator_(nullptr), - yaw_goal_tolerance_(0.25), - xy_goal_tolerance_(0.25), - old_xy_goal_tolerance_(0.0) -{ -} - -void mkt_plugins::GoalChecker::initialize(const robot::NodeHandle &nh) -{ - nh_ = nh; - this->intParam(nh); - robot::log_info_at(__FILE__, __LINE__, "[GoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f", xy_goal_tolerance_, yaw_goal_tolerance_); - line_generator_ = std::make_shared(); -} - -void mkt_plugins::GoalChecker::intParam(const robot::NodeHandle &nh) -{ - if (!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) - { - xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); - } - if (!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) - { - yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); - } -} - -void mkt_plugins::GoalChecker::reset() -{ - old_xy_goal_tolerance_ = 0; -} - -bool mkt_plugins::GoalChecker::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose, - const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) -{ - this->intParam(nh_); - double dx = query_pose.pose.x - goal_pose.pose.x; - double dy = query_pose.pose.y - goal_pose.pose.y; - double xy_tolerance = std::abs(std::sqrt(dx * dx + dy * dy)); - - if (!path.poses.empty() && path.poses.size() > 2) - { - double theta = angles::normalize_angle(query_pose.pose.theta - goal_pose.pose.theta); - for(int i = path.poses.size() - 1; i >= 0; i--) - { - double dx = path.poses[i].pose.x - path.poses.back().pose .x; - double dy = path.poses[i].pose.y - path.poses.back().pose.y; - if(std::sqrt(dx * dx + dy * dy) > 0.05 // TODO: get resolution from costmap - && fabs(dx) > 1e-6 && fabs(dy) > 1e-6) - { - theta = angles::normalize_angle(query_pose.pose.theta - atan2(dy, dx)); - break; - } - } - double x = cos(goal_pose.pose.theta) * dx + sin(goal_pose.pose.theta) * dy; - double y = -sin(goal_pose.pose.theta) * dx + cos(goal_pose.pose.theta) * dy; - if (xy_tolerance <= xy_goal_tolerance_ + 0.1) - { - double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; - if(fabs(tolerance) <= xy_goal_tolerance_) - { - robot::log_info_at(__FILE__, __LINE__, "%.3f %.3f %.3f %.3f %.3f", fabs(cos(theta)), fabs(sin(theta)),xy_tolerance, xy_goal_tolerance_, yaw_goal_tolerance_); - robot::log_info_at(__FILE__, __LINE__, "Goal checker 1 ok %.3f %.3f %.3f %.3f %.3f ", tolerance, old_xy_goal_tolerance_, x, y, theta); - return true; - } - } - else - old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; - } - else - { - double theta = angles::normalize_angle(query_pose.pose.theta - goal_pose.pose.theta); - double x = cos(goal_pose.pose.theta) * dx + sin(goal_pose.pose.theta) * dy; - double y = -sin(goal_pose.pose.theta) * dx + cos(goal_pose.pose.theta) * dy; - if (xy_tolerance <= xy_goal_tolerance_ + 0.1) - { - double tolerance = fabs(x) > fabs(y) ? x : y; - if( - (fabs(tolerance) <= xy_goal_tolerance_ || tolerance * old_xy_goal_tolerance_ < 0) - ) - { - robot::log_info_at(__FILE__, __LINE__, "%f %f", fabs(cos(theta)), fabs(sin(theta))); - robot::log_info_at(__FILE__, __LINE__, "Goal checker 2 ok %f %f %f %f %f ", tolerance, old_xy_goal_tolerance_, x, y, theta); - return true; - } - } - else - old_xy_goal_tolerance_ = fabs(x) > fabs(y) ? x : y; - } - - if (xy_tolerance <= xy_goal_tolerance_) - { - robot::log_info_at(__FILE__, __LINE__, "Goal checker ok %f %f", xy_tolerance, xy_goal_tolerance_); - return true; - } - return false; -} - -score_algorithm::GoalChecker::Ptr mkt_plugins::GoalChecker::create() -{ - return std::make_shared(); -} - +#include +#include +#include +#include +#include +#include +#include +#include + +mkt_plugins::GoalChecker::GoalChecker() + : nh_(), + line_generator_(nullptr), + yaw_goal_tolerance_(0.25), + xy_goal_tolerance_(0.25), + old_xy_goal_tolerance_(0.0) +{ +} + +void mkt_plugins::GoalChecker::initialize(const robot::NodeHandle &nh) +{ + nh_ = nh; + this->intParam(nh); + robot::log_info_at(__FILE__, __LINE__, "[GoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f", xy_goal_tolerance_, yaw_goal_tolerance_); + line_generator_ = std::make_shared(); +} + +void mkt_plugins::GoalChecker::intParam(const robot::NodeHandle &nh) +{ + if (!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) + { + xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); + } + if (!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) + { + yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); + } +} + +void mkt_plugins::GoalChecker::reset() +{ + old_xy_goal_tolerance_ = 0; +} + +bool mkt_plugins::GoalChecker::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose, + const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) +{ + this->intParam(nh_); + double dx = query_pose.pose.x - goal_pose.pose.x; + double dy = query_pose.pose.y - goal_pose.pose.y; + double xy_tolerance = std::abs(std::sqrt(dx * dx + dy * dy)); + + if (!path.poses.empty() && path.poses.size() > 2) + { + double theta = angles::normalize_angle(query_pose.pose.theta - goal_pose.pose.theta); + for(int i = path.poses.size() - 1; i >= 0; i--) + { + double dx = path.poses[i].pose.x - path.poses.back().pose .x; + double dy = path.poses[i].pose.y - path.poses.back().pose.y; + if(std::sqrt(dx * dx + dy * dy) > 0.05 // TODO: get resolution from costmap + && fabs(dx) > 1e-6 && fabs(dy) > 1e-6) + { + theta = angles::normalize_angle(query_pose.pose.theta - atan2(dy, dx)); + break; + } + } + double x = cos(goal_pose.pose.theta) * dx + sin(goal_pose.pose.theta) * dy; + double y = -sin(goal_pose.pose.theta) * dx + cos(goal_pose.pose.theta) * dy; + if (xy_tolerance <= xy_goal_tolerance_ + 0.1) + { + double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; + if(fabs(tolerance) <= xy_goal_tolerance_) + { + robot::log_info_at(__FILE__, __LINE__, "%.3f %.3f %.3f %.3f %.3f", fabs(cos(theta)), fabs(sin(theta)),xy_tolerance, xy_goal_tolerance_, yaw_goal_tolerance_); + robot::log_info_at(__FILE__, __LINE__, "Goal checker 1 ok %.3f %.3f %.3f %.3f %.3f ", tolerance, old_xy_goal_tolerance_, x, y, theta); + return true; + } + } + else + old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; + } + else + { + double theta = angles::normalize_angle(query_pose.pose.theta - goal_pose.pose.theta); + double x = cos(goal_pose.pose.theta) * dx + sin(goal_pose.pose.theta) * dy; + double y = -sin(goal_pose.pose.theta) * dx + cos(goal_pose.pose.theta) * dy; + if (xy_tolerance <= xy_goal_tolerance_ + 0.1) + { + double tolerance = fabs(x) > fabs(y) ? x : y; + if( + (fabs(tolerance) <= xy_goal_tolerance_ || tolerance * old_xy_goal_tolerance_ < 0) + ) + { + robot::log_info_at(__FILE__, __LINE__, "%f %f", fabs(cos(theta)), fabs(sin(theta))); + robot::log_info_at(__FILE__, __LINE__, "Goal checker 2 ok %f %f %f %f %f ", tolerance, old_xy_goal_tolerance_, x, y, theta); + return true; + } + } + else + old_xy_goal_tolerance_ = fabs(x) > fabs(y) ? x : y; + } + + if (xy_tolerance <= xy_goal_tolerance_) + { + robot::log_info_at(__FILE__, __LINE__, "Goal checker ok %f %f", xy_tolerance, xy_goal_tolerance_); + return true; + } + return false; +} + +score_algorithm::GoalChecker::Ptr mkt_plugins::GoalChecker::create() +{ + return std::make_shared(); +} + BOOST_DLL_ALIAS(mkt_plugins::GoalChecker::create, GoalChecker) \ No newline at end of file diff --git a/src/Algorithms/Libraries/mkt_plugins/src/kinematic_parameters.cpp b/src/Algorithms/Libraries/mkt_plugins/src/kinematic_parameters.cpp index dfd45dd..1bb07d3 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/kinematic_parameters.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/kinematic_parameters.cpp @@ -1,243 +1,243 @@ -#include -#include -#include -#include -#include - - -using robot_nav_2d_utils::moveDeprecatedParameter; - -namespace mkt_plugins -{ - - const double EPSILON = 1E-5; - - /** - * @brief Helper function to set the deceleration to the negative acceleration if it was not already set. - * @param nh NodeHandle - * @param dimension String representing the dimension, used in constructing parameter names - */ - void setDecelerationAsNeeded(const robot::NodeHandle &nh, const std::string dimension) - { - std::string decel_param = "decel_lim_" + dimension; - if (nh.hasParam(decel_param)) - return; - - std::string accel_param = "acc_lim_" + dimension; - if (!nh.hasParam(accel_param)) - return; - - double accel; - nh.getParam(accel_param, accel); - nh.setParam(decel_param, -accel); - } - - KinematicParameters::KinematicParameters() - : xytheta_direct_(), - min_vel_x_(0.0), - min_vel_y_(0.0), - max_vel_x_(0.0), - max_vel_y_(0.0), - max_vel_theta_(0.0), - min_speed_xy_(0.0), - max_speed_xy_(0.0), - min_speed_theta_(0.0), - acc_lim_x_(0.0), - acc_lim_y_(0.0), - acc_lim_theta_(0.0), - decel_lim_x_(0.0), - decel_lim_y_(0.0), - decel_lim_theta_(0.0), - min_speed_xy_sq_(0.0), - max_speed_xy_sq_(0.0), - original_min_vel_x_(0.0), - original_min_vel_y_(0.0), - original_max_vel_x_(0.0), - original_max_vel_y_(0.0), - original_max_vel_theta_(0.0), - original_min_speed_xy_(0.0), - original_max_speed_xy_(0.0), - original_min_speed_theta_(0.0), - original_acc_lim_x_(0.0), - original_acc_lim_y_(0.0), - original_acc_lim_theta_(0.0), - original_decel_lim_x_(0.0), - original_decel_lim_y_(0.0), - original_decel_lim_theta_(0.0) - { - } - - KinematicParameters::~KinematicParameters() - { - } - - void KinematicParameters::initialize(const robot::NodeHandle &nh) - { - // Special handling for renamed parameters - moveDeprecatedParameter(nh, "max_vel_theta", "max_rot_vel"); - moveDeprecatedParameter(nh, "min_speed_xy", "min_trans_vel"); - moveDeprecatedParameter(nh, "max_speed_xy", "max_trans_vel"); - moveDeprecatedParameter(nh, "min_speed_theta", "min_rot_vel"); - - // Set the deceleration parameters to negative the acceleration if the deceleration not already specified - setDecelerationAsNeeded(nh, "x"); - setDecelerationAsNeeded(nh, "y"); - setDecelerationAsNeeded(nh, "theta"); - - configure(nh); - xytheta_direct_[0] = xytheta_direct_[1] = xytheta_direct_[2] = 1; - } - - - void KinematicParameters::configure(const robot::NodeHandle &nh) - { - nh.param("max_vel_x", original_max_vel_x_, 0.0); - nh.param("max_vel_y", original_max_vel_y_, 0.0); - nh.param("max_vel_theta", original_max_vel_theta_, 0.0); - nh.param("min_vel_x", original_min_vel_x_, 0.0); - nh.param("min_vel_y", original_min_vel_y_, 0.0); - nh.param("min_speed_xy", original_min_speed_xy_, 0.0); - nh.param("max_speed_xy", original_max_speed_xy_, 0.0); - nh.param("min_speed_theta", original_min_speed_theta_, 0.0); - nh.param("acc_lim_x", original_acc_lim_x_, 0.0); - nh.param("acc_lim_y", original_acc_lim_y_, 0.0); - nh.param("acc_lim_theta", original_acc_lim_theta_, 0.0); - nh.param("decel_lim_x", original_decel_lim_x_, 0.0); - nh.param("decel_lim_y", original_decel_lim_y_, 0.0); - nh.param("decel_lim_theta", original_decel_lim_theta_, 0.0); - reconfigure(nh); - } - - void KinematicParameters::reconfigure(const robot::NodeHandle &nh) - { - nh.param("max_vel_x", max_vel_x_, 0.0); - nh.param("max_vel_y", max_vel_y_, 0.0); - nh.param("max_vel_theta", max_vel_theta_, 0.0); - nh.param("min_vel_x", min_vel_x_, 0.0); - nh.param("min_vel_y", min_vel_y_, 0.0); - nh.param("min_speed_xy", min_speed_xy_, 0.0); - nh.param("max_speed_xy", max_speed_xy_, 0.0); - nh.param("min_speed_theta", min_speed_theta_, 0.0); - nh.param("acc_lim_x", acc_lim_x_, 0.0); - nh.param("acc_lim_y", acc_lim_y_, 0.0); - nh.param("acc_lim_theta", acc_lim_theta_, 0.0); - nh.param("decel_lim_x", decel_lim_x_, 0.0); - nh.param("decel_lim_y", decel_lim_y_, 0.0); - nh.param("decel_lim_theta", decel_lim_theta_, 0.0); - } - - void KinematicParameters::setDirect(int *xytheta_direct) - { - xytheta_direct_[0] = xytheta_direct[0]; - xytheta_direct_[1] = xytheta_direct[1]; - xytheta_direct_[2] = xytheta_direct[2]; - } - - bool KinematicParameters::isValidSpeed(double x, double y, double theta) - { - double vmag_sq = x * x + y * y; - if (max_speed_xy_ >= 0.0 && vmag_sq > max_speed_xy_sq_ + EPSILON) - return false; - if (min_speed_xy_ >= 0.0 && vmag_sq + EPSILON < min_speed_xy_sq_ && - min_speed_theta_ >= 0.0 && fabs(theta) + EPSILON < min_speed_theta_) - return false; - if (vmag_sq == 0.0 && theta == 0.0) - return false; - return true; - } - - int *KinematicParameters::getDirect() { return xytheta_direct_; } - - double KinematicParameters::getMinX() { return min_vel_x_; } - - double KinematicParameters::getMaxX() { return max_vel_x_; } - - double KinematicParameters::getAccX() { return acc_lim_x_; } - - double KinematicParameters::getDecelX() { return decel_lim_x_; } - - double KinematicParameters::getMinY() { return min_vel_y_; } - - double KinematicParameters::getMaxY() { return max_vel_y_; } - - double KinematicParameters::getAccY() { return acc_lim_y_; } - - double KinematicParameters::getDecelY() { return decel_lim_y_; } - - double KinematicParameters::getMinSpeedXY() { return min_speed_xy_; } - - double KinematicParameters::getMinTheta() { return -max_vel_theta_; } - - double KinematicParameters::getMaxTheta() { return max_vel_theta_; } - - double KinematicParameters::getAccTheta() { return acc_lim_theta_; } - - double KinematicParameters::getDecelTheta() { return decel_lim_theta_; } - - double KinematicParameters::getMinSpeedTheta() { return min_speed_theta_; } - - void KinematicParameters::setMinX(double value) - { - min_vel_x_ = fabs(value) < fabs(original_min_vel_x_) + EPSILON ? value : min_vel_x_; - } - - void KinematicParameters::setMaxX(double value) - { - max_vel_x_ = fabs(value) <= fabs(original_max_vel_x_) + EPSILON ? value : original_max_vel_x_; - } - - void KinematicParameters::setAccX(double value) - { - acc_lim_x_ = fabs(value) <= fabs(original_acc_lim_x_) + EPSILON ? value : acc_lim_x_; - } - - void KinematicParameters::setDecelX(double value) - { - decel_lim_x_ = fabs(value) <= fabs(original_decel_lim_x_) + EPSILON ? value : decel_lim_x_; - } - - void KinematicParameters::setMinY(double value) - { - min_vel_y_ = fabs(value) <= fabs(original_min_vel_y_) + EPSILON ? value : min_vel_y_; - } - - void KinematicParameters::setMaxY(double value) - { - max_vel_y_ = fabs(value) <= fabs(original_max_vel_y_) + EPSILON ? value : max_vel_y_; - } - - void KinematicParameters::setAccY(double value) - { - acc_lim_y_ = fabs(value) <= fabs(original_acc_lim_y_) + EPSILON ? value : acc_lim_y_; - } - - void KinematicParameters::setDecelY(double value) - { - decel_lim_y_ = fabs(value) <= fabs(original_decel_lim_y_) + EPSILON ? value : decel_lim_y_; - } - - void KinematicParameters::setMinSpeedXY(double value) - { - min_speed_xy_ = fabs(value) <= fabs(original_min_speed_xy_) + EPSILON ? value : min_speed_xy_; - } - - void KinematicParameters::setMaxTheta(double value) - { - max_vel_theta_ = fabs(value) <= fabs(original_max_vel_theta_) + EPSILON? value : original_max_vel_theta_; - } - - void KinematicParameters::setAccTheta(double value) - { - acc_lim_theta_ = fabs(value) <= fabs(original_acc_lim_theta_) + EPSILON ? value : acc_lim_theta_; - } - - void KinematicParameters::setDecelTheta(double value) - { - decel_lim_theta_ = fabs(value) <= fabs(original_decel_lim_theta_) + EPSILON ? value : decel_lim_theta_; - } - - void KinematicParameters::setMinSpeedTheta(double value) - { - min_speed_theta_ = fabs(value) <= fabs(original_min_speed_theta_) + EPSILON ? value : min_speed_theta_; - } -} // namespace mkt_plugins +#include +#include +#include +#include +#include + + +using robot_nav_2d_utils::moveDeprecatedParameter; + +namespace mkt_plugins +{ + + const double EPSILON = 1E-5; + + /** + * @brief Helper function to set the deceleration to the negative acceleration if it was not already set. + * @param nh NodeHandle + * @param dimension String representing the dimension, used in constructing parameter names + */ + void setDecelerationAsNeeded(const robot::NodeHandle &nh, const std::string dimension) + { + std::string decel_param = "decel_lim_" + dimension; + if (nh.hasParam(decel_param)) + return; + + std::string accel_param = "acc_lim_" + dimension; + if (!nh.hasParam(accel_param)) + return; + + double accel; + nh.getParam(accel_param, accel); + nh.setParam(decel_param, -accel); + } + + KinematicParameters::KinematicParameters() + : xytheta_direct_(), + min_vel_x_(0.0), + min_vel_y_(0.0), + max_vel_x_(0.0), + max_vel_y_(0.0), + max_vel_theta_(0.0), + min_speed_xy_(0.0), + max_speed_xy_(0.0), + min_speed_theta_(0.0), + acc_lim_x_(0.0), + acc_lim_y_(0.0), + acc_lim_theta_(0.0), + decel_lim_x_(0.0), + decel_lim_y_(0.0), + decel_lim_theta_(0.0), + min_speed_xy_sq_(0.0), + max_speed_xy_sq_(0.0), + original_min_vel_x_(0.0), + original_min_vel_y_(0.0), + original_max_vel_x_(0.0), + original_max_vel_y_(0.0), + original_max_vel_theta_(0.0), + original_min_speed_xy_(0.0), + original_max_speed_xy_(0.0), + original_min_speed_theta_(0.0), + original_acc_lim_x_(0.0), + original_acc_lim_y_(0.0), + original_acc_lim_theta_(0.0), + original_decel_lim_x_(0.0), + original_decel_lim_y_(0.0), + original_decel_lim_theta_(0.0) + { + } + + KinematicParameters::~KinematicParameters() + { + } + + void KinematicParameters::initialize(const robot::NodeHandle &nh) + { + // Special handling for renamed parameters + moveDeprecatedParameter(nh, "max_vel_theta", "max_rot_vel"); + moveDeprecatedParameter(nh, "min_speed_xy", "min_trans_vel"); + moveDeprecatedParameter(nh, "max_speed_xy", "max_trans_vel"); + moveDeprecatedParameter(nh, "min_speed_theta", "min_rot_vel"); + + // Set the deceleration parameters to negative the acceleration if the deceleration not already specified + setDecelerationAsNeeded(nh, "x"); + setDecelerationAsNeeded(nh, "y"); + setDecelerationAsNeeded(nh, "theta"); + + configure(nh); + xytheta_direct_[0] = xytheta_direct_[1] = xytheta_direct_[2] = 1; + } + + + void KinematicParameters::configure(const robot::NodeHandle &nh) + { + nh.param("max_vel_x", original_max_vel_x_, 0.0); + nh.param("max_vel_y", original_max_vel_y_, 0.0); + nh.param("max_vel_theta", original_max_vel_theta_, 0.0); + nh.param("min_vel_x", original_min_vel_x_, 0.0); + nh.param("min_vel_y", original_min_vel_y_, 0.0); + nh.param("min_speed_xy", original_min_speed_xy_, 0.0); + nh.param("max_speed_xy", original_max_speed_xy_, 0.0); + nh.param("min_speed_theta", original_min_speed_theta_, 0.0); + nh.param("acc_lim_x", original_acc_lim_x_, 0.0); + nh.param("acc_lim_y", original_acc_lim_y_, 0.0); + nh.param("acc_lim_theta", original_acc_lim_theta_, 0.0); + nh.param("decel_lim_x", original_decel_lim_x_, 0.0); + nh.param("decel_lim_y", original_decel_lim_y_, 0.0); + nh.param("decel_lim_theta", original_decel_lim_theta_, 0.0); + reconfigure(nh); + } + + void KinematicParameters::reconfigure(const robot::NodeHandle &nh) + { + nh.param("max_vel_x", max_vel_x_, 0.0); + nh.param("max_vel_y", max_vel_y_, 0.0); + nh.param("max_vel_theta", max_vel_theta_, 0.0); + nh.param("min_vel_x", min_vel_x_, 0.0); + nh.param("min_vel_y", min_vel_y_, 0.0); + nh.param("min_speed_xy", min_speed_xy_, 0.0); + nh.param("max_speed_xy", max_speed_xy_, 0.0); + nh.param("min_speed_theta", min_speed_theta_, 0.0); + nh.param("acc_lim_x", acc_lim_x_, 0.0); + nh.param("acc_lim_y", acc_lim_y_, 0.0); + nh.param("acc_lim_theta", acc_lim_theta_, 0.0); + nh.param("decel_lim_x", decel_lim_x_, 0.0); + nh.param("decel_lim_y", decel_lim_y_, 0.0); + nh.param("decel_lim_theta", decel_lim_theta_, 0.0); + } + + void KinematicParameters::setDirect(int *xytheta_direct) + { + xytheta_direct_[0] = xytheta_direct[0]; + xytheta_direct_[1] = xytheta_direct[1]; + xytheta_direct_[2] = xytheta_direct[2]; + } + + bool KinematicParameters::isValidSpeed(double x, double y, double theta) + { + double vmag_sq = x * x + y * y; + if (max_speed_xy_ >= 0.0 && vmag_sq > max_speed_xy_sq_ + EPSILON) + return false; + if (min_speed_xy_ >= 0.0 && vmag_sq + EPSILON < min_speed_xy_sq_ && + min_speed_theta_ >= 0.0 && fabs(theta) + EPSILON < min_speed_theta_) + return false; + if (vmag_sq == 0.0 && theta == 0.0) + return false; + return true; + } + + int *KinematicParameters::getDirect() { return xytheta_direct_; } + + double KinematicParameters::getMinX() { return min_vel_x_; } + + double KinematicParameters::getMaxX() { return max_vel_x_; } + + double KinematicParameters::getAccX() { return acc_lim_x_; } + + double KinematicParameters::getDecelX() { return decel_lim_x_; } + + double KinematicParameters::getMinY() { return min_vel_y_; } + + double KinematicParameters::getMaxY() { return max_vel_y_; } + + double KinematicParameters::getAccY() { return acc_lim_y_; } + + double KinematicParameters::getDecelY() { return decel_lim_y_; } + + double KinematicParameters::getMinSpeedXY() { return min_speed_xy_; } + + double KinematicParameters::getMinTheta() { return -max_vel_theta_; } + + double KinematicParameters::getMaxTheta() { return max_vel_theta_; } + + double KinematicParameters::getAccTheta() { return acc_lim_theta_; } + + double KinematicParameters::getDecelTheta() { return decel_lim_theta_; } + + double KinematicParameters::getMinSpeedTheta() { return min_speed_theta_; } + + void KinematicParameters::setMinX(double value) + { + min_vel_x_ = fabs(value) < fabs(original_min_vel_x_) + EPSILON ? value : min_vel_x_; + } + + void KinematicParameters::setMaxX(double value) + { + max_vel_x_ = fabs(value) <= fabs(original_max_vel_x_) + EPSILON ? value : original_max_vel_x_; + } + + void KinematicParameters::setAccX(double value) + { + acc_lim_x_ = fabs(value) <= fabs(original_acc_lim_x_) + EPSILON ? value : acc_lim_x_; + } + + void KinematicParameters::setDecelX(double value) + { + decel_lim_x_ = fabs(value) <= fabs(original_decel_lim_x_) + EPSILON ? value : decel_lim_x_; + } + + void KinematicParameters::setMinY(double value) + { + min_vel_y_ = fabs(value) <= fabs(original_min_vel_y_) + EPSILON ? value : min_vel_y_; + } + + void KinematicParameters::setMaxY(double value) + { + max_vel_y_ = fabs(value) <= fabs(original_max_vel_y_) + EPSILON ? value : max_vel_y_; + } + + void KinematicParameters::setAccY(double value) + { + acc_lim_y_ = fabs(value) <= fabs(original_acc_lim_y_) + EPSILON ? value : acc_lim_y_; + } + + void KinematicParameters::setDecelY(double value) + { + decel_lim_y_ = fabs(value) <= fabs(original_decel_lim_y_) + EPSILON ? value : decel_lim_y_; + } + + void KinematicParameters::setMinSpeedXY(double value) + { + min_speed_xy_ = fabs(value) <= fabs(original_min_speed_xy_) + EPSILON ? value : min_speed_xy_; + } + + void KinematicParameters::setMaxTheta(double value) + { + max_vel_theta_ = fabs(value) <= fabs(original_max_vel_theta_) + EPSILON? value : original_max_vel_theta_; + } + + void KinematicParameters::setAccTheta(double value) + { + acc_lim_theta_ = fabs(value) <= fabs(original_acc_lim_theta_) + EPSILON ? value : acc_lim_theta_; + } + + void KinematicParameters::setDecelTheta(double value) + { + decel_lim_theta_ = fabs(value) <= fabs(original_decel_lim_theta_) + EPSILON ? value : decel_lim_theta_; + } + + void KinematicParameters::setMinSpeedTheta(double value) + { + min_speed_theta_ = fabs(value) <= fabs(original_min_speed_theta_) + EPSILON ? value : min_speed_theta_; + } +} // namespace mkt_plugins diff --git a/src/Algorithms/Libraries/mkt_plugins/src/limited_accel_generator.cpp b/src/Algorithms/Libraries/mkt_plugins/src/limited_accel_generator.cpp index 1b6e8c6..bd5959a 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/limited_accel_generator.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/limited_accel_generator.cpp @@ -1,59 +1,59 @@ -#include -#include -#include -#include -#include -#include - -namespace mkt_plugins -{ - -LimitedAccelGenerator::LimitedAccelGenerator() - : StandardTrajectoryGenerator(), - acceleration_time_(0.0) -{ -} - -LimitedAccelGenerator::~LimitedAccelGenerator() -{ -} - -void LimitedAccelGenerator::initialize(const robot::NodeHandle& nh) -{ - StandardTrajectoryGenerator::initialize(nh); - if (nh.hasParam("sim_period")) - { - nh.getParam("sim_period", acceleration_time_); - } - else - { - double controller_frequency = robot_nav_2d_utils::searchAndGetParam(nh, "controller_frequency", 20.0); - robot::log_warning("[%s:%d] limited_accel_generator: %f", __FILE__, __LINE__, controller_frequency); - if (controller_frequency > 0) - { - acceleration_time_ = 1.0 / controller_frequency; - } - else - { - robot::log_warning_at(__FILE__, __LINE__, "A controller_frequency less than or equal to 0 has been set. " - "Ignoring the parameter, assuming a rate of 20Hz"); - acceleration_time_ = 0.05; - } - } - -} - -void LimitedAccelGenerator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity) -{ - // Limit our search space to just those within the limited acceleration_time - velocity_iterator_->startNewIteration(current_velocity, acceleration_time_); -} - - score_algorithm::TrajectoryGenerator::Ptr LimitedAccelGenerator::create() - { - return std::make_shared(); - } - -} // namespace mkt_plugins - -BOOST_DLL_ALIAS(mkt_plugins::LimitedAccelGenerator::create, LimitedAccelGenerator) +#include +#include +#include +#include +#include +#include + +namespace mkt_plugins +{ + +LimitedAccelGenerator::LimitedAccelGenerator() + : StandardTrajectoryGenerator(), + acceleration_time_(0.0) +{ +} + +LimitedAccelGenerator::~LimitedAccelGenerator() +{ +} + +void LimitedAccelGenerator::initialize(const robot::NodeHandle& nh) +{ + StandardTrajectoryGenerator::initialize(nh); + if (nh.hasParam("sim_period")) + { + nh.getParam("sim_period", acceleration_time_); + } + else + { + double controller_frequency = robot_nav_2d_utils::searchAndGetParam(nh, "controller_frequency", 20.0); + robot::log_warning("[%s:%d] limited_accel_generator: %f", __FILE__, __LINE__, controller_frequency); + if (controller_frequency > 0) + { + acceleration_time_ = 1.0 / controller_frequency; + } + else + { + robot::log_warning_at(__FILE__, __LINE__, "A controller_frequency less than or equal to 0 has been set. " + "Ignoring the parameter, assuming a rate of 20Hz"); + acceleration_time_ = 0.05; + } + } + +} + +void LimitedAccelGenerator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity) +{ + // Limit our search space to just those within the limited acceleration_time + velocity_iterator_->startNewIteration(current_velocity, acceleration_time_); +} + + score_algorithm::TrajectoryGenerator::Ptr LimitedAccelGenerator::create() + { + return std::make_shared(); + } + +} // namespace mkt_plugins + +BOOST_DLL_ALIAS(mkt_plugins::LimitedAccelGenerator::create, LimitedAccelGenerator) diff --git a/src/Algorithms/Libraries/mkt_plugins/src/simple_goal_checker.cpp b/src/Algorithms/Libraries/mkt_plugins/src/simple_goal_checker.cpp index fa26177..df4b827 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/simple_goal_checker.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/simple_goal_checker.cpp @@ -1,81 +1,81 @@ -#include -#include -#include -#include -#include - -namespace mkt_plugins -{ - -SimpleGoalChecker::SimpleGoalChecker() - : nh_(), - xy_goal_tolerance_(0.25), - yaw_goal_tolerance_(0.25), - stateful_(true), - check_xy_(true), - xy_goal_tolerance_sq_(0.0625) -{ -} - -void SimpleGoalChecker::initialize(const robot::NodeHandle& nh) -{ - nh_ = nh; - this->intParam(nh); - robot::log_info_at(__FILE__, __LINE__, "[SimpleGoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f stateful %x check_xy_ %x" , xy_goal_tolerance_, yaw_goal_tolerance_, stateful_, check_xy_); -} - -void SimpleGoalChecker::intParam(const robot::NodeHandle& nh) -{ - if(!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) - { - xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); - } - if(!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) - { - yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); - } - if(nh.param("stateful", stateful_, true)) - { - stateful_ = robot_nav_2d_utils::searchAndGetParam(nh, "stateful", true); - } - robot::log_info_throttle(1.0,"[SimpleGoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f stateful %x check_xy_ %x" , xy_goal_tolerance_, yaw_goal_tolerance_, stateful_, check_xy_); - xy_goal_tolerance_sq_ = xy_goal_tolerance_ * xy_goal_tolerance_; -} - -void SimpleGoalChecker::reset() -{ - check_xy_ = true; -} - -bool SimpleGoalChecker::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& query_pose, const robot_nav_2d_msgs::Pose2DStamped& goal_pose, - const robot_nav_2d_msgs::Path2D& path, const robot_nav_2d_msgs::Twist2D& velocity) -{ - this->intParam(nh_); - if (check_xy_) - { - double dx = query_pose.pose.x - goal_pose.pose.x, - dy = query_pose.pose.y - goal_pose.pose.y; - if (dx * dx + dy * dy > 0.25) - { - return false; - } - // We are within the window - // If we are stateful, change the state. - if (stateful_) - { - check_xy_ = false; - } - } - double dyaw = angles::shortest_angular_distance(query_pose.pose.theta, goal_pose.pose.theta); - // robot::log_info_throttle(1.0, "dyaw %f yaw_goal_tolerance_ %f", fabs(dyaw), yaw_goal_tolerance_); - return fabs(dyaw) < yaw_goal_tolerance_; -} - -} // namespace mkt_plugins - -score_algorithm::GoalChecker::Ptr mkt_plugins::SimpleGoalChecker::create() -{ - return std::make_shared(); -} - -BOOST_DLL_ALIAS(mkt_plugins::SimpleGoalChecker::create, SimpleGoalChecker) +#include +#include +#include +#include +#include + +namespace mkt_plugins +{ + +SimpleGoalChecker::SimpleGoalChecker() + : nh_(), + xy_goal_tolerance_(0.25), + yaw_goal_tolerance_(0.25), + stateful_(true), + check_xy_(true), + xy_goal_tolerance_sq_(0.0625) +{ +} + +void SimpleGoalChecker::initialize(const robot::NodeHandle& nh) +{ + nh_ = nh; + this->intParam(nh); + robot::log_info_at(__FILE__, __LINE__, "[SimpleGoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f stateful %x check_xy_ %x" , xy_goal_tolerance_, yaw_goal_tolerance_, stateful_, check_xy_); +} + +void SimpleGoalChecker::intParam(const robot::NodeHandle& nh) +{ + if(!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) + { + xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); + } + if(!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) + { + yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); + } + if(nh.param("stateful", stateful_, true)) + { + stateful_ = robot_nav_2d_utils::searchAndGetParam(nh, "stateful", true); + } + robot::log_info_throttle(1.0,"[SimpleGoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f stateful %x check_xy_ %x" , xy_goal_tolerance_, yaw_goal_tolerance_, stateful_, check_xy_); + xy_goal_tolerance_sq_ = xy_goal_tolerance_ * xy_goal_tolerance_; +} + +void SimpleGoalChecker::reset() +{ + check_xy_ = true; +} + +bool SimpleGoalChecker::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& query_pose, const robot_nav_2d_msgs::Pose2DStamped& goal_pose, + const robot_nav_2d_msgs::Path2D& path, const robot_nav_2d_msgs::Twist2D& velocity) +{ + this->intParam(nh_); + if (check_xy_) + { + double dx = query_pose.pose.x - goal_pose.pose.x, + dy = query_pose.pose.y - goal_pose.pose.y; + if (dx * dx + dy * dy > 0.25) + { + return false; + } + // We are within the window + // If we are stateful, change the state. + if (stateful_) + { + check_xy_ = false; + } + } + double dyaw = angles::shortest_angular_distance(query_pose.pose.theta, goal_pose.pose.theta); + // robot::log_info_throttle(1.0, "dyaw %f yaw_goal_tolerance_ %f", fabs(dyaw), yaw_goal_tolerance_); + return fabs(dyaw) < yaw_goal_tolerance_; +} + +} // namespace mkt_plugins + +score_algorithm::GoalChecker::Ptr mkt_plugins::SimpleGoalChecker::create() +{ + return std::make_shared(); +} + +BOOST_DLL_ALIAS(mkt_plugins::SimpleGoalChecker::create, SimpleGoalChecker) diff --git a/src/Algorithms/Libraries/mkt_plugins/src/standard_traj_generator.cpp b/src/Algorithms/Libraries/mkt_plugins/src/standard_traj_generator.cpp index 581a835..9522393 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/standard_traj_generator.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/standard_traj_generator.cpp @@ -1,287 +1,287 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using robot_nav_2d_utils::loadParameterWithDeprecation; - -namespace mkt_plugins -{ - - StandardTrajectoryGenerator::StandardTrajectoryGenerator() - : nh_kinematics_(), - kinematics_(nullptr), - velocity_iterator_(nullptr), - sim_time_(0.0), - discretize_by_time_(false), - time_granularity_(0.0), - linear_granularity_(0.0), - angular_granularity_(0.0), - include_last_point_(false) - { - } - - StandardTrajectoryGenerator::~StandardTrajectoryGenerator() - { - } - - void StandardTrajectoryGenerator::initialize(const robot::NodeHandle &nh) - { - nh_kinematics_ = nh; - kinematics_ = std::make_shared(); - kinematics_->initialize(nh); - initializeIterator(nh); - - nh.param("sim_time", sim_time_, 1.7); - - nh.param("include_last_point", include_last_point_, true); - /* - * If discretize_by_time, then sim_granularity represents the amount of time that should be between - * two successive points on the trajectory. - * - * If discretize_by_time is false, then sim_granularity is the maximum amount of distance between - * two successive points on the trajectory, and angular_sim_granularity is the maximum amount of - * angular distance between two successive points. - */ - nh.param("discretize_by_time", discretize_by_time_, false); - if (discretize_by_time_) - { - time_granularity_ = loadParameterWithDeprecation(nh, "time_granularity", "sim_granularity", 0.025); - } - else - { - linear_granularity_ = loadParameterWithDeprecation(nh, "linear_granularity", "sim_granularity", 0.025); - angular_granularity_ = loadParameterWithDeprecation(nh, "angular_granularity", "angular_sim_granularity", 0.1); - } - } - - robot::NodeHandle StandardTrajectoryGenerator::getNodeHandle() - { - return nh_kinematics_; - } - - void StandardTrajectoryGenerator::initializeIterator(const robot::NodeHandle &nh) - { - velocity_iterator_ = std::make_shared(); - velocity_iterator_->initialize(nh, kinematics_); - } - - void StandardTrajectoryGenerator::setDirect(int *direct) - { - kinematics_->setDirect(direct); - } - - bool StandardTrajectoryGenerator::setTwistLinear(robot_geometry_msgs::Vector3 linear) - { - try - { - // ROS_INFO("Get linear %f ", linear.x); - if (linear.x > 0) - kinematics_->setMaxX(linear.x); - else if (linear.x < 0) - kinematics_->setMinX(linear.x); - else - { - kinematics_->setMinX(linear.x); - kinematics_->setMaxX(linear.x); - } - - if (linear.y > 0) - kinematics_->setMaxY(linear.y); - else if (linear.y < 0) - kinematics_->setMinY(linear.y); - else - { - kinematics_->setMinY(linear.y); - kinematics_->setMaxY(linear.y); - } - } - catch (const std::exception &e) - { - throw std::exception(e); - return false; - } - - return true; - } - - robot_geometry_msgs::Vector3 StandardTrajectoryGenerator::getTwistLinear(bool direct) - { - robot_geometry_msgs::Vector3 linear; - try - { - if (direct) - { - linear.x = kinematics_->getMaxX(); - linear.y = kinematics_->getMaxY(); - } - else - { - linear.x = kinematics_->getMinX(); - linear.y = kinematics_->getMinY(); - } - } - catch (const std::exception &e) - { - throw std::exception(e); - } - return linear; - } - - bool StandardTrajectoryGenerator::setTwistAngular(robot_geometry_msgs::Vector3 angular) - { - try - { - kinematics_->setMaxTheta(angular.z); - } - catch (const std::exception &e) - { - throw std::exception(e); - return false; - } - return true; - } - - robot_geometry_msgs::Vector3 StandardTrajectoryGenerator::getTwistAngular(bool direct) - { - robot_geometry_msgs::Vector3 angular; - try - { - if (direct) - { - angular.z = kinematics_->getMaxTheta(); - } - else - { - angular.z = kinematics_->getMinTheta(); - } - } - catch (const std::exception &e) - { - throw std::exception(e); - } - return angular; - } - - void StandardTrajectoryGenerator::startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) - { - velocity_iterator_->startNewIteration(current_velocity, sim_time_); - } - - bool StandardTrajectoryGenerator::hasMoreTwists() - { - return velocity_iterator_->hasMoreTwists(); - } - - robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::nextTwist() - { - return velocity_iterator_->nextTwist(); - } - - robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::getTwist() - { - return velocity_iterator_->getTwist(); - } - - std::vector StandardTrajectoryGenerator::getTimeSteps(const robot_nav_2d_msgs::Twist2D &cmd_vel) - { - std::vector steps; - if (discretize_by_time_) - { - steps.resize(ceil(sim_time_ / time_granularity_)); - } - else // discretize by distance - { - double vmag = hypot(cmd_vel.x, cmd_vel.y); - - // the distance the robot would travel in sim_time if it did not change velocity - double projected_linear_distance = vmag * sim_time_; - - // the angle the robot would rotate in sim_time - double projected_angular_distance = fabs(cmd_vel.theta) * sim_time_; - - // Pick the maximum of the two - int num_steps = ceil(std::max(projected_linear_distance / linear_granularity_, - projected_angular_distance / angular_granularity_)); - steps.resize(num_steps); - } - if (steps.size() == 0) - { - steps.resize(1); - } - std::fill(steps.begin(), steps.end(), sim_time_ / steps.size()); - return steps; - } - - mkt_msgs::Trajectory2D StandardTrajectoryGenerator::generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose, - const robot_nav_2d_msgs::Path2D &transformed_plan, - const robot_nav_2d_msgs::Twist2D &start_vel, - const robot_nav_2d_msgs::Twist2D &cmd_vel) - { - mkt_msgs::Trajectory2D traj; - traj.velocity = cmd_vel; - - // simulate the trajectory - robot_geometry_msgs::Pose2D pose = start_pose.pose; - robot_nav_2d_msgs::Twist2D vel = start_vel; - double running_time = 0.0; - std::vector steps = getTimeSteps(cmd_vel); - - for (double dt : steps) - { - traj.poses.push_back(pose); - traj.time_offsets.push_back(robot::Duration(running_time)); - // calculate velocities - vel = computeNewVelocity(cmd_vel, vel, dt); - - // update the position of the robot using the velocities passed in - pose = computeNewPosition(pose, vel, dt); - running_time += dt; - } // end for simulation steps - - if (include_last_point_) - { - traj.poses.push_back(pose); - traj.time_offsets.push_back(robot::Duration(running_time)); - } - - return traj; - } - - /** - * change vel using acceleration limits to converge towards sample_target-vel - */ - robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::computeNewVelocity(const robot_nav_2d_msgs::Twist2D &cmd_vel, - const robot_nav_2d_msgs::Twist2D &start_vel, const double dt) - { - robot_nav_2d_msgs::Twist2D new_vel; - new_vel.x = projectVelocity(start_vel.x, kinematics_->getAccX(), kinematics_->getDecelX(), dt, cmd_vel.x); - new_vel.y = projectVelocity(start_vel.y, kinematics_->getAccY(), kinematics_->getDecelY(), dt, cmd_vel.y); - new_vel.theta = projectVelocity(start_vel.theta, kinematics_->getAccTheta(), kinematics_->getDecelTheta(), - dt, cmd_vel.theta); - return new_vel; - } - - robot_geometry_msgs::Pose2D StandardTrajectoryGenerator::computeNewPosition(const robot_geometry_msgs::Pose2D start_pose, - const robot_nav_2d_msgs::Twist2D &vel, const double dt) - { - robot_geometry_msgs::Pose2D new_pose; - new_pose.x = start_pose.x + (vel.x * cos(start_pose.theta) + vel.y * cos(M_PI_2 + start_pose.theta)) * dt; - new_pose.y = start_pose.y + (vel.x * sin(start_pose.theta) + vel.y * sin(M_PI_2 + start_pose.theta)) * dt; - new_pose.theta = start_pose.theta + vel.theta * dt; - return new_pose; - } - - score_algorithm::TrajectoryGenerator::Ptr StandardTrajectoryGenerator::create() - { - return std::make_shared(); - } -} // namespace mkt_plugins - -BOOST_DLL_ALIAS(mkt_plugins::StandardTrajectoryGenerator::create, StandardTrajectoryGenerator) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using robot_nav_2d_utils::loadParameterWithDeprecation; + +namespace mkt_plugins +{ + + StandardTrajectoryGenerator::StandardTrajectoryGenerator() + : nh_kinematics_(), + kinematics_(nullptr), + velocity_iterator_(nullptr), + sim_time_(0.0), + discretize_by_time_(false), + time_granularity_(0.0), + linear_granularity_(0.0), + angular_granularity_(0.0), + include_last_point_(false) + { + } + + StandardTrajectoryGenerator::~StandardTrajectoryGenerator() + { + } + + void StandardTrajectoryGenerator::initialize(const robot::NodeHandle &nh) + { + nh_kinematics_ = nh; + kinematics_ = std::make_shared(); + kinematics_->initialize(nh); + initializeIterator(nh); + + nh.param("sim_time", sim_time_, 1.7); + + nh.param("include_last_point", include_last_point_, true); + /* + * If discretize_by_time, then sim_granularity represents the amount of time that should be between + * two successive points on the trajectory. + * + * If discretize_by_time is false, then sim_granularity is the maximum amount of distance between + * two successive points on the trajectory, and angular_sim_granularity is the maximum amount of + * angular distance between two successive points. + */ + nh.param("discretize_by_time", discretize_by_time_, false); + if (discretize_by_time_) + { + time_granularity_ = loadParameterWithDeprecation(nh, "time_granularity", "sim_granularity", 0.025); + } + else + { + linear_granularity_ = loadParameterWithDeprecation(nh, "linear_granularity", "sim_granularity", 0.025); + angular_granularity_ = loadParameterWithDeprecation(nh, "angular_granularity", "angular_sim_granularity", 0.1); + } + } + + robot::NodeHandle StandardTrajectoryGenerator::getNodeHandle() + { + return nh_kinematics_; + } + + void StandardTrajectoryGenerator::initializeIterator(const robot::NodeHandle &nh) + { + velocity_iterator_ = std::make_shared(); + velocity_iterator_->initialize(nh, kinematics_); + } + + void StandardTrajectoryGenerator::setDirect(int *direct) + { + kinematics_->setDirect(direct); + } + + bool StandardTrajectoryGenerator::setTwistLinear(robot_geometry_msgs::Vector3 linear) + { + try + { + // ROS_INFO("Get linear %f ", linear.x); + if (linear.x > 0) + kinematics_->setMaxX(linear.x); + else if (linear.x < 0) + kinematics_->setMinX(linear.x); + else + { + kinematics_->setMinX(linear.x); + kinematics_->setMaxX(linear.x); + } + + if (linear.y > 0) + kinematics_->setMaxY(linear.y); + else if (linear.y < 0) + kinematics_->setMinY(linear.y); + else + { + kinematics_->setMinY(linear.y); + kinematics_->setMaxY(linear.y); + } + } + catch (const std::exception &e) + { + throw std::exception(e); + return false; + } + + return true; + } + + robot_geometry_msgs::Vector3 StandardTrajectoryGenerator::getTwistLinear(bool direct) + { + robot_geometry_msgs::Vector3 linear; + try + { + if (direct) + { + linear.x = kinematics_->getMaxX(); + linear.y = kinematics_->getMaxY(); + } + else + { + linear.x = kinematics_->getMinX(); + linear.y = kinematics_->getMinY(); + } + } + catch (const std::exception &e) + { + throw std::exception(e); + } + return linear; + } + + bool StandardTrajectoryGenerator::setTwistAngular(robot_geometry_msgs::Vector3 angular) + { + try + { + kinematics_->setMaxTheta(angular.z); + } + catch (const std::exception &e) + { + throw std::exception(e); + return false; + } + return true; + } + + robot_geometry_msgs::Vector3 StandardTrajectoryGenerator::getTwistAngular(bool direct) + { + robot_geometry_msgs::Vector3 angular; + try + { + if (direct) + { + angular.z = kinematics_->getMaxTheta(); + } + else + { + angular.z = kinematics_->getMinTheta(); + } + } + catch (const std::exception &e) + { + throw std::exception(e); + } + return angular; + } + + void StandardTrajectoryGenerator::startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) + { + velocity_iterator_->startNewIteration(current_velocity, sim_time_); + } + + bool StandardTrajectoryGenerator::hasMoreTwists() + { + return velocity_iterator_->hasMoreTwists(); + } + + robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::nextTwist() + { + return velocity_iterator_->nextTwist(); + } + + robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::getTwist() + { + return velocity_iterator_->getTwist(); + } + + std::vector StandardTrajectoryGenerator::getTimeSteps(const robot_nav_2d_msgs::Twist2D &cmd_vel) + { + std::vector steps; + if (discretize_by_time_) + { + steps.resize(ceil(sim_time_ / time_granularity_)); + } + else // discretize by distance + { + double vmag = hypot(cmd_vel.x, cmd_vel.y); + + // the distance the robot would travel in sim_time if it did not change velocity + double projected_linear_distance = vmag * sim_time_; + + // the angle the robot would rotate in sim_time + double projected_angular_distance = fabs(cmd_vel.theta) * sim_time_; + + // Pick the maximum of the two + int num_steps = ceil(std::max(projected_linear_distance / linear_granularity_, + projected_angular_distance / angular_granularity_)); + steps.resize(num_steps); + } + if (steps.size() == 0) + { + steps.resize(1); + } + std::fill(steps.begin(), steps.end(), sim_time_ / steps.size()); + return steps; + } + + mkt_msgs::Trajectory2D StandardTrajectoryGenerator::generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose, + const robot_nav_2d_msgs::Path2D &transformed_plan, + const robot_nav_2d_msgs::Twist2D &start_vel, + const robot_nav_2d_msgs::Twist2D &cmd_vel) + { + mkt_msgs::Trajectory2D traj; + traj.velocity = cmd_vel; + + // simulate the trajectory + robot_geometry_msgs::Pose2D pose = start_pose.pose; + robot_nav_2d_msgs::Twist2D vel = start_vel; + double running_time = 0.0; + std::vector steps = getTimeSteps(cmd_vel); + + for (double dt : steps) + { + traj.poses.push_back(pose); + traj.time_offsets.push_back(robot::Duration(running_time)); + // calculate velocities + vel = computeNewVelocity(cmd_vel, vel, dt); + + // update the position of the robot using the velocities passed in + pose = computeNewPosition(pose, vel, dt); + running_time += dt; + } // end for simulation steps + + if (include_last_point_) + { + traj.poses.push_back(pose); + traj.time_offsets.push_back(robot::Duration(running_time)); + } + + return traj; + } + + /** + * change vel using acceleration limits to converge towards sample_target-vel + */ + robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::computeNewVelocity(const robot_nav_2d_msgs::Twist2D &cmd_vel, + const robot_nav_2d_msgs::Twist2D &start_vel, const double dt) + { + robot_nav_2d_msgs::Twist2D new_vel; + new_vel.x = projectVelocity(start_vel.x, kinematics_->getAccX(), kinematics_->getDecelX(), dt, cmd_vel.x); + new_vel.y = projectVelocity(start_vel.y, kinematics_->getAccY(), kinematics_->getDecelY(), dt, cmd_vel.y); + new_vel.theta = projectVelocity(start_vel.theta, kinematics_->getAccTheta(), kinematics_->getDecelTheta(), + dt, cmd_vel.theta); + return new_vel; + } + + robot_geometry_msgs::Pose2D StandardTrajectoryGenerator::computeNewPosition(const robot_geometry_msgs::Pose2D start_pose, + const robot_nav_2d_msgs::Twist2D &vel, const double dt) + { + robot_geometry_msgs::Pose2D new_pose; + new_pose.x = start_pose.x + (vel.x * cos(start_pose.theta) + vel.y * cos(M_PI_2 + start_pose.theta)) * dt; + new_pose.y = start_pose.y + (vel.x * sin(start_pose.theta) + vel.y * sin(M_PI_2 + start_pose.theta)) * dt; + new_pose.theta = start_pose.theta + vel.theta * dt; + return new_pose; + } + + score_algorithm::TrajectoryGenerator::Ptr StandardTrajectoryGenerator::create() + { + return std::make_shared(); + } +} // namespace mkt_plugins + +BOOST_DLL_ALIAS(mkt_plugins::StandardTrajectoryGenerator::create, StandardTrajectoryGenerator) diff --git a/src/Algorithms/Libraries/mkt_plugins/src/xy_theta_iterator.cpp b/src/Algorithms/Libraries/mkt_plugins/src/xy_theta_iterator.cpp index c4de3c0..e61857e 100644 --- a/src/Algorithms/Libraries/mkt_plugins/src/xy_theta_iterator.cpp +++ b/src/Algorithms/Libraries/mkt_plugins/src/xy_theta_iterator.cpp @@ -1,92 +1,92 @@ -#include -#include -#include - -namespace mkt_plugins -{ -XYThetaIterator::XYThetaIterator() - : vx_samples_(0), - vy_samples_(0), - vtheta_samples_(0), - kinematics_(nullptr), - x_it_(nullptr), - y_it_(nullptr), - th_it_(nullptr) -{ -} - -XYThetaIterator::~XYThetaIterator() -{ -} - -void XYThetaIterator::initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) -{ - kinematics_ = kinematics; - nh.param("vx_samples", vx_samples_, 20); - nh.param("vy_samples", vy_samples_, 5); - vtheta_samples_ = robot_nav_2d_utils::loadParameterWithDeprecation(nh, "vtheta_samples", "vth_samples", 20); -} - -void XYThetaIterator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) -{ - x_it_ = std::make_shared("x_it_", current_velocity.x, kinematics_->getDirect()[0], kinematics_->getMinX(), kinematics_->getMaxX(), - kinematics_->getAccX(), kinematics_->getDecelX(), dt, vx_samples_); - - y_it_ = std::make_shared("y_it_", current_velocity.y, kinematics_->getDirect()[1], kinematics_->getMinY(), kinematics_->getMaxY(), - kinematics_->getAccY(), kinematics_->getDecelY(), dt, vy_samples_); - - th_it_ = std::make_shared("th_it_", current_velocity.theta, kinematics_->getDirect()[2], kinematics_->getMinTheta(), kinematics_->getMaxTheta(), - kinematics_->getAccTheta(), kinematics_->getDecelTheta(), dt, vtheta_samples_); -} - -bool XYThetaIterator::hasMoreTwists() -{ - return x_it_ && !x_it_->isFinished(); -} - -robot_nav_2d_msgs::Twist2D XYThetaIterator::nextTwist() -{ - robot_nav_2d_msgs::Twist2D velocity; - velocity.x = x_it_->getVelocity(); - velocity.y = y_it_->getVelocity(); - velocity.theta = th_it_->getVelocity(); - iterateToValidVelocity(); - return velocity; -} - -robot_nav_2d_msgs::Twist2D XYThetaIterator::getTwist() -{ - robot_nav_2d_msgs::Twist2D velocity; - velocity.x = x_it_->getVelocity(); - velocity.y = y_it_->getVelocity(); - velocity.theta = th_it_->getVelocity(); - return velocity; -} - -bool XYThetaIterator::isValidVelocity() -{ - return kinematics_->isValidSpeed(x_it_->getVelocity(), y_it_->getVelocity(), th_it_->getVelocity()); -} - -void XYThetaIterator::iterateToValidVelocity() -{ - bool valid = false; - while (!valid && hasMoreTwists()) - { - ++(*th_it_); - if (th_it_->isFinished()) - { - th_it_->reset(); - ++(*y_it_); - if (y_it_->isFinished()) - { - y_it_->reset(); - ++(*x_it_); - } - } - valid = isValidVelocity(); - } -} - -} // namespace mkt_plugins - +#include +#include +#include + +namespace mkt_plugins +{ +XYThetaIterator::XYThetaIterator() + : vx_samples_(0), + vy_samples_(0), + vtheta_samples_(0), + kinematics_(nullptr), + x_it_(nullptr), + y_it_(nullptr), + th_it_(nullptr) +{ +} + +XYThetaIterator::~XYThetaIterator() +{ +} + +void XYThetaIterator::initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) +{ + kinematics_ = kinematics; + nh.param("vx_samples", vx_samples_, 20); + nh.param("vy_samples", vy_samples_, 5); + vtheta_samples_ = robot_nav_2d_utils::loadParameterWithDeprecation(nh, "vtheta_samples", "vth_samples", 20); +} + +void XYThetaIterator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) +{ + x_it_ = std::make_shared("x_it_", current_velocity.x, kinematics_->getDirect()[0], kinematics_->getMinX(), kinematics_->getMaxX(), + kinematics_->getAccX(), kinematics_->getDecelX(), dt, vx_samples_); + + y_it_ = std::make_shared("y_it_", current_velocity.y, kinematics_->getDirect()[1], kinematics_->getMinY(), kinematics_->getMaxY(), + kinematics_->getAccY(), kinematics_->getDecelY(), dt, vy_samples_); + + th_it_ = std::make_shared("th_it_", current_velocity.theta, kinematics_->getDirect()[2], kinematics_->getMinTheta(), kinematics_->getMaxTheta(), + kinematics_->getAccTheta(), kinematics_->getDecelTheta(), dt, vtheta_samples_); +} + +bool XYThetaIterator::hasMoreTwists() +{ + return x_it_ && !x_it_->isFinished(); +} + +robot_nav_2d_msgs::Twist2D XYThetaIterator::nextTwist() +{ + robot_nav_2d_msgs::Twist2D velocity; + velocity.x = x_it_->getVelocity(); + velocity.y = y_it_->getVelocity(); + velocity.theta = th_it_->getVelocity(); + iterateToValidVelocity(); + return velocity; +} + +robot_nav_2d_msgs::Twist2D XYThetaIterator::getTwist() +{ + robot_nav_2d_msgs::Twist2D velocity; + velocity.x = x_it_->getVelocity(); + velocity.y = y_it_->getVelocity(); + velocity.theta = th_it_->getVelocity(); + return velocity; +} + +bool XYThetaIterator::isValidVelocity() +{ + return kinematics_->isValidSpeed(x_it_->getVelocity(), y_it_->getVelocity(), th_it_->getVelocity()); +} + +void XYThetaIterator::iterateToValidVelocity() +{ + bool valid = false; + while (!valid && hasMoreTwists()) + { + ++(*th_it_); + if (th_it_->isFinished()) + { + th_it_->reset(); + ++(*y_it_); + if (y_it_->isFinished()) + { + y_it_->reset(); + ++(*x_it_); + } + } + valid = isValidVelocity(); + } +} + +} // namespace mkt_plugins + diff --git a/src/Algorithms/Packages/global_planners/two_points_planner/package.xml b/src/Algorithms/Packages/global_planners/two_points_planner/package.xml old mode 100644 new mode 100755 diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/CMakeLists.txt b/src/Algorithms/Packages/local_planners/pnkx_local_planner/CMakeLists.txt index 9255f4c..a628c28 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/CMakeLists.txt +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/CMakeLists.txt @@ -1,244 +1,244 @@ -cmake_minimum_required(VERSION 3.0.2) -project(pnkx_local_planner VERSION 1.0.0 LANGUAGES CXX) - -if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) - set(BUILDING_WITH_CATKIN TRUE) - message(STATUS "Building pnkx_local_planner with Catkin") - -else() - set(BUILDING_WITH_CATKIN FALSE) - message(STATUS "Building pnkx_local_planner with Standalone CMake") -endif() - -# C++ Standard - must be set before find_package -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -# Find dependencies -find_package(Boost REQUIRED COMPONENTS system) - -if (NOT BUILDING_WITH_CATKIN) - - # Enable Position Independent Code - set(CMAKE_POSITION_INDEPENDENT_CODE ON) - - # Cấu hình RPATH để tránh cycle trong runtime search path - set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) - set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - - set(PACKAGES_DIR - robot_geometry_msgs - robot_nav_msgs - robot_std_msgs - robot_visualization_msgs - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core2 - mkt_msgs - score_algorithm - robot_costmap_2d - tf3 - robot_tf3_geometry_msgs - data_convert - robot_cpp - angles - ) - - find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) - -else() - -# ======================================================== -# Catkin specific configuration -# ======================================================== - find_package(catkin REQUIRED COMPONENTS - robot_geometry_msgs - robot_nav_msgs - robot_std_msgs - robot_visualization_msgs - robot_nav_2d_msgs - robot_nav_2d_utils - robot_nav_core2 - mkt_msgs - score_algorithm - robot_costmap_2d - robot_tf3_geometry_msgs - data_convert - robot_cpp - angles - ) - - find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) - find_package(Boost REQUIRED COMPONENTS system) - - catkin_package( - INCLUDE_DIRS include - LIBRARIES ${PROJECT_NAME} ${PROJECT_NAME}_utils - CATKIN_DEPENDS robot_geometry_msgs robot_nav_msgs robot_std_msgs robot_visualization_msgs robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core2 mkt_msgs score_algorithm robot_costmap_2d robot_tf3_geometry_msgs data_convert robot_cpp angles - DEPENDS Boost - ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ${TF3_INCLUDE_DIR} - ) -endif() - -# ======================================================== -# Libraries -# ======================================================== -# Tạo thư viện utils trước -add_library(${PROJECT_NAME}_utils SHARED - src/transforms.cpp -) - -# Tạo thư viện chính -add_library(${PROJECT_NAME} SHARED - src/pnkx_local_planner.cpp - src/pnkx_go_straight_local_planner.cpp - src/pnkx_rotate_local_planner.cpp - src/pnkx_docking_local_planner.cpp -) - -if(BUILDING_WITH_CATKIN) - add_dependencies(${PROJECT_NAME}_utils ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - - target_include_directories(${PROJECT_NAME}_utils - PUBLIC - $ - $ - ) - - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME}_utils - PUBLIC ${catkin_LIBRARIES} - PRIVATE Boost::system - ${TF3_LIBRARY} - ) - - target_link_libraries(${PROJECT_NAME} - PUBLIC ${PROJECT_NAME}_utils - PUBLIC ${catkin_LIBRARIES} - PRIVATE Boost::system - ${TF3_LIBRARY} - ) - -else() - - target_include_directories(${PROJECT_NAME}_utils - PUBLIC - $ - $ - ) - - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ) - - target_link_libraries(${PROJECT_NAME}_utils - PUBLIC - ${PACKAGES_DIR} - PRIVATE - Boost::system - ) - - target_link_libraries(${PROJECT_NAME} - PUBLIC ${PROJECT_NAME}_utils - PUBLIC - ${PACKAGES_DIR} - PRIVATE - Boost::system - ${TF3_LIBRARY} - ) - - set_target_properties(${PROJECT_NAME}_utils PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - - set_target_properties(${PROJECT_NAME} PROPERTIES - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - BUILD_RPATH "${CMAKE_BINARY_DIR}" - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" - ) - -endif() - -# ======================================================== -# Install -# ======================================================== -if(BUILDING_WITH_CATKIN) - ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html - install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_utils - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - ## Install plugins.xml if it exists - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) - install(FILES plugins.xml - DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} - ) - endif() - -else() - - install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_utils - EXPORT ${PROJECT_NAME}-targets - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin - ) - - # Export targets - install(EXPORT ${PROJECT_NAME}-targets - FILE ${PROJECT_NAME}-targets.cmake - NAMESPACE ${PROJECT_NAME}:: - DESTINATION lib/cmake/${PROJECT_NAME} - ) - - ## Mark cpp header files for installation - install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION include - FILES_MATCHING PATTERN "*.h" - PATTERN ".svn" EXCLUDE - ) - - ## Install plugins.xml if it exists - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) - install(FILES plugins.xml - DESTINATION share/${PROJECT_NAME} - ) - endif() - - # Print configuration info - message(STATUS "=================================") - message(STATUS "Project: ${PROJECT_NAME}") - message(STATUS "Version: ${PROJECT_VERSION}") - message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Libraries: ${PROJECT_NAME}, ${PROJECT_NAME}_utils") - message(STATUS "Dependencies: robot_geometry_msgs, robot_nav_msgs, robot_std_msgs, robot_visualization_msgs, robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core2, mkt_msgs, score_algorithm, robot_costmap_2d, tf3, robot_tf3_geometry_msgs, data_convert, robot_cpp, angles, Boost") - message(STATUS "=================================") -endif() +cmake_minimum_required(VERSION 3.0.2) +project(pnkx_local_planner VERSION 1.0.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building pnkx_local_planner with Catkin") + +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building pnkx_local_planner with Standalone CMake") +endif() + +# C++ Standard - must be set before find_package +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Find dependencies +find_package(Boost REQUIRED COMPONENTS system) + +if (NOT BUILDING_WITH_CATKIN) + + # Enable Position Independent Code + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + # Cấu hình RPATH để tránh cycle trong runtime search path + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + set(PACKAGES_DIR + robot_geometry_msgs + robot_nav_msgs + robot_std_msgs + robot_visualization_msgs + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core2 + mkt_msgs + score_algorithm + robot_costmap_2d + tf3 + robot_tf3_geometry_msgs + data_convert + robot_cpp + angles + ) + + find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) + +else() + +# ======================================================== +# Catkin specific configuration +# ======================================================== + find_package(catkin REQUIRED COMPONENTS + robot_geometry_msgs + robot_nav_msgs + robot_std_msgs + robot_visualization_msgs + robot_nav_2d_msgs + robot_nav_2d_utils + robot_nav_core2 + mkt_msgs + score_algorithm + robot_costmap_2d + robot_tf3_geometry_msgs + data_convert + robot_cpp + angles + ) + + find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) + find_package(Boost REQUIRED COMPONENTS system) + + catkin_package( + INCLUDE_DIRS include + LIBRARIES ${PROJECT_NAME} ${PROJECT_NAME}_utils + CATKIN_DEPENDS robot_geometry_msgs robot_nav_msgs robot_std_msgs robot_visualization_msgs robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core2 mkt_msgs score_algorithm robot_costmap_2d robot_tf3_geometry_msgs data_convert robot_cpp angles + DEPENDS Boost + ) + + include_directories( + include + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ${TF3_INCLUDE_DIR} + ) +endif() + +# ======================================================== +# Libraries +# ======================================================== +# Tạo thư viện utils trước +add_library(${PROJECT_NAME}_utils SHARED + src/transforms.cpp +) + +# Tạo thư viện chính +add_library(${PROJECT_NAME} SHARED + src/pnkx_local_planner.cpp + src/pnkx_go_straight_local_planner.cpp + src/pnkx_rotate_local_planner.cpp + src/pnkx_docking_local_planner.cpp +) + +if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME}_utils ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + + target_include_directories(${PROJECT_NAME}_utils + PUBLIC + $ + $ + ) + + target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME}_utils + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::system + ${TF3_LIBRARY} + ) + + target_link_libraries(${PROJECT_NAME} + PUBLIC ${PROJECT_NAME}_utils + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::system + ${TF3_LIBRARY} + ) + +else() + + target_include_directories(${PROJECT_NAME}_utils + PUBLIC + $ + $ + ) + + target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + ) + + target_link_libraries(${PROJECT_NAME}_utils + PUBLIC + ${PACKAGES_DIR} + PRIVATE + Boost::system + ) + + target_link_libraries(${PROJECT_NAME} + PUBLIC ${PROJECT_NAME}_utils + PUBLIC + ${PACKAGES_DIR} + PRIVATE + Boost::system + ${TF3_LIBRARY} + ) + + set_target_properties(${PROJECT_NAME}_utils PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + + set_target_properties(${PROJECT_NAME} PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + +endif() + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + ## Mark libraries for installation + ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html + install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_utils + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + ## Install plugins.xml if it exists + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) + install(FILES plugins.xml + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} + ) + endif() + +else() + + install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_utils + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + + # Export targets + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION lib/cmake/${PROJECT_NAME} + ) + + ## Mark cpp header files for installation + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION include + FILES_MATCHING PATTERN "*.h" + PATTERN ".svn" EXCLUDE + ) + + ## Install plugins.xml if it exists + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml) + install(FILES plugins.xml + DESTINATION share/${PROJECT_NAME} + ) + endif() + + # Print configuration info + message(STATUS "=================================") + message(STATUS "Project: ${PROJECT_NAME}") + message(STATUS "Version: ${PROJECT_VERSION}") + message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") + message(STATUS "Libraries: ${PROJECT_NAME}, ${PROJECT_NAME}_utils") + message(STATUS "Dependencies: robot_geometry_msgs, robot_nav_msgs, robot_std_msgs, robot_visualization_msgs, robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core2, mkt_msgs, score_algorithm, robot_costmap_2d, tf3, robot_tf3_geometry_msgs, data_convert, robot_cpp, angles, Boost") + message(STATUS "=================================") +endif() diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_docking_local_planner.h b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_docking_local_planner.h index 36b3f23..d52631a 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_docking_local_planner.h +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_docking_local_planner.h @@ -1,182 +1,182 @@ -#ifndef _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_ -#define _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_ - -#include -#include -#include - -namespace pnkx_local_planner -{ - - /** - * @class PNKXDockingLocalPlanner - * @brief Plugin-based flexible local_planner - */ - class PNKXDockingLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner - { - public: - /** - * @brief Constructor that brings up pluginlib loaders - */ - PNKXDockingLocalPlanner(); - - virtual ~PNKXDockingLocalPlanner(); - - /** - * @brief robot_nav_core2 initialization - * @param name Namespace for this planner - * @param tf TFListener pointer - * @param costmap_robot Costmap pointer - */ - void initialize(robot::NodeHandle &parent, const std::string &name, - TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; - - /** - * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity - * - * It is presumed that the global plan is already set. - * - * This is mostly a wrapper for the protected computeVelocityCommands - * function which has additional debugging info. - * - * @param pose Current robot pose - * @param velocity Current robot velocity - * @return The best command for the robot to drive - */ - virtual robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. - * - * The pose that it checks against is the last pose in the current global plan. - * The calculation is delegated to the goal_checker plugin. - * - * @param pose Current pose - * @param velocity Current velocity - * @return True if the robot should be considered as having reached the goal. - */ - virtual bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Create a new instance of the PNKXDockingLocalPlanner - * @return A shared pointer to the new instance - */ - static robot_nav_core2::LocalPlanner::Ptr create(); - - protected: - /** - * @brief robot_nav_core2 initialization other - */ - void initializeOthers() override; - - /** - * @brief get docking maker - */ - void getMaker(); - - /** - * @brief robot_nav_core2 reset other - */ - void reset() override; - - /** - * @brief get parameters - * @param nh NodeHandle to read parameters from - */ - void getParams(robot::NodeHandle &nh) override; - - /** - * @brief Helper method for preparing for the core scoring algorithm - * - * Runs the prepare method on all the critics with freshly transformed data - */ - virtual void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Iterate through all the twists and find the best one - */ - virtual robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - private: - class DockingPlanner - { - public: - DockingPlanner(const std::string &name); - ~DockingPlanner(); - - /** - * @brief initialization - * @param name Namespace for maker - * @param tf TFListener pointer - * @param costmap_robot Costmap pointer - */ - void initialize(robot::NodeHandle &nh, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, - score_algorithm::TrajectoryGenerator::Ptr traj_generator); - - bool getMakerGoal(robot_nav_2d_msgs::Pose2DStamped &maker_goal); - - bool geLocalGoal(robot_nav_2d_msgs::Pose2DStamped &local_goal); - - bool getLocalPath(const robot_nav_2d_msgs::Pose2DStamped &local_pose, - const robot_nav_2d_msgs::Pose2DStamped &local_goal, robot_nav_msgs::Path &local_path); - - bool initialized_; - bool is_detected_; - bool is_goal_reached_; - bool following_; - bool allow_rotate_; - - double xy_goal_tolerance_; - double yaw_goal_tolerance_; - double min_lookahead_dist_; - double max_lookahead_dist_; - double lookahead_time_; - double angle_threshold_; - - std::string name_; - std::string docking_planner_name_; - std::string docking_nav_name_; - - robot_nav_core::BaseGlobalPlanner::Ptr docking_planner_; - score_algorithm::ScoreAlgorithm::Ptr docking_nav_; - - robot_geometry_msgs::Vector3 linear_; - robot_geometry_msgs::Vector3 angular_; - - private: - /** - * @brief Callback wall timer for detect timeout - */ - virtual void detectedTimeOutCb(const ::robot::WallTimerEvent &timer_event); - - /** - * @brief Callback wall timer for delay - */ - virtual void delayCb(const ::robot::WallTimerEvent &timer_event); - - robot::NodeHandle nh_, nh_priv_; - TFListenerPtr tf_; - robot_costmap_2d::Costmap2DROBOT *costmap_robot_; - score_algorithm::TrajectoryGenerator::Ptr traj_generator_; - std::function docking_planner_loader_; - std::function docking_nav_loader_; - - robot::WallTimer detected_timeout_wt_, delayed_wt_; - bool delayed_; - bool detected_timeout_; - std::string robot_base_frame_, maker_goal_frame_; - }; - - bool start_docking_; - double original_xy_goal_tolerance_, original_yaw_goal_tolerance_; - robot_xmlrpcpp::XmlRpcValue original_papams_; - std::vector dkpl_; - - bool dockingHanlde(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity); - - }; // PNKXDockingLocalPlanner - -} // namespace pnkx_local_planner - +#ifndef _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_ +#define _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_ + +#include +#include +#include + +namespace pnkx_local_planner +{ + + /** + * @class PNKXDockingLocalPlanner + * @brief Plugin-based flexible local_planner + */ + class PNKXDockingLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner + { + public: + /** + * @brief Constructor that brings up pluginlib loaders + */ + PNKXDockingLocalPlanner(); + + virtual ~PNKXDockingLocalPlanner(); + + /** + * @brief robot_nav_core2 initialization + * @param name Namespace for this planner + * @param tf TFListener pointer + * @param costmap_robot Costmap pointer + */ + void initialize(robot::NodeHandle &parent, const std::string &name, + TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; + + /** + * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity + * + * It is presumed that the global plan is already set. + * + * This is mostly a wrapper for the protected computeVelocityCommands + * function which has additional debugging info. + * + * @param pose Current robot pose + * @param velocity Current robot velocity + * @return The best command for the robot to drive + */ + virtual robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. + * + * The pose that it checks against is the last pose in the current global plan. + * The calculation is delegated to the goal_checker plugin. + * + * @param pose Current pose + * @param velocity Current velocity + * @return True if the robot should be considered as having reached the goal. + */ + virtual bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Create a new instance of the PNKXDockingLocalPlanner + * @return A shared pointer to the new instance + */ + static robot_nav_core2::LocalPlanner::Ptr create(); + + protected: + /** + * @brief robot_nav_core2 initialization other + */ + void initializeOthers() override; + + /** + * @brief get docking maker + */ + void getMaker(); + + /** + * @brief robot_nav_core2 reset other + */ + void reset() override; + + /** + * @brief get parameters + * @param nh NodeHandle to read parameters from + */ + void getParams(robot::NodeHandle &nh) override; + + /** + * @brief Helper method for preparing for the core scoring algorithm + * + * Runs the prepare method on all the critics with freshly transformed data + */ + virtual void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Iterate through all the twists and find the best one + */ + virtual robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + private: + class DockingPlanner + { + public: + DockingPlanner(const std::string &name); + ~DockingPlanner(); + + /** + * @brief initialization + * @param name Namespace for maker + * @param tf TFListener pointer + * @param costmap_robot Costmap pointer + */ + void initialize(robot::NodeHandle &nh, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, + score_algorithm::TrajectoryGenerator::Ptr traj_generator); + + bool getMakerGoal(robot_nav_2d_msgs::Pose2DStamped &maker_goal); + + bool geLocalGoal(robot_nav_2d_msgs::Pose2DStamped &local_goal); + + bool getLocalPath(const robot_nav_2d_msgs::Pose2DStamped &local_pose, + const robot_nav_2d_msgs::Pose2DStamped &local_goal, robot_nav_msgs::Path &local_path); + + bool initialized_; + bool is_detected_; + bool is_goal_reached_; + bool following_; + bool allow_rotate_; + + double xy_goal_tolerance_; + double yaw_goal_tolerance_; + double min_lookahead_dist_; + double max_lookahead_dist_; + double lookahead_time_; + double angle_threshold_; + + std::string name_; + std::string docking_planner_name_; + std::string docking_nav_name_; + + robot_nav_core::BaseGlobalPlanner::Ptr docking_planner_; + score_algorithm::ScoreAlgorithm::Ptr docking_nav_; + + robot_geometry_msgs::Vector3 linear_; + robot_geometry_msgs::Vector3 angular_; + + private: + /** + * @brief Callback wall timer for detect timeout + */ + virtual void detectedTimeOutCb(const ::robot::WallTimerEvent &timer_event); + + /** + * @brief Callback wall timer for delay + */ + virtual void delayCb(const ::robot::WallTimerEvent &timer_event); + + robot::NodeHandle nh_, nh_priv_; + TFListenerPtr tf_; + robot_costmap_2d::Costmap2DROBOT *costmap_robot_; + score_algorithm::TrajectoryGenerator::Ptr traj_generator_; + std::function docking_planner_loader_; + std::function docking_nav_loader_; + + robot::WallTimer detected_timeout_wt_, delayed_wt_; + bool delayed_; + bool detected_timeout_; + std::string robot_base_frame_, maker_goal_frame_; + }; + + bool start_docking_; + double original_xy_goal_tolerance_, original_yaw_goal_tolerance_; + robot_xmlrpcpp::XmlRpcValue original_papams_; + std::vector dkpl_; + + bool dockingHanlde(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity); + + }; // PNKXDockingLocalPlanner + +} // namespace pnkx_local_planner + #endif // _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_ \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_go_straight_local_planner.h b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_go_straight_local_planner.h index f05ccfa..59f2d70 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_go_straight_local_planner.h +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_go_straight_local_planner.h @@ -1,85 +1,85 @@ -#ifndef _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_ -#define _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_ - -#include - -namespace pnkx_local_planner -{ - /** - * @class PNKXGoStraightLocalPlanner - * @brief Plugin-based flexible local_planner - */ - class PNKXGoStraightLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner - { - public: - /** - * @brief Constructor that brings up pluginlib loaders - */ - PNKXGoStraightLocalPlanner(); - - virtual ~PNKXGoStraightLocalPlanner(); - - /** - * @brief robot_nav_core2 initialization - * @param name Namespace for this planner - * @param tf TFListener pointer - * @param costmap_robot Costmap pointer - */ - void initialize(robot::NodeHandle &parent, const std::string &name, - TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; - - /** - * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity - * - * It is presumed that the global plan is already set. - * - * This is mostly a wrapper for the protected computeVelocityCommands - * function which has additional debugging info. - * - * @param pose Current robot pose - * @param velocity Current robot velocity - * @return The best command for the robot to drive - */ - robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. - * - * The pose that it checks against is the last pose in the current global plan. - * The calculation is delegated to the goal_checker plugin. - * - * @param pose Current pose - * @param velocity Current velocity - * @return True if the robot should be considered as having reached the goal. - */ - bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Create a new instance of the PNKXGoStraightLocalPlanner - * @return A shared pointer to the new instance - */ - static robot_nav_core2::LocalPlanner::Ptr create(); - - protected: - /** - * @brief robot_nav_core2 reset other - */ - virtual void reset() override;; - - /** - * @brief Helper method for preparing for the core scoring algorithm - * - * Runs the prepare method on all the critics with freshly transformed data - */ - void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Iterate through all the twists and find the best one - */ - robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - }; - -} // namespace pnkx_local_planner +#ifndef _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_ +#define _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_ + +#include + +namespace pnkx_local_planner +{ + /** + * @class PNKXGoStraightLocalPlanner + * @brief Plugin-based flexible local_planner + */ + class PNKXGoStraightLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner + { + public: + /** + * @brief Constructor that brings up pluginlib loaders + */ + PNKXGoStraightLocalPlanner(); + + virtual ~PNKXGoStraightLocalPlanner(); + + /** + * @brief robot_nav_core2 initialization + * @param name Namespace for this planner + * @param tf TFListener pointer + * @param costmap_robot Costmap pointer + */ + void initialize(robot::NodeHandle &parent, const std::string &name, + TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; + + /** + * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity + * + * It is presumed that the global plan is already set. + * + * This is mostly a wrapper for the protected computeVelocityCommands + * function which has additional debugging info. + * + * @param pose Current robot pose + * @param velocity Current robot velocity + * @return The best command for the robot to drive + */ + robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. + * + * The pose that it checks against is the last pose in the current global plan. + * The calculation is delegated to the goal_checker plugin. + * + * @param pose Current pose + * @param velocity Current velocity + * @return True if the robot should be considered as having reached the goal. + */ + bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Create a new instance of the PNKXGoStraightLocalPlanner + * @return A shared pointer to the new instance + */ + static robot_nav_core2::LocalPlanner::Ptr create(); + + protected: + /** + * @brief robot_nav_core2 reset other + */ + virtual void reset() override;; + + /** + * @brief Helper method for preparing for the core scoring algorithm + * + * Runs the prepare method on all the critics with freshly transformed data + */ + void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Iterate through all the twists and find the best one + */ + robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + }; + +} // namespace pnkx_local_planner #endif // _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_ \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_local_planner.h b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_local_planner.h index f28d849..e46c425 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_local_planner.h +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_local_planner.h @@ -1,212 +1,212 @@ -#ifndef _PNKX_LOCAL_PLANNER_H_INCLUDED_ -#define _PNKX_LOCAL_PLANNER_H_INCLUDED_ - -#include -#include -#include -#include -#include -#include - -namespace pnkx_local_planner -{ - - /** - * @class PNKXLocalPlanner - * @brief Plugin-based flexible local_planner - */ - class PNKXLocalPlanner : public robot_nav_core2::LocalPlanner - { - public: - /** - * @brief Constructor that brings up pluginlib loaders - */ - PNKXLocalPlanner(); - - virtual ~PNKXLocalPlanner(); - - /** - * @brief robot_nav_core2 initialization - * @param name Namespace for this planner - * @param tf TFListener pointer - * @param costmap_robot Costmap pointer - */ - void initialize(robot::NodeHandle &parent, const std::string &name, - TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; - - /** - * @brief robot_nav_core2 setGoalPose - Sets the global goal pose - * @param goal_pose The Goal Pose - */ - void setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose) override; - - /** - * @brief robot_nav_core2 setPlan - Sets the global plan - * @param path The global plan - */ - void setPlan(const robot_nav_2d_msgs::Path2D &path) override; - - /** - * @brief robot_nav_core2 getPlan - Gets the current global plan - * @param path The global plan - */ - void getPlan(robot_nav_2d_msgs::Path2D &path) override; - - /** - * @brief robot_nav_core2 getGlobalPlan - Gets the current global plan - * @param path The global plan - */ - void getGlobalPlan(robot_nav_2d_msgs::Path2D &path) override; - - /** - * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity - * - * It is presumed that the global plan is already set. - * - * This is mostly a wrapper for the protected computeVelocityCommands - * function which has additional debugging info. - * - * @param pose Current robot pose - * @param velocity Current robot velocity - * @return The best command for the robot to drive - */ - robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief set velocity for x, y asix of the robot - * @param linear the velocity command - * @return True if set is done, false otherwise - */ - bool setTwistLinear(robot_geometry_msgs::Vector3 linear) override; - - /** - * @brief get velocity for x, y asix of the robot - * @param linear The velocity command - * @return True if set is done, false otherwise - */ - virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) override; - - /** - * @brief Set velocity theta for z asix of the robot - * @param angular the command velocity - * @return True if set is done, false otherwise - */ - virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) override; - - /** - * @brief Get velocity theta for z asix of the robot - * @param direct The velocity command - * @return True if set is done, false otherwise - */ - virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) override; - - /** - * @brief Check if the kinematic parameters are currently locked - * @return True if the kinematic parameters are locked, false otherwise - * - * This function indicates whether the kinematic parameters (e.g., velocities, accelerations, or direction settings) are in a locked state, preventing modifications. If the parameters are locked during in-place rotation, it could prevent updates to the direction or velocity, potentially causing inconsistencies in motion commands that lead to odometry errors and localization jumps in AMCL. - */ - virtual bool islock() override; - - /** - * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. - * - * The pose that it checks against is the last pose in the current global plan. - * The calculation is delegated to the goal_checker plugin. - * - * @param pose Current pose - * @param velocity Current velocity - * @return True if the robot should be considered as having reached the goal. - */ - bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Create a new PNKXLocalPlanner - * @return A shared pointer to the new PNKXLocalPlanner - */ - static robot_nav_core2::LocalPlanner::Ptr create(); - - protected: - /** - * @brief Lock the kinematic parameters to prevent modifications - * - * This function sets the kinematic parameters to a locked state, ensuring that values such as direction (xytheta_direct), velocities, or accelerations cannot be changed until unlocked. Locking during critical operations like in-place rotation may stabilize motion commands but could cause issues if the lock persists too long, preventing necessary updates to odometry data used by AMCL. - */ - virtual void lock(); - - /** - * @brief Unlock the kinematic parameters to allow modifications - * - * This function releases the lock on kinematic parameters, allowing changes to values such as direction, velocities, or accelerations. If the parameters are unlocked prematurely during in-place rotation, sudden changes to motion parameters (e.g., theta direction) could lead to odometry discontinuities, contributing to localization jumps in AMCL. - */ - virtual void unlock(); - /** - * @brief robot_nav_core2 initialization other - */ - virtual void initializeOthers(); - - /** - * @brief robot_nav_core2 reset other - */ - virtual void reset(); - - /** - * @brief Get parameters - * @param nh NodeHandle to read parameters from - */ - virtual void getParams(robot::NodeHandle &nh); - - /** - * @brief Helper method for preparing for the core scoring algorithm - * - * Runs the prepare method on all the critics with freshly transformed data - */ - virtual void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity); - - /** - * @brief Iterate through all the twists and find the best one - */ - virtual robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity); - - /** - * @brief Helper method to transform a given pose to the local costmap frame. - */ - robot_nav_2d_msgs::Pose2DStamped transformPoseToLocal(const robot_nav_2d_msgs::Pose2DStamped &pose); - - // Plugin handling - std::function traj_gen_loader_; - score_algorithm::TrajectoryGenerator::Ptr traj_generator_; - - std::function nav_algorithm_loader_; - score_algorithm::ScoreAlgorithm::Ptr nav_algorithm_; - std::function rotate_algorithm_loader_; - score_algorithm::ScoreAlgorithm::Ptr rotate_algorithm_; - - std::function goal_checker_loader_; - score_algorithm::GoalChecker::Ptr goal_checker_; - - bool initialized_; - TFListenerPtr tf_; - std::string name_; - robot::NodeHandle parent_, planner_nh_; - robot_nav_2d_msgs::Path2D global_plan_; ///< Saved Global Plan - robot_nav_2d_msgs::Path2D transformed_global_plan_; - robot_nav_2d_msgs::Path2D local_plan_; - robot_nav_2d_msgs::Pose2DStamped goal_pose_; ///< Saved Goal Pose - - robot_costmap_2d::Costmap2D *costmap_; - robot_costmap_2d::Costmap2DROBOT *costmap_robot_; - nav_grid::NavGridInfo info_; - boost::recursive_mutex configuration_mutex_; - bool update_costmap_before_planning_; - - bool ret_angle_, ret_nav_; - double yaw_goal_tolerance_, xy_goal_tolerance_; - bool lock_; - - }; // PNKXLocalPlanner - -} // namespace pnkx_local_planner - +#ifndef _PNKX_LOCAL_PLANNER_H_INCLUDED_ +#define _PNKX_LOCAL_PLANNER_H_INCLUDED_ + +#include +#include +#include +#include +#include +#include + +namespace pnkx_local_planner +{ + + /** + * @class PNKXLocalPlanner + * @brief Plugin-based flexible local_planner + */ + class PNKXLocalPlanner : public robot_nav_core2::LocalPlanner + { + public: + /** + * @brief Constructor that brings up pluginlib loaders + */ + PNKXLocalPlanner(); + + virtual ~PNKXLocalPlanner(); + + /** + * @brief robot_nav_core2 initialization + * @param name Namespace for this planner + * @param tf TFListener pointer + * @param costmap_robot Costmap pointer + */ + void initialize(robot::NodeHandle &parent, const std::string &name, + TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; + + /** + * @brief robot_nav_core2 setGoalPose - Sets the global goal pose + * @param goal_pose The Goal Pose + */ + void setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose) override; + + /** + * @brief robot_nav_core2 setPlan - Sets the global plan + * @param path The global plan + */ + void setPlan(const robot_nav_2d_msgs::Path2D &path) override; + + /** + * @brief robot_nav_core2 getPlan - Gets the current global plan + * @param path The global plan + */ + void getPlan(robot_nav_2d_msgs::Path2D &path) override; + + /** + * @brief robot_nav_core2 getGlobalPlan - Gets the current global plan + * @param path The global plan + */ + void getGlobalPlan(robot_nav_2d_msgs::Path2D &path) override; + + /** + * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity + * + * It is presumed that the global plan is already set. + * + * This is mostly a wrapper for the protected computeVelocityCommands + * function which has additional debugging info. + * + * @param pose Current robot pose + * @param velocity Current robot velocity + * @return The best command for the robot to drive + */ + robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief set velocity for x, y asix of the robot + * @param linear the velocity command + * @return True if set is done, false otherwise + */ + bool setTwistLinear(robot_geometry_msgs::Vector3 linear) override; + + /** + * @brief get velocity for x, y asix of the robot + * @param linear The velocity command + * @return True if set is done, false otherwise + */ + virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) override; + + /** + * @brief Set velocity theta for z asix of the robot + * @param angular the command velocity + * @return True if set is done, false otherwise + */ + virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) override; + + /** + * @brief Get velocity theta for z asix of the robot + * @param direct The velocity command + * @return True if set is done, false otherwise + */ + virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) override; + + /** + * @brief Check if the kinematic parameters are currently locked + * @return True if the kinematic parameters are locked, false otherwise + * + * This function indicates whether the kinematic parameters (e.g., velocities, accelerations, or direction settings) are in a locked state, preventing modifications. If the parameters are locked during in-place rotation, it could prevent updates to the direction or velocity, potentially causing inconsistencies in motion commands that lead to odometry errors and localization jumps in AMCL. + */ + virtual bool islock() override; + + /** + * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. + * + * The pose that it checks against is the last pose in the current global plan. + * The calculation is delegated to the goal_checker plugin. + * + * @param pose Current pose + * @param velocity Current velocity + * @return True if the robot should be considered as having reached the goal. + */ + bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Create a new PNKXLocalPlanner + * @return A shared pointer to the new PNKXLocalPlanner + */ + static robot_nav_core2::LocalPlanner::Ptr create(); + + protected: + /** + * @brief Lock the kinematic parameters to prevent modifications + * + * This function sets the kinematic parameters to a locked state, ensuring that values such as direction (xytheta_direct), velocities, or accelerations cannot be changed until unlocked. Locking during critical operations like in-place rotation may stabilize motion commands but could cause issues if the lock persists too long, preventing necessary updates to odometry data used by AMCL. + */ + virtual void lock(); + + /** + * @brief Unlock the kinematic parameters to allow modifications + * + * This function releases the lock on kinematic parameters, allowing changes to values such as direction, velocities, or accelerations. If the parameters are unlocked prematurely during in-place rotation, sudden changes to motion parameters (e.g., theta direction) could lead to odometry discontinuities, contributing to localization jumps in AMCL. + */ + virtual void unlock(); + /** + * @brief robot_nav_core2 initialization other + */ + virtual void initializeOthers(); + + /** + * @brief robot_nav_core2 reset other + */ + virtual void reset(); + + /** + * @brief Get parameters + * @param nh NodeHandle to read parameters from + */ + virtual void getParams(robot::NodeHandle &nh); + + /** + * @brief Helper method for preparing for the core scoring algorithm + * + * Runs the prepare method on all the critics with freshly transformed data + */ + virtual void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity); + + /** + * @brief Iterate through all the twists and find the best one + */ + virtual robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity); + + /** + * @brief Helper method to transform a given pose to the local costmap frame. + */ + robot_nav_2d_msgs::Pose2DStamped transformPoseToLocal(const robot_nav_2d_msgs::Pose2DStamped &pose); + + // Plugin handling + std::function traj_gen_loader_; + score_algorithm::TrajectoryGenerator::Ptr traj_generator_; + + std::function nav_algorithm_loader_; + score_algorithm::ScoreAlgorithm::Ptr nav_algorithm_; + std::function rotate_algorithm_loader_; + score_algorithm::ScoreAlgorithm::Ptr rotate_algorithm_; + + std::function goal_checker_loader_; + score_algorithm::GoalChecker::Ptr goal_checker_; + + bool initialized_; + TFListenerPtr tf_; + std::string name_; + robot::NodeHandle parent_, planner_nh_; + robot_nav_2d_msgs::Path2D global_plan_; ///< Saved Global Plan + robot_nav_2d_msgs::Path2D transformed_global_plan_; + robot_nav_2d_msgs::Path2D local_plan_; + robot_nav_2d_msgs::Pose2DStamped goal_pose_; ///< Saved Goal Pose + + robot_costmap_2d::Costmap2D *costmap_; + robot_costmap_2d::Costmap2DROBOT *costmap_robot_; + nav_grid::NavGridInfo info_; + boost::recursive_mutex configuration_mutex_; + bool update_costmap_before_planning_; + + bool ret_angle_, ret_nav_; + double yaw_goal_tolerance_, xy_goal_tolerance_; + bool lock_; + + }; // PNKXLocalPlanner + +} // namespace pnkx_local_planner + #endif // _PNKX_LOCAL_PLANNER_H_INCLUDED_ \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_rotate_local_planner.h b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_rotate_local_planner.h index 8e3cf8a..1faf556 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_rotate_local_planner.h +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/pnkx_rotate_local_planner.h @@ -1,85 +1,85 @@ -#ifndef _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_ -#define _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_ - -#include - -namespace pnkx_local_planner -{ - /** - * @class PNKXRotateLocalPlanner - * @brief Plugin-based flexible local_planner - */ - class PNKXRotateLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner - { - public: - /** - * @brief Constructor that brings up pluginlib loaders - */ - PNKXRotateLocalPlanner(); - - virtual ~PNKXRotateLocalPlanner(); - - /** - * @brief robot_nav_core2 initialization - * @param name Namespace for this planner - * @param tf TFListener pointer - * @param costmap_robot Costmap pointer - */ - void initialize(robot::NodeHandle &parent, const std::string &name, - TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; - - /** - * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity - * - * It is presumed that the global plan is already set. - * - * This is mostly a wrapper for the protected computeVelocityCommands - * function which has additional debugging info. - * - * @param pose Current robot pose - * @param velocity Current robot velocity - * @return The best command for the robot to drive - */ - robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. - * - * The pose that it checks against is the last pose in the current global plan. - * The calculation is delegated to the goal_checker plugin. - * - * @param pose Current pose - * @param velocity Current velocity - * @return True if the robot should be considered as having reached the goal. - */ - bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Create a new instance of the PNKXRotateLocalPlanner - * @return A shared pointer to the new instance - */ - static robot_nav_core2::LocalPlanner::Ptr create(); - - protected: - /** - * @brief robot_nav_core2 reset other - */ - virtual void reset() override; - - /** - * @brief Helper method for preparing for the core scoring algorithm - * - * Runs the prepare method on all the critics with freshly transformed data - */ - void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - /** - * @brief Iterate through all the twists and find the best one - */ - robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; - - }; -} - -#endif // _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_ +#ifndef _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_ +#define _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_ + +#include + +namespace pnkx_local_planner +{ + /** + * @class PNKXRotateLocalPlanner + * @brief Plugin-based flexible local_planner + */ + class PNKXRotateLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner + { + public: + /** + * @brief Constructor that brings up pluginlib loaders + */ + PNKXRotateLocalPlanner(); + + virtual ~PNKXRotateLocalPlanner(); + + /** + * @brief robot_nav_core2 initialization + * @param name Namespace for this planner + * @param tf TFListener pointer + * @param costmap_robot Costmap pointer + */ + void initialize(robot::NodeHandle &parent, const std::string &name, + TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; + + /** + * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity + * + * It is presumed that the global plan is already set. + * + * This is mostly a wrapper for the protected computeVelocityCommands + * function which has additional debugging info. + * + * @param pose Current robot pose + * @param velocity Current robot velocity + * @return The best command for the robot to drive + */ + robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity. + * + * The pose that it checks against is the last pose in the current global plan. + * The calculation is delegated to the goal_checker plugin. + * + * @param pose Current pose + * @param velocity Current velocity + * @return True if the robot should be considered as having reached the goal. + */ + bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Create a new instance of the PNKXRotateLocalPlanner + * @return A shared pointer to the new instance + */ + static robot_nav_core2::LocalPlanner::Ptr create(); + + protected: + /** + * @brief robot_nav_core2 reset other + */ + virtual void reset() override; + + /** + * @brief Helper method for preparing for the core scoring algorithm + * + * Runs the prepare method on all the critics with freshly transformed data + */ + void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + /** + * @brief Iterate through all the twists and find the best one + */ + robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override; + + }; +} + +#endif // _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_ diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/transforms.h b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/transforms.h index 4c7cd12..828c8cd 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/transforms.h +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/include/pnkx_local_planner/transforms.h @@ -1,50 +1,50 @@ -#ifndef _MKT_LOCAL_PLANNER_TRANSFORMS_CHECKER_H_INCLUDED__ -#define _MKT_LOCAL_PLANNER_TRANSFORMS_CHECKER_H_INCLUDED__ - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include - -namespace pnkx_local_planner -{ - bool getPose(TFListenerPtr tf, std::string base_frame_id, std::string global_frame, - robot_nav_2d_msgs::Pose2DStamped &global_pose, double transform_tolerance = 2.0); - - bool transformGlobalPose(TFListenerPtr tf, const std::string &global_frame, - const robot_nav_2d_msgs::Pose2DStamped &stamped_pose, robot_nav_2d_msgs::Pose2DStamped &newer_pose); - - double getSquareDistance(const robot_geometry_msgs::Pose2D &pose_a, const robot_geometry_msgs::Pose2D &pose_b); - - /** - * @brief Transforms the global plan of the robot from the planner frame to the local frame (modified). - * - * The method replaces transformGlobalPlan as defined in base_local_planner/goal_functions.h - * such that the index of the current goal pose is returned as well as - * the transformation between the global plan and the planning frame. - * @param tf A reference to a tf buffer - * @param global_plan The plan to be transformed - * @param pose The pose of the robot - * @param costmap A reference to the costmap being used so the window size for transforming can be computed - * @param global_frame The frame to transform the plan to - * @param max_plan_length Specify maximum length (cumulative Euclidean distances) of the transformed plan [if <=0: disabled; the length is also bounded by the local costmap size!] - * @param[out] transformed_plan Populated with the transformed plan - * @return \c true if the global plan is transformed, \c false otherwise - */ - bool transformGlobalPlan( - TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &global_frame, double max_plan_length, - robot_nav_2d_msgs::Path2D &transformed_plan, const bool from_global_frame = false); - -} - +#ifndef _MKT_LOCAL_PLANNER_TRANSFORMS_CHECKER_H_INCLUDED__ +#define _MKT_LOCAL_PLANNER_TRANSFORMS_CHECKER_H_INCLUDED__ + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include + +namespace pnkx_local_planner +{ + bool getPose(TFListenerPtr tf, std::string base_frame_id, std::string global_frame, + robot_nav_2d_msgs::Pose2DStamped &global_pose, double transform_tolerance = 2.0); + + bool transformGlobalPose(TFListenerPtr tf, const std::string &global_frame, + const robot_nav_2d_msgs::Pose2DStamped &stamped_pose, robot_nav_2d_msgs::Pose2DStamped &newer_pose); + + double getSquareDistance(const robot_geometry_msgs::Pose2D &pose_a, const robot_geometry_msgs::Pose2D &pose_b); + + /** + * @brief Transforms the global plan of the robot from the planner frame to the local frame (modified). + * + * The method replaces transformGlobalPlan as defined in base_local_planner/goal_functions.h + * such that the index of the current goal pose is returned as well as + * the transformation between the global plan and the planning frame. + * @param tf A reference to a tf buffer + * @param global_plan The plan to be transformed + * @param pose The pose of the robot + * @param costmap A reference to the costmap being used so the window size for transforming can be computed + * @param global_frame The frame to transform the plan to + * @param max_plan_length Specify maximum length (cumulative Euclidean distances) of the transformed plan [if <=0: disabled; the length is also bounded by the local costmap size!] + * @param[out] transformed_plan Populated with the transformed plan + * @return \c true if the global plan is transformed, \c false otherwise + */ + bool transformGlobalPlan( + TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &global_frame, double max_plan_length, + robot_nav_2d_msgs::Path2D &transformed_plan, const bool from_global_frame = false); + +} + #endif \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/package.xml b/src/Algorithms/Packages/local_planners/pnkx_local_planner/package.xml index f2495cd..6682f28 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/package.xml +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/package.xml @@ -1,67 +1,67 @@ - - pnkx_local_planner - 0.7.10 - - pnkx_local_planner is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. pnkx_local_planner - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/pnkx_local_planner - - catkin - - robot_geometry_msgs - robot_geometry_msgs - - robot_nav_msgs - robot_nav_msgs - - robot_std_msgs - robot_std_msgs - - robot_visualization_msgs - robot_visualization_msgs - - robot_nav_2d_msgs - robot_nav_2d_msgs - - robot_nav_2d_utils - robot_nav_2d_utils - - robot_nav_core2 - robot_nav_core2 - - mkt_msgs - mkt_msgs - - score_algorithm - score_algorithm - - robot_costmap_2d - robot_costmap_2d - - - - - robot_tf3_geometry_msgs - robot_tf3_geometry_msgs - - data_convert - data_convert - - robot_cpp - robot_cpp - - angles - angles - + + pnkx_local_planner + 0.7.10 + + pnkx_local_planner is the second generation of the transform library, which lets + the user keep track of multiple coordinate frames over time. pnkx_local_planner + maintains the relationship between coordinate frames in a tree + structure buffered in time, and lets the user transform points, + vectors, etc between any two coordinate frames at any desired + point in time. + + Tully Foote + Eitan Marder-Eppstein + Wim Meeussen + Tully Foote + BSD + + http://www.ros.org/wiki/pnkx_local_planner + + catkin + + robot_geometry_msgs + robot_geometry_msgs + + robot_nav_msgs + robot_nav_msgs + + robot_std_msgs + robot_std_msgs + + robot_visualization_msgs + robot_visualization_msgs + + robot_nav_2d_msgs + robot_nav_2d_msgs + + robot_nav_2d_utils + robot_nav_2d_utils + + robot_nav_core2 + robot_nav_core2 + + mkt_msgs + mkt_msgs + + score_algorithm + score_algorithm + + robot_costmap_2d + robot_costmap_2d + + + + + robot_tf3_geometry_msgs + robot_tf3_geometry_msgs + + data_convert + data_convert + + robot_cpp + robot_cpp + + angles + angles + \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_docking_local_planner.cpp b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_docking_local_planner.cpp index f09d811..3fd1314 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_docking_local_planner.cpp +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_docking_local_planner.cpp @@ -1,835 +1,832 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -pnkx_local_planner::PNKXDockingLocalPlanner::PNKXDockingLocalPlanner() - : PNKXLocalPlanner(), - start_docking_(false), - original_xy_goal_tolerance_(0.0), - original_yaw_goal_tolerance_(0.0) -{ -} - -pnkx_local_planner::PNKXDockingLocalPlanner::~PNKXDockingLocalPlanner() -{ - if (traj_generator_) - traj_generator_.reset(); - - if (nav_algorithm_) - nav_algorithm_.reset(); - - if (rotate_algorithm_) - rotate_algorithm_.reset(); - - if (goal_checker_) - goal_checker_.reset(); -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::initialize(robot::NodeHandle &parent, const std::string &name, - TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) -{ - if (!initialized_) - { - tf_ = tf; - name_ = name; - costmap_robot_ = costmap_robot; - costmap_ = costmap_robot_->getCostmap(); - - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - - parent_ = parent; - planner_nh_ = robot::NodeHandle(parent_, name); - robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str()); - this->getParams(planner_nh_); - - std::string traj_generator_name; - planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("StandardTrajectoryGenerator")); - robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(traj_generator_name); - traj_gen_loader_ = boost::dll::import_alias( - path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); - traj_generator_ = traj_gen_loader_(); - if (!traj_generator_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); - traj_generator_->initialize(nh_traj_gen); - robot::log_info_at(__FILE__, __LINE__, "Successfully initialized trajectory generator \"%s\"", traj_generator_name.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - - std::string algorithm_nav_name; - planner_nh_.getParam("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); - robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(algorithm_nav_name); - nav_algorithm_loader_ = boost::dll::import_alias( - path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations); - nav_algorithm_ = nav_algorithm_loader_(); - if (!nav_algorithm_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to load algorithm %s", algorithm_nav_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - - std::string algorithm_rotate_name; - planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("MKTAlgorithmDiffRotateToGoal")); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name); - rotate_algorithm_loader_ = boost::dll::import_alias( - path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations); - rotate_algorithm_ = rotate_algorithm_loader_(); - if (!rotate_algorithm_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create rotate algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); - } - rotate_algorithm_->initialize(parent_, algorithm_rotate_name, tf, costmap_robot_, traj_generator_); - robot::log_info_at(__FILE__, __LINE__, "Successfully initialized rotate algorithm \"%s\"", algorithm_rotate_name.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s rotate algorithm, are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); - } - - std::string goal_checker_name; - planner_nh_.param("goal_checker_name", goal_checker_name, std::string("dwb_plugins::SimpleGoalChecker")); - robot::log_info_at(__FILE__, __LINE__, "goal_checker_name: %s", goal_checker_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(goal_checker_name); - goal_checker_loader_ = boost::dll::import_alias( - path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); - goal_checker_ = goal_checker_loader_(); - if (!goal_checker_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - goal_checker_->initialize(parent_); - robot::log_info_at(__FILE__, __LINE__, "Successfully initialized goal checker \"%s\"", goal_checker_name.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Unexpected exception while creating goal checker \"%s\": %s", goal_checker_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - - this->initializeOthers(); - this->getMaker(); - robot::log_info_at(__FILE__, __LINE__, "%s is sucessed", name.c_str()); - initialized_ = true; - } -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::getMaker() -{ - std::string maker_name, maker_sources; - parent_.param("maker_name", maker_name, std::string("")); - parent_.param("maker_sources", maker_sources, std::string("")); - robot::log_info_at(__FILE__, __LINE__, "maker_name: %s", maker_name.c_str()); - robot::log_info_at(__FILE__, __LINE__, "maker_sources: %s", maker_sources.c_str()); - std::stringstream ss(maker_sources); - std::string source; - - while (ss >> source) - { - if (maker_name == source) - { - robot::NodeHandle source_node(parent_, source); - - if (source_node.hasParam("plugins")) - { - robot_xmlrpcpp::XmlRpcValue plugins; - source_node.getParam("plugins", plugins); - - if (plugins.getType() == robot_xmlrpcpp::XmlRpcValue::TypeArray) - { - for (int i = 0; i < plugins.size(); ++i) - { - if (plugins[i].getType() == robot_xmlrpcpp::XmlRpcValue::TypeStruct) - { - std::stringstream name; - name << source << "/" << static_cast(plugins[i]["name"]); - std::string docking_planner_name = static_cast(plugins[i]["docking_planner"]); - std::string docking_nav_name = static_cast(plugins[i]["docking_nav"]); - // std::shared_ptr dkpl = std::make_shared(name.str()); - DockingPlanner* dkpl = new DockingPlanner(name.str()); - dkpl->docking_planner_name_ = docking_planner_name; - dkpl->docking_nav_name_ = docking_nav_name; - dkpl_.push_back(dkpl); - } - } - } - else - { - robot::log_warning_at(__FILE__, __LINE__, "Expected 'plugins' to be an array under namespace [%s]", source.c_str()); - } - } - else - { - robot::log_warning_at(__FILE__, __LINE__, "No 'plugins' found under namespace [%s]", source.c_str()); - } - break; - } - } -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::initializeOthers() -{ - std::string algorithm_nav_name; - planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); - if (!parent_.getParam(algorithm_nav_name, original_papams_)) - robot::log_warning_at(__FILE__, __LINE__, "No found in %s in yaml-file, please check configuration", algorithm_nav_name.c_str()); - original_xy_goal_tolerance_ = xy_goal_tolerance_; - original_yaw_goal_tolerance_ = yaw_goal_tolerance_; -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::getParams(robot::NodeHandle &nh) -{ - // This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window - nh.param("update_costmap_before_planning", update_costmap_before_planning_, true); - if (!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) - { - xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); - } - if (!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) - { - yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); - } -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::reset() -{ - robot::log_info_at(__FILE__, __LINE__, "New Docking Goal Received."); - this->unlock(); - if(traj_generator_) traj_generator_->reset(); - if(goal_checker_) goal_checker_->reset(); - if(nav_algorithm_) nav_algorithm_->reset(); - if(rotate_algorithm_) rotate_algorithm_->reset(); - ret_nav_ = ret_angle_ = false; - - std::string algorithm_nav_name; - planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); - - parent_.setParam(algorithm_nav_name, original_papams_); - robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); - nh_algorithm.setParam("allow_rotate", false); -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - this->getParams(planner_nh_); - if (update_costmap_before_planning_) - { - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - } - - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), - local_goal_pose = this->transformPoseToLocal(goal_pose_); - if (start_docking_) - { - local_goal_pose = goal_pose_; - } - - try - { - if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) - robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed"); - } - catch(const robot_nav_core2::LocalPlannerException& e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } - - double x_direction, y_direction, theta_direction; - if (!ret_nav_) - { - if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - } - // else - // ROS_INFO_THROTTLE(0.2, "chieu %f %f %f", x_direction, y_direction, theta_direction); - - if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_) - { - this->lock(); - robot_geometry_msgs::Vector3 linear = dkpl_.front()->linear_; - traj_generator_->setTwistLinear(linear); - linear.x *= (-1); - traj_generator_->setTwistLinear(linear); - traj_generator_->setTwistAngular(dkpl_.front()->angular_); - - std::string algorithm_nav_name; - planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); - robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); - nh_algorithm.setParam("allow_rotate", dkpl_.front()->allow_rotate_); - nh_algorithm.setParam("min_lookahead_dist", dkpl_.front()->min_lookahead_dist_); - nh_algorithm.setParam("max_lookahead_dist", dkpl_.front()->max_lookahead_dist_); - nh_algorithm.setParam("lookahead_time", dkpl_.front()->lookahead_time_); - nh_algorithm.setParam("angle_threshold", dkpl_.front()->angle_threshold_); - - parent_.setParam("xy_goal_tolerance", dkpl_.front()->xy_goal_tolerance_); - parent_.setParam("yaw_goal_tolerance", dkpl_.front()->yaw_goal_tolerance_); - - if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_) - { - - if (dkpl_.front()->following_) - { - robot_nav_2d_msgs::Pose2DStamped follow_pose; - if (dkpl_.front()->geLocalGoal(local_goal_pose)) - { - local_goal_pose = follow_pose; - } - } - if (!dkpl_.front()->docking_nav_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); - } - } - } - } - else - { - if (!rotate_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", rotate_algorithm_->getName().c_str()); - } - // else - // ROS_INFO("chieu %f %f %f", x_direction, y_direction, theta_direction); - } - - int xytheta_direct[3]; - xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; - xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; - xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; - traj_generator_->setDirect(xytheta_direct); -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_nav_2d_msgs::Twist2D &velocity) -{ - // boost::recursive_mutex::scoped_lock l(configuration_mutex_); - robot::log_error("DEBUG 300"); - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - try - { - if (global_plan_.poses.empty()) - return cmd_vel; - this->prepare(pose, velocity); - cmd_vel = this->ScoreAlgorithm(pose, velocity); - return cmd_vel; - } - catch (const robot_nav_core2::PlannerException &e) - { - robot::log_warning_at(__FILE__, __LINE__, "%s", e.what()); - throw robot_nav_core2::LocalPlannerException(e.what()); - } -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - robot_nav_2d_msgs::Twist2D twist; - mkt_msgs::Trajectory2D traj; - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - cmd_vel.header.stamp = robot::Time::now(); - - if (ret_nav_ && ret_angle_) - return cmd_vel; - else if (!ret_nav_) - { - traj = nav_algorithm_->calculator(pose, velocity); - if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_) - { - if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_) - { - traj = dkpl_.front()->docking_nav_->calculator(pose, velocity); - } - } - local_plan_.header.stamp = robot::Time::now(); - robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); - local_plan_ = robot_nav_2d_utils::pathToPath(path); - } - else - { - traj = rotate_algorithm_->calculator(pose, velocity); - local_plan_.header.stamp = robot::Time::now(); - robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); - local_plan_ = robot_nav_2d_utils::pathToPath(path); - } - - cmd_vel.velocity = traj.velocity; - return cmd_vel; -} - -bool pnkx_local_planner::PNKXDockingLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - if (goal_pose_.header.frame_id == "") - { - robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); - return false; - } - robot::log_error("DEBUG 400.1"); - bool dock_ok = dockingHanlde(pose, velocity); - robot::log_error("DEBUG 400.2"); - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); - robot_nav_2d_msgs::Pose2DStamped local_goal = this->transformPoseToLocal(goal_pose_); - robot_nav_2d_msgs::Path2D plan = transformed_global_plan_; - if (start_docking_) - { - local_goal = goal_pose_; - if (!dkpl_.empty() && dkpl_.front()->initialized_) - { - if (dkpl_.front()->allow_rotate_) - plan = robot_nav_2d_msgs::Path2D(); - } - } - - if (!ret_nav_) - { - ret_nav_ = goal_checker_->isGoalReached(local_pose, local_goal, plan, velocity); - - if (ret_nav_) - { - robot::log_info_at(__FILE__, __LINE__, "local_pose %f %f %f", local_pose.pose.x, local_pose.pose.y, local_pose.pose.theta); - robot::log_info_at(__FILE__, __LINE__, "local_goal %f %f %f", local_goal.pose.x, local_goal.pose.y, local_goal.pose.theta); - } - } - - if (ret_nav_ && !ret_angle_ && !dock_ok) - { - double delta_orient = - fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta)); - ret_angle_ = (bool)(delta_orient <= yaw_goal_tolerance_); - if(ret_angle_) - robot::log_warning_at(__FILE__, __LINE__, "xy_goal_tolerance %f yaw_goal_tolerance %f",xy_goal_tolerance_, yaw_goal_tolerance_); - } - - if (start_docking_) - { - double dx = local_goal.pose.x - local_pose.pose.x; - double dy = local_goal.pose.y - local_pose.pose.y; - double dtheta = local_goal.pose.theta - local_pose.pose.theta; - } - if (ret_nav_ && ret_angle_ && dock_ok) - { - // nh_.setParam("xy_goal_tolerance", original_xy_goal_tolerance_); - // nh_.setParam("yaw_goal_tolerance", original_yaw_goal_tolerance_); - std::string algorithm_nav_name; - planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); - robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); - parent_.setParam(algorithm_nav_name, original_papams_); - nh_algorithm.setParam("allow_rotate", false); - } - return ret_nav_ && ret_angle_ && dock_ok; -} - -bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - if (!dkpl_.empty()) - { - if (ret_nav_ && ret_angle_) - { - if (!dkpl_.front()->is_detected_) - { - if (!dkpl_.front()->initialized_) - { - dkpl_.front()->initialize(parent_, tf_, costmap_robot_, traj_generator_); - dkpl_.front()->initialized_ = true; - } - else - { - if (dkpl_.front()->docking_planner_ && !dkpl_.front()->docking_nav_) - { - robot_nav_2d_msgs::Pose2DStamped local_goal; - try - { - if (dkpl_.front()->geLocalGoal(local_goal)) - { - robot::log_error("DEBUG 100"); - dkpl_.front()->is_detected_ = true; - start_docking_ = true; - robot_nav_msgs::Path path; - robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); - dkpl_.front()->getLocalPath(local_pose, local_goal, path); - this->setPlan(robot_nav_2d_utils::pathToPath(path)); - this->setGoalPose(local_goal); - } - } - catch (const std::exception &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } - } - else if (!dkpl_.front()->docking_planner_ && dkpl_.front()->docking_nav_) - { - robot_nav_2d_msgs::Pose2DStamped local_goal; - try - { - if (dkpl_.front()->geLocalGoal(local_goal)) - { - robot::log_error("DEBUG 200"); - dkpl_.front()->is_detected_ = true; - start_docking_ = true; - robot_nav_2d_msgs::Path2D path; - robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); - path.header.stamp = robot::Time::now(); - path.header.frame_id = costmap_robot_->getGlobalFrameID(); - path.poses.push_back(local_pose); - path.poses.push_back(local_goal); - this->setPlan(path); - this->setGoalPose(local_goal); - } - } - catch (const std::exception &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } - } - } - } - else - { - if (dkpl_.front()->initialized_ && !dkpl_.front()->is_goal_reached_) - { - dkpl_.front()->is_goal_reached_ = true; - robot::log_info_at(__FILE__, __LINE__, "%s is goal reached", dkpl_.front()->name_.c_str()); - } - - if (dkpl_.front()->initialized_ && dkpl_.front()->is_goal_reached_) - { - if(!dkpl_.empty()) - { - // if(dkpl_.front()) delete(dkpl_.front()); - dkpl_.erase(dkpl_.begin()); - } - start_docking_ = false; - } - } - } - } - bool result = false; - if (dkpl_.empty()) - { - robot::log_info_at(__FILE__, __LINE__, "Goal reached!"); - result = true; - this->getMaker(); - } - return result; -} - -pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::DockingPlanner(const std::string &name) - : initialized_(false), - is_detected_(false), - is_goal_reached_(false), - following_(false), - allow_rotate_(false), - xy_goal_tolerance_(0.05), - yaw_goal_tolerance_(0.05), - min_lookahead_dist_(0.4), - max_lookahead_dist_(1.0), - lookahead_time_(1.5), - angle_threshold_(0.4), - name_(name), - docking_planner_name_(), - docking_nav_name_(), - docking_planner_(nullptr), - docking_nav_(nullptr), - linear_(), - angular_(), - nh_(), - nh_priv_(), - tf_(nullptr), - costmap_robot_(nullptr), - traj_generator_(), - docking_planner_loader_(), - docking_nav_loader_(), - detected_timeout_wt_(), - delayed_wt_(), - delayed_(false), - detected_timeout_(false), - robot_base_frame_(), - maker_goal_frame_() -{ -} - -pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::~DockingPlanner() -{ - detected_timeout_wt_.stop(); - delayed_wt_.stop(); - if (docking_planner_ != nullptr) { - docking_planner_.reset(); - } - if (docking_nav_ != nullptr) { - docking_nav_.reset(); - } -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::initialize(robot::NodeHandle &nh, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, - score_algorithm::TrajectoryGenerator::Ptr traj_generator) -{ - nh_ = nh; - nh_priv_ = robot::NodeHandle(nh_, name_); - tf_ = tf; - costmap_robot_ = costmap_robot; - traj_generator_ = traj_generator; - - if (docking_planner_name_ != std::string("")) - { - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(docking_planner_name_); - docking_planner_loader_ = boost::dll::import_alias( - path_file_so, docking_planner_name_, boost::dll::load_mode::append_decorations); - docking_planner_ = docking_planner_loader_(); - if (!docking_planner_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create global planner \"%s\": returned null pointer", docking_planner_name_.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create global planner"); - } - docking_planner_->initialize(name_, costmap_robot_); - robot::log_info_at(__FILE__, __LINE__, "Created global_planner %s", docking_planner_name_.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s", - docking_planner_name_.c_str(), ex.what()); - } - } - - if (docking_nav_name_ != std::string("")) - { - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(docking_nav_name_); - docking_nav_loader_ = boost::dll::import_alias( - path_file_so, docking_nav_name_, boost::dll::load_mode::append_decorations); - docking_nav_ = docking_nav_loader_(); - if (!docking_nav_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create docking nav \"%s\": returned null pointer", docking_nav_name_.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create docking nav"); - } - robot::NodeHandle nh_docking_nav = robot::NodeHandle(nh_priv_, docking_nav_name_); - docking_nav_->initialize(nh_docking_nav, docking_nav_name_, tf_, costmap_robot_, traj_generator_); - robot::log_info_at(__FILE__, __LINE__, "Created docking nav %s", docking_nav_name_.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s", - docking_nav_name_.c_str(), ex.what()); - } - } - - robot_base_frame_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "robot_base_frame", std::string("base_link")); - if (!nh_priv_.param("maker_goal_frame", maker_goal_frame_, std::string(""))) - { - std::stringstream re; - re << "Can not get 'maker_goal_frame' in " << name_; - robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str()); - throw robot_nav_core2::LocalPlannerException(re.str()); - } - - nh_priv_.param("vel_x", linear_.x, 0.5); - nh_priv_.param("vel_theta", angular_.z, 0.5); - nh_priv_.param("following", following_, false); - nh_priv_.param("allow_rotate", allow_rotate_, false); - - double delay_time, time_out; - nh_priv_.param("delay", delay_time, 1.0); - nh_priv_.param("timeout", time_out, 1.0); - - nh_priv_.param("xy_goal_tolerance", xy_goal_tolerance_, 0.05); - nh_priv_.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.05); - - nh_priv_.param("min_lookahead_dist", min_lookahead_dist_, 0.4); - nh_priv_.param("max_lookahead_dist", max_lookahead_dist_, 1.0); - nh_priv_.param("lookahead_time", lookahead_time_, 1.5); - nh_priv_.param("angle_threshold", angle_threshold_, 0.4); - - robot::log_info("delay: %f", delay_time); - robot::log_info("timeout: %f", time_out); - robot::log_info("xy_goal_tolerance: %f", xy_goal_tolerance_); - robot::log_info("yaw_goal_tolerance: %f", yaw_goal_tolerance_); - robot::log_info("min_lookahead_dist: %f", min_lookahead_dist_); - robot::log_info("max_lookahead_dist: %f", max_lookahead_dist_); - robot::log_info("lookahead_time: %f", lookahead_time_); - robot::log_info("angle_threshold: %f", angle_threshold_); - - detected_timeout_wt_ = ::robot::WallTimer( - ::robot::WallDuration(time_out + delay_time), &pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::detectedTimeOutCb, this, false, false); - detected_timeout_wt_.start(); - robot::log_warning_at(__FILE__, __LINE__, "%s %f time_out start %f", name_.c_str(), delay_time, robot::Time::now().toSec()); - - delayed_wt_ = ::robot::WallTimer( - ::robot::WallDuration(delay_time), &pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::delayCb, this, false, false); - delayed_wt_.start(); - robot::log_warning_at(__FILE__, __LINE__, "%s %f delay start %f", name_.c_str(), delay_time, robot::Time::now().toSec()); - - initialized_ = true; -} - -bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::getMakerGoal(robot_nav_2d_msgs::Pose2DStamped &maker_goal) -{ - if (!delayed_) - return false; - - bool get_pose_result = false; - try - { - if (pnkx_local_planner::getPose(tf_, maker_goal_frame_, robot_base_frame_, maker_goal, 2.0)) - { - get_pose_result = true; - detected_timeout_wt_.stop(); - } - - if (get_pose_result) - return true; - } - catch (const std::exception &e) - { - if (detected_timeout_) - { - std::stringstream re; - re << "No detected " << maker_goal_frame_; - robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str()); - throw robot_nav_core2::LocalPlannerException(re.str()); - } - } - return false; -} - -bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::geLocalGoal(robot_nav_2d_msgs::Pose2DStamped &local_goal) -{ - if (!delayed_) - return false; - bool get_pose_result = false; - try - { - robot_nav_2d_msgs::Pose2DStamped maker_goal_on_robot; - if (pnkx_local_planner::getPose(tf_, maker_goal_frame_, robot_base_frame_, maker_goal_on_robot, 2.0)) - { - if (robot_nav_2d_utils::transformPose(tf_, costmap_robot_->getGlobalFrameID(), maker_goal_on_robot, local_goal)) - { - get_pose_result = true; - detected_timeout_wt_.stop(); - } - } - - if (get_pose_result) - return true; - } - catch (const std::exception &e) - { - if (detected_timeout_) - { - std::stringstream re; - re << "No detected " << maker_goal_frame_; - robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str()); - throw robot_nav_core2::LocalPlannerException(re.str()); - } - } - return false; -} - -bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::getLocalPath( - const robot_nav_2d_msgs::Pose2DStamped &local_pose, const robot_nav_2d_msgs::Pose2DStamped &local_goal, robot_nav_msgs::Path &local_path) -{ - robot_geometry_msgs::PoseStamped start = robot_nav_2d_utils::pose2DToPoseStamped(local_pose); - robot_geometry_msgs::PoseStamped goal = robot_nav_2d_utils::pose2DToPoseStamped(local_goal); - std::vector docking_plan; - robot::log_info_at(__FILE__, __LINE__, "start %s %f %f", start.header.frame_id.c_str(), start.pose.position.x, start.pose.position.y); - robot::log_info_at(__FILE__, __LINE__, "goal %s %f %f", goal.header.frame_id.c_str(), goal.pose.position.x, goal.pose.position.y); - if (!docking_planner_->makePlan(start, goal, docking_plan)) - { - throw robot_nav_core2::LocalPlannerException("Making plan from goal maker is failed"); - return false; - } - else - { - local_path = robot_nav_2d_utils::posesToPath(docking_plan); - return true; - } -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::detectedTimeOutCb(const ::robot::WallTimerEvent &timer_event) -{ - detected_timeout_ = true; - detected_timeout_wt_.stop(); - robot::log_warning_at(__FILE__, __LINE__, "%s time_out end %f", name_.c_str(), robot::Time::now().toSec()); -} - -void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::delayCb(const ::robot::WallTimerEvent &timer_event) -{ - delayed_ = true; - delayed_wt_.stop(); - robot::log_warning_at(__FILE__, __LINE__, "%s delay end %f", name_.c_str(), robot::Time::now().toSec()); -} - -robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXDockingLocalPlanner::create() -{ - return std::make_shared(); -} - -// register this planner as a LocalPlanner plugin -BOOST_DLL_ALIAS(pnkx_local_planner::PNKXDockingLocalPlanner::create, PNKXDockingLocalPlanner) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +pnkx_local_planner::PNKXDockingLocalPlanner::PNKXDockingLocalPlanner() + : PNKXLocalPlanner(), + start_docking_(false), + original_xy_goal_tolerance_(0.0), + original_yaw_goal_tolerance_(0.0) +{ +} + +pnkx_local_planner::PNKXDockingLocalPlanner::~PNKXDockingLocalPlanner() +{ + if (traj_generator_) + traj_generator_.reset(); + + if (nav_algorithm_) + nav_algorithm_.reset(); + + if (rotate_algorithm_) + rotate_algorithm_.reset(); + + if (goal_checker_) + goal_checker_.reset(); +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::initialize(robot::NodeHandle &parent, const std::string &name, + TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) +{ + if (!initialized_) + { + tf_ = tf; + name_ = name; + costmap_robot_ = costmap_robot; + costmap_ = costmap_robot_->getCostmap(); + + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + + parent_ = parent; + planner_nh_ = robot::NodeHandle(parent_, name); + robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str()); + this->getParams(planner_nh_); + + std::string traj_generator_name; + planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("StandardTrajectoryGenerator")); + robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(traj_generator_name); + traj_gen_loader_ = boost::dll::import_alias( + path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); + traj_generator_ = traj_gen_loader_(); + if (!traj_generator_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); + traj_generator_->initialize(nh_traj_gen); + robot::log_info_at(__FILE__, __LINE__, "Successfully initialized trajectory generator \"%s\"", traj_generator_name.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + + std::string algorithm_nav_name; + planner_nh_.getParam("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); + robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(algorithm_nav_name); + nav_algorithm_loader_ = boost::dll::import_alias( + path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations); + nav_algorithm_ = nav_algorithm_loader_(); + if (!nav_algorithm_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to load algorithm %s", algorithm_nav_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + + std::string algorithm_rotate_name; + planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("MKTAlgorithmDiffRotateToGoal")); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name); + rotate_algorithm_loader_ = boost::dll::import_alias( + path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations); + rotate_algorithm_ = rotate_algorithm_loader_(); + if (!rotate_algorithm_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create rotate algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); + } + rotate_algorithm_->initialize(parent_, algorithm_rotate_name, tf, costmap_robot_, traj_generator_); + robot::log_info_at(__FILE__, __LINE__, "Successfully initialized rotate algorithm \"%s\"", algorithm_rotate_name.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s rotate algorithm, are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); + } + + std::string goal_checker_name; + planner_nh_.param("goal_checker_name", goal_checker_name, std::string("dwb_plugins::SimpleGoalChecker")); + robot::log_info_at(__FILE__, __LINE__, "goal_checker_name: %s", goal_checker_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(goal_checker_name); + goal_checker_loader_ = boost::dll::import_alias( + path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); + goal_checker_ = goal_checker_loader_(); + if (!goal_checker_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + goal_checker_->initialize(parent_); + robot::log_info_at(__FILE__, __LINE__, "Successfully initialized goal checker \"%s\"", goal_checker_name.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Unexpected exception while creating goal checker \"%s\": %s", goal_checker_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + + this->initializeOthers(); + this->getMaker(); + robot::log_info_at(__FILE__, __LINE__, "%s is sucessed", name.c_str()); + initialized_ = true; + } +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::getMaker() +{ + std::string maker_name, maker_sources; + parent_.param("maker_name", maker_name, std::string("")); + parent_.param("maker_sources", maker_sources, std::string("")); + robot::log_info_at(__FILE__, __LINE__, "maker_name: %s", maker_name.c_str()); + robot::log_info_at(__FILE__, __LINE__, "maker_sources: %s", maker_sources.c_str()); + std::stringstream ss(maker_sources); + std::string source; + + while (ss >> source) + { + if (maker_name == source) + { + robot::NodeHandle source_node(parent_, source); + + if (source_node.hasParam("plugins")) + { + robot_xmlrpcpp::XmlRpcValue plugins; + source_node.getParam("plugins", plugins); + + if (plugins.getType() == robot_xmlrpcpp::XmlRpcValue::TypeArray) + { + for (int i = 0; i < plugins.size(); ++i) + { + if (plugins[i].getType() == robot_xmlrpcpp::XmlRpcValue::TypeStruct) + { + std::stringstream name; + name << source << "/" << static_cast(plugins[i]["name"]); + std::string docking_planner_name = static_cast(plugins[i]["docking_planner"]); + std::string docking_nav_name = static_cast(plugins[i]["docking_nav"]); + // std::shared_ptr dkpl = std::make_shared(name.str()); + DockingPlanner* dkpl = new DockingPlanner(name.str()); + dkpl->docking_planner_name_ = docking_planner_name; + dkpl->docking_nav_name_ = docking_nav_name; + dkpl_.push_back(dkpl); + } + } + } + else + { + robot::log_warning_at(__FILE__, __LINE__, "Expected 'plugins' to be an array under namespace [%s]", source.c_str()); + } + } + else + { + robot::log_warning_at(__FILE__, __LINE__, "No 'plugins' found under namespace [%s]", source.c_str()); + } + break; + } + } +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::initializeOthers() +{ + std::string algorithm_nav_name; + planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); + if (!parent_.getParam(algorithm_nav_name, original_papams_)) + robot::log_warning_at(__FILE__, __LINE__, "No found in %s in yaml-file, please check configuration", algorithm_nav_name.c_str()); + original_xy_goal_tolerance_ = xy_goal_tolerance_; + original_yaw_goal_tolerance_ = yaw_goal_tolerance_; +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::getParams(robot::NodeHandle &nh) +{ + // This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window + nh.param("update_costmap_before_planning", update_costmap_before_planning_, true); + if (!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) + { + xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); + } + if (!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) + { + yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); + } +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::reset() +{ + robot::log_info_at(__FILE__, __LINE__, "New Docking Goal Received."); + this->unlock(); + if(traj_generator_) traj_generator_->reset(); + if(goal_checker_) goal_checker_->reset(); + if(nav_algorithm_) nav_algorithm_->reset(); + if(rotate_algorithm_) rotate_algorithm_->reset(); + ret_nav_ = ret_angle_ = false; + + std::string algorithm_nav_name; + planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); + + parent_.setParam(algorithm_nav_name, original_papams_); + robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); + nh_algorithm.setParam("allow_rotate", false); +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + this->getParams(planner_nh_); + if (update_costmap_before_planning_) + { + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + } + + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), + local_goal_pose = this->transformPoseToLocal(goal_pose_); + if (start_docking_) + { + local_goal_pose = goal_pose_; + } + + try + { + if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) + robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed"); + } + catch(const robot_nav_core2::LocalPlannerException& e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } + + double x_direction, y_direction, theta_direction; + if (!ret_nav_) + { + if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + } + // else + // ROS_INFO_THROTTLE(0.2, "chieu %f %f %f", x_direction, y_direction, theta_direction); + + if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_) + { + this->lock(); + robot_geometry_msgs::Vector3 linear = dkpl_.front()->linear_; + traj_generator_->setTwistLinear(linear); + linear.x *= (-1); + traj_generator_->setTwistLinear(linear); + traj_generator_->setTwistAngular(dkpl_.front()->angular_); + + std::string algorithm_nav_name; + planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); + robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); + nh_algorithm.setParam("allow_rotate", dkpl_.front()->allow_rotate_); + nh_algorithm.setParam("min_lookahead_dist", dkpl_.front()->min_lookahead_dist_); + nh_algorithm.setParam("max_lookahead_dist", dkpl_.front()->max_lookahead_dist_); + nh_algorithm.setParam("lookahead_time", dkpl_.front()->lookahead_time_); + nh_algorithm.setParam("angle_threshold", dkpl_.front()->angle_threshold_); + + parent_.setParam("xy_goal_tolerance", dkpl_.front()->xy_goal_tolerance_); + parent_.setParam("yaw_goal_tolerance", dkpl_.front()->yaw_goal_tolerance_); + + if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_) + { + + if (dkpl_.front()->following_) + { + robot_nav_2d_msgs::Pose2DStamped follow_pose; + if (dkpl_.front()->geLocalGoal(local_goal_pose)) + { + local_goal_pose = follow_pose; + } + } + if (!dkpl_.front()->docking_nav_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); + } + } + } + } + else + { + if (!rotate_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", rotate_algorithm_->getName().c_str()); + } + // else + // ROS_INFO("chieu %f %f %f", x_direction, y_direction, theta_direction); + } + + int xytheta_direct[3]; + xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; + xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; + xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; + traj_generator_->setDirect(xytheta_direct); +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_nav_2d_msgs::Twist2D &velocity) +{ + // boost::recursive_mutex::scoped_lock l(configuration_mutex_); + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + try + { + if (global_plan_.poses.empty()) + return cmd_vel; + this->prepare(pose, velocity); + cmd_vel = this->ScoreAlgorithm(pose, velocity); + return cmd_vel; + } + catch (const robot_nav_core2::PlannerException &e) + { + robot::log_warning_at(__FILE__, __LINE__, "%s", e.what()); + throw robot_nav_core2::LocalPlannerException(e.what()); + } +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + robot_nav_2d_msgs::Twist2D twist; + mkt_msgs::Trajectory2D traj; + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + cmd_vel.header.stamp = robot::Time::now(); + + if (ret_nav_ && ret_angle_) + return cmd_vel; + else if (!ret_nav_) + { + traj = nav_algorithm_->calculator(pose, velocity); + if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_) + { + if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_) + { + traj = dkpl_.front()->docking_nav_->calculator(pose, velocity); + } + } + local_plan_.header.stamp = robot::Time::now(); + robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); + local_plan_ = robot_nav_2d_utils::pathToPath(path); + } + else + { + traj = rotate_algorithm_->calculator(pose, velocity); + local_plan_.header.stamp = robot::Time::now(); + robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); + local_plan_ = robot_nav_2d_utils::pathToPath(path); + } + + cmd_vel.velocity = traj.velocity; + return cmd_vel; +} + +bool pnkx_local_planner::PNKXDockingLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + if (goal_pose_.header.frame_id == "") + { + robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); + return false; + } + + bool dock_ok = dockingHanlde(pose, velocity); + + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); + robot_nav_2d_msgs::Pose2DStamped local_goal = this->transformPoseToLocal(goal_pose_); + robot_nav_2d_msgs::Path2D plan = transformed_global_plan_; + if (start_docking_) + { + local_goal = goal_pose_; + if (!dkpl_.empty() && dkpl_.front()->initialized_) + { + if (dkpl_.front()->allow_rotate_) + plan = robot_nav_2d_msgs::Path2D(); + } + } + + if (!ret_nav_) + { + ret_nav_ = goal_checker_->isGoalReached(local_pose, local_goal, plan, velocity); + + if (ret_nav_) + { + robot::log_info_at(__FILE__, __LINE__, "local_pose %f %f %f", local_pose.pose.x, local_pose.pose.y, local_pose.pose.theta); + robot::log_info_at(__FILE__, __LINE__, "local_goal %f %f %f", local_goal.pose.x, local_goal.pose.y, local_goal.pose.theta); + } + } + + if (ret_nav_ && !ret_angle_ && !dock_ok) + { + double delta_orient = + fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta)); + ret_angle_ = (bool)(delta_orient <= yaw_goal_tolerance_); + if(ret_angle_) + robot::log_warning_at(__FILE__, __LINE__, "xy_goal_tolerance %f yaw_goal_tolerance %f",xy_goal_tolerance_, yaw_goal_tolerance_); + } + + if (start_docking_) + { + double dx = local_goal.pose.x - local_pose.pose.x; + double dy = local_goal.pose.y - local_pose.pose.y; + double dtheta = local_goal.pose.theta - local_pose.pose.theta; + } + if (ret_nav_ && ret_angle_ && dock_ok) + { + // nh_.setParam("xy_goal_tolerance", original_xy_goal_tolerance_); + // nh_.setParam("yaw_goal_tolerance", original_yaw_goal_tolerance_); + std::string algorithm_nav_name; + planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); + robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); + parent_.setParam(algorithm_nav_name, original_papams_); + nh_algorithm.setParam("allow_rotate", false); + } + return ret_nav_ && ret_angle_ && dock_ok; +} + +bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + if (!dkpl_.empty()) + { + if (ret_nav_ && ret_angle_) + { + if (!dkpl_.front()->is_detected_) + { + if (!dkpl_.front()->initialized_) + { + dkpl_.front()->initialize(parent_, tf_, costmap_robot_, traj_generator_); + dkpl_.front()->initialized_ = true; + } + else + { + if (dkpl_.front()->docking_planner_ && !dkpl_.front()->docking_nav_) + { + robot_nav_2d_msgs::Pose2DStamped local_goal; + try + { + if (dkpl_.front()->geLocalGoal(local_goal)) + { + dkpl_.front()->is_detected_ = true; + start_docking_ = true; + robot_nav_msgs::Path path; + robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); + dkpl_.front()->getLocalPath(local_pose, local_goal, path); + this->setPlan(robot_nav_2d_utils::pathToPath(path)); + this->setGoalPose(local_goal); + } + } + catch (const std::exception &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } + } + else if (!dkpl_.front()->docking_planner_ && dkpl_.front()->docking_nav_) + { + robot_nav_2d_msgs::Pose2DStamped local_goal; + try + { + if (dkpl_.front()->geLocalGoal(local_goal)) + { + dkpl_.front()->is_detected_ = true; + start_docking_ = true; + robot_nav_2d_msgs::Path2D path; + robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); + path.header.stamp = robot::Time::now(); + path.header.frame_id = costmap_robot_->getGlobalFrameID(); + path.poses.push_back(local_pose); + path.poses.push_back(local_goal); + this->setPlan(path); + this->setGoalPose(local_goal); + } + } + catch (const std::exception &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } + } + } + } + else + { + if (dkpl_.front()->initialized_ && !dkpl_.front()->is_goal_reached_) + { + dkpl_.front()->is_goal_reached_ = true; + robot::log_info_at(__FILE__, __LINE__, "%s is goal reached", dkpl_.front()->name_.c_str()); + } + + if (dkpl_.front()->initialized_ && dkpl_.front()->is_goal_reached_) + { + if(!dkpl_.empty()) + { + // if(dkpl_.front()) delete(dkpl_.front()); + dkpl_.erase(dkpl_.begin()); + } + start_docking_ = false; + } + } + } + } + bool result = false; + if (dkpl_.empty()) + { + robot::log_info_at(__FILE__, __LINE__, "Goal reached!"); + result = true; + this->getMaker(); + } + return result; +} + +pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::DockingPlanner(const std::string &name) + : initialized_(false), + is_detected_(false), + is_goal_reached_(false), + following_(false), + allow_rotate_(false), + xy_goal_tolerance_(0.05), + yaw_goal_tolerance_(0.05), + min_lookahead_dist_(0.4), + max_lookahead_dist_(1.0), + lookahead_time_(1.5), + angle_threshold_(0.4), + name_(name), + docking_planner_name_(), + docking_nav_name_(), + docking_planner_(nullptr), + docking_nav_(nullptr), + linear_(), + angular_(), + nh_(), + nh_priv_(), + tf_(nullptr), + costmap_robot_(nullptr), + traj_generator_(), + docking_planner_loader_(), + docking_nav_loader_(), + detected_timeout_wt_(), + delayed_wt_(), + delayed_(false), + detected_timeout_(false), + robot_base_frame_(), + maker_goal_frame_() +{ +} + +pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::~DockingPlanner() +{ + detected_timeout_wt_.stop(); + delayed_wt_.stop(); + if (docking_planner_ != nullptr) { + docking_planner_.reset(); + } + if (docking_nav_ != nullptr) { + docking_nav_.reset(); + } +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::initialize(robot::NodeHandle &nh, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, + score_algorithm::TrajectoryGenerator::Ptr traj_generator) +{ + nh_ = nh; + nh_priv_ = robot::NodeHandle(nh_, name_); + tf_ = tf; + costmap_robot_ = costmap_robot; + traj_generator_ = traj_generator; + + if (docking_planner_name_ != std::string("")) + { + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(docking_planner_name_); + docking_planner_loader_ = boost::dll::import_alias( + path_file_so, docking_planner_name_, boost::dll::load_mode::append_decorations); + docking_planner_ = docking_planner_loader_(); + if (!docking_planner_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create global planner \"%s\": returned null pointer", docking_planner_name_.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create global planner"); + } + docking_planner_->initialize(name_, costmap_robot_); + robot::log_info_at(__FILE__, __LINE__, "Created global_planner %s", docking_planner_name_.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s", + docking_planner_name_.c_str(), ex.what()); + } + } + + if (docking_nav_name_ != std::string("")) + { + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(docking_nav_name_); + docking_nav_loader_ = boost::dll::import_alias( + path_file_so, docking_nav_name_, boost::dll::load_mode::append_decorations); + docking_nav_ = docking_nav_loader_(); + if (!docking_nav_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create docking nav \"%s\": returned null pointer", docking_nav_name_.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create docking nav"); + } + robot::NodeHandle nh_docking_nav = robot::NodeHandle(nh_priv_, docking_nav_name_); + docking_nav_->initialize(nh_docking_nav, docking_nav_name_, tf_, costmap_robot_, traj_generator_); + robot::log_info_at(__FILE__, __LINE__, "Created docking nav %s", docking_nav_name_.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s", + docking_nav_name_.c_str(), ex.what()); + } + } + + robot_base_frame_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "robot_base_frame", std::string("base_link")); + if (!nh_priv_.param("maker_goal_frame", maker_goal_frame_, std::string(""))) + { + std::stringstream re; + re << "Can not get 'maker_goal_frame' in " << name_; + robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str()); + throw robot_nav_core2::LocalPlannerException(re.str()); + } + + nh_priv_.param("vel_x", linear_.x, 0.5); + nh_priv_.param("vel_theta", angular_.z, 0.5); + nh_priv_.param("following", following_, false); + nh_priv_.param("allow_rotate", allow_rotate_, false); + + double delay_time, time_out; + nh_priv_.param("delay", delay_time, 1.0); + nh_priv_.param("timeout", time_out, 1.0); + + nh_priv_.param("xy_goal_tolerance", xy_goal_tolerance_, 0.05); + nh_priv_.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.05); + + nh_priv_.param("min_lookahead_dist", min_lookahead_dist_, 0.4); + nh_priv_.param("max_lookahead_dist", max_lookahead_dist_, 1.0); + nh_priv_.param("lookahead_time", lookahead_time_, 1.5); + nh_priv_.param("angle_threshold", angle_threshold_, 0.4); + + robot::log_info("delay: %f", delay_time); + robot::log_info("timeout: %f", time_out); + robot::log_info("xy_goal_tolerance: %f", xy_goal_tolerance_); + robot::log_info("yaw_goal_tolerance: %f", yaw_goal_tolerance_); + robot::log_info("min_lookahead_dist: %f", min_lookahead_dist_); + robot::log_info("max_lookahead_dist: %f", max_lookahead_dist_); + robot::log_info("lookahead_time: %f", lookahead_time_); + robot::log_info("angle_threshold: %f", angle_threshold_); + + detected_timeout_wt_ = ::robot::WallTimer( + ::robot::WallDuration(time_out + delay_time), &pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::detectedTimeOutCb, this, false, false); + detected_timeout_wt_.start(); + robot::log_warning_at(__FILE__, __LINE__, "%s %f time_out start %f", name_.c_str(), delay_time, robot::Time::now().toSec()); + + delayed_wt_ = ::robot::WallTimer( + ::robot::WallDuration(delay_time), &pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::delayCb, this, false, false); + delayed_wt_.start(); + robot::log_warning_at(__FILE__, __LINE__, "%s %f delay start %f", name_.c_str(), delay_time, robot::Time::now().toSec()); + + initialized_ = true; +} + +bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::getMakerGoal(robot_nav_2d_msgs::Pose2DStamped &maker_goal) +{ + if (!delayed_) + return false; + + bool get_pose_result = false; + try + { + if (pnkx_local_planner::getPose(tf_, maker_goal_frame_, robot_base_frame_, maker_goal, 2.0)) + { + get_pose_result = true; + detected_timeout_wt_.stop(); + } + + if (get_pose_result) + return true; + } + catch (const std::exception &e) + { + if (detected_timeout_) + { + std::stringstream re; + re << "No detected " << maker_goal_frame_; + robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str()); + throw robot_nav_core2::LocalPlannerException(re.str()); + } + } + return false; +} + +bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::geLocalGoal(robot_nav_2d_msgs::Pose2DStamped &local_goal) +{ + if (!delayed_) + return false; + bool get_pose_result = false; + try + { + robot_nav_2d_msgs::Pose2DStamped maker_goal_on_robot; + if (pnkx_local_planner::getPose(tf_, maker_goal_frame_, robot_base_frame_, maker_goal_on_robot, 2.0)) + { + if (robot_nav_2d_utils::transformPose(tf_, costmap_robot_->getGlobalFrameID(), maker_goal_on_robot, local_goal)) + { + get_pose_result = true; + detected_timeout_wt_.stop(); + } + } + + if (get_pose_result) + return true; + } + catch (const std::exception &e) + { + if (detected_timeout_) + { + std::stringstream re; + re << "No detected " << maker_goal_frame_; + robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str()); + throw robot_nav_core2::LocalPlannerException(re.str()); + } + } + return false; +} + +bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::getLocalPath( + const robot_nav_2d_msgs::Pose2DStamped &local_pose, const robot_nav_2d_msgs::Pose2DStamped &local_goal, robot_nav_msgs::Path &local_path) +{ + robot_geometry_msgs::PoseStamped start = robot_nav_2d_utils::pose2DToPoseStamped(local_pose); + robot_geometry_msgs::PoseStamped goal = robot_nav_2d_utils::pose2DToPoseStamped(local_goal); + std::vector docking_plan; + robot::log_info_at(__FILE__, __LINE__, "start %s %f %f", start.header.frame_id.c_str(), start.pose.position.x, start.pose.position.y); + robot::log_info_at(__FILE__, __LINE__, "goal %s %f %f", goal.header.frame_id.c_str(), goal.pose.position.x, goal.pose.position.y); + if (!docking_planner_->makePlan(start, goal, docking_plan)) + { + throw robot_nav_core2::LocalPlannerException("Making plan from goal maker is failed"); + return false; + } + else + { + local_path = robot_nav_2d_utils::posesToPath(docking_plan); + return true; + } +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::detectedTimeOutCb(const ::robot::WallTimerEvent &timer_event) +{ + detected_timeout_ = true; + detected_timeout_wt_.stop(); + robot::log_warning_at(__FILE__, __LINE__, "%s time_out end %f", name_.c_str(), robot::Time::now().toSec()); +} + +void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::delayCb(const ::robot::WallTimerEvent &timer_event) +{ + delayed_ = true; + delayed_wt_.stop(); + robot::log_warning_at(__FILE__, __LINE__, "%s delay end %f", name_.c_str(), robot::Time::now().toSec()); +} + +robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXDockingLocalPlanner::create() +{ + return std::make_shared(); +} + +// register this planner as a LocalPlanner plugin +BOOST_DLL_ALIAS(pnkx_local_planner::PNKXDockingLocalPlanner::create, PNKXDockingLocalPlanner) diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_go_straight_local_planner.cpp b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_go_straight_local_planner.cpp index 4e11876..fc4bd66 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_go_straight_local_planner.cpp +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_go_straight_local_planner.cpp @@ -1,260 +1,260 @@ -#include -#include -#include -#include -#include -#include - -// #include -// #include -// #include -#include -#include -#include "pnkx_local_planner/pnkx_go_straight_local_planner.h" -#include -#include - -pnkx_local_planner::PNKXGoStraightLocalPlanner::PNKXGoStraightLocalPlanner() - : PNKXLocalPlanner() -{ -} - -pnkx_local_planner::PNKXGoStraightLocalPlanner::~PNKXGoStraightLocalPlanner() -{ - if (traj_generator_) - traj_generator_.reset(); - - if (nav_algorithm_) - nav_algorithm_.reset(); - - if (goal_checker_) - goal_checker_.reset(); -} - -void pnkx_local_planner::PNKXGoStraightLocalPlanner::initialize(robot::NodeHandle& parent, const std::string& name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT* costmap_robot) -{ - if (!initialized_) - { - robot::log_info_at(__FILE__, __LINE__, "Using parent name \"%s\"", name.c_str()); - if(costmap_robot == nullptr) - { - robot::log_error_at(__FILE__, __LINE__, "Costmap2DROBOT is nullptr"); - throw robot_nav_core2::LocalPlannerException("Costmap2DROBOT is nullptr"); - } - if(tf == nullptr) - { - robot::log_error_at(__FILE__, __LINE__, "TFListener is nullptr"); - throw robot_nav_core2::LocalPlannerException("TFListener is nullptr"); - } - tf_ = tf; - costmap_robot_ = costmap_robot; - costmap_ = costmap_robot_->getCostmap(); - - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - - parent_ = parent; - planner_nh_ = robot::NodeHandle(parent_, name); - robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str()); - this->getParams(planner_nh_); - - // This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window - std::string traj_generator_name; - planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("nav_plugins::StandardTrajectoryGenerator")); - robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); - - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(traj_generator_name); - traj_gen_loader_ = boost::dll::import_alias( - path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); - traj_generator_ = traj_gen_loader_(); - if (!traj_generator_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); - traj_generator_->initialize(nh_traj_gen); - } - catch (const std::exception& ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - - std::string algorithm_nav_name = std::string("pnkx_local_planner::GoStraight"); - planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::GoStraight")); - robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(algorithm_nav_name); - nav_algorithm_loader_ = boost::dll::import_alias( - path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations); - nav_algorithm_ = nav_algorithm_loader_(); - if (!nav_algorithm_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create algorithm \"%s\": returned null pointer", algorithm_nav_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_); - } - catch (const std::exception& ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - - std::string goal_checker_name; - planner_nh_.param("goal_checker_name", goal_checker_name, std::string("score_algorithm::GoalChecker")); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(goal_checker_name); - goal_checker_loader_ = boost::dll::import_alias( - path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); - goal_checker_ = goal_checker_loader_(); - if (!goal_checker_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - robot::NodeHandle nh_goal_checker = robot::NodeHandle(parent_, goal_checker_name); - goal_checker_->initialize(nh_goal_checker); - } - catch (const std::exception& ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s Goal checker , are you sure it is properly registered and that the containing library is built? Exception: %s", goal_checker_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - - robot::log_info_at(__FILE__, __LINE__, "%s is initialized", name.c_str()); - initialized_ = true; - } -} - -void pnkx_local_planner::PNKXGoStraightLocalPlanner::reset() -{ - robot::log_info_at(__FILE__, __LINE__, "New Goal Received."); - this->unlock(); - traj_generator_->reset(); - goal_checker_->reset(); - nav_algorithm_->reset(); - ret_nav_ = ret_angle_ = false; -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXGoStraightLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped& pose, - const robot_nav_2d_msgs::Twist2D& velocity) -{ - // boost::recursive_mutex::scoped_lock l(configuration_mutex_); - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - try - { - if (global_plan_.poses.empty()) - return cmd_vel; - this->prepare(pose, velocity); - cmd_vel = this->ScoreAlgorithm(pose, velocity); - return cmd_vel; - } - catch (const robot_nav_core2::PlannerException &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } -} - -void pnkx_local_planner::PNKXGoStraightLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - this->getParams(planner_nh_); - if (update_costmap_before_planning_) - { - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - } - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), - local_goal_pose = this->transformPoseToLocal(goal_pose_); - - try - { - if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) - throw robot_nav_core2::LocalPlannerException("Transform global plan is failed"); - } - catch(const robot_nav_core2::LocalPlannerException& e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } - - double x_direction, y_direction, theta_direction; - if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - } - - int xytheta_direct[3]; - xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; - xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; - xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; - traj_generator_->setDirect(xytheta_direct); -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXGoStraightLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - robot_nav_2d_msgs::Twist2D twist; - mkt_msgs::Trajectory2D traj; - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - cmd_vel.header.stamp = robot::Time::now(); - - if (ret_nav_) - { - local_plan_.poses.clear(); - return cmd_vel; - } - - traj = nav_algorithm_->calculator(pose, velocity); - local_plan_.header.stamp = robot::Time::now(); - robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); - local_plan_ = robot_nav_2d_utils::pathToPath(path); - cmd_vel.velocity = traj.velocity; - return cmd_vel; -} - -bool pnkx_local_planner::PNKXGoStraightLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - if (goal_pose_.header.frame_id == "") - { - robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); - return false; - } - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - ret_nav_ = goal_checker_->isGoalReached(transformPoseToLocal(pose), transformPoseToLocal(goal_pose_), transformed_global_plan_, velocity); - - if (ret_nav_) - robot::log_info_at(__FILE__, __LINE__, "Goal reached!"); - return ret_nav_; -} - -robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXGoStraightLocalPlanner::create() -{ - return std::make_shared(); -} - -// register this planner as a LocalPlanner plugin +#include +#include +#include +#include +#include +#include + +// #include +// #include +// #include +#include +#include +#include "pnkx_local_planner/pnkx_go_straight_local_planner.h" +#include +#include + +pnkx_local_planner::PNKXGoStraightLocalPlanner::PNKXGoStraightLocalPlanner() + : PNKXLocalPlanner() +{ +} + +pnkx_local_planner::PNKXGoStraightLocalPlanner::~PNKXGoStraightLocalPlanner() +{ + if (traj_generator_) + traj_generator_.reset(); + + if (nav_algorithm_) + nav_algorithm_.reset(); + + if (goal_checker_) + goal_checker_.reset(); +} + +void pnkx_local_planner::PNKXGoStraightLocalPlanner::initialize(robot::NodeHandle& parent, const std::string& name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT* costmap_robot) +{ + if (!initialized_) + { + robot::log_info_at(__FILE__, __LINE__, "Using parent name \"%s\"", name.c_str()); + if(costmap_robot == nullptr) + { + robot::log_error_at(__FILE__, __LINE__, "Costmap2DROBOT is nullptr"); + throw robot_nav_core2::LocalPlannerException("Costmap2DROBOT is nullptr"); + } + if(tf == nullptr) + { + robot::log_error_at(__FILE__, __LINE__, "TFListener is nullptr"); + throw robot_nav_core2::LocalPlannerException("TFListener is nullptr"); + } + tf_ = tf; + costmap_robot_ = costmap_robot; + costmap_ = costmap_robot_->getCostmap(); + + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + + parent_ = parent; + planner_nh_ = robot::NodeHandle(parent_, name); + robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str()); + this->getParams(planner_nh_); + + // This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window + std::string traj_generator_name; + planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("nav_plugins::StandardTrajectoryGenerator")); + robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); + + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(traj_generator_name); + traj_gen_loader_ = boost::dll::import_alias( + path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); + traj_generator_ = traj_gen_loader_(); + if (!traj_generator_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); + traj_generator_->initialize(nh_traj_gen); + } + catch (const std::exception& ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + + std::string algorithm_nav_name = std::string("pnkx_local_planner::GoStraight"); + planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::GoStraight")); + robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(algorithm_nav_name); + nav_algorithm_loader_ = boost::dll::import_alias( + path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations); + nav_algorithm_ = nav_algorithm_loader_(); + if (!nav_algorithm_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create algorithm \"%s\": returned null pointer", algorithm_nav_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_); + } + catch (const std::exception& ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + + std::string goal_checker_name; + planner_nh_.param("goal_checker_name", goal_checker_name, std::string("score_algorithm::GoalChecker")); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(goal_checker_name); + goal_checker_loader_ = boost::dll::import_alias( + path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); + goal_checker_ = goal_checker_loader_(); + if (!goal_checker_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + robot::NodeHandle nh_goal_checker = robot::NodeHandle(parent_, goal_checker_name); + goal_checker_->initialize(nh_goal_checker); + } + catch (const std::exception& ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s Goal checker , are you sure it is properly registered and that the containing library is built? Exception: %s", goal_checker_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + + robot::log_info_at(__FILE__, __LINE__, "%s is initialized", name.c_str()); + initialized_ = true; + } +} + +void pnkx_local_planner::PNKXGoStraightLocalPlanner::reset() +{ + robot::log_info_at(__FILE__, __LINE__, "New Goal Received."); + this->unlock(); + traj_generator_->reset(); + goal_checker_->reset(); + nav_algorithm_->reset(); + ret_nav_ = ret_angle_ = false; +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXGoStraightLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped& pose, + const robot_nav_2d_msgs::Twist2D& velocity) +{ + // boost::recursive_mutex::scoped_lock l(configuration_mutex_); + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + try + { + if (global_plan_.poses.empty()) + return cmd_vel; + this->prepare(pose, velocity); + cmd_vel = this->ScoreAlgorithm(pose, velocity); + return cmd_vel; + } + catch (const robot_nav_core2::PlannerException &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } +} + +void pnkx_local_planner::PNKXGoStraightLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + this->getParams(planner_nh_); + if (update_costmap_before_planning_) + { + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + } + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), + local_goal_pose = this->transformPoseToLocal(goal_pose_); + + try + { + if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) + throw robot_nav_core2::LocalPlannerException("Transform global plan is failed"); + } + catch(const robot_nav_core2::LocalPlannerException& e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } + + double x_direction, y_direction, theta_direction; + if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + } + + int xytheta_direct[3]; + xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; + xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; + xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; + traj_generator_->setDirect(xytheta_direct); +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXGoStraightLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + robot_nav_2d_msgs::Twist2D twist; + mkt_msgs::Trajectory2D traj; + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + cmd_vel.header.stamp = robot::Time::now(); + + if (ret_nav_) + { + local_plan_.poses.clear(); + return cmd_vel; + } + + traj = nav_algorithm_->calculator(pose, velocity); + local_plan_.header.stamp = robot::Time::now(); + robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); + local_plan_ = robot_nav_2d_utils::pathToPath(path); + cmd_vel.velocity = traj.velocity; + return cmd_vel; +} + +bool pnkx_local_planner::PNKXGoStraightLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + if (goal_pose_.header.frame_id == "") + { + robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); + return false; + } + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + ret_nav_ = goal_checker_->isGoalReached(transformPoseToLocal(pose), transformPoseToLocal(goal_pose_), transformed_global_plan_, velocity); + + if (ret_nav_) + robot::log_info_at(__FILE__, __LINE__, "Goal reached!"); + return ret_nav_; +} + +robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXGoStraightLocalPlanner::create() +{ + return std::make_shared(); +} + +// register this planner as a LocalPlanner plugin BOOST_DLL_ALIAS(pnkx_local_planner::PNKXGoStraightLocalPlanner::create, PNKXGoStraightLocalPlanner) \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_local_planner.cpp b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_local_planner.cpp index c595656..2957991 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_local_planner.cpp +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_local_planner.cpp @@ -1,494 +1,492 @@ -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -pnkx_local_planner::PNKXLocalPlanner::PNKXLocalPlanner() - : initialized_(false), - traj_generator_(nullptr), - nav_algorithm_(nullptr), - rotate_algorithm_(nullptr), - goal_checker_(nullptr), - tf_(nullptr), - costmap_(nullptr), - costmap_robot_(nullptr), - info_(), - update_costmap_before_planning_(false), - ret_angle_(false), - ret_nav_(false), - yaw_goal_tolerance_(0.0), - xy_goal_tolerance_(0.0), - lock_(false) -{ -} - -pnkx_local_planner::PNKXLocalPlanner::~PNKXLocalPlanner() -{ - if (traj_generator_) - traj_generator_.reset(); - - if (nav_algorithm_) - nav_algorithm_.reset(); - - if (rotate_algorithm_) - rotate_algorithm_.reset(); - - if (goal_checker_) - goal_checker_.reset(); -} - -void pnkx_local_planner::PNKXLocalPlanner::initialize(robot::NodeHandle &parent, const std::string &name, - TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) -{ - if (!initialized_) - { - tf_ = tf; - name_ = name; - costmap_robot_ = costmap_robot; - costmap_ = costmap_robot_->getCostmap(); - - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - - parent_ = parent; - planner_nh_ = robot::NodeHandle(parent_, name); - robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str()); - this->getParams(planner_nh_); - - std::string traj_generator_name; - planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("StandardTrajectoryGenerator")); - robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(traj_generator_name); - traj_gen_loader_ = boost::dll::import_alias( - path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); - traj_generator_ = traj_gen_loader_(); - if (!traj_generator_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); - traj_generator_->initialize(nh_traj_gen); - robot::log_info_at(__FILE__, __LINE__, "Successfully initialized trajectory generator \"%s\"", traj_generator_name.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - - std::string algorithm_nav_name; - planner_nh_.getParam("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); - robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(algorithm_nav_name); - robot::log_info_at(__FILE__, __LINE__, "path_file_so: %s", path_file_so.c_str()); - nav_algorithm_loader_ = boost::dll::import_alias( - path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations); - nav_algorithm_ = nav_algorithm_loader_(); - if (!nav_algorithm_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to load algorithm %s", algorithm_nav_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - - std::string algorithm_rotate_name; - planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("MKTAlgorithmDiffRotateToGoal")); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name); - rotate_algorithm_loader_ = boost::dll::import_alias( - path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations); - rotate_algorithm_ = rotate_algorithm_loader_(); - if (!rotate_algorithm_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create rotate algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); - } - rotate_algorithm_->initialize(parent_, algorithm_rotate_name, tf, costmap_robot_, traj_generator_); - robot::log_info_at(__FILE__, __LINE__, "Successfully initialized rotate algorithm \"%s\"", algorithm_rotate_name.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s rotate algorithm, are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); - } - - std::string goal_checker_name; - planner_nh_.param("goal_checker_name", goal_checker_name, std::string("dwb_plugins::SimpleGoalChecker")); - robot::log_info_at(__FILE__, __LINE__, "goal_checker_name: %s", goal_checker_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(goal_checker_name); - goal_checker_loader_ = boost::dll::import_alias( - path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); - goal_checker_ = goal_checker_loader_(); - if (!goal_checker_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - goal_checker_->initialize(parent_); - robot::log_info_at(__FILE__, __LINE__, "Successfully initialized goal checker \"%s\"", goal_checker_name.c_str()); - } - catch (const std::exception &ex) - { - robot::log_error_at(__FILE__, __LINE__, "Unexpected exception while creating goal checker \"%s\": %s", goal_checker_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - - this->initializeOthers(); - robot::log_info("[%s:%d]\n %s is sucessed", __FILE__, __LINE__, name.c_str()); - initialized_ = true; - } -} - -void pnkx_local_planner::PNKXLocalPlanner::initializeOthers() -{ -} - -void pnkx_local_planner::PNKXLocalPlanner::getParams(robot::NodeHandle &nh) -{ - // This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window - nh.param("update_costmap_before_planning", update_costmap_before_planning_, true); - if (!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) - { - xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); - } - if (!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) - { - yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); - } -} - -void pnkx_local_planner::PNKXLocalPlanner::reset() -{ - this->unlock(); - if(traj_generator_) traj_generator_->reset(); - if(goal_checker_) goal_checker_->reset(); - if(nav_algorithm_) nav_algorithm_->reset(); - if(rotate_algorithm_) rotate_algorithm_->reset(); - ret_nav_ = ret_angle_ = false; -} - -void pnkx_local_planner::PNKXLocalPlanner::setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose) -{ - // boost::recursive_mutex::scoped_lock l(configuration_mutex_); - robot::log_error("[PNKXLocalPlanner] Receive new goal(%f, %f)!", goal_pose.pose.x, goal_pose.pose.y); - reset(); - goal_pose_ = goal_pose; -} - -void pnkx_local_planner::PNKXLocalPlanner::setPlan(const robot_nav_2d_msgs::Path2D &path) -{ - robot::log_error("[PNKXLocalPlanner] size path: %d", (int)path.poses.size()); - // boost::recursive_mutex::scoped_lock l(configuration_mutex_); - costmap_robot_->resetLayers(); - global_plan_ = path; - if((unsigned int)global_plan_.poses.size() > 2) - global_plan_.poses.erase(global_plan_.poses.begin()); - for (unsigned int i = 0; i < (unsigned int)global_plan_.poses.size(); i++) - { - global_plan_.poses[i].header.seq = i; - } -} - -void pnkx_local_planner::PNKXLocalPlanner::getPlan(robot_nav_2d_msgs::Path2D &path) -{ - if (local_plan_.poses.empty()) - { - return; - } - path = local_plan_; - -} - -void pnkx_local_planner::PNKXLocalPlanner::getGlobalPlan(robot_nav_2d_msgs::Path2D &path) -{ - if (global_plan_.poses.empty()) - { - return; - } - path = global_plan_; -} - -void pnkx_local_planner::PNKXLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - this->getParams(planner_nh_); - if (update_costmap_before_planning_) - { - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - } - - // Update time stamp of goal pose - robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), - local_goal_pose = this->transformPoseToLocal(goal_pose_); - - if (!pnkx_local_planner::transformGlobalPlan( - tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) - { - robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed"); - throw robot_nav_core2::LocalPlannerException("Transform global plan is failed"); - } - - double x_direction, y_direction, theta_direction; - if (!ret_nav_) - { - if (nav_algorithm_ && !nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - } - } - else - { - if (rotate_algorithm_ && !rotate_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", rotate_algorithm_->getName().c_str()); - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - } - } - - int xytheta_direct[3]; - xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; - xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; - xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; - if(traj_generator_) traj_generator_->setDirect(xytheta_direct); -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, - const robot_nav_2d_msgs::Twist2D &velocity) -{ - // boost::recursive_mutex::scoped_lock l(configuration_mutex_); - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - try - { - if (global_plan_.poses.empty()) - return cmd_vel; - this->prepare(pose, velocity); - cmd_vel = this->ScoreAlgorithm(pose, velocity); - return cmd_vel; - } - catch (const robot_nav_core2::PlannerException &e) - { - robot::log_warning_at(__FILE__, __LINE__, "PNKXLocalPlanner computing velocity commands has been broken: %s", e.what()); - throw robot_nav_core2::LocalPlannerException("computing velocity commands has been broken"); - return cmd_vel; - } -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - robot_nav_2d_msgs::Twist2D twist; - mkt_msgs::Trajectory2D traj; - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - cmd_vel.header.stamp = robot::Time::now(); - - if (ret_nav_ && ret_angle_) - { - return cmd_vel; - local_plan_.poses.clear(); - } - else if (!ret_nav_) - { - if(nav_algorithm_) traj = nav_algorithm_->calculator(pose, velocity); - local_plan_.header.stamp = robot::Time::now(); - robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); - local_plan_ = robot_nav_2d_utils::pathToPath(path); - } - else - { - if(rotate_algorithm_) traj = rotate_algorithm_->calculator(pose, velocity); - local_plan_.header.stamp = robot::Time::now(); - robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); - local_plan_ = robot_nav_2d_utils::pathToPath(path); - } - - cmd_vel.velocity = traj.velocity; - return cmd_vel; -} - -bool pnkx_local_planner::PNKXLocalPlanner::setTwistLinear(robot_geometry_msgs::Vector3 linear) -{ - try - { - if (linear.x == 0.0 && linear.y == 0.0 && linear.z == 0.0) - { - if (nav_algorithm_) - nav_algorithm_->stop(); - if (rotate_algorithm_) - rotate_algorithm_->stop(); - } - else - { - if (nav_algorithm_) - nav_algorithm_->resume(); - if (rotate_algorithm_) - rotate_algorithm_->resume(); - } - - if (traj_generator_) - return traj_generator_->setTwistLinear(linear); - else - throw robot_nav_core2::LocalPlannerException("Failed to set linear"); - } - catch (const std::exception &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - return false; - } -} - -robot_geometry_msgs::Vector3 pnkx_local_planner::PNKXLocalPlanner::getTwistLinear(bool direct) -{ - try - { - if (traj_generator_) - return traj_generator_->getTwistLinear(direct); - else - throw robot_nav_core2::LocalPlannerException("Failed to get linear"); - } - catch (const std::exception &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } -} - -bool pnkx_local_planner::PNKXLocalPlanner::setTwistAngular(robot_geometry_msgs::Vector3 angular) -{ - try - { - if (traj_generator_) - return traj_generator_->setTwistAngular(angular); - else - throw robot_nav_core2::LocalPlannerException("Failed to set angular"); - } - catch (const std::exception &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - return false; - } -} - -robot_geometry_msgs::Vector3 pnkx_local_planner::PNKXLocalPlanner::getTwistAngular(bool direct) -{ - try - { - if (traj_generator_) - return traj_generator_->getTwistAngular(direct); - else - throw robot_nav_core2::LocalPlannerException("Failed to get angular"); - } - catch (const std::exception &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } -} - -bool pnkx_local_planner::PNKXLocalPlanner::islock() -{ - return lock_; -} - -void pnkx_local_planner::PNKXLocalPlanner::lock() -{ - lock_ = true; -} - -void pnkx_local_planner::PNKXLocalPlanner::unlock() -{ - lock_ = false; -} - -bool pnkx_local_planner::PNKXLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) -{ - if (goal_pose_.header.frame_id == "") - { - robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); - return false; - } - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); - robot_nav_2d_msgs::Pose2DStamped local_goal = this->transformPoseToLocal(goal_pose_); - robot_nav_2d_msgs::Path2D plan = transformed_global_plan_; - if (!ret_nav_) - { - ret_nav_ = goal_checker_->isGoalReached(local_pose, local_goal, plan, velocity); - } - else - { - double delta_orient = fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta)); - ret_angle_ = (bool)(delta_orient <= yaw_goal_tolerance_); - } - - if (ret_nav_ && ret_angle_) - { - robot::log_info_throttle(1.0, "Goal reached!"); - } - return ret_nav_ && ret_angle_; -} - -inline double getSquareDistance(const robot_nav_2d_msgs::Pose2DStamped &pose_a, const robot_nav_2d_msgs::Pose2DStamped &pose_b) -{ - double x_diff = pose_a.pose.x - pose_b.pose.x; - double y_diff = pose_a.pose.y - pose_b.pose.y; - return x_diff * x_diff + y_diff * y_diff; -} - -robot_nav_2d_msgs::Pose2DStamped pnkx_local_planner::PNKXLocalPlanner::transformPoseToLocal(const robot_nav_2d_msgs::Pose2DStamped &pose) -{ - robot_nav_2d_msgs::Pose2DStamped local_pose; - robot_nav_2d_utils::transformPose(tf_, costmap_robot_->getGlobalFrameID(), pose, local_pose); - return local_pose; -} - -robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXLocalPlanner::create() -{ - return std::make_shared(); -} - -// register this planner as a LocalPlanner plugin +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +pnkx_local_planner::PNKXLocalPlanner::PNKXLocalPlanner() + : initialized_(false), + traj_generator_(nullptr), + nav_algorithm_(nullptr), + rotate_algorithm_(nullptr), + goal_checker_(nullptr), + tf_(nullptr), + costmap_(nullptr), + costmap_robot_(nullptr), + info_(), + update_costmap_before_planning_(false), + ret_angle_(false), + ret_nav_(false), + yaw_goal_tolerance_(0.0), + xy_goal_tolerance_(0.0), + lock_(false) +{ +} + +pnkx_local_planner::PNKXLocalPlanner::~PNKXLocalPlanner() +{ + if (traj_generator_) + traj_generator_.reset(); + + if (nav_algorithm_) + nav_algorithm_.reset(); + + if (rotate_algorithm_) + rotate_algorithm_.reset(); + + if (goal_checker_) + goal_checker_.reset(); +} + +void pnkx_local_planner::PNKXLocalPlanner::initialize(robot::NodeHandle &parent, const std::string &name, + TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) +{ + if (!initialized_) + { + tf_ = tf; + name_ = name; + costmap_robot_ = costmap_robot; + costmap_ = costmap_robot_->getCostmap(); + + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + + parent_ = parent; + planner_nh_ = robot::NodeHandle(parent_, name); + robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str()); + this->getParams(planner_nh_); + + std::string traj_generator_name; + planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("StandardTrajectoryGenerator")); + robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(traj_generator_name); + traj_gen_loader_ = boost::dll::import_alias( + path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); + traj_generator_ = traj_gen_loader_(); + if (!traj_generator_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); + traj_generator_->initialize(nh_traj_gen); + robot::log_info_at(__FILE__, __LINE__, "Successfully initialized trajectory generator \"%s\"", traj_generator_name.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + + std::string algorithm_nav_name; + planner_nh_.getParam("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); + robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(algorithm_nav_name); + robot::log_info_at(__FILE__, __LINE__, "path_file_so: %s", path_file_so.c_str()); + nav_algorithm_loader_ = boost::dll::import_alias( + path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations); + nav_algorithm_ = nav_algorithm_loader_(); + if (!nav_algorithm_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to load algorithm %s", algorithm_nav_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + + std::string algorithm_rotate_name; + planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("MKTAlgorithmDiffRotateToGoal")); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name); + rotate_algorithm_loader_ = boost::dll::import_alias( + path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations); + rotate_algorithm_ = rotate_algorithm_loader_(); + if (!rotate_algorithm_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create rotate algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); + } + rotate_algorithm_->initialize(parent_, algorithm_rotate_name, tf, costmap_robot_, traj_generator_); + robot::log_info_at(__FILE__, __LINE__, "Successfully initialized rotate algorithm \"%s\"", algorithm_rotate_name.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s rotate algorithm, are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm"); + } + + std::string goal_checker_name; + planner_nh_.param("goal_checker_name", goal_checker_name, std::string("dwb_plugins::SimpleGoalChecker")); + robot::log_info_at(__FILE__, __LINE__, "goal_checker_name: %s", goal_checker_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(goal_checker_name); + goal_checker_loader_ = boost::dll::import_alias( + path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); + goal_checker_ = goal_checker_loader_(); + if (!goal_checker_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + goal_checker_->initialize(parent_); + robot::log_info_at(__FILE__, __LINE__, "Successfully initialized goal checker \"%s\"", goal_checker_name.c_str()); + } + catch (const std::exception &ex) + { + robot::log_error_at(__FILE__, __LINE__, "Unexpected exception while creating goal checker \"%s\": %s", goal_checker_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + + this->initializeOthers(); + robot::log_info("[%s:%d]\n %s is sucessed", __FILE__, __LINE__, name.c_str()); + initialized_ = true; + } +} + +void pnkx_local_planner::PNKXLocalPlanner::initializeOthers() +{ +} + +void pnkx_local_planner::PNKXLocalPlanner::getParams(robot::NodeHandle &nh) +{ + // This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window + nh.param("update_costmap_before_planning", update_costmap_before_planning_, true); + if (!nh.param("xy_goal_tolerance", xy_goal_tolerance_, 0.1)) + { + xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1); + } + if (!nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1)) + { + yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1); + } +} + +void pnkx_local_planner::PNKXLocalPlanner::reset() +{ + this->unlock(); + if(traj_generator_) traj_generator_->reset(); + if(goal_checker_) goal_checker_->reset(); + if(nav_algorithm_) nav_algorithm_->reset(); + if(rotate_algorithm_) rotate_algorithm_->reset(); + ret_nav_ = ret_angle_ = false; +} + +void pnkx_local_planner::PNKXLocalPlanner::setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose) +{ + // boost::recursive_mutex::scoped_lock l(configuration_mutex_); + reset(); + goal_pose_ = goal_pose; +} + +void pnkx_local_planner::PNKXLocalPlanner::setPlan(const robot_nav_2d_msgs::Path2D &path) +{ + // boost::recursive_mutex::scoped_lock l(configuration_mutex_); + costmap_robot_->resetLayers(); + global_plan_ = path; + if((unsigned int)global_plan_.poses.size() > 2) + global_plan_.poses.erase(global_plan_.poses.begin()); + for (unsigned int i = 0; i < (unsigned int)global_plan_.poses.size(); i++) + { + global_plan_.poses[i].header.seq = i; + } +} + +void pnkx_local_planner::PNKXLocalPlanner::getPlan(robot_nav_2d_msgs::Path2D &path) +{ + if (local_plan_.poses.empty()) + { + return; + } + path = local_plan_; + +} + +void pnkx_local_planner::PNKXLocalPlanner::getGlobalPlan(robot_nav_2d_msgs::Path2D &path) +{ + if (global_plan_.poses.empty()) + { + return; + } + path = global_plan_; +} + +void pnkx_local_planner::PNKXLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + this->getParams(planner_nh_); + if (update_costmap_before_planning_) + { + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + } + + // Update time stamp of goal pose + robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), + local_goal_pose = this->transformPoseToLocal(goal_pose_); + + if (!pnkx_local_planner::transformGlobalPlan( + tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) + { + robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed"); + throw robot_nav_core2::LocalPlannerException("Transform global plan is failed"); + } + + double x_direction, y_direction, theta_direction; + if (!ret_nav_) + { + if (nav_algorithm_ && !nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + } + } + else + { + if (rotate_algorithm_ && !rotate_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", rotate_algorithm_->getName().c_str()); + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + } + } + + int xytheta_direct[3]; + xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; + xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; + xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; + if(traj_generator_) traj_generator_->setDirect(xytheta_direct); +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, + const robot_nav_2d_msgs::Twist2D &velocity) +{ + // boost::recursive_mutex::scoped_lock l(configuration_mutex_); + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + try + { + if (global_plan_.poses.empty()) + return cmd_vel; + this->prepare(pose, velocity); + cmd_vel = this->ScoreAlgorithm(pose, velocity); + return cmd_vel; + } + catch (const robot_nav_core2::PlannerException &e) + { + robot::log_warning_at(__FILE__, __LINE__, "PNKXLocalPlanner computing velocity commands has been broken: %s", e.what()); + throw robot_nav_core2::LocalPlannerException("computing velocity commands has been broken"); + return cmd_vel; + } +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + robot_nav_2d_msgs::Twist2D twist; + mkt_msgs::Trajectory2D traj; + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + cmd_vel.header.stamp = robot::Time::now(); + + if (ret_nav_ && ret_angle_) + { + return cmd_vel; + local_plan_.poses.clear(); + } + else if (!ret_nav_) + { + if(nav_algorithm_) traj = nav_algorithm_->calculator(pose, velocity); + local_plan_.header.stamp = robot::Time::now(); + robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); + local_plan_ = robot_nav_2d_utils::pathToPath(path); + } + else + { + if(rotate_algorithm_) traj = rotate_algorithm_->calculator(pose, velocity); + local_plan_.header.stamp = robot::Time::now(); + robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); + local_plan_ = robot_nav_2d_utils::pathToPath(path); + } + + cmd_vel.velocity = traj.velocity; + return cmd_vel; +} + +bool pnkx_local_planner::PNKXLocalPlanner::setTwistLinear(robot_geometry_msgs::Vector3 linear) +{ + try + { + if (linear.x == 0.0 && linear.y == 0.0 && linear.z == 0.0) + { + if (nav_algorithm_) + nav_algorithm_->stop(); + if (rotate_algorithm_) + rotate_algorithm_->stop(); + } + else + { + if (nav_algorithm_) + nav_algorithm_->resume(); + if (rotate_algorithm_) + rotate_algorithm_->resume(); + } + + if (traj_generator_) + return traj_generator_->setTwistLinear(linear); + else + throw robot_nav_core2::LocalPlannerException("Failed to set linear"); + } + catch (const std::exception &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + return false; + } +} + +robot_geometry_msgs::Vector3 pnkx_local_planner::PNKXLocalPlanner::getTwistLinear(bool direct) +{ + try + { + if (traj_generator_) + return traj_generator_->getTwistLinear(direct); + else + throw robot_nav_core2::LocalPlannerException("Failed to get linear"); + } + catch (const std::exception &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } +} + +bool pnkx_local_planner::PNKXLocalPlanner::setTwistAngular(robot_geometry_msgs::Vector3 angular) +{ + try + { + if (traj_generator_) + return traj_generator_->setTwistAngular(angular); + else + throw robot_nav_core2::LocalPlannerException("Failed to set angular"); + } + catch (const std::exception &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + return false; + } +} + +robot_geometry_msgs::Vector3 pnkx_local_planner::PNKXLocalPlanner::getTwistAngular(bool direct) +{ + try + { + if (traj_generator_) + return traj_generator_->getTwistAngular(direct); + else + throw robot_nav_core2::LocalPlannerException("Failed to get angular"); + } + catch (const std::exception &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } +} + +bool pnkx_local_planner::PNKXLocalPlanner::islock() +{ + return lock_; +} + +void pnkx_local_planner::PNKXLocalPlanner::lock() +{ + lock_ = true; +} + +void pnkx_local_planner::PNKXLocalPlanner::unlock() +{ + lock_ = false; +} + +bool pnkx_local_planner::PNKXLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) +{ + if (goal_pose_.header.frame_id == "") + { + robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); + return false; + } + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); + robot_nav_2d_msgs::Pose2DStamped local_goal = this->transformPoseToLocal(goal_pose_); + robot_nav_2d_msgs::Path2D plan = transformed_global_plan_; + if (!ret_nav_) + { + ret_nav_ = goal_checker_->isGoalReached(local_pose, local_goal, plan, velocity); + } + else + { + double delta_orient = fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta)); + ret_angle_ = (bool)(delta_orient <= yaw_goal_tolerance_); + } + + if (ret_nav_ && ret_angle_) + { + robot::log_info_throttle(1.0, "Goal reached!"); + } + return ret_nav_ && ret_angle_; +} + +inline double getSquareDistance(const robot_nav_2d_msgs::Pose2DStamped &pose_a, const robot_nav_2d_msgs::Pose2DStamped &pose_b) +{ + double x_diff = pose_a.pose.x - pose_b.pose.x; + double y_diff = pose_a.pose.y - pose_b.pose.y; + return x_diff * x_diff + y_diff * y_diff; +} + +robot_nav_2d_msgs::Pose2DStamped pnkx_local_planner::PNKXLocalPlanner::transformPoseToLocal(const robot_nav_2d_msgs::Pose2DStamped &pose) +{ + robot_nav_2d_msgs::Pose2DStamped local_pose; + robot_nav_2d_utils::transformPose(tf_, costmap_robot_->getGlobalFrameID(), pose, local_pose); + return local_pose; +} + +robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXLocalPlanner::create() +{ + return std::make_shared(); +} + +// register this planner as a LocalPlanner plugin BOOST_DLL_ALIAS(pnkx_local_planner::PNKXLocalPlanner::create, PNKXLocalPlanner) \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_rotate_local_planner.cpp b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_rotate_local_planner.cpp index f0b5718..942f684 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_rotate_local_planner.cpp +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/pnkx_rotate_local_planner.cpp @@ -1,247 +1,247 @@ -#include "pnkx_local_planner/pnkx_rotate_local_planner.h" -#include "pnkx_local_planner/transforms.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -pnkx_local_planner::PNKXRotateLocalPlanner::PNKXRotateLocalPlanner() - : PNKXLocalPlanner() -{ -} - -pnkx_local_planner::PNKXRotateLocalPlanner::~PNKXRotateLocalPlanner() -{ - if (traj_generator_) - traj_generator_.reset(); - - if (nav_algorithm_) - nav_algorithm_.reset(); - - if (goal_checker_) - goal_checker_.reset(); -} - -void pnkx_local_planner::PNKXRotateLocalPlanner::initialize(robot::NodeHandle& parent, const std::string& name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT* costmap_robot) -{ - if (!initialized_) - { - robot::log_info_at(__FILE__, __LINE__, "Using parent name \"%s\"", name.c_str()); - tf_ = tf; - costmap_robot_ = costmap_robot; - costmap_ = costmap_robot_->getCostmap(); - - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - parent_ = parent; - planner_nh_ = robot::NodeHandle(parent_, name); - - this->getParams(planner_nh_); - - std::string traj_generator_name; - planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("nav_plugins::StandardTrajectoryGenerator")); - robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(traj_generator_name); - traj_gen_loader_ = boost::dll::import_alias( - path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); - traj_generator_ = traj_gen_loader_(); - if (!traj_generator_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); - traj_generator_->initialize(nh_traj_gen); - } - catch (const std::exception& ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); - } - - std::string algorithm_rotate_name = std::string("nav_algorithm::Rotate"); - planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("nav_algorithm::Rotate")); - robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_rotate_name.c_str()); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name); - nav_algorithm_loader_ = boost::dll::import_alias( - path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations); - nav_algorithm_ = nav_algorithm_loader_(); - if (!nav_algorithm_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_rotate_name); - nav_algorithm_->initialize(nh_algorithm, algorithm_rotate_name, tf, costmap_robot_, traj_generator_); - } - catch (const std::exception& ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); - } - - std::string goal_checker_name; - planner_nh_.param("goal_checker_name", goal_checker_name, std::string("nav_algorithm::GoalChecker")); - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(goal_checker_name); - goal_checker_loader_ = boost::dll::import_alias( - path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); - goal_checker_ = goal_checker_loader_(); - if (!goal_checker_) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - robot::NodeHandle nh_goal_checker = robot::NodeHandle(parent_, goal_checker_name); - goal_checker_->initialize(nh_goal_checker); - } - catch (const std::exception& ex) - { - robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s Goal checker , are you sure it is properly registered and that the containing library is built? Exception: %s", goal_checker_name.c_str(), ex.what()); - throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); - } - - robot::log_info_at(__FILE__, __LINE__, "%s is sucessed", name.c_str()); - initialized_ = true; - } -} - -void pnkx_local_planner::PNKXRotateLocalPlanner::reset() -{ - robot::log_info_at(__FILE__, __LINE__, "New Goal Received."); - this->unlock(); - if (traj_generator_) - traj_generator_->reset(); - if (goal_checker_) - goal_checker_->reset(); - if (nav_algorithm_) - nav_algorithm_->reset(); - ret_nav_ = ret_angle_ = false; -} - -void pnkx_local_planner::PNKXRotateLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - this->getParams(planner_nh_); - if (update_costmap_before_planning_) - { - info_.width = costmap_->getSizeInCellsX(); - info_.height = costmap_->getSizeInCellsY(); - info_.resolution = costmap_->getResolution(); - info_.frame_id = costmap_robot_->getGlobalFrameID(); - info_.origin_x = costmap_->getOriginX(); - info_.origin_y = costmap_->getOriginY(); - - if (!costmap_robot_->isCurrent()) - throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); - } - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), - local_goal_pose = this->transformPoseToLocal(goal_pose_); - try - { - if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) - throw robot_nav_core2::LocalPlannerException("Transform global plan is failed"); - } - catch(const robot_nav_core2::LocalPlannerException& e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } - - double x_direction, y_direction, theta_direction; - if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) - { - throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); - } - - int xytheta_direct[3]; - xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; - xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; - xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; - traj_generator_->setDirect(xytheta_direct); -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXRotateLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - // boost::recursive_mutex::scoped_lock l(configuration_mutex_); - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - try - { - if (global_plan_.poses.empty()) - return cmd_vel; - this->prepare(pose, velocity); - cmd_vel = this->ScoreAlgorithm(pose, velocity); - return cmd_vel; - } - catch (const robot_nav_core2::PlannerException &e) - { - throw robot_nav_core2::LocalPlannerException(e.what()); - } -} - -robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXRotateLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - robot_nav_2d_msgs::Twist2D twist; - mkt_msgs::Trajectory2D traj; - robot_nav_2d_msgs::Twist2DStamped cmd_vel; - cmd_vel.header.stamp = robot::Time::now(); - if (ret_nav_) - { - local_plan_.poses.clear(); - return cmd_vel; - } - - traj = nav_algorithm_->calculator(pose, velocity); - local_plan_.header.stamp = robot::Time::now(); - robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); - local_plan_ = robot_nav_2d_utils::pathToPath(path); - cmd_vel.velocity = traj.velocity; - return cmd_vel; -} - -bool pnkx_local_planner::PNKXRotateLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) -{ - if (goal_pose_.header.frame_id == "") - { - robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); - return false; - } - // Update time stamp of goal pose - // goal_pose_.header.stamp = pose.header.stamp; - robot_nav_2d_msgs::Path2D empty; - ret_nav_ = goal_checker_->isGoalReached( - this->transformPoseToLocal(pose), this->transformPoseToLocal(goal_pose_), empty, velocity); - - if (ret_nav_) - robot::log_info_at(__FILE__, __LINE__, "Goal reached!"); - return ret_nav_; -} - -robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXRotateLocalPlanner::create() -{ - return std::make_shared(); -} - -// register this planner as a LocalPlanner plugin +#include "pnkx_local_planner/pnkx_rotate_local_planner.h" +#include "pnkx_local_planner/transforms.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +pnkx_local_planner::PNKXRotateLocalPlanner::PNKXRotateLocalPlanner() + : PNKXLocalPlanner() +{ +} + +pnkx_local_planner::PNKXRotateLocalPlanner::~PNKXRotateLocalPlanner() +{ + if (traj_generator_) + traj_generator_.reset(); + + if (nav_algorithm_) + nav_algorithm_.reset(); + + if (goal_checker_) + goal_checker_.reset(); +} + +void pnkx_local_planner::PNKXRotateLocalPlanner::initialize(robot::NodeHandle& parent, const std::string& name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT* costmap_robot) +{ + if (!initialized_) + { + robot::log_info_at(__FILE__, __LINE__, "Using parent name \"%s\"", name.c_str()); + tf_ = tf; + costmap_robot_ = costmap_robot; + costmap_ = costmap_robot_->getCostmap(); + + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + parent_ = parent; + planner_nh_ = robot::NodeHandle(parent_, name); + + this->getParams(planner_nh_); + + std::string traj_generator_name; + planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("nav_plugins::StandardTrajectoryGenerator")); + robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(traj_generator_name); + traj_gen_loader_ = boost::dll::import_alias( + path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations); + traj_generator_ = traj_gen_loader_(); + if (!traj_generator_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name); + traj_generator_->initialize(nh_traj_gen); + } + catch (const std::exception& ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator"); + } + + std::string algorithm_rotate_name = std::string("nav_algorithm::Rotate"); + planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("nav_algorithm::Rotate")); + robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_rotate_name.c_str()); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name); + nav_algorithm_loader_ = boost::dll::import_alias( + path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations); + nav_algorithm_ = nav_algorithm_loader_(); + if (!nav_algorithm_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_rotate_name); + nav_algorithm_->initialize(nh_algorithm, algorithm_rotate_name, tf, costmap_robot_, traj_generator_); + } + catch (const std::exception& ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create algorithm"); + } + + std::string goal_checker_name; + planner_nh_.param("goal_checker_name", goal_checker_name, std::string("nav_algorithm::GoalChecker")); + try + { + robot::PluginLoaderHelper loader; + std::string path_file_so = loader.findLibraryPath(goal_checker_name); + goal_checker_loader_ = boost::dll::import_alias( + path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations); + goal_checker_ = goal_checker_loader_(); + if (!goal_checker_) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + robot::NodeHandle nh_goal_checker = robot::NodeHandle(parent_, goal_checker_name); + goal_checker_->initialize(nh_goal_checker); + } + catch (const std::exception& ex) + { + robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s Goal checker , are you sure it is properly registered and that the containing library is built? Exception: %s", goal_checker_name.c_str(), ex.what()); + throw robot_nav_core2::LocalPlannerException("Failed to create goal checker"); + } + + robot::log_info_at(__FILE__, __LINE__, "%s is sucessed", name.c_str()); + initialized_ = true; + } +} + +void pnkx_local_planner::PNKXRotateLocalPlanner::reset() +{ + robot::log_info_at(__FILE__, __LINE__, "New Goal Received."); + this->unlock(); + if (traj_generator_) + traj_generator_->reset(); + if (goal_checker_) + goal_checker_->reset(); + if (nav_algorithm_) + nav_algorithm_->reset(); + ret_nav_ = ret_angle_ = false; +} + +void pnkx_local_planner::PNKXRotateLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + this->getParams(planner_nh_); + if (update_costmap_before_planning_) + { + info_.width = costmap_->getSizeInCellsX(); + info_.height = costmap_->getSizeInCellsY(); + info_.resolution = costmap_->getResolution(); + info_.frame_id = costmap_robot_->getGlobalFrameID(); + info_.origin_x = costmap_->getOriginX(); + info_.origin_y = costmap_->getOriginY(); + + if (!costmap_robot_->isCurrent()) + throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); + } + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), + local_goal_pose = this->transformPoseToLocal(goal_pose_); + try + { + if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) + throw robot_nav_core2::LocalPlannerException("Transform global plan is failed"); + } + catch(const robot_nav_core2::LocalPlannerException& e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } + + double x_direction, y_direction, theta_direction; + if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) + { + throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); + } + + int xytheta_direct[3]; + xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0; + xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0; + xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0; + traj_generator_->setDirect(xytheta_direct); +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXRotateLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + // boost::recursive_mutex::scoped_lock l(configuration_mutex_); + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + try + { + if (global_plan_.poses.empty()) + return cmd_vel; + this->prepare(pose, velocity); + cmd_vel = this->ScoreAlgorithm(pose, velocity); + return cmd_vel; + } + catch (const robot_nav_core2::PlannerException &e) + { + throw robot_nav_core2::LocalPlannerException(e.what()); + } +} + +robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXRotateLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + robot_nav_2d_msgs::Twist2D twist; + mkt_msgs::Trajectory2D traj; + robot_nav_2d_msgs::Twist2DStamped cmd_vel; + cmd_vel.header.stamp = robot::Time::now(); + if (ret_nav_) + { + local_plan_.poses.clear(); + return cmd_vel; + } + + traj = nav_algorithm_->calculator(pose, velocity); + local_plan_.header.stamp = robot::Time::now(); + robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now()); + local_plan_ = robot_nav_2d_utils::pathToPath(path); + cmd_vel.velocity = traj.velocity; + return cmd_vel; +} + +bool pnkx_local_planner::PNKXRotateLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity) +{ + if (goal_pose_.header.frame_id == "") + { + robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); + return false; + } + // Update time stamp of goal pose + // goal_pose_.header.stamp = pose.header.stamp; + robot_nav_2d_msgs::Path2D empty; + ret_nav_ = goal_checker_->isGoalReached( + this->transformPoseToLocal(pose), this->transformPoseToLocal(goal_pose_), empty, velocity); + + if (ret_nav_) + robot::log_info_at(__FILE__, __LINE__, "Goal reached!"); + return ret_nav_; +} + +robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXRotateLocalPlanner::create() +{ + return std::make_shared(); +} + +// register this planner as a LocalPlanner plugin BOOST_DLL_ALIAS(pnkx_local_planner::PNKXRotateLocalPlanner::create, PNKXRotateLocalPlanner) \ No newline at end of file diff --git a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/transforms.cpp b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/transforms.cpp index ef1a911..7f1760d 100644 --- a/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/transforms.cpp +++ b/src/Algorithms/Packages/local_planners/pnkx_local_planner/src/transforms.cpp @@ -1,206 +1,206 @@ -#include -#include -#include -#include -#include -#include - -bool pnkx_local_planner::getPose(TFListenerPtr tf, std::string base_frame_id, std::string global_frame, robot_nav_2d_msgs::Pose2DStamped& global_pose, double transform_tolerance) -{ - if (!tf) - return false; - - robot_geometry_msgs::PoseStamped global_pose_stamped; - tf3::toMsg(tf3::Transform::getIdentity(), global_pose_stamped.pose); - robot_geometry_msgs::PoseStamped robot_pose; - tf3::toMsg(tf3::Transform::getIdentity(), robot_pose.pose); - robot_pose.header.frame_id = base_frame_id; - robot_pose.header.stamp = robot::Time(); - robot::Time current_time = robot::Time::now(); // save time for checking tf delay later - - // Convert robot::Time to tf3::Time - tf3::Time tf3_current_time = data_convert::convertTime(current_time); - tf3::Time tf3_zero_time = data_convert::convertTime(robot::Time()); - - // get the global pose of the robot - try - { - // use current time if possible (makes sure it's not in the future) - std::string error_msg; - if (tf->canTransform(global_frame, base_frame_id, tf3_current_time, &error_msg)) - { - // Transform is available at current time - tf3::TransformStampedMsg transform = tf->lookupTransform(global_frame, base_frame_id, tf3_current_time); - tf3::doTransform(robot_pose, global_pose_stamped, transform); - } - // use the latest otherwise (tf3::Time() means latest available) - else - { - // Try to get latest transform - tf3::TransformStampedMsg transform = tf->lookupTransform(global_frame, base_frame_id, tf3_zero_time); - tf3::doTransform(robot_pose, global_pose_stamped, transform); - } - global_pose = robot_nav_2d_utils::poseStampedToPose2D(global_pose_stamped); - } - catch (tf3::LookupException& ex) - { - robot::log_warning_throttle(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what()); - return false; - // throw robot_nav_core2::LocalPlannerException(ex.what()); - } - catch (tf3::ConnectivityException& ex) - { - robot::log_warning_throttle(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what()); - return false; - // throw robot_nav_core2::LocalPlannerException(ex.what()); - } - catch (tf3::ExtrapolationException& ex) - { - robot::log_warning_throttle(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what()); - return false; - // throw robot_nav_core2::LocalPlannerException(ex.what()); - } - // check global_pose timeout - if (!global_pose_stamped.header.stamp.isZero() && current_time.toSec() - global_pose_stamped.header.stamp.toSec() > transform_tolerance) - { - robot::log_warning_throttle(1.0, "Local Planner transform %s %s timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f", base_frame_id.c_str(), global_frame.c_str(), - current_time.toSec(), global_pose_stamped.header.stamp.toSec(), transform_tolerance); - return false; - } - return true; -} - -bool pnkx_local_planner::transformGlobalPose(TFListenerPtr tf, const std::string& global_frame, - const robot_nav_2d_msgs::Pose2DStamped& stamped_pose, robot_nav_2d_msgs::Pose2DStamped& newer_pose) -{ - if (tf == nullptr) - return false; - bool result = robot_nav_2d_utils::transformPose(tf, global_frame, stamped_pose, newer_pose); - newer_pose.header.seq = stamped_pose.header.seq; - return result; -} - -double pnkx_local_planner::getSquareDistance(const robot_geometry_msgs::Pose2D& pose_a, const robot_geometry_msgs::Pose2D& pose_b) -{ - double x_diff = pose_a.x - pose_b.x; - double y_diff = pose_a.y - pose_b.y; - return x_diff * x_diff + y_diff * y_diff; -} - -bool pnkx_local_planner::transformGlobalPlan( - TFListenerPtr tf, const robot_nav_2d_msgs::Path2D& global_plan, const robot_nav_2d_msgs::Pose2DStamped& pose, - const robot_costmap_2d::Costmap2DROBOT* costmap, const std::string& global_frame, double max_plan_length, - robot_nav_2d_msgs::Path2D& transformed_plan, const bool from_global_frame) -{ - if (global_plan.poses.size() == 0) - { - robot::log_warning("Received plan with zero length"); - throw robot_nav_core2::PlannerException("Received plan with zero length"); - } - - transformed_plan.poses.clear(); - if (tf == nullptr) - throw robot_nav_core2::PlannerException("TFListenerPtr is null"); - - if (global_plan.poses.empty()) - throw robot_nav_core2::PlannerException("Received plan with zero length"); - - try - { - // let's get the pose of the robot in the frame of the plan - robot_nav_2d_msgs::Pose2DStamped robot_pose; - if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot_pose)) - { - throw robot_nav_core2::PlannerTFException("transformGlobalPlan: Unable to transform robot pose into global plan's frame"); - } - - transformed_plan.header.frame_id = costmap->getGlobalFrameID(); - transformed_plan.header.stamp = pose.header.stamp; - - robot_nav_2d_msgs::Pose2DStamped new_pose; - robot_nav_2d_msgs::Pose2DStamped stamped_pose; - stamped_pose.header.frame_id = global_plan.header.frame_id; - - for (unsigned int i = 0; i < global_plan.poses.size(); i++) - { - // now we'll transform until points are outside of our distance threshold - stamped_pose = global_plan.poses[i]; - if (pnkx_local_planner::transformGlobalPose(tf, global_frame, global_plan.poses[i], new_pose)) - { - transformed_plan.poses.push_back(new_pose); - } - } - - // Prune both plans based on robot position - // Note that this part of the algorithm assumes that the global plan starts near the robot (at one point) - // Otherwise it may take a few iterations to converge to the proper behavior - - // let's get the pose of the robot in the frame of the transformed_plan/costmap - robot_nav_2d_msgs::Pose2DStamped costmap_pose; - if (!robot_nav_2d_utils::transformPose(tf, transformed_plan.header.frame_id, pose, costmap_pose)) - { - throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into costmap's frame"); - } - - robot::log_assert(global_plan.poses.size() >= transformed_plan.poses.size(), "Global plan size is less than transformed plan size"); - - std::vector::iterator it = transformed_plan.poses.begin(); - - double sq_prune_dist = 0.1; - - std::vector footprint = costmap->getRobotFootprint(); - size_t n = footprint.size(); - if (n > 1) - { - double max_length = 0.0; - for (size_t i = 0; i < n; ++i) - { - const robot_geometry_msgs::Point& p1 = footprint[i]; - const robot_geometry_msgs::Point& p2 = footprint[(i + 1) % n]; // wrap around to first point - double len = std::hypot(p2.x - p1.x, p2.y - p1.y); - if (len > max_length) - { - max_length = len; - } - } - sq_prune_dist += max_length; - } - // if(from_global_frame) sq_prune_dist = 0; - while (it != transformed_plan.poses.end()) - { - const robot_nav_2d_msgs::Pose2DStamped& w = *it; - // Fixed error bound of 1 meter for now. Can reduce to a portion of the map size or based on the resolution - if (pnkx_local_planner::getSquareDistance(costmap_pose.pose, w.pose) < sq_prune_dist) - { - // robot::log_debug_at(__FILE__, __LINE__, "Nearest waypoint to <%f, %f> is <%f, %f>\n", - // costmap_pose.pose.x, costmap_pose.pose.y, w.pose.x, w.pose.y); - break; - } - - it = transformed_plan.poses.erase(it); - } - - if (transformed_plan.poses.size() == 0) - { - throw robot_nav_core2::PlannerTFException("Resulting plan has 0 poses in it."); - } - } - catch (tf3::LookupException& ex) - { - robot::log_error_at(__FILE__, __LINE__, "No Transform available Error: %s\n", ex.what()); - return false; - } - catch (tf3::ConnectivityException& ex) - { - robot::log_error("Connectivity Error: %s\n", ex.what()); - return false; - } - catch (tf3::ExtrapolationException& ex) - { - robot::log_error("Extrapolation Error: %s\n", ex.what()); - if (global_plan.poses.size() > 0) - robot::log_error("[%s:%d]\n Robot Frame: %s Plan Frame size %d: %s\n", __FILE__, __LINE__, global_frame.c_str(), (unsigned int)global_plan.poses.size(), global_plan.header.frame_id.c_str()); - return false; - } - return true; +#include +#include +#include +#include +#include +#include + +bool pnkx_local_planner::getPose(TFListenerPtr tf, std::string base_frame_id, std::string global_frame, robot_nav_2d_msgs::Pose2DStamped& global_pose, double transform_tolerance) +{ + if (!tf) + return false; + + robot_geometry_msgs::PoseStamped global_pose_stamped; + tf3::toMsg(tf3::Transform::getIdentity(), global_pose_stamped.pose); + robot_geometry_msgs::PoseStamped robot_pose; + tf3::toMsg(tf3::Transform::getIdentity(), robot_pose.pose); + robot_pose.header.frame_id = base_frame_id; + robot_pose.header.stamp = robot::Time(); + robot::Time current_time = robot::Time::now(); // save time for checking tf delay later + + // Convert robot::Time to tf3::Time + tf3::Time tf3_current_time = data_convert::convertTime(current_time); + tf3::Time tf3_zero_time = data_convert::convertTime(robot::Time()); + + // get the global pose of the robot + try + { + // use current time if possible (makes sure it's not in the future) + std::string error_msg; + if (tf->canTransform(global_frame, base_frame_id, tf3_current_time, &error_msg)) + { + // Transform is available at current time + tf3::TransformStampedMsg transform = tf->lookupTransform(global_frame, base_frame_id, tf3_current_time); + tf3::doTransform(robot_pose, global_pose_stamped, transform); + } + // use the latest otherwise (tf3::Time() means latest available) + else + { + // Try to get latest transform + tf3::TransformStampedMsg transform = tf->lookupTransform(global_frame, base_frame_id, tf3_zero_time); + tf3::doTransform(robot_pose, global_pose_stamped, transform); + } + global_pose = robot_nav_2d_utils::poseStampedToPose2D(global_pose_stamped); + } + catch (tf3::LookupException& ex) + { + robot::log_warning_throttle(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what()); + return false; + // throw robot_nav_core2::LocalPlannerException(ex.what()); + } + catch (tf3::ConnectivityException& ex) + { + robot::log_warning_throttle(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what()); + return false; + // throw robot_nav_core2::LocalPlannerException(ex.what()); + } + catch (tf3::ExtrapolationException& ex) + { + robot::log_warning_throttle(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what()); + return false; + // throw robot_nav_core2::LocalPlannerException(ex.what()); + } + // check global_pose timeout + if (!global_pose_stamped.header.stamp.isZero() && current_time.toSec() - global_pose_stamped.header.stamp.toSec() > transform_tolerance) + { + robot::log_warning_throttle(1.0, "Local Planner transform %s %s timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f", base_frame_id.c_str(), global_frame.c_str(), + current_time.toSec(), global_pose_stamped.header.stamp.toSec(), transform_tolerance); + return false; + } + return true; +} + +bool pnkx_local_planner::transformGlobalPose(TFListenerPtr tf, const std::string& global_frame, + const robot_nav_2d_msgs::Pose2DStamped& stamped_pose, robot_nav_2d_msgs::Pose2DStamped& newer_pose) +{ + if (tf == nullptr) + return false; + bool result = robot_nav_2d_utils::transformPose(tf, global_frame, stamped_pose, newer_pose); + newer_pose.header.seq = stamped_pose.header.seq; + return result; +} + +double pnkx_local_planner::getSquareDistance(const robot_geometry_msgs::Pose2D& pose_a, const robot_geometry_msgs::Pose2D& pose_b) +{ + double x_diff = pose_a.x - pose_b.x; + double y_diff = pose_a.y - pose_b.y; + return x_diff * x_diff + y_diff * y_diff; +} + +bool pnkx_local_planner::transformGlobalPlan( + TFListenerPtr tf, const robot_nav_2d_msgs::Path2D& global_plan, const robot_nav_2d_msgs::Pose2DStamped& pose, + const robot_costmap_2d::Costmap2DROBOT* costmap, const std::string& global_frame, double max_plan_length, + robot_nav_2d_msgs::Path2D& transformed_plan, const bool from_global_frame) +{ + if (global_plan.poses.size() == 0) + { + robot::log_warning("Received plan with zero length"); + throw robot_nav_core2::PlannerException("Received plan with zero length"); + } + + transformed_plan.poses.clear(); + if (tf == nullptr) + throw robot_nav_core2::PlannerException("TFListenerPtr is null"); + + if (global_plan.poses.empty()) + throw robot_nav_core2::PlannerException("Received plan with zero length"); + + try + { + // let's get the pose of the robot in the frame of the plan + robot_nav_2d_msgs::Pose2DStamped robot_pose; + if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot_pose)) + { + throw robot_nav_core2::PlannerTFException("transformGlobalPlan: Unable to transform robot pose into global plan's frame"); + } + + transformed_plan.header.frame_id = costmap->getGlobalFrameID(); + transformed_plan.header.stamp = pose.header.stamp; + + robot_nav_2d_msgs::Pose2DStamped new_pose; + robot_nav_2d_msgs::Pose2DStamped stamped_pose; + stamped_pose.header.frame_id = global_plan.header.frame_id; + + for (unsigned int i = 0; i < global_plan.poses.size(); i++) + { + // now we'll transform until points are outside of our distance threshold + stamped_pose = global_plan.poses[i]; + if (pnkx_local_planner::transformGlobalPose(tf, global_frame, global_plan.poses[i], new_pose)) + { + transformed_plan.poses.push_back(new_pose); + } + } + + // Prune both plans based on robot position + // Note that this part of the algorithm assumes that the global plan starts near the robot (at one point) + // Otherwise it may take a few iterations to converge to the proper behavior + + // let's get the pose of the robot in the frame of the transformed_plan/costmap + robot_nav_2d_msgs::Pose2DStamped costmap_pose; + if (!robot_nav_2d_utils::transformPose(tf, transformed_plan.header.frame_id, pose, costmap_pose)) + { + throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into costmap's frame"); + } + + robot::log_assert(global_plan.poses.size() >= transformed_plan.poses.size(), "Global plan size is less than transformed plan size"); + + std::vector::iterator it = transformed_plan.poses.begin(); + + double sq_prune_dist = 0.1; + + std::vector footprint = costmap->getRobotFootprint(); + size_t n = footprint.size(); + if (n > 1) + { + double max_length = 0.0; + for (size_t i = 0; i < n; ++i) + { + const robot_geometry_msgs::Point& p1 = footprint[i]; + const robot_geometry_msgs::Point& p2 = footprint[(i + 1) % n]; // wrap around to first point + double len = std::hypot(p2.x - p1.x, p2.y - p1.y); + if (len > max_length) + { + max_length = len; + } + } + sq_prune_dist += max_length; + } + // if(from_global_frame) sq_prune_dist = 0; + while (it != transformed_plan.poses.end()) + { + const robot_nav_2d_msgs::Pose2DStamped& w = *it; + // Fixed error bound of 1 meter for now. Can reduce to a portion of the map size or based on the resolution + if (pnkx_local_planner::getSquareDistance(costmap_pose.pose, w.pose) < sq_prune_dist) + { + // robot::log_debug_at(__FILE__, __LINE__, "Nearest waypoint to <%f, %f> is <%f, %f>\n", + // costmap_pose.pose.x, costmap_pose.pose.y, w.pose.x, w.pose.y); + break; + } + + it = transformed_plan.poses.erase(it); + } + + if (transformed_plan.poses.size() == 0) + { + throw robot_nav_core2::PlannerTFException("Resulting plan has 0 poses in it."); + } + } + catch (tf3::LookupException& ex) + { + robot::log_error_at(__FILE__, __LINE__, "No Transform available Error: %s\n", ex.what()); + return false; + } + catch (tf3::ConnectivityException& ex) + { + robot::log_error("Connectivity Error: %s\n", ex.what()); + return false; + } + catch (tf3::ExtrapolationException& ex) + { + robot::log_error("Extrapolation Error: %s\n", ex.what()); + if (global_plan.poses.size() > 0) + robot::log_error("[%s:%d]\n Robot Frame: %s Plan Frame size %d: %s\n", __FILE__, __LINE__, global_frame.c_str(), (unsigned int)global_plan.poses.size(), global_plan.header.frame_id.c_str()); + return false; + } + return true; } \ No newline at end of file diff --git a/src/Libraries/costmap_2d.zip b/src/Libraries/costmap_2d.zip old mode 100644 new mode 100755 diff --git a/src/Libraries/costmap_2d_dev_1_cam.zip b/src/Libraries/costmap_2d_dev_1_cam.zip old mode 100644 new mode 100755 diff --git a/src/Libraries/costmap_2d_dev_multi_cam_test.zip b/src/Libraries/costmap_2d_dev_multi_cam_test.zip old mode 100644 new mode 100755 diff --git a/src/Libraries/data_convert.zip b/src/Libraries/data_convert.zip old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_cpp/CMakeLists.txt b/src/Libraries/robot_cpp/CMakeLists.txt index 3b941ee..5b148fd 100644 --- a/src/Libraries/robot_cpp/CMakeLists.txt +++ b/src/Libraries/robot_cpp/CMakeLists.txt @@ -264,6 +264,35 @@ if(BUILD_TESTS) # Add test to CTest add_test(NAME NodeHandleTest COMMAND test_node_handle) - - message(STATUS "Test executable 'test_node_handle' will be built") + + # ------------------------------------------------------------------ + # Throttled logging: the throttle window must be private to each call + # site, and must survive concurrent calls, so this test needs threads. + # ------------------------------------------------------------------ + find_package(Threads REQUIRED) + + add_executable(test_console_throttle + test/test_console_throttle.cpp + ) + + target_include_directories(test_console_throttle + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + + target_link_libraries(test_console_throttle + PRIVATE + ${PROJECT_NAME} + Threads::Threads + ) + + set_target_properties(test_console_throttle PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + + add_test(NAME ConsoleThrottleTest COMMAND test_console_throttle) + + message(STATUS "Test executables 'test_node_handle', 'test_console_throttle' will be built") endif() diff --git a/src/Libraries/robot_cpp/include/robot/console.h b/src/Libraries/robot_cpp/include/robot/console.h index f70d864..847d170 100644 --- a/src/Libraries/robot_cpp/include/robot/console.h +++ b/src/Libraries/robot_cpp/include/robot/console.h @@ -459,9 +459,24 @@ namespace robot * Logs an error message with red text color. Use for errors that indicate * problems or failures. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. - */ + */ void log_error_throttle(double throttle, const char *format, ...); /** @@ -470,6 +485,21 @@ namespace robot * Logs a debug message with cyan text color. Use for debugging information * that is typically only needed during development. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. */ @@ -481,6 +511,21 @@ namespace robot * Logs a success message with green text color. Use for successful operations * or positive status updates. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. */ @@ -492,6 +537,21 @@ namespace robot * Logs a warning message with yellow text color. Use for warnings that don't * prevent operation but should be noted. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. */ diff --git a/src/Libraries/robot_cpp/src/console.cpp b/src/Libraries/robot_cpp/src/console.cpp index 1e7f66e..fc6b039 100644 --- a/src/Libraries/robot_cpp/src/console.cpp +++ b/src/Libraries/robot_cpp/src/console.cpp @@ -1,18 +1,45 @@ #include "robot/console.h" #include +#include +#include +#include #include #include #include #include #include +#include +#include #include #include +// Identifies the caller of a throttled log function. Every call site has its +// own return address, which is what lets the throttle window be private per +// call site without changing any public signature. +#if defined(__GNUC__) || defined(__clang__) +#define ROBOT_LOG_CALL_SITE() __builtin_return_address(0) +#else +// Without the builtin the format string pointer alone keys the throttle. That +// is weaker (identical literals may be folded together) but still far better +// than one window shared by the whole process. +#define ROBOT_LOG_CALL_SITE() static_cast(nullptr) +#endif + namespace robot { - // Global flag to enable/disable colors - static bool color_enabled = true; + // Written through set_color_enabled() and read by every log call, so it is + // touched from the control loop, sensor callbacks and planner threads at + // once. Plain bool made that a data race. + static std::atomic color_enabled{true}; + + // TERM and NO_COLOR do not change while the process runs, but + // is_color_enabled() is called two to three times per log line. Detecting + // support on every one of them meant several getenv() calls per line inside + // the control loop, and getenv() is not safe against a concurrent setenv(). + // Detect once, then answer from the cache. + static std::once_flag color_support_once; + static bool color_supported_cached = true; static inline bool format_ends_with_newline(const char *format) { @@ -24,7 +51,7 @@ namespace robot return (n > 0 && format[n - 1] == '\n'); } - bool is_color_supported() + static bool detect_color_support() { // Check if NO_COLOR environment variable is set const char *no_color = std::getenv("NO_COLOR"); @@ -52,14 +79,22 @@ namespace robot return true; } + bool is_color_supported() + { + std::call_once(color_support_once, + []() { color_supported_cached = detect_color_support(); }); + return color_supported_cached; + } + void set_color_enabled(bool enabled) { - color_enabled = enabled && is_color_supported(); + color_enabled.store(enabled && is_color_supported(), + std::memory_order_relaxed); } bool is_color_enabled() { - return color_enabled && is_color_supported(); + return color_enabled.load(std::memory_order_relaxed) && is_color_supported(); } // Helper function to format timestamp as "sec.nsec" @@ -359,68 +394,180 @@ namespace robot va_end(args); } + // ---------------------------------------------------------------------- + // Per-call-site throttle state + // + // The throttle window has to belong to the call site, not to the function. + // move_base2's controller_runner alone holds eleven log_error_throttle() + // calls; with one shared timestamp, whichever fired first silenced the other + // ten for the rest of the window, so real faults were swallowed. + // + // The call site is identified by its return address, which keeps the public + // signatures untouched - no caller has to change. The format pointer is + // mixed in as a second key because identical string literals can be folded + // into one address by the linker. + // + // Known limit: if a caller invokes one of these functions as the very last + // thing it does, the compiler may turn it into a tail call, and the return + // address then belongs to that caller's own caller. The window is then kept + // per calling site of the wrapper instead of per wrapper. That splits a + // window into several, never merges two into one, so the failure mode is + // extra log lines rather than a swallowed message. Tests pin their call + // sites down with a volatile read to keep this out of the measurement. + // + // The table is fixed size and lock free on purpose: these functions are + // called from the control loop, so no allocation and no mutex on the path. + // ---------------------------------------------------------------------- + constexpr std::size_t kThrottleSlots = 512; // power of two: mask, not modulo + constexpr std::size_t kThrottleProbe = 8; // linear probing depth + + struct ThrottleSlot + { + std::atomic key{0}; // 0 marks a free slot + std::atomic last_ns{0}; + }; + + static ThrottleSlot throttle_slots[kThrottleSlots]; + + static inline std::uintptr_t throttle_key(const void *site, const void *format) + { + std::uint64_t key = static_cast(reinterpret_cast(site)); + key ^= static_cast(reinterpret_cast(format)) + + 0x9E3779B97F4A7C15ull + (key << 6) + (key >> 2); + key *= 0xFF51AFD7ED558CCDull; + key ^= key >> 33; + const std::uintptr_t folded = static_cast(key); + return (folded == 0) ? 1 : folded; // 0 is reserved for "slot free" + } + + /** + * @brief Decide whether this call site may print now. + * + * @param site Return address of the caller. Must be taken in the public + * log function, never inside this helper: from here the + * builtin would report an address in this function and every + * call site would collapse back onto a single key. + * @param format Format string pointer, used as a second key component. + * @param throttle Minimum interval between two prints [s]. + */ + static bool throttle_allows(const void *site, const void *format, double throttle) + { + const std::int64_t now_ns = + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); + + // A NaN or negative interval means "do not throttle" rather than "never + // log again". A bad parameter must make the log noisy, never silent - + // NaN used to fail the >= test forever and mute the call site for good. + std::int64_t window_ns = 0; + if (std::isfinite(throttle) && throttle > 0.0) + { + const double scaled = throttle * 1e9; + window_ns = (scaled >= 9.0e18) + ? std::numeric_limits::max() + : static_cast(scaled); + } + if (window_ns <= 0) + { + return true; + } + + const std::uintptr_t key = throttle_key(site, format); + const std::size_t home = static_cast(key) & (kThrottleSlots - 1); + + for (std::size_t probe = 0; probe < kThrottleProbe; ++probe) + { + ThrottleSlot &slot = throttle_slots[(home + probe) & (kThrottleSlots - 1)]; + + std::uintptr_t owner = slot.key.load(std::memory_order_acquire); + if (owner == 0) + { + std::uintptr_t expected = 0; + owner = slot.key.compare_exchange_strong(expected, key, + std::memory_order_acq_rel, + std::memory_order_acquire) + ? key + : expected; // lost the race, another site owns it now + } + if (owner != key) + { + continue; // slot belongs to a different call site + } + + const std::int64_t last = slot.last_ns.load(std::memory_order_relaxed); + // last == 0 is a slot nobody has printed from yet: always print, which + // matches the old default-constructed time_point behaviour. + if (last != 0 && (now_ns - last) < window_ns) + { + return false; + } + // The exchange is what stops two threads printing in the same window; + // the loser sees the updated timestamp and gives up. + std::int64_t expected_ns = last; + return slot.last_ns.compare_exchange_strong(expected_ns, now_ns, + std::memory_order_relaxed); + } + + // Table full: print. A saturated table must cost extra log lines, never a + // swallowed fault. + return true; + } + void log_error_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::RED, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::RED, format, args); + va_end(args); } void log_info_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::BRIGHT_BLUE, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::BRIGHT_BLUE, format, args); + va_end(args); } void log_success_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::GREEN, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::GREEN, format, args); + va_end(args); } void log_warning_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::YELLOW, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::YELLOW, format, args); + va_end(args); } void log_assert(bool condition, const char *format, ...) @@ -474,3 +621,5 @@ namespace robot } } // namespace robot + +#undef ROBOT_LOG_CALL_SITE diff --git a/src/Libraries/robot_cpp/src/node_handle.cpp b/src/Libraries/robot_cpp/src/node_handle.cpp index 3345288..3ee0f3f 100644 --- a/src/Libraries/robot_cpp/src/node_handle.cpp +++ b/src/Libraries/robot_cpp/src/node_handle.cpp @@ -379,6 +379,8 @@ namespace robot return false; } + // Keep owned node copies: yaml-cpp iterator proxies make &it->second dangling. + std::vector owned; const YAML::Node *current = &root_; for (size_t i = 0; i < segments.size(); ++i) @@ -391,61 +393,55 @@ namespace robot if (current->IsMap()) { - // Search for the segment without inserting default nodes - const YAML::Node *found_child = nullptr; - + YAML::Node found_child; + bool found = false; + try { for (YAML::const_iterator it = current->begin(); it != current->end(); ++it) { try { - // Safety check: validate iterator nodes - if (!it->first.IsDefined()) + const auto kv = *it; + if (!kv.first.IsDefined()) { continue; } - - // Safely convert key to string + std::string key_str; try { - key_str = it->first.as(); + key_str = kv.first.as(); } catch (...) { - // Skip nodes that can't be converted to string continue; } - - if (key_str == segments[i]) + + if (key_str == segments[i] && kv.second.IsDefined()) { - // Safety check: validate value node - if (it->second.IsDefined()) - { - found_child = &(it->second); - break; - } + found_child = kv.second; + found = true; + break; } } catch (...) { - // Skip invalid nodes and continue iteration continue; } } } catch (...) { - // If iteration fails, return false return false; } - - if (!found_child || !found_child->IsDefined()) + + if (!found || !found_child.IsDefined()) { return false; } - current = found_child; + owned.push_back(std::move(found_child)); + current = &owned.back(); continue; } @@ -459,12 +455,13 @@ namespace robot { return false; } - const YAML::Node &child = (*current)[idx]; + YAML::Node child = (*current)[idx]; if (!child.IsDefined()) { return false; } - current = &child; + owned.push_back(std::move(child)); + current = &owned.back(); continue; } catch (...) @@ -477,7 +474,7 @@ namespace robot // Neither map nor sequence: cannot traverse further return false; } - + // Safety check: ensure current is valid before returning return current && current->IsDefined(); } @@ -515,7 +512,8 @@ namespace robot } // Traverse the tree without modifying node_handle_ - // Use const reference to the original node_handle_ to avoid any modifications + // Owned copies keep child nodes alive (yaml-cpp iterator proxies are temporaries). + std::vector owned; const YAML::Node *current = &root_; for (size_t i = 0; i < segments.size(); ++i) @@ -527,62 +525,56 @@ namespace robot } // Access child node without mutating the map (avoid operator[] default insertion) - const YAML::Node *found_child = nullptr; - + YAML::Node found_child; + bool found = false; + try { for (YAML::const_iterator it = current->begin(); it != current->end(); ++it) { try { - // Safety check: validate iterator nodes - if (!it->first.IsDefined()) + const auto kv = *it; + if (!kv.first.IsDefined()) { continue; } - - // Safely convert key to string + std::string key_str; try { - key_str = it->first.as(); + key_str = kv.first.as(); } catch (...) { - // Skip nodes that can't be converted to string continue; } - - if (key_str == segments[i]) + + if (key_str == segments[i] && kv.second.IsDefined()) { - // Safety check: validate value node - if (it->second.IsDefined()) - { - found_child = &(it->second); - break; - } + found_child = kv.second; + found = true; + break; } } catch (...) { - // Skip invalid nodes and continue iteration continue; } } } catch (...) { - // If iteration fails, return empty node return YAML::Node(); } - - if (!found_child || !found_child->IsDefined()) + + if (!found || !found_child.IsDefined()) { return YAML::Node(); } - // Move to next level - current = found_child; + owned.push_back(std::move(found_child)); + current = &owned.back(); } // Safety check: ensure current is valid before cloning @@ -629,6 +621,7 @@ namespace robot return YAML::Node(); } + std::vector owned; const YAML::Node *current = &root_; for (size_t i = 0; i < segments.size(); ++i) @@ -643,9 +636,10 @@ namespace robot bool found_child = false; for (auto it = current->begin(); it != current->end(); ++it) { - if (it->first.as() == segments[i]) + const auto kv = *it; + if (kv.first.as() == segments[i]) { - segment_node = it->second; + segment_node = kv.second; found_child = true; break; } @@ -659,7 +653,8 @@ namespace robot return YAML::Node(); } - current = &segment_node; + owned.push_back(std::move(segment_node)); + current = &owned.back(); } return YAML::Clone(*current); } @@ -712,8 +707,10 @@ namespace robot { for (auto it = node.begin(); it != node.end(); ++it) { - std::string key = it->first.as(); - const YAML::Node &value = it->second; + // Copy pair: it->second is a temporary (yaml-cpp iterator proxy). + const auto kv = *it; + std::string key = kv.first.as(); + const YAML::Node value = kv.second; std::string full_key = prefix.empty() ? key : prefix + "/" + key; if(full_key.find("MKTAlgorithmDiffPredictiveTrajectory") == std::string::npos) continue; @@ -803,8 +800,12 @@ namespace robot for (auto it = src.begin(); it != src.end(); ++it) { - std::string key = it->first.as(); - const YAML::Node &src_value = it->second; + // yaml-cpp map iterators return a temporary pair via operator-> proxy. + // Binding a reference to it->second dangles after the full-expression and + // throws "invalid node; ... map iterator as a sequence iterator" on 0.9+. + const auto kv = *it; + std::string key = kv.first.as(); + YAML::Node src_value = kv.second; // Get current value in dest (if exists) YAML::Node dest_current = dest[key]; @@ -1879,6 +1880,7 @@ namespace robot return false; } + std::vector owned; const YAML::Node *current = search_root; for (const auto &seg : segments) { @@ -1888,61 +1890,56 @@ namespace robot return false; } - const YAML::Node *found_child = nullptr; - + YAML::Node found_child; + bool found = false; + try { for (YAML::const_iterator it = current->begin(); it != current->end(); ++it) { try { - // Safety check: validate iterator nodes - if (!it->first.IsDefined()) + const auto kv = *it; + if (!kv.first.IsDefined()) { continue; } - - // Safely convert key to string + std::string key_str; try { - key_str = it->first.as(); + key_str = kv.first.as(); } catch (...) { - // Skip nodes that can't be converted to string continue; } - - if (key_str == seg) + + if (key_str == seg && kv.second.IsDefined()) { - // Safety check: validate value node - if (it->second.IsDefined()) - { - found_child = &(it->second); - break; - } + found_child = kv.second; + found = true; + break; } } catch (...) { - // Skip invalid nodes and continue iteration continue; } } } catch (...) { - // If iteration fails, return false return false; } - if (!found_child || !found_child->IsDefined()) + if (!found || !found_child.IsDefined()) { return false; } - current = found_child; + owned.push_back(std::move(found_child)); + current = &owned.back(); } // Safety check: ensure current is valid before returning @@ -2059,4 +2056,4 @@ namespace robot std::string NodeHandle::config_directory_; YAML::Node NodeHandle::root_; -} // namespace robot +} // namespace robot \ No newline at end of file diff --git a/src/Libraries/robot_cpp/src/plugin_loader_helper.cpp b/src/Libraries/robot_cpp/src/plugin_loader_helper.cpp index 7049a61..f48bf5b 100644 --- a/src/Libraries/robot_cpp/src/plugin_loader_helper.cpp +++ b/src/Libraries/robot_cpp/src/plugin_loader_helper.cpp @@ -57,6 +57,8 @@ void PluginLoaderHelper::setNodeHandle(robot::NodeHandle nh, const std::string& std::string PluginLoaderHelper::findLibraryPath(const std::string& symbol_name) { + const bool dbg = (symbol_name == "global_costmap"); + // Build parameter path: {config_namespace}/{symbol_name}/library_path std::string param_path; if (!config_namespace_.empty()) { @@ -67,14 +69,32 @@ std::string PluginLoaderHelper::findLibraryPath(const std::string& symbol_name) // Try to read from NodeHandle std::string library_path; robot::log_info_at(__FILE__, __LINE__, "%s", symbol_name.c_str()); + if (dbg) { + const char* nav_lib = std::getenv("PNKX_NAV_CORE_LIBRARY_PATH"); + const char* ld_env = std::getenv("LD_LIBRARY_PATH"); + log_debug("[PluginLoaderHelper][global_costmap] nh_ns='%s' config_ns='%s' param_path='%s' " + "PNKX_NAV_CORE_LIBRARY_PATH='%s' LD_LIBRARY_PATH='%s'\n", + nh_.getNamespace().c_str(), config_namespace_.c_str(), param_path.c_str(), + nav_lib ? nav_lib : "(null)", ld_env ? ld_env : "(null)"); + } if (nh_.hasParam(param_path)) { nh_.getParam(param_path, library_path, std::string("")); + if (dbg) { + log_debug("[PluginLoaderHelper][global_costmap] hasParam('%s')=true library_path='%s'\n", + param_path.c_str(), library_path.c_str()); + } if (!library_path.empty()) { std::string resolved_path = resolveLibraryPath(library_path); + if (dbg) { + log_debug("[PluginLoaderHelper][global_costmap] resolveLibraryPath('%s') -> '%s'\n", + library_path.c_str(), resolved_path.c_str()); + } if (!resolved_path.empty()) { return resolved_path; } } + } else if (dbg) { + log_debug("[PluginLoaderHelper][global_costmap] hasParam('%s')=false\n", param_path.c_str()); } // Try without namespace in symbol name (e.g., "custom_planner::CustomPlanner" -> "CustomPlanner") @@ -122,6 +142,10 @@ std::string PluginLoaderHelper::findLibraryPath(const std::string& symbol_name) for (const auto& name : possible_names) { std::filesystem::path full_path = std::filesystem::path(path) / name; + if (dbg) { + log_debug("[PluginLoaderHelper][global_costmap] try LD_LIBRARY_PATH '%s'\n", + full_path.string().c_str()); + } if (std::filesystem::exists(full_path)) { log_info("[PluginLoaderHelper] Found library in LD_LIBRARY_PATH: %s", full_path.string().c_str()); @@ -130,6 +154,9 @@ std::string PluginLoaderHelper::findLibraryPath(const std::string& symbol_name) } } } + } else if (dbg) { + log_debug("[PluginLoaderHelper][global_costmap] LD_LIBRARY_PATH unset; library_path still='%s'\n", + library_path.c_str()); } log_warning("[PluginLoaderHelper] Library not found for symbol: %s", symbol_name.c_str()); @@ -440,4 +467,3 @@ std::string PluginLoaderHelper::getWorkspacePath() } } // namespace robot - diff --git a/src/Libraries/robot_cpp/test/test_console_throttle.cpp b/src/Libraries/robot_cpp/test/test_console_throttle.cpp new file mode 100644 index 0000000..f33cd3c --- /dev/null +++ b/src/Libraries/robot_cpp/test/test_console_throttle.cpp @@ -0,0 +1,310 @@ +/********************************************************************* + * + * Test program for the throttled logging functions in robot/console.h + * + * The point of these tests is that a throttle window belongs to a call + * site, not to the logging function. Before that fix a single static + * timestamp per function meant the first call site to fire silenced every + * other one process-wide, which swallowed real fault messages in the + * navigation stack. + * + * All test reporting goes to stderr, because stdout is redirected to a + * temporary file while the log calls run. + * + *********************************************************************/ + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +int g_failures = 0; + +void check(bool condition, const std::string &message) +{ + if (condition) + { + std::cerr << "PASS: " << message << std::endl; + } + else + { + std::cerr << "FAIL: " << message << std::endl; + ++g_failures; + } +} + +/** + * @brief Run @p body with stdout redirected, return everything it printed. + * + * dup/dup2 rather than freopen so the real stdout can be restored: the test + * has to keep reporting after the capture ends. + */ +std::string capture(const std::function &body) +{ + char path[] = "/tmp/robot_cpp_throttle_XXXXXX"; + const int tmp_fd = ::mkstemp(path); + if (tmp_fd < 0) + { + std::cerr << "FAIL: cannot create temp file for capture" << std::endl; + ++g_failures; + return ""; + } + + std::fflush(stdout); + const int saved_fd = ::dup(STDOUT_FILENO); + ::dup2(tmp_fd, STDOUT_FILENO); + + body(); + + std::fflush(stdout); + ::dup2(saved_fd, STDOUT_FILENO); + ::close(saved_fd); + + ::lseek(tmp_fd, 0, SEEK_SET); + std::string out; + char buffer[4096]; + ssize_t got = 0; + while ((got = ::read(tmp_fd, buffer, sizeof(buffer))) > 0) + { + out.append(buffer, static_cast(got)); + } + ::close(tmp_fd); + ::unlink(path); + return out; +} + +/// Number of non-overlapping occurrences of @p needle in @p haystack. +int countOf(const std::string &haystack, const std::string &needle) +{ + int count = 0; + std::size_t pos = haystack.find(needle); + while (pos != std::string::npos) + { + ++count; + pos = haystack.find(needle, pos + needle.size()); + } + return count; +} + +// A throttle window far longer than the test run: anything printed twice +// under this interval means the throttle failed, and anything printed once +// per call site means it worked. +constexpr double kLongWindow = 1000.0; + +/// Two distinct call sites, distinct format strings, must not silence each other. +void testDistinctCallSites() +{ + const std::string out = capture([]() { + robot::log_warning_throttle(kLongWindow, "SITE_ONE %d", 1); + robot::log_warning_throttle(kLongWindow, "SITE_TWO %d", 2); + }); + + check(countOf(out, "SITE_ONE") == 1, "first call site printed"); + check(countOf(out, "SITE_TWO") == 1, + "second call site printed despite the first holding the window"); +} + +/// Same test with an identical format string in both places: the linker may +/// fold the two literals into one address, so the return address is the only +/// thing left that can tell the call sites apart. +void testDistinctCallSitesSharedLiteral() +{ + const std::string out = capture([]() { + robot::log_error_throttle(kLongWindow, "SHARED_LITERAL"); + robot::log_error_throttle(kLongWindow, "SHARED_LITERAL"); + }); + + check(countOf(out, "SHARED_LITERAL") == 2, + "two call sites sharing one format literal both printed"); +} + +/// One call site hammered in a loop prints exactly once per window. +void testSameCallSiteThrottled() +{ + const std::string out = capture([]() { + for (int i = 0; i < 100; ++i) + { + robot::log_warning_throttle(kLongWindow, "LOOP_SITE %d", i); + } + }); + + check(countOf(out, "LOOP_SITE") == 1, "repeated call site printed once"); +} + +// Wrapped in a function so every call below really is the same call site. +// Three separate lines would be three call sites and the test would pass +// without the window ever expiring. +// +// Two attributes are needed to pin the call site down: +// - noinline, or each call would be inlined and get its own return address; +// - the volatile read, which leaves a live instruction after the log call so +// the compiler cannot turn it into a tail call. A tail call would hand +// log_info_throttle the return address of *this* function's caller, and +// the three calls below would again look like three different sites. +__attribute__((noinline)) void expiryLogger() +{ + robot::log_info_throttle(0.05, "EXPIRY_SITE"); + static volatile int keep_frame = 0; + (void)keep_frame; +} + +/// The window has to expire. +void testWindowExpires() +{ + const std::string out = capture([]() { + expiryLogger(); + expiryLogger(); // same window, must be swallowed + std::this_thread::sleep_for(std::chrono::milliseconds(120)); + expiryLogger(); + }); + + check(countOf(out, "EXPIRY_SITE") == 2, + "call site printed once per window, again after it expired"); +} + +/// The four functions keep separate state from one another. +void testFunctionsIndependent() +{ + const std::string out = capture([]() { + robot::log_error_throttle(kLongWindow, "FN_ERROR"); + robot::log_warning_throttle(kLongWindow, "FN_WARNING"); + robot::log_info_throttle(kLongWindow, "FN_INFO"); + robot::log_success_throttle(kLongWindow, "FN_SUCCESS"); + }); + + check(countOf(out, "FN_ERROR") == 1 && countOf(out, "FN_WARNING") == 1 && + countOf(out, "FN_INFO") == 1 && countOf(out, "FN_SUCCESS") == 1, + "all four throttled log levels printed"); +} + +/// A bad interval must make the call site noisy, never silent. NaN used to +/// fail the >= comparison forever and mute the call site for the whole run. +void testDegenerateIntervals() +{ + const std::string out = capture([]() { + for (int i = 0; i < 3; ++i) + { + robot::log_warning_throttle(std::nan(""), "NAN_SITE"); + } + for (int i = 0; i < 3; ++i) + { + robot::log_warning_throttle(-1.0, "NEGATIVE_SITE"); + } + for (int i = 0; i < 3; ++i) + { + robot::log_warning_throttle(0.0, "ZERO_SITE"); + } + }); + + check(countOf(out, "NAN_SITE") == 3, "NaN interval does not silence the call site"); + check(countOf(out, "NEGATIVE_SITE") == 3, "negative interval prints every time"); + check(countOf(out, "ZERO_SITE") == 3, "zero interval prints every time"); +} + +// Called from every worker thread, so all of them share one call site and +// therefore one throttle slot. Exactly one print may get through. +__attribute__((noinline)) void concurrentLogger() +{ + robot::log_warning_throttle(kLongWindow, "THREAD_SITE"); + static volatile int keep_frame = 0; // see expiryLogger(): blocks tail call + (void)keep_frame; +} + +/// Concurrent calls from one call site: the old plain timestamp was a data +/// race and could let several threads print inside one window. +void testConcurrentSameCallSite() +{ + const std::string out = capture([]() { + constexpr int kThreads = 8; + constexpr int kIterations = 50; + + std::atomic go{false}; + std::vector workers; + workers.reserve(kThreads); + + for (int t = 0; t < kThreads; ++t) + { + workers.emplace_back([&go]() { + while (!go.load(std::memory_order_acquire)) + { + std::this_thread::yield(); + } + for (int i = 0; i < kIterations; ++i) + { + concurrentLogger(); + } + }); + } + + go.store(true, std::memory_order_release); + for (std::thread &worker : workers) + { + worker.join(); + } + }); + + check(countOf(out, "THREAD_SITE") == 1, + "8 threads x 50 calls on one call site printed exactly once"); +} + +/// Colour can be turned off and on, and the cached terminal detection does not +/// freeze the answer at its first value. +void testColorToggle() +{ + const std::string colored = capture([]() { + robot::set_color_enabled(true); + robot::log_warning_throttle(0.0, "COLOR_ON_SITE"); + }); + + const std::string plain = capture([]() { + robot::set_color_enabled(false); + robot::log_warning_throttle(0.0, "COLOR_OFF_SITE"); + }); + + robot::set_color_enabled(true); + + check(countOf(plain, "COLOR_OFF_SITE") == 1 && plain.find("\033[") == std::string::npos, + "colour disabled emits no escape sequence"); + // Whether colour is actually available depends on the environment the test + // runs in, so only assert the message itself here. + check(countOf(colored, "COLOR_ON_SITE") == 1, "colour enabled still logs the message"); +} + +} // namespace + +int main() +{ + std::cerr << "=== robot::log_*_throttle tests ===" << std::endl; + + testDistinctCallSites(); + testDistinctCallSitesSharedLiteral(); + testSameCallSiteThrottled(); + testWindowExpires(); + testFunctionsIndependent(); + testDegenerateIntervals(); + testConcurrentSameCallSite(); + testColorToggle(); + + if (g_failures == 0) + { + std::cerr << "\nAll throttle tests passed." << std::endl; + return 0; + } + + std::cerr << "\n" << g_failures << " throttle test(s) failed." << std::endl; + return 1; +} diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/ComplexPolygon2D.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/ComplexPolygon2D.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridInfo.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridInfo.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfChars.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfChars.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfCharsUpdate.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfCharsUpdate.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfDoubles.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfDoubles.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfDoublesUpdate.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/NavGridOfDoublesUpdate.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Path2D.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Path2D.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Point2D.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Point2D.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Polygon2D.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Polygon2D.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Polygon2DCollection.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Polygon2DCollection.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Polygon2DStamped.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Polygon2DStamped.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Pose2D32.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Pose2D32.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Pose2DStamped.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Pose2DStamped.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/SwitchPlugin.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/SwitchPlugin.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/SwitchPluginRequest.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/SwitchPluginRequest.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/SwitchPluginResponse.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/SwitchPluginResponse.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Twist2D.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Twist2D.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Twist2D32.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Twist2D32.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Twist2DStamped.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/Twist2DStamped.h old mode 100644 new mode 100755 diff --git a/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/UIntBounds.h b/src/Libraries/robot_nav_2d_msgs/include/robot_nav_2d_msgs/UIntBounds.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/move_base_core/CMakeLists.txt b/src/Navigations/Cores/move_base_core/CMakeLists.txt old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/move_base_core/include/move_base_core/common.h b/src/Navigations/Cores/move_base_core/include/move_base_core/common.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/move_base_core/package.xml b/src/Navigations/Cores/move_base_core/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/robot_nav_core/CMakeLists.txt b/src/Navigations/Cores/robot_nav_core/CMakeLists.txt old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/robot_nav_core/package.xml b/src/Navigations/Cores/robot_nav_core/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/robot_nav_core2/package.xml b/src/Navigations/Cores/robot_nav_core2/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Cores/robot_nav_core_adapter/package.xml b/src/Navigations/Cores/robot_nav_core_adapter/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/nav_grid/CMakeLists.txt b/src/Navigations/Libraries/nav_grid/CMakeLists.txt index 6c75965..7dbb193 100755 --- a/src/Navigations/Libraries/nav_grid/CMakeLists.txt +++ b/src/Navigations/Libraries/nav_grid/CMakeLists.txt @@ -134,11 +134,14 @@ endif() # ======================================================== # Test executables # ======================================================== -# Tests are a development-machine concern: a catkin workspace is where they run, -# while the standalone CMake build is the robot deployment path and must not -# produce test executables. Force with -DBUILD_NAV_GRID_TESTS=ON to build them -# from a standalone build. -option(BUILD_NAV_GRID_TESTS "Build the nav_grid unit tests" ${BUILDING_WITH_CATKIN}) +# Tests are off by default for every build mode. Turn them all on with +# -DPNKX_NAV_CORE_BUILD_TESTS=ON, or one package with -DBUILD_NAV_GRID_TESTS=ON. +if(PNKX_NAV_CORE_BUILD_TESTS) + set(_nav_grid_tests_default ON) +else() + set(_nav_grid_tests_default OFF) +endif() +option(BUILD_NAV_GRID_TESTS "Build the nav_grid unit tests" ${_nav_grid_tests_default}) if(BUILD_NAV_GRID_TESTS AND (GTest_FOUND OR GTEST_FOUND)) enable_testing() @@ -154,6 +157,6 @@ if(BUILD_NAV_GRID_TESTS AND (GTest_FOUND OR GTEST_FOUND)) ) add_test(NAME ${PROJECT_NAME}_test COMMAND ${PROJECT_NAME}_test) endif() -else() +elseif(BUILD_NAV_GRID_TESTS) message(STATUS "Google Test not found. Tests will not be built.") endif() diff --git a/src/Navigations/Libraries/nav_grid/package.xml b/src/Navigations/Libraries/nav_grid/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_actionlib_msgs/CMakeLists.txt b/src/Navigations/Libraries/robot_actionlib_msgs/CMakeLists.txt old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_actionlib_msgs/include/robot_actionlib_msgs/GoalID.h b/src/Navigations/Libraries/robot_actionlib_msgs/include/robot_actionlib_msgs/GoalID.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_actionlib_msgs/include/robot_actionlib_msgs/GoalStatus.h b/src/Navigations/Libraries/robot_actionlib_msgs/include/robot_actionlib_msgs/GoalStatus.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_actionlib_msgs/include/robot_actionlib_msgs/GoalStatusArray.h b/src/Navigations/Libraries/robot_actionlib_msgs/include/robot_actionlib_msgs/GoalStatusArray.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_actionlib_msgs/package.xml b/src/Navigations/Libraries/robot_actionlib_msgs/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_clear_costmap_recovery/CMakeLists.txt b/src/Navigations/Libraries/robot_clear_costmap_recovery/CMakeLists.txt old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_clear_costmap_recovery/package.xml b/src/Navigations/Libraries/robot_clear_costmap_recovery/package.xml old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/CMakeLists.txt b/src/Navigations/Libraries/robot_move_base_msgs/CMakeLists.txt old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseAction.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseAction.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseActionFeedback.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseActionFeedback.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseActionGoal.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseActionGoal.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseActionResult.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseActionResult.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseFeedback.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseFeedback.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseGoal.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseGoal.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseResult.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/MoveBaseResult.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/RecoveryStatus.h b/src/Navigations/Libraries/robot_move_base_msgs/include/robot_move_base_msgs/RecoveryStatus.h old mode 100644 new mode 100755 diff --git a/src/Navigations/Libraries/robot_move_base_msgs/package.xml b/src/Navigations/Libraries/robot_move_base_msgs/package.xml old mode 100644 new mode 100755